Develop > Server Automation Platform > Python API access with Pytwist

Python API access with Pytwist

Pytwist is a set of Python libraries that provide access to the SA API from managed servers and custom extensions. (The twist is the internal name for the Web Services Data Access Engine.) For managed servers, you can set up Python scripts that call SA APIs through Pytwist so that end users can invoke the scripts as DSEs or ISM controls. Created by HPE SA Professional Services, custom extensions are Python scripts that run in the Command Engine (way). Pytwist enables custom extensions to access recent additions to the SA data model, such as folders and software policies, which are not accessible from Command Engine scripts.

This topic is intended for developers and consultants who are already familiar with the SA data model, custom extensions, Agents, and the Python programming language.

Following topics are discussed in this section:

Setup for Pytwist

Before trying out the examples in this section, make sure that your environment meets the following setup requirements, as detailed in the following sections.

Supported platforms for Pytwist

Pytwist is supported on managed servers and core servers. For a list of operating systems supported for these servers.

Pytwist relies on Python version 2.7.10, the version used by SA Agents and custom extensions.

Unlike Web Services and Java RMI clients, a Pytwist client relies on internal SA libraries. If your client program needs to access the SA API from a server that is not a managed or core server, then use a Web Services or Java RMI client, not Pytwist.

Access requirements for Pytwist

Pytwist needs to access port 1032 of the core server running the Web Services Data Access Engine. By default, the engine listens on port 1032.

Installing Pytwist libraries

The pytwist libraries need not be installed as they are part of the agent libraries.

Pytwist examples

The Python code examples in this section show how to get information from managed servers, create folders, and remediate software policies. Each Pytwist example performs the following operations:

  1. Import the packages.

    When importing objects of the SA API name space, such as Filter, the path includes the Java package name, preceded by pytwist. Here are the import statements for the get_server_info.py example:

    import sys
    from pytwist import *
    from pytwist.com.opsware.search import Filter
  2. Create the TwistServer object:
    ts = twistserver.TwistServer()

    See TwistServer method syntax for information about the method’s arguments.
  3. Get a reference to the service.

    The Python package name of the service is the same as the Java package name, but without the leading opsware.com. For example, the Java com.opsware.server.ServerService package maps to the Pytwist server.ServerService:

    serverservice = ts.server.ServerService
  4. Invoke the SA API methods of the service:
    filter = Filter()
    . . .
    servers = serverservice.findServerRefs(filter)
    . . .
    for server in servers: vo = serverservice.getServerVO(server)
    . . .

get_server_info.py

This script searches for all managed servers with host names containing the command-line argument. The search method, findServerRefs, returns an array of references to server persistent objects. For each reference, the getServerVO method returns the value object (VO), which is the data representation that holds the server’s attributes. Here is the code for the get_server_info.py script:

#!/opt/opsware/agent/bin/python
# get_server_info.py

# Search for servers by partial hostname.

import sys
from pytwist import *
from pytwist.com.opsware.search import Filter

# Check for the command-line argument.
if len(sys.argv) < 2:
	print "You must specify part of the hostname as the search target."
	print "Example: " + sys.argv[0] + " " + "opsware.com"
	sys.exit(2)
# Construct a search filter.
filter = Filter()
filter.expression = 'device_hostname *=* "%s" ' % (sys.argv[1])

# Create a TwistServer object.
ts = twistserver.TwistServer()

# Get a reference to ServerService.
serverservice = ts.server.ServerService

# Perform the search, returning a tuple of references.
servers = serverservice.findServerRefs(filter)

if len(servers) < 1:
	print "No matching servers found"
	sys.exit(3)

# For each server found, get the server’s value object (VO)
# and print some of the VO’s attributes.
for server in servers:
	vo = serverservice.getServerVO(server)
	print "Name: " + vo.name	
	print "Management IP: " + vo.managementIP
	print "OS Version: " + vo.osVersion	

create_folder.py

This script creates a folder named /TestA/TestB by invoking the createPath method. Note that the path parameter of createPath does not contain slashes. Each string element in path indicates a level in the folder. Next, the script retrieves and prints the names of all folders directly below the root folder. The listing for the create_folder.py script follows:

#!/opt/opsware/agent/bin/python
# create_folder.py

# Create a folder in SA.

import sys
from pytwist import *

# Create a TwistServer object.
ts = twistserver.TwistServer()

# Get a reference to FolderService.
folderservice = ts.folder.FolderService

# Get a reference to the root folder.
rootfolder = folderservice.getRoot()
# Construct the path of the new folder.
path = 'TestA', 'TestB'

# Create the folder /TestA/TestB relative to the root.
folderservice.createPath(rootfolder, path)

# Get the child folders of the root folder.
rootchildren = folderservice.getChildren(rootfolder,
'com.opsware.folder.FolderRef')

# Print the names of the child folders.
for child in rootchildren:
	vo = folderservice.getFolderVO(child)
	print vo.name	

remediate_policy.py

This script creates a software policy, attaches it to a server, and then remediates the policy. Several names are hard-coded in the script: the platform, server, and parent folder. Optionally, you can specify the policy name on the command-line, which is convenient if you run the script multiple times. The platform of the software policy must match the OS of the packages contained in the policy. Therefore, if you change the hard-coded platform name, then you also change the name in unitfilter.expression.

The following listing has several bad line breaks. If you copy this code, be sure to fix the bad line breaks before running it. The comment lines beginning with "NOTE" point out the bad line breaks.

#!/opt/opsware/agent/bin/python
# remediate_policy.py

# Create, attach, and remediate a software policy.

import sys
from pytwist import *
from pytwist.com.opsware.search import Filter
from pytwist.com.opsware.swmgmt import SoftwarePolicyVO

# Initialize the names used by this script.
foldername = 'TestB'
platformname = 'Windows 2003'
servername = 'd04.example.com'
# If a command-line argument is specified,
# use it as the policy name
if len(sys.argv) == 2:
	policyname = sys.argv[1]
else:
	policyname = 'TestPolicyA'

# Create a TwistServer object.
ts = twistserver.TwistServer()
ts.authenticate("SAUser", "SAPassword")

# Get the references to the services used by this script.
folderservice = ts.folder.FolderService
swpolicyservice = ts.swmgmt.SoftwarePolicyService
serverservice = ts.server.ServerService
unitservice = ts.pkg.UnitService
platformservice = ts.device.PlatformService

# Search for the folder that will contain the policy.
folderfilter = Filter()
folderfilter.expression = 'FolderVO.name = %s' % foldername
folderrefs = folderservice.findFolderRefs(folderfilter)
if len(folderrefs) == 1:
	parent = folderrefs[0]
elif len(folderrefs) < 1:
	print "No matching folders found."
	sys.exit(2)
else:
	print "Non-unique folder name: " + foldername
	sys.exit(3)
# Search for the reference to the platform "Windows Server 2003."
platformfilter = Filter()
platformfilter.objectType = 'platform'
# Because the platform name contains spaces,
# it’s enclosed in double quotes
# NOTE: The following code line has a bad line break.
# The assignment statement should be on a single line.
platformfilter.expression = 'platform_name = "%s"' % platformname
platformrefs = platformservice.findPlatformRefs(platformfilter)

if len(platformrefs) == 0:
	print "No matching platforms found."
	sys.exit(4)	

# Search for the references to some software packages.
unitfilter = Filter()
unitfilter.objectType = 'software_unit'
# NOTE: The following code line has a bad line break.
# The assignment statement should be on a single line.
unitfilter.expression = '((UnitVO.unitType = "MSI") & ( UnitVO.name contains
"ismtool" ) & ( software_platform_name = "Windows 2003" ))'
unitrefs = unitservice.findUnitRefs(unitfilter)

# Create a value object for the new software policy.
vo = SoftwarePolicyVO()
vo.name = policyname
vo.folder = parent
vo.platforms = platformrefs
vo.softwarePolicyItems = unitrefs

# Create the software policy.
swpolicyvo = swpolicyservice.create(vo)

# Search by hostname for the reference to a managed server.
serverfilter = Filter()
serverfilter.objectType = 'server'
# NOTE: The following code line has a bad line break.
# The assignment statement should be on a single line.
serverfilter.expression = 'ServerVO.hostname = %s' % servername
serverrefs = serverservice.findServerRefs(serverfilter)

if len(serverrefs) == 0:
	print "No matching servers found."
	sys.exit(5) 

# Create an array that has a reference to the
# newly created policy.
swpolicyrefs = [1]
swpolicyrefs[0] = swpolicyvo.ref

# Attach the software policy to the server.
swpolicyservice.attachToPolicies(swpolicyrefs, serverrefs)

# Remediate the policy and the server.
# NOTE: The following code line has a bad line break.
# The assignment statement should be on a single line.
jobref = swpolicyservice.startRemediateNow(swpolicyrefs, serverrefs)
print "The remediation job ID is %d" % jobref.id

Virtualization Pytwist examples

This topic provides examples (createVM_WithOSBP.py and deployVM.py ) of creating and deploying virtual machines (VMs) using SA API. For more examples about Virtualization, see the Server Automation Using Guide on the HPE SSO portal.

createVM_WithOSBP.py

This basic example creates a VM on a VMware vCenter using CD boot with static IP configuration.

All properties have not been set in these examples. Please refer to API documentation (javadocs) to understand and set the properties for your use case.

#!/opt/opsware/agent/bin/python
from pytwist import twistserver
from pytwist.com.opsware.locality import CustomerRef, RealmRef
from pytwist.com.opsware.osprov import OSBuildPlanRef
from pytwist.com.opsware.pkg import UnknownPkgRef
from pytwist.com.opsware.v12n import AdapterIPSettings, V12nHypervisorRef, \
	V12nHypervisorService, V12nInventoryFolderRef, V12nResourcePoolRef, \
	V12nResourcePoolRef, V12nVIManagerService, VirtualCpuConfig,
VirtualDevice, \
	VirtualDeviceChangeConfig, VirtualDeviceTypeConstant,
VirtualHardwareConfigSpec, \
	VirtualMemoryConfig, VirtualServerCDProvisioningSpec,
VirtualServerComputeSpec, \
	VirtualServerConfigSpec, VirtualServerCreateSpec,
VirtualStorageDeviceConstant, \
	VirtualStorageDeviceHWConfig
from pytwist.com.opsware.v12n.vmware import V12nDatastoreRef, \
	VmwareVirtualInterfaceBacking, VmwareVirtualNicHWConfig, \
	VmwareVirtualServerDetails, VmwareVirtualServerStorageSpec, \
	VmwareVirtualStorageFileBacking 
import time


# This is a bare bones example of creating a Virtual Machine on a VMware
# vCenter while booting from CD with Static IP configuration. It also
# provisions the Virtual Machine with the give OS Build Plan. For more
# detailed information please refer to the java doc. All the properties have
# not been set in the example below, please review the java doc to understand
# and set the properties for your use case.


# This method constructs the create specification to create the Virtual
# Machine and provision it.
def constructCreateSpec():

	# Construct VmwareVirtualServerDetails
	detail = VmwareVirtualServerDetails()
	# Virtual Machine Name
	detail.name = "Test VM"
	# Description for the Virtual Machine
	detail.description = "Sample test create VM"
	# This is the key for the guest operating system that will installed on
	# the Virtual Machine.
	# V12nVIManagerService.getGuestOSList() provides the supported list for
	# the given V12n Manager and hypervisor.
	detail.guestId = "rhel6Guest"
	# This is folder where the VM will reside in you can see the list of
	# folders at V12nInventoryFolderService.findV12nInventoryFolderRefs() it
	# is the inventory location of the Virtual Machine
	folder = V12nInventoryFolderRef(2020001)
	detail.inventoryFolderRef = folder


	# Configure the number of Virtual processors on the Virtual Machine
	cpuConfig = VirtualCpuConfig()
	cpuConfig.virtualCpuCount = 1
	
	# Configure the Memory for the Virtual Machine
	memoryConfig = VirtualMemoryConfig()
	memoryConfig.size = 1024*1024*1024

	# Configure NICs
	# Construct the virtual device of type network i.e a NIC
	virtualNetworkDevice = VirtualDevice()
	virtualNetworkDevice.type = VirtualDeviceTypeConstant.NETWORK
	# A unique identifier for the virtual device
	virtualNetworkDevice.key = "4001"
	backingNetwork = VmwareVirtualInterfaceBacking()
	# This is the port group that the nic will be assigned to
	backingNetwork.portGroup = "VLAN 625"

	hwConfigNetwork = VmwareVirtualNicHWConfig()
	# The kind of network adapter to use, other options are listed in
	# VmwareVirtualNicHWConfig
	hwConfigNetwork.adapterType = VmwareVirtualNicHWConfig.E1000
	hwConfigNetwork.macAddressIsDynamic = True 

	virtualNetworkDevice.hwConfig = hwConfigNetwork
	virtualNetworkDevice.backingInfo = backingNetwork
	virtualNetworkDevice.connected = True
	virtualNetworkDevice.startConnected = True

	# Configure Hard Disk
	virtualDiskDevice = VirtualDevice()
	virtualDiskDevice.type = VirtualDeviceTypeConstant.STORAGE

	backingStorage = VmwareVirtualStorageFileBacking()

	# This is Ref for the data store on the hypervisor where the VM will be
	# hosted. The list of datastores associated with the Hypervisors are
	# listed at V12nHypervisorService.getV12nHypervisorVO() under storage
	# config
	dataStoreRef = V12nDatastoreRef(90001)
	backingStorage.datastore = dataStoreRef
	backingStorage.lazyAllocation = True 

	hwConfigStorage = VirtualStorageDeviceHWConfig()
	hwConfigStorage.capacity = 10*1024*1024*1024
	hwConfigStorage.usageType = 
VirtualStorageDeviceConstant.USAGE_TYPE_DISK_DRIVE

	virtualDiskDevice.hwConfig = hwConfigStorage
	virtualDiskDevice.backingInfo = backingStorage

	# Add both the virtual devices to be created, i.e. the hard disk and the
	# nic
	virtualDvcs_toAdd = []
	virtualDvcs_toAdd.append(virtualNetworkDevice)
	virtualDvcs_toAdd.append(virtualDiskDevice)
	deviceChange = VirtualDeviceChangeConfig()
	deviceChange.addList = virtualDvcs_toAdd

	# Finalize the Config Spec
	configSpec = VirtualServerConfigSpec()
	configSpec.detail = detail
	configSpec.virtualHardware = VirtualHardwareConfigSpec()
	configSpec.virtualHardware.cpuConfig = cpuConfig
	configSpec.virtualHardware.memoryConfig = memoryConfig
	configSpec.virtualHardware.deviceChange = deviceChange

	# Constructing the Compute Spec
	computeSpec = VirtualServerComputeSpec()
	# This is the hypervisor hosting the VM
	hypervisorRef = V12nHypervisorRef(2030001)
	computeSpec.computeProviderRef = hypervisorRef
	# This is resource pool on the hypervisor/cluster that the VM belongs to
	# It can be retrieved by using hypervisorVO.children or the Cluster
	# children
	resourcePool = V12nResourcePoolRef(2040001)
	computeSpec.resourcePoolRef = resourcePool

	storageSpec = VmwareVirtualServerStorageSpec()
	storageSpec.datastore = dataStoreRef

	# This example deals with provisioning a VM through CD boot and with
	# static IP configuration. The example deals setting the boot ISO and
	# network information to be used.
	# All the information for this is contained in the
	# VirtualServerCDProvisioningSpec

	# Set all the network information
	gateways =[]
	gw ="192.168.135.33"
	gateways.append(gw)
	dnsServers =[]
	dnsServer = "192.168.2.13"
	dnsServers.append(dnsServer)


	interfaces =[]
	interface = AdapterIPSettings()

	# Construct the network interface
	interface.useDHCP=False
	# Note this is the virtual device we have created above, we use the same
	# device key to indicate to provisioning which virtual device is to be
	# used for provisioning
	interface.virtualDeviceKey="4001"
	interface.gateways=gateways
	interface.ipAddress="192.168.135.45"
	interface.netmask="255.255.255.224"
	interface.dnsServerList=dnsServers

	interfaces.append(interface)

	# This is the boot ISO Ref that will be used to get the server into
	# maintenance mode
	# The name and the id need to match the packages on the core.	
	# Use the UnitService.findUnitRefs() to find the boot ISO's
	bootISORef = UnknownPkgRef(5340001)	
	bootISORef.name="HPSA_linux_boot_cd.iso"
	# The realm assigned to the Virtual Machine will be the realm of the
	# Virtualization Service
	realmRef = RealmRef(30001)
	# The OS Build Plan that needs be run on the Virtual Machine after the VM
	# has been created.
	osbpRef = OSBuildPlanRef(580001)

	provisioningSpec = VirtualServerCDProvisioningSpec()

	provisioningSpec.bootISORef = bootISORef
	provisioningSpec.interfaces = interfaces
	provisioningSpec.realmRef = realmRef
	provisioningSpec.oSBuildPlanRef = osbpRef

	# Finally put together all the information to be set on the Create
	# Specification
	createSpec = VirtualServerCreateSpec()
	createSpec.configSpec = configSpec
	createSpec.computeSpec = computeSpec
	createSpec.storageSpec = storageSpec

	createSpec.provisioningSpec = provisioningSpec
	#Set the customer to be associated with the Virtual Machine
	customer = CustomerRef(9)
	createSpec.setCustomerRef(customer)
	return createSpec

def createVirtualMachine():
	twist = twistserver.TwistServer()
	twist.authenticate("hp", "opsware")
	vmService = twist.v12n.V12nVirtualServerService
	createSpec = constructCreateSpec()
	jobRef = vmService.startCreate(createSpec,4*60*60,"Sample create
VM",None, None)


createVirtualMachine()

deployVM.py

This basic example shows how to deploy a VM from a VM template on VMware vCenter and customize the guest OS of the deployed VM.

All properties have not been set in these examples. Please refer to API documentation (javadocs) to understand and set the properties for your use case.

#!/opt/opsware/agent/bin/python
from pytwist import twistserver
from pytwist.com.opsware.locality import CustomerRef, RealmRef
from pytwist.com.opsware.osprov import OSBuildPlanRef
from pytwist.com.opsware.pkg import UnknownPkgRef
from pytwist.com.opsware.v12n import AdapterIPSettings, V12nHypervisorRef, \
	V12nHypervisorService, V12nInventoryFolderRef, V12nResourcePoolRef, \
	V12nResourcePoolRef, V12nVIManagerService, VirtualCpuConfig,
VirtualDevice, \
	VirtualDeviceChangeConfig, VirtualDeviceTypeConstant,
VirtualHardwareConfigSpec, \
	VirtualMemoryConfig, VirtualServerCDProvisioningSpec,
VirtualServerComputeSpec, \
	VirtualServerConfigSpec, VirtualServerCreateSpec,
VirtualStorageDeviceConstant, \
	VirtualStorageDeviceHWConfig, V12nVirtualServerTemplateRef, \
	VirtualServerCloneSpec, VirtualServerGuestCustomizationSpec
from pytwist.com.opsware.v12n.vmware import V12nDatastoreRef, \
	VmwareVirtualInterfaceBacking, VmwareVirtualNicHWConfig, \
	VmwareVirtualServerDetails, VmwareVirtualServerStorageSpec, \
	VmwareVirtualStorageFileBacking
import time

# This is a bare bones example of deploying a Template VMware vCenter. It
# deploys the template and then guest customizes the deployed Virtual Machine.
# For more detailed information please refer to the java doc. All the
# properties have not been set in the example below, please review the java
# doc to understand and set the properties for your use case.

# This method constructs the deploy specification to deploy the Template and
# customizes it.
def constructDeploySpec(sourceTemplateVO):

	# Construct the Deploy Spec
	clonespec = VirtualServerCloneSpec()

	clonespec.computeSpec = VirtualServerComputeSpec()
	# This is the hypervisor hosting the VM
	targetHypervisorRef = V12nHypervisorRef(2030001)
	clonespec.computeSpec.computeProviderRef = targetHypervisorRef

	computeSpec = VirtualServerComputeSpec()
	# This is the resource pool on the hypervisor/cluster that the VM belongs to
	# It can be retrieved by using hypervisorVO.children or the Cluster
	# children
	targetResourcePoolRef = V12nResourcePoolRef(2040001)
	computeSpec.resourcePoolRef = targetResourcePoolRef
	clonespec.computeSpec.resourcePoolRef = targetResourcePoolRef

	storageSpec = VmwareVirtualServerStorageSpec()
	dataStoreRef = V12nDatastoreRef(90001)
	storageSpec.datastore = dataStoreRef
	clonespec.storageSpec = storageSpec
	# Construct VmwareVirtualServerDetails
	detail = VmwareVirtualServerDetails()
	# Virtual Machine Name
	detail.name = "Test Deploy VM"
	# Description for the Virtual Machine
	detail.description = "Sample Deploy create VM"

	# This is the folder where the VM will reside in. You can see the list of
	# folders at V12nInventoryFolderService.findV12nInventoryFolderRefs(). It
	# is the inventory location of the Virtual Machine
	targetFolderRef = V12nInventoryFolderRef(2020001)
	detail.inventoryFolderRef = targetFolderRef
	configSpec = VirtualServerConfigSpec()
	configSpec.detail = detail
	clonespec.configSpec=configSpec

	# Create the Guest Customization Spec, this is needed to customized the
	# deployed VM so that it does not use the network settings and host name
	# of the source template
	# In this example all the interfaces are set to DHCP but you can
	# customize each of the interfaces by either providing static or DHCP
	# configuration details
	interfaces = createInterfaces(sourceTemplateVO)
	# The realm assigned to the Virtual Machine will be the realm of the
	# Virtualization Service
	realmRef = RealmRef(30001)
	clonespec.guestCustomizationSpec =
createGuestCustomizationSpec("testDeployVM",realmRef,interfaces)
	clonespec.setPowerOn(True)
	# Set the customer to be associated with the Virtual Machine
	customerRef = CustomerRef(9)
	clonespec.customerRef = customerRef
	return clonespec

def createGuestCustomizationSpec(newVmNameVal,realmRef,interfaces):
	gcSpec = VirtualServerGuestCustomizationSpec()
	gcSpec.computerName = newVmNameVal
	gcSpec.interfaces = interfaces
	gcSpec.realmRef = realmRef
	return gcSpec

def createInterfaces(virtualServerVO):
	interfaces = []
	virtualDevices = virtualServerVO.virtualHardware.deviceList
	vNICs = [vd for vd in virtualDevices if vd.type ==
VirtualDeviceTypeConstant.NETWORK]
	for vNIC in vNICs:
		intf = AdapterIPSettings()
		intf.useDHCP = True
		intf.hardwareAddress = vNIC.hwConfig.macAddress
		intf.virtualDeviceKey = vNIC.key
		interfaces.append(intf)
	return interfaces


def deployVirtualMachine():
	twist = twistserver.TwistServer()
	twist.authenticate("hp", "opsware")
	vmTemplateService = twist.v12n.V12nVirtualServerTemplateService
	vmService = twist.v12n.V12nVirtualServerBaseService
	sourceTemplateRef = V12nVirtualServerTemplateRef(1520001)
	sourceTemplateVO =
vmService.getV12nVirtualServerBaseVO(sourceTemplateRef)
	deploySpec = constructDeploySpec(sourceTemplateVO)
	jobRef =
vmTemplateService.startDeploy(sourceTemplateRef,deploySpec,30*60,"Sample
Deploy VM",None, None);

deployVirtualMachine()

Pytwist details

This topic describes the behavior and syntax that is specific to Pytwist:

Authentication modes

The authentication mode of a Pytwist client is important because it affects the SA features and the resources that the client can access. A Pytwist client can run in one of the following modes:

  • Authenticated: The client has called the authenticate(username, password) method on a TwistServer object. After calling the authenticate method, the client is authorized as the SA user specified by the username parameter, much like an end user who logs onto the SA Client.
  • Not Authenticated: The client has not called the TwistServer.authenticate method. On a managed server, the client is authenticated as if it is the device that controls the Agent certificate. When used within a custom extension, a non-authenticated Pytwist client needs access to the Command Engine certificate. For more information on custom extensions and certificates, contact your technical support representative.

TwistServer method syntax

The TwistServer method configures the connection from the client to the Web Services Data Access Engine. (For sample invocations, see Pytwist examples.) All of the arguments of TwistServer are optional. The following table lists the default values for the arguments.

Arguments of the TwistServer method

Argument

Description

Default

host

The hostname to connect to.

twist

port

The port number to connect to.

1032

secure

Whether to use https for the connection. Allowed values: 1 (true) or 0 (false).

1

ctx

The SSL context for the connection.

None. (See also Authentication modes.)

When the TwistServer object is created, the client does not establish a connection with the server. Therefore, if a connectivity problem occurs, it is not encountered until the client calls authenticate or an SA API method.

Error handling

If the TwistServer.authenticate method or an SA API method encounters a problem, a Python exception is raised. You can catch these exceptions in an except clause, as in the following example:

# Create the TwistServer object.
ts = twistserver.TwistServer(’localhost’)
# Authenticate by passing an SA user name and password.
try:
	ts.authenticate(’jdoe’, ’secretpass’)
except:
	print "Authentication failed."
	sys.exit(2)	

Mapping Java package names and data types to Pytwist

The Pytwist interface is for Python, but the SA API is written in Java. Because of the differences between two programming languages a Pytwist client must follow the mapping rules described in this section.

In the SA API documentation, Java package names begin with com.opsware. When specifying the package name in Pytwist, insert pytwist at the beginning, for example:

from pytwist.com.opsware.compliance.sco import *

The SA API documentation specifies method parameters and return values as Java data types. The following table shows how to map the Java data types to Python for the API method invocations in Pytwist.

Mapping data types from Java to Python

Java data type in SA API

Python data type in Pytwist

Boolean

An integer 1 for true or the integer 0 for false.

Object[]
(object array)

As input parameters to API method calls, object arrays can be either Python tuples or lists. As output from API method calls, object arrays are returned as Python tuples.

Map

Dictionary

Date

A long data type representing the number of milliseconds since epoch (midnight on January 1, 1970).