服务器获取外网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)
相关推荐
望获linux3 小时前
【实时Linux实战系列】硬实时与软实时设计模式
linux·运维·服务器·数据库·操作系统·rtos·嵌入式软件
沉默的八哥6 小时前
Linux中LVM逻辑卷扩容
linux·运维·服务器
YZJenny6 小时前
没有管理员权限,在服务器安装使用 Jupyter + R 内核
服务器·jupyter
wanhengidc7 小时前
服务器机柜与网络机柜各自的优势
服务器·网络·智能路由器
颖川初尘8 小时前
端口到底是个什么鬼?回答我!
服务器·网络·tcp/ip·node.js
stark张宇8 小时前
Linux 文件创建、删除、移动、复制基础知识整理
linux·服务器·centos
将心ONE9 小时前
使用 lstrip() 和 rstrip() 方法
运维·服务器
Two_brushes.11 小时前
【linux网络】深入理解 TCP/UDP:从基础端口号到可靠传输机制全解析
linux·运维·服务器
FJW02081411 小时前
【Linux】系统引导修复
linux·运维·服务器
设计师小聂!11 小时前
linux常用命令(一)
linux·运维·服务器