服务器获取外网IP,并发送到钉钉

服务器获取外网IP,并发送到钉钉

python 复制代码
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

# === 请填入你的钉钉机器人配置 ===
access_token = 'XXXX'
secret = 'XXXX'

# 获取公网 IP
def get_public_ip():
    try:
        response = requests.get("https://api.ipify.org", timeout=5)
        return response.text.strip()
    except Exception as e:
        return f"获取公网 IP 失败: {e}"

# 生成签名
def generate_signature(secret):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = f'{timestamp}\n{secret}'
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign

# 发送消息到钉钉
def send_dingding_message(ip_address):
    timestamp, sign = generate_signature(secret)
    url = f'https://oapi.dingtalk.com/robot/send?access_token={access_token}&timestamp={timestamp}&sign={sign}'
    headers = {'Content-Type': 'application/json'}
    message = {
        "msgtype": "markdown",
        "markdown": {
            "title": "服务器公网 IP 通知",
            "text": f"###  新加坡服务器公网 IP\n\n当前公网 IP 地址为:`{ip_address}`\n\n发送时间:{time.strftime('%Y-%m-%d %H:%M:%S')}"
        }
    }

    response = requests.post(url, headers=headers, json=message)
    if response.status_code == 200 and response.json().get("errcode") == 0:
        print("钉钉消息发送成功 ✅")
    else:
        print(f"发送失败 ❌: {response.text}")

if __name__ == '__main__':
    ip = get_public_ip()
    send_dingding_message(ip)
相关推荐
xw51 小时前
免费的个人网站托管-Cloudflare
服务器·前端
!win !1 小时前
免费的个人网站托管-Cloudflare
服务器·前端·开发工具
conkl2 小时前
嵌入式 Linux 深度解析:架构、原理与工程实践(增强版)
linux·运维·服务器·架构·php·底层·堆栈
AI视觉网奇4 小时前
whisper tokenizer
linux·运维·服务器
m0_738120725 小时前
Solar月赛(应急响应)——攻击者使用什么漏洞获取了服务器的配置文件?
运维·服务器·安全·web安全·网络安全
咕噜签名分发冰淇淋5 小时前
应用app的服务器如何增加高并发
运维·服务器
闻道且行之5 小时前
TTS语音合成|GPT-SoVITS语音合成服务器部署,实现http访问
服务器·gpt·http
forestqq6 小时前
zabbix平台无法删除已停用主机的处理案例
运维·服务器·zabbix
大锦终7 小时前
【Linux】环境变量
linux·运维·服务器
萑澈7 小时前
我在 Arch Linux Plasma 6 Wayland 下驯服 Chromium 输入法的完整记录
linux·运维·服务器