def run(FileName):
    try:
        stc = StcPython()
        log_dir = stc.perform('GetSystemPaths').get('SessionDataPath', '')
        stc.perform('SaveEquipmentInfoCommand')
        stc.perform('GetEquipmentLogsCommand',
                    EquipmentList='project1', TimestampFileNames=False)
        stc.perform('SaveToTccCommand',
                    FileName=os.path.join(log_dir, 'config.tcc'))
        _archive(stc, FileName, log_dir)

    except Exception:
        stc.log('ERROR',
                'error: unhandled exception:\n' + traceback.format_exc())
        return False

    return True
Exemplo n.º 2
0
# This is the only module that is required by the Spirent TestCenter API.
import sys

import time
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print("Loading the Spirent TestCenter API...")
sys.path.append('/home/mjefferson/spirent/stc/stc4.69/API/Python')
from StcPython import StcPython
stc = StcPython()

###############################################################################
####
####    Global variables
####
###############################################################################

# Specify the labserver IP address if you want to use it. Specify an empty
# string to just connect to the hardware directly.
#labserverip = '192.168.130.135'
labserverip = ''
locationlist = [
    '10.140.96.81/7/1', '10.140.96.81/7/2', '10.140.96.81/7/3',
    '10.140.96.81/7/4'
]
Exemplo n.º 3
0
def create_testcase(p, finame):
    print(p.show())
    stc = StcPython()
    hProject = stc.create("project")
    print("##### Create port #####")
    hPortTx = stc.create("port", under=hProject)
    print("##### creating the streamblock on port1 #####")
    hsb = stc.create("streamblock",
                     under=hPortTx,
                     load="10",
                     loadunit="PERCENT_LINE_RATE",
                     insertSig="true",
                     frameLengthMode="FIXED",
                     maxFrameLength="1200",
                     FixedFrameLength="256",
                     frameconfig="")

    layersStr = p.summary()
    layers = [x.strip() for x in layersStr.split('/')]
    layers.pop()
    for layer in layers:
        if 'Ether' in layer:
            print("##### creating the Ethernet header #####")
            heth = stc.create("ethernet:EthernetII",
                              under=hsb,
                              srcmac=p[Ether].src,
                              dstmac=p[Ether].dst)
        elif 'IP' in layer:
            print("##### creating the IPv4 header #####")
            hip = stc.create("ipv4:IPv4",
                             under=hsb,
                             sourceaddr="10.10.10.1",
                             destaddr="10.10.10.2",
                             gateway="10.10.10.2")
        elif 'TCP' in layer:
            print("#### creating tcp:TCP header ####")
            htcp = stc.create("tcp:TCP", under=hsb)
        elif 'UDP' in layer:
            print("#### creating udp:UDP header ####")
            htcp = stc.create("tcp:TCP", under=hsb)
        else:
            print("##### creating the custom header #####")
            lyr = get_customclass(layer)
            field_names = [field.name for field in p[lyr].fields_desc]
            #fields = {field_name: getattr(p[lyr], field_name) for field_name in field_names}
            pattern = ''
            for field_name in field_names:
                v = getattr(p[lyr], field_name)
                pattern = pattern + str(v)
            pattern = '0x' + pattern
            hcp = stc.create("custom:Custom", under=hsb, pattern=pattern)

    print("##### Saving the config in XML file #####")
    stc.perform("saveasxml", filename=finame)
Exemplo n.º 4
0
import pdb

# This is for training only...
pdb.set_trace()

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython

stc = StcPython()

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

if labserverip:
    print 'Connecting to Lab Server'
    stc.perform("CSTestSessionConnect",
                host=labserverip,
                TestSessionName="Training",
                OwnerId="matt",
                CreateNewTestSession="true")

    # Terminate the Lab Server session when the last client disconnects.
    stc.perform("TerminateBll", TerminateType="ON_LAST_DISCONNECT")
def loadTestCenter(version):
    from StcPython import StcPython
    stc = StcPython(version)
    print "Spirent TestCenter version : %s" % stc.get("system1", "version")
def main():
    parser = argparse.ArgumentParser()
    # Required parameters
    requirednamed = parser.add_argument_group("required named arguments")
    requirednamed.add_argument("--lab_server_addr",
                               required=True,
                               help="The IP address of the Spirent Lab Server",
                               dest="lab_server_addr")
    requirednamed.add_argument("--license_server_addr",
                               required=True,
                               help="The IP address of the Spirent License Server",
                               dest="license_server_addr")
    requirednamed.add_argument("--east_chassis_addr",
                               required=True,
                               help="The TestCenter chassis IP address to use for the east test port",
                               dest="east_chassis_addr")
    requirednamed.add_argument("--east_slot_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter slot number to use for the east test port",
                               dest="east_slot_num")
    requirednamed.add_argument("--east_port_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter port number to use for the east test port",
                               dest="east_port_num")
    requirednamed.add_argument("--west_chassis_addr",
                               required=True,
                               help="The TestCenter chassis IP address to use for the west test port",
                               dest="west_chassis_addr")
    requirednamed.add_argument("--west_slot_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter slot number to use for the west test port",
                               dest="west_slot_num")
    requirednamed.add_argument("--west_port_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter port number to use for the west test port",
                               dest="west_port_num")
    # Optional parameters
    optionalnamed = parser.add_argument_group("optional named arguments")
    optionalnamed.add_argument("--test_session_name",
                               required=False,
                               default="RFC2544 East-West Throughput",
                               help="The friendly name to identify the Spirent Lab Server test session",
                               dest="test_session_name")
    optionalnamed.add_argument("--results_dir",
                               required=False,
                               default="./Results",
                               help="The directory to copy results to",
                               dest="results_dir")
    optionalnamed.add_argument("--csv_results_file_prefix",
                               required=False,
                               default="Rfc2544Tput",
                               help="The prefix for the CSV results files",
                               dest="csv_results_file_prefix")
    optionalnamed.add_argument("--num_trials",
                               type=positive_int,
                               required=False,
                               default=1,
                               help="The number of trials to execute during the test",
                               dest="num_trials")
    optionalnamed.add_argument("--trial_duration_sec",
                               type=positive_int,
                               required=False,
                               default=60,
                               help="The duration of each trial executed during the test",
                               dest="trial_duration_sec")
    optionalnamed.add_argument("--traffic_pattern",
                               required=False,
                               choices=["BACKBONE", "MESH", "PAIR"],
                               default="PAIR",
                               help="The traffic pattern between endpoints",
                               dest="traffic_pattern")
    optionalnamed.add_argument("--search_mode",
                               required=False,
                               choices=["COMBO", "STEP", "BINARY"],
                               default="BINARY",
                               help="The search mode used to find the throughput rate",
                               dest="search_mode")
    optionalnamed.add_argument("--learning_mode",
                               required=False,
                               choices=["AUTO", "L2_LEARNING", "L3_LEARNING", "NONE"],
                               default="AUTO",
                               help="The learning mode used during the test, default = 'NONE'",
                               dest="learning_mode")
    optionalnamed.add_argument("--rate_lower_limit_pct",
                               type=percent_float,
                               required=False,
                               default=1.0,
                               help="The minimum percent line rate that will be used during the test",
                               dest="rate_lower_limit_pct")
    optionalnamed.add_argument("--rate_upper_limit_pct",
                               type=percent_float,
                               required=False,
                               default=99.0,
                               help="The maximum percent line rate that will be used during the test",
                               dest="rate_upper_limit_pct")
    optionalnamed.add_argument("--rate_initial_pct",
                               type=percent_float,
                               required=False,
                               default=99.0,
                               help="If Search Mode is BINARY, the percent line rate that will be used at the start of the test",
                               dest="rate_initial_pct")
    optionalnamed.add_argument("--rate_step_pct",
                               type=percent_float,
                               required=False,
                               default=10.0,
                               help="If SearchMode is STEP, the percent load increase per step",
                               dest="rate_step_pct")
    optionalnamed.add_argument("--resolution_pct",
                               type=percent_float,
                               required=False,
                               default=1.0,
                               help="The minimum percentage of load adjustment between iterations",
                               dest="resolution_pct")
    optionalnamed.add_argument("--frame_size_list",
                               type=lambda s: [int(item) for item in s.split(',')],
                               required=False,
                               default=[64, 128, 256],
                               help="A comma-delimited list of frame sizes",
                               dest="frame_size_list")
    optionalnamed.add_argument("--acceptable_frame_loss_pct",
                               type=percent_float,
                               required=False,
                               default=0.0,
                               help="The maximum acceptable frame loss percent in any iteration",
                               dest="acceptable_frame_loss_pct")
    optionalnamed.add_argument("--east_intf_addr",
                               required=False,
                               default="192.85.1.3",
                               help="The address to assign to the first emulated device interface on the first east port",
                               dest="east_intf_addr")
    optionalnamed.add_argument("--east_intf_gateway_addr",
                               required=False,
                               default="192.85.1.53",
                               help="The gateway address to assign to the first emulated device interface on the first east port",
                               dest="east_intf_gateway_addr")
    optionalnamed.add_argument("--west_intf_addr",
                               required=False,
                               default="192.85.1.53",
                               help="The address to assign to the first emulated device interface on the first west port",
                               dest="west_intf_addr")
    optionalnamed.add_argument("--west_intf_gateway_addr",
                               required=False,
                               default="192.85.1.53",
                               help="The gateway address to assign to the first emulated device interface on the first west port",
                               dest="west_intf_gateway_addr")
    parser.add_argument("-v",
                        "--verbose",
                        required=False,
                        default=False,
                        help="More output during operation when present",
                        action="store_true",
                        dest="verbose")
    args = parser.parse_args()

    if args.verbose:
        print("Make sure results directory exists")
    create_dir(args.results_dir)

    # Load Spirent Test Center library
    from StcPython import StcPython
    stc = StcPython()

    tx_port_loc = "//%s/%s/%s" % (args.east_chassis_addr,
                                  args.east_slot_num,
                                  args.east_port_num)
    rx_port_loc = "//%s/%s/%s" % (args.west_chassis_addr,
                                  args.west_slot_num,
                                  args.west_port_num)

    # This line will write the TestCenter commands to a log file
    stc.config("automationoptions", logto="test-op", loglevel="DEBUG")

    # Retrieve and display the current API version.
    if args.verbose:
        print ("SpirentTestCenter system version: %s" % stc.get("system1", "version"))

    create_session(stc, args.lab_server_addr, args.test_session_name)

    try:
        device_list = []

        if args.verbose:
            print("Bring up license server")
        license_mgr = stc.get("system1", "children-licenseservermanager")
        if args.verbose:
            print("license_mgr = %s" % license_mgr)
        stc.create("LicenseServer", under=license_mgr, server=args.license_server_addr)

        # Create the root project object
        if args.verbose:
            print ("Creating project ...")
        project = stc.get("System1", "children-Project")

        # Create ports
        if args.verbose:
            print ("Creating ports ...")
        east_chassis_port = stc.create("port",
                                       under=project,
                                       location=tx_port_loc,
                                       useDefaultHost="False")
        west_chassis_port = stc.create("port",
                                       under=project,
                                       location=rx_port_loc,
                                       useDefaultHost="False")

        if args.verbose:
            print ("Creating devices...")
        # Create emulated genparam for east port
        east_device_gen_params = stc.create("EmulatedDeviceGenParams",
                                            under=project,
                                            Port=east_chassis_port)
        # Create the DeviceGenEthIIIfParams object
        stc.create("DeviceGenEthIIIfParams",
                   under=east_device_gen_params)
        # Configuring Ipv4 interfaces
        stc.create("DeviceGenIpv4IfParams",
                   under=east_device_gen_params,
                   Addr=args.east_intf_addr,
                   Gateway=args.east_intf_gateway_addr)
        # Create Devices using the Device Wizard
        device_gen_config = stc.perform("DeviceGenConfigExpand",
                                        DeleteExisting="No",
                                        GenParams=east_device_gen_params)
        # Append to the device list
        device_list.append(device_gen_config['ReturnList'])

        # Create emulated genparam for west port
        west_device_gen_params = stc.create("EmulatedDeviceGenParams",
                                            under=project,
                                            Port=west_chassis_port)
        # Create the DeviceGenEthIIIfParams object
        stc.create("DeviceGenEthIIIfParams",
                   under=west_device_gen_params)
        # Configuring Ipv4 interfaces
        stc.create("DeviceGenIpv4IfParams",
                   under=west_device_gen_params,
                   Addr=args.west_intf_addr,
                   Gateway=args.west_intf_gateway_addr)
        # Create Devices using the Device Wizard
        device_gen_config = stc.perform("DeviceGenConfigExpand",
                                        DeleteExisting="No",
                                        GenParams=west_device_gen_params)
        # Append to the device list
        device_list.append(device_gen_config['ReturnList'])

        if args.verbose:
            print(device_list)

        # Create the RFC 2544 throughput test
        if args.verbose:
            print ("Set up the RFC2544 throughput test...")
        stc.perform("Rfc2544SetupThroughputTestCommand",
                    AcceptableFrameLoss=args.acceptable_frame_loss_pct,
                    Duration=args.trial_duration_sec,
                    FrameSizeList=args.frame_size_list,
                    LearningMode=args.learning_mode,
                    NumOfTrials=args.num_trials,
                    RateInitial=args.rate_initial_pct,
                    RateLowerLimit=args.rate_lower_limit_pct,
                    RateStep=args.rate_step_pct,
                    RateUpperLimit=args.rate_upper_limit_pct,
                    Resolution=args.resolution_pct,
                    SearchMode=args.search_mode,
                    TrafficPattern=args.traffic_pattern)

        # Save the configuration
        stc.perform("SaveToTcc", Filename="2544.tcc")

        # Connect to the hardware...
        stc.perform("AttachPorts", portList=stc.get("system1.project", "children-port"), autoConnect="TRUE")

        # Apply configuration.
        if args.verbose:
            print("Apply configuration...")
        stc.apply

        if args.verbose:
            print("Starting the sequencer...")
        stc.perform("SequencerStart")

        # Wait for sequencer to finish
        print("Starting test... Please wait for the test to complete...")
        stc.waitUntilComplete()
        print("The test has completed... Saving results...")

        # Determine what the results database filename is...
        lab_server_resultsdb = stc.get("system1.project.TestResultSetting", "CurrentResultFileName")

        if args.verbose:
            print("The lab server results database is %s" % lab_server_resultsdb)

        stc.perform("CSSynchronizeFiles",
                    DefaultDownloadDir=args.results_dir)

        resultsdb = args.results_dir + lab_server_resultsdb.split("/Results")[1]

        print("The local summary DB file has been saved to %s" % resultsdb)

        # The returns the "RFC2544ThroughputTestResultDetailedSummaryView" table view from the results database.
        # There are other views available.
        resultsdict = stc.perform("QueryResult",
                                  DatabaseConnectionString=resultsdb,
                                  ResultPath="RFC2544ThroughputTestResultDetailedSummaryView")
        if args.verbose:
            print("resultsdict[\"Columns\"]: %s" % resultsdict["Columns"])
            print("resultsdict[\"Output\"]: %s" % resultsdict["Output"])

        if args.verbose:
            print("Result paths: %s" % stc.perform("GetTestResultSettingPaths"))

        # Write results to csv
        if args.verbose:
            print("Writing CSV file to results directory %s" % args.results_dir)
        write_query_results_to_csv(args.results_dir, args.csv_results_file_prefix, resultsdict)

    except Exception, e:
        print("Exception: %s" % str(e))
        # destroy_session(stc, args.lab_server_addr, args.test_session_name)
        raise
Exemplo n.º 7
0
# possibility of such damage.

# File Name:                 Anatomy.py
# Description:               This script demonstrates basic features 
#                            such as creating streams, generating traffic,
#                            enabling capture, saving realtime results
#                            to files, and retrieving results.

import sys
import time

ENABLE_CAPTURE = True

# This loads the TestCenter library.
from StcPython import StcPython
stc = StcPython()

stc.log("INFO", "Starting Test")

# This line will show the TestCenter commands on stdout
#stc.config("automationoptions", logto="stdout", loglevel="INFO")

# Retrieve and display the current API version.
print "SpirentTestCenter system version:\t", stc.get("system1", "version")

# Physical topology
szChassisIp1 = "10.29.0.49"
szChassisIp2 = "10.29.0.45"
txPortLoc = "//%s/%s/%s" % ( szChassisIp1, 1, 1)
rxPortLoc = "//%s/%s/%s" % ( szChassisIp2, 1, 1)
Exemplo n.º 8
0
port1_location = '//10.2.100.6/1/1'
port2_location = '//10.2.100.6/1/2'
# Results dir name
results_dir = 'untitled-results'
#################################

# All possible generator, analyzer, rxstreamsummary port result attributes:
generator_attributes = 'totalframecount totaloctetcount generatorframecount generatoroctetcount generatorsigframecount generatorundersizeframecount generatoroversizeframecount generatorjumboframecount totalframerate totaloctetrate generatorframerate generatoroctetrate generatorsigframerate generatorundersizeframerate generatoroversizeframerate generatorjumboframerate generatorcrcerrorframecount generatorl3checksumerrorcount generatorl4checksumerrorcount generatorcrcerrorframerate generatorl3checksumerrorrate generatorl4checksumerrorrate totalipv4framecount totalipv6framecount totalmplsframecount generatoripv4framecount generatoripv6framecount generatorvlanframecount generatormplsframecount totalipv4framerate totalipv6framerate totalmplsframerate generatoripv4framerate generatoripv6framerate generatorvlanframerate generatormplsframerate totalbitrate generatorbitrate l1bitcount l1bitrate pfcframecount pfcpri0framecount pfcpri1framecount pfcpri2framecount pfcpri3framecount pfcpri4framecount pfcpri5framecount pfcpri6framecount pfcpri7framecount l1bitratepercent'

analyzer_attributes = 'totalframecount totaloctetcount sigframecount undersizeframecount oversizeframecount jumboframecount minframelength maxframelength pauseframecount totalframerate totaloctetrate sigframerate undersizeframerate oversizeframerate jumboframerate pauseframerate fcserrorframecount ipv4checksumerrorcount tcpchecksumerrorcount udpchecksumerrorcount prbsfilloctetcount prbsbiterrorcount fcserrorframerate ipv4checksumerrorrate tcpchecksumerrorrate udpchecksumerrorrate prbsfilloctetrate prbsbiterrorrate ipv4framecount ipv6framecount ipv6overipv4framecount tcpframecount udpframecount mplsframecount icmpframecount vlanframecount ipv4framerate ipv6framerate ipv6overipv4framerate tcpframerate udpframerate mplsframerate icmpframerate vlanframerate trigger1count trigger1rate trigger2count trigger2rate trigger3count trigger3rate trigger4count trigger4rate trigger5count trigger5rate trigger6count trigger6rate trigger7count trigger7rate trigger8count trigger8rate combotriggercount combotriggerrate totalbitrate prbsbiterrorratio vlanframerate l1bitcount l1bitrate pfcframecount fcoeframecount pfcframerate fcoeframerate pfcpri0framecount pfcpri1framecount pfcpri2framecount pfcpri3framecount pfcpri4framecount pfcpri5framecount pfcpri6framecount pfcpri7framecount pfcpri0quanta pfcpri1quanta pfcpri2quanta pfcpri3quanta pfcpri4quanta pfcpri5quanta pfcpri6quanta pfcpri7quanta prbserrorframecount prbserrorframerate userdefinedframecount1 userdefinedframerate1 userdefinedframecount2 userdefinedframerate2 userdefinedframecount3 userdefinedframerate3 userdefinedframecount4 userdefinedframerate4 userdefinedframecount5 userdefinedframerate5 userdefinedframecount6 userdefinedframerate6 l1bitratepercent outseqframecount preambletotalbytes preambleminlength preamblemaxlength droppedframecount inorderframecount reorderedframecount duplicateframecount lateframecount firstarrivaltime lastarrivaltime'

rxstreamsummaryresults_attributes = 'avginterarrivaltime avgjitter avglatency bitcount bitrate cellcount cellrate comp16_1 comp16_2 comp16_3 comp16_4 comp32 countertimestamp droppedframecount droppedframepercent droppedframepercentrate droppedframerate duplicateframecount duplicateframerate expectedseqnum fcserrorframecount fcserrorframerate firstarrivaltime framecount framerate histbin10count histbin10name histbin10rate histbin11count histbin11name histbin11rate histbin12count histbin12name histbin12rate histbin13count histbin13name histbin13rate histbin14count histbin14name histbin14rate histbin15count histbin15name histbin15rate histbin16count histbin16name histbin16rate histbin1count histbin1name histbin1rate histbin2count histbin2name histbin2rate histbin3count histbin3name histbin3rate histbin4count histbin4name histbin4rate histbin5count histbin5name histbin5rate histbin6count histbin6name histbin6rate histbin7count histbin7name histbin7rate histbin8count histbin8name histbin8rate histbin9count histbin9name histbin9rate inorderframecount inorderframerate inseqframecount inseqframerate ipv4checksumerrorcount ipv4checksumerrorrate l1bitcount l1bitrate lastarrivaltime lastseqnum lateframecount lateframerate maxframelength maxinterarrivaltime maxjitter maxlatency minframelength mininterarrivaltime minjitter minlatency octetcount octetrate outseqframecount outseqframerate portstrayframes prbsbiterrorcount prbsbiterrorrate prbsbiterrorratio prbserrorframecount prbserrorframerate prbsfilloctetcount prbsfilloctetrate reorderedframecount reorderedframerate rfc4689absoluteavgjitter rxport seqrunlength shorttermavginterarrivaltime shorttermavgjitter shorttermavglatency sigframecount sigframerate streamindex tcpudpchecksumerrorcount tcpudpchecksumerrorrate totalinterarrivaltime totaljitter totaljitterrate totallatency'
#################################

# Create Spirent API instance
stc = StcPython()
# Create project - the root object
hProject = stc.create("project")
# Print WARN and ERROR messages
stc.config("automationoptions", logTo='stdout', logLevel='WARN')

# Load configuration from XML
stc.perform('loadfromxml', filename=xml_filename)
# Search for objects of type 'Port' in the configuration and extract them
rv = stc.perform('GetObjects', ClassName='Port', Condition='IsVirtual=false')
ports = str.split(rv['ObjectList'])
if len(ports) != 2:
    print("Error: failed to find two ports in configuration\n")
    exit(1)

# Configure ports, set results dir, set sequencer to stop on error
import sys
sys.path.append('/home/mjefferson/spirent/stc/stc4.61/API/Python/')
from StcPython import StcPython
stc = StcPython()

port_traffic1 = stc.create("port", under="project1")
port_traffic2 = stc.create("port", under="project1")

# NOTE: The FrameConfig PDUs are case-sensitive.
#       Examples are: EthernetII, Vlan, IPv4, IPv6, Mpls, Tcp, UDP, PPP, Gre, etc. There are many more.
# Default: "EthernetII IPv4"}
streamblock1 = stc.create("StreamBlock",
                          under=port_traffic1,
                          FrameConfig="EthernetII IPv4")
stc.get(streamblock1)
stc.config(streamblock1 + ".ethernet:EthernetII",
           srcMac="00:11:94:00:00:02",
           dstMac="00:12:94:00:00:02")
stc.config(streamblock1 + ".ipv4:IPv4",
           sourceAddr="192.168.11.2",
           destAddr="192.168.12.2",
           gateway="192.168.11.1",
           prefixlength="24",
           destprefixlength="24")

streamblock2 = stc.create("StreamBlock",
                          under=port_traffic2,
                          FrameConfig="EthernetII IPv4")
stc.get(streamblock2)
stc.config(streamblock2 + ".ethernet:EthernetII",
           srcMac="00:12:94:00:00:02",
                   under=sbrds,
                   ResultRootList=project,
                   ConfigClassId="StreamBlock",
                   ResultClassId="RxStreamBlockResults")

    return sbrds


print("Loading the Spirent TestCenter API...")
#sys.path.append('/home/mjefferson/spirent/stc/stc4.66/API/Python')
sys.path.append(
    'C:/Program Files (x86)/Spirent Communications/Spirent TestCenter 4.66/Spirent TestCenter Application/API/Python'
)

from StcPython import StcPython
stc = StcPython()

labserverip = "192.168.130.207"
sessionname = "test"
username = "******"

# Connect to an existing Lab Server session...
print("Connecting to the Lab Server...")
stc.perform("CSTestSessionConnect",
            host=labserverip,
            TestSessionName=sessionname,
            OwnerId=username,
            CreateNewTestSession="false")

project = stc.get("system1", "children-project")
Exemplo n.º 11
0
import os.path
import re

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print("Loading the Spirent TestCenter API...")
#sys.path.append('/home/mjefferson/spirent/stc/stc4.66/API/Python')
sys.path.append(
    'c:/program files (x86)/Spirent Communications/Spirent TestCenter 4.66/Spirent TestCenter Application/API/Python'
)
from StcPython import StcPython
stc = StcPython()

###############################################################################
####
####    Global variables
####
###############################################################################

labserverip = '192.168.130.207'
sessionname = 'test'
username = '******'


###############################################################################
####
####    Procedures
Exemplo n.º 12
0
print "Loading libraries..."

import sys
#import time
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Create the configuration from scratch.
print "Creating the configuration from scratch..."
project = stc.get("system1", "children-project")

# Start by creating two ports. port1 is the Tx port, and port2 is the Rx.
port1 = stc.create("port", under=project, location="10.140.99.120/1/1")
port2 = stc.create("port", under=project, location="10.140.99.121/1/1")

# Create a single Emulated Device on each port.
# The "IfStack" is the space-separated list of interface objects used by the device.
# It is sorted top-down, meaning that the EthIIIf object will be the last element of the list.
Exemplo n.º 13
0
##############################################################################

import time
import json
import requests
import sys

# This loads the TestCenter library.
from StcPython import StcPython

# This loads the AN/LT Transceiver Tune library.
from l1_tune_alg import L1Tune, L1TuneRough

print("Loading TestCenter library ... "),
sys.stdout.flush()
stc = StcPython()
print("Done.")

#########################################################################################

# port1_location is to tune
g_port1_location = "//neb-nickluong-01.calenglab.spirentcom.com/1/1"
g_port2_location = "//neb-nickluong-01.calenglab.spirentcom.com/1/2"
#g_port1_location = ""
#g_port2_location = ""

g_interface = "COPPER"
g_resultdbid = ""
g_iqserviceurl = ""

g_port1_name = ""
#                            to files, and retrieving results.

import sys
import time

ENABLE_CAPTURE = True

# This loads the TestCenter library. 
# Note that a viable Tcl environment must be available for the library to run
# and that the Python Tkinter package must be installed.
# The version of the TestCenter library that will be loaded will be determined
# by normal Tcl package management. The easiest way to change versions will be
# to set the TCLLIBPATH environment variable to point to the desired version
# just like would be done in a normal Tcl installation.
from StcPython import StcPython
stc = StcPython()

stc.log("INFO", "Starting Test")

# This line will show the TestCenter commands on stdout
#stc.config("automationoptions", logto="stdout", loglevel="INFO")

# Retrieve and display the current API version.
print "SpirentTestCenter system version:\t", stc.get("system1", "version")

# Physical topology
szChassisIp = "192.168.22.253"
iTxSlot = 2
iTxPort = 1
iRxSlot = 2
iRxPort = 2
Exemplo n.º 15
0
import sys
import os.path
import re
import pyparsing

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.62/API/Python')
from StcPython import StcPython
stc = StcPython()

# Prevent the API from output log messages to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Each results database file contains a number of result "views", which are
# statistics in a tabular format (rows and columns). Each database contains a number
# of different ResultPaths (views). You can use the "getValidResultPaths" function to
# determine what the valid ResultPaths are for any database.
# Once you have a valid ResultPath, you can pass it into the "QueryResult" command to
# extract the result data from the database.

resultsdbfilename = "test.db"
for resultpath in getValidResultPaths(resultsdbfilename):
    try:
        result = stc.perform("QueryResult",
Exemplo n.º 16
0
import json
# This loads the TestCenter library.
from StcPython import StcPython
stc = StcPython()

port1_location = "//neb-nickluong-01.calenglab.spirentcom.com/1/17"
port2_location = "//neb-nickluong-01.calenglab.spirentcom.com/1/25"

print("reserving ports")
ret = stc.perform("createandreserveports",
                  locationlist=[port1_location, port2_location])

hportlist = ret["PortList"].split()

hport1 = hportlist[0]
hport2 = hportlist[1]

print("config port1 lane 0 PRBS TxPattern as PRBS7")
stc.config("%s.l1configgroup.l1portprbs.l1laneprbspam4(1)" % hport1,
           TxPattern="PRBS7")

stc.apply()

stc.perform("startenhancedresultstestcommand")

query_json = {
    "definition": {
        "multi_result": {
            "filters": [],
            "groups": [],
            "orders": [
Exemplo n.º 17
0
print "Loading libraries..."

import sys
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all log entries to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Create the configuration from scratch.
print "Creating the configuration from scratch..."
project = stc.get("system1", "children-project")

# Start by creating two ports. port1 is the Tx port, and port2 is the Rx.
port1 = stc.create("port", under=project, location="10.140.99.120/1/1")
port2 = stc.create("port", under=project, location="10.140.99.121/1/1")

# Create a single Emulated Device on each port.
# The "IfStack" is the space-separated list of interface objects used by the device.
# It is sorted top-down, meaning that the EthIIIf object will be the last element of the list.
Exemplo n.º 18
0
class StcDriver(API):
   
    def __init__(self):
        #super(API, self).__init__()
        self.handle = StcPython()
        main.log.info("STC component initialized")

    def connect(self,**connectargs):
        for key in connectargs:
            vars(self)[key] = connectargs[key]

        self.name = self.options['name']
        main.log.info("Component name is "+self.name)
        connect_result = super(API,self).connect()
        main.log.info("Main dir "+main.logdir)
        self.logFileName = main.logdir+"/"+self.name+".session"
        main.log.info("Session log file is "+self.logFileName)
        self.handle.config('automationoptions', loglevel='info',logto=self.logFileName)
        main.log.info("Connected successfully")
        return main.TRUE
    
    def apply(self):
        try :
            main.log.info("apply the action")
            return self.handle.apply()
        except :
            main.log.error("Apply failed because of Exception"+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE , 'error' : sys.exc_info()[0]}
    
    def create(self,objectTypeString,**arguments) :
        try :
            main.log.info("creating arguments") 
            #return { result : main.TRUE,return value : self.handle.create(objectTypeString,**arguments) }
            return self.handle.create(objectTypeString,**arguments)
            #return ReturnValue(main.TRUE,self.handle.create(objectTypeString,**arguments))
        except :
            main.log.error("Operation "+str(objectTypeString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    
    def config(self,handleString,**attributes) :
        try :
            main.log.info("Configure Port locations")
            self.handle.config(handleString,**attributes)
            #return { result : main.TRUE, return value : slef.handle.config(handleString,**attributes)}
            return self.handle.config(handleString,**attributes)
            #return ReturnValue(main.TRUE,self.handle.config(handleString,**attributes))
        except :
            main.log.error("Operation "+str(handleString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] } 
    
    def get(self,handleString, attribute) :
        try :
            main.log.info("Getting attributes for "+str(handleString))
            #return { result : main.TRUE , return value : self.handle.get(handleString,attribute)}
            return self.handle.get(handleString, attribute)
            #return ReturnValue(main.TRUE,self.handle.get(handleString, attribute))
        except :
            main.log.error("operation"+str(handleString)+"failed because of exception"+str(sys.exc_info()[0]))
            return { 'result' :main.FALSE , 'error': sys.exc_info()[0]}

    def perform(self,commandNameString, **attribute) :
        try :
            main.log.info("Performing action "+str(commandNameString))
            #return { result : main.TRUE , return value : self.handle.perform(commandNameString,**attribute)}
            return self.handle.perform(commandNameString, **attribute)
            #return ReturnValue(main.TRUE , self.handle.perform(commandNameString,**attribute))
        except :
            main.log.error("Operation "+str(commandNameString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }
    
    def subscribe(self,**inputParams) :
        try :
            main.log.info("subscribe the result")
            #return { result : main.TRUE , return value : self.handle.subscribe(**inputParams)}
            return self.handle.subscribe(**inputParams)
            #return ReturnValue(main.TRUE,self.handle.subscribe(**inputParams))
        except :
            main.log.error("Operation failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE , 'error' : sys.exc_info()[0] }

    def disconnect(self,hostNameString) :
        try :
            main.log.info("disconnect")
            #return { result : main.TRUE ,return value : self.handle.disconnect(hostNameString)}
            return self.handle.disconnect(str(hostNameString))
            #return ReturnValue(main.TRUE,self.handle.disconnect(hostNameString))
        except :
            main.log.error("Operation failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    def sleep(self,numberSecondsInteger) :
        try :
            main.log.info("sleep time is")
            #return { result : main.TRUE , return value : self.handle.sleep(numberSecondsInteger)}
            return self.handle.sleep(numberSecondsInteger)
            #return ReturnValue(main.TRUE,self.handle.sleep(numberSecondsInteger))
        except :
            main.log.error("Operation failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    def unsubscribe(self,resultDataSetHandleString) :
        try :
            main.log.info("unsubscribe the ports"+str(resultDataSetHandleString))
            return self.handle.unsubscribe(str(resultDataSetHandleString))
            #return { result : main.TRUE , return value : self.handle.unsubscribe(resultDataSetHandleString)}
            #return ReturnValue(main.TRUE,self.handle.unsubscribe(resultDataSetHandleString))
        except :
            main.log.error("unsubscribe"+str(resultDataSetHandleString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    def delete(self,handleString) :
        try :
            main.log.info("Deleting ports"+str(handleString))
            return self.handle.delete(str(handleString))
            #return ReturnValue(main.TRUE,self.handle.delete(handleString))
        except :
            main.log.error("Deletion of "+str(handleString)+"failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }
    def parseresults(self,Attribute,CsvFile) :
        
        try :
            main.log.info("parsing the CSV file for the traffic results")                 
            totalrows = len(open('/home/sudheer-570/Desktop/sk/TestON/bin/Untitled/'+CsvFile).readlines())
            fp = open("/home/sudheer-570/Desktop/sk/TestON/bin/Untitled/"+CsvFile,'Ur')
            data_list = []
            attributes=[]
            attribute_values=[]
            for line in fp:
                data_list.append(line.strip().split(','))
            attribute_values=data_list[totalrows-1]
            attributes=data_list[totalrows-3]

            for index in range (0,100) :
                if attributes[index]==Attribute:
                    main.log.info("Given Attribute Name is:'"+Attribute+"'")
                    main.log.info("Attribute value is:'"+attribute_values[index]+"'")
                    result = attribute_values[index]
                    if result == '0' :
                        main.log.info("Traffic is not generated on this attribute :"+Attribute)
                        return main.FALSE
                    else :
                        return result
        except :
            main.log.error("operation failed because of"+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }
Exemplo n.º 19
0
import sys
import time
import datetime
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.61/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

stc.perform("LoadFromDatabaseCommand",
            DatabaseConnectionString="capturetest.tcc")

# Remap port locations if necessary.
for port, location in zip(
        stc.get("system1.project", "children-port").split(), port_locations):
    print "Remapping " + port + " to " + location
    stc.config(port, location=location)

# Connect to the hardware.
stc.perform("AttachPorts",
Exemplo n.º 20
0
 def __init__(self):
     #super(API, self).__init__()
     self.handle = StcPython()
     main.log.info("STC component initialized")
Exemplo n.º 21
0
#	Port 1/1 default gateway - 192.168.202.2/24
#	Port 1/2 default gateway - 192.168.203.2/24
#	Chassis IP 		 - 10.2.100.6

STRESS_TESTS_DIR = 'stress_tests'
VERIFICATION_TESTS_DIR = 'verification_tests'
STRESS_TESTS_TO_RUN = 6  # how many random stress tests to run in iteration
SAPEE_TEST_LEN = 45  # SAPEE test duration in minutes

# Collect test files
stress_test_files = glob.glob(os.path.join(STRESS_TESTS_DIR, '*.xml'))
verification_test_files = glob.glob(
    os.path.join(VERIFICATION_TESTS_DIR, '*.xml'))

# Create Spirent API instance
stc = StcPython()


# Common setup before test
def common_init(test_dir, file_name):
    # Create project - the root object
    hProject = stc.create("project")

    # Print WARN and ERROR messages
    stc.config("automationoptions", logTo='stdout', logLevel='WARN')

    # Load configuration from XML, set results dir, set sequencer to stop on error
    stc.perform('loadfromxml', filename=file_name)
    results_dir = os.path.join(test_dir,
                               os.path.basename(os.path.splitext(testfile)[0]))
    stc.config(hProject + '.testResultSetting',
Exemplo n.º 22
0
Created on Feb 21, 2014

@author: khiemtd
'''
'''
def tinnh(L):
    if not L:
        return 0
    else:
        return L[0]+ tinnh(L[1:])
L=([1,2,3,4,5])
print tinnh(L)
'''
from StcPython import StcPython

stc = StcPython()
#print stc.get('system1', 'version')

chassisAddress = '172.33.42.4'
slot = 4
port = 3
print "using //%s/%s/%s" % (chassisAddress, slot, port)

#stc.connect('172.33.42.4')
#stc.reserve('//172.33.42.4/4/3')

print 'Create a Project  - root'

project = stc.create('project')

print 'Get Project attributes'
Exemplo n.º 23
0
print "Loading libraries..."

import sys
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all log entries to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Create the configuration from scratch.
print "Creating the configuration from scratch..."
project = stc.get("system1", "children-project")

# Start by creating two ports. port1 is the Tx port, and port2 is the Rx.
port1 = stc.create("port", under=project, location="10.140.99.120/1/1")

###############################################################################
####
####    Method 1 : DeviceCreateCommand
####
Exemplo n.º 24
0
###############################################################################


import sys
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.62/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all log entries to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# The project object always exists (no need to create it).
project = stc.get("system1", "children-project")

# Create a single port that we want to enable routing emulation on.
port1 = stc.create("port", under=project, location="10.140.99.120/1/1")

# Create an emulated device associated with the port.
result = stc.perform("DeviceCreate", ParentList=project, DeviceType="Router", IfStack="Ipv4If EthIIIf", IfCount="1 1", Port=port1)
emulateddevice = result["ReturnList"]