当然,有几种方法可以做到!
假设您在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
...