在Ubuntu 18.04上使用uwsgi和nginx远程执行wakeonlan

应用场景:局域网内有一台常开的低功耗server (例如raspberry pi),同时还有其他几台需要远程唤醒的机器。可以在server上部署一个web服务来执行wakeonlan。这在路由器不支持wakeonlan packet forwarding的时候很有用。

1. 实现简单的uwsgi脚本:

sudo apt install wakeonlan
vim /var/www/wol/wol.py
#!/usr/bin/env python
from cgi import parse_qs
from subprocess import call

def application(env, start_response):
  d = parse_qs(env['QUERY_STRING'])
  mac = d.get('mac', [''])[0]
  # Replace 192.168.12.255 with your LAN broadcast address
  call(["/usr/bin/wakeonlan", "-i", "192.168.12.255",  mac])
  start_response('200 OK', [('Content-Type','text/html')])
  return ["<TITLE>Wake on Lan</TITLE><p>WOL sent to %s</p>"%(mac)]

2. 安装并配置uwsgi为开机启动。

pip install uwsgi
vim /etc/init.d/uwsgi
#!/bin/bash

### BEGIN INIT INFO
# Provides:        uwsgi
# Required-Start:  $network
# Required-Stop:   $network
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start/Stop uwsgi server
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/local/bin

start() {
  uwsgi --wsgi-file /var/www/wol/wol.py \
    --socket=/tmp/wol.sock \
    --pidfile=/tmp/wol.pid \
    --daemonize=/dev/shm/wol.log
}

stop() {
  uwsgi --stop /tmp/wol.pid
}

case $1 in
  start|stop) $1;;
  restart) stop; start;;
  *) echo "Run as $0 <start|stop|restart>"; exit 1;;
esac
chmod 755 /etc/init.d/uwsgi
/etc/init.d/uwsgi restart
update-rc.d uwsgi defaults
update-rc.d uwsgi enable

3. 将uwsgi接入nginx,注意将your.website.com替换成自己的域名或IP。

vim /etc/nginx/sites-enabled/default
server {
        listen 80;
        listen [::]:80;
        server_name your.website.com;
        charset utf-8;
        root /var/www/html;
        location /wol {
            uwsgi_pass  unix:///tmp/wol.sock;
            include     /etc/nginx/uwsgi_params;
            uwsgi_param SCRIPT_NAME /wol;
            uwsgi_modifier1 30;
        }
}
/etc/init.d/nginx restart

4. 访问http://your.website.com/wol?mac=XX:XX:XX:XX:XX:XX 即可远程开机。

One Reply to “在Ubuntu 18.04上使用uwsgi和nginx远程执行wakeonlan”

Leave a Reply

Your email address will not be published. Required fields are marked *