Shell script: log in using SSH and change your password
Usually operation and maintenance sometimes encounter the need to change the server administrator password, if there are more servers, we can write a script to achieve, saving time and effort.
When linux logs in using SSH, you need to manually type yes to confirm the connection, so you need to solve this problem first and let the script execute commands remotely without human intervention.
The first step is to create the local public key and private key using ssh-keygen
After successful creation, private and public keys are generated under / root/.ssh.
The second step is to use ssh-copy-id to copy the public key to the remote host and expect internal commands to write the ssh automatic login script
Auto_ssh_copy_id () {
Expect-c "set timeout-1
Spawn / usr/bin/ssh-copy-id-I / root/.ssh/id_rsa.pub root@$2
Expect {
* (yes/no) * {send-- yes\ r Tincture expandable continue;}
* password:* {send-- $1\ rth expandable continue;}
Eof {exit 0;}
} "
}
Calling method: auto_ssh_copy_id $pass1 $ipnet.$i
Suppose the server IP that needs to change the password is between 172.18.0.1 and 172.18.0.100, and the script is as follows.
#! / bin/bash
# Program
#
# relase
# tryrus 20161029
Change ipnet=172.18.0 # to the actual IP segment
Change declare iTunes 1 # to the actual starting IP
Pass1=password1 # ssh password for remote login to root
Pass2=password2 # New password to set
Auto_ssh_copy_id () {
Expect-c "set timeout-1
Spawn / usr/bin/ssh-copy-id-I / root/.ssh/id_rsa.pub root@$2
Expect {
* (yes/no) * {send-- yes\ r Tincture expandable continue;}
* password:* {send-- $1\ rth expandable continue;}
Eof {exit 0;}
} "
}
Auto_ssh_change_psw () {
Expect-c "set timeout-1
Spawn ssh root@$2 "passwd"
Expect {
* New* {send-- $1\ rth expandable continue;}
* Retype* {send-- $1\ rth expandable continue;}
Eof {exit 0;}
} "
}
While [["$I"-le "100"] # controls the loop and changes the value to the actual IP to be used
Do
Ping "$ipnet.$i"-c 3 > / dev/null
If [$?-eq 0]; then
After auto_ssh_copy_id $pass1 $ipnet.$i # is run once, this line is not needed
Auto_ssh_change_psw $pass2 $ipnet.$i
Fi
Let "iTunes 1"
Done
Results of the second test
Thank you for opening this blog post and keep reading it all the time. If you think it's helpful to you, please don't be stingy with the likes in the lower right corner.