ssh登陆不能在命令行中指定密码,sshpass 的出现,解决了这一问题。它允许你用 -p 参数指定明文密码,然后直接登录远程服务器。 它支持密码从命令行,文件,环境变量中读取。
一、sshpass安装
代码非常小,可以选择从epel源下载安装,也可以通过源码安装,这里以源码安装为例。从网站上下载代码,http://sourceforge.net/projects/sshpass/
tar -zxvf sshpass-1.05.tar.gz cd sshpass-1.05 ./configure make && make install
二、sshpass参数
[root@localhost ~]# sshpass -h 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
三、sshpass的用法
1、-p参数中使用
通过sshpass参数-p指定密码,在ssh命令的等待输入密码的时候就能自动将密码写入到输入流中了:
[root@localhost ~]# sshpass -p '361way.com' ssh -p 22 root@10.212.52.252 Last login: Tue May 12 10:16:53 2015 from 10.212.52.253 Authorized users only. All activity may be monitored and reported linux-wdh1:~ # exit [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、密码文件读取
$> echo "user_password" > user.passwd $> sshpass -f user.passwd ssh user_name@192.168..1.2
3、从环境变量获取密码
$> export SSHPASS="user_password" $> sshpass -e ssh user_name@192.168..1.2
四、优缺点
缺点:密码放在参数里使用,有些不安全,别人可以使用history来查看到历史的命令,虽然指定了参数可以从文件中获取,但是这个文件里面也是需要进行权限控制的。
优点:简单,速度会比使用expect快很多。