![](/img/trans.png)
[英]Bash script how to run a command remotely and then exit the remote terminal
[英]Bash: how to run a script remotely
我有一個腳本(比如run.py
),我想將它scp到遠程機器(比如10.1.100.100
),cd到該遠程機器的目錄中,然后在該目錄中執行run.py
如何在一個單獨的bash腳本中包含上述過程? 我不知道如何讓bash在另一台機器上遠程執行命令。
希望我能在終端中看到run.py
stdout。 但如果我只能重定向它,那也沒關系。
chmod +x ./run.py
scp -pq ./run.py 10.1.100.100:'/home/myremotedirectory/run.py'
ssh 10.1.100.100 'cd /somedirectory && /home/myremotedirectory/run.py'
看看是否有幫助
你可以這樣做:
ssh -l yourid 10.1.100.100 << DONE
cd /your/dir/
./run.py
DONE
上面已經編輯過,我不記得它原來是什么樣的,如果我想在一個連接中做到這一點,我會這樣做。
ssh -l yourid 10.1.100.100 python < <(
echo "import os"
echo "os.chdir('/yourdir')"
echo "print(os.getcwd())"
cat yourscript.py
)
通過SSH執行腳本而不復制腳本文件。 您需要一個簡單的SSH連接和本地腳本。
#!/bin/sh
print_usage() {
echo -e "`basename $0` ssh_connexion local_script"
echo -e "Remote executes local_script on ssh server"
echo -e "For convinient use, use ssh public key for remote connexion"
exit 0
}
[ $# -eq "2" ] && [ $1 != "-h" ] && [ $1 != "--help" ] || print_usage
INTERPRETER=$(head -n 1 $2 | sed -e 's/#!//')
cat $2 | grep -v "#" | ssh -t $1 $INTERPRETER
- ssh-remote-exec root@server1 myLocalScript.sh #for Bash
- ssh-remote-exec root@server1 myLocalScript.py #for Python
- ssh-remote-exec root@server1 myLocalScript.pl #for Perl
- ssh-remote-exec root@server1 myLocalScript.rb #for Ruby
此腳本執行此操作:1°捕獲第一行#! 獲得解釋器(即:Perl,Python,Ruby,Bash解釋器),2°通過SSH啟動遠程互操作,3°通過SSH發送所有腳本體。
本地腳本必須以#!/ path / to / interpreter開頭
- #!/bin/sh for Bash script
- #!/usr/bin/perl for Perl script
- #!/usr/bin/python for Python script
- #!/usr/bin/ruby for Ruby script
此腳本不是基於本地腳本擴展,而是基於#! 信息。
請記住,這不是一個規則,你必須cd到所請求的目錄。
一旦您訪問遠程計算機,只需鍵入此文件的相對路徑,而不使用cd:
/some_folder/./run.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.