一、学习目标
【通过Windows下远程控制Linux系统实现对socket模块认识】
二、实验环境
Windows下(模拟客户端 [ IP:192.168.43.87 ] ):python3.6
Linux下(模拟服务端 [ IP:192.168.43.226 ] ):python2.7
三、前提条件
两者能够ping通
服务端关闭防火墙,selinux
四、代码
服务端代码(server.py):
#!/usr/bin/env python#coding:utf-8import socketimport osHOST = "192.168.43.226"PORT = 5000s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)addr = (HOST,PORT)s.bind(addr) # 绑定地址s.listen(1) # 打开监听conn,addr = s.accept() # 同意建立连接print(addr) # 输出客户端IPdef get_client_file(): # 定义服务端获取文件函数 conn.send("Ready to receive!") data = conn.recv(20480) # 接受客户端的数据 print(data) with open("clientFile.txt",'wb') as f: f.write(data) conn.close()def send_server_file(): # 定义服务端发送文件函数 c_filepath = conn.recv(1024) # 接受客户机请求路径 with open(c_filepath,'rb') as f: data = f.read() conn.sendall(data) conn.close()def main(): while True: cmd = conn.recv(1024) print(cmd) # 打印接受的命令 if cmd == "q": break if cmd == "transdata": get_client_file() # 获取客户端文件 break if cmd == "recvdata": send_server_file() # 发送服务端文件 break data = os.popen(cmd) # 响应客户端命令 sdata = data.read() if sdata: conn.sendall(sdata) else: conn.send("finish") conn.close() s.close() if __name__ == "__main__": main()
客户端(client.py):
import socketHOST = "192.168.43.226"PORT = 5000c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)addr = ((HOST,PORT))c.connect(addr) # 连接服务器def send_client_file(): # 定义客户端发送文件函数 data = c.recv(1024) # 接收预备传输提示 print(data) c_filepath = input("Please enter the client file path:") with open(c_filepath,"rb") as f: file = f.read() # 以byte方式读取文件内容 c.sendall(file) # 将读取的内容发往服务端def get_server_file(): # 定义客户端接受文件函数 s_filepath = input("Please enter the server file path:") c.send(bytes(s_filepath,encoding='gbk')) data = c.recv(20480) # 等待接受服务器数据 with open("shadow.txt","wb") as f: f.write(data)def main(): while True: cmd = input("Plsase input a command:") c.send(bytes(cmd,encoding="gbk")) # 发送数据 if cmd == "q": break if cmd == "transdata": # 创建发送客户端文件命令 send_client_file() break if cmd == "recvdata": # 创建接收服务端文件命令 get_server_file() break data = c.recv(20480) print(data) c.close()if __name__ =="__main__": main()
五、测试结果(这里拿获取服务端shadow文件测试)
在windows下运行client.py文件
》》键入:recvdata
》》键入:/etc/shadow
新闻热点
疑难解答