Oct 31

[python] shellsvr 不指定

felix021 @ 2011-10-31 19:15 [IT » Python] 评论(0) , 引用(0) , 阅读(5070) | Via 本站原创 | |
一个蛋疼的服务:向某个端口提供shell服务。

基本流程是这样的:python虚拟一个终端,载入了一个bash;然后呢,监听某个端口,连上该端口的客户端的输入当作bash的输入,将bash的输出返回给该客户端。当客户端断开的时候,bash继续运行,等待下一个客户端。

之所以倒腾出这么个东西,主要是突然想写个php在一个session里面完成一系列任务(甚至su成另外一个用户),但是system之类的函数就很难搞。基本上就是没用的东西。
#!/usr/bin/python

import socket
import os
import thread
import pty

tty = open("/dev/tty", "w")

shell_input_reader, shell_input_writer = os.pipe()
shell_output_reader, shell_output_writer = os.pipe()

def sheller(arg):
    global shell, shell_input_reader, shell_output_writer
    os.dup2(shell_input_reader, 0)
    os.dup2(shell_output_writer, 1)
    os.dup2(shell_output_writer, 2)
    while True:
        pty.spawn('/bin/bash')

def shell_to_sock(conn):
    global shell_output_reader
    while True:
        try:
            conn.send(os.read(shell_output_reader, 1024))
        except:
            break

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 4698)) #如果希望这个服务对其他机器开放的话,那就把这个ip改成0.0.0.0或者外网的ip

sock.listen(5)

thread.start_new_thread(sheller, (1,))

while True:
    conn, addr = sock.accept()
    print >>tty, "%s:%d connected" % (addr[0], addr[1])
    thread.start_new_thread(shell_to_sock, (conn, ))

    while True:
        try:
            buf = conn.recv(1024)
            if not buf:
                break
            print >>tty, "[%s]" % buf.strip()
            os.write(shell_input_writer, buf)
        except:
            break

    conn.close()




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]