服务器获取外网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)
相关推荐
小辰记事本8 小时前
从零读懂RoCEv2数据包构造:从WQE到线缆上的完整旅程
服务器·网络·网络协议·rdma
江公望11 小时前
Ubuntu htop命令,10分钟讲清楚
linux·服务器
哎呦,帅小伙哦11 小时前
Linux 时间:从原子钟到 clock_gettime 的每一面
linux·运维·服务器
张小姐的猫12 小时前
【Linux】多线程 —— 线程互斥
linux·运维·服务器·c++
YuanDaima204812 小时前
Linux 进阶运维与 AI 环境实战:进程管理、网络排错与 GPU 监控
linux·运维·服务器·网络·人工智能
lolo大魔王14 小时前
Linux 数据文件处理实战:排序、搜索、压缩、归档一站式详解
linux·运维·服务器
1892280486114 小时前
NY382固态MT29F32T08GSLBHL8-24QM:B
大数据·服务器·人工智能·科技·缓存
xhbh66614 小时前
网关端口映射和路由器端口转发有什么区别?配置要点全解析
运维·服务器·网络·智能路由器·端口映射·映射·无痕网关
STDD14 小时前
Soulmask《灵魂面具》 专用服务器搭建教程
运维·服务器·github
半壶清水15 小时前
用P4 Tutorial、BMv2 和 Mininet‌解析网络第一集------模拟环境搭建
运维·服务器·网络·网络协议·tcp/ip