Analog ssh remote command execution

Server:

import socket
import subprocess
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #可以重复适用系统端口
phone.bind(('192.168.43.14', 8081))
phone.listen(5)
while True:
conn, clent_add = phone.accept()
while True:
try:
#1 接受命令
data = conn.recv(1024)
obj = subprocess.Popen(data.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = obj.stdout.read()
= obj.stderr.read stderr ()
#if Not Data: # BREAK If the client hangs up, this method is suitable for linux operating system
#Print (data.decode ( 'UTF-. 8'))
# 2 Run get results
Finding # 3 pull execute commands sent to the client
conn.send (stdout + stderr) # + "here you can continue to optimize the except ConnectionResetError: # If the client hang up, this method is suitable for windows operating system BREAK conn.Close () Phone .close ()








client:

Socket Import 
Phone = socket.socket (socket.AF_INET , socket.SOCK_STREAM)
phone.connect (( '192.168.43.14' , 8081))
the while True:
MSG = INPUT ( . '>>>') Strip ()
IF Not MSG : Continue # Once the input is empty, while the application layer can receive, but the operating system to the application layer, there is no, you can not send the server
# commanding
phone.send (msg.encode ( 'UTF-. 8'))
Run # and sends the results
Data = phone.recv ( 1024) # 1024 where there is a huge hole Print (data.decode ( 'GBK')) phone.close ()




supplementary content:

import os
res = os.system('dir')
print(res)


# import subprocess
# obj = subprocess.Popen('dffif /', shell= True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
# print('正确管道', obj.stdout.read().decode('GBK'))
# print('错误管道', obj.stderr.read().decode('GBK'))

Guess you like

Origin www.cnblogs.com/yuexijun/p/11408785.html