使用sshpass进行无密码输入提示的SSH连接

大家都知道,使用ssh命令进行远程主机连接时是需要输入密码或使用密钥登录然后进行交互式操作的,如下:

[root@test1 ~]# ssh [email protected]
The authenticity of host '172.16.220.230 (172.16.220.230)' can't be established.
RSA key fingerprint is e1:10:85:ba:b5:01:de:67:67:f1:9d:27:51:d7:8d:e1.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.220.230' (RSA) to the list of known hosts.
[email protected]'s password: 
Last login: Mon Mar 13 10:48:56 2017 from 172.16.220.100
[root@test2 ~]# 

如使用密钥进行连接,可以直接后面接入命令直接执行,但仍需要事先导入对端连接密钥:

[root@test3 ~]# ssh [email protected]
The authenticity of host '172.16.220.230 (172.16.220.230)' can't be established.
RSA key fingerprint is e1:10:85:ba:b5:01:de:67:67:f1:9d:27:51:d7:8d:e1.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.220.230' (RSA) to the list of known hosts.
Last login: Mon Mar 13 10:21:48 2017 from 172.16.200.100
[root@test2 ~]# logout
[root@test3 ~]# ssh [email protected] ls
anaconda-ks.cfg
install.log
install.log.syslog
tarball
[root@test3 ~]#

这样都不方便脚本的制作和移值使用。

下面介绍一款工具可以解决这种情况,方便脚本的制作。

sshpass,项目地址: https://sourceforge.net/projects/sshpass

源码安装:

[root@test1 tarball]# wget https://nchc.dl.sourceforge.net/project/sshpass/sshpass/1.06/sshpass-1.06.tar.gz
[root@test1 tarball]# tar zxf sshpass-1.06.tar.gz -C /usr/local/src/
[root@test1 tarball]# cd /usr/local/src/sshpass-1.06/
[root@test1 sshpass-1.06]# CFLAGS="-fPIC -O3" ./configure --prefix=/usr/local/spass
...
[root@test1 sshpass-1.06]# make -j `cat /proc/cpuinfo | grep processor | wc -l` && make install
[root@test sshpass-1.06]# echo 'export PATH=$PATH:/usr/local/spass/bin/' > /etc/profile.d/spass.sh
[root@test1 sshpass-1.06]# source /etc/profile.d/spass.sh
[root@test1 sshpass-1.06]# sshpass -V
sshpass 1.06
(C) 2006-2011 Lingnu Open Source Consulting Ltd.
(C) 2015-2016 Shachar Shemesh
This program is free software, and can be distributed under the terms of the GPL
See the COPYING file for more information.

Using "assword" as the default password prompt indicator.
[root@test1 sshpass-1.06]#

使用sshpass来调用ssh命令来连接对端:

[root@test1 ~]# sshpass -p 'H***#' ssh -o StrictHostKeyChecking=no [email protected] "ls"  
anaconda-ks.cfg
install.log
install.log.syslog
tarball
[root@test1 ~]#

同样,同样使用ssh提供服务的scp命令也可以使用sshpass:

[root@test1 ~]# touch testfile
[root@test1 ~]# sshpass -p 'H***#' scp -o StrictHostKeyChecking=no testfile [email protected]:~/
[root@test1 ~]# sshpass -p 'H***#' ssh -o StrictHostKeyChecking=no [email protected] "ls"
anaconda-ks.cfg
install.log
install.log.syslog
tarball
testfile
[root@test1 ~]#

怎么样,有了这个工具可以方便我们制作脚本来管理其它服务器了。

《使用sshpass进行无密码输入提示的SSH连接》有1条评论

发表评论

error: Content is protected !!