我正在编写一个脚本来自动化Python中的一些命令行命令。目前,我正在进行这样的调用:
cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)
但是,我需要在远程机器上运行一些命令。我会手动使用ssh
登录,然后运行命令。我将如何在Python中自动执行此操作?我需要使用(已知的)密码登录到远程机器,所以我不能只使用cmd = ssh user@remotehost
,我想知道是否有我应该使用的模块?
发布于 2010-08-28 00:18:03
我会推荐你去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)
发布于 2010-08-28 00:44:46
或者,您可以只使用commands.getstatusoutput
commands.getstatusoutput("ssh machine 1 'your script'")
我广泛地使用了它,它工作得很好。
在Python 2.6+中,使用subprocess.check_output
。
发布于 2019-08-10 13:49:07
保持简单。不需要任何库。
import subprocess
subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
https://stackoverflow.com/questions/3586106
复制相似问题