模块
aliyun-python-sdk-core-v3==2.9.1
aliyun-python-sdk-cms
oss2
脚本
import oss2
from aliyunsdkcore import client
from aliyunsdkcms.request.v20180308 import QueryMetricListRequest
import datetime
import time
import json
def BusinessOssTask():
auth = oss2.Auth('key', 'secret')
service = oss2.Service(auth, 'http://oss-区域.aliyuncs.com')
name_list = [b.name for b in oss2.BucketIterator(service)]
now = datetime.datetime.now()
oss_size = []
for name in name_list:
clt = client.AcsClient('key', 'secret', 'region')
request = QueryMetricListRequest.QueryMetricListRequest()
request.set_accept_format('json') # 获取的是json格式
request.set_Project('acs_oss')
request.set_Metric('MeteringStorageUtilization') # 这个获得的值单位是字节
start_time = (now - datetime.timedelta(hours=4)).strftime("%Y-%m-%d %H:%S:%M")
end_time = (now - datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%S:%M")
print(start_time, end_time)
timestamp_start = int(time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))) * 1000
timestamp_end = int(time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))) * 1000
request.set_StartTime(timestamp_start)
request.set_EndTime(timestamp_end)
request.set_Dimensions({'BucketName': name}) # 这里就是填写bucket名字的地方
request.set_Period('3600') # 计量类指标的Metric如下,注意聚合粒度为3600s。
result = clt.do_action_with_exception(request)
res = json.loads(result)
res_list = res['Datapoints'][1:-1].split(":")
oss_size.append(float(res_list[-1][:-1]))
print(round(sum(oss_size) / 1024 / 1024 / 1024 / 1024, 2),'Tb')
参考:
https://blog.51cto.com/chenx1242/1968378