【问题标题】:Paramiko server: Redirect the output of a SUBPROCESS to a channelParamiko 服务器:将 SUBPROCESS 的输出重定向到通道
【发布时间】:2017-12-03 14:46:42
【问题描述】:

我正在尝试使用paramiko 实现一个(本地伪造)服务器,它响应自定义命令,就像用于测试目的的原始命令一样。主要从提供的demo server复制,我设法想出了这个自定义方法来处理通过paramiko.ServerInterface实现的服务器的exec_requests

def check_channel_exec_request(self,channel,command):
    print("User wants to execute '%s'" %(command))
    comm_main, comm_add = command.decode().split(sep=" ",maxsplit=1)
    if comm_main in self.allowed_commands:
        chout = channel.makefile("w")
        subprocess.Popen(command,stdout=chout)
        return True
        else:
            return False

服务器运行后通过:

PORT = 50007 # The same port as used by the server
HOST = 'localhost'
host_key = paramiko.RSAKey(filename = <FILEPATH>)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((HOST,PORT))
    sock.listen(1)
    conn, addr = sock.accept() # Connected!
    with conn:
        trans = paramiko.Transport(conn)
        trans.add_server_key(host_key)
        trans.set_subsystem_handler("job",JobHandler)
        server = FakeCluster() # Custom class sublassing paramiko.ServerInterface
        trans.start_server(server=server)
        chan = trans.accept() # Accept authentication from client
        while trans.is_active(): # Do not close until inactive
            time.sleep(1)
        chan.close()

客户端会尝试以下列方式执行echo 123

PORT = 50007 # The same port as used by the server
HOST = 'localhost' 
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind((HOST,PORT))

    ssh = paramiko.client.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(HOST, PORT,username=<USERNAME>,password=<PASSWORD>)
    ssh.exec_command("echo 123")

现在,我在尝试执行 subprocess'ChannelFile' has no attribute 'fileno' 时遇到 错误。此外,我想知道以后如何将 python 脚本作为exec_command 调用的自定义命令执行。 (也许通过调用调用 python 脚本的批处理文件?)

【问题讨论】:

  • 找到fileno错误here的解决方案/解释

标签: python python-3.x subprocess paramiko


【解决方案1】:

你的问题真的很令人困惑,这是我与远程服务器通信所做的。

本地机器:窗口

远程机器:ubuntu

远程机器上的命令:'who'

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.268.21.26',port=22,username='root',password='default')
stdin,stdout,stderr=ssh.exec_command('who')
output=stdout.readlines()
print '\n'.join(output)

#output
#root    tty7         2017-11-28 14:13 (:0)

#if you wish to execute a python file there , this should work
stdin,stdout,stderr=ssh.exec_command('python file.py')

【讨论】:

  • 感谢您的回答,我承认我写这个问题真的很困惑。我在this question 中总结了我的进展,希望能澄清我的一般问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 2017-07-06
  • 2015-01-23
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
相关资源
最近更新 更多