Dependency:
- boto3 and AWS credential configured on your local
- colored
Usage:
$ python ech.py server-name
More simple usage:
- Rename
ech.py
toech
and move it to~/bin
or somewhere listed in your$PATH
. $ ech server-name
#!/home/hj/bin/python | |
import os | |
import sys | |
import textwrap | |
import boto3 | |
from colored import fg, attr | |
def find_tag(tags, name): | |
for tag in tags: | |
if tag['Key'] == name: | |
return tag['Value'] | |
return None | |
if __name__ == '__main__': | |
name = sys.argv[1] | |
instances = list(boto3.resource('ec2')\ | |
.instances\ | |
.filter(Filters=[ | |
{'Name': 'instance-state-name', 'Values': ['running']}, | |
{'Name': 'tag:Name', 'Values': [f'*{name}*']} | |
])) | |
instances.sort(key=lambda i: find_tag(i.tags, 'Name')) | |
if not instances: | |
print('Not found') | |
sys.exit(1) | |
longest_name_length = max(len(find_tag(i.tags, 'Name')) for i in instances) | |
name_fmt = '{:%ds}' % longest_name_length | |
for i, instance in enumerate(instances): | |
instance_name = find_tag(instance.tags, 'Name') | |
print( | |
fg('dark_olive_green_3b'), | |
f'{i:2d}.', | |
name_fmt.format(instance_name), | |
attr('reset'), | |
fg('light_green_3'), | |
instance.instance_type, | |
attr('reset'), | |
'\t', | |
instance.public_ip_address, | |
'\n ', | |
fg('dark_green_sea'), | |
instance.public_dns_name, | |
attr('reset'), | |
) | |
idx = 0 | |
if len(instances) > 1: | |
idx = input('Type #: ') | |
try: | |
idx = int(idx) | |
except ValueError: | |
print('Invalid input') | |
sys.exit(1) | |
chosen = instances[idx] | |
chosen_name = find_tag(chosen.tags, 'Name') | |
print( | |
'\n', | |
'Connecting to ', | |
fg('light_green_3'), attr('bold'), | |
f'{chosen_name}', | |
attr('reset'), '\n', | |
f' Id:\t\t{chosen.id}\n', | |
f' Public:\t{chosen.public_ip_address}\n', | |
f' Private:\t{chosen.private_ip_address}\n', | |
attr('reset'), | |
) | |
command = f'ssh ubuntu@{chosen.public_dns_name}' | |
os.system(command) |