AWS lightsail 实例统计流量,Python脚本
目录
一、AWS lightsail 实例统计流量,Python脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# cat 2.py import boto3 import argparse from datetime import datetime, timezone, timedelta def get_total_bytes(client, instance_name, metric_name, start_time, end_time, period=3600): """获取指定实例的某个网络指标(NetworkIn / NetworkOut)的总和(字节数)""" response = client.get_instance_metric_data( instanceName=instance_name, metricName=metric_name, period=period, startTime=start_time, endTime=end_time, unit='Bytes', statistics=['Sum'] ) datapoints = response.get("metricData", []) total = sum(d['sum'] for d in datapoints if 'sum' in d) return total def parse_args(): parser = argparse.ArgumentParser(description="统计 AWS Lightsail 实例流量") parser.add_argument("--region", required=True, help="AWS 区域,例如 ap-northeast-1") parser.add_argument("--instance", required=True, help="Lightsail 实例名称") parser.add_argument("--start", required=True, help="起始日期 (格式: YYYY-MM-DD,例如 2025-08-01)") parser.add_argument("--end", required=True, help="结束日期 (格式: YYYY-MM-DD,例如 2025-09-03)") return parser.parse_args() def main(): args = parse_args() # 自动补全时间 start_time = datetime.strptime(args.start, "%Y-%m-%d").replace(tzinfo=timezone.utc) end_time = datetime.strptime(args.end, "%Y-%m-%d") + timedelta(hours=23, minutes=59, seconds=59) end_time = end_time.replace(tzinfo=timezone.utc) client = boto3.client("lightsail", region_name=args.region) total_in = get_total_bytes(client, args.instance, "NetworkIn", start_time, end_time) total_out = get_total_bytes(client, args.instance, "NetworkOut", start_time, end_time) print(f"实例: {args.instance}") print(f"区域: {args.region}") print(f"时间段: {start_time} ~ {end_time}") print(f"总入流量: {total_in / (1024**3):.2f} GB ({total_in:,} 字节)") print(f"总出流量: {total_out / (1024**3):.2f} GB ({total_out:,} 字节)") print(f"总流量: {(total_in + total_out) / (1024**3):.2f} GB") if __name__ == "__main__": main() |
二、AWS lightsail 实例统计流量,Python脚本运行参数
1 2 3 4 5 6 7 8 9 10 |
python3 2.py -h usage: 2.py [-h] --region REGION --instance INSTANCE --start START --end END 统计 AWS Lightsail 实例流量 optional arguments: -h, --help show this help message and exit --region REGION AWS 区域,例如 ap-northeast-1 --instance INSTANCE Lightsail 实例名称 --start START 起始日期 (格式: YYYY-MM-DD,例如 2025-08-01) --end END 结束日期 (格式: YYYY-MM-DD,例如 2025-09-03) |
三、AWS lightsail 实例统计流量,Python脚本传参示例
1 2 3 4 5 6 7 8 |
# python3 2.py --region="ap-northeast-1" --instance="aws-rent-4" --start="2025-08-25" --end="2025-09-03" 实例: aws-rent-4 区域: ap-northeast-1 时间段: 2025-08-25 00:00:00+00:00 ~ 2025-09-03 23:59:59+00:00 总入流量: 756.25 GB (812,021,616,037.0 字节) 总出流量: 790.04 GB (848,303,514,218.0 字节) 总流量: 1546.30 G |