See all of the unique IDs related to a vmware virtual machine - virtual-machine

I want to see all of the unique IDs that are specific for a virtual machine such as:
hardware ID, CPU ID, UUID , Mac address and etc.
could anybody please help me to find these IDs??

I can help you finding some of these. For rest of the things you have to search the doc.
Install pyVmomi and run the following code.
EDIT: Changed the code to run on esx host. Simply run it by python .py
Now to know how this code is working. You have to learn Manged Objects. For example here we are working with the Manged Object vm and this object has many properties listed in the doc. So to retrieve uuid of a vm we are invoking vm.config.uuid. Regarding other details you have to go through the VirtualMachine object see what all properties you nedd.
import sys
import atexit
import time
from pyVmomi import vim, vmodl
from pyVim.connect import Disconnect
from pyVim import connect
inputs = {'esx_ip': '15.22.10.10',
'esx_password': 'Password123',
'esx_user': 'root',
'vm_name': 'ubuntu',
}
def wait_for_task(task, actionName='job', hideResult=False):
"""
Waits and provides updates on a vSphere task
"""
while task.info.state == vim.TaskInfo.State.running:
time.sleep(2)
if task.info.state == vim.TaskInfo.State.success:
if task.info.result is not None and not hideResult:
out = '%s completed successfully, result: %s' % (actionName, task.info.result)
print out
else:
out = '%s completed successfully.' % actionName
print out
else:
out = '%s did not complete successfully: %s' % (actionName, task.info.error)
raise task.info.error
print out
return task.info.result
def get_obj(content, vimtype, name):
"""
Get the vsphere object associated with a given text 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
def main():
si = None
try:
print "Trying to connect ..."
si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'])
except IOError, e:
pass
if not si:
print "Cannot connect to specified host using specified username and password"
sys.exit()
print "Connected to vcenter!"
atexit.register(Disconnect, si)
content = si.RetrieveContent()
# Get the VirtualMachine Object
vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name'])
print "GuestID: ", vm.config.guestId
print "UUID: ", vm.config.uuid
print "Version: ", vm.config.version
for device in vm.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualEthernetCard):
print "MAC Address: ", device.macAddress
#Example of changing UUID:
new_uuid = '423ffff0-5d62-d040-248c-4538ae2c734f'
vmconf = vim.vm.ConfigSpec()
vmconf.uuid = new_uuid
task = vm.ReconfigVM_Task(vmconf)
wait_for_task(task, si)
print "Successfully changed UUID"
print "New UUID: ", vm.config.uuid
if __name__ == "__main__":
main()

Related

How to extract the [Documentation] text from Robot framework test case

I am trying to extract the content of the [Documentation] section as a string for comparision with other part in a Python script.
I was told to use Robot framework API https://robot-framework.readthedocs.io/en/stable/
to extract but I have no idea how.
However, I am required to work with version 3.1.2
Example:
*** Test Cases ***
ATC Verify that Sensor Battery can enable and disable manufacturing mode
[Documentation] E1: This is the description of the test 1
... E2: This is the description of the test 2
[Tags] E1 TRACE{Trace_of_E1}
... E2 TRACE{Trace_of_E2}
Extract the string as
E1: This is the description of the test 1
E2: This is the description of the test 2
Have a look at these examples. I did something similar to generate testplans descritio. I tried to adapt my code to your requirements and this could maybe work for you.
import os
import re
from robot.api.parsing import (
get_model, get_tokens, Documentation, EmptyLine, KeywordCall,
ModelVisitor, Token
)
class RobotParser(ModelVisitor):
def __init__(self):
# Create object with remarkup_text to store formated documentation
self.text = ''
def get_text(self):
return self.text
def visit_TestCase(self, node):
# The matched `TestCase` node is a block with `header` and
# `body` attributes. `header` is a statement with familiar
# `get_token` and `get_value` methods for getting certain
# tokens or their value.
for keyword in node.body:
# skip empty lines
if keyword.get_value(Token.DOCUMENTATION) == None:
continue
self.text += keyword.get_value(Token.ARGUMENT)
def visit_Documentation(self,node):
# The matched "Documentation" node with value
self.remarkup_text += node.value + self.new_line
def visit_File(self, node):
# Call `generic_visit` to visit also child nodes.
return self.generic_visit(node)
if __name__ == "__main__":
path = "../tests"
for filename in os.listdir(path):
if re.match(".*\.robot", filename):
model = get_model(os.path.join(path, filename))
robot_parser = RobotParser()
robot_parser.visit(model)
text=robot_parser._text()
The code marked as best answer didn't quite work for me and has a lot of redundancy but it inspired me enough to get into the parsing and write it in a much readable and efficient way that actually works as is. You just have to have your own way of generating & iterating through filesystem where you call the get_robot_metadata(filepath) function.
from robot.api.parsing import (get_model, ModelVisitor, Token)
class RobotParser(ModelVisitor):
def __init__(self):
self.testcases = {}
def visit_TestCase(self, node):
testcasename = (node.header.name)
self.testcases[testcasename] = {}
for section in node.body:
if section.get_value(Token.DOCUMENTATION) != None:
documentation = section.value
self.testcases[testcasename]['Documentation'] = documentation
elif section.get_value(Token.TAGS) != None:
tags = section.values
self.testcases[testcasename]['Tags'] = tags
def get_testcases(self):
return self.testcases
def get_robot_metadata(filepath):
if filepath.endswith('.robot'):
robot_parser = RobotParser()
model = get_model(filepath)
robot_parser.visit(model)
metadata = robot_parser.get_testcases()
return metadata
This function will be able to extract the [Documentation] section from the testcase:
def documentation_extractor(testcase):
documentation = []
for setting in testcase.settings:
if len(setting) > 2 and setting[1].lower() == "[documentation]":
for doc in setting[2:]:
if doc.startswith("#"):
# the start of a comment, so skip rest of the line
break
documentation.append(doc)
break
return "\n".join(documentation)

How can I remove messages from an ActiveMQ queue using Python?

I have an ActiveMQ queue which has several messages that were sent using persistent set to true. When I create a subscriber in Python to read the queue, I get all of the messages in the queue. The next time I open the subscriber, I get all of the same messages. I adjusted the code that writes to the queue to set persistent to false, but the message remains in the queue. Have I neglected to send an acknowledgement?
The code is written using Python 2.7 because that's what our customer is using. I'd love to upgrade them, but I don't have the time.
Here's the script that reads the queue:
import socket
import threading
import xml.etree.ElementTree as etree
from xml.dom import minidom # for pretty printing
# import SampleXML
import sys
import os
import math
import time
from time import monotonic
import string
import stomp # for queue support
import platform
class ConnectionListener(stomp.ConnectionListener):
def __init__(self, connection):
self.connection = connection
print ("Listener created")
def on_message(self, message):
print ("Received message with body ") + message.body
class Reader:
def __init__(self):
pass
def ConnectToQueue(self):
#For Production
user = os.getenv("ACTIVEMQ_USER") or "worthington"
#user = os.getenv("ACTIVEMQ_USER") or "worthington_test"
password = os.getenv("ACTIVEMQ_PASSWORD") or "level3"
host = os.getenv("ACTIVEMQ_HOST") or "localhost"
port = os.getenv("ACTIVEMQ_PORT") or 61613
# destination = sys.argv[1:2] or ["/topic/event"]
# destination = destination[0]
dest = "from_entec_test"
#For Production
# dest = "from_entec"
try:
conn = stomp.Connection10(host_and_ports = [(host, port)])
conn.set_listener('message', ConnectionListener(conn))
# conn.start()
# subscribe_id = '-'.join(map(str, (platform.node(), os.getppid(), os.getpid())))
conn.connect(login=user,passcode=password)
subscribe_id = "Queue Test Listener"
conn.subscribe(destination=dest, id=subscribe_id, ack='client-individual')
conn.unsubscribe(id=subscribe_id)
conn.disconnect()
except Exception as error:
reason = str(error)
print("Exception when readig data from queue: " + str(error))
pass
if __name__ == "__main__" :
try:
UploadData = Reader()
UploadData.ConnectToQueue()
print ("Reader finished.")
except Exception as Value:
reason = str(Value)
pass
And here's the code that writes to it:
import socket
import threading
import xml.etree.ElementTree as etree
from xml.dom import minidom # for pretty printing
# import SampleXML
import sys
import os
import math
import time
from time import monotonic
import string
import stomp # for queue support
import platform
class ConnectionListener(stomp.ConnectionListener):
def __init__(self, connection):
self.connection = connection
print "Listener created"
def on_message(self, message):
print "Received message with body " + message.body
class UploadData:
def __init__(self):
pass
def ConnectToQueue(self):
#For Production
user = os.getenv("ACTIVEMQ_USER") or "worthington"
#user = os.getenv("ACTIVEMQ_USER") or "worthington_test"
password = os.getenv("ACTIVEMQ_PASSWORD") or "level3"
host = os.getenv("ACTIVEMQ_HOST") or "localhost"
port = os.getenv("ACTIVEMQ_PORT") or 61613
# destination = sys.argv[1:2] or ["/topic/event"]
# destination = destination[0]
dest = "from_entec_test"
#For Production
# dest = "from_entec"
try:
conn = stomp.Connection10(host_and_ports = [(host, port)])
# conn.start()
# subscribe_id = '-'.join(map(str, (platform.node(), os.getppid(), os.getpid())))
subscribe_id = "Queue Test Listener"
conn.connect(login=user,passcode=password)
message = "This is a test message."
conn.send(dest, message, persistent='true')
print "Sent message containing: " + message
conn.disconnect()
except Exception, error:
reason = str(error)
print "Exception when writing data to queue: " + str(error)
pass
if __name__ == "__main__" :
try:
UploadData = UploadData()
UploadData.ConnectToQueue()
except Exception, Value:
reason = str(Value)
print "Main routine exception: " + str(Value)
pass
I'm not very familiar with Python STOMP clients but from the code you appear to be subscribing using the 'client-individual' mode of STOMP which means that each message you receive requires you to send an ACK frame back with the message Id value so that the remote can mark it as consumed. Since you are not doing that the messages will not be removed from the Queue.
As an alternative you can use the 'auto' acknowledgement mode which marks the message as consumed as soon as the broker dispatches them. To understand the STOMP subscription model please refer to the STOMP specification.

Freezing the time and date of an array of VMs

Is there a way to freeze the time and date of a VM, so that it is not synchronized with the guest BIOS and/or the internet? I have seen some solutions which talk about killing services inside the VM, but I wish to avoid this as it changes the "clean state" of the VM (used for testing purposes).
To clarify: I don't want to set the time offset for a VM, I want to set the exact time that will be passed to the OS at boot time.
From there, is there a way to do this across a large number of VMs?
Ended up solving the issue with a python script.
To use it, you edit the VM_NAMES list to contain the names of the VMs as they appear in VirtualBox, then set the RESET_TIME_VALUE according to the date and time you wish to send the VMs.
If you have installed VirtualBox in a non-default location, edit the VIRTUAL_BOX_MANAGE_PATH variable as well.
To run, call the main method.
import datetime
import subprocess
VIRTUAL_BOX_MANAGE_PATH = r"C:\Program Files\Oracle\VirtualBox\vboxmanage.exe"
SET_EXTRA_DATA_COMMAND = r"setextradata"
GET_HOST_TIME_DISABLE_COMMAND = "\"VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled\" \"1\""
MODIFY_VM_COMMAND = r"modifyvm"
BIOS_SYSTEM_TIME_OFFSET = r"--biossystemtimeoffset"
# Edit this list to add more Virtual Machines
VM_NAMES = ("xxx",
"yyy",
"zzz")
RESET_TIME_VALUE = datetime.datetime(2014, 6, 7, 13, 0, 0, 0)
def main():
for vm in VM_NAMES:
reset_time(vm)
disable_time_sync(vm)
def reset_time(vm_name):
"""
Resets the VM to the clean install time
"""
args = get_subprocess_args_set_bios_time(vm_name, RESET_TIME_VALUE)
print("Resetting time on VM [" + vm_name + "] to " + str(RESET_TIME_VALUE) + " ...")
subprocess.call(args)
print("\tDone.")
def disable_time_sync(vm_name):
"""
Disables the time synchronization of a VM with the BIOS
"""
args = [
VIRTUAL_BOX_MANAGE_PATH,
SET_EXTRA_DATA_COMMAND,
vm_name,
GET_HOST_TIME_DISABLE_COMMAND
]
print("Disabling time synchronization on VM [" + vm_name + "] ...")
subprocess.call(args)
print("\tDone.")
def get_subprocess_args_set_bios_time(vm_name, datetime_to_set):
"""
Returns a list containing the arguments to pass to the subprocess method
to start the Virtual Box Manage program and set the BIOS time to the supplied value
"""
return [
VIRTUAL_BOX_MANAGE_PATH,
MODIFY_VM_COMMAND,
vm_name,
BIOS_SYSTEM_TIME_OFFSET,
str(get_msec_time_difference(datetime.datetime.now(), datetime_to_set))
]
def get_msec_time_difference(reference_point, check_point):
"""
Computes the offset in msec from the reference point to the check point
"""
return int(round( (check_point - reference_point).total_seconds() * 1000 ))
" To run, call the main method."
..or just add at the end of the file
if __name__ == '__main__':
main()

SoapUI API - Setting TestCase property

I'm trying to use SoapUI API in jython (modifying SoapUILibrary for Robot Framework) and somehow i am not able to find any way to set property of a Property TestStep.
Setting project, global and system properties is easy using
SoapUITestCaseRunner.setProjectProperties()
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from robot.api import logger
class SoapUILibrary2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run. (...)
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
SoapUITestCaseRunner class does not contain any way to access testSteps...
I found some examples how to solve this issue in groovy, however is it possible to set such properties using SoapUI API?
EDIT:
Adding whole code of the library. It's made to be imported in robot framework and used as its keywords.
http://tny.cz/34882261
In SOAPUI you can define properties for project, testCase and testSuite, it's also possible to generate a special type of testStep (Properties TestStep) but you can't define properties on a specific testStep (i.e on SOAP TestStep). You can see more info about here
However you can use a properties from project, testCase or testSuite in your testSteps so i.e you can define a property in a project level and then use it in your testStep. I can't give more specific info because I don't know exactly what you're trying to achieve.
EDIT:
I don't know the specific jython syntax but If you have the project file (as I see in your sample) you can access a specific testStep through com.eviware.soapui.impl.wsdl.WsdlProject, I give you a groovy script as example:
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
def prj = new WsdlProject(path_prj_file,null);
def tsuite = prj.getTestSuiteByName("TestSuiteName");
def tcase = tsuite.getTestCaseByName("TestCaseName");
def tstep = tcase.getTestStepByName("TestStep");
EDIT 2:
I download jython standalone version 2.5.3 and use soapui 5.0.0 and works for me:
hw.py
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUILoadTestRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from com.eviware.soapui.impl.wsdl import (WsdlProject)
from com.eviware.soapui.impl.wsdl import (WsdlTestSuite)
from com.eviware.soapui.impl.wsdl.testcase import (WsdlTestCase)
from com.eviware.soapui.impl.wsdl.teststeps import (WsdlTestRequestStep)
import thread
class SoapUI2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
self.__prj = WsdlProject('C:\soapui_project.xml', None)
self.__tsuite = self.__prj.getTestSuiteByName("myTestSuite")
self.__tcase = self.__tsuite.getTestCaseByName("myTestCase")
self.__tstep = self.__tcase.getTestStepByName("myTestStep")
t = self.__tstep.getPropertyValue("Value")
print "Works ok"
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_multiproject(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUILoadTestRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run.
This assumes that you have already initialized the project via
the `SoapUI Project` keyword.
`properies` may contain multiple statements, and each must be specified as: key=value.
This is useful to data drive your existing SoapUI tests via property expansion.
For more information see: http://www.soapui.org/Scripting-Properties/property-expansion.html
Example:
| SoapUI Project | My Project |
| SoapUI Set Project Property | ServiceEndpoint=https://staging.company.com | # set a single property |
| SoapUI Set Project Property | CustomProperty=foo | AnotherProperty=bar | # or set multiple properties |
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
def soapui_set_multiproject_threads(self, t):
""" Sets number of threads to run in load test """
self.__runner.setThreadCount(long(t))
logger.info("Running with %s threads at once." % t)
def soapui_run(self):
""" Run the runner and report to Robot """
logger.info("Running with the following project properties set: %s" % self._project_properties)
if not self.__runner.run():
raise AssertionError('FAIL: failed to run')
if self.__runner == SoapUITestCaseRunner():
n = self.__runner.getFailedTests().size()
if n != 0:
raise AssertionError('FAIL: ' + str(n) + ' tests failed')
def soapui_start_mock_service(self, p, m):
""" Runs a mock service """
try:
self.__mockrunner = SoapUIMockServiceRunner()
self.__mockrunner.setProjectFile(p)
self.__mockrunner.setMockService(m)
self.__mockrunner.setBlock(False)
self.__mockrunner.run()
except Exception, e:
raise AssertionError('FAIL: Error running the mock service ' + m + '. Reason: ' + str(e))
def soapui_stop_mock_service(self):
""" Stops the mock service """
self.__mockrunner.stopAll()
def soapui_set_step_property(self, s, p,v):
testStep = self.__runner.testCase.getTestStepByName(s)
testStep.setPropertyValue(p,v)
if __name__ == "__main__":
SoapUI2().__init__()
cmd line execution:
java -classpath "jython-standalone-2.5.3.jar;C:\Programari\SoapUI-5.0.0\lib\*;C:\Programari\SoapUI-5.0.0\bin\*" org.python.util.jython hw.py
execution result:
2014-05-27 12:43:09,058 [main] WARN com.eviware.soapui.SoapUI - Could not find jfxrt.jar. Internal browser will be disabled.
12:43:09,589 WARN [SoapUI] Missing folder [C:\temp\ext] for external libraries
12:43:09,964 INFO [DefaultSoapUICore] initialized soapui-settings from [C:\Documents and Settings\aciffone\soapui-settings.xml]
12:43:09,995 INFO [HttpClientSupport$Helper] Initializing KeyStore
12:43:11,682 INFO [WsdlProject] Loaded project from [file:/C:/soapui_project.xml]
Works ok
Hope this helps,

debug in openerp6.1

I have added the following code in sale.py but I am unable to see output of print in
server.log. I wish to fill a one2many field by returned list of this function
I am using openerp6.1 under windows xp
my code is
def model_id_change(self,cr,uid,ids,model_id,context=None):
list1=[]
if context is None:
context = {}
print "Hi"
print str(model_id)
if not model_id:
raise osv.except_osv(_('No Model Selected !'),_('You have to select Model.'))
querystr = 'SELECT microswitch FROM product_model WHERE id = ' + model_id
print querystr
try:
cr.execute(querystr)
s=cr.fetchone()
print s
list1=[]
print list1
for t in s.split(','):
if t:
list1.append(t)
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
return(list1)
The print statement prints to standard output. If you want to get something in the server log, use the logging module.
import logging
logger = logging.getLogger(__name__)
logger.info('my message, with a substituted variable %s', s)