經常我們使用腳本登入服務器的時候,如果使用ssh 命令,經常會提示密碼輸入,我們不得不手動輸入密碼,因為ssh 沒有 密碼的選項。
為了能繞過交互式驗證,我們使用sshpass命令解決這個問題:
1. 安裝
➜ Desktop sudo yum install sshpass [sudo] password for xuyaowen: Last metadata expiration check: 0:04:22 ago on Mon 02 Jul 2018 11:25:32 AM CST. Package sshpass-1.06-5.fc28.x86_64 is already installed, skipping. Dependencies resolved. Nothing to do. Complete!
檢查是否安裝
[root@yaowenxu Desktop]# rpm -qa sshpass sshpass-1.06-5.fc28.x86_64
2. 查看 sshpass 命令幫助, 也可以使用 man sshpass

NAME sshpass - noninteractive ssh password provider SYNOPSIS sshpass [-ffilename|-dnum|-ppassword|-e] [options] command arguments DESCRIPTION This manual page documents the sshpass command. sshpass is a utility designed for running ssh using the mode referred to as "keyboard-interactive" password authentication, but in non-interactive mode. ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user. Sshpass runs ssh in a dedicated tty, fooling it into thinking it is getting the password from an interactive user. The command to run is specified after sshpass' own options. Typically it will be "ssh" with arguments, but it can just as well be any other command. The password prompt used by ssh is, however, currently hardcoded into sshpass.
[root@yaowenxu Desktop]# 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
3. 使用密碼驗證登錄
➜ ~ sshpass -p 123 ssh root@10.66.65.15
4. ssh 第一次登錄提示問題使用:
ssh -o StrictHostKeyChecking=no
來解決
➜ Desktop sshpass -p 123 ssh -o StrictHostKeyChecking=no root@10.66.8.142 Warning: Permanently added '10.66.8.142' (ECDSA) to the list of known hosts. Last login: Mon Jul 2 10:51:29 2018
5. 優缺點
優點: 快速,便捷
缺點: 密碼明文暴露,可以使用 history 命令查找到