python远程登录并执行命令_在Python中的远程机器上执行命令

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

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

它是运行命令的默认Python库.

您可以使它运行ssh并在远程服务器上执行您需要的任何操作.

scrat has it covered in his answer.如果你不想使用任何第三方库,你绝对应该这样做.

您还可以使用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('

')

client.close()

您也可以使用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.

这就像在远程服务器中键入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

或者您可以将主机放入fabfile中的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

...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值