python通过Windows下远程控制Linux系统
一、学习目标
【通过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-8 import socket import os HOST = "192.168.43.226" PORT = 5000 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) addr = (HOST,PORT) s.bind(addr) # 绑定地址 s.listen(1) # 打开监听 conn,addr = s.accept() # 同意建立连接 print(addr) # 输出客户端IP def 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 socket HOST = "192.168.43.226" PORT = 5000 c = 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
感兴趣的朋友可以一起研究讨论学习技术!
相关推荐
bluecarrot 2020-11-23
Attend 2020-11-17
ZHAICAN 2020-11-16
codedecode 2020-11-14
zhangbingb 2020-11-12
ykmail 2020-11-11
futurezone 2020-11-06
rikeyone 2020-11-04
橄榄 2020-11-04
WenCoo 2020-10-31
zhjn0 2020-11-24
以梦为马不负韶华 2020-10-20
farwang 2020-11-25
星愿心愿 2020-11-24
tianhuak 2020-11-24
昭君出塞 2020-11-23
linuxwcj 2020-10-21