Network programming-socket simulates ssh remote login execution command

Replenish:

Windows:

dir: View subfolder names and subfile names in a directory

ipconfig: View the ip information of the local network card

tasklist: View running processes

Linux:

ls: View subfolder names and subfile names in a directory

ifconfig: View the ip information of the local network card

ps aux: view running processes

Execute the system command and get the result:

os.system(): Execute the result and return the flag of whether the command was executed successfully, 0 means success, non-0 means execution failure

subprocess.Popen(cmd, shell=True): execute the result and return the result

import subprocess
obj=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
obj.stdout.read()
obj.stderr.read()

  server side

import socket,os
import subprocess
phone = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
phone.bind(('127.0.0.1',8080))
phone.listen(5)
while True:
    conn,client_addr = phone.accept()
     print (client_addr)
     while True:
         try :
             # 1. Receive the command 
            cmd=conn.recv(1024 )
             if  not cmd: break 
            # 2. Execute the command and get the result 
            obj=subprocess.Popen (cmd.decode( ' gbk ' ),shell=True,stdout=subprocess.PIPE,stderr= subprocess.PIPE)
            stdout=obj.stdout.read()
            stderr = obj.stderr.read()
             # 3. Send command result conn.send 
            (stdout+stderr) # "+" sign needs to be optimized 
        except ConnectionResetError:
             break 
    conn.close() #Connection close 
phone.close() #Socket word close

  client side

import socket
client = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))

while True:
     # 1. Send the command 
    cmd=input( ' >> ' ).strip()
     if  not cmd: continue 
    client.send(cmd.encode( ' gbk ' ))
     # 2. Get the result and print 
    data=client .recv(1024).decode( ' gbk ' ) # 1024 is the pit 
    print (data)
client.close()

 Client order execution

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324859700&siteId=291194637