TestCenter 自带的python库 :
# -*- coding: UTF-8 -*-
import os
import sys
import time
import atexit
import _winreg
class StcPython():
def __init__(self , version = None):
self.stcInt = None
self.stcVersionList = []
if sys.hexversion < 0x020605F0 or sys.hexversion >= 0x030500F0:
raise ImportError('This version of StcPython requires Python version 2.6.5 up to 3.4.4')
# STC_PRIVATE_INSTALL_DIR may either be set as a system environment
# variable or directly in the script.
# Windows example:
# 'C:/Program Files (x86)/Spirent Communications/Spirent TestCenter 4.40/Spirent TestCenter Application'
# Linux example:
# /home/user/Spirent_TestCenter_4.40/Spirent_TestCenter_Application_Linux
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,r"SOFTWARE\Spirent Communications\Spirent TestCenter")
try:
i = 0
while True :
stcVersion = _winreg.EnumKey(key, i)
self.stcVersionList.append(stcVersion)
i +=1
except WindowsError:
pass
if self.stcVersionList == [] :
print('The TestCenter Client is not installed!!')
sys.exit(1)
self.stcVersionList.sort()
if version == None :
version = self.stcVersionList[-1]
elif version not in self.stcVersionList :
print 'The TestCenter Client %s is not installed!!'%version
sys.exit(1)
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,r"SOFTWARE\Spirent Communications\Spirent TestCenter\%s\Components\Spirent TestCenter Application"%version)
stcDir, type = _winreg.QueryValueEx(key, 'TARGETDIR')
stcTitle, type = _winreg.QueryValueEx(key, 'Title')
stcInstallDir = stcDir + '\\' + stcTitle
os.environ['STC_PRIVATE_INSTALL_DIR'] = stcInstallDir
pvt_inst_dir = os.environ['STC_PRIVATE_INSTALL_DIR']
if (not os.path.exists(pvt_inst_dir) or
not os.path.exists(os.path.join(pvt_inst_dir, 'stcbll.ini'))):
raise ValueError(pvt_inst_dir +
' is not a valid STC install directory.')
runningDir = os.getcwd()
os.environ['STC_SCRIPT_RUNNING_DIR'] = runningDir
os.chdir(pvt_inst_dir)
if 'Spirent TestCenter Application' in sys.path[0] :
sys.path[0] = pvt_inst_dir
else :
# sys.path.append(pvt_inst_dir)
sys.path.insert(0,pvt_inst_dir)
print('Begin Loading Spirent TestCenter Client ...')
if sys.platform.startswith('linux'):
install_exit_fix(self)
if hex(sys.hexversion).startswith('0x2060'):
self.stcInt = __import__('StcIntPython')
elif hex(sys.hexversion).startswith('0x2070'):
self.stcInt = __import__('StcIntPython27')
else:
self.stcInt = __import__('StcIntPython34')
print('Loading Spirent TestCenter Client Successful ...')
os.chdir(runningDir)
def apply(self):
return self.stcInt.salApply()
def config(self, _object, **kwargs):
svec = []
StcPython._packKeyVal(svec, kwargs)
return self.stcInt.salSet(_object, svec)
def connect(self, *hosts):
svec = StcPython._unpackArgs(*hosts)
return self.stcInt.salConnect(svec)
def create(self, _type, **kwargs):
svec = []
if _type != 'project':
svec.append('-under')
svec.append(kwargs.pop('under'))
StcPython._packKeyVal(svec, kwargs)
return self.stcInt.salCreate(_type, svec)
def delete(self, handle):
return self.stcInt.salDelete(handle)
def shutdown(self, *args):
return self.stcInt.salShutdown(*args)
def disconnect(self, *hosts):
svec = StcPython._unpackArgs(*hosts)
return self.stcInt.salDisconnect(svec)
def get(self, handle, *args):
svec = StcPython._unpackArgs(*args)
svecDashes = []
for i, attName in enumerate(svec):
svecDashes.append('-' + attName)
retSvec = self.stcInt.salGet(handle, svecDashes)
if len(retSvec) == 1:
return retSvec[0]
else:
return StcPython._unpackGetResponseAndReturnKeyVal(retSvec, svec)
def help(self, topic=''):
if topic == '' or topic.find(' ') != -1:
return 'Usage: \n' + \
' stc.help(\'commands\')\n' + \
' stc.help()\n' + \
' stc.help()\n' + \
' stc.help()'
if topic == 'commands':
allCommands = []
for commandHelp in StcIntPythonHelp.HELP_INFO.values():
allCommands.append(commandHelp['desc'])
allCommands.sort()
return '\n'.join(allCommands)
info = StcIntPythonHelp.HELP_INFO.get(topic)
if info:
return 'Desc: ' + info['desc'] + '\n' + \
'Usage: ' + info['usage'] + '\n' + \
'Example: ' + info['example'] + '\n'
return self.stcInt.salHelp(topic)
def log(self, level, msg):
return self.stcInt.salLog(level, msg)
def perform(self, _cmd, **kwargs):
svec = []
StcPython._packKeyVal(svec, kwargs)
retSvec = self.stcInt.salPerform(_cmd, svec)
return StcPython._unpackPerformResponseAndReturnKeyVal(retSvec,
kwargs.keys())
def release(self, *csps):
svec = StcPython._unpackArgs(*csps)
return self.stcInt.salRelease(svec)
def reserve(self, *csps):
svec = StcPython._unpackArgs(*csps)
return self.stcInt.salReserve(svec)
def sleep(self, seconds):
time.sleep(seconds)
def subscribe(self, **kwargs):
svec = []
StcPython._packKeyVal(svec, kwargs)
return self.stcInt.salSubscribe(svec)
def unsubscribe(self, rdsHandle):
return self.stcInt.salUnsubscribe(rdsHandle)
def waitUntilComplete(self, **kwargs):
timeout = 0
if 'timeout' in kwargs:
timeout = int(kwargs['timeout'])
sequencer = self.get('system1', 'children-sequencer')
timer = 0
while True:
curTestState = self.get(sequencer, 'state')
if 'PAUSE' in curTestState or 'IDLE' in curTestState:
break
time.sleep(1)
timer += 1
if timeout > 0 and timer > timeout:
raise Exception('ERROR: Stc.waitUntilComplete timed out after '
'%s sec' % timeout)
if ('STC_SESSION_SYNCFILES_ON_SEQ_COMPLETE' in os.environ and
os.environ['STC_SESSION_SYNCFILES_ON_SEQ_COMPLETE'] == '1' and
self.perform('CSGetBllInfo')['ConnectionType'] == 'SESSION'):
self.perform('CSSynchronizeFiles')
return self.get(sequencer, 'testState')
@staticmethod
def _unpackArgs(*args):
svec = []
for arg in args:
if isinstance(arg, list):
svec.extend(arg)
else:
svec.append(arg)
return svec
@staticmethod
def _packKeyVal(svec, hash):
for key, val in sorted(hash.items()):
svec.append('-' + str(key))
if isinstance(val, list):
svec.append(' '.join(map(str, val)))
else:
svec.append(str(val))
@staticmethod
def _unpackGetResponseAndReturnKeyVal(svec, origKeys):
useOrigKey = len(origKeys) == len(svec)/2
hash = dict()
for i in range(0, int(len(svec)/2)):
key = svec[i*2]
key = key[1:len(key)]
val = svec[i*2+1]
if useOrigKey:
key = origKeys[i]
hash[key] = val
return hash
@staticmethod
def _unpackPerformResponseAndReturnKeyVal(svec, origKeys):
origKeyHash = dict()
for key in origKeys:
origKeyHash[key.lower()] = key
hash = dict()
for i in range(0, int(len(svec)/2)):
key = svec[i*2]
key = key[1:len(key)]
val = svec[i*2+1]
if key.lower() in origKeyHash:
key = origKeyHash[key.lower()]
hash[key] = val
return hash
_unhandled = None
_old_hook = None
_stc_inst = None
def _fix_exit():
if _unhandled:
# import traceback
# traceback.print_exception(*_unhandled)
_old_hook(*_unhandled)
_stc_inst.stcInt.salShutdown(1)
def _save_uncaught_exception(ex, val, tb):
global _unhandled
_unhandled = (ex, val, tb)
def install_exit_fix(stc_inst):
global _old_hook, _stc_inst
_stc_inst = stc_inst
sys.excepthook, _old_hook = _save_uncaught_exception, sys.excepthook
atexit.register(_fix_exit)
def uninstall_exit_fix():
global _old_hook, _unhandled, _stc_inst
if _old_hook:
sys.excepthook = _old_hook
_old_hook = None
_unhandled = None
_stc_inst = None
# internal help info
class StcIntPythonHelp(object):
def __init__(self):
pass
HELP_INFO = dict(
create=dict(
desc="create: -Creates an object in a test hierarchy",
usage="stc.create( className, under = parentObjectHandle, propertyName1 = propertyValue1, ... )",
example='stc.create( \'port\', under=\'project1\', location = "#{mychassis1}/1/2" )'),
config=dict(
desc="config: -Sets or modifies the value of an attribute",
usage="stc.config( objectHandle, propertyName1 = propertyValue1, ... )",
example="stc.config( stream1, enabled = true )"),
get=dict(
desc="get: -Retrieves the value of an attribute",
usage="stc.get( objectHandle, propertyName1, propertyName2, ... )",
example="stc.get( stream1, 'enabled', 'name' )"),
perform=dict(
desc="perform: -Invokes an operation",
usage="stc.perform( commandName, propertyName1 = propertyValue1, ... )",
example="stc.perform( 'createdevice', parentHandleList = 'project1' createCount = 4 )"),
delete=dict(
desc="delete: -Deletes an object in a test hierarchy",
usage="stc.delete( objectHandle )",
example="stc.delete( stream1 )"),
connect=dict(
desc="connect: -Establishes a connection with a Spirent TestCenter chassis",
usage="stc.connect( hostnameOrIPaddress, ... )",
example="stc.connect( mychassis1 )"),
disconnect=dict(
desc="disconnect: -Removes a connection with a Spirent TestCenter chassis",
usage="stc.disconnect( hostnameOrIPaddress, ... )",
example="stc.disconnect( mychassis1 )"),
reserve=dict(
desc="reserve: -Reserves a port group",
usage="stc.reserve( CSP1, CSP2, ... )",
example='stc.reserve( "//#{mychassis1}/1/1", "//#{mychassis1}/1/2" )'),
release=dict(
desc="release: -Releases a port group",
usage="stc.release( CSP1, CSP2, ... )",
example='stc.release( "//#{mychassis1}/1/1", "//#{mychassis1}/1/2" )'),
apply=dict(
desc="apply: -Applies a test configuration to the Spirent TestCenter firmware",
usage="stc.apply()",
example="stc.apply()"),
log=dict(
desc="log: -Writes a diagnostic message to the log file",
usage="stc.log( logLevel, message )",
example="stc.log( 'DEBUG', 'This is a debug message' )"),
waitUntilComplete=dict(
desc="waitUntilComplete: -Suspends your application until the test has finished",
usage="stc.waitUntilComplete()",
example="stc.waitUntilComplete()"),
subscribe=dict(
desc="subscribe: -Directs result output to a file or to standard output",
usage="stc.subscribe( parent=parentHandle, resultParent=parentHandles, configType=configType, resultType=resultType, viewAttributeList=attributeList, interval=interval, fileNamePrefix=fileNamePrefix )",
example="stc.subscribe( parent='project1', configType='Analyzer', resulttype='AnalyzerPortResults', filenameprefix='analyzer_port_counter' )"),
unsubscribe=dict(
desc="unsubscribe: -Removes a subscription",
usage="stc.unsubscribe( resultDataSetHandle )",
example="stc.unsubscribe( resultDataSet1 )"))
#============================diy====================================
def readtxt(filename):
'''读取一个文本文件,返回列表,每行数据作为一个元素'''
with open(filename,'rb') as f:
szlist = f.readlines()
for index in range(0,len(szlist)):
szlist[index] = szlist[index].strip()
#支持注释功能
if '#' in szlist[index] :
szlist[index] = ''
while '' in szlist:
szlist.remove('')
return szlist
获取testcenter机框板卡SN信息.py
# -*- coding: UTF-8 -*-
import sys,os,time
current_dir = os.path.split(os.path.realpath(__file__))[0]
if current_dir not in sys.path :
sys.path.append(current_dir)
import StcPython as zte
######################################
stc = zte.StcPython()
print("Spirent TestCenter version : %s" % stc.get("system1", "version"))
######################################
def main():
#初始化
szChassisIpList = zte.readtxt('ChassisIpList.py')
chassisLocationList = []
chassisInfoDict = {}
tmLocationList = []
tmInfoDict ={}
timestamp = time.strftime('%Y.%m.%d.%H.%M.%S')
for szChassisIp in szChassisIpList :
try:
print('Connect to TestCenter Chassis : '+szChassisIp)
stc.connect(szChassisIp)
except:
continue
#获取 Chassis 信息
hChassisList = getChassis()
for hChassis in hChassisList :
chassisProps = stc.get(hChassis)
chassisIpAddr = chassisProps['Hostname']
chassisPartNum = chassisProps['PartNum']
chassisSerialNum = chassisProps['SerialNum']
chassisFirmwareVersion = chassisProps['FirmwareVersion']
chassisLocation = '//%s' % chassisIpAddr
chassisLocationList.append(chassisLocation)
szTemp = '{:<24}{:<19}{:<15}{:<20}'.format(chassisLocation,chassisPartNum,chassisSerialNum,
chassisFirmwareVersion)
chassisInfoDict[chassisLocation] = szTemp
#获取 TestModules 信息
hTmList = getTestModules(hChassis)
for hTm in hTmList :
tmProps = stc.get(hTm)
tmPartNum = tmProps['PartNum']
tmSlotIndex = tmProps['Index']
tmSerialNum = tmProps['SerialNum']
tmFirmwareVersion = tmProps['FirmwareVersion']
tmLocation = '//%s/%s' %(chassisIpAddr,tmSlotIndex)
tmLocationList.append(tmLocation)
szTemp = '{:<24}{:<19}{:<15}{:<20}'.format(tmLocation,tmPartNum,tmSerialNum, tmFirmwareVersion)
tmInfoDict[tmLocation] = szTemp
print('Collect TestCenter SerialNum Info ...')
#编写文件抬头
item1 = r'Location'
item2 = r'PartNum'
item3 = r'SerialNum'
item4 = r'FirmwareVersion'
item = '{:<24}{:<19}{:<15}{:<20}'.format(item1,item2,item3, item4)
parting_line = '============================================================================'
filename = 'TestCenter_SerialNum_info_' + timestamp + '.txt'
with open(filename,'wb') as f:
f.write(item+'\r\n')
f.write(parting_line+'\r\n')
for chassisLocation in chassisLocationList :
f.write(chassisInfoDict[chassisLocation]+'\r\n')
f.write(parting_line+'\r\n')
for tmLocation in tmLocationList :
f.write(tmInfoDict[tmLocation]+'\r\n')
stc.perform("ChassisDisconnectAll")
print('Collect TestCenter SerialNum Info Finished! ...')
def getChassisManager():
return stc.get('system1','children-PhysicalChassisManager')
def getChassis():
hMgr = getChassisManager()
Chassis = stc.get(hMgr,'children-PhysicalChassis')
return Chassis.split()
def getTestModules(hChassis):
TestModules = stc.get(hChassis,'children-PhysicalTestmodule')
return TestModules.split()
def getPortGroups(hTm):
PortGroups = stc.get(hTm,'children-PhysicalPortgroup')
return PortGroups.split()
def getPorts(hPg):
Ports = stc.get(hPg,'children-PhysicalPort')
return Ports.split()
def getEthernetFiber(hPort):
return stc.get(hPort,'EthernetFiber')
def displayChassisInfo(hChassis):
chassisProps = stc.get(hChassis)
print chassisProps['SerialNum']
def displayEthernetFiberInfo(hEthernetFiber) :
fiberProps = stc.get(hEthernetFiber)
print fiberProps['ModuleType']
print fiberProps['VendorName']
print fiberProps['VendorSerialNumber']
main()
获取testcenter光模块SN信息.py :
# -*- coding: UTF-8 -*-
import sys,os,time
current_dir = os.path.split(os.path.realpath(__file__))[0]
if current_dir not in sys.path :
sys.path.append(current_dir)
# This loads the TestCenter library.
import StcPython as zte
stc = zte.StcPython()
######################################
def main():
szChassisIpList = zte.readtxt('ChassisIpList.py')
for szChassisIp in szChassisIpList :
try:
print('Connect to TestCenter Chassis : '+szChassisIp)
stc.connect(szChassisIp)
except:
continue
hChassisList = getChassis()
hProject = stc.create("project")
portLocationList = []
hTestPortFiberInterfaceDict ={}
timestamp = time.strftime('%Y.%m.%d.%H.%M.%S')
for hChassis in hChassisList :
chassisProps = stc.get(hChassis)
chassisIpAddr = chassisProps['Hostname']
hTmList = getTestModules(hChassis)
for hTm in hTmList :
tmProps = stc.get(hTm)
if '100G' not in tmProps['Description'] :
continue
tmSlotIndex = tmProps['Index']
hPgList = getPortGroups(hTm)
for hPg in hPgList :
hPortList = getPorts(hPg)
for hPort in hPortList :
portProps = stc.get(hPort)
portIndex = portProps['Index']
portLocation = '//%s/%s/%s' %(chassisIpAddr,tmSlotIndex,portIndex)
portLocationList.append(portLocation)
hTestPort = stc.create("port", under=hProject, location= portLocation , useDefaultHost=False)
hTestPortFiberInterfaceDict[portLocation] = stc.create("Ethernet100GigFiber", under=hTestPort)
print('ForceReservePorts...wait a moment...')
stc.perform('ReservePort',Location = portLocationList,RevokeOwner = True)
print('Attaching ports ...')
stc.perform('AttachPorts')
print('Apply configuration')
stc.apply()
print('Collect TestCenter OpticalModule SN Info ...')
#编写文件抬头
item1 = r'测试仪端口'
item2 = r'SN编号'
item3 = r'类型'
item4 = r'厂商'
item = '{:<31}{:<22}{:<16}{:<22}'.format(item1,item2,item3,item4)
parting_line = '================================================================================'
filename_100g = 'TestCenter_opticalmodule_sn_info_100g_' + timestamp + '.txt'
with open(filename_100g,'wb') as f:
f.write(item+'\r\n')
f.write(parting_line+'\r\n')
for portLocation in portLocationList :
fiberProps = stc.get(hTestPortFiberInterfaceDict[portLocation])
#print(fiberProps['ModuleType'])
if fiberProps['ModuleType'] == 'ABSENT' :
continue
#光模块类型应该读取的是fiberProps['ModuleType'] ,而不是fiberProps['PersonalityCardType'] ,此处TestCenter有bug,把CFP2返回的值是CFP。这里是临时用法。
szTemp = '{:<25}{:<21}{:<14}{:<22}'.format(portLocation,fiberProps['VendorSerialNumber'],fiberProps['PersonalityCardType'],fiberProps['VendorName'])
f.write(szTemp+'\r\n')
# Disconnect from chassis, release ports, and reset configuration.
print('Release ports and disconnect from Chassis')
stc.perform("ChassisDisconnectAll")
stc.perform("ResetConfig")
stc.delete(hProject)
print('Collect TestCenter OpticalModule SN Info Finished! ...')
def getChassisManager():
return stc.get('system1','children-PhysicalChassisManager')
def getChassis():
hMgr = getChassisManager()
Chassis = stc.get(hMgr,'children-PhysicalChassis')
return Chassis.split()
def getTestModules(hChassis):
TestModules = stc.get(hChassis,'children-PhysicalTestmodule')
return TestModules.split()
def getPortGroups(hTm):
PortGroups = stc.get(hTm,'children-PhysicalPortgroup')
return PortGroups.split()
def getPorts(hPg):
Ports = stc.get(hPg,'children-PhysicalPort')
return Ports.split()
def getEthernetFiber(hPort):
return stc.get(hPort,'EthernetFiber')
def displayChassisInfo(hChassis):
chassisProps = stc.get(hChassis)
print chassisProps['SerialNum']
def displayEthernetFiberInfo(hEthernetFiber) :
fiberProps = stc.get(hEthernetFiber)
print fiberProps['ModuleType']
print fiberProps['VendorName']
print fiberProps['VendorSerialNumber']
#================================================================
main()
获取testcenter端口占用信息.py :
# -*- coding: UTF-8 -*-
import sys,os,time
current_dir = os.path.split(os.path.realpath(__file__))[0]
if current_dir not in sys.path :
sys.path.append(current_dir)
import StcPython as zte
######################################
stc = zte.StcPython()
print("Spirent TestCenter version : %s" % stc.get("system1", "version"))
######################################
def main():
szChassisIpList = zte.readtxt('ChassisIpList.py')
for szChassisIp in szChassisIpList :
try:
print('Connect to TestCenter Chassis : '+szChassisIp)
stc.connect(szChassisIp)
except:
continue
hChassisList = getChassis()
pgLocationList = []
BoardInfoDict ={}
timestamp = time.strftime('%Y.%m.%d.%H.%M.%S')
for hChassis in hChassisList :
chassisProps = stc.get(hChassis)
chassisIpAddr = chassisProps['Hostname']
hTmList = getTestModules(hChassis)
for hTm in hTmList :
tmProps = stc.get(hTm)
tmType = tmProps['PartNum']
tmSlotIndex = tmProps['Index']
hPgList = getPortGroups(hTm)
for hPg in hPgList :
pgProps = stc.get(hPg)
pgSlotIndex = pgProps['Index']
pgLocation = '//%s/%s/%s' %(chassisIpAddr,tmSlotIndex,pgSlotIndex)
pgLocationList.append(pgLocation)
if pgProps['OwnershipState'] != 'OWNERSHIP_STATE_RESERVED' :
OwnerUser = '空闲'
else :
OwnerUser = pgProps['OwnerUserId'] + '@' + pgProps['OwnerHostname']
szTemp = '{:<25}{:<21}{:<21}'.format(pgLocation,tmType,OwnerUser)
BoardInfoDict[pgLocation] = szTemp
print('Collect TestCenter TestModules Info ...')
#编写文件抬头
item1 = r'测试仪端口'
item2 = r'单板类型'
item3 = r'使用人'
item = '{:<30}{:<25}{:<22}'.format(item1,item2,item3)
parting_line = '================================================================================'
filename = 'TestCenter_UsageRate_info_' + timestamp + '.txt'
with open(filename,'wb') as f:
f.write(item+'\r\n')
f.write(parting_line+'\r\n')
for pgLocation in pgLocationList :
f.write(BoardInfoDict[pgLocation]+'\r\n')
stc.perform("ChassisDisconnectAll")
print('Collect TestCenter TestModules Info Finished! ...')
def getChassisManager():
return stc.get('system1','children-PhysicalChassisManager')
def getChassis():
hMgr = getChassisManager()
Chassis = stc.get(hMgr,'children-PhysicalChassis')
return Chassis.split()
def getTestModules(hChassis):
TestModules = stc.get(hChassis,'children-PhysicalTestmodule')
return TestModules.split()
def getPortGroups(hTm):
PortGroups = stc.get(hTm,'children-PhysicalPortgroup')
return PortGroups.split()
def getPorts(hPg):
Ports = stc.get(hPg,'children-PhysicalPort')
return Ports.split()
def getEthernetFiber(hPort):
return stc.get(hPort,'EthernetFiber')
def displayChassisInfo(hChassis):
chassisProps = stc.get(hChassis)
print chassisProps['SerialNum']
def displayEthernetFiberInfo(hEthernetFiber) :
fiberProps = stc.get(hEthernetFiber)
print(fiberProps['ModuleType'])
print(fiberProps['VendorName'])
print(fiberProps['VendorSerialNumber'])
#========================================================
main()
多进程方式加载testcenter.py
# -*- coding: UTF-8 -*-
import sys,os,time
current_dir = os.path.split(os.path.realpath(__file__))[0]
if current_dir not in sys.path :
sys.path.append(current_dir)
#==========================================================
'''采用多进程方式加载不同版本的testcenter'''
from multiprocessing import Process
def main():
ProcessList = []
tn = Process(target = loadTestCenter,args = ('4.75', ))
tn.start()
ProcessList.append(tn)
tn = Process(target = loadTestCenter,args = ('4.54', ))
tn.start()
ProcessList.append(tn)
for item in ProcessList:
item.join()
def loadTestCenter(version):
from StcPython import StcPython
stc = StcPython(version)
print("Spirent TestCenter version : %s" % stc.get("system1", "version"))
if __name__ == '__main__':
main()