使用 python 在远程服务器上运行命令 [英] Run a command on remote server using python

查看:61
本文介绍了使用 python 在远程服务器上运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cmd ="some command"
echo "The answer is"
echo $cmd

当我尝试在 python 中使用 paramiko 库运行上述命令时.

When I try to run the above command using paramiko library in python.

上面的命令保存在一个名为command的变量中.

The above command is saved in a variable named command.

stdin,stdout,stderr=ssh_conn.exec_command(command)

stdin,stdout,stderr=ssh_conn.exec_command(command)

进程没有运行echo $cmd"命令的一部分.请帮忙.

The process does not run the "echo $cmd" part of the command. Please help.

推荐答案

首先安装 paramiko

pip3 install paramiko

然后用你自己的命令试试这个代码:

Then try this code with your own commands:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    client.connect(hostname="192.168.1.100", username="user", password="pass")
except:
    exit()

commands = ["pwd", "id", "uname -a", "df -h"]
for command in commands:
    print(command, ":")
    stdin, stdout, stderr = client.exec_command(command)
    print(stdout.read().decode())
    err = stderr.read().decode()
    if err:
        print(err)

这篇关于使用 python 在远程服务器上运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆