有台ECS,建了Web server,因为后台是用别的非80端口。
需要添加规则以方便自己管理后台,因为自己家用的IP经常不定时更新,所以每次要去阿里云后台再去修改添加就显示比较麻烦。
于是想有没有办法将本人所在的市的IP都添加到允许列表,这样不就可以一劳永逸了吗?
后来发现网上没有本地(城市级)的电信IP段的数据,只好扩大范围,采集整个江苏省的电信IP段。地址见:http://ipcn.chacuo.net/view/i_CHINANET
接下来,就是将这个IP段添加到规则当中。无奈我这个笨蛋,以为后台添加规则,只能针对一条CIDR进行添加。(因为我测试时,使用的是编辑现有的规则,它是限制只允许一条的,但新添加的界面里面却是允许多条添加--不过即使如此,它最多也是10条CIDR记录而已,所以阿里云也是笨蛋!)
不过不管如何,手工添加绝对是件麻烦事。于是想着怎么批量添加。好在,看到了可以导入规则。规则怎么写呢?不知道,那将现有规则导出一份不就完事了。导出一个规则后发现,它的规则是一个列表,每个列表元素是一个字典。如下:
{"SourceCidrIp": "11.22.0.0/11", "Description": "admin-web Jiangsu", "DestCidrIp": "", "NicType": "intranet", "DestGroupName": "", "PortRange": "8080/8080", "DestGroupId": "", "Ipv6DestCidrIp": "", "Direction": "ingress", "Priority": 1, "IpProtocol": "TCP", "SourcePortRange": "", "SourceGroupOwnerAccount": "", "Policy": "Accept", "CreateTime": "2019-04-02T09:39:01Z", "SourceGroupId": "", "DestGroupOwnerAccount": "", "Ipv6SourceCidrIp": "", "SourceGroupName": ""},
这就好办了。用程序批量跑一下
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 17:52:26 2019 @author: Linc """ import netaddr import json x='''49.64.0.0-49.95.255.255 180.96.0.0-180.127.255.255 58.208.0.0-58.223.255.255 114.224.0.0-114.239.255.255 117.80.0.0-117.95.255.255 121.224.0.0-121.239.255.255 114.216.0.0-114.223.255.255 221.224.0.0-221.231.255.255 222.184.0.0-222.191.255.255 117.60.0.0-117.63.255.255 222.92.0.0-222.95.255.255 218.2.0.0-218.3.255.255 218.4.0.0-218.5.255.255 61.132.0.0-61.132.255.255 61.160.0.0-61.160.255.255 61.177.0.0-61.177.255.255 202.111.0.0-202.111.127.255 202.102.64.0-202.102.127.255 202.102.0.0-202.102.31.255 202.102.32.0-202.102.63.255 103.12.68.0-103.12.71.255 103.22.20.0-103.22.23.255''' rule_json=[] CIDR=x.splitlines() for i in CIDR: cidrs = netaddr.iprange_to_cidrs(i.split('-')[0], i.split('-')[1]) for k, iplist in enumerate(cidrs): json_str= ('''{"SourceCidrIp":"''' + str(iplist) +'''","Description":"admin-web Jiangsu","DestCidrIp":"","NicType":"intranet","DestGroupName":"","PortRange":"8080/8080","DestGroupId":"","Ipv6DestCidrIp":"","Direction":"ingress","Priority":1,"IpProtocol":"TCP","SourcePortRange":"","SourceGroupOwnerAccount":"","Policy":"Accept","CreateTime":"2019-04-02T09:39:01Z","SourceGroupId":"","DestGroupOwnerAccount":"","Ipv6SourceCidrIp":"","SourceGroupName":""}''') rule_json.append(json.loads(json_str)) with open("aliyun_ip_rule.json","w") as f: f.write(json.dumps(rule_json))
这里注意一下JSON格式的规范是使用双引号,所以最后一步json.dumps其实是将单引号转成双引号的目的.
转载请注明:Linc Hu » [python] 阿里云主机批量添加安全组规则