Execute command on server
It seems that there is no module to execute the command before. Now it is added
import subprocess obj = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) #Get an object. The command is in front, shell The script can be executed, stdout Set a process pipeline. There are actually two processes, one is the main process and the other is shell process x = obj.stdout.read() # Here is the execution information print(str(x,'gbk')) # str(x,'utf8')Forget that the system is gbk Encoding
###Example of remote command execution:
#If the execution result of the instruction is short, there will be no problem
cmd_server.py1 import socket 2 import subprocess 3 def get_server_socket(): 4 sk = socket.socket() 5 server_address = ('127.0.0.1',8888) 6 sk.bind(server_address) 7 sk.listen(5) 8 return sk 9 10 def get_conn(sk): 11 print('waitconnect...') 12 conn,addr = sk.accept() 13 return conn 14 15 if __name__ == '__main__': 16 sk = get_server_socket() 17 conn = get_conn(sk) 18 while True: 19 try: 20 data = conn.recv(1024)##Linux will not report an error here. If conn is closed forcibly, data will become empty, that is to say, Linux will not try directly. 21 except Exception as e: 22 conn = get_conn(sk) 23 print(str(data,'utf8')) 24 if not data: 25 conn = get_conn(sk) 26 continue 27 sp = subprocess.Popen(str(data,'utf8'),shell=True,stdout=subprocess.PIPE)#Note if the command is of string type 28 result = sp.stdout.read()#str(sp.stdout.read(),'gbk') 29 conn.send(result) 30 print(str(result,'gbk')) 31 print('waiting...') 32 conn.close()