VMware Cloud Community
weisenberg
Contributor
Contributor

Automatically adding ESXi host to vCenter with python

Hi,

I am trying to use a @lamw script ​to have ESXi hosts automatically join a vCenter as part of the kickstart process. I am hitting a problem with HTTP authentication to the vCenter appliance via python. Both the host and vCenter are v6.5 U3.

Here is the relevant part of the script:

# --------begin snippet--------

import sys,re,os,urllib,base64,syslog,socket,ssl,urllib.request

vc_username = "<snip>"

vc_encodedpassword = '<snip>'

vc_password = base64.b64decode(vc_encodedpassword).decode('utf-8')

# vCenter mob URL for findByInventoryPath

url = "https://" + vcenter_server + "/mob/?moid=SearchIndex&method=findByInventoryPath"

# this allows self-signed certs

gcontext = ssl.create_default_context()

gcontext.check_hostname = False

gcontext.verify_mode = ssl.CERT_NONE

# Create global variables

global passman,authhandler,opener,req,page,page_content,nonce,headers,cookie,params,e_params,syslogGhetto,clusterMoRef

# syslog key for easier troubleshooting

syslogGhetto = 'GHETTO-JOIN-VC'

syslog.syslog(syslogGhetto + ' Starting joinvCenter process - ' + url)

# Code to build opener with HTTP Basic Authentication

try:

        passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()

        passman.add_password(None,url,vc_username,vc_password)

        authhandler = urllib.request.HTTPBasicAuthHandler(passman)

        opener = urllib.request.build_opener(authhandler)

        urllib.request.install_opener(opener)

except IOError as e:

        opener.close()

        syslog.syslog(syslogGhetto + ' Failed HTTP Basic Authentication!')

        sys.exit(1)

else:

        syslog.syslog(syslogGhetto + ' Succesfully built HTTP Basic Authentication')

# Code to capture required page data and cookie required for post back to meet CSRF requirements

# Thanks to user klich - http://communities.vmware.com/message/1722582#1722582

try:

        req = urllib.request.Request(url)

        page = urllib.request.urlopen(req,context=gcontext)

        page_content= page.read()

except IOError as e:

        opener.close()

        syslog.syslog(syslogGhetto + ' Failed to retrieve MOB data -> ' + str(e.args))

        sys.exit(1)

else:

        syslog.syslog(syslogGhetto + ' Succesfully requested MOB data')

# --------end snippet--------

No matter which credentials I try, I always get an HTTP/401 unauthorized error from vCenter. This happens at first contact on the line ‘page = urllib.request.urlopen(req,context=gcontext)’) If I use the same credentials in a browser to go the same URL (mob browser), it works.

Any ideas how to solve this problem?

Thanks!

0 Kudos
0 Replies