expect配合脚本实现ssh免密

1、生成密钥,创建脚本目录,具体不贴图了
[[email protected] sshcopy]#
[[email protected] sshcopy]# pwd
/root/sshcopy
[[email protected] sshcopy]# ll
total 8
-rwxr-xr-x. 1 root root 360 Aug 19 02:23 ssh.exp
-rwxr-xr-x. 1 root root 199 Aug 19 02:46 sshkey.sh
[[email protected] sshcopy]#
2、编辑免密脚本
[[email protected] sshcopy]# cat ssh.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
3、调用免密脚本,注意文件路径按自己的情况进行更改
[[email protected] sshcopy]# cat ssh
ssh.exp sshkey.sh
[[email protected] sshcopy]# cat sshkey.sh
#!/bin/bash
ip=`echo -n “n1,n2,n3,n4” | xargs -d “,” -i echo {}`
password=”123456″

for i in $ip;do
/root/sshcopy/ssh.exp [email protected]$i $password $ >> /root/sshcopy/out.log
ssh [email protected]$i “echo $i ok”
done
[[email protected] sshcopy]#
4、验证
[[email protected] sshcopy]# ll
total 8
-rwxr-xr-x. 1 root root 360 Aug 19 02:23 ssh.exp
-rwxr-xr-x. 1 root root 199 Aug 19 02:46 sshkey.sh
[[email protected] sshcopy]# ./sshkey.sh
n1 ok
n2 ok
n3 ok
n4 ok
[[email protected] sshcopy]#
[[email protected] sshcopy]# ssh n1
Last login: Mon Aug 19 14:53:13 2019 from 10.1.24.232
[[email protected] ~]# exit
logout
Connection to n1 closed.
[[email protected] sshcopy]# ssh n2
Last login: Mon Aug 19 02:13:50 2019 from 10.1.24.232
[[email protected] ~]# exit
logout
Connection to n2 closed.
[[email protected] sshcopy]#

此条目发表在shell, ssh分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注