domainruntime() and CD('/') issue - python

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 ?!

Related

Monitor CPU temperature in python on windows11

I have wrote a code to monitor ram memory usage, CPU memory usage, and CPU temperature I have used both psutil and WMI and I'm some kind of problem the code ran perfectly when I had windows 10 I updated to window 11 it is not working. I have checked python interpreter it is on 3.10
I get this my output/error message:
C:\Users\jeries\PycharmProjects\PP1\venv\Scripts\python.exe C:/Users/jeries/PycharmProjects/PP1/study.py
The CPU usage is: 47.1
RAM memory % used: 54.0
Traceback (most recent call last):
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\wmi.py", line 880, in query
return self._namespace.query(wql, self, fields)
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\wmi.py", line 1072, in query
return [ _wmi_object(obj, instance_of, fields) for obj in self._raw_query(wql) ]
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\wmi.py", line 1072, in <listcomp>
return [ _wmi_object(obj, instance_of, fields) for obj in self._raw_query(wql) ]
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\win32com\client\dynamic.py", line 324, in __getitem__
return self._get_good_object_(self._enum_.__getitem__(index))
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\win32com\client\util.py", line 41, in __getitem__
return self.__GetIndex(index)
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\win32com\client\util.py", line 62, in __GetIndex
result = self._oleobj_.Next(1)
pywintypes.com_error: (-2147217372, 'OLE error 0x80041024', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jeries\PycharmProjects\PP1\study.py", line 30, in <module>
temperature_infos = w.Sensor()
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\wmi.py", line 882, in query
handle_com_error()
File "C:\Users\jeries\PycharmProjects\PP1\venv\lib\site-packages\wmi.py", line 258, in handle_com_error
raise klass(com_error=err)
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217372, 'OLE error 0x80041024', None, None)>
Process finished with exit code 1
I have tried this:
w = wmi.WMI(namespace="root\openHardwareMonitor")
temperature_infos = w.Sensor()
for sensor in temperature_infos:
if sensor.SensorType == u'Temperature':
print(sensor.Name)
print(sensor.Value)
not working it says that the w.Senosor() "no documentation found"
this is my current code:
import os
import psutil
import wmi
def avg(value_list):
num = 0
length = len(value_list)
for val in value_list:
num += val
return num / length
# Calling psutil.cpu_precent() after 2 seconds
print('The CPU usage is: ', psutil.cpu_percent(2))
print('RAM memory % used:', psutil.virtual_memory()[2])
# have the open hardware monitor opened
w = wmi.WMI(namespace="root\\OpenHardwareMonitor")
sensors = w.Sensor()
cpu_temps = []
gpu_temp = 0
for sensor in sensors:
if sensor.SensorType == u'Temperature' and not 'GPU' in sensor.Name:
cpu_temps += [float(sensor.Value)]
elif sensor.SensorType == u'Temperature' and 'GPU' in sensor.Name:
gpu_temp = sensor.Value
print("Avg CPU: {}".format(avg(cpu_temps)))
print("GPU: {}".format(gpu_temp))
OpenHardwareMonitor can generate logs (options/log Sensors)
The log is called OpenHardwareMonitorLog-YYYY-MM-DD.csv
The idea is therefore to launch OpenHardwareMonitor beforehand (possible to execute via scheduled task + subprocess, or in automatic execution at startup), and to retrieve the correct column in the last line of the file:
#Code
from datetime import date
while 1 == 1:
#Génère le nom du log
now = date.today()
infile = r"C:\OpenHardwareMonitor\OpenHardwareMonitorLog-" + now.strftime("%Y-%m-%d") + ".csv"
#Ouvre en lecture seule
with open(infile, "r") as f:
f = f.readlines()[-1] #Lis la dernière ligne
output = f.split(',') # Sépare via les ","
print(output[10]) # 10 = Colonne T°CPU Core #1
edit:
You will have to find your column number by looking at the log, it's 10 for me, but it must be able to change depending on your config...
I'm just starting, the script should be able to be improved by scanning the first 2 lines and determining the correct column with its name ;-)

Change directory to each value of list

I am writing the below code:
connect('user', 'password', url='t3://host:1234')
domainConfig()
cd("JDBCSystemResources")
dataSources = cmo.getJDBCSystemResources()
if [len(dataSources) >0]:
mylist = []
for dataSource in dataSources:
dsName = dataSource.getName()
mylist.append(str(dsName))
mylist_len=len(mylist)
y=1
while(y <= mylist_len):
for dir in mylist:
cd(os.path.join(dir+'/JDBCResource/'+dir+'/JDBCResource/'+dir))
max_value = cmo.getMaxCapacity()
print dir+'='+str(max_cap)
cd('/')
y = y + 1
when I execute this code, it cd to only first value of the list and give this error
EssXADS=100
This Exception occurred at Sat Aug 21 08:41:53 UTC 2021.
javax.management.AttributeNotFoundException:
com.bea:Name=EssXADS,Location=FADomain,Type=weblogic.j2ee.descriptor.wl.JDBCConnectionPoolParamsBean,Parent=[FADomain]/JDBCSystemResources[EssXADS],Path=JDBCResource[EssXADS]/JDBCConnectionPoolParams:mds-ESS_MDS_DS
Problem invoking WLST - Traceback (innermost last): File
"/tmp/data_source_status_new.py.FS_bkp", line 16, in ? File
"", line 182, in cd File "", line 1878, in
raiseWLSTException WLSTException: Error cding to the MBean
Please help me to change the directory and perform the action on every value of list. I am running this on weblogic prompt.
you could use the os.path.join() function for this.
In your code it would look something like this,
for dir in mylist:
cd(os.path.join(dir,"some_dir",dir,"some_dir",dir))

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.

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