自动检测 自动更新 设置crontab 定时每10分钟执行一下sh if-public-net.sh 检测脚本即可
[11:16:17root@Test /opt/hxkj]#cat if-public-net.sh
#!/bin/bash
old_ip=$(cat old.log)
new_ip=$(curl -s https://ipw.cn/api/ip/myip)
echo oldip:$old_ip
echo newip:$new_ip
if [ "$old_ip" != "$new_ip" ];then
python3 /opt/hxkj/aliyun-update-ip-test.py
python3 /opt/hxkj/aliyun-update-ip-prod.py
curl -s https://ipw.cn/api/ip/myip > old.log
else
exit 0
fi
[11:17:22root@Test /opt/hxkj]#cat aliyun-update-ip-test.py
#!/usr/local/bin/python3
#coding=utf-8
import re
from urllib import request
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.RevokeSecurityGroupRequest import RevokeSecurityGroupRequest
from aliyunsdkecs.request.v20140526.AuthorizeSecurityGroupRequest import AuthorizeSecurityGroupRequest
# 获取当前公网ip
def GetCompanyPublicIp():
req = request.Request('https://ipw.cn/api/ip/myip')
# req.add_header('User-Agent', 'curl/7.53.1') ## 用curl方式请求,会少很多html页面。
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()
# 此处分别填写创建的RAM子账号的AccessKeyId,子账号的AccessKeySecret,以及要管理的大区
client = AcsClient('111111', '111111', 'cn-111111')
def DelGroup(SourceCidrIp):
request = RevokeSecurityGroupRequest()
request.set_accept_format('json')
request.set_SecurityGroupId("sg-111111")
request.set_PortRange("1/65535")
request.set_IpProtocol("tcp")
request.set_SourceCidrIp(SourceCidrIp)
response = client.do_action_with_exception(request)
request.set_Description("公司出网端口")
print(str(response, encoding='utf-8'))
# 添加规则
def AddGroup(SourceCidrIp):
request = AuthorizeSecurityGroupRequest()
request.set_accept_format('json')
request.set_SecurityGroupId("sg-111111") # 安全组ID
request.set_IpProtocol("tcp")
request.set_PortRange("1/65535")
request.set_Description("公司出网端口")
request.set_SourceCidrIp(SourceCidrIp)
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
# AddGroup(ip)
if __name__ == '__main__':
NewIp = GetCompanyPublicIp()
OldIp = GetCompanyOldIp()
if NewIp == OldIp:
print('公司出口ip没有发生变化')
else:
print('公司出口ip发生变化:', NewIp)
IputCompanyNewIp(NewIp)
DelGroup(OldIp)
AddGroup(NewIp)
# 本文使用的Python版本为Python 3.7
pip install aliyun-python-sdk-core-v3
pip install aliyun-python-sdk-ecs
# 脚本如下:
#!/usr/bin/python3
#coding=utf-8
'''
当办公室的公网ip改变时,调用阿里云的API放行当前的公网IP和指定的端口
'''
import json
import re
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
def get_ip(url):
"""
定义http head伪装成curl浏览器获取IP数据
"""
headers = { 'User-Agent': "curl/10.0","Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
r = requests.get(url,headers=headers)
text = re.search(r'(\d+\.\d+\.\d+\.\d+)',r.text).group(1)
return (text)
def get_old_ip(log_file):
"""
获取文件中的IP地址
"""
try:
open_files = open(log_file, "r")
old_ip = open_files.read()
open_files.close()
return (old_ip)
except:
return 0
def change_ip(log_file):
try:
open_files = open(log_file, "w+")
open_files.write(new_ip)
open_files.close()
except:
pass
def Get_sourceIP(RegionId,SecurityGroupId,Port):
'''
获取已存在的安全组的IP
'''
request.set_action_name('DescribeSecurityGroupAttribute')
request.add_query_param('RegionId', RegionId)
request.add_query_param('SecurityGroupId', SecurityGroupId)
request.add_query_param('NicType', 'intranet')
request.add_query_param('Direction', 'all')
response = client.do_action_with_exception(request) #调用阿里云api返回安全组所有规则
text = (re.match(r'^b\'(.*?)\'$' ,str(response)).group(1)) #将获取到的bytes数据转换成str并用正则去掉b前缀
text = json.loads(text) #将数据用json解码
#len_text = len(text)
for i in range(0,len(text)): #获取text列表的长度,并以此开始循环遍历
if text['Permissions']['Permission'][i]['PortRange'] == Port:
ip = (text['Permissions']['Permission'][i]['SourceCidrIp'])
break
#遍历列表,当PortRange等于所定义的端口时,返回IP并跳出循环
# print(text['Permissions']['Permission'][]['SourceCidrIp'])
return (ip)
def Remove(RegionId,SecurityGroupId,IpProtocol,PortRange,SourceCidrIp):
'''
RevokeSecurityGroup:从指定的安全组删除一条规则
'''
request.set_action_name('RevokeSecurityGroup')
request.add_query_param('RegionId', RegionId)
request.add_query_param('SecurityGroupId', SecurityGroupId)
request.add_query_param('IpProtocol', IpProtocol)
request.add_query_param('PortRange', PortRange)
request.add_query_param('SourceCidrIp', SourceCidrIp)
request.add_query_param('NicType', 'intranet')
response = client.do_action_with_exception(request)
#print(response)
def Add_NewIP(RegionId,SecurityGroupId,IpProtocol,PortRange,SourceCidrIp):
'''
AuthorizeSecurityGroup:添加一个规则到指定的安全组
'''
request.set_action_name('AuthorizeSecurityGroup')
request.add_query_param('RegionId', RegionId)
request.add_query_param('SecurityGroupId', SecurityGroupId)
request.add_query_param('IpProtocol', IpProtocol)
request.add_query_param('PortRange', PortRange)
request.add_query_param('SourceCidrIp', SourceCidrIp)
request.add_query_param('NicType', 'intranet')
request.add_query_param('Description', 'PythonScriptCreated')
response = client.do_action_with_exception(request)
if __name__ == "__main__":
request = CommonRequest()
request.set_accept_format('json') #阿里云返回的数据类型为json格式
request.set_domain('ecs.aliyuncs.com')
request.set_method('POST')
request.set_version('2014-05-26') #api版本
client = AcsClient('填写AccessKeyID', '填写AccessKeySecret', 'cn-shenzhen')
#阿里云api固定认证格式:AccessKeyID,AccessKeySecret,RegionId
RegionId = 'cn-shenzhen' #区域
SecurityGroupId = ['填写安全组id'] #安全组ID
IpProtocol = 'tcp' #协议类型
PortRange = ['38848/38848'] #端口
log_file = 'ip.log' #将IP地址保存至一个文件中
new_ip = get_ip("https://ipv4.ngx.hk") #获取当前IP的URL https://ipv4.ngx.hk http://ip.42.pl/raw
old_ip = get_old_ip(log_file)
NewIP = new_ip
if new_ip != old_ip:
change_ip(log_file)
for i in SecurityGroupId:
for j in PortRange:
try:
OldIP = Get_sourceIP(RegionId=RegionId, SecurityGroupId=i, Port='38848/38848')
# 调用Get_sourceIP函数获取旧的IP。若IP不存在或对应的端口不对,则抛出异常,直接执行添加
Remove(RegionId=RegionId, SecurityGroupId=i, IpProtocol=IpProtocol, PortRange=j, SourceCidrIp=OldIP)
Add_NewIP(RegionId=RegionId, SecurityGroupId=i, IpProtocol=IpProtocol, PortRange=j, SourceCidrIp=NewIP)
except:
Add_NewIP(RegionId=RegionId, SecurityGroupId=i, IpProtocol=IpProtocol, PortRange=j, SourceCidrIp=NewIP)