使用户能够使用 Python 从另一台设备(智能手机/PC)运行批处理文件。

この記事は約6分で読めます。
スポンサーリンク

我想做的事情

这将允许您使用 Python 从另一台设备(智能手机/PC)运行批处理文件(bat)。

背景

我想用智能手机在 Windows 系统上运行一个批处理文件,但使用远程桌面似乎有点麻烦,而且我查了一下,发现它的口碑不太好。所以,我在 Windows 系统上搭建了一个 Web 服务器,然后通过手机上的网页访问它来执行批处理文件。

概述

准备批处理文件。

请用 Python 编写代码。(覆盖 Python 服务器)

使用 Python 启动 Web 服务器

从其他设备访问 Web 服务器

此方法不能使用HTTPS。

请采取安全预防措施,例如限制对局域网的访问。

スポンサーリンク

准备

安装 Python

如果尚未安装 Python,请从以下页面下载并安装。

Welcome to Python.org
The official home of the Python Programming Language

创建批处理文件

创建一个包含要执行的进程的批处理文件。这里,我们将文件命名为`process.bat`。

服务器处理实现(Python)

创建 OriginalServer.py 文件,并添加以下内容。

import http.server
import socketserver
import subprocess
import os

BAT_FILE_PATH = "process.bat"

PORT = 8000
HANDLER_CLASS = http.server.SimpleHTTPRequestHandler

class CustomHandler(HANDLER_CLASS):
    def do_GET(self):
        if self.path == '/run_bat':
            self.run_batch_file()
        else:
            super().do_GET()

    def run_batch_file(self):
        try:
            result = subprocess.run(
                [BAT_FILE_PATH],
                shell=True,
                capture_output=True,
                text=True,
                check=True
            )

            self.send_response(200)
            self.send_header("Content-type", "text/html; charset=utf-8")
            self.end_headers()

            html_content = f"""
            <html>
            <head><title>BAT Execution Result</title></head>
            <body>
            <h1>RESULT for '{BAT_FILE_PATH}'</h1>
            <h2>STD OUT:</h2>
            <pre>{result.stdout}</pre>
            <h2>STD ERR:</h2>
            <pre>{result.stderr}</pre>
            <p><a href="/">Return to root</a></p>
            </body>
            </html>
            """
            self.wfile.write(html_content.encode('utf-8'))

        except subprocess.CalledProcessError as e:
            print(f"Error while bat process: {e}")
            self.send_error(
                500,
                "Internal Server Error",
                f"Error while bat process: {e.stderr or e.stdout}"
            )
        except Exception as e:
            print(f"Unexpected error: {e}")
            self.send_error(
                500,
                "Internal Server Error",
                f"Erroe in Server: {str(e)}"
            )

def run_server():
    with socketserver.TCPServer(("", PORT), CustomHandler) as httpd:
        print(f"Starting server with port {PORT} ...")
        print(f"URL to execute bat: http://localhost:{PORT}/run_bat")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nThe server is stopping")
            httpd.shutdown()

if __name__ == "__main__":
    if not os.path.exists(BAT_FILE_PATH):
        print(f"Error: file '{BAT_FILE_PATH}' does not exist.")
        exit(1)
    
    run_server()

如果您正在执行的批处理文件不是 process.bat,请更正 FILE_PATH。

代码说明

当使用 GET 方法访问 `/run_bat` 目录时,`do_GET(self):` 语句会执行 `run_batch_file` 函数。当访问其他目录时,则会执行正常的处理(在服务器上返回文件)。

`run_batch_file(self)` 方法执行批处理文件,如果成功,则以 HTML 格式返回执行结果。

修改后的服务器使用 `run_server()` 函数启动。(该函数在文件末尾调用。)

スポンサーリンク

执行

服务器端

将创建的批处理文件(Process.bat)和OriginalServer.py放在同一文件夹中。

使用命令提示符或类似工具导航到包含 bat 和 py 文件的文件夹,然后执行以下命令。

python OriginalServer.py

客户端(其他电脑/智能手机等)

服务器启动完成后,打开浏览器并访问 http://[ServerのIP]访问:8000/run_bat。

通过以上步骤,我们能够从客户端在 Windows 上启动批处理文件。

服务器启动后,客户端可以反复执行该程序,直到服务器关闭为止。

コメント

タイトルとURLをコピーしました