2016-12-02 64 views
0

我沒有在我的兩臺服務器a和b之間啓用無密碼ssh。所以我使用sshpass從a連接到服務器b。使用shell腳本修改/ etc/hosts文件

我有一個要求,從一個服務器b的/ etc/hosts中添加主機條目。但是我登錄到服務器b的用戶是非root用戶,但具有sudo權限來編輯由root擁有的文件。

如何在使用sshpass時通過shell腳本將主機條目添加到服務器b的/ etc/hosts中。

這裏是一個被審判的腳本:

#!/bin/bash 

export SSHPASS="password" 
SSHUSER=ciuser 
WPC_IP=10.8.150.28 

sshpass -e ssh -o UserKnownHostsFile=/dev/null -o 'StrictHostKeyChecking no' [email protected]$WPC_IP "echo test >> /etc/hosts" 

輸出:

bash test.sh 
Warning: Permanently added '10.8.150.28' (RSA) to the list of known hosts. 
bash: /etc/hosts: Permission denied 

謝謝。

+0

你能發佈你嘗試過的命令嗎? –

+0

@thatotherguy:更新了問題。謝謝 – user2714227

回答

1

sudodoesn't work with redirects直接,所以你可以使用sudo tee -a追加到一個文件:

echo '1.2.3.4 test' | sudo tee -a /etc/hosts 

在你的命令,這將是:

sshpass -e ssh -o UserKnownHostsFile=/dev/null -o 'StrictHostKeyChecking no' "[email protected]$WPC_IP" "echo test | sudo tee -a /etc/hosts" 

注意,這需要無密碼的sudo訪問tty,它不一定與你的sudo權限相同。