批量实现SSH免密登录

借助expect工具实现非交互式的ssh-copy-id

cat auto_sshcopyid.exp

#!/usr/bin/expect

set timeout 10

set user_hostname [lindex $argv 0]

set password [lindex $argv 1]

spawn ssh-copy-id $user_hostname

expect {

        "(yes/no)?"

        {

                send "yes\n"

                expect "*password: " { send "$password\n" }

        }

        "*password: " { send "$password\n" }

}

expect eof 

 

# 批量调用expect的shell脚本

[root@server ~]# cat sshkey.sh

#!/bin/bash

#在192.168.0.31-40,50共11台客户端安装

ip=`echo -n "$(seq -s "," 31 40),50" | xargs -d "," -i echo 192.168.0.{}`

password="123456" 

for i in $ip;do

        /root/auto_sshcopyid.exp root@$i $password &>>/tmp/a.log

        ssh root@$i "echo $i ok"

done

 

# 执行shell脚本

[root@server ~]# chmod +x /root/{sshkey.sh,auto_sshcopyid.exp}

[root@server ~]# ./sshkey.sh

posted @ 2021-03-06 13:52  ST运维  阅读(225)  评论(0编辑  收藏  举报