一、學(xué)習(xí)目標(biāo)
【通過Windows下遠(yuǎn)程控制Linux系統(tǒng)實(shí)現(xiàn)對socket模塊認(rèn)識】
二、實(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):
#!/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) # 打開監(jiān)聽conn,addr = s.accept() # 同意建立連接print(addr) # 輸出客戶端IPdef 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ī)請求路徑 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):
import socketHOST = "192.168.43.226"PORT = 5000c = 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
新聞熱點(diǎn)
疑難解答