Skip to content

Instantly share code, notes, and snippets.

@kouk
Created May 14, 2014 10:53
Show Gist options
  • Save kouk/748c55ffd400013bb87e to your computer and use it in GitHub Desktop.
Save kouk/748c55ffd400013bb87e to your computer and use it in GitHub Desktop.
ec2ssh.sh
#!/bin/sh
function ec2ssh() {
sshopt="1246AaCfgKkMNnqsTtVvXxYyb:c:D:e:F:I:i:L:l:m:O:o:p:R:S:W:w:"
while getopts $sshopt o ; do done
hostname=region=""
if [ $OPTIND -le $# ] ; then
eval hostarg='$'$OPTIND
host=${hostarg##*@} # remove optional user part
hostname=$(get_ssh_var $host HostName)
domain=${hostname#ec2*.}
region=${domain%%.*}
fi
if [ -n "$host" -a -n "hostname" -a -n "$region" ] ; then
echo "refreshing hostname from EC2.."
new_hostname=$(ec2-public-dns $host $region)
if [ $hostname != $new_hostname ] ; then
echo "hostname changed to $new_hostname"
replace_ssh_val $host $hostname $new_hostname
fi
fi
/usr/bin/ssh "$@"
return $?
}
#!/usr/bin/env python
import botocore.session
def get_public_dns_name(host, region):
session = botocore.session.get_session()
ec2 = session.get_service('ec2')
r, d = ec2.get_operation('DescribeInstances').call(
ec2.get_endpoint(region_name=region),
filters=[{'Name': 'tag:Name', 'Values': [host]}])
r.raise_for_status()
return d['Reservations'][0]['Instances'][0]['PublicDnsName']
if __name__ == "__main__":
import sys
host = sys.argv[1]
region = sys.argv[2]
print get_public_dns_name(host, region)
# sed routines to manage hostnames ssh config
_ssh_cfg="$HOME/.ssh/config"
# sed loop over host stanzas in ssh config
_s_pre=':s
n
/^$/{
n
t
}'
_s_post='t
b s'
get_ssh_var() {
cat $_ssh_cfg | sed -n "/Host $1/{$_s_pre
s/$2 //p;$_s_post
}"
}
replace_ssh_val(){
# usage: replace_ssh_val host old new [varname]
sed -i orig "/Host $1/{$_s_pre
s/$4 $2/$4 $3/;$_s_post
}" $_ssh_cfg
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment