在使用ssh对服务器进行远程操作时,都需要停下来输入密码,这在批量执行脚本时很不方便。
可以使用sshpass来进行执行,将password通过命令行、环境变量或者文件传递进去,从而可以完全在脚本里面跑执行命令,实现自动化的操作。这里主要分享Ubuntu上面的使用情况。
安装 sshpass,基于Debian / Ubuntu Linux
输入命令:
$ sudo apt-get install sshpass
- 在MacOS上安装使用:brew install http://git.io/sshpass.rb
在Linux使用sshpass
安装完毕后,直接输入sshpass将显示帮助信息。
Login 到 ssh server(server.example.com),password 为 t@uyM59bQ:
$ sshpass -p 't@uyM59bQ' ssh username@server.example.com
对于shell script,你可能需要 disable host key 检查:
$ sshpass -p 't@uyM59bQ' ssh -o StrictHostKeyChecking=no username@server.example.com
- Security unwise warning:
- The -p option should be considered the least secure of all of sshpass’s options.
- I recommend that you use ssh’s public key authentication.
基于bash shell script使用 SSHPASS 的例子
可以在脚本中使用-p参数、SSHPASS环境变量、文件等方式读取password的值并自动传递给ssh。
快速开始使用
sshpass -p mypassword ssh user@server ifconfig
上面的命令将使用mypassword和user账户登录到server并执行ifconfig命令后,自动退出。
更新Ubuntu系统软件包
sshpass -p MyPassWord ssh root@remoteServerIP "apt update && apt upgrade -y && apt autoremove -y"
使用环境变量传递password
语法:
SSHPASS='t@uyM59bQ' sshpass -e ssh vivek@server42.cyberciti.biz SSHPASS='t@uyM59bQ' sshpass -e ssh vivek@server42.cyberciti.biz date SSHPASS='t@uyM59bQ' sshpass -e ssh vivek@server42.cyberciti.biz w SSHPASS='t@uyM59bQ' sshpass -e ssh -o StrictHostKeyChecking=no vivek@server42.cyberciti.biz |
password 通过名为 SSHPASS 的环境变量传递进去。
从文件读取 password
另外一个选项是从文件读取password,使用 -f 选项。语法为:
sshpass -f fileNameHere ssh user@server
创建文件,如下:
$ echo 'myPassword' > myfile $ chmod 0400 myfile $ sshpass -f myfile ssh vivek@server42.cyberciti.biz |
使用rsync备份backup /var/www/html
通过SSH运行rsync,启用password authentication, 传递 password 在命令行中:
$ rsync --rsh="sshpass -p myPassword ssh -l username" server.example.com:/var/www/html/ /backup/
或者:
$ SSHPASS='yourPasswordHere' rsync --rsh="sshpass -e ssh -l username" server.example.com:/var/www/html/ /backup/
使用 sshpass with gpg encrypted file
首先,创建文件如下:
$ echo 'mySshPasswordHere' > .sshpassword
现在,使用gpg command加密文件:
$ gpg -c .sshpassword
$ rm .sshpassword
最后,如下使用:
$ gpg -d -q .sshpassword.gpg > fifo; sshpass -f fifo ssh vivek@server1.cyberciti.biz
更多信息: