Skip to content

Instantly share code, notes, and snippets.

@weldpua2008
Created January 15, 2017 09:29
Show Gist options
  • Select an option

  • Save weldpua2008/046f3203344c3f9f65b11b094107e711 to your computer and use it in GitHub Desktop.

Select an option

Save weldpua2008/046f3203344c3f9f65b11b094107e711 to your computer and use it in GitHub Desktop.
Get IP of any VM by name on ESXi
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################
# Get IP of VM by name on ESXi
#
##############################################################
##############################################################
# author: Valeriy Solovyov <weldpua2008@gmail.com>
# version 0.2 <4.11.2015>
# - fixed issue on getting ip. By default return same as you
# see in the vSphere Client
# version 0.1 <3.11.2015>
# - initial
##############################################################
from pysphere import VIException
from pysphere import VIServer
import logging
import sys
import argparse
import base64
import getpass
import re
import time
def vm_by_name(name, con):
"""Find vm by name
:param name:
:param con:
:return:
"""
try:
vm = con.get_vm_by_name(name)
logging.debug('Found VM %s' % vm.properties.name)
return vm
except VIException:
return None
def to_esx(server, username, password):
con = VIServer()
try:
logging.debug('Trying to connect with provided credentials')
con.connect(server, username, password)
logging.info('Connected to server %s' % server)
logging.debug('Server type: %s' % con.get_server_type())
logging.debug('API version: %s' % con.get_api_version())
except VIException as ins:
logging.error(ins)
logging.debug('Loggin error. Program will exit now.')
sys.exit()
return con
def get_args(): # pragma: no cover
# Creating the argument parser
parser = argparse.ArgumentParser(
description="Getting info of VM.")
parser.add_argument(
'-s',
'--server',
nargs=1,
required=True,
help='The vCenter or ESXi server to connect to',
dest='server',
type=str)
parser.add_argument(
'-u',
'--user',
nargs=1,
required=True,
help='The username with which to connect to the server',
dest='username',
type=str)
parser.add_argument(
'-p',
'--password',
nargs=1,
required=False,
help='The password in plain text with which to connect to the host. If not specified, the user is prompted at runtime for a password.',
dest='password',
type=str)
parser.add_argument(
'-pe',
'--password-encrypted',
nargs=1,
required=False,
help='The password encrypted using Base64 with which to connect to the host. ',
dest='passwordEncrypted',
type=str)
parser.add_argument(
'-m',
'--vm',
nargs=1,
required=True,
help='The virtual machine (VM)',
dest='vmname',
type=str)
parser.add_argument(
'-v',
'--verbose',
required=False,
help='Enable verbose output',
dest='verbose',
action='store_true')
parser.add_argument(
'-d',
'--debug',
required=False,
help='Enable debug output',
dest='debug',
action='store_true')
parser.add_argument(
'-l',
'--log-file',
nargs=1,
required=False,
help='File to log to (default = stdout)',
dest='logfile',
type=str)
parser.add_argument(
'-V',
'--version',
action='version',
version="%(prog)s (version 0.1)")
# subparsers = parser.add_subparsers(help='commands')
args = parser.parse_args()
return args
def find_ip(vm, ipv6=False, timeout=1800):
ips = None
ip = vm.get_property('ip_address', False)
i = 0
sleep_delay_sec = 1
while not ip:
time.sleep(sleep_delay_sec)
ip = vm.get_property('ip_address', False)
i += sleep_delay_sec
if i > timeout:
break
# getting ipthat inside ESXi was shown
if ip:
if ipv6 and re.match('\d{1,4}\:.*', ip) and not re.match('fe83\:.*',ip):
print 'IPv6 address found: %s' % ip
ips = ip
#return ip
elif not ipv6 and re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',ip) and ip != '127.0.0.1':
print 'IPv4 address found: %s' % ip
ips = ip
else:
# getting ip that inside vm object
net_info = vm.get_property('net', False)
if net_info:
for ip in net_info[0]['ip_addresses']:
if ipv6 and re.match('\d{1,4}\:.*', ip) and not re.match('fe83\:.*',ip):
print 'IPv6 address found: %s' % ip
ips = str(ips) + ';' + ip
#return ip
elif not ipv6 and re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',ip) and ip != '127.0.0.1':
print 'IPv4 address found: %s' % ip
ips = str(ips) + ';' + ip
#return ip
return ips
def run(): # pragma: no cover
# Notification settings
args = get_args()
# argsdict = vars(args)
server = args.server[0]
username = args.username[0]
vmname = args.vmname[0]
verbose = args.verbose
debug = args.debug
log_file = None
password = None
if args.password:
password = args.password[0]
if args.logfile:
log_file = args.logfile[0]
# Logging settings
if debug:
log_level = logging.DEBUG
elif verbose:
log_level = logging.INFO
else:
log_level = logging.WARNING
#Initializing logger
if log_file:
logging.basicConfig(
filename=log_file,
format='%(asctime)s %(levelname)s %(message)s',
level=log_level)
else:
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=log_level)
logger = logging.getLogger(__name__)
logger.debug('logger initialized')
try:
logger.debug('Using encrypted password. Decrypting now.')
if args.passwordEncrypted:
password = base64.b64decode(args.passwordEncrypted[0])
except Exception as error:
logger.error(error)
logger.debug(
'Password error. Either this is not an encrypted passowrd or is not well formated.')
sys.exit()
# Asking Users password for server
if password is None:
logger.debug(
'No command line password received, requesting plain text password from user.')
password = getpass.getpass(
prompt='Enter password for vCenter %s for user %s: ' %
(server, username))
logger.debug(password)
# Connecting to server
logger.info('Connecting to server %s with username %s' % (server, username))
con = to_esx(
server=server,
username=username,
password=password)
try:
# Getting VM object
vm = vm_by_name(vmname, con)
if vm:
logger.info(
'Successfully found %s in %s' %
(vm.get_property('name'), vm.get_property('path')))
else:
logger.error(
"Could not find %s, please verify VM's name and try again." %
vm)
con.disconnect()
sys.exit()
find_ip(vm)
con.disconnect()
except VIException as inst:
logger.error(inst)
logger.error('An unexpceted error ocurred. Program will be terminated.')
sys.exit()
if __name__ == '__main__': # pragma: no cover
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment