0

这是我的代码 它只使用“bash”命令在网络上创建终端。
我想向此代码添加类似于交互式实验室工作的功能。一侧有终端,另一侧有内容部分。我想在我的 Web 终端上运行 mouseclick 功能上的命令,我正在寻找解决方案如何做到这一点,你能提出一些建议吗?

class WebmuxTermManager(terminado.SingleTermManager):
def get_terminal(self, port_number):
    self.shell_command = ["bash"]
    term = self.new_terminal()
    self.start_reading(term)
    return term

class TerminalPageHandler(tornado.web.RequestHandler):
def get_host(self, port_number):
    pass

def get(self, port_number):
    return self.render("term.html", static=self.static_url, ws_url_path="/_websocket/"+port_number, hostname=self.get_host(port_number))

if __name__ == "__main__":

term_manager = WebmuxTermManager(shell_command=('bash'))
handlers = [
    (r"/_websocket/(\w+)", terminado.TermSocket, {'term_manager': term_manager}),
    (r"/shell/([\d]+)/?", TerminalPageHandler),
    (r"/webmux_static/(.*)", tornado.web.StaticFileHandler, {'path':os.path.join(TEMPLATE_DIR,"webmux_static")}),
]
application = tornado.web.Application(handlers, static_path=STATIC_DIR,template_path=TEMPLATE_DIR,term_manager=term_manager,debug=True)
application.listen(8888)


try:
    IOLoop.current().start()
except KeyboardInterrupt:
    logging.info("\nShuttiing down")
finally:
    term_manager.shutdown()
    IOLoop.current().close()
4

1 回答 1

1

首先我不知道terminado是什么,所以我会坚持使用tornado的websockets,

根据您的规则集创建一个 websocket 类来发送和接收消息

class WebsocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        # deals with allowing certain ip address ranges or domain_names to
        # connect to your websocket

        pass

    def open(self):
        # perform some logic when the socket is connected to the client side
        # eg give it a unique id to and append it to a list etc, its up to you

        pass

    def on_message(self, command):
        # this is where your problem lies
        # act on the message
        send_back = self.runCommand(command)
        self.write_message(send_back)

   def on_close(self):
       # delete the socket

       pass

   def runCommand(self, command):
       # import shlex
       # import supbrocess
       cmd = shlex.split(command)
       process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
       stdout, stderr = process.communicate()

       return dict(
           stdout=stdout.decode(),
           stderr=stdout.decode()
       )

WebsocketHandler类的路由是

(r"/websocket_test", WebsocketHandler)

将其连接到您的路线并启动龙卷风服务器

在客户端

使用 javascript 连接如下:

//secure or unsecure, up to you.

unsecure_test_conn = new WebSocket('ws://ip_address_or_domain_name/websocket_test')
secure_test_conn = new WebSocket('wss://ip_address_or_domain_name/websocket_test')

unsecure_test_conn.onmessage = function(event){
    data = JSON.parse(event.data)
    //act on the data as you see fit and probably send it back to server
    send_back = parseMessage(data)
    unsecure_test_conn.send(send_back)
}

这应该让您开始了解如何在网络上来回发送信息。

于 2018-06-21T07:18:14.713 回答