使用paramiko python ssh库通过xterm远程执行程序

时间:2013-10-06 09:13:06

标签: python multithreading ssh x11 paramiko

该计划的流程是:

  1. 使用Paramiko库
  2. 连接Linux机器上的OpenSSH服务器
  3. 打开X11会话
  4. 运行xterm可执行文件
  5. 通过在终端中键入可执行文件名并运行它来运行其他程序(例如Firefox)。
  6. 如果有人能够解释如何使用以下代码在一个打开的终端中运行某些可执行文件并提供示例源代码(source),我将不胜感激:

    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()
    

    我正在考虑在子线程中运行程序,而运行xterm的线程正在等待子进程终止。

1 个答案:

答案 0 :(得分:2)

嗯,这有点像黑客,但是嘿。

您可以在远程端执行以下操作:在xterm中,您运行netcat,侦听某些端口上的任何数据,然后管道进入bash的任何内容。它与在xterm direclty中输入它并不完全相同,但它几乎和直接在bash中键入它一样好,所以我希望它能让你更接近你的目标。如果您真的想直接与xterm交互,可能需要read this

例如:

终端1:

% nc -l 3333 | bash

终端2(此处输入echo hi):

% nc localhost 3333
echo hi

现在您应该看到第一个终端弹出hi。现在尝试使用xterm&。它对我有用。

以下是如何在Python中自动执行此操作的方法。您可能希望添加一些代码,使服务器能够告诉客户何时准备好,而不是使用愚蠢的time.sleep

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

# for connecting to netcat running remotely
from multiprocessing import Process
import time

# data
import getpass
SSHServerPort=22
SSHServerIP = "localhost"
# get username/password interactively, or use some other method..
user = getpass.getuser()
pwd = getpass.getpass("enter pw for '" + user + "': ")
NETCAT_PORT = 3333
FIREFOX_CMD="/path/to/firefox &"
#FIREFOX_CMD="xclock&"#or this :)

def run_stuff_in_xterm():
    time.sleep(5)
    s = socket.socket(socket.AF_INET6 if ":" in SSHServerIP else socket.AF_INET, socket.SOCK_STREAM)
    s.connect((SSHServerIP, NETCAT_PORT))
    s.send("echo \"Hello there! Are you watching?\"\n")
    s.send(FIREFOX_CMD + "\n")
    time.sleep(30)
    s.send("echo bye bye\n")
    time.sleep(2)
    s.close()

# 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 -e \"nc -l 0.0.0.0 %d | /bin/bash\"" % NETCAT_PORT)
p = Process(target=run_stuff_in_xterm)
transport.accept()
p.start()

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()

p.join()
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()

我在Mac上对此进行了测试,因此我将XmingProc位注释掉,并将/Applications/Firefox.app/Contents/MacOS/firefox用作FIREFOX_CMD(和xclock)。

以上并非完全安全的设置,因为任何在适当的时间连接到端口的人都可以在远程服务器上运行任意代码,但听起来您计划将其用于测试目的无论如何。如果要提高安全性,可以将netcat绑定到127.0.0.1而不是0.0.0.0,设置ssh隧道(运行ssh -L3333:localhost:3333 username@remote-host.com以将端口3333上本地接收的所有流量隧道传输到远程 - host.com:3333),让Python连接到("localhost", 3333)

现在,您可以将其与selenium结合使用,以实现浏览器自动化:

按照this page中的说明进行操作,即下载selenium独立服务器jar文件,将其放入/path/to/some/place(在服务器上)和pip install -U selenium(再次,在服务器上)。

接下来,将以下代码放入selenium-example.py中的/path/to/some/place

#!/usr/bin/env python
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.yahoo.com") # Load page
assert "Yahoo" in browser.title
elem = browser.find_element_by_name("p") # Find the query box
elem.send_keys("seleniumhq" + Keys.RETURN)
time.sleep(0.2) # Let the page load, will be added to the API
try:
    browser.find_element_by_xpath("//a[contains(@href,'http://docs.seleniumhq.org')]")
except NoSuchElementException:
    assert 0, "can't find seleniumhq"
browser.close()

并更改firefox命令:

FIREFOX_CMD="cd /path/to/some/place && python selenium-example.py"

观看firefox做雅虎搜索。您可能还想增加time.sleep

如果你想运行更多程序,你可以在运行firefox之前或之后做这样的事情:

# start up xclock, wait for some time to pass, kill it.
s.send("xclock&\n")
time.sleep(1)
s.send("XCLOCK_PID=$!\n")  # stash away the process id (into a bash variable)
time.sleep(30)
s.send("echo \"killing $XCLOCK_PID\"\n")
s.send("kill $XCLOCK_PID\n\n")
time.sleep(5)

如果你想执行一般的X11应用程序控制,我认为你可能需要编写类似的"驱动程序应用程序",尽管使用不同的库。您可能希望搜索" x11发送{mouse | keyboard}事件"找到更一般的方法。这会带来these questions,但我确定还有更多。

如果远程端没有立即响应,您可能想要在Wireshark中嗅探您的网络流量,并检查TCP是否正在对数据进行批处理,而不是逐行发送({{1似乎在这里有所帮助,但我想这里没有保证)。如果是这种情况,您可能是out of luck,但nothing is impossible。我希望你不要走那么远; - )

还有一点需要注意:如果您需要与CLI程序进行通信' STDIN / STDOUT,您可能希望查看期望脚本(例如使用pexpect,或者对于简单的情况,您可以使用subprocess.Popen.communicate](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate))。