服务器获取外网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)
相关推荐
jun_bai1 小时前
Orthanc服务器使用java上传dicom影像文件
java·运维·服务器
RisunJan2 小时前
Linux命令-semanage(SELinux 策略管理)
linux·运维·服务器
流浪0012 小时前
Linux系统篇 21:文件(五)——动静态库、ELF 底层原理全解
linux·运维·服务器
snow@li2 小时前
Spring Boot:项目服务器完整部署教程(零基础可直接实操)
服务器·spring boot·后端
Dawn-bit2 小时前
Linux救援模式和系统恢复
linux·运维·服务器·云计算·运维开发
李昊哲小课2 小时前
咖啡工坊 · FastAPI 22 章教程合集
服务器·人工智能·python·fastapi
十八岁牛爷爷2 小时前
Linux 进程与进程状态・三层级深度解析
linux·运维·服务器
不会就选b3 小时前
linux之进程管理(二)--替换
linux·运维·服务器
倔强的石头1063 小时前
【Linux指南】动静态库系列(二):从源码复用到目标文件复用:为什么需要把 .o 打包成库
linux·运维·服务器
码农学院3 小时前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python