一、学习目标
【通过Windows下远程控制Linux系统实现对socket模块认识】
二、实验环境
Windows下(模拟客户端 [ IP:192.168.43.87 ] ):python3.6
Linux下(模拟服务端 [ IP:192.168.43.226 ] ):python2.7
三、前提条件
两者能够ping通
服务端关闭防火墙,selinux
四、代码
服务端代码(server.py):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#!/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):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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
感兴趣的朋友可以一起研究讨论学习技术!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Aaron_Miller/article/details/80485430