服务器获取外网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)
相关推荐
翼龙云_cloud14 小时前
阿里云渠道商:如何三步提升阿里云轻量服务器单机性能?
运维·服务器·阿里云·云计算
失眠的树亚14 小时前
vscode连接阿里云ECS服务器
服务器·vscode·阿里云
gaize121314 小时前
关于服务器的入门知识
服务器
库库林_沙琪马14 小时前
3、Sentinel
服务器·网络·sentinel
默|笙15 小时前
【Linux】进程(4)进程优先级、切换和调度
linux·运维·服务器
gaize121315 小时前
如何撰写有效的服务器申请用途以提高审核通过率
服务器·云计算
郑州光合科技余经理15 小时前
定制开发实战:海外版外卖系统PHP全栈解决方案
java·服务器·开发语言·javascript·git·uni-app·php
郝学胜-神的一滴15 小时前
Linux线程编程:从原理到实践
linux·服务器·开发语言·c++·程序人生·设计模式·软件工程
✿ ༺ ོIT技术༻15 小时前
服务端高并发分布式结构演进之路
运维·服务器·redis·分布式·架构
..空空的人15 小时前
C++基于protobuf实现仿RabbitMQ消息队列---技术认识2
服务器·数据库·c++·网络协议·gtest·异步·protobuf