python用socket實現用戶端在linux伺服器上執行命令

來源:互聯網
上載者:User

 今天,在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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.