Python簡易遠隔制御(単線版)

3081 ワード

1.技術:パイプ通信、ストリームファイル処理、socket基礎
2. Tips:
デフォルトIP:127.0.0.1
デフォルトポート:7676
3.コードサンプル:
サービス:
#!/usr/bin/env python  
# encoding: utf-8  

import socket
import sys
from os import *

reload(sys)  
sys.setdefaultencoding("utf-8")  

def socketInit():
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	return s

def socketDeal(s,HOST,PORT):
	s.bind((HOST,PORT))
	s.listen(1)

def ControlModule(sS,addr):
	recv_buffer = sS.recv(20048)
	if recv_buffer == "[-]Error:Server is OFF" or recv_buffer == "[*]Server is OFF":
		print recv_buffer
		sys.exit(0)
	else:
		print recv_buffer
	send_buf = raw_input(addr[0]+">")
	sS.send(send_buf)


def main():
	HOST = "127.0.0.1"
	PORT = 7676
	s = socketInit()
	socketDeal(s, HOST, PORT)
	sS,addr = s.accept()
	print "Connect from " + addr[0] + ":" + repr(addr[1])
	try:
		while True:
			ControlModule(sS,addr)
	except Exception as e:
		print "[-]Connect Error"
		sS.close()
		s.close()
		sys.exit(-1)
	except KeyboardInterrupt:
		sS.close()
		s.close()
		sys.exit(0)

if __name__ == '__main__':
	main()

管理側:
#!/usr/bin/env python  
# encoding: utf-8  

import socket
import sys
import re
import traceback
import tempfile
from os import *
from subprocess import *

reload(sys)  
sys.setdefaultencoding("utf-8")  

def socketInit():
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	return s

def socketConn(s,HOST,PORT):
	while True:
		try:
			s.connect((HOST,PORT))
		except Exception as e:
			continue
		else:
			s.send("Welcome Sir ~")
			break


def String_Deal(recv,send):
	P_str = re.findall("cd(.*)|(\w):", recv)
	if P_str!=[] and send == "":
		if P_str[0][0]!="":
			try:
				chdir(P_str[0][0].strip())
			except Exception as e:
				flag = -1
			else:
				flag = 1
		else:
			try:
				chdir(recv)
			except Exception as e:
				#traceback.print_exc()
				flag = -1
			else:
				flag = 1
	else:
		if send == "":
			flag = 1
		else:
			flag = 0
	return flag

def OpenProcess(s):
	try:
		while True:
			recv_buf = s.recv(2048)
			#     ,      
			out_temp = tempfile.SpooledTemporaryFile(bufsize=10*1000)
			fileNo = out_temp.fileno()
			cmd = Popen(recv_buf, shell=True,stdin=PIPE, stdout=fileNo, stderr=STDOUT)
			cmd.wait()
			out_temp.seek(0)
			send_buf = out_temp.read()
			#print len(send_buf)
			#           
			flag = String_Deal(recv_buf,send_buf)
			if flag == 1:
				s.send("OK")
			elif flag == -1:
				s.send("Error!!")
			else:
				s.send(send_buf)
			send_buf = ""
	except Exception as e:
		try:
			s.send("[-]Error:Server is OFF")
		except Exception as e:
			pass
			s.close()
		sys.exit(-1)		
	except KeyboardInterrupt:
		try:
			s.send("[*]Server is OFF")
		except Exception as e:
			pass
		s.close()
		sys.exit(0)	
def main():
	flag = 0
	HOST = "127.0.0.1"
	PORT = 7676
	s = socketInit()
	socketConn(s, HOST, PORT)
	OpenProcess(s)


if __name__ == '__main__':
	main()