一、學(xué)習(xí)目標(biāo)
【通過Windows下遠(yuǎn)程控制Linux系統(tǒng)實(shí)現(xiàn)對(duì)socket模塊認(rèn)識(shí)】
二、實(shí)驗(yàn)環(huán)境
Windows下(模擬客戶端 [ IP:192.168.43.87 ] ):python3.6
Linux下(模擬服務(wù)端 [ IP:192.168.43.226 ] ):python2.7
三、前提條件
兩者能夠ping通
服務(wù)端關(guān)閉防火墻,selinux
四、代碼
服務(wù)端代碼(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 ) # 打開監(jiān)聽 conn,addr = s.accept() # 同意建立連接 print (addr) # 輸出客戶端IP def get_client_file(): # 定義服務(wù)端獲取文件函數(shù) conn.send( "Ready to receive!" ) data = conn.recv( 20480 ) # 接受客戶端的數(shù)據(jù) print (data) with open ( "clientFile.txt" , 'wb' ) as f: f.write(data) conn.close() def send_server_file(): # 定義服務(wù)端發(fā)送文件函數(shù) c_filepath = conn.recv( 1024 ) # 接受客戶機(jī)請(qǐng)求路徑 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() # 發(fā)送服務(wù)端文件 break data = os.popen(cmd) # 響應(yīng)客戶端命令 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) # 連接服務(wù)器 def send_client_file(): # 定義客戶端發(fā)送文件函數(shù) data = c.recv( 1024 ) # 接收預(yù)備傳輸提示 print (data) c_filepath = input ( "Please enter the client file path:" ) with open (c_filepath, "rb" ) as f: file = f.read() # 以byte方式讀取文件內(nèi)容 c.sendall( file ) # 將讀取的內(nèi)容發(fā)往服務(wù)端 def get_server_file(): # 定義客戶端接受文件函數(shù) s_filepath = input ( "Please enter the server file path:" ) c.send(bytes(s_filepath,encoding = 'gbk' )) data = c.recv( 20480 ) # 等待接受服務(wù)器數(shù)據(jù) 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" )) # 發(fā)送數(shù)據(jù) if cmd = = "q" : break if cmd = = "transdata" : # 創(chuàng)建發(fā)送客戶端文件命令 send_client_file() break if cmd = = "recvdata" : # 創(chuàng)建接收服務(wù)端文件命令 get_server_file() break data = c.recv( 20480 ) print (data) c.close() if __name__ = = "__main__" : main() |
五、測試結(jié)果(這里拿獲取服務(wù)端shadow文件測試)
在windows下運(yùn)行client.py文件
》》鍵入:recvdata
》》鍵入:/etc/shadow
感興趣的朋友可以一起研究討論學(xué)習(xí)技術(shù)!
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/Aaron_Miller/article/details/80485430