python脚本修改阿里云,腾讯云修改安全组
因为公司外网没有固定ip,现需要把公司外网ip添加到信任安全组里,外网ip一旦漂移,及时修改安全组规则
思路:
获取当前外网ip地址,并写入老地址,
判断新外网ip地址和老ip地址是否相同,如果相同则退出脚本,如果不相同及执行阿里云和腾讯云安全组脚本
IP判断脚本:
#!/bin/bash old_ip=$(cat old.log) new_ip=$(curl -s http://ip.cip.cc) echo oldip:$old_ip echo newip:$new_ip if [ "$old_ip" != "$new_ip" ];then python /opt/python/safe/shsafe.py python /opt/python/safe/gzsafe.py curl -s http://ip.cip.cc > old.log else exit 0 fi
阿里云脚本:
#!/usr/local/python3/bin/python3.7 #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://ip.cn/') #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('LTAI4F**********94nD4', 'LT8U*************ecc', 'cn-hangzhou')
# 删除规则 def DelGroup(SourceCidrIp): request = RevokeSecurityGroupRequest() request.set_accept_format('json') request.set_SecurityGroupId("sg-bp***********s1") 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-bp*********s1") #安全组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)
腾讯云脚本:(腾讯云使用接口修改,https://cloud.tencent.com/document/api/215/15810)
# 获取公网ip
import urllib2 response = urllib2.urlopen("http://ip.cip.cc") ip = response.read().strip() import json from tencentcloud.common import credential from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.vpc.v20170312 import vpc_client, models try: cred = credential.Credential("AKID************A1zo", "mBiz2************X8U") #腾讯云API接口密钥secretid和secretkey httpProfile = HttpProfile() httpProfile.endpoint = "vpc.tencentcloudapi.com" #腾讯云接口地址 clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = vpc_client.VpcClient(cred, "ap-shanghai", clientProfile) #这里注意传入大区 req = models.ModifySecurityGroupPoliciesRequest() params1 = {"SecurityGroupId":"sg-6ebi******i","SecurityGroupPolicySet":{"Ingress":[{"Protocol":"ALL","CidrBlock":"*.*.*.*","Action":"accept","PolicyDescription":"公司内网"}]}} #这里填入安全组规则参数,ip地址可以随便先填个,后面步骤会替换掉 params1["SecurityGroupPolicySet"]["Ingress"][0]["CidrBlock"]=ip params=json.dumps(params1) req.from_json_string(params) resp = client.ModifySecurityGroupPolicies(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err)