这几天配置一台服务器,在某云平台创建云服务器后,生成了巨长、巨复杂的一串密码,在输入几十次密码后,依然是密码错误。这时候就想如果密码是非交互式输入,可以将密码做为参数或从文件输入就太好了。sshpass就是一款密码输入辅助工具,它可以从命令行明文参数、文件或环境变量中指定密码,从而避免交互式密码输入。
1. sshpass的安装
首先从以下网址下载sshpass源码:
https://sourceforge.net/projects/sshpass/
下载后解码压,然后进入源码目录:
tar -zxvf sshpass-1.06.tar.gz
cd sshpass-1.06
配置安装:
./configure
编译并安装:
make && make install
在Mac系统下,也可以使用brew安装:
brew install sshpass
2. 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
如上所示,command parameters为你要执行的需要交互式输入密码的命令,如:ssh、scp等。当sshpass没有指定参数时会从stdin获取密码,几个密码输入相关参数如下:
-f filename:从文件中获取密码
-d number:使用数字作为获取密码的文件描述符
-p password:指定明文本密码输入(安全性较差)
-e:从环境变量SSHPASS获取密码
3. sshpass的使用
现有一台服务器登录密码是mypass,IP为192.168.1.33。使用sshpass的几种录方式如下。
将密码写入文件,并从文件获取登录密码:
$ echo "mypass" > user.passwd
$ sshpass -f user.passwd ssh root@192.168.1.33
以明文的方式输入密码:
sshpass -p mypass ssh root@192.168.1.33
从环境变量中获取密码:
$ export SSHPASS="mypass"
$> sshpass -e ssh root@192.168.1.33