How to execute a bat file from a different device (smartphone/PC) using Python

This article can be read in about 8 minutes.
PR

The purpose

In Python, I want to be able to execute a batch file (.bat) from a different device (smartphone/PC).

Background

I needed a way to trigger a Windows batch file (.bat) from my phone. I ruled out Remote Desktop as it was too heavy/verbose and received poor reviews. Instead, I opted to host a web server on the Windows machine and execute the batch file via a mobile web request.

Overview

Prepare the batch file.

Write code in Python (to override the Python server).

Start the Python Web server.

Access the Web server from another device.

This method cannot use HTTPS. Please be mindful of security, such as limiting use to a LAN.

PR

Preparation

Install Python

If Python is not installed, please download and install it from the page below.

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

Make bat

Create a batch file for the process I want to execute. I’ve named the file process.bat.

Implementing server processing (Python)

Create OriginalServer.py with the following content.

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()

If the .bat file you are executing is not process.bat, modify FILE_PATH.

Code explanation

do_GET(self): executes run_batch_file when a GET request is made to ‘/run_bat’. For any access other than ‘/run_bat’, it performs the standard process (returning files from the server).

The run_batch_file(self) method executes the batch file (.bat) and, if successful, returns the execution result in HTML.

run_server() starts the modified server (this is called at the end of the file).

PR

Execution

Server side

Place the created .bat file ($\text{Process.bat}$) and $\text{OriginalServer.py}$ in the same folder.

Navigate to the folder containing the $\text{.bat}$ and $\text{.py}$ files using the Command Prompt or similar, and execute the following command.

python OriginalServer.py

Client side (other PC/ smart phone etc.)

Once the server-side startup is complete, launch your browser and access http://[Server IP]:8000/run_bat.

This concludes the process for executing a Windows batch file from the client.

Once the server is started, it can be repeatedly executed from the client until the server is shut down.

comment

Copied title and URL