安装pip和依赖
apt install python3-pip
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple flask requests
在root目录下创建文件 DY.py
from flask import Flask, request, jsonify
import requests
import time
import os
import json
import socket
import re
import threading
import subprocess
from concurrent.futures import ThreadPoolExecutor
app = Flask(__name__)
# 获取已连接WiFi的信息
def get_connected_wifi_info():
cmd = "iwgetid"
output = subprocess.check_output(cmd, shell=True, text=True)
# 解析输出结果
ssid = output.strip().split('"')[1]
return ssid
# 获取本地局域网IP地址
def get_local_ip():
# 创建UDP连接
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# 连接一个公共的IP地址和端口
sock.connect(("8.8.8.8", 80))
# 获取本地IP地址
local_ip = sock.getsockname()[0]
return local_ip
finally:
# 关闭连接
sock.close()
local_ip = get_local_ip()
# 推送开机信息
def push_information():
push_url = "http://**.***.205.189:12346/VdZAJR*****du7EfKwaSGG" #自己设置推送地址
push_title = "戴尔已成功开机"
wifi_ssid = get_connected_wifi_info()
push_text = f"{wifi_ssid}局域网内IP为{local_ip}"
final_url = f"{push_url}/{push_title}/{push_text}"
response = requests.get(final_url)
print("如果显示200则成功推送")
print(response.status_code)
push_information()
lock = threading.Lock()
# 处理关机请求
@app.route('/shutdown/1', methods=['POST'])
def shutdown_zero3():
subprocess.Popen(["sudo","poweroff"])
text = "戴尔小主机已收到关机请求,正在执行"
return jsonify({'message': text})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
可以使用 systemd 来管理进程并设置开机启动。以下是具体步骤:
创建一个名为 video_download.service 的服务文件,路径为 /etc/systemd/system/,内容如下:
[Unit]
Description=Your Service Description
After=network.target
[Service]
User=root
ExecStartPre=/bin/sleep 60
ExecStart=/usr/bin/python3 /root/DY.py
Restart=on-failure
[Install]
WantedBy=default.target
重新加载 systemd 配置
sudo systemctl daemon-reload
之后,可以使用以下命令来启动、停止和禁用服务:
sudo systemctl start CentralControl.service # 启动服务
sudo systemctl stop CentralControl.service # 停止服务
sudo systemctl enable CentralControl.service # 开机自启
sudo systemctl disable CentralControl.service # 禁止开机自启
sudo journalctl -u CentralControl.service # 查看日志
sudo journalctl -u CentralControl.service -n 20 # 查看最新20条日志