對於部署在阿里雲上的重要系統通常是不讓其餘人訪問的,因此會在負載均衡(SLB)上加上訪問控制列表。而使用ASDL撥號上網的寬帶來講通常公網IP都不會固定的,會隨時變動公網IP,因此此腳本正是解決此需求。html
腳本運行前須要先安裝aliyun-python-sdk-core 和aliyun-python-sdk-slb 2個sdk,而且在阿里雲帳戶裏面建立access_key和access_secret。
腳本會查詢到目前的公網IP,如何建立本地一個文件將IP記錄到文件裏,下次執行時會將查詢到的IP和文件裏的對比,若是IP和文件裏記錄的IP不一致則將IP添加到訪問控制列表裏。
最後只須要在服務器裏每隔一段時間執行一次此腳本就OK。python
sdk 下載:https://developer.aliyun.com/tools/sdk#/pythonjson
若是是重要的數據在公網傳輸,仍是儘可能使用加密傳輸。畢竟阿里雲的SSL 和IPSEC 也很完善了,推薦使用。api
#!/usr/bin/env python3 #coding:utf-8 from aliyunsdkcore import client import time,requests from aliyunsdkslb.request.v20140515 import AddAccessControlListEntryRequest from aliyunsdkcore.profile import region_provider #region_provider.modify_point('slb', '<regionId>', 'slb.<regionId>.aliyuncs.com') # 名稱:阿里雲負載均衡白名單自動修改腳本 ### 變量配置 ### # 保存歷史IP地址的文件名 file_save_ipaddr = 'ipaddr.txt' # 一些能夠獲取本機出口IP的API地址 ip_api_list = 'http://icanhazip.com,http://ident.me,http://ifconfig.me,http://ipecho.net/plain,http://whatismyip.akamai.com,http://myip.dnsomatic.com' # SLB 配置,此 Access Key 只需添加 ACL 的權限 aliyun_access_key = 'xxxxxxxxx' aliyun_access_secret = 'xxxxxxxxxxxxxx' # 在這裏能夠獲取region:https://help.aliyun.com/document_detail/40654.html aliyun_region = 'cn-hangzhou' # 訪問列表一(acl-bp1792k8uvk11xxpgu5l) # 訪問列表二(acl-bp1okd1kud9a41kyjkja) # 須要修改的ACL的ID,進入負載均衡控制檯 -> 訪問控制 -> 策略ID aliyun_acl_id = ['acl-bp1okd1kud9a41kyjkja','acl-bp1792k8uvk11xxpgu5l'] ### 配置結束 ### def getExitIpAddr(ip_api_list): '''獲取出口IP地址''' url_list = str(ip_api_list).split(',') ip = None for url in url_list: resp = requests.get(url,timeout=3) if resp.status_code == 200: ip = resp.text.strip() break return ip def setAcl(access_key,access_secret,region,acl_id,ip): '''修改ACL''' clt = client.AcsClient(access_key,access_secret,region) # 設置參數 request = AddAccessControlListEntryRequest.AddAccessControlListEntryRequest() request.set_accept_format('json') request.add_query_param('AclId',acl_id) request.add_query_param('RegionId',region) request.add_query_param('Tags', 'API自動添加') request.add_query_param('AclEntrys', '[{{"entry":"{ip}/32","comment":"此處是註釋{d}"}}]'.format(ip=ip,d=time.strftime("%Y-%m-%d",time.localtime()))) #添加ip並添加註釋 # 發起請求 response = clt.do_action_with_exception(request) print(response) def getSavedIp(filename): '''獲取已保存的IP''' try: with open(filename,'r',encoding='utf-8') as f: return f.readline() except IOError: print("文件不存在") def saveNewIp(filename,ipaddr): '''保存新IP''' with open(filename,'w',encoding='utf-8') as f: f.write(ipaddr) def main(): current_ip = getExitIpAddr(ip_api_list) saved_ip = getSavedIp(file_save_ipaddr) print('當前IP',current_ip) print('保存的IP',saved_ip) if current_ip == saved_ip: print('IP無變化') exit(0) else: for acl_id in aliyun_acl_id: setAcl(access_key=aliyun_access_key, access_secret=aliyun_access_secret, region=aliyun_region, acl_id=acl_id, ip=current_ip) time.sleep(5) saveNewIp(file_save_ipaddr,current_ip) if __name__ == '__main__': main()