当共享带宽包具有非常多的ip时,倘若带宽异常爆满,这时候依靠阿里云监控去排查是非常繁琐不直观的。
通过调用ip带宽的监控,可以分析出当带宽包爆满时的所有IP流量大小,从而快速定位问题。
代码如下(代码有很大改进空间,是本人刚接触python写的脚本,没有花很多时间优化,使用pyhton3,请见谅):
#!/usr/bin/env python
#coding=utf-8
import re
import json
import csv
import datetime
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcms.request.v20190101.DescribeMetricDataRequest import DescribeMetricDataRequest
from aliyunsdkvpc.request.v20160428.DescribeEipAddressesRequest import DescribeEipAddressesRequest
#输出地域和带宽包,这里可以修改你公司所在的地域,
region_list = ['cn-hangzhou','cn-shanghai','cn-qingdao','cn-beijing','cn-zhangjiakou','cn-huhehaote','cn-shenzhen']
region = input("请输入地域:'cn-hangzhou','cn-shanghai','cn-qingdao','cn-beijing','cn-zhangjiakou','cn-huhehaote','cn-shenzhen'")
if region not in region_list:
print('地域错误,请重新输入')
exit()
BandwidthPackage = input('请输入带宽包:')
endtime = input("请输入时间:,以%Y-%m-%d %H:%M:%S为格式 ")
endtime1 = datetime.datetime.strptime(endtime, '%Y-%m-%d %H:%M:%S')
starttime = (endtime1+ datetime.timedelta(minutes=-1))
now1 = endtime1.strftime("%Y-%m-%d-%H-%M-%S")
#清空生成文件
f=open(BandwidthPackage + now1 + 'ip.csv', "w")
f.truncate()
f.close()
f=open('共享带宽IPlist.txt', "w")
f.truncate()
f.close()
with open(BandwidthPackage + now1 + 'ip.csv',"w",encoding='utf-8',newline='')as f:
writer = csv.writer(f)
writer.writerow(["IP","Outflow/MB","Inflow/MB"])
mbps_list = {}
float_num = []
unsort_list = []
unsort_list1 = []
#初始化一遍api获取页数
client = AcsClient('你的阿里云key', '你的阿里云key', region)
request = DescribeEipAddressesRequest()
request.set_accept_format('json')
request.set_PageNumber(1)
request.set_PageSize(50)
response = client.do_action_with_exception(request)
###计算页数和余数
totalcount = json.loads(response)['TotalCount']
print(totalcount)
pagesize = json.loads(response)['PageSize']
print(pagesize)
page = int(totalcount//pagesize)+1
print(page)
def request(pagenumber,pagesize,BandwidthPackage,region):
client = AcsClient('你的阿里云key', '你的阿里云key', region)
request = DescribeEipAddressesRequest()
request.set_accept_format('json')
request.set_PageNumber(pagenumber)
request.set_PageSize(pagesize)
response = client.do_action_with_exception(request)
main = json.loads(response)['EipAddresses']['EipAddress']
for i in main:
if i['BandwidthPackageId'] == BandwidthPackage:
with open('共享带宽IPlist.txt', 'a', encoding='utf-8')as f:
f.write(i['AllocationId'] + ' ' + i['IpAddress'] + '
')
for i in range(page):
i+=1
request(i,50,BandwidthPackage,region)
#获取出流量
def run(EIPid,ip,region):
client = AcsClient('你的阿里云key', '你的阿里云key', region)
request = DescribeMetricDataRequest()
request.set_accept_format('json')
request.set_MetricName("net_tx.rate")
request.set_Period("60")
request.set_StartTime(starttime)
request.set_EndTime(endtime)
request.set_Dimensions("[{"instanceId": ""+ EIPid + ""}]")
request.set_Namespace("acs_vpc_eip")
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
flow = json.loads(json.loads(response)['Datapoints'])[0]['Value']
mb = flow/8/1024/128
print(mb)
unsort_list.append(ip + " " + str(mb))
time.sleep (0.1)
#获取进流量
def run1(EIPid,ip,region):
client = AcsClient('你的阿里云key', '你的阿里云key', region)
request = DescribeMetricDataRequest()
request.set_accept_format('json')
request.set_MetricName("net_rx.rate")
request.set_Period("60")
request.set_StartTime(starttime)
request.set_EndTime(endtime)
request.set_Dimensions("[{"instanceId": ""+ EIPid + ""}]")
request.set_Namespace("acs_vpc_eip")
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
flow = json.loads(json.loads(response)['Datapoints'])[0]['Value']
mb = flow/8/1024/128
print(mb)
unsort_list1.append(str(mb))
time.sleep(0.1)
f = open('共享带宽IPlist.txt','r',encoding='utf-8')
for i in f:
s = i.split()
print(s[0],s[1])
time.sleep(0.1)
try:
run(s[0],s[1],region)
except:
print("接口调用过多无法返回数据")
try:
run1(s[0],s[1],region)
except:
print("接口调用过多无法返回数据")
with open( BandwidthPackage + now1 + 'ip.csv','a',newline='')as f:
for i in range(len(unsort_list)):
f_csv = csv.writer(f)
s = unsort_list[i].split()
s1 = unsort_list1[i].split()
main = [(str(s[0]), str(s[1]),str(s1[0]))]
f_csv.writerows(main)
执行后排序即可找出有异常流量的IP信息