Trying to pull task information on an virtual machine entity - python

If I run the below code in pycharm, I get this error:
--error--
C:\Python33\python.exe B:/Python/untitled3/working_test.py
'vim.VirtualMachine:vm-65063'
Traceback (most recent call last):
File "B:/Python/untitled3/working_test.py", line 47, in <module>
main()
File "B:/Python/untitled3/working_test.py", line 37, in main
filterspec = vim.TaskFilterSpec(vim.TaskFilterSpec.ByEntity(entity=source_machine))
TypeError: __init__() takes 1 positional argument but 2 were given
Process finished with exit code 1
--error--
I've tried using self, creating a class etc, but I just can't get my head around what I'm doing wrong. Any help is appreciated. I'm basically, trying to get task information on an entity (virtual machine) within vsphere.
Thanks!
import ssl
from pyVim import connect
from pyVmomi import vmodl, vim
def main():
try:
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_NONE
si = connect.SmartConnect(host='vcenter name',
user='user name',
pwd='password',
port=443,
sslContext=context)
if not si:
print("Could not connect to the specified host using specified "
"username and password")
return -1
content = si.RetrieveContent()
def getobject(vimtype, name):
obj = None
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
for c in container.view:
if c.name == name:
obj = c
break
return obj
source_machine = getobject([vim.VirtualMachine], 'virtual machine name')
print(source_machine)
taskManager = content.taskManager
filterspec = vim.TaskFilterSpec(vim.TaskFilterSpec.ByEntity(entity=source_machine))
collector = taskManager.CreateCollectorForTasks(filterspec)
except vmodl.MethodFault as e:
print("Caught vmodl fault : {}".format(e.msg))
return -1
return 0
if __name__ == "__main__":
main()

thank you for the help.
i've adjusted this portion of the code and it's returned back without errors, but looking into now, why it only seems to be returning the query task itself instead of the tasks pertaining to the vm. I think it may have something to do with the tasks being at a vcenter level, but working throug it now.
source_machine = getobject([vim.VirtualMachine], 'virtual machine name)
taskManager = content.taskManager
filterspec = vim.TaskFilterSpec()
filterspec.entity = vim.TaskFilterSpec.ByEntity(entity=source_machine,recursion='all')
collector = taskManager.CreateCollectorForTasks(filterspec)
print(collector)
output returned:
C:\Python33\python.exe B:/Python/untitled3/working_test.py
'vim.TaskHistoryCollector:session[52b617f0-0f65-705c-7462-814d8b648fdd]52081175-cb98-a09f-f9f6-f6787f68d3b7'
Process finished with exit code 0

vim.TaskFilterSpec() accepts no positional arguments. A minimal reproduction of the exception can be had with:
>>> vim.TaskFilterSpec(vim.TaskFilterSpec.ByEntity(entity=vim.ManagedEntity('1')))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
The class constructor vim.TaskFilterSpec() wants to be invoked with a entity named parameter. In your example code above, this would mean altering line 37 to read:
filterspec = vim.TaskFilterSpec(entity=vim.TaskFilterSpec.ByEntity(entity=source_machine))
When invoked with a placebo ManagedEntity, this results in a filter-spec similar to:
>>> source_machine=vim.ManagedEntity('1')
>>> filterspec = vim.TaskFilterSpec(entity=vim.TaskFilterSpec.ByEntity(entity=source_machine))
>>> filterspec
(vim.TaskFilterSpec) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
entity = (vim.TaskFilterSpec.ByEntity) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
entity = 'vim.ManagedEntity:1',
recursion = <unset>
},
time = <unset>,
userName = <unset>,
activationId = (str) [],
state = (vim.TaskInfo.State) [],
alarm = <unset>,
scheduledTask = <unset>,
eventChainId = (int) [],
tag = (str) [],
parentTaskKey = (str) [],
rootTaskKey = (str) []
}

Related

Spotify voice assistant attribute error __enter__

Hi there so I wanted to make a spotify voice assistant so I found a video on youtube and the guy just went through his code and how it works and left the source code on his github so I used that and configured it to work on my settings but i'm getting an attribute error enter with one of his lines and theres 3 files "main.py" "setup.txt" and "pepper.py" but the problem is in main so im gonna drop the code down below
main.py:
import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth
from pepper import *
# Set variables from setup.txt
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username)
spotify = sp.Spotify(auth_manager=auth_manager)
# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
d['name'] = d['name'].replace('’', '\'')
if d['name'] == device_name:
deviceID = d['id']
break
# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'Voicemod Virtual Audio Device (WDM)' # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
if microphone_name == input_mic:
m = Microphone(device_index=i)
while True:
"""
Commands will be entered in the specific format explained here:
- the first word will be one of: 'album', 'artist', 'play'
- then the name of whatever item is wanted
"""
with m as source:
r.adjust_for_ambient_noise(source=source)
audio = r.listen(source=source)
command = None
try:
command = r.recognize_google(audio_data=audio).lower()
except UnknownValueError:
continue
print(command)
words = command.split()
if len(words) <= 1:
print('Could not understand. Try again')
continue
name = ' '.join(words[1:])
try:
if words[0] == 'album':
uri = get_album_uri(spotify=spotify, name=name)
play_album(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'artist':
uri = get_artist_uri(spotify=spotify, name=name)
play_artist(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'play':
uri = get_track_uri(spotify=spotify, name=name)
play_track(spotify=spotify, device_id=deviceID, uri=uri)
else:
print('Specify either "album", "artist" or "play". Try Again')
except InvalidSearchError:
print('InvalidSearchError. Try Again')
the exact error is:
Traceback (most recent call last):
File "c:/Users/Yousif/Documents/Python spotify/main.py", line 49, in <module>
with m as source:
AttributeError: __enter__
__enter__ is a python method that allows you to implement objects that can be used easily with the with statement. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
The error here is caused because m = None, and None cannot be used in a with statement.
>>> with None as a:
... print(a)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __enter__

pyvim UpdateVirtualSwitch return "A specified parameter was not correct"

I'm trying to update virtual switch security setting via python but failing with message:
Traceback (most recent call last):
File "VPC_CRS-Compliance-Remediation-ESXi.py", line 787, in <module>
main()
File "VPC_CRS-Compliance-Remediation-ESXi.py", line 771, in main
current_setting(hosts, "check")
File "VPC_CRS-Compliance-Remediation-ESXi.py", line 653, in current_setting
host.configManager.networkSystem.UpdateVirtualSwitch(vswitchName="vSwitch0", spec=switch.spec)
File "/root/pydev/py36-venv/lib64/python3.6/site-packages/pyVmomi/VmomiSupport.py", line 706, in <lambda>
self.f(*(self.args + (obj,) + args), **kwargs)
File "/root/pydev/py36-venv/lib64/python3.6/site-packages/pyVmomi/VmomiSupport.py", line 512, in _InvokeMethod
return self._stub.InvokeMethod(self, info, args)
File "/root/pydev/py36-venv/lib64/python3.6/site-packages/pyVmomi/SoapAdapter.py", line 1374, in InvokeMethod
raise obj # pylint: disable-msg=E0702
pyVmomi.VmomiSupport.InvalidArgument: (vmodl.fault.InvalidArgument) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A specified parameter was not correct: ',
faultCause = <unset>,
faultMessage = (vmodl.LocalizableMessage) [],
invalidProperty = <unset>
I'm trying to set it like this:
for host in hosts:
if host.runtime.connectionState == 'connected':
#set_port_grp_security(host)
security_policy = vim.host.NetworkPolicy.SecurityPolicy()
security_policy.allowPromiscuous = False
security_policy.macChanges = False
security_policy.forgedTransmits = True
network_policy = vim.host.NetworkPolicy(security=security_policy)
switch = vim.host.VirtualSwitch.Config()
switch.spec = vim.host.VirtualSwitch.Specification()
switch.spec.policy = network_policy
a = host.config.network.vswitch
for i in a:
print(i.spec.policy.security.allowPromiscuous)
print(i.name)
host.configManager.networkSystem.UpdateVirtualSwitch(vswitchName=i.name, spec=switch.spec)
I can't find any example how this should be updated correctly anywhere everybody is either creating or removing stuff, nobody is updating :D any idea how to do it ?
This did it for me ( its called in function, parameter for function is a host object from vim.HostSystem):
switches = host.config.network.vswitch
# attept to set security policy
for vswitch in switches:
host_id = host.configManager.networkSystem
specs = vswitch.spec
specs.policy.security.allowPromiscuous = var_allowPromiscuous
specs.policy.security.macChanges = var_macChanges
specs.policy.security.forgedTransmits = var_forgedTransmits
host_id.UpdateVirtualSwitch(vswitchName=vswitch.name, spec=specs)
Took me for ever to figure out, hope it helps somebody....

Unable to construct python class

I have the following functions, that are working within the boundaries on the Python script
The loop_vcenters function will return a dictinary with cluster: host
subs_per_socket function will return the number of sockets for esx
def loop_vcenters(vcenters):
#------------------------- connect to vcenter ----------------------------------------
si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
# disconnect from vcenter one done
atexit.register(Disconnect, si)
#get the object content from vcenter
content = si.RetrieveContent()
#list clusters
cluster_host_dic_list=[]
cluster_name = ""
for cluster_obj in get_obj(content, vim.ComputeResource):
cluster=cluster_obj.name
hosts=[]
for host in cluster_obj.host:
hosts.append(host.name)
#create dictinary ,key=cluster value=esx
cluster_dic={cluster:hosts}
cluster_host_dic_list.append(cluster_dic)
return cluster_host_dic_list
def subs_per_socket(host):
shost = content.searchIndex.FindByDnsName(dnsName=host, vmSearch=False)
socket_count = shost.summary.hardware.numCpuPkgs
sub_per_socket = socket_count/2
return sub_per_socket
I want to put both functions into a class, but I cannot figure out how
class loop_vcenters:
def hosts_dic(self,name):
si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
atexit.register(Disconnect, si)
content = si.RetrieveContent()
cluster_host_dic_list=[]
cluster_name = ""
for cluster_obj in get_obj(content, vim.ComputeResource):
cluster=cluster_obj.name
hosts=[]
for host in cluster_obj.host:
hosts.append(host.name)
cluster_dic={cluster:hosts}
cluster_host_dic_list.append(cluster_dic)
return cluster_host_dic_list
I am unable to get the host dictionary like the loop_vcenters function returned.
d = loop_vcenters('vcenters')
Traceback (most recent call last):
File "", line 1, in
File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
How can I add the subs_per_socket(host) function to the class?
d = loop_vcenters('vcenters')
You are calling the class loop_vcenters with an argument when no init is defined.
File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
If you want to pass the argument to host_dic, you should be calling
d = loop_vcenters.host_dic('vcenters')
which will return cluster_host_dic_list to the variable d.
To add subs_per_socket(host), just define it under the class just as you did the other function.

VMWare pyvmomi 6.0.0 : Operation not supported

I am using VMWare's pyvmomi to manage my ESXI's virtual machines
I'm using :
pyvmomi-6.0.0 with python 2.7.5 to clone a VM on
VMWare ESXi 6.0.0 Update 1 which is managed by
vCenter Server 6
Using pyvmomi, i can successfully retrieve vm objects, iterate through datacenters, datastores, vm etc...
But i can't clone them.
I am connecting to my ESXi as root
I'm always getting the following error :
(I've tried cloning vms and creating folders on ESXI)
./test.py
Source VM : TEST_A
Pool cible : Pool_2
Traceback (most recent call last):
File "./vmomiTest.py", line 111, in <module>
sys.exit(main())
File "./vmomiTest.py", line 106, in main
tasks.wait_for_tasks(esxi, [task])
File "/home/user/dev/tools/tasks.py", line 53, in wait_for_tasks
raise task.info.error
pyVmomi.VmomiSupport.NotSupported: (vmodl.fault.NotSupported) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'The operation is not supported on the object.',
faultCause = <unset>,
faultMessage = (vmodl.LocalizableMessage) []
}
When I read by /var/log/hostd.log file on esxi, i get the following :
2016-09-13T10:15:17.775Z info hostd[51F85B70] [Originator#6876
sub=Vimsvc.TaskManager opID=467be296 user=root] Task Created :
haTask-2-vim.VirtualMachine.clone-416315
2016-09-13T10:15:17.779Z info
hostd[51F03B70] [Originator#6876 sub=Default opID=467be296 user=root]
AdapterServer caught exception: vmodl.fault.NotSupported
2016-09-13T10:15:17.779Z info hostd[51F03B70] [Originator#6876
sub=Vimsvc.TaskManager opID=467be296 user=root] Task Completed :
haTask-2-vim.VirtualMachine.clone-416315 Status error
Is there any other pre-requisites that i don't match ?
Has anyone any clue ?
Using the following test.py example code :
def get_obj_case_insensitive(content, vimtype, name, folder=None):
obj = None
if not folder:
folder = content.rootFolder
container = content.viewManager.CreateContainerView(folder, vimtype, True)
for item in container.view:
if item.name.lower() == name.lower():
obj = item
break
return obj
def get_obj(content, vimtype, name, folder=None):
obj = None
if not folder:
folder = content.rootFolder
container = content.viewManager.CreateContainerView(folder, vimtype, True)
for item in container.view:
if item.name == name:
obj = item
break
return obj
def main():
esxi = connect.SmartConnect(user=esxi_user,
pwd=esxi_password,
host=esxi_addr,
port=443)
atexit.register(connect.Disconnect, esxi)
content = esxi.RetrieveContent()
source_vm = get_obj(content, [vim.VirtualMachine], source_vm_name)
if source_vm == None:
print "Source VM %s doesn't exist, couldn't create VM" % source_vm_name
return None
print "Source VM Found : %s" % source_vm.config.name
wanted_pool = get_obj_case_insensitive(content, [vim.ResourcePool], wanted_pool_name)
if wanted_pool == None:
print "Resource Pool couldn't be found: Pool=%s" % wanted_pool_name
return None
else:
print "Pool Found : %s " % wanted_pool.name
new_location = vim.vm.RelocateSpec()
new_location.diskMoveType = 'createNewChildDiskBacking'
new_location.datastore = content.rootFolder.childEntity[0].datastore[0]
new_location.pool = wanted_pool
ESXI.ensure_snapshot_exists(source_vm)
clone_spec = vim.vm.CloneSpec(template=False, location=new_location, snapshot=source_vm.snapshot.rootSnapshotList[0].snapshot)
task = source_vm.Clone(name=dest_vm_name, folder=source_vm.parent, spec=clone_spec)
tasks.wait_for_tasks(esxi, [task])
print "Cloning %s into %s was successfull" % (source_vm.config.name, dest_vm_name)
if __name__ == '__main__':
sys.exit(main())
It appears this is because VMWARE has disabled many operations when directly connected to the ESXi.
Apparently, i should have connected to my vCenterServer in order to properly clone my VM.

AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'

I'm currently trying to use the pjsip api pjsua in python and therefor studying this Hello World example: http://trac.pjsip.org/repos/wiki/Python_SIP/Hello_World
I copied the code over, integrated account configuration according to http://trac.pjsip.org/repos/wiki/Python_SIP/Accounts etc. But when I run the sample, I get the following output:
Traceback (most recent call last):
File "/home/dmeli/workspace/eit.cubiephone.sip_test/eit/cubiephone/sip_test/hello.py", line 48, in <module>
acc = lib.create_account(acc_cfg)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2300, in create_account
err, acc_id = _pjsua.acc_add(acc_config._cvt_to_pjsua(), set_default)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 900, in _cvt_to_pjsua
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'
Because I'm not really a python expert and never worked with PJSIP before, I can't really figure out the error. Too me, it looks like it's actually an error in the pjsip python wrapper. But what do I know?
Code:
lib = pj.Lib()
lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
transport = lib.create_transport(pj.TransportType.UDP)
lib.start()
acc_cfg = pj.AccountConfig("XXXXX", "XXXXXX", "XXXXXX")
acc_cfg.id = "sip:XXXXXXX#XXXXXXXX"
acc_cfg.reg_uri = "sip:XXXXXXXXX"
acc_cfg.proxy = [ "sip:XXXXXXXXX;lr" ]
acc = lib.create_account(acc_cfg)
# Make call
call = acc.make_call("XXXXXXXXXXX", MyCallCallback())
Line where the error happens in pjsua.py:
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
(rtp_transport_cfg doesn't seem to have a member _cvt_to_pjsua()??)
For further work correctly, look at the PJSIP api (pjsua.py) that he is waiting for the order and structure!!!
## start lib.
def start(self):
try:
self._start_lib()
self._start_acc()
except pj.Error:
print "Error starting lib."
def _bind(self):
try:
t = pj.TransportConfig()
t.bound_addr = '0.0.0.0'
t.port = 5060
acc_transport = "udp" # depend if you need.
if acc_transport == "tcp":
self.transport = self.lib.create_transport(pj.TransportType.TCP, t)
# or this pj.TransportConfig(0) is creating random port ...
#self.transport = self.lib.create_transport(pj.TransportType.TCP, pj.TransportConfig(0))
else:
self.transport = self.lib.create_transport(pj.TransportType.UDP, t)
#self.transport = self.lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
except pj.Error:
print "Error creating transport."
#you need create callbacks for app, to work incoming calls, check on the server that returns the error code 200, and such a way your program will know that you are logged on correctly
#from callback.acc_cb import acc_cb
#self.acc_t = self.lib.create_account_for_transport(self.transport, cb=acc_cb())
def _start_lib(self):
self.lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
self.lib.start()
self._bind()
#codecs.load_codecs()
def _start_acc(self):
#from callback.acc_cb import acc_cb
try:
proxy = "sip server ip" # or proxy = socket.gethostbyname(unicode("sip.serverdnsname.com")) is needed to import socket
login = "Atrotygma" # real username
password = "Atrotygma_password" # real username
lib.create_account(acc_config=pj.AccountConfig(proxy, login, password))
except Exception, e:
print "Error creating account", e

Categories

Resources