Pythonで別デバイス(スマホ/PC)からbatを実行できるようにする

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

やりたいこと

Pythonで別デバイス(スマホ/PC)からbatを実行できるようにします。

背景

スマホからWindows上にbatをたたきたかったのですが、リモートデスクトップだとちょっと仰々しいのと調べると、評判よくなかったりするのでWindows上にWebサーバを立ててスマホからWebアクセスるすることでBatを実行するようにしました。

概要

batの準備。

Pythonでコードを書く。(Pythonのサーバをオーバーライド)

PythonでWebサーバ起動

他デバイスからWebサーバにアクセス

今回の方法はhttpsは使用できません。

LANに限定するなどセキュリティに留意してください。

スポンサーリンク

準備

Pythonのインストール

Pythonがインストールされていない場合、Pythonを以下のページからダウンロードしインストールします。

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

batの作成

実行したい処理をbatにします。ここではファイル名をprocess.batとしました。

サーバー処理の実装(Pyhton)

以下の内容で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()

実行するbatファイルがprocess.batではない場合は、FILE_PATHを修正します。

コードの説明

do_GET(self):で’/run_bat’にGetメソッドでアクセスされたときにrun_batch_fileを実行します。/run_bat以外にアクセスされたときは通常の処理(サーバ上のファイルを返す)を行います。

run_batch_file(self)でbatを実行し成功した場合は実行結果をHTMLで返します。

run_server()で修正したサーバを起動します。(ファイルの最後に呼んでいます。)

スポンサーリンク

実行

サーバ側

作成したbat(Process.bat)とOriginalServer.pyを同じフォルダに置きます。

コマンドプロンプトなどでbatとpyファイルを置いたフォルダに移動して以下のコマンドを実行します。

python OriginalServer.py

クライアント側(他PC/スマホなど)

サーバ側の起動が完了したらブラウザを起動して http://[ServerのIP]:8000/run_bat にアクセスします。

以上でクライアントからWindows上のbatを起動することができました。

一度サーバを起動すればサーバを終了するまでクライアントから繰り返し実行することができます。

コメント

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