Created
December 24, 2019 11:10
-
-
Save jamil666/f27136f118090613c035d5ff43ee8161 to your computer and use it in GitHub Desktop.
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
from pyVim.connect import SmartConnect, SmartConnectNoSSL, Disconnect | |
from pyVmomi import vim | |
import re, ssl | |
vc = 'Vcenter name' | |
username = 'username' | |
password = 'password' | |
pg = input('New network name: ') # Port Group name in Vcenter | |
vlan_id = input('New vlan ID: ') # Vlan ID | |
esx_host = ['esxi1', 'esxi2'] # List of ESXi hosts | |
vswitch = 'vSwitch0' | |
# This function get esxi host object from vmware API | |
def GetVMHosts(content, regex_esxi=None): | |
host_view = content.viewManager.CreateContainerView(content.rootFolder, | |
[vim.HostSystem], | |
True) | |
obj = [host for host in host_view.view] | |
match_obj = [] | |
if regex_esxi: | |
for esxi in obj: | |
if re.findall(r'%s.*' % regex_esxi, esxi.name): | |
match_obj.append(esxi) | |
match_obj_name = [match_esxi.name for match_esxi in match_obj] | |
print("Matched ESXi hosts: %s" % match_obj_name) | |
host_view.Destroy() | |
return match_obj | |
else: | |
host_view.Destroy() | |
return obj | |
# This function add port group to single ESXI host | |
def AddHostsPortgroup(hosts, vswitchName, portgroupName, vlanId): | |
for host in hosts: | |
AddHostPortgroup(host, vswitchName, portgroupName, vlanId) | |
# This function add port group to all ESXI hosts | |
def AddHostPortgroup(host, vswitchName, portgroupName, vlanId): | |
portgroup_spec = vim.host.PortGroup.Specification() | |
portgroup_spec.vswitchName = vswitchName | |
portgroup_spec.name = portgroupName | |
portgroup_spec.vlanId = int(vlanId) | |
network_policy = vim.host.NetworkPolicy() | |
network_policy.security = vim.host.NetworkPolicy.SecurityPolicy() | |
network_policy.security.allowPromiscuous = True | |
network_policy.security.macChanges = False | |
network_policy.security.forgedTransmits = False | |
portgroup_spec.policy = network_policy | |
host.configManager.networkSystem.AddPortGroup(portgroup_spec) | |
# This function making connection to Vcenter and starting another function for new port group creation | |
def main(): | |
s = ssl.SSLContext(ssl.PROTOCOL_TLSv1) | |
s.verify_mode = ssl.CERT_NONE | |
serviceInstance = SmartConnect(host=vc, | |
user=username, | |
pwd=password, | |
port=443, | |
sslContext=s) | |
print('Connected') | |
content = serviceInstance.RetrieveContent() | |
for host in esx_host: | |
print(host) | |
hosts = GetVMHosts(content, host) | |
AddHostsPortgroup(hosts, vswitch, pg, vlan_id) | |
print('PortGroup {} succeffully creatde!'.format(pg)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment