Bash
如何在函式(bash)中使用 ssh?
我正在嘗試通過使用
sshpass
如下命令登錄來在伺服器中執行一些命令。SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q' sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo sed -i "/^server 0.rhel.pool.ntp.org/ { N; s/^server 0.rhel.pool.ntp.org\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf' sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo sed -i "/^#server 0.rhel.pool.ntp.org iburst/ { N; s/^#server 0.rhel.pool.ntp.org iburst\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf' echo "File /etc/ntp.conf is now edited" sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo cat /etc/ntp.conf | grep "server xxx.xx.xx.xx iburst"' if [ $? = 0 ]; then sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo service ntpd status;sudo service ntpd restart' else echo "File /etc/ntp.conf is not updated in IP" fi
因此,我不想每次都重複 sshpass,而是將其
sshpass -p 'password' ssh ${SSH_ARGS} user@IP
作為變數或函式。怎麼做?我試過了 ::
SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q' sshpp=`sshpass -p 'password' ssh ${SSH_ARGS} user@IP` $sshpp 'sudo service ntpd status'
還有這個 ::
SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q' sshpp() { sshpass -p 'password' ssh ${SSH_ARGS} user@IP` } sshpp 'sudo service ntpd status'
我也試過這個,但沒有用。
我將如何實現這一目標而不是
sshpass
每次都重複?
您似乎正在尋找的是
alias
:alias sp='sshpass -p "password" ssh $SSH_ARGS user@IP'
因此,您可以執行以下命令:
sp 'sudo sed -i "/^server 0.rhel.pool.ntp.org/ { N; s/^server 0.rhel.pool.ntp.org\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf'
請注意,可能有一些方法可以通過編寫腳本來執行這些重複性任務來進一步簡化您的生活,但這超出了這個問題的範圍。