Things I want to do
This will allow you to run a batch file (bat) from another device (smartphone/PC) using Python.
background
I wanted to run a batch file from my smartphone onto Windows, but using remote desktop seemed a bit cumbersome, and my research indicated it had a poor reputation. So, I set up a web server on Windows and accessed it from my smartphone via the web to execute the batch file.
overview
Prepare the batch file.
Write the code in Python. (Override the Python server)
Starting a web server with Python
Accessing the web server from other devices
HTTPS cannot be used with this method.
Please take security precautions, such as limiting access to the LAN.
Prepare
Installing Python
If Python is not installed, download and install it from the following page.

Creating a batch file
Create a batch file containing the process you want to execute. Here, we’ve named the file `process.bat`.
Server processing implementation (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 batch file you are executing is not process.bat, correct the FILE_PATH.
Code explanation
The `do_GET(self):` statement executes `run_batch_file` when ` /run_bat` is accessed using the GET method. When any other directory is accessed, normal processing (returning a file on the server) is performed.
The `run_batch_file(self)` method executes a batch file, and if successful, returns the execution result in HTML.
The modified server is started using `run_server()`. (This is called at the end of the file.)
execution
Server side
Place the created batch file (Process.bat) and OriginalServer.py in the same folder.
Navigate to the folder containing the bat and py files using a command prompt or similar tool, and execute the following command.
python OriginalServer.pyClient side (other PC/smartphone, etc.)
Once the server has finished starting up, launch your browser and go to http://[ServerのIP]Access :8000/run_bat.
With the above steps, we were able to launch a batch file on Windows from the client.
Once the server is started, it can be repeatedly executed by clients until the server is shut down.


コメント