[英]Execute Bash script remotely via cURL
我有一個簡單的 Bash 腳本,它接收輸入並用這些輸入打印幾行
fortinet測試文件
read -p "Enter SSC IP: $ip " ip && ip=${ip:-1.1.1.1}
printf "\n"
#check IP validation
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "SSC IP: $ip"
printf "\n"
else
echo "Enter a valid SSC IP address. Ex. 1.1.1.1"
exit
fi
我嘗試將它們上傳到我的服務器,然后嘗試通過curl
運行它
我不知道為什么在我使用 cURL/wget 時輸入提示永遠不會啟動。
我錯過了什么嗎?
隨着curl ... | bash
curl ... | bash
形式,bash 的 stdin 正在讀取腳本,因此 stdin 對read
命令不可用。
嘗試使用進程替換來像調用本地文件一樣調用遠程腳本:
bash <( curl -s ... )
您的問題可以通過運行如下腳本來簡單地重現
$ cat test.sh | bash
Enter a valid SSC IP address. Ex. 1.1.1.1
這是因為您使用pipe
啟動的 bash 沒有獲得TTY
,當您執行read -p
它是從stdin
讀取的,在這種情況下是test.sh
內容。 所以問題不在於卷曲。 問題不是從 tty 讀取
所以修復是確保你從 tty 准備好
read < /dev/tty -p "Enter SSC IP: $ip " ip && ip=${ip:-1.1.1.1}
printf "\n"
#check IP validation
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "SSC IP: $ip"
printf "\n"
else
echo "Enter a valid SSC IP address. Ex. 1.1.1.1"
exit
fi
一旦你這樣做了,即使curl
也會開始工作
vagrant@vagrant:/var/www/html$ curl -s localhost/test.sh | bash
Enter SSC IP: 2.2.2.2
SSC IP: 2.2.2.2
我個人更喜歡source <(curl -s localhost/test.sh)
選項。 雖然它類似於bash ...
,但一個顯着的區別是進程的處理方式。
bash
將導致啟動一個新進程,該進程將從腳本中調用命令。
另一方面, source
將使用當前進程從腳本中調用命令。
在某些情況下可以發揮關鍵作用。 我承認這並不常見。
要演示,請執行以下操作:
### Open Two Terminals
# In the first terminal run:
echo "sleep 5" > ./myTest.sh
bash ./myTest.sh
# Switch to the second terminal and run:
ps -efjh
## Repeat the same with _source_ command
# In the first terminal run:
source ./myTest.sh
# Switch to the second terminal and run:
ps -efjh
結果應該類似於:
執行前:
運行bash
(主進程 + 兩個子進程):
運行source
(主進程 + 一個子進程):
更新: bash
和source
使用變量用法的差異:
source
命令將使用您當前的環境。 這意味着在執行時,腳本所做的所有更改和變量聲明都將在您的提示中可用。
另一方面, bash
將作為不同的進程運行; 因此,當進程退出時,所有變量都將被丟棄。
我想每個人都會同意每種方法都有優點和缺點。 您只需要決定哪一種更適合您的用例。
## Test for variables declared by the script:
echo "test_var3='Some Other Value'" > ./myTest3.sh
bash ./myTest3.sh
echo $test_var3
source ./myTest3.sh
echo $test_var3
## Test for usability of current environment variables:
test_var="Some Value" # Setting a variable
echo "echo $test_var" > myTest2.sh # Creating a test script
chmod +x ./myTest2.sh # Adding execute permission
## Executing:
. myTest2.sh
bash ./myTest2.sh
source ./myTest2.sh
./myTest2.sh
## All of the above results should print the variable.
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.