ssh登陆不能在命令行中指定密码,sshpass 的出现,解决了这一问题。它允许你用 -p 参数指定明文密码,然后直接登录远程服务器。 它支持密码从命令行,文件,环境变量中读取。

一、sshpass安装

代码非常小,可以选择从epel源下载安装,也可以通过源码安装,这里以源码安装为例。从网站上下载代码,http://sourceforge.net/projects/sshpass/

1tar -zxvf sshpass-1.05.tar.gz
2cd sshpass-1.05
3./configure
4make && make install

二、sshpass参数

 1[root@localhost ~]# sshpass -h
 2Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
 3   -f filename   Take password to use from file
 4   -d number     Use number as file descriptor for getting password
 5   -p password   Provide password as argument (security unwise)
 6   -e            Password is passed as env-var "SSHPASS"
 7   With no parameters - password will be taken from stdin
 8   -h            Show help (this screen)
 9   -V            Print version information
10At most one of -f, -d, -p or -e should be used

三、sshpass的用法

1、-p参数中使用

通过sshpass参数-p指定密码,在ssh命令的等待输入密码的时候就能自动将密码写入到输入流中了:

1[root@localhost ~]# sshpass -p '361way.com' ssh -p 22 root@10.212.52.252
2Last login: Tue May 12 10:16:53 2015 from 10.212.52.253
3Authorized users only. All activity may be monitored and reported
4linux-wdh1:~ # exit
5[root@localhost ~]# sshpass -p '361way.com' scp -P22 10.212.52.252:/home/test/file . 

以上我指定了密码为361way.com,通过10.212.52.253登录10.212.52.252,也可以通过scp结合进行取文件。

注:连接前,需要~/.ssh/known_hosts文件中进行验证。不然会提示Host key verification failed ,避免该问题也可以在ssh或scp的时候通过-o选择加参数 StrictHostKeyChecking=no来规避该问题。

2、密码文件读取

1$> echo "user_password" > user.passwd
2$> sshpass -f user.passwd ssh user_name@192.168..1.2

3、从环境变量获取密码

1$> export SSHPASS="user_password"
2$> sshpass -e ssh user_name@192.168..1.2 

四、优缺点

缺点:密码放在参数里使用,有些不安全,别人可以使用history来查看到历史的命令,虽然指定了参数可以从文件中获取,但是这个文件里面也是需要进行权限控制的。

优点:简单,速度会比使用expect快很多。