我想運行一個python腳本來關閉我網路上的所有PC。它們都是啟用了ssh功能的Linux機器,并使用相同的用戶名和密碼。我是個新手,在任何地方都找不到關于我如何做這件事的資訊。
uj5u.com熱心網友回復:
在我看來,最好使用一個bash腳本,因為你可以通過機器上的ssh命令輸入命令。
例如,在bash中,執行通過ssh關閉電腦的命令的一行將是:
ssh user1@server1 "sudo shutdown -h now"
如果你仍然想在Python中進行,請嘗試使用subprocess模塊或os模塊來執行shell命令。
uj5u.com熱心網友回復:
首先,使用公鑰認證比把你的密碼存盤在某個地方要好得多(https://serverpilot.io/docs/how-to-use-ssh-public-key-authentication/)。
然后你只需通過ssh呼叫shutdown命令。
importos
os.system("ssh user@host 'shutdown now'"/span>)
顯然,你的遠程系統中的用戶必須具有關閉計算機的權限。
uj5u.com熱心網友回復:
另一個選擇是使用Ansible(用Python撰寫,有Python模塊),用它可以管理遠程服務器(幾乎所有的OS-es)。
下面是一些Ansible代碼在多種重啟情況下的示例(例如,test.yml):
- name: 無條件地 重新啟動 the machine with all defaults
重新啟動:
- name: 重新啟動 一個 慢 機器 那 可能 有 大量 of updates to apply
重新啟動:
reboot_timeout: 3600
- name: 重新啟動 a 機器 with shutdown command in unusual place
重新啟動:
search_paths:
- '/lib/molly-guard'/span>
- name: 重新啟動 機器 使用 a custom reboot command
重新啟動:
reboot_command: launchctl reboot userspace
boot_time_command: uptime | cut -d ' ' f 5
Ansible只需要安裝在你的電腦上(臺式機/筆記本電腦/服務器),它將控制所有其他節點。對你能控制的作業系統或發行版幾乎沒有限制(這包括Linux、UNIX、Windows等)。ssh連接需要被配置(用戶和密碼)。你的代碼將不必硬編碼節點串列、用戶名或密碼,它將只是一個配置。
這種設定可能是最容易大規模管理多個節點的,并且可以提供添加額外節點管理功能的能力。
為了從Python中運行ansible,Ansible提供了ansible-runner Python包(PyPI,GitHub),它可以用于此。
import ansible_runner
r = ansible_runner.run(private_data_dir='/tmp/demo', playbook='test.yml')
print("{}: {}".format(r.status, r.rc)
# successful: 0
for each_host_event in r.events。
print(each_host_event['event'])
print("最終狀態:")
print(r.stats)
更多檔案。ansible-runner: python_interface/a>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333347.html
標籤:
