21.4. Using LMIShell
21.4.1. Starting, Using, and Exiting LMIShell
Starting LMIShell in Interactive Mode
lmishell command with no additional arguments:
lmishelllmishell command with the --noverify or -n command line option:
lmishell --noverifyUsing Tab Completion
Browsing History
~/.lmishell_history file. This allows you to browse the command history and re-use already entered lines in interactive mode without the need to type them at the prompt again. To move backward in the command history, press the Up Arrow key or the Ctrl+p key combination. To move forward in the command history, press the Down Arrow key or the Ctrl+n key combination.
> (reverse-i-search)`connect':c = connect("server.example.com", "pegasus")
clear_history() function as follows:
clear_history()history_length option in the ~/.lmishellrc configuration file. In addition, you can change the location of the history file by changing the value of the history_file option in this configuration file. For example, to set the location of the history file to ~/.lmishell_history and configure LMIShell to store the maximum of 1000 lines in it, add the following lines to the ~/.lmishellrc file:
history_file = "~/.lmishell_history" history_length = 1000
Handling Exceptions
use_exceptions() function as follows:
use_exceptions()use_exception(False)
use_exceptions option in the ~/.lmishellrc configuration file to True:
use_exceptions = True
Configuring a Temporary Cache
clear_cache() method as follows:
object_name.clear_cache()use_cache() method as follows:
object_name.use_cache(False)
object_name.use_cache(True)
use_cache option in the ~/.lmishellrc configuration file to False:
use_cache = False
Exiting LMIShell
quit() function as follows:
> quit()
~]$Running an LMIShell Script
lmishell command as follows:
lmishell file_name--interact or -i command line option:
lmishell --interact file_name.lmi.
21.4.2. Connecting to a CIMOM
Connecting to a Remote CIMOM
connect() function as follows:
connect(host_name, user_name[, password])LMIConnection object.
Example 21.1. Connecting to a Remote CIMOM
server.example.com as user pegasus, type the following at the interactive prompt:
> c = connect("server.example.com", "pegasus")
password:
>Connecting to a Local CIMOM
root user and the /var/run/tog-pegasus/cimxml.socket socket must exist.
connect() function as follows:
connect(host_name)localhost, 127.0.0.1, or ::1. The function returns an LMIConnection object or None.
Example 21.2. Connecting to a Local CIMOM
localhost as the root user, type the following at the interactive prompt:
> c = connect("localhost")
>Verifying a Connection to a CIMOM
connect() function returns either an LMIConnection object, or None if the connection could not be established. In addition, when the connect() function fails to establish a connection, it prints an error message to standard error output.
isinstance() function as follows:
isinstance(object_name,LMIConnection)
True if object_name is an LMIConnection object, or False otherwise.
Example 21.3. Verifying a Connection to a CIMOM
c variable created in Example 21.1, “Connecting to a Remote CIMOM” contains an LMIConnection object, type the following at the interactive prompt:
> isinstance(c, LMIConnection)
True
>c is not None:
> c is None
False
>21.4.3. Working with Namespaces
root namespace is the first entry point of a connection object.
Listing Available Namespaces
print_namespaces() method as follows:
object_name.print_namespaces()namespaces:
object_name.namespacesExample 21.4. Listing Available Namespaces
root namespace object of the c connection object created in Example 21.1, “Connecting to a Remote CIMOM” and list all available namespaces, type the following at the interactive prompt:
> c.root.print_namespaces()
cimv2
interop
PG_InterOp
PG_Internal
>root_namespaces, type:
> root_namespaces = c.root.namespaces
>Accessing Namespace Objects
object_name.namespace_name
LMINamespace object.
Example 21.5. Accessing Namespace Objects
cimv2 namespace of the c connection object created in Example 21.1, “Connecting to a Remote CIMOM” and assign it to a variable named ns, type the following at the interactive prompt:
> ns = c.root.cimv2
> 21.4.4. Working with Classes
Listing Available Classes
print_classes() method as follows:
namespace_object.print_classes()classes() method:
namespace_object.classes()Example 21.6. Listing Available Classes
ns namespace object created in Example 21.5, “Accessing Namespace Objects” and list all available classes, type the following at the interactive prompt:
> ns.print_classes()
CIM_CollectionInSystem
CIM_ConcreteIdentity
CIM_ControlledBy
CIM_DeviceSAPImplementation
CIM_MemberOfStatusCollection
...
>cimv2_classes, type:
> cimv2_classes = ns.classes()
>Accessing Class Objects
namespace_object.class_name
Example 21.7. Accessing Class Objects
LMI_IPNetworkConnection class of the ns namespace object created in Example 21.5, “Accessing Namespace Objects” and assign it to a variable named cls, type the following at the interactive prompt:
> cls = ns.LMI_IPNetworkConnection
>Examining Class Objects
class_object.classnameclass_object.namespacedoc() method as follows:
class_object.doc()Example 21.8. Examining Class Objects
cls class object created in Example 21.7, “Accessing Class Objects” and display its name and corresponding namespace, type the following at the interactive prompt:
>cls.classname'LMI_IPNetworkConnection' >cls.namespace'root/cimv2' >
> cls.doc()
Class: LMI_IPNetworkConnection
SuperClass: CIM_IPNetworkConnection
[qualifier] string UMLPackagePath: 'CIM::Network::IP'
[qualifier] string Version: '0.1.0'
...Listing Available Methods
print_methods() method as follows:
class_object.print_methods()methods() method:
class_object.methods()Example 21.9. Listing Available Methods
cls class object created in Example 21.7, “Accessing Class Objects” and list all available methods, type the following at the interactive prompt:
> cls.print_methods()
RequestStateChange
>service_methods, type:
> service_methods = cls.methods()
>Listing Available Properties
print_properties() method as follows:
class_object.print_properties()properties() method:
class_object.properties()Example 21.10. Listing Available Properties
cls class object created in Example 21.7, “Accessing Class Objects” and list all available properties, type the following at the interactive prompt:
> cls.print_properties()
RequestedState
HealthState
StatusDescriptions
TransitioningToState
Generation
...
>service_properties, type:
> service_properties = cls.properties()
>Listing and Viewing ValueMap Properties
print_valuemap_properties() method as follows:
class_object.print_valuemap_properties()valuemap_properties() method:
class_object.valuemap_properties()Example 21.11. Listing ValueMap Properties
cls class object created in Example 21.7, “Accessing Class Objects” and list all available ValueMap properties, type the following at the interactive prompt:
> cls.print_valuemap_properties()
RequestedState
HealthState
TransitioningToState
DetailedStatus
OperationalStatus
...
>service_valuemap_properties, type:
> service_valuemap_properties = cls.valuemap_properties()
>class_object.valuemap_propertyValuesprint_values() method as follows:
class_object.valuemap_propertyValues.print_values()
values() method:
class_object.valuemap_propertyValues.values()
Example 21.12. Accessing ValueMap Properties
RequestedState. To inspect this property and list available constant values, type the following at the interactive prompt:
> cls.RequestedStateValues.print_values()
Reset
NoChange
NotApplicable
Quiesce
Unknown
...
>requested_state_values, type:
> requested_state_values = cls.RequestedStateValues.values()
>class_object.valuemap_propertyValues.constant_value_namevalue() method as follows:
class_object.valuemap_propertyValues.value("constant_value_name")
value_name() method:
class_object.valuemap_propertyValues.value_name("constant_value")
Example 21.13. Accessing Constant Values
RequestedState property provides a constant value named Reset. To access this named constant value, type the following at the interactive prompt:
>cls.RequestedStateValues.Reset11 >cls.RequestedStateValues.value("Reset")11 >
> cls.RequestedStateValues.value_name(11)
u'Reset'
>Fetching a CIMClass Object
CIMClass object, which is why LMIShell only fetches this object from the CIMOM when a called method actually needs it. To fetch the CIMClass object manually, use the fetch() method as follows:
class_object.fetch()CIMClass object fetch it automatically.
21.4.5. Working with Instances
Accessing Instances
instances() method as follows:
class_object.instances()LMIInstance objects.
first_instance() method:
class_object.first_instance()LMIInstance object.
instances() and first_instance() support an optional argument to allow you to filter the results:
class_object.instances(criteria)class_object.first_instance(criteria)Example 21.14. Accessing Instances
cls class object created in Example 21.7, “Accessing Class Objects” that has the ElementName property equal to eth0 and assign it to a variable named device, type the following at the interactive prompt:
> device = cls.first_instance({"ElementName": "eth0"})
>Examining Instances
instance_object.classnameinstance_object.namespaceinstance_object.pathLMIInstanceName object.
doc() method as follows:
instance_object.doc()Example 21.15. Examining Instances
device instance object created in Example 21.14, “Accessing Instances” and display its class name and the corresponding namespace, type the following at the interactive prompt:
>device.classnameu'LMI_IPNetworkConnection' >device.namespace'root/cimv2' >
> device.doc()
Instance of LMI_IPNetworkConnection
[property] uint16 RequestedState = '12'
[property] uint16 HealthState
[property array] string [] StatusDescriptions
...Creating New Instances
create_instance() method as follows:
class_object.create_instance(properties)LMIInstance object.
Example 21.16. Creating New Instances
LMI_Group class represents system groups and the LMI_Account class represents user accounts on the managed system. To use the ns namespace object created in Example 21.5, “Accessing Namespace Objects”, create instances of these two classes for the system group named pegasus and the user named lmishell-user, and assign them to variables named group and user, type the following at the interactive prompt:
>group = ns.LMI_Group.first_instance({"Name" : "pegasus"})>user = ns.LMI_Account.first_instance({"Name" : "lmishell-user"})>
LMI_Identity class for the lmishell-user user, type:
> identity = user.first_associator(ResultClass="LMI_Identity")
>LMI_MemberOfGroup class represents system group membership. To use the LMI_MemberOfGroup class to add the lmishell-user to the pegasus group, create a new instance of this class as follows:
>ns.LMI_MemberOfGroup.create_instance({..."Member" : identity.path,..."Collection" : group.path})LMIInstance(classname="LMI_MemberOfGroup", ...) >
Deleting Individual Instances
delete() method as follows:
instance_object.delete()Example 21.17. Deleting Individual Instances
LMI_Account class represents user accounts on the managed system. To use the ns namespace object created in Example 21.5, “Accessing Namespace Objects”, create an instance of the LMI_Account class for the user named lmishell-user, and assign it to a variable named user, type the following at the interactive prompt:
> user = ns.LMI_Account.first_instance({"Name" : "lmishell-user"})
>lmishell-user from the system, type:
> user.delete()
True
>Listing and Accessing Available Properties
print_properties() method as follows:
instance_object.print_properties()properties() method:
instance_object.properties()Example 21.18. Listing Available Properties
device instance object created in Example 21.14, “Accessing Instances” and list all available properties, type the following at the interactive prompt:
> device.print_properties()
RequestedState
HealthState
StatusDescriptions
TransitioningToState
Generation
...
>device_properties, type:
> device_properties = device.properties()
>instance_object.property_name
instance_object.property_name = value
push() method:
instance_object.push()Example 21.19. Accessing Individual Properties
device instance object created in Example 21.14, “Accessing Instances” and display the value of the property named SystemName, type the following at the interactive prompt:
> device.SystemName
u'server.example.com'
>Listing and Using Available Methods
print_methods() method as follows:
instance_object.print_methods()method() method:
instance_object.methods()Example 21.20. Listing Available Methods
device instance object created in Example 21.14, “Accessing Instances” and list all available methods, type the following at the interactive prompt:
> device.print_methods()
RequestStateChange
>network_device_methods, type:
> network_device_methods = device.methods()
>instance_object.method_name(
parameter=value,
...)Important
LMIInstance objects do not automatically refresh their contents (properties, methods, qualifiers, and so on). To do so, use the refresh() method as described below.
Example 21.21. Using Methods
PG_ComputerSystem class represents the system. To create an instance of this class by using the ns namespace object created in Example 21.5, “Accessing Namespace Objects” and assign it to a variable named sys, type the following at the interactive prompt:
> sys = ns.PG_ComputerSystem.first_instance()
>LMI_AccountManagementService class implements methods that allow you to manage users and groups in the system. To create an instance of this class and assign it to a variable named acc, type:
> acc = ns.LMI_AccountManagementService.first_instance()
>lmishell-user in the system, use the CreateAccount() method as follows:
> acc.CreateAccount(Name="lmishell-user", System=sys)
LMIReturnValue(rval=0, rparams=NocaseDict({u'Account': LMIInstanceName(classname="LMI_Account"...), u'Identities': [LMIInstanceName(classname="LMI_Identity"...), LMIInstanceName(classname="LMI_Identity"...)]}), errorstr='')LMI_StorageJobLMI_SoftwareInstallationJobLMI_NetworkJob
instance_object.Syncmethod_name(
parameter=value,
...)Sync prefix in their name and return a three-item tuple consisting of the job's return value, job's return value parameters, and job's error string.
PreferPolling parameter as follows:
instance_object.Syncmethod_name(PreferPolling=Trueparameter=value, ...)
Listing and Viewing ValueMap Parameters
print_valuemap_parameters() method as follows:
instance_object.method_name.print_valuemap_parameters()valuemap_parameters() method:
instance_object.method_name.valuemap_parameters()Example 21.22. Listing ValueMap Parameters
acc instance object created in Example 21.21, “Using Methods” and list all available ValueMap parameters of the CreateAccount() method, type the following at the interactive prompt:
> acc.CreateAccount.print_valuemap_parameters()
CreateAccount
>create_account_parameters, type:
> create_account_parameters = acc.CreateAccount.valuemap_parameters()
>instance_object.method_name.valuemap_parameterValuesprint_values() method as follows:
instance_object.method_name.valuemap_parameterValues.print_values()
values() method:
instance_object.method_name.valuemap_parameterValues.values()
Example 21.23. Accessing ValueMap Parameters
CreateAccount. To inspect this parameter and list available constant values, type the following at the interactive prompt:
> acc.CreateAccount.CreateAccountValues.print_values()
Operationunsupported
Failed
Unabletosetpasswordusercreated
Unabletocreatehomedirectoryusercreatedandpasswordset
Operationcompletedsuccessfully
>create_account_values, type:
> create_account_values = acc.CreateAccount.CreateAccountValues.values()
>instance_object.method_name.valuemap_parameterValues.constant_value_namevalue() method as follows:
instance_object.method_name.valuemap_parameterValues.value("constant_value_name")
value_name() method:
instance_object.method_name.valuemap_parameterValues.value_name("constant_value")
Example 21.24. Accessing Constant Values
CreateAccount ValueMap parameter provides a constant value named Failed. To access this named constant value, type the following at the interactive prompt:
>acc.CreateAccount.CreateAccountValues.Failed2 >acc.CreateAccount.CreateAccountValues.value("Failed")2 >
> acc.CreateAccount.CreateAccountValues.value_name(2)
u'Failed'
>Refreshing Instance Objects
refresh() method as follows:
instance_object.refresh()Example 21.25. Refreshing Instance Objects
device instance object created in Example 21.14, “Accessing Instances”, type the following at the interactive prompt:
> device.refresh()
LMIReturnValue(rval=True, rparams=NocaseDict({}), errorstr='')
>Displaying MOF Representation
tomof() method as follows:
instance_object.tomof()Example 21.26. Displaying MOF Representation
device instance object created in Example 21.14, “Accessing Instances”, type the following at the interactive prompt:
> device.tomof()
instance of LMI_IPNetworkConnection {
RequestedState = 12;
HealthState = NULL;
StatusDescriptions = NULL;
TransitioningToState = 12;
...21.4.6. Working with Instance Names
Accessing Instance Names
CIMInstance objects are identified by CIMInstanceName objects. To get a list of all available instance name objects, use the instance_names() method as follows:
class_object.instance_names()LMIInstanceName objects.
first_instance_name() method:
class_object.first_instance_name()LMIInstanceName object.
instance_names() and first_instance_name() support an optional argument to allow you to filter the results:
class_object.instance_names(criteria)class_object.first_instance_name(criteria)Example 21.27. Accessing Instance Names
cls class object created in Example 21.7, “Accessing Class Objects” that has the Name key property equal to eth0 and assign it to a variable named device_name, type the following at the interactive prompt:
> device_name = cls.first_instance_name({"Name": "eth0"})
>Examining Instance Names
instance_name_object.classnameinstance_name_object.namespaceExample 21.28. Examining Instance Names
device_name instance name object created in Example 21.27, “Accessing Instance Names” and display its class name and the corresponding namespace, type the following at the interactive prompt:
>device_name.classnameu'LMI_IPNetworkConnection' >device_name.namespace'root/cimv2' >
Creating New Instance Names
CIMInstanceName object if you know all primary keys of a remote object. This instance name object can then be used to retrieve the whole instance object.
new_instance_name() method as follows:
class_object.new_instance_name(key_properties)LMIInstanceName object.
Example 21.29. Creating New Instance Names
LMI_Account class represents user accounts on the managed system. To use the ns namespace object created in Example 21.5, “Accessing Namespace Objects” and create a new instance name of the LMI_Account class representing the lmishell-user user on the managed system, type the following at the interactive prompt:
>instance_name = ns.LMI_Account.new_instance_name({..."CreationClassName" : "LMI_Account",..."Name" : "lmishell-user",..."SystemCreationClassName" : "PG_ComputerSystem",..."SystemName" : "server"})>
Listing and Accessing Key Properties
print_key_properties() method as follows:
instance_name_object.print_key_properties()key_properties() method:
instance_name_object.key_properties()Example 21.30. Listing Available Key Properties
device_name instance name object created in Example 21.27, “Accessing Instance Names” and list all available key properties, type the following at the interactive prompt:
> device_name.print_key_properties()
CreationClassName
SystemName
Name
SystemCreationClassName
>device_name_properties, type:
> device_name_properties = device_name.key_properties()
>instance_name_object.key_property_name
Example 21.31. Accessing Individual Key Properties
device_name instance name object created in Example 21.27, “Accessing Instance Names” and display the value of the key property named SystemName, type the following at the interactive prompt:
> device_name.SystemName
u'server.example.com'
>Converting Instance Names to Instances
to_instance() method as follows:
instance_name_object.to_instance()LMIInstance object.
Example 21.32. Converting Instance Names to Instances
device_name instance name object created in Example 21.27, “Accessing Instance Names” to an instance object and assign it to a variable named device, type the following at the interactive prompt:
> device = device_name.to_instance()
>21.4.7. Working with Associated Objects
Accessing Associated Instances
associators() method as follows:
instance_object.associators(AssocClass=class_name,ResultClass=class_name,ResultRole=role,IncludeQualifiers=include_qualifiers,IncludeClassOrigin=include_class_origin,PropertyList=property_list)
first_associator() method:
instance_object.first_associator(AssocClass=class_name,ResultClass=class_name,ResultRole=role,IncludeQualifiers=include_qualifiers,IncludeClassOrigin=include_class_origin,PropertyList=property_list)
AssocClass— Each returned object must be associated with the source object through an instance of this class or one of its subclasses. The default value isNone.ResultClass— Each returned object must be either an instance of this class or one of its subclasses, or it must be this class or one of its subclasses. The default value isNone.Role— Each returned object must be associated with the source object through an association in which the source object plays the specified role. The name of the property in the association class that refers to the source object must match the value of this parameter. The default value isNone.ResultRole— Each returned object must be associated with the source object through an association in which the returned object plays the specified role. The name of the property in the association class that refers to the returned object must match the value of this parameter. The default value isNone.
IncludeQualifiers— A boolean indicating whether all qualifiers of each object (including qualifiers on the object and on any returned properties) should be included as QUALIFIER elements in the response. The default value isFalse.IncludeClassOrigin— A boolean indicating whether the CLASSORIGIN attribute should be present on all appropriate elements in each returned object. The default value isFalse.PropertyList— The members of this list define one or more property names. Returned objects will not include elements for any properties missing from this list. IfPropertyListis an empty list, no properties are included in returned objects. If it isNone, no additional filtering is defined. The default value isNone.
Example 21.33. Accessing Associated Instances
LMI_StorageExtent class represents block devices available in the system. To use the ns namespace object created in Example 21.5, “Accessing Namespace Objects”, create an instance of the LMI_StorageExtent class for the block device named /dev/vda, and assign it to a variable named vda, type the following at the interactive prompt:
>vda = ns.LMI_StorageExtent.first_instance({..."DeviceID" : "/dev/vda"})>
vda_partitions, use the associators() method as follows:
> vda_partitions = vda.associators(ResultClass="LMI_DiskPartition")
> Accessing Associated Instance Names
associator_names() method as follows:
instance_object.associator_names(AssocClass=class_name,ResultClass=class_name,Role=role,ResultRole=role)
first_associator_name() method:
instance_object.first_associator_name(AssocClass=class_object,ResultClass=class_object,Role=role,ResultRole=role)
AssocClass— Each returned name identifies an object that must be associated with the source object through an instance of this class or one of its subclasses. The default value isNone.ResultClass— Each returned name identifies an object that must be either an instance of this class or one of its subclasses, or it must be this class or one of its subclasses. The default value isNone.Role— Each returned name identifies an object that must be associated with the source object through an association in which the source object plays the specified role. The name of the property in the association class that refers to the source object must match the value of this parameter. The default value isNone.ResultRole— Each returned name identifies an object that must be associated with the source object through an association in which the returned named object plays the specified role. The name of the property in the association class that refers to the returned object must match the value of this parameter. The default value isNone.
Example 21.34. Accessing Associated Instance Names
vda instance object created in Example 21.33, “Accessing Associated Instances”, get a list of its associated instance names, and assign it to a variable named vda_partitions, type:
> vda_partitions = vda.associator_names(ResultClass="LMI_DiskPartition")
>21.4.8. Working with Association Objects
Accessing Association Instances
references() method as follows:
instance_object.references(ResultClass=class_name,Role=role,IncludeQualifiers=include_qualifiers,IncludeClassOrigin=include_class_origin,PropertyList=property_list)
first_reference() method:
instance_object.first_reference( ...ResultClass=class_name, ...Role=role, ...IncludeQualifiers=include_qualifiers, ...IncludeClassOrigin=include_class_origin, ...PropertyList=property_list) >
ResultClass— Each returned object must be either an instance of this class or one of its subclasses, or it must be this class or one of its subclasses. The default value isNone.Role— Each returned object must refer to the target object through a property with a name that matches the value of this parameter. The default value isNone.
IncludeQualifiers— A boolean indicating whether each object (including qualifiers on the object and on any returned properties) should be included as a QUALIFIER element in the response. The default value isFalse.IncludeClassOrigin— A boolean indicating whether the CLASSORIGIN attribute should be present on all appropriate elements in each returned object. The default value isFalse.PropertyList— The members of this list define one or more property names. Returned objects will not include elements for any properties missing from this list. IfPropertyListis an empty list, no properties are included in returned objects. If it isNone, no additional filtering is defined. The default value isNone.
Example 21.35. Accessing Association Instances
LMI_LANEndpoint class represents a communication endpoint associated with a certain network interface device. To use the ns namespace object created in Example 21.5, “Accessing Namespace Objects”, create an instance of the LMI_LANEndpoint class for the network interface device named eth0, and assign it to a variable named lan_endpoint, type the following at the interactive prompt:
>lan_endpoint = ns.LMI_LANEndpoint.first_instance({..."Name" : "eth0"})>
LMI_BindsToLANEndpoint object and assign it to a variable named bind, type:
>bind = lan_endpoint.first_reference(...ResultClass="LMI_BindsToLANEndpoint")>
Dependent property to access the dependent LMI_IPProtocolEndpoint class that represents the IP address of the corresponding network interface device:
>ip = bind.Dependent.to_instance()>print ip.IPv4Address192.168.122.1 >
Accessing Association Instance Names
reference_names() method as follows:
instance_object.reference_names(ResultClass=class_name,Role=role)
first_reference_name() method:
instance_object.first_reference_name(ResultClass=class_name,Role=role)
ResultClass— Each returned object name identifies either an instance of this class or one of its subclasses, or this class or one of its subclasses. The default value isNone.Role— Each returned object identifies an object that refers to the target instance through a property with a name that matches the value of this parameter. The default value isNone.
Example 21.36. Accessing Association Instance Names
lan_endpoint instance object created in Example 21.35, “Accessing Association Instances”, access the first association instance name that refers to an LMI_BindsToLANEndpoint object, and assign it to a variable named bind, type:
>bind = lan_endpoint.first_reference_name(...ResultClass="LMI_BindsToLANEndpoint")
Dependent property to access the dependent LMI_IPProtocolEndpoint class that represents the IP address of the corresponding network interface device:
>ip = bind.Dependent.to_instance()>print ip.IPv4Address192.168.122.1 >
21.4.9. Working with Indications
Subscribing to Indications
subscribe_indication() method as follows:
connection_object.subscribe_indication(QueryLanguage="WQL",Query='SELECT * FROM CIM_InstModification',Name="cpu",CreationNamespace="root/interop",SubscriptionCreationClassName="CIM_IndicationSubscription",FilterCreationClassName="CIM_IndicationFilter",FilterSystemCreationClassName="CIM_ComputerSystem",FilterSourceNamespace="root/cimv2",HandlerCreationClassName="CIM_IndicationHandlerCIMXML",HandlerSystemCreationClassName="CIM_ComputerSystem",Destination="http://host_name:5988")
connection_object.subscribe_indication(Query='SELECT * FROM CIM_InstModification',Name="cpu",Destination="http://host_name:5988")
Permanent=True keyword parameter to the subscribe_indication() method call. This will prevent LMIShell from deleting the subscription.
Example 21.37. Subscribing to Indications
c connection object created in Example 21.1, “Connecting to a Remote CIMOM” and subscribe to an indication named cpu, type the following at the interactive prompt:
>c.subscribe_indication(...QueryLanguage="WQL",...Query='SELECT * FROM CIM_InstModification',...Name="cpu",...CreationNamespace="root/interop",...SubscriptionCreationClassName="CIM_IndicationSubscription",...FilterCreationClassName="CIM_IndicationFilter",...FilterSystemCreationClassName="CIM_ComputerSystem",...FilterSourceNamespace="root/cimv2",...HandlerCreationClassName="CIM_IndicationHandlerCIMXML",...HandlerSystemCreationClassName="CIM_ComputerSystem",...Destination="http://server.example.com:5988")LMIReturnValue(rval=True, rparams=NocaseDict({}), errorstr='') >
Listing Subscribed Indications
print_subscribed_indications() method as follows:
connection_object.print_subscribed_indications()subscribed_indications() method:
connection_object.subscribed_indications()Example 21.38. Listing Subscribed Indications
c connection object created in Example 21.1, “Connecting to a Remote CIMOM” and list all subscribed indications, type the following at the interactive prompt:
> c.print_subscribed_indications()
>indications, type:
> indications = c.subscribed_indications()
>Unsubscribing from Indications
unsubscribe_indication() method as follows:
connection_object.unsubscribe_indication(indication_name)unsubscribe_all_indications() method:
connection_object.unsubscribe_all_indications()Example 21.39. Unsubscribing from Indications
c connection object created in Example 21.1, “Connecting to a Remote CIMOM” and unsubscribe from the indication created in Example 21.37, “Subscribing to Indications”, type the following at the interactive prompt:
> c.unsubscribe_indication('cpu')
LMIReturnValue(rval=True, rparams=NocaseDict({}), errorstr='')
>Implementing an Indication Handler
subscribe_indication() method allows you to specify the host name of the system you want to deliver the indications to. The following example shows how to implement an indication handler:
>def handler(ind, arg1, arg2, **kwargs):...exported_objects = ind.exported_objects()...do_something_with(exported_objects)>listener = LmiIndicationListener("0.0.0.0", listening_port)>listener.add_handler("indication-name-XXXXXXXX", handler, arg1, arg2, **kwargs)>listener.start()>
LmiIndication object, which contains a list of methods and objects exported by the indication. Other parameters are user specific: those arguments need to be specified when adding a handler to the listener.
add_handler() method call uses a special string with eight “X” characters. These characters are replaced with a random string that is generated by listeners in order to avoid a possible handler name collision. To use the random string, start the indication listener first and then subscribe to an indication so that the Destination property of the handler object contains the following value: schema://host_name/random_string.
Example 21.40. Implementing an Indication Handler
192.168.122.1 and calls the indication_callback() function whenever a new user account is created:
#!/usr/bin/lmishell
import sys
from time import sleep
from lmi.shell.LMIUtil import LMIPassByRef
from lmi.shell.LMIIndicationListener import LMIIndicationListener
# These are passed by reference to indication_callback
var1 = LMIPassByRef("some_value")
var2 = LMIPassByRef("some_other_value")
def indication_callback(ind, var1, var2):
# Do something with ind, var1 and var2
print ind.exported_objects()
print var1.value
print var2.value
c = connect("hostname", "username", "password")
listener = LMIIndicationListener("0.0.0.0", 65500)
unique_name = listener.add_handler(
"demo-XXXXXXXX", # Creates a unique name for me
indication_callback, # Callback to be called
var1, # Variable passed by ref
var2 # Variable passed by ref
)
listener.start()
print c.subscribe_indication(
Name=unique_name,
Query="SELECT * FROM LMI_AccountInstanceCreationIndication WHERE SOURCEINSTANCE ISA LMI_Account",
Destination="192.168.122.1:65500"
)
try:
while True:
sleep(60)
except KeyboardInterrupt:
sys.exit(0)21.4.10. Example Usage
c = connect("host_name", "user_name", "password")
ns = c.root.cimv2Using the OpenLMI Service Provider
Example 21.41. Listing Available Services
TRUE) or stopped (FALSE) and the status string, use the following code snippet:
for service in ns.LMI_Service.instances():
print "%s:\t%s" % (service.Name, service.Status)cls = ns.LMI_Service
for service in cls.instances():
if service.EnabledDefault == cls.EnabledDefaultValues.Enabled:
print service.NameEnabledDefault property is equal to 2 for enabled services and 3 for disabled services.
cups service, use the following:
cups = ns.LMI_Service.first_instance({"Name": "cups.service"})
cups.doc()Example 21.42. Starting and Stopping Services
cups service and to see its current status, use the following code snippet:
cups = ns.LMI_Service.first_instance({"Name": "cups.service"})
cups.StartService()
print cups.Status
cups.StopService()
print cups.StatusExample 21.43. Enabling and Disabling Services
cups service and to display its EnabledDefault property, use the following code snippet:
cups = ns.LMI_Service.first_instance({"Name": "cups.service"})
cups.TurnServiceOff()
print cups.EnabledDefault
cups.TurnServiceOn()
print cups.EnabledDefaultUsing the OpenLMI Networking Provider
Example 21.44. Listing IP Addresses Associated with a Given Port Number
device = ns.LMI_IPNetworkConnection.first_instance({'ElementName': 'eth0'})
for endpoint in device.associators(AssocClass="LMI_NetworkSAPSAPDependency", ResultClass="LMI_IPProtocolEndpoint"):
if endpoint.ProtocolIFType == ns.LMI_IPProtocolEndpoint.ProtocolIFTypeValues.IPv4:
print "IPv4: %s/%s" % (endpoint.IPv4Address, endpoint.SubnetMask)
elif endpoint.ProtocolIFType == ns.LMI_IPProtocolEndpoint.ProtocolIFTypeValues.IPv6:
print "IPv6: %s/%d" % (endpoint.IPv6Address, endpoint.IPv6SubnetPrefixLength)LMI_IPProtocolEndpoint class associated with a given LMI_IPNetworkConnection class.
for rsap in device.associators(AssocClass="LMI_NetworkRemoteAccessAvailableToElement", ResultClass="LMI_NetworkRemoteServiceAccessPoint"):
if rsap.AccessContext == ns.LMI_NetworkRemoteServiceAccessPoint.AccessContextValues.DefaultGateway:
print "Default Gateway: %s" % rsap.AccessInfo
LMI_NetworkRemoteServiceAccessPoint instance with the AccessContext property equal to DefaultGateway.
- Get the
LMI_IPProtocolEndpointinstances associated with a givenLMI_IPNetworkConnectionusingLMI_NetworkSAPSAPDependency. - Use the same association for the
LMI_DNSProtocolEndpointinstances.
LMI_NetworkRemoteServiceAccessPoint instances with the AccessContext property equal to the DNS Server associated through LMI_NetworkRemoteAccessAvailableToElement have the DNS server address in the AccessInfo property.
RemoteServiceAccessPath and entries can be duplicated. The following code snippet uses the set() function to remove duplicate entries from the list of DNS servers:
dnsservers = set()
for ipendpoint in device.associators(AssocClass="LMI_NetworkSAPSAPDependency", ResultClass="LMI_IPProtocolEndpoint"):
for dnsedpoint in ipendpoint.associators(AssocClass="LMI_NetworkSAPSAPDependency", ResultClass="LMI_DNSProtocolEndpoint"):
for rsap in dnsedpoint.associators(AssocClass="LMI_NetworkRemoteAccessAvailableToElement", ResultClass="LMI_NetworkRemoteServiceAccessPoint"):
if rsap.AccessContext == ns.LMI_NetworkRemoteServiceAccessPoint.AccessContextValues.DNSServer:
dnsservers.add(rsap.AccessInfo)
print "DNS:", ", ".join(dnsservers)Example 21.45. Creating a New Connection and Configuring a Static IP Address
capability = ns.LMI_IPNetworkConnectionCapabilities.first_instance({ 'ElementName': 'eth0' })
result = capability.LMI_CreateIPSetting(Caption='eth0 Static',
IPv4Type=capability.LMI_CreateIPSetting.IPv4TypeValues.Static,
IPv6Type=capability.LMI_CreateIPSetting.IPv6TypeValues.Stateless)
setting = result.rparams["SettingData"].to_instance()
for settingData in setting.associators(AssocClass="LMI_OrderedIPAssignmentComponent"):
if setting.ProtocolIFType == ns.LMI_IPAssignmentSettingData.ProtocolIFTypeValues.IPv4:
# Set static IPv4 address
settingData.IPAddresses = ["192.168.1.100"]
settingData.SubnetMasks = ["255.255.0.0"]
settingData.GatewayAddresses = ["192.168.1.1"]
settingData.push()LMI_CreateIPSetting() method on the instance of LMI_IPNetworkConnectionCapabilities, which is associated with LMI_IPNetworkConnection through LMI_IPNetworkConnectionElementCapabilities. It also uses the push() method to modify the setting.
Example 21.46. Activating a Connection
ApplySettingToIPNetworkConnection() method of the LMI_IPConfigurationService class. This method is asynchronous and returns a job. The following code snippets illustrates how to call this method synchronously:
setting = ns.LMI_IPAssignmentSettingData.first_instance({ "Caption": "eth0 Static" })
port = ns.LMI_IPNetworkConnection.first_instance({ 'ElementName': 'ens8' })
service = ns.LMI_IPConfigurationService.first_instance()
service.SyncApplySettingToIPNetworkConnection(SettingData=setting, IPNetworkConnection=port, Mode=32768)Mode parameter affects how the setting is applied. The most commonly used values of this parameter are as follows:
1— apply the setting now and make it auto-activated.2— make the setting auto-activated and do not apply it now.4— disconnect and disable auto-activation.5— do not change the setting state, only disable auto-activation.32768— apply the setting.32769— disconnect.
Using the OpenLMI Storage Provider
c and ns variables, these examples use the following variable definitions:
MEGABYTE = 1024*1024 storage_service = ns.LMI_StorageConfigurationService.first_instance() filesystem_service = ns.LMI_FileSystemConfigurationService.first_instance()
Example 21.47. Creating a Volume Group
/dev/myGroup/ that has three members and the default extent size of 4 MB, use the following code snippet:
# Find the devices to add to the volume group
# (filtering the CIM_StorageExtent.instances()
# call would be faster, but this is easier to read):
sda1 = ns.CIM_StorageExtent.first_instance({"Name": "/dev/sda1"})
sdb1 = ns.CIM_StorageExtent.first_instance({"Name": "/dev/sdb1"})
sdc1 = ns.CIM_StorageExtent.first_instance({"Name": "/dev/sdc1"})
# Create a new volume group:
(ret, outparams, err) = storage_service.SyncCreateOrModifyVG(
ElementName="myGroup",
InExtents=[sda1, sdb1, sdc1])
vg = outparams['Pool'].to_instance()
print "VG", vg.PoolID, \
"with extent size", vg.ExtentSize, \
"and", vg.RemainingExtents, "free extents created."Example 21.48. Creating a Logical Volume
# Find the volume group:
vg = ns.LMI_VGStoragePool.first_instance({"Name": "/dev/mapper/myGroup"})
# Create the first logical volume:
(ret, outparams, err) = storage_service.SyncCreateOrModifyLV(
ElementName="Vol1",
InPool=vg,
Size=100 * MEGABYTE)
lv = outparams['TheElement'].to_instance()
print "LV", lv.DeviceID, \
"with", lv.BlockSize * lv.NumberOfBlocks,\
"bytes created."
# Create the second logical volume:
(ret, outparams, err) = storage_service.SyncCreateOrModifyLV(
ElementName="Vol2",
InPool=vg,
Size=100 * MEGABYTE)
lv = outparams['TheElement'].to_instance()
print "LV", lv.DeviceID, \
"with", lv.BlockSize * lv.NumberOfBlocks, \
"bytes created."Example 21.49. Creating a File System
ext3 file system on logical volume lv from Example 21.48, “Creating a Logical Volume”, use the following code snippet:
(ret, outparams, err) = filesystem_service.SyncLMI_CreateFileSystem(
FileSystemType=filesystem_service.LMI_CreateFileSystem.FileSystemTypeValues.EXT3,
InExtents=[lv])Example 21.50. Mounting a File System
# Find the file system on the logical volume:
fs = lv.first_associator(ResultClass="LMI_LocalFileSystem")
mount_service = ns.LMI_MountConfigurationService.first_instance()
(rc, out, err) = mount_service.SyncCreateMount(
FileSystemType='ext3',
Mode=32768, # just mount
FileSystem=fs,
MountPoint='/mnt/test',
FileSystemSpec=lv.Name)Example 21.51. Listing Block Devices
devices = ns.CIM_StorageExtent.instances()
for device in devices:
if lmi_isinstance(device, ns.CIM_Memory):
# Memory and CPU caches are StorageExtents too, do not print them
continue
print device.classname,
print device.DeviceID,
print device.Name,
print device.BlockSize*device.NumberOfBlocksUsing the OpenLMI Hardware Provider
Example 21.52. Viewing CPU Information
cpu = ns.LMI_Processor.first_instance() cpu_cap = cpu.associators(ResultClass="LMI_ProcessorCapabilities")[0] print cpu.Name print cpu_cap.NumberOfProcessorCores print cpu_cap.NumberOfHardwareThreads
Example 21.53. Viewing Memory Information
mem = ns.LMI_Memory.first_instance()
for i in mem.associators(ResultClass="LMI_PhysicalMemory"):
print i.NameExample 21.54. Viewing Chassis Information
chassis = ns.LMI_Chassis.first_instance() print chassis.Manufacturer print chassis.Model
Example 21.55. Listing PCI Devices
for pci in ns.LMI_PCIDevice.instances():
print pci.Name
Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.