Shell脚本:使用SSH登陆并更改密码
更新:HHH   时间:2023-1-7


平时运维中有时会遇到需要更改服务器的管理员密码,如果服务器比较多的时候,我们可以编写一个脚本来实现,省时省力。

linux使用SSH登陆时需 要手动输入yes 来确认连接,所以首先要解决这个问题,让脚本实现远程执行命令无须人工干预。

第一步 使用ssh-keygen创建本机的公钥和私钥

创建成功后会在/root/.ssh下生成私钥和公钥

第二步 使用ssh-copy-id复制公钥到远程主机及expect内部命令编写ssh自动登陆脚本

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;exp_continue;}

        *password:* {send -- $1\r;exp_continue;}

        eof{exit 0;}

    }";

}

调用方法:auto_ssh_copy_id $pass1 $ipnet.$i  

假设需要更改密码的服务器IP 在172.18.0.1-172.18.0.100之间,脚本如下。

#!/bin/bash

#Program

#

#relase

#tryrus 20161029

ipnet=172.18.0   #改成实际的IP 段

declare i=1      #改成实际开始的IP

pass1=password1 #ssh远程登陆root的密码

pass2=password2   #要设定的新密码

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;exp_continue;}

        *password:* {send -- $1\r;exp_continue;}

        eof{exit 0;}

    }";

}

auto_ssh_change_psw() {

    expect -c "set timeout -1;

    spawn ssh root@$2 "passwd";

    expect {

        *New* {send -- $1\r;exp_continue;}

        *Retype* {send -- $1\r;exp_continue;}

        eof{exit 0;}

    }";

}

while [[ "$i" -le "100" ]]      #控制循环,数值改成实际要使用的IP

    do

        ping "$ipnet.$i" -c 3 > /dev/null

        if [ $? -eq 0 ];then

            auto_ssh_copy_id $pass1 $ipnet.$i            #运行一次后,这行就不需要了

            auto_ssh_change_psw $pass2 $ipnet.$i            

        fi

    let "i+=1"

done

第二次测试结果


谢谢你打开这篇博文,并一直坚持看到了这里,如果觉得对你有帮助,请不要吝啬点一下右下角的赞。


返回网络安全教程...