发布时间:2019-09-25 08:23:39编辑:auto阅读(1971)
阿里云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)
上一篇: Python3环境搭建(Windows)
下一篇: python3完全零基础入门视频
47760
46269
37152
34655
29246
25906
24777
19878
19441
17933
5730°
6335°
5853°
5903°
7004°
5841°
5860°
6372°
6331°
7695°