Python 3を利用してオフィスのパブリックネットワークIPを取得し、アリクラウドセキュリティグループのルールを修正する


  • 阿里雲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)