今天,在python核心編程上看到了網路編程這章內容,試著用socket模組寫了一個c/s的小程式,此程式可以實現通過在linux用戶端執行遠端伺服器上的命令,比如A/B兩台linux主機,A是server端,B是client端,分別在A上執行server.pysocket server),B上執行client.pysocket client),這樣在client B上就可以通過socket發送linux命令至server A,在A上執行命令後,再把執行結果通過socket返回給B,以下是代碼:
server.py:
#coding:utf-8import osimport socketimport subprocessHOST = '192.168.1.10' PORT = 50008 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT))s.listen(5)while True: conn, addr = s.accept() print 'Connected by', addr while True: command = conn.recv(1024) if not command: break if command == 'quit': break #data = os.popen(command).read() result = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) data = result.stdout.read() conn.sendall(data) conn.close()s.close()
client.py:
#coding:utf-8import socketHOST = '192.168.1.10' PORT = 50008 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))while True: command = raw_input('Input your linux command: ') if command == 'quit': break if not command: break s.send(command) data = s.recv(10240)#.decode('utf-8') if not data: break print datas.close()
如有疑問,請及時聯絡我
本文出自 “Halcyon” 部落格,請務必保留此出處http://halcyonsky.blog.51cto.com/604918/1290641