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

Irf*_*ar7 16 python terminal ubuntu tkinter paramiko

我在Ubuntu上用python编写程序,ls -l在RaspberryPi上执行命令,与Network连接.

任何人都可以指导我如何做到这一点?

Igo*_*ist 37

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

假设您在raspberry.lan主机上有一个Raspberry Pi,而您的用户名是irfan.

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

scrat 已经在他的回答覆盖.如果您不想使用任何第三方库,您肯定应该这样做.

您还可以使用自动输入密码/密码pexpect.

的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()
Run Code Online (Sandbox Code Playgroud)

您也可以使用它来实现它fabric.
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.
Run Code Online (Sandbox Code Playgroud)

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

然后在shell中运行:

fab list_files
Run Code Online (Sandbox Code Playgroud)

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

No hosts found. Please specify (single) host string for connection: irfan@raspberry.lan
Run Code Online (Sandbox Code Playgroud)

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

fab list_files -U irfan -H raspberry.lan
Run Code Online (Sandbox Code Playgroud)

或者您可以将主机放入env.hostsfabfile中的变量中.这是怎么做的.


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

[irfan@raspberry.lan] run: ls -l
[irfan@raspberry.lan] Login password for 'irfan':
Run Code Online (Sandbox Code Playgroud)

然后命令将成功运行.

[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
...
Run Code Online (Sandbox Code Playgroud)

  • @ IrfanGhaffar7您可以使用`pip`或`easy_install`安装第三方Python库.所以它将是`pip install fabric`.查看文档(我链接到fabric和paramiko docs),它有快速入门和教程! (2认同)
  • @ IrfanGhaffar7和`paramiko`你可以运行实际的python脚本本身. (2认同)
  • @ IrfanGhaffar7如果你使用paramiko,你应该像那样连接:`client.connect('192.168.2.40',username ='pi',password ='raspberry')` (2认同)

sas*_*hab 13

这里简单的例子:

import subprocess
import sys

HOST="www.example.org"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uname -a"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result
Run Code Online (Sandbox Code Playgroud)

它完全符合您的要求:通过ssh连接,执行命令,返回输出.不需要第三方库.

  • @IrfanGhaffar7 这是因为 `result` 是一个列表,而不是一个字符串。您可以改为执行 `print ''.join(result)` 以使其看起来可读。 (2认同)