首页 > 解决方案 > Paramiko exec_command() 不在远程 Linux 服务器上执行命令

问题描述

我正在编写一个 Python 3.7 脚本来在远程 Linux 服务器上连接和执行命令。

我使用了 paramiko 和 ssh2.session 库,脚本能够连接到远程服务器,但没有执行命令。

远程服务器详细信息

cat /etc/issue

**Welcome to SUSE Linux Enterprise Server 12 SP2  (x86_64) - Kernel \r (\l).**

视窗python版

C:\Users\Desktop>python --version

**Python 3.7.4**

我已经通过链接python paramiko ssh并使用了类似的 python 脚本

请使用 paramiko 库检查以下代码

import paramiko

hostname='x.x.x.x' #ip not mentioned for privacy reasons
port=4422
username='ts_r'
password='a'


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,port=port,username=username,password=password)
stdin, stdout, stderr = ssh.exec_command("ls -lrt")
print(stdout.readlines())
print(stderr.readlines())
ssh.close()


script output:
--------------
C:\Users\Desktop>python test.py
[]
[]

使用 ssh2.session

我已经浏览了链接https://pypi.org/project/ssh2-python/并使用了类似的 python 脚本

请使用 ssh2.session 库检查以下代码

from __future__ import print_function

import socket

from ssh2.session import Session

host = 'x.x.x.x' #ip not mentioned for privacy reasons
user = 'ts_r'
port = 4422
password = 'a'
cmd="ls -lrt"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

session = Session()
session.handshake(sock)
session.userauth_password(user, password)

channel = session.open_session()
channel.execute(cmd)
size, data = channel.read()
while size > 0:
    print(data)
    size, data = channel.read()
channel.close()
print("Exit status: %s" % channel.get_exit_status())


script output:
--------------
C:\Users\Desktop>python test3.py
Exit status: 1

我使用端口 4422 而不是端口 22,因为它用于远程 linux 服务器上的其他应用程序。

有人可以解释不在远程服务器上执行命令的原因以及如何解决问题。

这里的问题是脚本既没有给出执行命令的输出也没有抛出错误。

我尝试了不同的命令,例如“pwd”、“uname -a”,它们都没有被执行。

我从 paramiko 文档中找到了关于 exec_command 的以下描述

exec_command(*args, **kwds)

Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed.

我想知道服务器是否允许连接但不允许执行命令如何检查。

标签: pythonparamikossh2

解决方案


推荐阅读