1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 """ 4 @file: device_http_server.py 5 @time: 2022/12/2 13:11 6 @file_desc: 7 """ 8 import os 9 from http.server import BaseHTTPRequestHandler, HTTPServer 10 11 import pyautogui 12 import socket 13 14 PORT = 9999 15 IP = socket.gethostbyname(socket.gethostname()) 16 print(IP) 17 18 19 class ScreenHandler(BaseHTTPRequestHandler): 20 def do_GET(self): 21 cmd = self.path.strip("/") 22 if "." not in cmd and "screenshot" != cmd.lower(): 23 try: 24 print(cmd) 25 if "%20" in cmd: 26 cmd = cmd.replace("%20", " ") 27 cmd_exe = os.popen(cmd) 28 output = cmd_exe.read() 29 self.send_response(200) # HTTP Status Code 30 self.send_header('Content-Type', 'text/plain') 31 self.end_headers() 32 self.wfile.write(output.encode("utf-8")) 33 except Exception as error: 34 pass 35 elif "screenshot" == cmd.lower(): 36 img = pyautogui.screenshot() # Screenshot 37 if img: 38 self.send_response(200) # HTTP Status Code 39 self.send_header('Content-Type', 'image/png') 40 self.end_headers() 41 img.save(self.wfile, 'PNG') # HTTP Response Stream 42 43 44 def main(): 45 try: 46 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 47 # check port is open 48 result = sock.connect_ex((IP, PORT)) 49 portopen = result == 0 50 sock.close() 51 if not portopen: 52 # start web server use defined handler 53 server = HTTPServer((IP, PORT), ScreenHandler) 54 server.serve_forever() # listen 55 except: 56 pass 57 58 59 if __name__ == '__main__': 60 main()View Code
实现远程在Windows机器上执行命令和截图。
1. 使用socket和http.server搭建一个简单的web server.
2. pyautogui实现截图功能
3. 通过获取浏览器的path, 截取要执行的命令(注意空格的替换%20), 通过os.popen执行命令,并将结果写回web页面。
目前将python代码打包成exe放在开机启动项执行(不可以打包成服务在后台运行,否则截图功能没法使用)
具体代码如上。
标签:截图,HTTP,socket,Windows,self,cmd,Server,server From: https://www.cnblogs.com/daly/p/16944960.html