VMWare pyvmomi 6.0.0 : Operation not supported - python

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.

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__

domainruntime() and CD('/') issue

I created a python file and created another shell file to prepare the environment to run the python script. Below is part of the python script including two functions and the error code.
I have the following Python code
def getState():
print "Getting Servers status..."
cd ('/')
allModules = cmo.getServers()
domainRuntime()
cnt = 0
modules = ""
for moduleName in allModules:
currentModule = moduleName.getName()
print ":: Current Server Name = " + currentModule
cd ('/')
slrBean = cmo.lookupServerLifeCycleRuntime(currentModule)
serverState = slrBean.getState()
print "Current Server status is: " + serverState
if serverState == "RUNNING" and (currentModule.find("amq")) != -1:
print "Shutting down AMQ managed server"
shutdown(currentModule, 'Server', 'true', 1000, force="true", block='true')
undeployApp()
ds(currentModule,moduleName)
elif (currentModule.find("amq")) != -1:
try:
print "ElseIf"
undeployApp()
except Exception, e:
print e
ds(currentModule,moduleName)
if (cnt == 0):
modules = currentModule
else:
modules = modules + "," + currentModule
cnt = cnt + 1
return modules
def ds(myModule,mo):
print "Deleting AMQ server"
cd('/Servers/'+myModule)
cmo.setCluster(None)
cmo.setMachine(None)
editService.getConfigurationManager().removeReferencesToBean(getMBean('/Servers/'+myModule))
cd('/')
cmo.destroyServer(getMBean('/Servers/'+myModule))
I am getting this error
Deleting AMQ server
This Exception occurred at Mon Oct 07 08:24:52 PDT 2019.
javax.management.AttributeNotFoundException: com.bea:Name=gems,Type=DomainRuntime:Servers
Problem invoking WLST - Traceback (innermost last):
File "/x/home/pegaadmin/test.py", line 233, in ?
File "/x/home/pegaadmin/test.py", line 107, in getState
File "/x/home/pegaadmin/test.py", line 118, in ds
File "<iostream>", line 164, in cd
File "<iostream>", line 552, in raiseWLSTException
WLSTException: Error cding to the MBean
Configuration failied, aborting .....
I can't figure out the domainruntime() and the correct path CD('/')
any solutions and suggestions please ?!

Trying to pull task information on an virtual machine entity

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) []
}

Error when using offlineimap: getfolder() asked for nonexisting folder

I'm trying to get my emails to work from commandline with mutt. I have been trying to follow these two guides: http://blog.developwithpassion.com/2013/05/02/getting-up-and-running-with-a-sane-mutt-setup/ and http://stevelosh.com/blog/2012/10/the-homely-mutt/#configuring-offlineimap
To do this there are 4 main steps:
1. setup offlineimap to download and keep synced your emails
2. setup mutt (the email user interface)
3. setup notmuch (to be able to search your emails)
4. setup msmtp (to be able to send emails)
Note that I am using Macbook Pro running the OS X 10.9.2. I am stuck at step 1 because I am getting an error with offlineimap! I am able to run offlineimap for a long time, i.e. it will sync all of the emails (36197 of them!) and then right at the end it spits out the following error:
ERROR: getfolder() asked for a nonexisting folder 'Drafts'.
Folder Deleted Items [acc: gloriphobia]:
Establishing connection to imap.gmail.com:993
Account sync gloriphobia:
*** Finished account 'gloriphobia' in 137:16
ERROR: Exceptions occurred during the run!
ERROR: command: UID => socket error: <class 'socket.error'> - [Errno 54] Connection reset by peer
Traceback:
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/folder/IMAP.py", line 219, in getmessage
'(BODY.PEEK[])')
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1167, in uid
return self._simple_command('UID', command, *args, **kw)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1615, in _simple_command
return self._command_complete(self._command(name, *args), kw)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1378, in _command_complete
typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 176, in get_response
raise typ(exc_fmt % str(val))
ERROR: getfolder() asked for a nonexisting folder 'Drafts'.
Traceback:
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 241, in syncrunner
self.sync()
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 320, in sync
localfolder = self.get_local_folder(remotefolder)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 269, in get_local_folder
replace(self.remoterepos.getsep(), self.localrepos.getsep()))
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/repository/Maildir.py", line 134, in getfolder
OfflineImapError.ERROR.FOLDER)
My .offlineimaprc is:
[general]
accounts = gloriphobia
ui = TTYUI
pythonfile=~/Development/MuttMailPython/offline.py
fsync = False
[Account gloriphobia]
localrepository = gloriphobia_local
remoterepository = gloriphobia_remote
status_backend = sqlite
postsynchook = notmuch new
[Repository gloriphobia_local]
type = Maildir
localfolders = ~/.mail/Test
nametrans = get_remote_name
[Repository gloriphobia_remote]
maxconnections = 1
type = Gmail
cert_fingerprint = 89091347184d41768bfc0da9fad94bfe882dd358
remoteuser = myemailaddress
remotepasseval = get_keychain_pass(account="myemailaddress",server="imap.gmail.com")
realdelete = no
nametrans = get_local_name
folderfilter = is_included
My python file, the one that is called offline.py is:
#!/usr/bin/python
import subprocess
import re
class NameMapping:
def __init__(self, local_name, remote_name):
self.local_name = local_name
self.remote_name = remote_name
class LocalName:
def __init__(self, folder):
self.folder = folder
def matches(self, mapping):
return mapping.remote_name == self.folder
def mapped_folder_name(self, mapping):
return mapping.local_name
class RemoteName:
def __init__(self, folder):
self.folder = folder
def matches(self, mapping):
return mapping.local_name == self.folder
def mapped_folder_name(self, mapping):
return mapping.remote_name
def get_keychain_pass(account=None, server=None):
params = {
'security': '/usr/bin/security',
'command': 'find-internet-password',
'account': account,
'server': server,
'keychain': '/Users/mec07/Library/Keychains/login.keychain',
}
command = "sudo -u mec07 %(security)s -v %(command)s -g -a %(account)s -s %(server)s %(keychain)s" % params
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
outtext = [l for l in output.splitlines()
if l.startswith('password: ')][0]
return re.match(r'password: "(.*)"', outtext).group(1)
def is_included(folder):
result = True
for pattern in exclusion_patterns:
result = result and (re.search(pattern, folder) == None)
return result
exclusion_patterns = [
"efax",
"earth_class_mail",
"eventbrite",
"gotomeeting",
"moshi_monsters",
"peepcode",
"raini_fowl",
"stuart_know",
"training.*2008",
"training.*2009",
"training.*2010",
"training.*2011",
"training.*2012",
"training.*nbdn",
"training.*nothin_but_bdd",
"unblock_us",
"web_hosting",
"webinars",
"Gmail.*Important"
]
name_mappings = [
NameMapping('inbox', '[Gmail]/Inbox'),
NameMapping('starred', '[Gmail]/Starred'),
NameMapping('important', '[Gmail]/Important'),
NameMapping('sent', '[Gmail]/Sent Mail'),
NameMapping('drafts', '[Gmail]/Drafts'),
NameMapping('archive', '[Gmail]/All Mail'),
NameMapping('spam', '[Gmail]/Spam'),
NameMapping('flagged', '[Gmail]/Starred'),
NameMapping('trash', '[Gmail]/Trash'),
NameMapping('deleted', '[Gmail]/Deleted Items'),
NameMapping('Mum', '[Gmail]/Jana'),
NameMapping('Maggie', '[Gmail]/Maggie'),
NameMapping('papers', '[Gmail]/Scholar Alert'),
NameMapping('sent items', '[Gmail]/Sent Items'),
NameMapping('sent messages', '[Gmail]/Sent Messages')
]
def find_name_mapping(name):
default_mapping = NameMapping(name.folder, name.folder)
for mapping in name_mappings:
if (name.matches(mapping)):
return mapping
return default_mapping
def get_name_mapping(name):
mapping = find_name_mapping(name)
return name.mapped_folder_name(mapping)
def get_remote_name(local_folder_name):
name = RemoteName(local_folder_name)
return get_name_mapping(name)
def get_local_name(remote_folder_name):
name = LocalName(remote_folder_name)
return get_name_mapping(name)
Thanks in advance for your help!
Add:
folderfilter = lambda folder: folder not in ['Drafts,]

Python win32com open OpenOffice Calc (.xls) spreadsheet through Task Scheduler

I am trying to open an existing .xls document with OpenOffice using the Python 2.7 win32com module. The following script runs perfectly through an interpreter:
from win32com import client
import time
import string
def pathnameToUrl( cPathname):
"""Convert a Windows or Linux pathname into an OOo URL."""
if len( cPathname ) > 1:
if cPathname[1:2] == ":":
cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
cPathname = string.replace( cPathname, "\\", "/" )
cPathname = "file://" + cPathname
return cPathname
def PropertyValueArray(num):
'''Creates an openoffice property value array'''
l = []
for x in range(num):
_p = manager.Bridge_GetStruct("com.sun.star.beans.PropertyValue")
_p.Name = ''
_p.Value = ''
l.append(_p)
return l
wbcpath = r"C:\myexcelfile.xls"
manager = client.DispatchEx("com.sun.star.ServiceManager")
desktop = manager.CreateInstance("com.sun.star.frame.Desktop")
manager._FlagAsMethod("Bridge_GetStruct")
manager._FlagAsMethod("Bridge_GetValueObject")
p = PropertyValueArray(1)
p[0].Name = 'Hidden' # doc should run hidden
p[0].Value = True # doc should run hidden
doc = desktop.loadComponentFromURL(pathnameToUrl(wbcpath), "_blank", 0, p)
doc.store()
time.sleep(5)
doc.dispose()
When I try to schedule this under Windows Task Scheduler on Windows Server Standard 2007 SP2 if get the following error:
Traceback (most recent call last):
File "D:\report_polygon_count.py", line 216, in <module>
manager = client.DispatchEx("com.sun.star.ServiceManager")
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\__init__.py", line 113, in DispatchEx
dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
com_error: (-2146959355, 'Server execution failed', None, None)
I am sure the issue is that the application wants to open a window and it is begin rejected because there is no user logged in. I have attempted to run it as hidden to avoid this issue. Is there a way to get round this or is it too ambitious?

Categories

Resources