利用Python3获取办公室的公网IP并
短信预约 -IT技能 免费直播动态提醒
-
阿里云Python SDK:SDK使用说明
-
API详情请参考:阿里云ECS API
-
安装依赖
#本文使用的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('LTxxxxxxxxxxxxx1dmms', 'xxxxxxxxxxxxxxxxxxxxxxxxxxx', 'cn-shenzhen')
#阿里云api固定认证格式:AccessKeyID,AccessKeySecret,RegionId
RegionId = 'cn-shenzhen' #区域
SecurityGroupId = ['sg-wz9xxxxxxx','sg-xxxxxxxxxxxxxxx'] #安全组ID
IpProtocol = 'tcp' #协议类型
PortRange = ['22/22','3306/3306'] #端口
log_file = 'ip.log' #将IP地址保存至一个文件中
new_ip = get_ip("https://ip.cn/") #获取当前IP的URL
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='22/22')
# 调用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)
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341