在Python中的远程机器上执行命令

2024-03-21

我正在 Ubuntu 上用 python 编写一个程序来执行命令ls -l在 RaspberryPi 上,连接网络。

有人可以指导我该怎么做吗?


当然,有多种方法可以做到!

假设您有一个 Raspberry Piraspberry.lan主机和您的用户名是irfan.

子流程

它是运行命令的默认 Python 库。
你可以让它运行ssh并在远程服务器上执行您需要的任何操作。

scrat 他的回答涵盖了吗 https://stackoverflow.com/a/28413657/974317。如果您不想使用任何第三方库,您绝对应该这样做。

您还可以使用自动输入密码/密码短语pexpect http://pexpect.readthedocs.org/en/latest/.

paramiko

paramiko https://github.com/paramiko/paramiko是一个添加 SSH 协议支持的第三方库,因此它可以像 SSH 客户端一样工作。

连接到服务器、执行并获取结果的示例代码ls -l命令看起来像这样:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('raspberry.lan', username='irfan', password='my_strong_password')

stdin, stdout, stderr = client.exec_command('ls -l')

for line in stdout:
    print line.strip('\n')

client.close()

fabric

您还可以使用它来实现fabric http://docs.fabfile.org/en/1.10/tutorial.html.
Fabric是一个部署工具,可以在远程服务器上执行各种命令。

它通常用于在远程服务器上运行内容,因此您可以轻松地使用单个命令放置最新版本的 Web 应用程序、重新启动 Web 服务器等等。实际上,您可以在多个服务器上运行相同的命令,这太棒了!

尽管它是作为部署和远程管理工具制作的,但您仍然可以使用它来执行基本命令。

# fabfile.py
from fabric.api import *

def list_files():
    with cd('/'):  # change the directory to '/'
        result = run('ls -l')  # run a 'ls -l' command
        # you can do something with the result here,
        # though it will still be displayed in fabric itself.

就像打字一样cd / and ls -l在远程服务器中,因此您将获得根文件夹中的目录列表。

然后在shell中运行:

fab list_files

它将提示输入服务器地址:

No hosts found. Please specify (single) host string for connection: [email protected] /cdn-cgi/l/email-protection

快速说明:您还可以在 a 中分配用户名和主机权限fab命令:

fab list_files -U irfan -H raspberry.lan

或者你可以将主机放入env.hostsfabfile 中的变量。以下是具体操作方法 http://docs.fabfile.org/en/1.10/tutorial.html#defining-connections-beforehand.


然后系统会提示您输入 SSH 密码:

[[email protected] /cdn-cgi/l/email-protection] run: ls -l
[[email protected] /cdn-cgi/l/email-protection] Login password for 'irfan':

然后命令就会成功运行。

[[email protected] /cdn-cgi/l/email-protection] out: total 84
[[email protected] /cdn-cgi/l/email-protection] out: drwxr-xr-x   2 root root  4096 Feb  9 05:54 bin
[[email protected] /cdn-cgi/l/email-protection] out: drwxr-xr-x   3 root root  4096 Dec 19 08:19 boot
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Python中的远程机器上执行命令 的相关文章

随机推荐