Change VCenter administrator#vsphere.local password Python VMware vsphere - python

Some time ago I was working to rotate the password of the administrator#vsphere.local user in the Vcenter, but there isn't a lot of information about how to do that with Python. I did with LDAP protocol, I just want to create this to future references if someone need it.
import ldap
import os
import sys
vcenter = "the_IP_OR_Host_Name_of_the_VC"
ad_server = "ldap://"+vcenter
userAccount = 'Administrator'
ad_dn = "cn="+userAccount+",cn=users,dc=vsphere,dc=local"
username = 'CPMS_Test#vsphere.local'
old_pwd = 'The_Actual_PAss_of_Administrator'
new_pwd = 'New_Pass_of_the_Account'
# Lets initialize the LDAP, in our case is the same VC
l = ldap.initialize(ad_server)
#LDAP settings, Im not using SSL, but you can use it
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)
l.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
l.simple_bind_s(ad_dn.format(username), old_pwd)
#lets run the update of the pass
password_value_old = old_pwd.encode("utf-8")
password_value = new_pwd.encode("utf-8")
mod_list = [
(ldap.MOD_DELETE, 'userpassword', [password_value_old]),
(ldap.MOD_ADD, 'userpassword', [password_value]),
]
result = l.modify_s(ad_dn.format(username), mod_list)
print(result.info)

Related

Linux NoHup fails for Streaming API IG Markets where file is python

This is quite a specific question regarding nohup in linux, which runs a python file.
Back-story, I am trying to save down streaming data (from IG markets broadcast signal). And, as I am trying to run it via a remote-server (so I don't have to keep my own local desktop up 24/7),
somehow, the nohup will not engage when it 'listen's to a broadcast signal.
Below, is the example python code
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
IG Markets Stream API sample with Python
"""
user_ = 'xxx'
password_ = 'xxx'
api_key_ = 'xxx' # this is the 1st api key
account_ = 'xxx'
acc_type_ = 'xxx'
fileLoc = 'marketdata_IG_spx_5min.csv'
list_ = ["CHART:IX.D.SPTRD.DAILY.IP:5MINUTE"]
fields_ = ["UTM", "LTV", "TTV", "BID_OPEN", "BID_HIGH", \
"BID_LOW", "BID_CLOSE",]
import time
import sys
import traceback
import logging
import warnings
warnings.filterwarnings('ignore')
from trading_ig import (IGService, IGStreamService)
from trading_ig.lightstreamer import Subscription
cols_ = ['timestamp', 'data']
# A simple function acting as a Subscription listener
def on_prices_update(item_update):
# print("price: %s " % item_update)
print("xxxxxxxx
))
# A simple function acting as a Subscription listener
def on_charts_update(item_update):
# print("price: %s " % item_update)
print(xxxxxx"\
.format(
stock_name=item_update["name"], **item_update["values"]
))
res_ = [xxxxx"\
.format(
stock_name=item_update["name"], **item_update["values"]
).split(' '))]
# display(pd.DataFrame(res_))
try:
data_ = pd.read_csv(fileLoc)[cols_]
data_ = data_.append(pd.DataFrame(res_, columns = cols_))
data_.to_csv(fileLoc)
print('there is data and we are reading it')
# display(data_)
except:
pd.DataFrame(res_, columns = cols_).to_csv(fileLoc)
print('there is no data and we are saving first time')
time.sleep(60) # sleep for 1 min
def main():
logging.basicConfig(level=logging.INFO)
# logging.basicConfig(level=logging.DEBUG)
ig_service = IGService(
user_, password_, api_key_, acc_type_
)
ig_stream_service = IGStreamService(ig_service)
ig_session = ig_stream_service.create_session()
accountId = account_
################ my code to set sleep function to sleep/read at only certain time intervals
s_time = time.time()
############################
# Making a new Subscription in MERGE mode
subscription_prices = Subscription(
mode="MERGE",
# make sure to put L1 in front of the instrument name
items= list_,
fields= fields_
)
# adapter="QUOTE_ADAPTER")
# Adding the "on_price_update" function to Subscription
subscription_prices.addlistener(on_charts_update)
# Registering the Subscription
sub_key_prices = ig_stream_service.ls_client.subscribe(subscription_prices)
print('this is the line here')
input("{0:-^80}\n".format("HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM \
LIGHTSTREAMER"))
# Disconnecting
ig_stream_service.disconnect()
if __name__ == '__main__':
main()
#######
Then, I try to run it on linux using this command : nohup python marketdata.py
where marketdata.py is basically the python code above.
Somehow, the nohup will not engage....... Any experts/guru who might see what I am missing in my code?

SAS IOM Bridge with Python

I'm making a connection to a remote SAS Workspace Server using IOM Bridge:
import win32com.client
objFactory = win32com.client.Dispatch("SASObjectManager.ObjectFactoryMulti2")
objServerDef = win32com.client.Dispatch("SASObjectManager.ServerDef")
objServerDef.MachineDNSName = "servername"
objServerDef.Port = 8591 # workspace server port
objServerDef.Protocol = 2 # 2 = IOM protocol
objServerDef.BridgeSecurityPackage = "Username/Password"
objServerDef.ClassIdentifier = "workspace server id"
objSAS = objFactory.CreateObjectByServer("SASApp", True, objServerDef, "uid", "pw")
program = "ods listing;proc means data=sashelp.cars mean mode min max; run;"
objSAS.LanguageService.Submit(program)
_list = objSAS.LanguageService.FlushList(999999)
print(_list)
log = objSAS.LanguageService.FlushLog(999999)
print(log)
objSAS.Close()
It work fine. But I cant seem to find the right attribut for CreateObjectByServer, when trying with a Stored Process Server (when I change 'Port' and 'ClassIdentifier'):
import win32com.client
objFactory = win32com.client.Dispatch("SASObjectManager.ObjectFactoryMulti2")
objServerDef = win32com.client.Dispatch("SASObjectManager.ServerDef")
objServerDef.MachineDNSName = "servername"
objServerDef.Port = 8601 # stored process server port
objServerDef.Protocol = 2 # 2 = IOM protocol
objServerDef.BridgeSecurityPackage = "Username/Password"
objServerDef.ClassIdentifier = "stp server id"
objSAS = objFactory.CreateObjectByServer("SASApp", True, objServerDef, "uid", "pw")
objSAS.StoredProcessService.Repository("path", "stp", "params")
_list = objSAS.LanguageService.FlushList(999999)
print(_list)
log = objSAS.LanguageService.FlushLog(999999)
print(log)
objSAS.Close()
When trying the above I get:
AttributeError: CreateObjectByServer.StoredProcessService
I cant seem to find much documentation IOM to Stored Process Servers. Anyone got any suggestions?

process management with python: execute service or systemd or init.d script

How to efficiently and correctly manage processes with python. I want to run commands like:
/etc/init.d/daemon stop
service daemon start
systemctl restart daemon
Is there any python module available for this?
Any help will be highly appreciated.
I found a way using systemd dbus interface. Here is the code:
import dbus
import subprocess
import os
import sys
import time
SYSTEMD_BUSNAME = 'org.freedesktop.systemd1'
SYSTEMD_PATH = '/org/freedesktop/systemd1'
SYSTEMD_MANAGER_INTERFACE = 'org.freedesktop.systemd1.Manager'
SYSTEMD_UNIT_INTERFACE = 'org.freedesktop.systemd1.Unit'
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.systemd1.manage-units'
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation id
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
if result[1] != 0:
sys.exit("Need administrative privilege")
systemd_object = bus.get_object(SYSTEMD_BUSNAME, SYSTEMD_PATH)
systemd_manager = dbus.Interface(systemd_object, SYSTEMD_MANAGER_INTERFACE)
unit = systemd_manager.GetUnit('cups.service')
unit_object = bus.get_object(SYSTEMD_BUSNAME, unit)
#unit_interface = dbus.Interface(unit_object, SYSTEMD_UNIT_INTERFACE)
#unit_interface.Stop('replace')
systemd_manager.StartUnit('cups.service', 'replace')
while list(systemd_manager.ListJobs()):
time.sleep(2)
print 'there are pending jobs, lets wait for them to finish.'
prop_unit = dbus.Interface(unit_object, 'org.freedesktop.DBus.Properties')
active_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
sub_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'SubState')
print active_state, sub_state

How do I modify an existing vm template's only ethernet adapter's IP address with pyvmomi

Below is the code I think should be used to modify the network adapter IP of an ethernet adapter for a windows VM while cloning a VM from a template using pyvmomi and virtual center. It doesn't work, the VM clones but the network adapter is not modified. I only seem to be finding examples that assume there are no adapters at all and creating new ones. I could use some help figuring out what I'm doing wrong:
def clone_vm(
content, template, vm_name, si, ip,
datacenter_name, vm_folder, datastore_name,
cluster_name, resource_pool, power_on):
"""
Clone a VM from a template/VM, datacenter_name, vm_folder, datastore_name
cluster_name, resource_pool, and power_on are all optional.
"""
# if none git the first one
datacenter = get_obj(content, [vim.Datacenter], datacenter_name)
if vm_folder:
destfolder = get_obj(content, [vim.Folder], vm_folder)
else:
destfolder = datacenter.vmFolder
if datastore_name:
datastore = get_obj(content, [vim.Datastore], datastore_name)
else:
datastore = get_obj(
content, [vim.Datastore], template.datastore[0].info.name)
# if None, get the first one
cluster = get_obj(content, [vim.ClusterComputeResource], cluster_name)
if resource_pool:
resource_pool = get_obj(content, [vim.ResourcePool], resource_pool)
else:
resource_pool = cluster.resourcePool
# set relospec
relospec = vim.vm.RelocateSpec()
relospec.datastore = datastore
relospec.pool = resource_pool
deviceToChange = None
for device in template.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualEthernetCard):
deviceToChange = device
#guest NIC settings
nic = vim.vm.device.VirtualDeviceSpec()
nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit # or add to make a new one
nic.device = deviceToChange
nic.device.wakeOnLanEnabled = True
nic.device.addressType = 'assigned' #mac address assigned by virtual center
nic.device.key = 4000 # 4000 seems to be the value to use for a vmxnet3 device
# nic.device.deviceInfo = vim.Description()
# nic.device.deviceInfo.label = "Network Adapter"
# nic.device.deviceInfo.summary = "summary text here"
#"adapter map" no idea wtf this is
guest_map = vim.vm.customization.AdapterMapping()
guest_map.adapter = vim.vm.customization.IPSettings()
guest_map.adapter.ip = vim.vm.customization.FixedIp()
guest_map.adapter.ip.ipAddress = str(ip)
guest_map.adapter.subnetMask = str(subnet)
guest_map.adapter.gateway = str(gateway)
# DNS settings
globalip = vim.vm.customization.GlobalIPSettings()
globalip.dnsServerList = dns
# globalip.dnsSuffixList = ip_settings[0]['domain'] #do I need this? I don't think so
# Hostname settings
ident = vim.vm.customization.Sysprep()
ident.guiUnattended = vim.vm.customization.GuiUnattended()
ident.guiUnattended.autoLogon = False #the machine does not auto-logon
ident.guiUnattended.password = vim.vm.customization.Password()
ident.guiUnattended.password.value = vm_password
ident.guiUnattended.password.plainText = True #the password passed over is not encrypted
ident.userData = vim.vm.customization.UserData()
ident.userData.fullName = "Derek Chadwell"
ident.userData.orgName = "NetApp"
ident.userData.computerName = vim.vm.customization.FixedName()
ident.userData.computerName.name = vm_name
ident.identification = vim.vm.customization.Identification()
# create spec to change host IP address
customspec = vim.vm.customization.Specification()
customspec.nicSettingMap = [guest_map]
customspec.globalIPSettings = globalip
customspec.identity = ident
# VM config spec
vmconf = vim.vm.ConfigSpec()
#vmconf.numCPUs = deploy_settings['cpus']
#vmconf.memoryMB = deploy_settings['mem']
#vmconf.cpuHotAddEnabled = True
#vmconf.memoryHotAddEnabled = True
vmconf.deviceChange = [nic]
clonespec = vim.vm.CloneSpec()
clonespec.location = relospec
clonespec.config = vmconf
clonespec.customization = customspec
clonespec.powerOn = power_on
clonespec.template = False
print "cloning VM..."
task = template.Clone(folder=destfolder, name=vm_name, spec=clonespec)
wait_for_task(task)

How to create a VM (not clone) with a vmdk disk attached using Pyvmomi?

I am trying to create a new VM using Pyvmomi. I am successful creating the VM with RAM and CPU, but I cannot find docs on how to create this VM with a disk attached.
I am looking to create a VM with a 20GB thin provisioned HDD, but I cannot find documentation on how to do this.
This is what I am using:
import atexit
import hashlib
import json
import random
import time
import requests
from pyVim import connect
from pyVmomi import vim
from tools import tasks
vc_host = 'vc.example.com'
vc_user = 'john#example.com'
vc_ds = 'datastore1'
vc_password = 'secret'
def create_vm(name, service_instance, vm_folder, resource_pool,datastore):
vm_name = 'VM-' + name
datastore_path = '[' + datastore + '] ' + vm_name
# bare minimum VM shell, no disks. Feel free to edit
vmx_file = vim.vm.FileInfo(logDirectory=None,
snapshotDirectory=None,
suspendDirectory=None,
vmPathName=datastore_path)
config = vim.vm.ConfigSpec(
name=vm_name,
memoryMB=128,
numCPUs=1,
files=vmx_file,
guestId='dosGuest',
version='vmx-07'
)
print "Creating VM {}...".format(vm_name)
task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
tasks.wait_for_tasks(service_instance, [task])
def main():
name = 'testvm'
service_instance = connect.SmartConnect(host=vc_host,
user=vc_user,
pwd=vc_password,
)
if not service_instance:
print("Could not connect to the specified host using specified "
"username and password")
return -1
atexit.register(connect.Disconnect, service_instance)
content = service_instance.RetrieveContent()
datacenter = content.rootFolder.childEntity[0]
vmfolder = datacenter.vmFolder
hosts = datacenter.hostFolder.childEntity
resource_pool = hosts[0].resourcePool
create_vm(name, service_instance, vmfolder, resource_pool, vc_ds)
return 0
# Start program
if __name__ == "__main__":
main()
First create a VM:
datastore_path = '[datastore1] vm1'
vmx_file = vim.vm.FileInfo(logDirectory=None,
snapshotDirectory=None,
suspendDirectory=None,
vmPathName=datastore_path)
config = vim.vm.ConfigSpec(
name=vm_name,
memoryMB=2048,
numCPUs=cpu,
files=vmx_file,
guestId=None,
version='vmx-07'
)
hostobj = <get the esx host object>
vm_folder = hostobj.vm[0].parent
resource_pool = hostobj.vm[0].resourcePool
task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
Then reconfigure the VM by adding required devices:
spec = vim.vm.ConfigSpec()
scsi_ctr = vim.vm.device.VirtualDeviceSpec()
scsi_ctr.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
scsi_ctr.device = vim.vm.device.VirtualLsiLogicController()
scsi_ctr.device.deviceInfo = vim.Description()
scsi_ctr.device.slotInfo = vim.vm.device.VirtualDevice.PciBusSlotInfo()
scsi_ctr.device.slotInfo.pciSlotNumber = 16
scsi_ctr.device.controllerKey = 100
scsi_ctr.device.unitNumber = 3
scsi_ctr.device.busNumber = 0
scsi_ctr.device.hotAddRemove = True
scsi_ctr.device.sharedBus = 'noSharing'
scsi_ctr.device.scsiCtlrUnitNumber = 7
unit_number = 0
controller = scsi_ctr.device
disk_spec = vim.vm.device.VirtualDeviceSpec()
disk_spec.fileOperation = "create"
disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
disk_spec.device = vim.vm.device.VirtualDisk()
disk_spec.device.backing = \
vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
disk_spec.device.backing.diskMode = 'persistent'
disk_spec.device.backing.fileName = '[%s] %s/%s.vmdk' % \
( ds_name, client, vmdk_name )
disk_spec.device.unitNumber = unit_number
disk_spec.device.capacityInKB = <size in kb>
disk_spec.device.controllerKey = controller.key
dev_changes = []
dev_changes.append( scsi_ctr )
dev_changes.append( disk_spec )
spec.deviceChange = dev_changes
vmobj.ReconfigVM_Task( spec=spec )
I can't see what you have initialized in devices
So you can try something like this
vdisk_pec = vim.vm.device.VirtualDeviceSpec()
vdisk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
vdisk_spec.operation.backing = vim.vm.device.VirtualDisk.RawDiskVer2BackingInfo()
vdisk_spec.operation.backing.changeId = change_id
vdisk_spec.operation.backing.descriptorFileName = descriptor_file_name
then append vdisk_spec to your devices

Categories