ssh远程连接到服务器认证密码的时候分为交互模式和非交互模式。交互模式就是我们登入要手动输入密码,非交互模式就是不需要人工输入密码。
这里我们介绍非交互模式
【非交互模式】
1.公钥和私钥的方式
Master作为客户端,要实现无密码公钥认证,连接到服务器Salve上时,需要在Master上生成一个密钥对,包括一个公钥和一个私钥,而后将公钥复制到所有的Salve上。当Master通过SSH链接到Salve上时,Salve会生成一个随机数并用Master的公钥对随机数进行加密,并发送给Master。Master收到加密数之后再用私钥解密,并将解密数回传给Salve,Salve确认解密数无误之后就允许Master进行连接了。这就是一个公钥认证过程,期间不需要手工输入密码,重要的过程是将Master上产生的公钥复制到Salve上。
1.1 ssh-keygen -t rsa 生成密钥文件
1.2 将id_rsa.pub加到授权的authorized_keys里面去
1.3 拷贝id_rsa.pub密匙文件到目的服务器(ssh-copy-id)
1.4 注意文件的权限问题
2.sshpass
sshpass is a utility designed for running ssh using the mode referred to as "keyboard-interactive" password authentication, but in non-interactive mode.
[root@sparkVM script]# sshpass --help sshpass: invalid option -- '-' Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters -f filename Take password to use from file -d number Use number as file descriptor for getting password -p password Provide password as argument (security unwise) -e Password is passed as env-var "SSHPASS" With no parameters - password will be taken from stdin -h Show help (this screen) -V Print version information At most one of -f, -d, -p or -e should be used
[root@sparkVM script]# sshpass root ssh -l root ipaddress "cat /etc/issue"
3.expect交互
[root@sparkVM script]# cat expect.exp #!/usr/bin/expect -f set ip [lindex $argv 0 ] set password [lindex $argv 1 ] set timeout 5 spawn ssh root@$ip expect { "*yes/no" { send "yes\r"; exp_continue} "*password:" { send "$password\r" } } interact [root@sparkVM script]# ./expect.exp ipaddress root spawn ssh [email protected]
【参考】
http://www.2cto.com/os/201301/186673.html
https://linuxtoy.org/archives/sshpass.html