ssh远程连接时,每次让提示输入密码。实在不方便,特别是需要ssh到多台机器时。sshpass可以解决这个问题。

sshpass可以实现ssh的自动的登录

1.安装

wget http://sourceforge.net/projects/sshpass/files/sshpass/1.05/sshpass-1.05.tar.gz
tar xf sshpass-1.05.tar.gz
cd sshpass-1.05/
 ./configure
 make && make install

2.用法介绍

[root@zhu ~]# 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
-p password #后跟密码
[root@zhu ~]# sshpass -p 123456 ssh root@192.168.56.102
Last login: Wed Apr 16 15:35:22 2014 from 192.168.56.1
[root@jiang ~]# exit
logout
Connection to 192.168.56.102 closed.
-f filename #后跟保存密码的文件名,密码是文件内容的第一行。
[root@zhu ~]# cat 1.txt
123456
[root@zhu ~]# sshpass -f 1.txt  ssh root@192.168.56.102
Last login: Fri Apr 18 13:48:20 2014 from 192.168.56.101
[root@jiang ~]# exit
logout
Connection to 192.168.56.102 closed.
-e #将环境变量SSHPASS作为密码
[root@zhu ~]# export SSHPASS=123456
[root@zhu ~]# sshpass -e  ssh root@192.168.56.102
Last login: Fri Apr 18 13:51:45 2014 from 192.168.56.101
[root@jiang ~]# exit
logout
Connection to 192.168.56.102 closed.


如在多台主机执行命令:

[root@zhu ~]# cat a.sh
#!/bin/bash
for i in $(cat /root/1.txt)
do
    echo $i
    sshpass -p123456 ssh root@$i 'ls -l'
done