WMI querying issues in Python - python

I've recently been working on a Squish test script, and trying to do something like what's described in the solution at:
Total memory used by Python process?
The relevant snippets from my code are as follows:
def measureMemory():
w = wmi.WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE Name=\"some_program\"")
print result
for WorkingSet in result:
print WorkingSet
subset = result[0]
print subset['WorkingSet']
# return result[0]['WorkingSet']
for i in range(50):
memory = measureMemory()
if memory:
# test.passes("%d memory used during undo." % memory)
print memory
Unfortunately, I've run into an error whenever I actually try to run the thing, as can be seen below.
[<_wmi_object: \\USER-PC\root\cimv2:Win32_PerfRawData_PerfProc_Process.Name="some_program">]
instance of Win32_PerfRawData_PerfProc_Process
{
Name = "some_program";
WorkingSet = "19386368";
};
Traceback (most recent call last):
File "C:\Python26\Test scripts\Testify", line 25, in -toplevel-
memory = measureMemory()
File "C:\Python26\Test scripts\Testify", line 19, in measureMemory
print subset['WorkingSet']
File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 242, in __getitem__
raise TypeError("This object does not support enumeration")
TypeError: This object does not support enumeration
I'm not sure why this should be throwing an error, as I don't think I've changed anything significant from the example I took code from.
I'm using Python 2.4.4, if that's significant, and unfortunately I can't really upgrade, no matter how much it might help.

The WMI syntax seems to have changed from the examples. Try using subset.WorkingSet instead of subset['WorkingSet']

Related

how to use trigger.adddependencies in pyzabbix

i'm a newbie in python and coding,i'm trying to use pyzabbix to add trigger dependecies,but some error occusrs.
When i run
zapi.trigger.addDependencies(triggerid, dependsOnTriggerid)
an error occurs
pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist!', -32500)
i get the "triggerid" and "dependsOnTriggerid" by trigger.get:
triggerid_info = zapi.trigger.get(filter={'host': 'xx','description': 'xx'},output=['triggerid'], selectDependencies=['description'])
triggerid = triggerid_info[0]['triggerid']
dependsOnTriggerid = trigger_info[0]['dependencies'][0]['triggerid']
The results are as follws:
Traceback (most recent call last): File "E:/10.python/2019-03-07/1.py", line 14, in zapi.trigger.addDependencies(triggerid, dependsOnTriggerid) File "D:\Program Files\Python37\lib\site-packages\pyzabbix__init__.py", line 166, in fn args or kwargs File "D:\Program Files\Python37\lib\site-packages\pyzabbix__init__.py", line 143, in do_request raise ZabbixAPIException(msg, response_json['error']['code']) pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist!', -32500)
Did i get the wrong triggerid? or the i use the method in a wrong way? Thanks so much
To add a dependancy means that you need to link two different triggers (from the same host or from another one) with a master-dependent logic.
You are trying to add the dependancy triggerid -> dependsOnTriggerid, which is obtained from a supposed existing dependancy (trigger_info[0]['dependencies'][0]['triggerid']), and this makes little sense and I suppose it's the cause of the error.
You need to get both trigger's triggerid and then add the dependancy:
masterTriggerObj = zapi.trigger.get( /* filter to get your master trigger here */ )
dependentTriggerObj = zapi.trigger.get( /* filter to get your dependent trigger here */)
result = zapi.trigger.adddependencies(triggerid=dependentTriggerObj[0]['triggerid'], dependsOnTriggerid=masterTriggerObj[0]['triggerid'])
The method "trigger.addDependencies" need only one parameter,and it should be a dict or some other object/array.The following code solves the problem.
trigger_info = zapi.trigger.get(filter={xx},output=['triggerid'])
trigger_depends_info_193 = zapi.trigger.get(filter={xx},output=['triggerid'])
trigger_dependson_193 = {"triggerid": trigger_info[0]['triggerid'], "dependsOnTriggerid": trigger_depends_info_193[0]['triggerid']}
zapi.trigger.adddependencies(trigger_dependson_193)

Python: EOFError using cPickle while running a class instance

This is the code snippet causing the problem:
if str(sys.argv[2]) + '.pickle' in os.listdir(os.curdir): #os.path.isfile(str(sys.argv[2]) + '.pickle'):
path = sys.argv[2] + '.pickle'
#print path
instance = cPickle.load(open(str(path)))
This is the traceback:
Traceback (most recent call last):
File "parent_cls.py", line 92, in <module>
instance = cPickle.load(open(str(path)))
EOFError
If this keeps happening because of file.close() is not performed or some other ridiculous mistake, please let me know if there is a way to access the pickle file using subprocess. Thanks.
UPDATE: Another thing I notice. The filename.pickle to check if its there or not using the if condition actually is creating a filename.pickle although it wasn't there first.
I dont want to create it but to check its existence. is this some other problem?
Open it in binary mode :
open(str(path), 'rb')

Python : NameError: global name 'GetText' is not defined

I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!

Python NoneType _getitem_ error

I'm working with a pice of software written in python from US CERT to do some fuzzing. Included in the software is a minimizer.py tool which is designed to be ran against certain test cases that cause crashes in order to determine exactly which byte mutations are causing the crash.
However when attempting to run the tool it's spitting an error at me. Google searches for both the tool and the error are drawing a blank. Attempting to troubleshoot it myself with limited python experience is not helping either. Any ideas on whats causing the error so I can fix it and get the tool working?
command line options being used are: minimizer.py --stringmode
The error output is as follows:
Traceback (most recent call last):
File "C:\FOE2\tools\minimize.py", line 234, in <module>
main()
File "C:\FOE2\tools\minimize.py", line 183, in main
config = Config(cfg_file).config
File "C:\FOE2\certfuzz\campaign\config\__init__.py", line 76, in __init__
self._set_derived_options()
File "C:\FOE2\certfuzz\campaign\config\foe_config.py", line 93, in _set_derived_options
t = Template(self.config['target']['cmdline_template'])
TypeError: 'NoneType' object has no attribute '__getitem__'
Segments of code from both of the files in last two lines of error are:
__init__.py:
def __init__(self, config_file):
self.file = config_file
self.config = None
self.load()
self._set_derived_options()
self.validations = []
self._add_validations()
self.validate()
def _set_derived_options(self):
pass
And then from foe_config_.py (added the preceding lines of code just in case they are relevant.):
class Config(ConfigBase):
def _add_validations(self):
self.validations.append(self._validate_debugger_timeout_exceeds_runner)
def _set_derived_options(self):
# interpolate program name
# add quotes around $SEEDFILE
t = Template(self.config['target']['cmdline_template'])
#self.config['target']['cmdline_template'] = t.safe_substitute(PROGRAM=self.config['target']['program'])
self.config['target']['cmdline_template'] = t.safe_substitute(PROGRAM=quoted(self.config['target']['program']), SEEDFILE=quoted('$SEEDFILE'))
It's hard to tell from the code you posted, but it looks like __init__ sets self.config to None. Then it calls _set_derived_options which uses self.config here:
t = Template(self.config['target']['cmdline_template'])
But self.config hasn't changed from being None. You wouldn't expect None['target'] to give you anything (other than an Exception), but I think that is essentially what you're doing here.

Is it possible to serialize tasklet code (not just exec state) using SPickle without doing a RPC?

Trying to use stackless python (2.7.2) with SPickle to send a test method over celery for execution on a different machine. I would like the test method (code) to be included with the pickle and not forced to exist on the executing machines python path.
Been referencing following presentation:
https://ep2012.europython.eu/conference/talks/advanced-pickling-with-stackless-python-and-spickle
Trying to use the technique shown in the checkpointing slide 11. The RPC example doesn't seem right given that we are using celery:
Client code:
from stackless import run, schedule, tasklet
from sPickle import SPickleTools
def test_method():
print "hello from test method"
tasks = []
test_tasklet = tasklet(test_method)()
tasks.append(test_tasklet)
pt = SPickleTools(serializeableModules=['__test_method__'])
pickled_task = pt.dumps(tasks)
Server code:
pt = sPickle.SPickleTools()
unpickledTasks = pt.loads(pickled_task)
Results in:
[2012-03-09 14:24:59,104: ERROR/MainProcess] Task
celery_tasks.test_exec_method[8f462bd6-7952-4aa1-9adc-d84ee4a51ea6] raised exception:
AttributeError("'module'
object has no attribute 'test_method'",)
Traceback (most recent call last):
File "c:\Python27\lib\site-packages\celery\execute\trace.py", line 153, in trace_task
R = retval = task(*args, **kwargs)
File "c:\Python27\celery_tasks.py", line 16, in test_exec_method
unpickledTasks = pt.loads(pickled_task)
File "c:\Python27\lib\site-packages\sPickle\_sPickle.py", line 946, in loads
return unpickler.load()
AttributeError: 'module' object has no attribute 'test_method'
Any suggestions on what I am doing incorrect or if this is even possible?
Alternative suggestions for doing dynamic module loading in a celeryd would also be good (as an alternative for using sPickle). I have experimented with doing:
py_mod = imp.load_source(module_name,'some script path')
sys.modules.setdefault(module_name,py_mod)
but the dynamically loaded module does not seem to persist through different calls to celeryd, i.e. different remote calls.
You must define test_method within its own module. Currently sPickle detects whether test_method is defined in a module that can be imported. An alternative way is to set the __module__ attribute of the function to None.
def test_method():
pass
test_method.__module__ = None

Categories

Resources