python简易远程控制单线程版
程序员文章站
2022-10-29 16:02:10
本文实例为大家分享了python简易远程控制的具体代码,供大家参考,具体内容如下
1. 技术:管道通信,流文件处理,socket基础
2. tips:
默认ip:12...
本文实例为大家分享了python简易远程控制的具体代码,供大家参考,具体内容如下
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()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。