python用socket实现客户端在linux服务器上执行命令

 今天,在python核心编程上看到了网络编程这章内容,试着用socket模块写了一个c/s的小程序,此程序可以实现通过在linux客户端执行远端服务器上的命令,比如A/B两台linux主机,A是server端,B是client端,分别在A上执行server.py(socket server),B上执行client.py(socket client),这样在client B上就可以通过socket发送linux命令至server A,在A上执行命令后,再把执行结果通过socket返回给B,以下是代码:

  server.py:

           
#coding:utf-8
import os
import socket
import subprocess
HOST = '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-8
import socket
HOST = '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 data
s.close()

 如有疑问,请及时联系我

你可能感兴趣的:(linux,python,socket,服务器,网络编程)