Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Shell script: log in using SSH and change your password

Shulou Source: shulou.com Published: 2022-06-01 06:56:14 10月01日 Update

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.

Tags: Script password login public key actual server service command stingy save time success save time and effort host between manual manual numerical method time luck Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Xiaomi vpn Shulou Tech Info Shulou Technology