![](/img/trans.png)
[英]Using Python to ssh then run bash script. The output of the running bash script i need to display on the screen
[英]Need to write a bash script to ssh into many UNIX machines, run a python script and push results to GitHub
我正在嘗試編寫一個bash腳本,該腳本對200台UNIX計算機執行以下操作:
在for循環中,ssh輸入,導航到正確的目錄。
然后,使用命令行參數在給定目錄中執行python文件。 此命令行參數是根據for循環中的位置指定的。 因此,第一台計算機使用命令“ 0”運行腳本,然后第二台計算機使用命令“ 1”運行腳本,依此類推。
我將如何去做呢? 我正在研究shell腳本,但是我以前從未寫過。
另外,我必須使用密碼登錄機器,因此我需要在腳本中進行說明。
Sparrowdo提供一個整潔的API來做到這一點,我寫了關於這一主題的小文章- https://sparrowdo.wordpress.com/2017/02/01/sshscp-commands-with-sparrowdo/ 。 好處是您可以使用高級語言Perl6編寫腳本,並且可以自由實現任何復雜的邏輯。
PS.disclosure-我是工具作者。
首先,我假設您像我一樣懶惰,並且想要采用最簡單的解決方案。 我認為在這種情況下是Ansible 。 它是一個自動化工具,可以在hosts
文件中列出的所有計算機上使用ssh命令。
主機文件:
[myServers]
myServer1
myServer2
myServer3
...
您可以編寫劇本,這是在每台計算機上執行的一系列操作。 在這里,例如您的playbook.yml
看起來像
- name: Executing my python program
shell: "python mypythoncommand"
args:
chdir: theDirectoryYouWant
此時,我們仍然需要為每台計算機增加命令中的某些部分。 為此,我們可以使用Jinja2語言,該語言基本上是在應用命令之前對代碼進行解釋的語言。
我認為類似的事情會做的工作:
hosts: myServers
vars:
- myVariable: 0
tasks:
{% for thehost in play_hosts %}
{% if inventory_hostname==thehost %}
- name: Executing my python program
shell: "python mypythoncommand {{myVariable + loop.index}}"
args:
chdir: theDirectoryYouWantToBeIn
{% endif %}
{% endfor %}
該劇本ssh在所有服務器上運行,並在服務器列表上進行迭代,當它發現服務器Ansible處於ssh-ing狀態時,它將對已傳遞的每台服務器執行變量遞增的命令。
您將需要在文件中獲取程序的輸出。 Ansible將日志存儲在您想要的位置,您只需要:
export ANSIBLE_LOG_PATH="/path/to/my/log" && ansible-playbook myAwesomePlaybook.yml -k -u username && git commit -a -m "execution log $(date)"
-k
要求輸入密碼, -u username
選擇您要以ssh身份登錄的用戶。
希望有幫助,如果你真的想要去,你可能需要閱讀的bash 這並看看sshpass
才能連接到每台服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.