Linux 非交互式 ssh 密码认证工具之 sshpass

2018/11/20 ssh,sshpass

ssh 登陆不能在命令行中指定密码。sshpass 的出现,解决了这一问题。

sshpass 用于非交互 SSH 的密码验证,一般用在sh脚本中,无须再次输入密码。

它允许你用 -p 参数指定明文密码,然后直接登录远程服务器,它支持密码从命令行、文件、环境变量中读取。

安装方式

其默认没有安装,需要手动安装,方法如下:

源码安装

sshpass 下载地址:http://sourceforge.net/projects/sshpass/ 下载为一个 tar.gz 的压缩包。


$ tar -zxvf sshpass-1.05.tar.gz
$ cd sshpass-1.05

#指定安装目录
$ ./configure --prefix=/opt/sshpass
$ make
$ make install
$ cp /opt/sshpass/bin/sshpass /usr/bin/

yum/apt 软件包安装

# centos
$ sudo yum install sshpass -y

# ubuntu
$ sudo apt install sshpass -y

经过以上步骤,sshpass 安装完成,输入命令 sshpass 如出现如下提示即安装成功:

$ sshpass
sshpass
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

   -P prompt     Which string should sshpass search for to detect a password prompt
   -v            Be verbose about what you're doing
   -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.

从命令行方式传递密码 -p 指定密码

[root@zhu ~] sshpass -p '123456' ssh user_name@host_ip
[root@zhu ~] sshpass -p '123456' scp root@host_ip:/home/test/t  ./tmp/

如在多台主机执行命令:

[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

原文链接:https://www.cnblogs.com/chenlaichao/p/7727554.html

Search

    Table of Contents