18

我正在尝试运行一个paramiko应该能够打开 X 窗口的命令。我使用的脚本如下:

import paramiko                                    

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('192.168.122.55', username='user', password='password')
transport = ssh_client.get_transport()
session = transport.open_session()

session.request_x11()
stdin = session.makefile('wb')
stdout = session.makefile('rb')
stderr = session.makefile_stderr('rb')
session.exec_command('env; xterm')
transport.accept()

print 'Exit status:', session.recv_exit_status()
print 'stdout:\n{}'.format(stdout.read())
print 'stderr:\n{}'.format(stderr.read())
session.close()

不幸的是,当我运行上面的脚本时,我得到了这个输出:

Exit status: 1
stdout:
SHELL=/bin/bash
XDG_SESSION_COOKIE=8025e1ba5e6c47be0d2f3ad6504a25ee-1347286654.617967-1932974971
SSH_CLIENT=192.168.122.1 58654 22
USER=user
MAIL=/var/mail/user
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
PWD=/home/user
LANG=en_US.UTF-8
SHLVL=1
HOME=/home/user
LOGNAME=user
SSH_CONNECTION=192.168.122.1 58654 192.168.122.55 22
DISPLAY=localhost:10.0
_=/usr/bin/env

stderr:  
xterm: Xt error: Can't open display: localhost:10.0

如果我在终端中运行以下命令:

ssh -X user@192.168.122.55 'env; xterm'

然后我得到相同的环境变量(虽然有些端口发生了变化),所以我会说我的环境是正确的。但是,我仍然缺少paramiko使用 x11 转发的东西。

我尝试过的几件事是:

  • 使用handler参数 in request_x11: 除了打印值之外,我没有比使用默认处理程序更进一步。
  • Use the auth_cookieparameter in : 尝试硬编码根据输出request_x11正在使用的 cookie 值。xauth list这样做的想法是避免根据文档字符串paramiko本身可能发生的问题:

如果省略 auth_cookie,将生成、使用和返回一个新的安全随机 128 位值。您将需要使用此值来验证传入的 x11 请求并将其替换为实际的本地 x11 cookie(这需要一些 x11 协议的知识)。

我还能做些什么来使其正常工作或解决问题吗?

注意:这已经在之前被问过:

  • superuser:唯一的响应指向request_x11我已经尝试使用无济于事的文档。
  • stackoverflow:接受的响应建议使用handler参数,但它是错误的。
  • github:一年多没有提供答案。
4

5 回答 5

21

阅读 paramiko 代码,我意识到 paramiko 只是实现了一种建立 x11 通道的方法。它不会将通道连接到本地 x11 显示器。那是留给你的。

这是我刚刚编写的一个小实现:

#!/usr/bin/env python

import os
import select
import sys

import paramiko
import Xlib.support.connect as xlib_connect


local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])
local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3])


ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('server', username='username', password='password')
transport = ssh_client.get_transport()
session = transport.open_session()
session.request_x11(single_connection=True)
session.exec_command('xterm')
x11_chan = transport.accept()

session_fileno = session.fileno()
x11_chan_fileno = x11_chan.fileno()
local_x11_socket_fileno = local_x11_socket.fileno()

poller = select.poll()
poller.register(session_fileno, select.POLLIN)
poller.register(x11_chan_fileno, select.POLLIN)
poller.register(local_x11_socket, select.POLLIN)
while not session.exit_status_ready():
    poll = poller.poll()
    if not poll: # this should not happen, as we don't have a timeout.
        break
    for fd, event in poll:
        if fd == session_fileno:
            while session.recv_ready():
                sys.stdout.write(session.recv(4096))
            while session.recv_stderr_ready():
                sys.stderr.write(session.recv_stderr(4096))
        if fd == x11_chan_fileno:
            local_x11_socket.sendall(x11_chan.recv(4096))
        if fd == local_x11_socket_fileno:
            x11_chan.send(local_x11_socket.recv(4096))

print 'Exit status:', session.recv_exit_status()
while session.recv_ready():
    sys.stdout.write(session.recv(4096))
while session.recv_stderr_ready():
    sys.stdout.write(session.recv_stderr(4096))
session.close()

一些注意事项:

  • 我正在使用 python-Xlib 中的一些辅助函数。这是 Xlib 的纯 python 实现。有关安装它的详细信息,请参阅此问题:How do you install Python Xlib with pip?

  • 我如何实现它的一些细节让我相信它只适用于 1 x11 连接(因此session.request_x11(single_connection=True)。)我想继续努力让它处理多个连接,但这将不得不等待另一天.

  • 此代码实质上使用以下方式以异步方式将以下通道/套接字连接在一起select.poll

    • session.stdout->sys.stdout
    • session.stderr->sys.stderr
    • x11channel->local_x11_socket
    • local_x11_socket- >x11channel
  • 模块向paramiko模块输出大量有用的调试信息logging。您可以通过配置日志记录模块来查看:

    import logging
    logging.basicConfig(level=logging.DEBUG)
    
于 2012-10-15T20:56:06.593 回答
2
  • x11请求可能使用MIT-MAGIC-COOKIE-1您可能无法正确处理的
  • 直接使用 ssh 我看到它需要确认 x11 请求(cookie 挑战?)
  • .Xauthority文件也可能是一个问题
  • 您可以尝试stracessh 进程并查看正常流程
  • 在您的脚本中,您可以替换xtermstrace xterm并与上述内容进行比较。

一些链接:

祝你好运。

编辑:建立在加里的答案之上,有多个 x11 连接。

#!/usr/bin/env python

import os
import select
import sys
import getpass
import paramiko
import socket
import logging
import Xlib.support.connect as xlib_connect
LOGGER = logging.getLogger(__name__)

# connection settings
host = '192.168.122.55'
user = 'user'
password = getpass.getpass()

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(host, username=user, password=password)
del password

# maintain map
# { fd: (channel, remote channel), ... }
channels = {}

poller = select.poll()
def x11_handler(channel, (src_addr, src_port)):
    '''handler for incoming x11 connections
    for each x11 incoming connection,
    - get a connection to the local display
    - maintain bidirectional map of remote x11 channel to local x11 channel
    - add the descriptors to the poller
    - queue the channel (use transport.accept())'''
    x11_chanfd = channel.fileno()
    local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3])
    local_x11_socket_fileno = local_x11_socket.fileno()
    channels[x11_chanfd] = channel, local_x11_socket
    channels[local_x11_socket_fileno] = local_x11_socket, channel
    poller.register(x11_chanfd, select.POLLIN)
    poller.register(local_x11_socket, select.POLLIN)
    LOGGER.debug('x11 channel on: %s %s', src_addr, src_port)
    transport._queue_incoming_channel(channel)

def flush_out(session):
    while session.recv_ready():
        sys.stdout.write(session.recv(4096))
    while session.recv_stderr_ready():
        sys.stderr.write(session.recv_stderr(4096))

# get local disply
local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])
# start x11 session
transport = ssh_client.get_transport()
session = transport.open_session()
session.request_x11(handler=x11_handler)
session.exec_command('xterm')
session_fileno = session.fileno()
poller.register(session_fileno, select.POLLIN)
# accept first remote x11 connection
transport.accept()

# event loop
while not session.exit_status_ready():
    poll = poller.poll()
    # accept subsequent x11 connections if any
    if len(transport.server_accepts) > 0:
        transport.accept()
    if not poll: # this should not happen, as we don't have a timeout.
        break
    for fd, event in poll:
        if fd == session_fileno:
            flush_out(session)
        # data either on local/remote x11 socket
        if fd in channels.keys():
            channel, counterpart = channels[fd]
            try:
                # forward data between local/remote x11 socket.
                data = channel.recv(4096)
                counterpart.sendall(data)
            except socket.error:
                channel.close()
                counterpart.close()
                del channels[fd]

print 'Exit status:', session.recv_exit_status()
flush_out(session)
session.close()
于 2012-10-13T19:30:17.403 回答
2

鉴于您要求使用最小版本,我认为它尽可能易于使用。这是基于两种代码的版本,但这将 x11 会话命令与通用代码分开,使主程序简单且会话代码可重用:

import paramiko
import os
import select
import sys
import Xlib.support.connect as xlib_connect

def run(transport, session, command):
    def x11_handler(channel, (src_addr, src_port)):
        x11_fileno = channel.fileno()
        local_x11_channel = xlib_connect.get_socket(*local_x11_display[:3])
        local_x11_fileno = local_x11_channel.fileno()

        # Register both x11 and local_x11 channels
        channels[x11_fileno] = channel, local_x11_channel
        channels[local_x11_fileno] = local_x11_channel, channel

        poller.register(x11_fileno, select.POLLIN)
        poller.register(local_x11_fileno, select.POLLIN)

        transport._queue_incoming_channel(channel)

    def flush_out(channel):
        while channel.recv_ready():
            sys.stdout.write(channel.recv(4096))
        while channel.recv_stderr_ready():
            sys.stderr.write(channel.recv_stderr(4096))

    local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])

    channels = {}
    poller = select.poll()
    session_fileno = session.fileno()
    poller.register(session_fileno)

    session.request_x11(handler=x11_handler)
    session.exec_command(command)
    transport.accept()

    # event loop
    while not session.exit_status_ready():
        poll = poller.poll()
        if not poll: # this should not happen, as we don't have a timeout.
            break
        for fd, event in poll:
            if fd == session_fileno:
                flush_out(session)
            # data either on local/remote x11 channels/sockets
            if fd in channels.keys():
                sender, receiver = channels[fd]
                try:
                    receiver.sendall(sender.recv(4096))
                except:
                    sender.close()
                    receiver.close()
                    channels.remove(fd)

    flush_out(session)
    return session.recv_exit_status()

if __name__ == '__main__':
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect('192.168.122.55', username='user', password='password')
    transport = ssh_client.get_transport()
    session = transport.open_session()
    run(transport, session, 'xterm')

我知道你可以自己做。但是,只要复制该功能,run任何人都可以轻松使用它。

正确答案是https://stackoverflow.com/a/12903844/278878。这个例子是为了让新手更容易。

于 2012-10-19T05:15:08.063 回答
1

感谢 Gary van der Merwednozay的代码。下面的代码严重依赖它并用于在 Windows 上运行 X 程序。显着的区别是使用 select.select 而不是 poll,因为 poll 在 Windows 中不可用。欢迎任何改进或更正。

import select
import sys
import paramiko
import Xlib.support.connect as xlib_connect
import os
import socket
import subprocess



# run xming
XmingProc = subprocess.Popen("C:/Program Files (x86)/Xming/Xming.exe :0 -clipboard -multiwindow")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(SSHServerIP, SSHServerPort, username=user, password=pwd)
transport = ssh_client.get_transport()
channelOppositeEdges = {}

local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])
inputSockets = []

def x11_handler(channel, (src_addr, src_port)):
    local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3])
    inputSockets.append(local_x11_socket)
    inputSockets.append(channel)
    channelOppositeEdges[local_x11_socket.fileno()] = channel
    channelOppositeEdges[channel.fileno()] = local_x11_socket
    transport._queue_incoming_channel(channel)

session = transport.open_session()
inputSockets.append(session)
session.request_x11(handler = x11_handler)
session.exec_command('xterm')
transport.accept()

while not session.exit_status_ready():
    readable, writable, exceptional = select.select(inputSockets,[],[])
    if len(transport.server_accepts) > 0:
        transport.accept()
    for sock in readable:
        if sock is session:
            while session.recv_ready():
                sys.stdout.write(session.recv(4096))
            while session.recv_stderr_ready():
                sys.stderr.write(session.recv_stderr(4096))   
        else: 
            try:
                data = sock.recv(4096)
                counterPartSocket  = channelOppositeEdges[sock.fileno()]
                counterPartSocket.sendall(data)
            except socket.error:
                inputSockets.remove(sock)
                inputSockets.remove(counterPartSocket)
                del channelOppositeEdges[sock.fileno()]
                del channelOppositeEdges[counterPartSocket.fileno()]
                sock.close()
                counterPartSocket.close()

print 'Exit status:', session.recv_exit_status()
while session.recv_ready():
    sys.stdout.write(session.recv(4096))
while session.recv_stderr_ready():
    sys.stdout.write(session.recv_stderr(4096))
session.close()
XmingProc.terminate()
XmingProc.wait()
于 2013-10-03T16:11:36.923 回答
0

对于那些在 Mac OS X Leopard 中工作的人,没有 select.poll()。这是使用 kqueue 而不是 poll的dnozay 答案的修改版本。对此的任何改进/更正将不胜感激。

#!/usr/bin/env python

import os
import select
import sys
import paramiko
import socket
import Xlib.support.connect as xlib_connect

# get local display
local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('hostname', port=22, username='username', password='password')

channels = {}
kq = select.kqueue()

def x11Handler(x11_chan, (src_addr, src_port)):
    x11_chan_fileno = x11_chan.fileno()
    local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3])
    local_x11_socket_fileno = local_x11_socket.fileno()
    channels[x11_chan_fileno] = x11_chan, local_x11_socket
    channels[local_x11_socket_fileno] = local_x11_socket, x11_chan

    ev = [select.kevent(x11_chan_fileno, filter=select.KQ_FILTER_READ, flags=select.KQ_EV_ADD), select.kevent(local_x11_socket_fileno, filter=select.KQ_FILTER_READ, flags=select.KQ_EV_ADD)]
    kevents = kq.control(ev, 0, None)
    transport._queue_incoming_channel(x11_chan)

def flushOut(session):
    while session.recv_ready():
        sys.stdout.write(session.recv(4096))
    while session.recv_stderr_ready():
        sys.stderr.write(session.recv_stderr(4096))

# start x11 session
transport = ssh_client.get_transport()
session = transport.open_session()
session.request_x11(handler=x11Handler)
session.exec_command('xterm')

# accept first remote x11 connection
x11_chan = transport.accept()
session_fileno = session.fileno()

session_ev = [select.kevent(session_fileno, 
    filter=select.KQ_FILTER_READ,
    flags=select.KQ_EV_ADD)] 

kevents_session = kq.control(session_ev, 0, None)

# event loop
while not session.exit_status_ready():
    r_events = kq.control(None, 4)
    # accept subsequent x11 connections if any

    if len(transport.server_accepts) > 0:
        transport.accept()
    if not r_events: # this should not happen, as we don't have a timeout.
        break
    for event in r_events:
        print event
        if event.ident & session_fileno:
            flushOut(session)
        # data either on local/remote x11 socket
        if event.ident in channels.keys():
            x11_chan, counterpart = channels[event.ident]
            try:
                # forward data between local/remote x11 socket.
                data = x11_chan.recv(4096)
                counterpart.sendall(data)
            except socket.error:
                x11_chan.close()
                counterpart.close()
                del channels[event.ident]

flushOut(session)
kq.close()
session.close()
于 2013-01-31T20:54:37.827 回答