![使用 ssh 和 Expect 腳本對遠端伺服器上的檔案進行計數](https://rvso.com/image/31672/%E4%BD%BF%E7%94%A8%20ssh%20%E5%92%8C%20Expect%20%E8%85%B3%E6%9C%AC%E5%B0%8D%E9%81%A0%E7%AB%AF%E4%BC%BA%E6%9C%8D%E5%99%A8%E4%B8%8A%E7%9A%84%E6%AA%94%E6%A1%88%E9%80%B2%E8%A1%8C%E8%A8%88%E6%95%B8.png)
下面是我的腳本,用於對遠端伺服器中存在的檔案進行計數。但它不起作用。
#!/usr/bin/expect
spawn ssh [email protected]
expect "123"
send "123"
interact
destPath='/archive/Input/ERICIN/AIR/EMG'
dayStamp=`(date --date='1 day ago' '+%Y%m%d')`
if [ -d $destPath ]
then
cd $destPath
`cat 'emg_audit_1_'$dayStamp.csv|grep 'ACTPSO_NE_'$dayStamp|wc -l > /home/stsuser/eastregioncount/NEremote$dayStamp.txt`
else
echo "ERROR: Path $destPath Does not Exists."
fi
答案1
為了讓它發揮作用,我建議進行兩項重大改變:
- 使用公鑰/私鑰對
- 在命令列上發送命令到 ssh
您可以使用ssh-keygen
產生新的私鑰-公鑰對,並使用ssh-copy-id
將產生的公鑰安裝到 上的新帳戶172.0.0.2
。之後您就不必expect "123"
再執行該序列了。
這也使您能夠ssh
更輕鬆地在命令列上呼叫命令(假設兩台電腦上的時區相同):
destPath='/archive/Input/ERICIN/AIR/EMG'
dayStamp=`(date --date='1 day ago' '+%Y%m%d')`
ssh [email protected] "cd $destPath; cat 'emg_audit_1_'$dayStamp.csv| grep 'ACTPSO_NE_'$dayStamp| wc -l > /home/stsuser/eastregioncount/NEremote$dayStamp.txt"
if [ $? -ne 0 ]
then
echo "ERROR"
fi
cd 指令已經告訴您 $destPath 不存在,無須自行回顯。但echo "Error"
如果有必要,您可以測試退出程式碼並執行一些更有意義的操作(比)。