Python uses socket to execute commands on the client on a linux Server

Source: Internet
Author: User

Today, I saw the network programming chapter in python core programming. I tried to use the socket module to write a c/s applet, this program can execute commands on the remote server on the linux client. For example, A and B are two linux Hosts, A is A server, and B is A client, run server. pysocket server), execute client on B. pysocket client), so that the linux Command can be sent to server A through socket on client B, after the command is executed on A, the execution result is returned to B through socket, the following code is used:

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()

If you have any questions, please contact me in time

This article is from the "Halcyon" blog, please be sure to keep this source http://halcyonsky.blog.51cto.com/604918/1290641

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.