使用Python通过ssh执行命令
使用Python通过ssh执行命令
我正在编写一个Python脚本来自动化一些命令行命令。目前,我正在进行如下调用:
cmd = "some unix command" retcode = subprocess.call(cmd,shell=True)
但是,我需要在远程机器上运行一些命令。手动操作时,我会使用ssh
登录,然后运行命令。我该如何在Python中自动化这个过程?我需要使用(已知的)密码登录到远程机器,所以我不能仅仅使用cmd = ssh user@remotehost
,我在想是否有应该使用的模块?
admin 更改状态以发布 2023年5月22日
简单点。不需要用到库。
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()
我向您引荐 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)