1. 程式人生 > >利用Python3獲取辦公室的公網IP並修改阿裏雲安全組規則

利用Python3獲取辦公室的公網IP並修改阿裏雲安全組規則

lencod 函數 range plain url move __name__ method port

  • 阿裏雲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.match(r‘當前 IP:(.*?) 來自.*?‘,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獲取辦公室的公網IP並修改阿裏雲安全組規則