Skip to content

Instantly share code, notes, and snippets.

@ihciah
Last active June 8, 2018 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ihciah/1d45419457d5a3d7ff668a6bc82f4a23 to your computer and use it in GitHub Desktop.
Save ihciah/1d45419457d5a3d7ff668a6bc82f4a23 to your computer and use it in GitHub Desktop.
AWS used bandwidth query script (Mainly used for query free bandwidth)

You should pip install boto3 first.

Go to IAM Management Console to create access key.

Also, you should modify the instance_id and region_name in the script above.

Then, you can call get_used_bandwidth() to get used bandwidth in Byte, or just run the script to get it in GB.

#-*-coding: utf-8 -*-
__author__ = 'ihciah'
import boto3
from datetime import datetime
from dateutil.tz import tzutc
instance_id = 'i-068fb997b5721188c'
region_name = 'ap-northeast-1'
aws_access_key_id = ''
aws_secret_access_key = ''
def get_used_bandwidth():
now = datetime.utcnow()
client = boto3.client('cloudwatch', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name)
response = client.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='NetworkOut',
Dimensions=[
{
'Name': 'InstanceId',
'Value': instance_id
},
],
StartTime=datetime(now.year, now.month, 1, 0, 0, tzinfo=tzutc()),
EndTime=datetime(now.year, now.month, now.day, 23, 59, tzinfo=tzutc()),
Period=31*24*3600,
Statistics=[
'Sum',
],
#Unit='Gigabytes'
)
if 'Datapoints' in response and len(response['Datapoints']) > 0:
return response['Datapoints'][0]['Sum']
return 0
if __name__ == "__main__":
used = get_used_bandwidth()
print "%.2f GB" % (used/(1000**3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment