Last active
December 7, 2022 12:16
-
-
Save DoriftoShoes/b98d89d2c339c10c952164d6eab63eec to your computer and use it in GitHub Desktop.
Get ip address of libvirt guest via virsh console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# USAGE: python domipaddr.py qemu:///system HOSTNAME DISTRO INTERFACE USERNAME PASSWORD | |
import sys, pexpect | |
import pprint | |
SUPPORTED_DISTROS = [ | |
'ubuntu1404', | |
'centos6', | |
'centos7'] | |
class DomIPAddr(): | |
def __init__(self, uri, domain, distro, interface, username, password): | |
if distro not in SUPPORTED_DISTROS: | |
print "Unsupported distro" | |
sys.exit(2) | |
self.uri = uri | |
self.domain = domain | |
self.distro = distro | |
self.interface = interface | |
self.username = username | |
self.password = password | |
self.ip_addr = None | |
self.child = None | |
def connect(self): | |
self.child = pexpect.spawn("virsh -c %s console %s" % (self.uri, self.domain)) | |
self.child.expect('.*]') | |
self.child.sendline('\r') | |
self.child.expect('.*login: ') | |
self.child.sendline(self.username) | |
self.child.expect('.*assword:.*') | |
self.child.sendline(self.password) | |
self.child.sendline('\r') | |
def get_ip(self): | |
self.connect() | |
self.child.expect('.*~.*') | |
self.child.sendline("ip addr | grep -A3 '%s:' | grep 'inet ' | awk '{print $2}'\r" % self.interface) | |
self.child.expect('.*/\d\d') | |
self.child.sendline('exit') | |
def parse_ip(self): | |
output_parts = [] | |
if self.distro == 'centos6': | |
split_chars = '\n' | |
else: | |
split_chars = '\r\n' | |
# Janky hack. Sometimes the output isn't captured correctly | |
# so we fetch it again | |
while len(output_parts) < 4: | |
self.get_ip() | |
output_parts = self.child.after.split(split_chars) | |
self.ip_addr = output_parts[3].split('/')[0] | |
if __name__ == '__main__': | |
get_ip = DomIPAddr(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]) | |
get_ip.get_ip() | |
get_ip.parse_ip() | |
print get_ip.ip_addr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment