自己写的监控服务,想监控windows ,所以用python写了一个服务,用于执行系统命令
用python 3写的,2的话需要修改。
server端,也就是被监控端
import socket import sys,os host = '0.0.0.0' port = int(sys.argv[1])
#这里写入可以连接的客户端地址 trust = '127.0.0.1,192.168.1.31' s = None def conn(): for res in socket.getaddrinfo(host,port,socket.AF_UNSPEC,socket.SOCK_STREAM,0,socket.AI_PASSIVE): af,socktype,proto,canonname,sa = res try: s = socket.socket(af,socktype,proto) except OSError as msg: s = None continue try: s.bind(sa) s.listen(1) except OSError as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) conn,addr = s.accept() error = 'ok' if str(addr[0]) not in str(trust): error = 'error' print('Connected by',addr) while True: conn.settimeout(5) if error != 'error': data = conn.recv(102400) if not data:break data = data.decode(encoding='utf-8',errors='strict') comm = str(data)+' '+'2>&1' content = os.popen(comm).read() content = content.encode(encoding='utf-8',errors='strict') conn.send(content) else: conn.send(b'not trust address') break conn.close() while True: conn()
客户端,也就是监控服务器使用的
import socket import sys host=sys.argv[1] port = sys.argv[2] s = None o = len(sys.argv) comm = [] for i in range(3,o): comm.append(sys.argv[i]) for res in socket.getaddrinfo(host,port,socket.AF_UNSPEC,socket.SOCK_STREAM): af,socktype,proto,canonname,sa = res try: s = socket.socket(af,socktype,proto) except OSError as msg: s = None continue try: s.connect(sa) except OSError as msg: s.close() s = None continue break if s is None: print("could not opensocket") sys.exit(1) comm = ''.join(comm) comm = comm.replace('[]',' ') comm = comm.encode(encoding='utf-8',errors='strict') s.sendall(comm) data = s.recv(102400) print(repr(data)) s.close() sys.exit(0)
使用方法:
服务端启动服务
python server.pyw 8765
#启动服务,监听8765端口
客户端,也就是监控服务器使用的脚本
python client.pyw 127.0.0.1 8765 ipcofing
连接127.0.0.1的8765端口,执行ipconfig命令,
python client.pyw 127.0.0.1 8765 ipcofing[]/all
如果带参数的话,空格使用[]代替