我正在 Ubuntu 上用 python 编写程序,在 RaspberryPi 上执行命令 ls -l
,连接网络。
谁能指导我该怎么做?
最佳答案
当然,有几种方法可以做到!
假设您在 raspberry.lan
主机上有一个 Raspberry Pi,您的用户名是 irfan
。
子进程
它是运行命令的默认 Python 库。
您可以让它运行 ssh
并在远程服务器上执行您需要的任何操作。
抓取 has it covered in his answer .如果您不想使用任何第三方库,您绝对应该这样做。
您还可以使用 pexpect
自动输入密码/口令。 .
Paramiko
paramiko
是添加 SSH 协议(protocol)支持的第三方库,因此它可以像 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
来实现它.
Fabric 是一种部署工具,可在远程服务器上执行各种命令。
它通常用于在远程服务器上运行东西,因此您可以轻松地放置最新版本的网络应用程序、重新启动网络服务器以及诸如此类的单个命令。实际上,您可以在多个服务器上运行相同的命令,这太棒了!
虽然它是作为部署和远程管理工具而制作的,但您仍然可以使用它来执行基本命令。
# 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/
和 ls -l
一样,您将获得根文件夹中的目录列表。
然后在shell中运行:
fab list_files
它将提示输入服务器地址:
No hosts found. Please specify (single) host string for connection: irfan@raspberry.lan
快速说明:您还可以在 fab
命令中分配用户名和主机:
fab list_files -U irfan -H raspberry.lan
或者您可以将主机放入您的 fab 文件中的 env.hosts
变量中。 Here's how to do it .
然后系统会提示您输入 SSH 密码:
[irfan@raspberry.lan] run: ls -l
[irfan@raspberry.lan] Login password for 'irfan':
然后命令将成功运行。
[irfan@raspberry.lan] out: total 84
[irfan@raspberry.lan] out: drwxr-xr-x 2 root root 4096 Feb 9 05:54 bin
[irfan@raspberry.lan] out: drwxr-xr-x 3 root root 4096 Dec 19 08:19 boot
...
关于python - 使用 Python 在远程机器上执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28411960/