服务器获取外网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)
相关推荐
bqq198610263 小时前
Ubuntu vs CentOS
linux·服务器
雨声不在3 小时前
linux Copy Fail
linux·服务器
Gary Studio3 小时前
Selinux编写
linux·服务器·前端
Danileaf_Guo4 小时前
手搓KVM虚拟化!Ubuntu 26.04 + KVM 7.0.0,告别VMware的低成本玩法
linux·运维·服务器·ubuntu
中海德--陈顺真4 小时前
HONEYWELL 扫描架控制板 51000398
运维·服务器·人工智能
lbb 小魔仙4 小时前
2026远程办公软件夏季深度横测:ToDesk、向日葵、网易UU远程全面对比,远控白皮书
android·服务器·网络协议·tcp/ip·postgresql
嵌入式×边缘AI:打怪升级日志4 小时前
全志T113 Tina-Linux开发环境搭建:从安装依赖到打包烧录完整教程
linux·运维·服务器
yugi9878384 小时前
Linux下58mm热敏打印机驱动安装与配置指南
linux·运维·服务器
遇见火星4 小时前
centos7和centos8设置本地镜像为yum安装源的方法
linux·运维·服务器
piaopiaolanghua4 小时前
[Ai问答] Docker是否支持跨架构镜像,譬如ARM/X86
linux·运维·服务器