如何使用 Python 透過 ssh 執行不同的命令?


使用 python 使用 SSH 最簡單的方法是使用 paramiko。可以使用以下方法安裝它 −

$ pip install paramiko

為使用 Paramiko,確保已在主機上正確設定 SSH 金鑰(https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html),並且在執行 Python 指令碼時,可以訪問這些金鑰。完成後,使用以下程式碼透過 ssh 連線到遠端伺服器 −

from paramiko import SSHClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('user@server:path')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls')
print(ssh_stdout) #print the output of ls command

可以使用 exec_command 函式執行所連線伺服器支援的任何命令。執行以上程式碼將在遠端伺服器上獲取目錄列表。

更新於:2020 年 2 月 18 日

1 千 + 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.