使用Python通过ssh执行命令

2024-04-25 23:55:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本来自动执行Python中的一些命令行命令。现在我正在打电话:

cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)

不过,我需要在远程计算机上运行一些命令。手动地,我将使用ssh登录,然后运行命令。如何在Python中实现自动化?我需要用一个(已知的)密码登录到远程计算机,所以我不能只使用cmd = ssh user@remotehost,我想知道是否有我应该使用的模块?


Tags: 命令行命令脚本cmdtrue远程计算机unix
3条回答

或者您可以使用commands.getstatusoutput

   commands.getstatusoutput("ssh machine 1 'your script'")

我用得很广泛,效果很好。

在Python 2.6+中,使用^{}

我把你介绍给paramiko

this question

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

你看过Fabric吗?它允许您使用python通过SSH执行各种远程操作。

相关问题 更多 >