如何通过Python将OSX shell提示符返回给用户?
我想实现自己的"远程终端"。 我正在尝试这个,但它每次只执行一个命令。 我希望它像终端窗口一样持久。
import socket
import threading
import subprocess
bind_ip = "0.0.0.0"
bind_port = 9997
# how to connect?
# telnet 0.0.0.0 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip,bind_port)
# this is our client-handling thread
def handle_client(client_socket):
try:
while True:
# print out what the client sends
request = client_socket.recv(1024)
print "[*] Received: %s" % request
# send back a packet
# client_socket.send("ACK!\n")
if request == "quit": break
# do shell command
proc = subprocess.Popen(request.strip(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# read output
stdout_value = proc.stdout.read() + proc.stderr.read()
# send output to attacker
client_socket.send(stdout_value)
except:
print "Connection failed. Closing port..."
client_socket.close()
while True:
client,addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1])
# spin up our client thread to handle incoming data
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()