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.

5
  • 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 Commented Apr 24, 2018 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. Commented Apr 24, 2018 at 9:33
  • Depending on your version of Linux it may serve you better to use hostnamectl to set the host name. Commented Apr 24, 2018 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. Commented Apr 24, 2018 at 9:42
  • Thanks for your help i already put script working Its more simple and work Commented Apr 24, 2018 at 9:48

1 Answer 1

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.