服务器端:
import socket,os server=socket.socket() server.bind(('localhost',9999)) server.listen() while True: conn,addr=server.accept() print("new conn:",addr) while True: print("等待新指令") data=conn.recv(1024) if not data: print("客户端已经断开") break print("执行指令:",data) cmd_res=os.popen(data.decode()).read()
#接收字符串,执行结果也是字符串.os.popen()函数调用系统命令nmap进行扫描,
#但用os.popen就可以读出执行的内容,popen返回的是file read的对象,对其进行读取使用read(),就可看到执行的输出: if len(cmd_res)==0: cmd_res="cmd has no output.." print("before send",len(cmd_res)) conn.send(cmd_res.encode("utf-8")) print("send done")
客户端:
import socket client=socket.socket() client.connect(("localhost",9999)) while True: cmd=input(">>:").strip() if len(cmd)==0:continue client.send(cmd.encode("utf-8")) cmd_res=client.recv(1024) print(cmd_res.decode()) server.close()
服务器端运行结果:
new conn: ('127.0.0.1', 64074) 等待新指令 执行指令: b'dir' before send 466 send done 等待新指令 执行指令: b'pwd' 'pwd' is not recognized as an internal or external command, operable program or batch file. before send 19 send done 等待新指令
客户端运行结果:
>>:dir b' Volume in drive C is OSDisk Volume Serial Number is 002E-D604 Directory of C:\abccdxddd\Oldboy\Py_Exercise\Day8 08/03/2017 11:18 AM <DIR> . 08/03/2017 11:18 AM <DIR> .. 08/03/2017 11:17 AM 650 socket_server_ssh.py 08/03/2017 11:18 AM 250 sock_server_client.py 08/02/2017 01:50 PM 187 ????.py 3 File(s) 1,087 bytes 2 Dir(s) 146,482,311,168 bytes free ' >>:pwd b'cmd has no output..' >>: