使用 Python 通过 ssh 执行命令 [英] Perform commands over ssh with Python

查看:129
本文介绍了使用 Python 通过 ssh 执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来自动化 Python 中的一些命令行命令.目前我正在打电话:

I'm writing a script to automate some command line commands in Python. At the moment I'm doing calls thus:

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

但是我需要在远程机器上运行一些命令.手动,我会使用 ssh 登录,然后运行命令.我将如何在 Python 中自动执行此操作?我需要使用(已知)密码登录到远程机器,所以我不能只使用 cmd = ssh user@remotehost,我想知道是否有我应该使用的模块?

However I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I automate this in Python? I need to log in with a (known) password to the remote machine, so I can't just use cmd = ssh user@remotehost, I'm wondering if there's a module I should be using?

推荐答案

我会向你推荐paramiko

参见这个问题

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

如果您使用 ssh 密钥,请执行以下操作:

If you are using ssh keys, do:

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)

这篇关于使用 Python 通过 ssh 执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆