61 lines
1.5 KiB
Bash
61 lines
1.5 KiB
Bash
#!/bin/bash
|
|
|
|
# Function to remount file system as read-write
|
|
remount_rw() {
|
|
mount -o remount,rw /
|
|
}
|
|
|
|
# Function to remount file system as read-only
|
|
remount_ro() {
|
|
mount -o remount,ro /
|
|
}
|
|
|
|
# Display current hostname
|
|
current_hostname=$(cat /etc/hostname)
|
|
echo -e "\033[0;32mCurrent hostname: $current_hostname\033[0m"
|
|
|
|
# Prompt for new hostname
|
|
echo -e "\033[0;32mEnter new hostname (or 'exit' to cancel):\033[0m"
|
|
read new_hostname
|
|
|
|
if [ "$new_hostname" = "exit" ]; then
|
|
echo -e "\033[0;31mHostname change cancelled.\033[0m"
|
|
exit 0
|
|
fi
|
|
|
|
# Validate hostname format
|
|
if ! echo "$new_hostname" | grep -qE '^[a-zA-Z0-9-]+$'; then
|
|
echo -e "\033[0;31mInvalid hostname. Hostname can only contain letters, numbers, and hyphens.\033[0m"
|
|
exit 1
|
|
fi
|
|
|
|
# Change hostname
|
|
remount_rw
|
|
echo "$new_hostname" > /etc/hostname
|
|
sed -i "s/127.0.1.1.*$/127.0.1.1\t$new_hostname/g" /etc/hosts
|
|
hostname "$new_hostname"
|
|
|
|
# Create the hostname service with sleep
|
|
cat > /lib/systemd/system/set-hostname.service << EOF
|
|
[Unit]
|
|
Description=Set system hostname
|
|
After=network.target
|
|
|
|
[Service]
|
|
Type=oneshot
|
|
ExecStartPre=/bin/sleep 30
|
|
ExecStart=/bin/sh -c 'hostname \$(cat /etc/hostname)'
|
|
RemainAfterExit=yes
|
|
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
systemctl daemon-reload
|
|
systemctl enable set-hostname.service
|
|
systemctl start set-hostname.service
|
|
|
|
remount_ro
|
|
|
|
echo -e "\033[0;32mHostname has been changed to: $new_hostname\033[0m"
|
|
echo -e "\033[0;33mPlease reboot the device for the change to take full effect.\033[0m" |