os模塊實現 🍀
osssh_server.py
# 導入socket模塊 import socket # 導入os模塊 import os # 創建套接字對象 sock = socket.socket() # 重置ip和端口 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 綁定ip和端口 sock.bind(('127.0.0.1', 8080)) # 監聽 sock.listen(5) # 鏈接循環 while True: print("Waitting for connection...") # 阻塞 conn, addr = sock.accept() print("{}successful connection...".format(addr)) while True: cmd = conn.recv(1024) # 接收為空說明客戶端斷開了連接 if not cmd: print("Client is disconnected...") break print("The command is {}".format(cmd.decode())) # 利用os模塊進行系統調用,py3中popen參數為str,所以先decode data = os.popen(cmd.decode()).read() # 發送命令執行結果 conn.send(data.encode('utf-8')) # 關閉鏈接 conn.close() # 關閉套接字 sock.close()
osssh_client.py
# 導入socket模塊 import socket # 創建套接字對象 sock = socket.socket() # 連接服務端 sock.connect(('127.0.0.1', 8080)) while True: cmd = input("Please input the command:").strip() if not cmd: print("Can't empty...") continue elif cmd == 'exit': break # 發送命令 sock.send(cmd.encode('utf-8')) # 接收命令執行結果 data = sock.recv(1024) print(data.decode('utf-8')) # 關閉套接字 sock.close()
subprocess模塊實現 🍀
subprocess_server.py
import socket import subprocess sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('127.0.0.1', 8080)) sock.listen(5) while True: print("Waitting for connection...") conn, addr = sock.accept() print("{}successful connection...".format(addr)) while True: cmd = conn.recv(1024) if not cmd: print("Client is disconnected...") break print("The command is {}".format(cmd.decode())) # 利用subprocess模塊進行系統調用 data = subprocess.Popen(cmd.decode(),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) stdout = data.stdout.read() stderr = data.stderr.read() # 打包執行結果 res = stdout + stderr # 發送執行結果 conn.send(res) conn.close() sock.close()
subprocess_client.py
import socket sock = socket.socket() sock.connect(('127.0.0.1', 8080)) while True: cmd = input("Please input the command:").strip() if not cmd: print("Can't empty...") continue elif cmd == 'exit': break sock.send(cmd.encode('utf-8')) data = sock.recv(1024) # Windows終端默認編碼是gbk,所以得用gbk進行解碼 print(data.decode('gbk')) sock.close()
以上兩種方法實現了簡單的ssh , 即遠程執行命令 , 但是這兩個都一個問題 , 當我們執行多次命令后 , 結果就不是我們想要得到了 , 它會發生粘包 , 即有可能上條命令的結果粘到這條命令的結果了 , 如何解決粘包問題 ? 下一篇整理
