Created
July 11, 2015 18:00
-
-
Save wanghongfei/f83c06afff5a15a0f13f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding=UTF-8 | |
__author__ = 'whf' | |
import socket | |
import subprocess | |
import sys | |
import thread | |
HOST = '' | |
PORT = 9013 | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.bind((HOST, PORT)) | |
s.listen(5) | |
def process_connection(conn ,addr): | |
while True: | |
data = conn.recv(1024).strip('\r\n') | |
cmds = data.split(' ') | |
print 'command received: %s' % cmds | |
# 断开连接 | |
if cmds[0] == 'exit': | |
conn.sendall('bye~') | |
conn.close() | |
print 'Disconnected by ', addr | |
break | |
# 退出程序 | |
if cmds[0] == 'close': | |
conn.sendall('server program is going to shutdown!!\n') | |
conn.close() | |
sys.exit(0) | |
if not cmds: | |
continue | |
# execute command | |
outcome = None | |
try: | |
outcome = subprocess.check_output(cmds, stderr=subprocess.STDOUT) | |
except subprocess.CalledProcessError as e: | |
outcome = e.output | |
except OSError as e: | |
outcome = e.__str__() | |
print 'sending result:%s' % outcome | |
conn.sendall(outcome + '\n') | |
while True: | |
conn, addr = s.accept() | |
print 'Connected by', addr | |
# process request in a separate thread | |
thread.start_new_thread(process_connection, (conn, addr)) | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment