sshpass 的使用

​ ssh远程连接时,每次都提示需要输入密码。需要ssh到多台机器时很不方便。sshpass可以解决这个问题。sshpass可以实现ssh的自动的登录。直接在命令里输入密码,但是安全性的问题需要自己判断。

安装

  1. Installing on Ubuntu

    apt-get install sshpass

  2. Installing on OS X

    • 开始之前需要安装install xcode and command line tools.

    • 之后安装Installing with Homebrew

    • 由于安全问题,brew 官方默认不允许安装,可以尝试如下方法:

    brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

  3. 源码安装

    • Download the Source Code
    • Extract it and cd into the directory
    • ./configure
    • sudo make install

用法介绍

1
2
3
4
5
6
7
8
9
10
11
[root@zhu ~]# sshpass --help
sshpass: invalid option -- '-'
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-p password #后跟密码
[root@zhu ~]# sshpass -p 123456 ssh [email protected]
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 [email protected]
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 [email protected]
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.

如果在多台主机执行命令:

1
2
3
4
5
6
7
[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

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×