簡易Webサーバを起動する

環境

$ uname -a
Linux rpi4 6.6.62+rpt-rpi-v8 #1 SMP PREEMPT Debian 1:6.6.62-1+rpt1 (2024-11-25) aarch64 GNU/Linux

導入

Python のビルドインサーバを使うので、Python3 導入... しようとしたら入っていた。

Debian -- bookworm の python3.11-minimal パッケージに関する詳細

$ apt-cache search python3-minimal
python3-minimal - minimal subset of the Python language (default python3 version)

$ sudo apt install -y python3-minimal
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3-minimal is already the newest version (3.11.2-1+b1).
python3-minimal set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

$ python3 -V
Python 3.11.2

ビルドインサーバ起動

http.server を起動。

http.server --- HTTP サーバー — Python 3.13.1 ドキュメント
このモジュールは HTTP サーバを実装するためのクラスを提供しています。

引数 --directory で DocumentRoot を指定して nohup & でバックグラウンド起動。
※デフォルトでポート 8000 を使用(なので、下記のように指定しなくても可)。

$ nohup python -m http.server 8000 --directory /media/*** &

$ tail nohup.out -f
192.168.9.999 - - [18/Jan/2025 09:41:45] "GET / HTTP/1.1" 200 -

$ ps aux | head -n 1; ps aux | grep http.server
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
{username}   66511  0.1  0.4 175580 18432 pts/0    S    09:41   0:00 python -m http.server 8000 --directory /media/***
{username}   66722  0.0  0.0   6264  1920 pts/0    S+   09:44   0:00 grep --color=auto http.server

STAT S なので、待ち(割り込み可能)状態にあることが分かります。
アクセスすると、ちゃんと表示された。

  • STATE 列の見方メモ

    $ man ps
    PROCESS STATE CODES
           Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display to describe the state of a process:
    
                   D    uninterruptible sleep (usually IO)
                   I    Idle kernel thread
                   R    running or runnable (on run queue)
                   S    interruptible sleep (waiting for an event to complete)
                   T    stopped by job control signal
                   t    stopped by debugger during the tracing
                   W    paging (not valid since the 2.6.xx kernel)
                   X    dead (should never be seen)
                   Z    defunct ("zombie") process, terminated but not reaped by its parent
    
           For BSD formats and when the stat keyword is used, additional characters may be displayed:
    
                   <    high-priority (not nice to other users)
                   N    low-priority (nice to other users)
                   L    has pages locked into memory (for real-time and custom IO)
                   s    is a session leader
                   l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
                   +    is in the foreground process group

自動起動

/etc/rc.local はデフォルトだと無効化されているので)cron でリブート時に自動起動するように設定。

$ crontab -e
@reboot python -m http.server 8000 --directory /media/*** --cgi > /media/***/cgi-bin/httpserver.log 2>&1

2>&1 を使って、標準出力と標準エラー出力をまとめて log へ書き込み。