使用Python通过SSH执行命令
我正在写一个脚本,用Python来自动化一些命令行的操作。目前,我是这样调用命令的:
cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)
不过,我需要在一台远程机器上运行一些命令。手动操作时,我会用ssh
登录,然后再运行命令。我想知道如何在Python中自动化这个过程?我需要用一个(已知的)密码登录到远程机器,所以我不能仅仅使用cmd = ssh user@remotehost
,我在想是否有什么模块可以使用?
17 个回答
57
或者你可以直接使用 commands.getstatusoutput:
commands.getstatusoutput("ssh machine 1 'your script'")
我用这个方法很多次,效果非常好。
在 Python 2.6 及以上版本中,使用 subprocess.check_output
。
85
保持简单。不需要任何库。
import subprocess
# Python 2
subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
# Python 3
subprocess.Popen(f"ssh {user}@{host} {cmd}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
283
我推荐你去看看 paramiko 这个网站。
你可以参考 这个问题。
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)
如果你在使用 SSH 密钥的话,可以这样做:
k = paramiko.RSAKey.from_private_key_file(keyfilename)
# OR k = paramiko.DSSKey.from_private_key_file(keyfilename)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, pkey=k)