0

im using this script to change hostname via ssh but i got some errors.

read -p "Insira o IP : " ip
read -p "Insira o nome do utilizador : " host
read -s -p "Insira a palavra passe : " oldpass

sshpass -p $oldpass ssh $host@$ip "cat /etc/hostname > hostname.txt"\
run="sshpass -p $oldpass ssh $host@$ip" \ 
hostn=$($run "cat hostname.txt") \ 
echo $hostn

sshpass -p $oldpass ssh  $host@$ip " \
echo "Enter new hostname: " \ 
read newhost \ 
sed -i "s/$hostn/$newhost/g" /etc/hosts \
sed -i "s/$hostn/$newhost/g" /etc/hostname \ 
echo "Your new hostname is "$newhost"" \ 
read -s -n 1 -p "Press any key to reboot" \ 
reboot"

When i write new hostname appear that:

unable to resolve host"=.

But the script continued work and do reboot.

  • my guess is that $hostn is define in your first sshpass but the variable leave only during this execution, when you execute sshpass for the second time the variable $hostn doesn't exit anymore – Kiwy Apr 24 '18 at 9:31
  • A space in your password (or any globbing characters) may confuse your code as $oldpass in never properly quoted. Also, backslashes will not be read correctly as you're not using -r with read. In general, your script is a quoting minefield. – Kusalananda Apr 24 '18 at 9:33
  • Depending on your version of Linux it may serve you better to use hostnamectl to set the host name. – Raman Sailopal Apr 24 '18 at 9:40
  • Since you're trying to pass multiple commands on the same line (escaping the newlines), each command has to be terminated by ;. Otherwise you'll be trying to execute echo something read newhost sed ... etc. as a single command. – Kusalananda Apr 24 '18 at 9:42
  • Thanks for your help i already put script working Its more simple and work – helpme123 Apr 24 '18 at 9:48
0

Instead of replacing name in /etc/hostname file use below command to change hostname if it is a RHEL7/CentOs7 machine

hostnamectl set-hostname $newhost

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.