Advertisement
Guest User

Untitled

a guest
Aug 25th, 2016
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #!/usr/bin/python
  2. # USAGE: python domipaddr.py qemu:///system HOSTNAME DISTRO USERNAME PASSWORD
  3.  
  4. import sys, pexpect
  5. import pprint
  6.  
  7. SUPPORTED_DISTROS = [
  8. 'ubuntu1404',
  9. 'centos6',
  10. 'centos7']
  11.  
  12. class DomIPAddr():
  13.  
  14.  
  15. def __init__(self, uri, domain, distro, username, password):
  16. if distro not in SUPPORTED_DISTROS:
  17. print "Unsupported distro"
  18. sys.exit(2)
  19.  
  20. self.uri = uri
  21. self.domain = domain
  22. self.distro = distro
  23. self.username = username
  24. self.password = password
  25. self.ip_addr = None
  26. self.child = None
  27.  
  28. def connect(self):
  29. self.child = pexpect.spawn("virsh -c %s console %s" % (self.uri, self.domain))
  30. self.child.expect('.*]')
  31. self.child.sendline('\r')
  32. self.child.expect('.*login: ')
  33. self.child.sendline(self.username)
  34. self.child.expect('.*assword:.*')
  35. self.child.sendline(self.password)
  36. self.child.sendline('\r')
  37.  
  38. def get_ip(self):
  39. self.connect()
  40. self.child.expect('.*~.*')
  41. self.child.sendline("ip addr | grep 'inet ' | grep -v 127 | awk '{print $2}'\r")
  42. self.child.expect('.*/\d\d')
  43. self.child.sendline('exit')
  44.  
  45. def parse_ip(self):
  46. output_parts = []
  47. if self.distro == 'centos6':
  48. split_chars = '\n'
  49. else:
  50. split_chars = '\r\n'
  51.  
  52. # Janky hack. Sometimes the output isn't captured correctly
  53. # so we fetch it again
  54. while len(output_parts) < 4:
  55. self.get_ip()
  56. output_parts = self.child.after.split(split_chars)
  57. self.ip_addr = output_parts[3].split('/')[0]
  58.  
  59.  
  60. if __name__ == '__main__':
  61. get_ip = DomIPAddr(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
  62. get_ip.get_ip()
  63. get_ip.parse_ip()
  64.  
  65. print get_ip.ip_addr
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement