Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created February 24, 2010 23:10
Show Gist options
  • Select an option

  • Save tmcw/314001 to your computer and use it in GitHub Desktop.

Select an option

Save tmcw/314001 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os, sys, pickle
from optparse import OptionParser
from subprocess import *
# Usage
# ec2 l (lists servers)
# ec2 n 37a -m "Message" (appends the message "Message" to a server like i-37ablah)
# ec2 c 37a (connects to a server like i-37ablah)
def get_ec2(fragment):
hostname = ''
ec2s = Popen(["aws", "din", "--simple"], stdout=PIPE).communicate()[0]
for e in ec2s.splitlines():
if e.find(fragment) > -1 and hostname != '':
raise Exception('Multiple hostnames matched that string')
elif e.find(fragment) > -1:
return e.split()
def main():
if(sys.argv[1] == 'c'):
connect(sys.argv[2])
if(sys.argv[1] == 'l'):
list()
if(sys.argv[1] == 'n'):
note(sys.argv[2])
def load_notes():
notes_file = os.path.expanduser('~/.ec2.notes')
if(os.path.exists(notes_file)):
return pickle.load(open(notes_file, 'rb'))
else:
return {}
def save_notes(notes):
notes_file = os.path.expanduser('~/.ec2.notes')
pickle.dump(notes, open(notes_file, 'wb+'))
def note(fragment):
parser = OptionParser()
parser.add_option("-m", "--msg", dest="msg")
(options, args) = parser.parse_args()
hostname = get_ec2(fragment)[0]
notes = load_notes()
notes[hostname] = options.msg
save_notes(notes)
def list():
notes = load_notes()
ec2s = Popen(["aws", "din", "--simple"], stdout=PIPE).communicate()[0]
for e in ec2s.splitlines():
print e
if(notes.has_key(e.split()[0])):
print " %s" % notes[e.split()[0]]
def connect(fragment):
hostname = 'pending'
KEY = '~/.ssh/ec2-keypair.pem'
SSH = '/usr/bin/ssh'
fragment = 'i-'+fragment
print "Connecting to instance...",
while hostname == 'pending':
hostname = get_ec2(fragment)[2]
print ".",
call('%s -i %s root@%s' % (SSH, KEY, hostname), shell=True)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment