Skip to content

Instantly share code, notes, and snippets.

@freyes
Last active May 4, 2016 19:31
Show Gist options
  • Save freyes/20f658a9adc6e405a0626868c10bc253 to your computer and use it in GitHub Desktop.
Save freyes/20f658a9adc6e405a0626868c10bc253 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# Author: Felipe Reyes <[email protected]>
#
import sys
import subprocess
try:
import pylxd
except ImportError:
sys.stderr.write("couldn't import pylxd (apt install python3-pylxd)\n")
sys.exit(1)
lxd = pylxd.api.API()
username = None
if len(sys.argv) == 1:
sys.stderr.write("Usage:\n\t%s [username@]container\n" % sys.argv[0])
sys.exit(1)
cname = sys.argv[1]
if "@" in cname:
username, cname = cname.split('@', 1)
if not lxd.container_defined(cname):
sys.stderr.write('Error: container %s not found\n' % cname)
sys.exit(1)
cname_ip = None
cinfo = lxd.container_info(cname)
for key in cinfo.get('network', {}):
if key == 'lo':
continue # skipping loopback device
for address in cinfo['network'][key]['addresses']:
ip_addr = address['address']
try:
if username:
host = "%s@%s" % (username, ip_addr)
else:
host = ip_addr
retcode = subprocess.call('ssh %s' % host, shell=True)
if retcode < 0:
sys.stderr.write("SSH Error: %s\n" % retcode)
else:
sys.exit(retcode)
except OSError as e:
sys.stderr.write("Execution failed: %s\n" % e)
sys.stderr.write('No valid IP was found\n')
sys.exit(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment