一:脚本详情
# 脚本作用:把本地出口ip发生变化时,发钉钉告警。另外此脚本可打包成exe程序在windown系统下执行,且win系统不需要安装python环境
# 打包exe命令: 先安装包:pip3 install pyinstaller ,再打包:pyinstaller -F -w ./脚本名称.py ,进入dist目录执行exe,拷贝至其他服务器也可执行,无论是否安装python。
二:脚本详情
# -*- coding: utf-8 -*-
import re
import os
from urllib import request
'''
# 获取当前公网ip
def GetCompanyPublicIp() :
req = request.Request('https://myip.ipip.net/')
req.add_header('User-Agent', 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
f = request.urlopen(req)
ip_str = f.read().decode('utf-8')
ip = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", ip_str)
return ip[0]
# 从本地缓存文件中获取历史公网ip
def GetCompanyOldIp():
try:
f = open('ip.txt', 'r')
oldIP = f.read().strip()
return oldIP
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
f.close()
# 写入新的ip到本地
def IputCompanyNewIp(ip):
try:
f = open('ip.txt', 'w')
f.write(ip)
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("写入NewIp成功")
f.close()
#发送钉钉
def SendDing(msg):
import requests
import json
dingding_url = 'https://oapi.dingtalk.com/robot/send?access_token=xxx'
data = {"msgtype": "text","text": {"content": "请注意:"+str(msg)}}
headers = {'Content-Type':'application/json;charset=UTF-8'}
send_data = json.dumps(data).encode('utf-8')
ret = requests.post(url=dingding_url,data=send_data,headers=headers)
print(ret.text)
if __name__ == '__main__':
ip_file = os.path.exists('ip.txt')
if ip_file == True:
print('本地ip.txt文件存在,继续...')
else:
print('本地ip.txt文件不存在,模拟写入一个...')
IputCompanyNewIp('1.1.1.1')
NewIp = GetCompanyPublicIp()
OldIp = GetCompanyOldIp()
if NewIp == OldIp:
print('公司出口ip没有发生变化,脚本退出。')
else:
print('公司出口ip发生变化:', NewIp)
IputCompanyNewIp(NewIp)
# SendDing("本地ip发生变化")
SendDing("本地ip发生变化;旧的:%s 新的:%s" %(OldIp,NewIp))
# AddToNg(NewIp)
#连接至ng服务器
#sc = SSHConnection(host="139.15.119.193", port=22, user="root", pwd="R123")
#sc.cmd("/bin/bash /tmp/p.sh 192.168.1.1")
#sc.cmd("/bin/bash /opt/yunwei/add_denyip_to_ng.sh %s" %NewIp)
print("Client IP: %s was successfully send to dingdingGroup." % NewIp)
三:效果
完!