首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Paramiko服务器:将SUBPROCESS的输出重定向到信道

Paramiko服务器:将SUBPROCESS的输出重定向到信道
EN

Stack Overflow用户
提问于 2017-12-03 14:46:42
回答 1查看 827关注 0票数 0

我正在尝试用实现一个(本地假的) paramiko服务器,它响应自定义命令,就像最初的测试目的一样。主要是从提供的演示服务器复制,我设法提出了这个自定义方法来处理通过paramiko.ServerInterface实现的服务器的请求

代码语言:javascript
复制
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

在服务器通过以下方式运行之后:

代码语言:javascript
复制
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

代码语言:javascript
复制
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脚本的批处理文件?)

EN

回答 1

Stack Overflow用户

发布于 2017-12-04 07:24:45

您的问题非常令人困惑,下面是我为与远程服务器进行通信所做的工作。

本地机器:窗口

远程机器:ubuntu

远程计算机上的命令:“谁”

代码语言:javascript
复制
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')
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47619517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档