如果你的創建的密鑰對設置了密碼短語,使用ssh或者sftp命令時,提示手動輸入密碼短語。
這時候如果是自動化的腳本作業,應該如何寫呢?
網上的方案有使用sshpass,但是如果服務器是AIX系統,很不幸,大概率是找不到這個命令的。
ssh.com官網的ssh-add有提及用到密碼短語的密鑰使用情況。
Keys with Passphrases
If the key being added has a passphrase,
ssh-add
will run thessh-askpass
program to obtain the passphrase from the user. If theSSH_ASKPASS
environment variable is set, the program given by that environment variable is used instead.Some people use the
SSH_ASKPASS
environment variable in scripts to provide a passphrase for a key. The passphrase might then be hard-coded into the script, or the script might fetch it from a password vault. However, use of passphrases in this manner does not eliminate the need for proper key lifecycle management and rotation. Instead, we recommend looking at the PrivX On-Demand Access Manager on how to completely eliminate SSH keys in such applications and replace them by short-lived certificates issued on-demand based on centrally managed access policies.
大意就是,可以用SSH_ASKPASS這個環境變量來實現自動輸入密碼短語。但是,官方不推薦因爲這種取巧的方法並不能滿足密鑰的生命週期管理和輪替。順便帶出另一款產品——PrivX。
我不管,我就用取巧的方法。這裏有一個帖子提到如何利用SSH_ASKPASS。
大概如下:
printf "#!/bin/bash\necho password\n" > /usr/bin/sshpass.sh
printf "ls -lrt \n quit \n" > /opt/operation.batch
export SSH_ASKPASS=/usr/bin/sshpass.sh
setsid sftp unixforum@localhost < operation.batch
可以看到,sshpass.sh不過是將密碼硬編碼輸出。這裏有一個關鍵點,setsid。