Paramiko exec_command()未在远程Linux服务器上执行命令

时间:2020-01-06 07:28:09

标签: python paramiko ssh2

我正在研究Python 3.7脚本,以在远程Linux服务器上连接并执行命令。

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

远程服务器详细信息

cat /etc/issue

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

Windows 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.

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

0 个答案:

没有答案