Nginx随机端口

随机更改Nginx端口并发送Telegram通知

编写代码randomport.py

运行环境为:python3

#!/usr/bin
# -*- coding: UTF-8 -*-
import random
import subprocess
from telegram import Bot

# 定义Nginx配置文件路径
config_file = "/etc/nginx/conf/nginx.conf"

# 定义Telegram机器人API token和Chat ID
api_token = "your_api_token"
chat_id = "your_chat_id"

# 定义获取空闲端口的函数
def get_free_port():
    while True:
        port = random.randint(1024, 65535)
        status = subprocess.call(["nc", "-z", "localhost", str(port)])
        if status == 1:
            return port

# 获取随机端口号
new_port = get_free_port()

# 修改Nginx配置文件
subprocess.call(["sed", "-i", "s/listen [0-9]\+/listen {}/g".format(new_port), config_file])
subprocess.call(["systemctl", "reload", "nginx"])

# 发送Telegram通知
bot = Bot(api_token)
bot.send_message(chat_id=chat_id, text="Nginx端口已更换为{}。".format(new_port))

添加定时任务

crontab -e

0 7 * * * python3 /etc/randomport.py