[英]Bash script not executing command properly when run from script
我有一個shell腳本如下
#!/bin/bash
USER=someuser
HOSTNAMEORIP=somehostname
SCRIPT="/etc/rc.d/netif restart && /etc/rc.d/routing restart"
su -c "ssh -l ${USER} ${HOSTNAMEORIP} ${SCRIPT}" -s /bin/sh someotheruser
如果我登錄到計算機並僅運行"/etc/rc.d/netif restart && /etc/rc.d/routing restart"
那么它將起作用。 但是,如果我運行上面的整個腳本,則會得到sh: 1: /etc/rc.d/routing: not found
,好像不是在處理腳本部分一樣。 我什至可以在沒有這樣的用戶的情況下使用上述腳本
#!/bin/bash
USER=someuser
HOSTNAMEORIP=somehostname
SCRIPT="/etc/rc.d/netif restart && /etc/rc.d/routing restart"
ssh -l ${USER} ${HOSTNAMEORIP} ${SCRIPT}
它可以正常工作,但是我需要使用su -c <command> -s /bin/sh user
因為另一個應用程序正在調用該腳本,並且關聯的用戶是唯一具有ssh-key登錄/沒有密碼的用戶。
如何使su -c "ssh -l ${USER} ${HOSTNAMEORIP} ${SCRIPT}" -s /bin/sh someotheruser
在此用例中正確運行腳本?
讓我們來完成它。 該命令:
su -c "ssh -l ${USER} ${HOSTNAMEORIP} ${SCRIPT}" -s /bin/sh someotheruser
將執行此字符串作為shell命令:
ssh -l someuser somehostname /etc/rc.d/netif restart && /etc/rc.d/routing restart
這顯然是錯誤的,並且會因相同的錯誤而失敗。
要修復它,讓我們修復命令並向后工作。 你應該在執行
ssh -l someuser somehostname '/etc/rc.d/netif restart && /etc/rc.d/routing restart'
因此,您可以像這樣更新腳本:
#!/bin/bash
USER=someuser
HOSTNAMEORIP=somehostname
SCRIPT="/etc/rc.d/netif restart && /etc/rc.d/routing restart"
su -c "ssh -l ${USER} ${HOSTNAMEORIP} '${SCRIPT}'" -s /bin/sh someotheruser
# ^--- ^---
請注意,這取決於$SCRIPT
不包含嵌入式單引號的事實。 如果可以,或者您不知道,可以使用$(printf "%q" "$SCRIPT")
代替嵌入字符串中的'$SCRIPT'
來使bash自動轉義。
或者您可以切換到sudo
。 由於它使用安全且健壯的execve(2)
語義而不是system(3)
語義,因此您不必嵌套轉義:
sudo -u someotheruser ssh -l "$USER" "$HOSTNAMEORIP" "$SCRIPT"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.