def MoveFile(** kwargs): """ Library function to move files on workstations :param deviceObj : Device object :type deviceObj : object :param sourceFilePath : Filepath of the file to be moved :type sourceFilePath : string :param destinationFilePath : Destination filepath :type destinationFilePath : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) sourceFilePath = kwargs.get('sourceFilePath', None) destinationFilePath = kwargs.get('destinationFilePath', None) # Variables returnCode = 0 overallBuffer = [] # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Move files on workstation to destination path command = "mv -f " + str(sourceFilePath) + " " + str(destinationFilePath) returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to move files %s on %s->" % (sourceFilePath, deviceObj.device)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Moved the file %s on %s ->" % (sourceFilePath, deviceObj.device)) bufferString = ' ' for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def MoveFile(**kwargs): """ Library function to move files on workstations :param deviceObj : Device object :type deviceObj : object :param sourceFilePath : Filepath of the file to be moved :type sourceFilePath : string :param destinationFilePath : Destination filepath :type destinationFilePath : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) sourceFilePath = kwargs.get('sourceFilePath', None) destinationFilePath = kwargs.get('destinationFilePath', None) # Variables returnCode = 0 overallBuffer = [] # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Move files on workstation to destination path command = "mv -f " + str(sourceFilePath) + " " + str(destinationFilePath) returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to move files %s on %s->" % (sourceFilePath, deviceObj.device)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Moved the file %s on %s ->" % (sourceFilePath, deviceObj.device)) bufferString = ' ' for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def GetServicePID(**kwargs): """ Library function to get the PID of a server service :param deviceObj : Device object :type deviceObj : object :param service : service(freeradius/dhcpd/tftp) :type service : string :return: returnStruct Object data: - Dictionary: 'pid': PID of the service running :returnType: object """ service = kwargs.get('service', None) deviceObj = kwargs.get('deviceObj', None) returnDict = dict() returnCode = 0 # Confirm service pid command = "pgrep " + str(service) returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') if returnCode != 0: opstestfw.LogOutput( 'error', "pid for service %s : service not running" % (service)) returnCls = opstestfw.returnStruct( returnCode=returnCode, data=returnDict, buffer=buffer) else: splitBuffer = buffer.split("\r\n") for line in splitBuffer: line = line.strip() pidMatch = re.match(r'(\d+)', line) if pidMatch: returnDict['pid'] = pidMatch.group(1) opstestfw.LogOutput( 'info', "%s service pid :: %s" % (service, returnDict['pid'])) # Compile information to return returnCls = opstestfw.returnStruct( returnCode=returnCode, data=returnDict, buffer=buffer) return returnCls
def FileEdit(** kwargs): """ Library function to edit/make new files :param deviceObj : Device object :type deviceObj : object :param stringEdit : File string content :type stringEdit : string :param filename : Filepath of the file to be edited :type filename : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) stringEdit = kwargs.get('stringEdit', None) filename = kwargs.get('filename', None) overallBuffer = [] command = "echo " + str(stringEdit) + " > " + filename returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to edit file %s on %s->" % (filename, deviceObj.device)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Edited file %s on %s->" % (filename, deviceObj.device)) bufferString = ' ' for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def FileEdit(**kwargs): """ Library function to edit/make new files :param deviceObj : Device object :type deviceObj : object :param stringEdit : File string content :type stringEdit : string :param filename : Filepath of the file to be edited :type filename : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) stringEdit = kwargs.get('stringEdit', None) filename = kwargs.get('filename', None) overallBuffer = [] command = "echo " + str(stringEdit) + " > " + filename returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to edit file %s on %s->" % (filename, deviceObj.device)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Edited file %s on %s->" % (filename, deviceObj.device)) bufferString = ' ' for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def hostIperfClientStart(**kwargs): """ Library function to generate traffic using iperf. :param deviceObj : Device object :type deviceObj : object :param time : amount of time in seconds where traffic will be sent :type time : integer :param protocol : UDP or TCP :type protocol : string :param interval : Result reporting interval :type interval : integer :param port : server port number :type port : integer :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) port = kwargs.get('port', 5001) serverIP = kwargs.get('serverIP', None) protocol = kwargs.get('protocol', 'TCP') interval = kwargs.get('interval', 1) rtime = kwargs.get('time', 10) # Variables bufferString = '' # If device is not passed, we need error message if deviceObj is None or serverIP is None: opstestfw.LogOutput( 'error', "Need to pass device to configure and server IP address.") returnStruct = opstestfw.returnStruct(returnCode=1) return returnStruct # Verify if iperf is installed on host assuming it is Ubuntu and then # install it command = 'iperf' opstestfw.LogOutput( 'debug', "Verifying if iperf is installed on device " + deviceObj.device) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect( ['Usage', '(command not found)|(install)']) bufferString += str(deviceObj.expectHndl.before) if index == 0: # In case iperf is installed index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput( 'error', "Error while verifying status of iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: # In case iperf is not installed index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput( 'error', "Error while verifying status of iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) opstestfw.LogOutput('debug', "Installing iperf") command = 'apt-get install iperf' deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=30) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput( 'error', "Error while installing iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) command = 'iperf' deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect( ['Usage', '(command not found)|(install)', pexpect.TIMEOUT]) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput('error', "Could not install iperf correctly") index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput('error', "Unknown error on device") return opstestfw.returnStruct(returnCode=1, buffer=bufferString) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput('error', "Unknown error on device") return opstestfw.returnStruct(returnCode=1, buffer=bufferString) opstestfw.LogOutput('debug', "Successfully installed iperf on device") command = 'iperf -c ' + str(serverIP) + ' -p ' + str(port) command += ' -i ' + str(interval) command += ' -t ' + str(rtime) if protocol == 'UDP': command += ' -u' deviceObj.expectHndl.sendline(command) # Compile information to return bufferString = "" returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagFallback(**kwargs): """ Library function to configure fallback settings for a LAG working in dynamic mode :param deviceObj : Device object :type deviceObj : object :param lagId : LAG Identifier :type lagId : integer :param fallbackFlag : off: Static LAG active: Active dynamic LAG passive: Passive dynamic LAG :type fallbackFlag : string :return: returnStruct Object :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) fallbackFlag = kwargs.get('fallbackFlag', True) # Variables overallBuffer = [] finalReturnCode = 0 # If deviceObj, lagId or fallbackFlag are not passed, we need to throw # an error if deviceObj is None or lagId is None: opstestfw.LogOutput( 'error', "Need to pass deviceObj and lagId to use " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to create LAG " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput( 'debug', "Created LAG " + str(lagId) + " on device " + deviceObj.device) # configure LAG's LACP fallback settings if fallbackFlag is True: command = "lacp fallback" else: command = "no lacp fallback" returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: if fallbackFlag is True: opstestfw.LogOutput( 'error', "Failed to enable LACP fallback on interface " "lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput( 'error', "Failed to disable LACP fallback on interface " "lag " + str(lagId) + " on device " + deviceObj.device) else: if fallbackFlag is True: opstestfw.LogOutput( 'debug', "Enabled LACP fallback on interface lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput( 'debug', "Disabled LACP fallback on interface lag " + str(lagId) + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def lagpGlobalSystemPriority(**kwargs): """ Function to configure Global LACP system Priority :param deviceObj : Device object :type deviceObj : object :param systemPriority : Identification Default is system MAC address, can be changed for another one :type systemPriority : string :param configure : (Optional -Default is True) True to configure, False to unconfigure :type configure : boolean :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) systemPriority = kwargs.get('systemPriority', None) configure = kwargs.get('configure', True) # Variables overallBuffer = [] data = dict() bufferString = "" command = "" # If Device object is not passed, we need to error out if deviceObj is None or systemPriority is None: opstestfw.LogOutput( 'error', "Need to pass switch deviceObj and systemPriority" " to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtysh returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Uconfigure system ID if configure is False: command = "no " # Normal configuration command command += ("lacp system-priority " + str(systemPriority)) returnStructure = deviceObj.DeviceInteract(command=command) retCode = returnStructure['returnCode'] overallBuffer.append(returnStructure['buffer']) if retCode != 0: opstestfw.LogOutput( 'error', "Failed to configure LACP system priority: " + str(systemPriority)) else: opstestfw.LogOutput( 'debug', "LACP system priority configured: " + str(systemPriority)) # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit configure terminal prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.retStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit enable prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.retStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Return results for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString, data=data) return returnCls
def LogoutInbandSshSession(** kwargs): """ Library function to logout/exit from a user initiated inband SSH session The device object that must be passed here references the inband ssh session initiated from the workstations . :param deviceObj : Device object(Pass the device object of the ssh DUT session) :type deviceObj : object :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) # Variables bufferString = '' overallBuffer = [] returnCode = 0 # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device object") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson expectList = ['\[root@\S+.*\]#', 'root@\S+#', pexpect.EOF, pexpect.TIMEOUT] # Clear out buffer try: buf = deviceObj.expectHndl.read_nonblocking(128, 0) except pexpect.TIMEOUT: pass except pexpect.EOF: pass command = "exit" deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) bufferString += str(deviceObj.expectHndl.before) print index if index == 0 or index == 1: bufferString += str(deviceObj.expectHndl.before) opstestfw.LogOutput("info","Logged out from the session **") else : bufferString += str(deviceObj.expectHndl.before) opstestfw.LogOutput("error","Session not logged out**") returnCode = 1 deviceObj.expectHndl.expect(['$'], timeout=2) bufferString += str(deviceObj.expectHndl.after) overallBuffer.append(bufferString) for curLine in overallBuffer: bufferString += str(curLine) #Compile information to return returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=overallBuffer) return returnCls
def hostIperfServerStart(** kwargs): """ Library function to receive traffic using iperf. :param deviceObj : Device object :type deviceObj : object :param protocol : UDP or TCP :type protocol : string :param interval : Result reporting interval :type interval : integer :param port : server port number :type port : integer :return: returnStruct Object data: - Dictionary: 'Client IP': Server IP address 'Client port': Client port 'Server IP': Server IP address 'Server port': Server port :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) port = kwargs.get('port', 5001) protocol = kwargs.get('protocol', 'TCP') interval = kwargs.get('interval', 1) # Variables bufferString = '' # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Verify if iperf is installed on host assuming it is Ubuntu and then # install it command = 'iperf' opstestfw.LogOutput( 'debug', "Verifying if iperf is installed on device " + deviceObj.device) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect( ['Usage', '(command not found)|(install)']) bufferString += str(deviceObj.expectHndl.before) if index == 0: # In case iperf is installed index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput( 'error', "Error while verifying status of iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: # In case iperf is not installed index = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput( 'error', "Error while verifying status of iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) opstestfw.LogOutput('debug', "Installing iperf") command = 'apt-get install iperf' deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect( ['# ', pexpect.TIMEOUT], timeout=40) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput( 'error', "Error while installing iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) command = 'iperf' deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect( ['Usage', '(command not found)|(install)', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput('error', "Could not install iperf correctly") index = deviceObj.expectHndl.expect( ['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput('error', "Unknown error on device") return opstestfw.returnStruct(returnCode=1, buffer=bufferString) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: index = deviceObj.expectHndl.expect( ['# ', pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput('error', "Unknown error on device") return opstestfw.returnStruct(returnCode=1, buffer=bufferString) opstestfw.LogOutput('debug', "Successfully installed iperf on device") command = 'iperf -s -p ' + str(port) command += ' -i ' + str(interval) if protocol == 'UDP': command += ' -u' deviceObj.expectHndl.sendline(command) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def VlanDescription(**kwargs): """ Library function to show the VLANs. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param description : string with the VLAN description. This is casted to string. :type description : string :param config : True if a VLAN description is to be added, False if a VLAN description is to be deleted. Defaults to True. :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) description = kwargs.get('description', None) config = kwargs.get('config', True) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None or description is None or vlanId is None: opstestfw.LogOutput('error', "Need to pass switch device object deviceObj, " "VLAN id vlanId and VLAN description description " "to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "vlan " + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to get into vlan prompt." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Created VLAN." + command) if config: command = "" else: command = "no " command = command + "description " + str(description) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: if config: opstestfw.LogOutput('error', "Failed to set the VLAN description." + command) else: opstestfw.LogOutput('error', "Failed to remove the VLAN description." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "VLAN description set." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit vlan context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited VLAN context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def VlanStatus(**kwargs): """ Library function to set a VLAN status. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param status : True to set the status to up, False to set the status to down :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) status = kwargs.get('status', None) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None or vlanId is None: opstestfw.LogOutput('error', "Need to pass switch device object deviceObj and" " VLAN Id vlanId to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "vlan " + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to create VLAN." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Created VLAN." + command) if status: command = "no shutdown" else: command = "shutdown" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to set the VLAN status." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "VLAN status set." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit vlan context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited VLAN context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagpGlobalSystemShow(**kwargs): """ Function to extract Global LACP configuration :param deviceObj : Device object :type deviceObj : object :return: returnStruct Object data dictionary with the following keys/values System-id = <int> System-priority = <int> [0-65534] :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) # Variables overallBuffer = [] data = dict() bufferString = "" command = "" # Dictionary initialization data['System-id'] = "" data['System-priority'] = 0 # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput('error', "Need to pass switch deviceObj to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtysh returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Show command command += ("show lacp configuration") returnStructure = deviceObj.DeviceInteract(command=command) retCode = returnStructure['returnCode'] overallBuffer.append(returnStructure['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to execute LACP configuration show") else: opstestfw.LogOutput('debug', "LACP configuration show succeeded") # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit enable prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.retStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Return results for curLine in overallBuffer: bufferString += str(curLine) # Fill dictionary out for curLine in bufferString.split('\r\n'): print curLine showLine1 = re.match( r'System-id\s*:\s*(([A-Za-z0-9]{2}:?){6})', curLine) if showLine1: data['System-id'] = showLine1.group(1) continue showLine2 = re.match(r'System-priority \s*:\s*(\d+)', curLine) if showLine2: data['System-priority'] = int(showLine2.group(1)) continue returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString, data=data) return returnCls
def InterfaceStatisticsShow(**kwargs): """ Library function get statistics for an specific interface :param deviceObj : Device object :type deviceObj : object :param interface : interface to configure :type interface : integer :return: returnStruct Object data: RX: inputPackets,inputErrors,CRC_FCS,bytes, dropped TX: outputPackets,inputError,collision,bytes,dropped :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) interface = kwargs.get('interface', None) # Variables overallBuffer = [] data = dict() bufferString = "" command = "" returnCode = 0 # Dictionary initialization data['RX'] = [] data['TX'] = [] if deviceObj is None: opstestfw.LogOutput('error', "Need to pass switch deviceObj to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Send Command command = "show interface" if interface is not None: command += " " + str(interface) opstestfw.LogOutput('info', "Show interface statistics.*****" + command) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) # temporaryBuffer = returnDevInt['buffer'] if retCode != 0: opstestfw.LogOutput('error', "Failed to get information ." + command) # Get out of the Shell # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # End Return Command # Return The Dict responds for curLine in overallBuffer: bufferString += str(curLine) bufferSplit = bufferString.split("\r\n") rx = dict() tx = dict() # Filling up the dictionaries rxTokens = re.findall( r'RX\s*\r\n\s*(\d*)\s*input\s*packets\s*(\d*)\s*bytes\s*\r\n\s*' + '(\d*)\s*input\s*error\s*(\d*)\s*dropped\s*\r\n\s*(\d*)', bufferString) txTokens = re.findall( r'TX\s*\r\n\s*(\d*)\s*output\s*packets\s*(\d*)\s*bytes\s*\r\n\s*' + '(\d*)\s*input\s*error\s*(\d*)\s*dropped\s*\r\n\s*(\d*)', bufferString) if rxTokens: rx['inputPackets'] = rxTokens[0][0] rx['bytes'] = rxTokens[0][1] rx['inputErrors'] = rxTokens[0][2] rx['dropped'] = rxTokens[0][3] rx['CRC_FCS'] = rxTokens[0][4] else: returnCode = 1 opstestfw.LogOutput('error', "Failed to get information ." + command) if txTokens: tx['outputPackets'] = txTokens[0][0] tx['bytes'] = txTokens[0][1] tx['inputErrors'] = txTokens[0][2] tx['dropped'] = txTokens[0][3] tx['collision'] = txTokens[0][4] else: returnCode = 1 opstestfw.LogOutput('error', "Failed to get information ." + command) data['RX'] = rx data['TX'] = tx # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString, data=data) return returnCls
def AddVlan(**kwargs): """ Library function to add a VLAN. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param config : True if a port is to be added to the VLAN, False if a port is to be removed from a VLAN. Defaults to True. :type config : boolean :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) config = kwargs.get('config', True) overallBuffer = [] resultCode = 0 # If Device object is not passed, we need to error out if deviceObj is None or vlanId is None: opstestfw.LogOutput( 'error', "Need to pass switch device object deviceObj and " "VLAN Id vlanId to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls if config: command = "" else: command = "no " command = command + "vlan " + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) bufferString = "" if retCode != 0: if config: opstestfw.LogOutput( 'error', "Failed to create VLAN or failed to get " "into VLAN context." + command) resultCode = 3 else: opstestfw.LogOutput('error', "Failed to delete VLAN." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: if config: opstestfw.LogOutput( 'debug', "Created VLAN or entered VLAN context." + command) else: opstestfw.LogOutput('debug', "Deleted VLAN." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit vlan context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited VLAN context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) if resultCode == 3: returnCls = opstestfw.returnStruct(returnCode=3, buffer=bufferString) return returnCls returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagHash(**kwargs): """ Library function to configure fallback settings for a LAG working in dynamic mode :param deviceObj : Device object :type deviceObj : object :param lagId : LAG Identifier :type lagId : integer :param hashType : l2-src-dst/l3-dsrc-dst hashing algortihms :type hashType : string :return: returnStruct Object :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) hashType = kwargs.get('hashType', 'l3-src-dst') # Variables overallBuffer = [] finalReturnCode = 0 # If deviceObj, lagId, hashType are not present, display an error if deviceObj is None or lagId is None: opstestfw.LogOutput('error', "Need to pass deviceObj and lagId to use " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # If hashType is different from l2-src-dst and l3-src-dst throw an error if hashType != 'l2-src-dst' and hashType != 'l3-src-dst': opstestfw.LogOutput('error', "hashType must be l2-src-dst or l3-src-dst") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to create LAG " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Created LAG " + str(lagId) + " on device " + deviceObj.device) # Generate command to query switch if hashType == 'l2-src-dst': command = "hash l2-src-dst" else: command = "hash l2-src-dst" returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Failed to configure " + hashType + " hashing on interface lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Configured l2-src-dst hashing on interface lag " + str(lagId) + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def ShowVlan(**kwargs): """ Library function to show the VLANs. :param deviceObj : Device object :type deviceObj : object :return: returnStruct Object buffer data keys Status - string set to "up" or "down" Reserved - string Name - string set to the name of the VLAN VLAN - string set to the id of the VLAN Reason - string Ports - list of strings :returnType: object """ deviceObj = kwargs.get('deviceObj', None) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput('error', "Need to pass switch device object deviceObj " "to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "show vlan" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) temporaryBuffer = returnDevInt['buffer'] if retCode != 0: opstestfw.LogOutput('error', "Failed to create VLAN." + command) else: opstestfw.LogOutput('debug', "Created VLAN." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls result = [] opstestfw.LogOutput('debug', "Buffer: " + temporaryBuffer) rgx = r'(VLAN|vlan|Vlan)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)' keys = re.findall(rgx, temporaryBuffer) temporaryBuffer = temporaryBuffer.encode('string-escape') opstestfw.LogOutput('debug', "Keys: " + str(keys)) opstestfw.LogOutput('debug', "Buffer: " + temporaryBuffer) if len(keys) == 1: keys = keys[0] rgx = r'(\d+)\s+(\w+)\s+(\w+)\s+([\w_]+)\s*(\(\w+\))?\s*([\w\d ,]+)?' vlans = \ re.findall(rgx, temporaryBuffer) opstestfw.LogOutput('debug', "Vlans: " + str(vlans)) for vlan in vlans: dictionary = {} for key, value in zip(keys, vlan): if key == 'Ports': dictionary[key] = value.split(', ') else: dictionary[key] = value result.append(dictionary) # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString, data=result) return returnCls
def lagHash(**kwargs): """ Library function to configure fallback settings for a LAG working in dynamic mode :param deviceObj : Device object :type deviceObj : object :param lagId : LAG Identifier :type lagId : integer :param hashType : l2-src-dst/l3-dsrc-dst hashing algortihms :type hashType : string :return: returnStruct Object :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) hashType = kwargs.get('hashType', 'l3-src-dst') # Variables overallBuffer = [] finalReturnCode = 0 # If deviceObj, lagId, hashType are not present, display an error if deviceObj is None or lagId is None: opstestfw.LogOutput( 'error', "Need to pass deviceObj and lagId to use " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # If hashType is different from l2-src-dst and l3-src-dst throw an error if hashType != 'l2-src-dst' and hashType != 'l3-src-dst': opstestfw.LogOutput('error', "hashType must be l2-src-dst or l3-src-dst") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to create LAG " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput( 'debug', "Created LAG " + str(lagId) + " on device " + deviceObj.device) # Generate command to query switch if hashType == 'l2-src-dst': command = "hash l2-src-dst" else: command = "hash l2-src-dst" returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput( 'error', "Failed to configure " + hashType + " hashing on interface lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput( 'debug', "Configured l2-src-dst hashing on interface lag " + str(lagId) + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def InterfaceLagShow(** kwargs): """ Library function to configure LAG parameters on an interface :param deviceObj : Device object :type deviceObj : object :param interface : interface to configure :type interface : integer :return: returnStruct Object data: "localPort": "lagId","systemId","portId","key", "activeFlag","shortTimeFlag", "collectingFlag","stateExpiredFlag", "passiveFlag","longTimeOutFlag", "distributingFlag","aggregableFlag", "inSyncFlag","neighborStateFlag", "individualFlag","outSyncFlag" "remotePort":"lagId","systemId","portId","key", "activeFlag","shortTimeFlag", "collectingFlag","stateExpiredFlag", "passiveFlag","longTimeOutFlag", "distributingFlag","aggregableFlag", "inSyncFlag","neighborStateFlag", "individualFlag","outSyncFlag" :returnType: object """ deviceObj = kwargs.get('deviceObj', None) interface = kwargs.get('interface', None) overallBuffer = [] bufferString = "" data = dict() # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput('error', "Need to pass switch device object deviceObj to " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Send Command command = "show lacp interface" if interface is not None: command += " " + str(interface) opstestfw.LogOutput('info', "Show lacp interface.*****" + command) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) # temporaryBuffer = returnDevInt['buffer'] if retCode != 0: opstestfw.LogOutput('error', "Failed to get information ." + command) # Get out of the Shell # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # End Return Command # Return The Dict responds for curLine in overallBuffer: bufferString += str(curLine) bufferSplit = bufferString.split("\r\n") data['localPort'] = [] data['remotePort'] = [] localPort = dict() remotePort = dict() for curLine in bufferSplit: # Search System id lagIdLine = re.match("Aggregate-name\s* :\s*lag(\w*)", curLine) if lagIdLine: curLocalLagId = lagIdLine.group(1) curRemoteLagId = lagIdLine.group(1) localPort['lagId'] = curLocalLagId remotePort['lagId'] = curRemoteLagId systemIdLine = re.match("System-id\s*\|(.*)\|(.*)", curLine) if systemIdLine: curLocalSystemId = systemIdLine.group(1) curRemoteSystemId = systemIdLine.group(2) localPort['systemId'] = curLocalSystemId remotePort['systemId'] = curRemoteSystemId portIdLine = re.match("Port-id\s*\|(.*)\|(.*)", curLine) if portIdLine: curLocalPort = portIdLine.group(1) curRemotePort = portIdLine.group(2) localPort['portId'] = curLocalPort remotePort['portId'] = curRemotePort keyLine = re.match("Key\s*\|(.*)\|(.*)", curLine) if keyLine: curLocalKey = keyLine.group(1) curRemoteKey = keyLine.group(2) localPort['key'] = curLocalKey remotePort['key'] = curRemoteKey stateLine = re.match("State\s*\|(.*)\|(.*)", curLine) if stateLine: # Catch from local activeFlag = re.match("A", stateLine.group(1)) if activeFlag: localPort['activeFlag'] = True else: localPort['activeFlag'] = False shortTimeFlag = re.match("S", stateLine.group(1)) if shortTimeFlag: localPort['shortTimeFlag'] = True else: localPort['shortTimeFlag'] = False collectingFlag = re.match("C", stateLine.group(1)) if collectingFlag: localPort['collectingFlag'] = True else: localPort['collectingFlag'] = False stateExpiredFlag = re.match("X", stateLine.group(1)) if stateExpiredFlag: localPort['stateExpiredFlag'] = True else: localPort['stateExpiredFlag'] = False passiveFlag = re.match("P", stateLine.group(1)) if passiveFlag: localPort['passiveFlag'] = True else: localPort['passiveFlag'] = False longTimeOutFlag = re.match("L", stateLine.group(1)) if longTimeOutFlag: localPort['longTimeOutFlag'] = True else: localPort['longTimeOutFlag'] = False distributingFlag = re.match("D", stateLine.group(1)) if distributingFlag: localPort['distributingFlag'] = True else: localPort['distributingFlag'] = False aggregableFlag = re.match("F", stateLine.group(1)) if aggregableFlag: localPort['aggregableFlag'] = True else: localPort['aggregableFlag'] = False inSyncFlag = re.match("N", stateLine.group(1)) if inSyncFlag: localPort['inSyncFlag'] = True else: localPort['inSyncFlag'] = False neighborStateFlag = re.match("E", stateLine.group(1)) if neighborStateFlag: localPort['neighborStateFlag'] = True else: localPort['neighborStateFlag'] = False individualFlag = re.match("I", stateLine.group(1)) if individualFlag: localPort['individualFlag'] = True else: localPort['individualFlag'] = False outSyncFlag = re.match("O", stateLine.group(1)) if outSyncFlag: localPort['outSyncFlag'] = True else: localPort['outSyncFlag'] = False # Cath from remote activeFlag = re.match("A", stateLine.group(1)) if activeFlag: remotePort['activeFlag'] = True else: remotePort['activeFlag'] = False shortTimeFlag = re.match("S", stateLine.group(1)) if shortTimeFlag: remotePort['shortTimeFlag'] = True else: remotePort['shortTimeFlag'] = False collectingFlag = re.match("C", stateLine.group(1)) if collectingFlag: remotePort['collectingFlag'] = True else: remotePort['collectingFlag'] = False stateExpiredFlag = re.match("X", stateLine.group(1)) if stateExpiredFlag: remotePort['stateExpiredFlag'] = True else: remotePort['stateExpiredFlag'] = False passiveFlag = re.match("P", stateLine.group(1)) if passiveFlag: remotePort['passiveFlag'] = True else: remotePort['passiveFlag'] = False longTimeOutFlag = re.match("L", stateLine.group(1)) if longTimeOutFlag: remotePort['longTimeOutFlag'] = True else: remotePort['longTimeOutFlag'] = False distributingFlag = re.match("D", stateLine.group(1)) if distributingFlag: remotePort['distributingFlag'] = True else: remotePort['distributingFlag'] = False aggregableFlag = re.match("F", stateLine.group(1)) if aggregableFlag: remotePort['aggregableFlag'] = True else: remotePort['aggregableFlag'] = False inSyncFlag = re.match("N", stateLine.group(1)) if inSyncFlag: remotePort['inSyncFlag'] = True else: remotePort['inSyncFlag'] = False neighborStateFlag = re.match("E", stateLine.group(1)) if neighborStateFlag: remotePort['neighborStateFlag'] = True else: remotePort['neighborStateFlag'] = False individualFlag = re.match("I", stateLine.group(1)) if individualFlag: remotePort['individualFlag'] = True else: remotePort['individualFlag'] = False outSyncFlag = re.match("O", stateLine.group(1)) if outSyncFlag: remotePort['outSyncFlag'] = True else: remotePort['outSyncFlag'] = False data['localPort'] = localPort data['remotePort'] = remotePort # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=overallBuffer, data=data) return returnCls
def ShowVlan(**kwargs): """ Library function to show the VLANs. :param deviceObj : Device object :type deviceObj : object :return: returnStruct Object buffer data keys Status - string set to "up" or "down" Reserved - string Name - string set to the name of the VLAN VLAN - string set to the id of the VLAN Reason - string Ports - list of strings :returnType: object """ deviceObj = kwargs.get('deviceObj', None) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput( 'error', "Need to pass switch device object deviceObj " "to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "show vlan" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) temporaryBuffer = returnDevInt['buffer'] if retCode != 0: opstestfw.LogOutput('error', "Failed to create VLAN." + command) else: opstestfw.LogOutput('debug', "Created VLAN." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls result = [] opstestfw.LogOutput('debug', "Buffer: " + temporaryBuffer) rgx = r'(VLAN|vlan|Vlan)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)' keys = re.findall(rgx, temporaryBuffer) temporaryBuffer = temporaryBuffer.encode('string-escape') opstestfw.LogOutput('debug', "Keys: " + str(keys)) opstestfw.LogOutput('debug', "Buffer: " + temporaryBuffer) if len(keys) == 1: keys = keys[0] rgx = r'(\d+)\s+(\w+)\s+(\w+)\s+([\w_]+)\s*(\(\w+\))?\s*([0-9\- ,]+)?' vlans = \ re.findall(rgx, temporaryBuffer) opstestfw.LogOutput('debug', "Vlans: " + str(vlans)) for vlan in vlans: dictionary = {} for key, value in zip(keys, vlan): if key == 'Ports': dictionary[key] = value.split(', ') else: dictionary[key] = value result.append(dictionary) # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString, data=result) return returnCls
def showInterface(**kwargs): """ Library function to get specific interface information from the device :param deviceObj : Device object :type deviceObj : object :param interface : interface number context (optional) :type interface : integer :return: returnStruct Object buffer :returnType: object """ deviceObj = kwargs.get('deviceObj', None) interface = kwargs.get('interface', None) overallBuffer = [] bufferString = "" # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput('error', "Need to pass switch deviceObj" + "to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls ########################################################################## # Send Command ########################################################################## if interface is None: command = "show interface" else: command = "show interface " + str(interface) opstestfw.LogOutput('debug', "Sending: " + command) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to get information ." + command) ########################################################################### # Get out of the Shell ########################################################################### returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls ########################################################################### # Exit for context and validate buffer with information ########################################################################### for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def UserAddRemove(**kwargs): """ Library function to add / remove user on switch The function also changes password for an existing user :param deviceObj : Device object :type deviceObj : object :param action : add - adds user(default) : password - changes password of an existing user : remove - removes local user on switch :type action : string :param user : username :type user : string :param password : password string :type password : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) action = kwargs.get('action', "add") user = kwargs.get('user', "user1") password = kwargs.get('password', "openswitch") # Variables bufferString = '' overallBuffer = [] returnCode = 0 # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Get into vtyshell returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls expectList = [ 'Enter password:'******'Confirm password:'******'[A-Za-z0-9]+#', 'User added successfully', 'Enter new password:'******'Confirm new password:'******'user add ' + user opstestfw.LogOutput( 'debug', "Adding user %s on the device :%s " % (user, deviceObj.device)) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) bufferString += str(deviceObj.expectHndl.before) # Entering passwords for the user if index == 0: command = password deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 1: command = password deviceObj.expectHndl.sendline(command) bufferString += str(deviceObj.expectHndl.before) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 3: opstestfw.LogOutput( "info", "User : %s added successfully on device %s **" % (user, deviceObj.device)) elif index == 6: # Got EOF opstestfw.LogOutput('error', "End of File") return None elif index == 7: # Got a Timeout opstestfw.LogOutput('error', "Connection timed out") return None elif action == "password": # Password change opstestfw.LogOutput("info", "Password Change ***") command = "password " + str(user) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 4: command = password deviceObj.expectHndl.sendline(command) bufferString += str(deviceObj.expectHndl.before) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 5: deviceObj.expectHndl.sendline(command) bufferString += str(deviceObj.expectHndl.before) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 2: opstestfw.LogOutput( "info", "User : %s password changed successfully on device %s **" % (user, deviceObj.device)) else: opstestfw.LogOutput( "error", "User : %s password not changed on device %s **" % (user, deviceObj.device)) else: # Remove user opstestfw.LogOutput( 'info', "remove user %s on device %s" % (user, deviceObj.device)) command = 'user remove ' + user opstestfw.LogOutput( 'debug', "Removing user %s on the device :%s " % (user, deviceObj.device)) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 0: opstestfw.LogOutPut('info', "User %s removed from DUT " % (user)) deviceObj.expectHndl.expect(['$'], timeout=5) bufferString += str(deviceObj.expectHndl.before) bufferString += str(deviceObj.expectHndl.after) overallBuffer.append(bufferString) for curLine in overallBuffer: bufferString += str(curLine) errCheckRetStr = deviceObj.ErrorCheckCLI(buffer=bufferString) returnCode = errCheckRetStr['returnCode'] #Compile information to return returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=overallBuffer) return returnCls
def ServerConfig(**kwargs): """ Library function to configure workstations with server configuration. Take a backup of default server files and edit with customized configuration when the action = config (default) Start the respective service specified for the server (dhcpd/tftp/radiusd) When (action = "unconfig") move the backed up files to restore the workstation and stop the server services configured. :param deviceObj : Device object :type deviceObj : object :param serverConfigs : server string to be configured :type serverConfigs : string :param serviceConfig : server service configuration :type serviceConfig : string :param backupFile : backup file path for server configuration files :type backupFile : string :param serverConfigFile : Filepath of server configuration files :type serverConfigFile : string :param service : server service to be configured (restart/stop/start) :type service : string :param action : config(configure server parameters) , "unconfig" (to unconfigure) :type action : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) service = kwargs.get('service', None) serverConfigFile = kwargs.get('serverConfigFile', None) backupFile = kwargs.get('backupFile', None) serverConfigs = kwargs.get('serverConfigs', None) serviceConfig = kwargs.get('serviceConfig', None) action = kwargs.get('action', "config") # Variables bufferString = '' returnCode = 0 overallBuffer = [] retDictionary = [] # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Define the server configuration files depending on the service to be # configured/unconfigured if service == "dhcpd": serverConfigFile = "/etc/dhcp/dhcpd.conf" backupFile = "/etc/dhcp/dhcpd_bkup.conf" elif service == "tftp": serverConfigFile = "/etc/default/tftpd-hpa" backupFile = "/etc/default/tftpd-hpa_bkup" #Configuring TFTP server if service == "tftp": #Configure Tftp server configure serverConfigs = """ 'TFTP_USERNAME="******"\nTFTP_DIRECTORY="'/var/lib/tftpboot'"\nTFTP_ADDRESS="'0.0.0.0:69'"\nTFTP_OPTIONS="'\--secure \-c'"' """ #Appropriate permissions to the /var/lib/tftpboot directory command = "chmod 777 /var/lib/tftpboot/" returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') if returnCode != 0: opstestfw.LogOutput( 'error', " command %s not send on workstation" % (command)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput('info', "command %s executed " % (command)) command = "sudo chown -R nobody /var/lib/tftpboot/" returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') if returnCode != 0: opstestfw.LogOutput( 'error', " command %s not send on workstation" % (command)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput('info', "command %s executed " % (command)) if action == "config": # Configure the server # Move the server file and take a backup returnStruct = opstestfw.host.MoveFile(deviceObj=deviceObj, sourceFilePath=serverConfigFile, destinationFilePath=backupFile) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to move file %s on %s ->" % (serverConfigFile, deviceObj.device)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Moved the file %s to %s-->" % (serverConfigFile, backupFile)) # Edit the server file returnStruct = opstestfw.host.FileEdit(deviceObj=deviceObj, stringEdit=str(serverConfigs), filename=serverConfigFile) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to edit server file %s ->" % (serverConfigFile)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls # Check the pid and kill the service of it is already running (Residue # process should be killed) if service is not None: if serviceConfig != "stop": # Stop the service if it already running # Killing the old pid is important , since the service needs to # resume newly after configuration edit retStruct = opstestfw.host.GetServicePID(deviceObj=deviceObj, service=service) retDictionary = retStruct.dataKeys() if retDictionary: ProcessID = retStruct.valueGet(key='pid') command = "kill " + ProcessID returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') if returnCode != 0: opstestfw.LogOutput( 'error', "running (residue) process for service %s not killed" % (service)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "killed the running process for service %s" % (service)) else: opstestfw.LogOutput( 'info', "Stop service %s explicitly before starting it after configuration change" % (service)) # Pass service configurations to workstations and get the PID to check # if the service is running/stopped if service is not None: returnStruct = opstestfw.host.ServicesConfig(deviceObj=deviceObj, service=service, action=serviceConfig) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to configure action %s on service %s for %s ->" % (serviceConfig, service, deviceObj.device)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: retStruct = opstestfw.host.GetServicePID(deviceObj=deviceObj, service=service) retDictionary = retStruct.dataKeys() if (retDictionary and serviceConfig == "start") or ( retDictionary and serviceConfig == "restart"): opstestfw.LogOutput( 'info', "Service %s --> %s" % (service, serviceConfig)) elif retDictionary is None and serviceConfig == "stop": opstestfw.LogOutput( 'info', "Service %s --> %s" % (service, serviceConfig)) else: opstestfw.LogOutput( 'error', "Service %s --> %s failed" % (service, serviceConfig)) returnCls = opstestfw.returnStruct(returnCode=1, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Unconfigure Server configurations , restore backup files") # Move the backedup config file returnStruct = opstestfw.host.MoveFile( deviceObj=deviceObj, sourceFilePath=backupFile, destinationFilePath=serverConfigFile) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to move backup file %s on ->" % (backupFile, deviceObj.device)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls # Stop the service if it already running if service is not None: retStruct = opstestfw.host.GetServicePID(deviceObj=deviceObj, service=service) retDictionary = retStruct.dataKeys() if retDictionary: ProcessID = retStruct.valueGet(key='pid') command = "kill " + ProcessID returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to kill %s service while unconfiguring " % (service)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Kill %s service while unconfiguring " % (service)) bufferString = ' ' for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def hostIperfClientStart(**kwargs): """ Library function to generate traffic using iperf. :param deviceObj : Device object :type deviceObj : object :param time : amount of time in seconds where traffic will be sent :type time : integer :param protocol : UDP or TCP :type protocol : string :param interval : Result reporting interval :type interval : integer :param port : server port number :type port : integer :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get("deviceObj", None) port = kwargs.get("port", 5001) serverIP = kwargs.get("serverIP", None) protocol = kwargs.get("protocol", "TCP") interval = kwargs.get("interval", 1) rtime = kwargs.get("time", 10) # Variables bufferString = "" # If device is not passed, we need error message if deviceObj is None or serverIP is None: opstestfw.LogOutput("error", "Need to pass device to configure and server IP address.") returnStruct = opstestfw.returnStruct(returnCode=1) return returnStruct # Verify if iperf is installed on host assuming it is Ubuntu and then # install it command = "iperf" opstestfw.LogOutput("debug", "Verifying if iperf is installed on device " + deviceObj.device) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(["Usage", "(command not found)|(install)"]) bufferString += str(deviceObj.expectHndl.before) if index == 0: # In case iperf is installed index = deviceObj.expectHndl.expect(["# ", pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput("error", "Error while verifying status of iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: # In case iperf is not installed index = deviceObj.expectHndl.expect(["# ", pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput("error", "Error while verifying status of iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) opstestfw.LogOutput("debug", "Installing iperf") command = "apt-get install iperf" deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(["# ", pexpect.TIMEOUT], timeout=30) bufferString += str(deviceObj.expectHndl.before) if index == 1: opstestfw.LogOutput("error", "Error while installing iperf on device " + deviceObj.device) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) command = "iperf" deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(["Usage", "(command not found)|(install)", pexpect.TIMEOUT]) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput("error", "Could not install iperf correctly") index = deviceObj.expectHndl.expect(["# ", pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput("error", "Unknown error on device") return opstestfw.returnStruct(returnCode=1, buffer=bufferString) return opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: index = deviceObj.expectHndl.expect(["# ", pexpect.TIMEOUT], timeout=5) bufferString += str(deviceObj.expectHndl.before) if index != 0: opstestfw.LogOutput("error", "Unknown error on device") return opstestfw.returnStruct(returnCode=1, buffer=bufferString) opstestfw.LogOutput("debug", "Successfully installed iperf on device") command = "iperf -c " + str(serverIP) + " -p " + str(port) command += " -i " + str(interval) command += " -t " + str(rtime) if protocol == "UDP": command += " -u" deviceObj.expectHndl.sendline(command) # Compile information to return bufferString = "" returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagHeartbeat(**kwargs): """ Library function to configure heartbeat speed on a LAG :param deviceObj: device object :type deviceObj: VSwitch device object :param lagId: LAG identifier :type lagId: int :param lacpFastFlag: True for LACP fast heartbeat, false for slow heartbeat :type lacpFastFlag: boolean :return: returnStruct object :rtype: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) lacpFastFlag = kwargs.get('lacpFastFlag', True) # Variables overallBuffer = [] finalReturnCode = 0 # If device, LAG Id or lacpFastFlag are not passed, return an error if deviceObj is None or lagId is None or lacpFastFlag is None: opstestfw.LogOutput('error', "Need to pass deviceObj and lagId to use " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to create LAG " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Created LAG " + str(lagId) + " on device " + deviceObj.device) # configure LAG heartbeat settings command = "" if lacpFastFlag is False: command = "no " command += "lacp rate fast" returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: if lacpFastFlag is True: opstestfw.LogOutput('error', "Failed to configure LACP fast heartbeat on " "interface lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('error', "Failed to configure LACP slow heartbeat on " "interface lag " + str(lagId) + " on device " + deviceObj.device) else: if lacpFastFlag is True: opstestfw.LogOutput('debug', "Configured LACP fast heartbeat on interface" " lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Configure LACP slow heartbeat on interface" " lag " + str(lagId) + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def lagFallback(**kwargs): """ Library function to configure fallback settings for a LAG working in dynamic mode :param deviceObj : Device object :type deviceObj : object :param lagId : LAG Identifier :type lagId : integer :param fallbackFlag : off: Static LAG active: Active dynamic LAG passive: Passive dynamic LAG :type fallbackFlag : string :return: returnStruct Object :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) fallbackFlag = kwargs.get('fallbackFlag', True) # Variables overallBuffer = [] finalReturnCode = 0 # If deviceObj, lagId or fallbackFlag are not passed, we need to throw # an error if deviceObj is None or lagId is None: opstestfw.LogOutput('error', "Need to pass deviceObj and lagId to use " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to create LAG " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Created LAG " + str(lagId) + " on device " + deviceObj.device) # configure LAG's LACP fallback settings if fallbackFlag is True: command = "lacp fallback" else: command = "no lacp fallback" returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: if fallbackFlag is True: opstestfw.LogOutput('error', "Failed to enable LACP fallback on interface " "lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('error', "Failed to disable LACP fallback on interface " "lag " + str(lagId) + " on device " + deviceObj.device) else: if fallbackFlag is True: opstestfw.LogOutput('debug', "Enabled LACP fallback on interface lag " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Disabled LACP fallback on interface lag " + str(lagId) + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def hostIperfServerStop(** kwargs): """ Library function to process information from traffic received using iperf. :param deviceObj : Device object :type deviceObj : object :return: returnStruct Object data: - Dictionary: 'Client IP': Server IP address 'Client port': Client port 'Server IP': Server IP address 'Server port': Server port :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) #Variable initialization retBuffer = '' # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=1) retBuffer = deviceObj.expectHndl.before ips_and_ports = re.search( 'local (.*) port (\d+) connected with (.*) port (\d+)', deviceObj.expectHndl.before) traffic_data = re.findall( 'sec ([.\d]+ .*?) ([.\d]+ .+)\r', deviceObj.expectHndl.before) # If client fails result is None and returnList == [] server_ip = None server_port = None client_ip = None client_port = None if ips_and_ports is not None: server_ip = ips_and_ports.group(1) server_port = ips_and_ports.group(2) client_ip = ips_and_ports.group(3) client_port = ips_and_ports.group(4) data_dict = {} data_dict['Server IP'] = server_ip data_dict['Server port'] = server_port data_dict['Client IP'] = client_ip data_dict['Client port'] = client_port data_dict['Traffic data'] = traffic_data command = '\003' deviceObj.expectHndl.send(command) deviceObj.expectHndl.expect('#') retBuffer += deviceObj.expectHndl.before # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=retBuffer, data=data_dict) return returnCls
def hostIperfServerStop(**kwargs): """ Library function to process information from traffic received using iperf. :param deviceObj : Device object :type deviceObj : object :return: returnStruct Object data: - Dictionary: 'Client IP': Server IP address 'Client port': Client port 'Server IP': Server IP address 'Server port': Server port :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) #Variable initialization retBuffer = '' # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=1) retBuffer = deviceObj.expectHndl.before ips_and_ports = re.search( 'local (.*) port (\d+) connected with (.*) port (\d+)', deviceObj.expectHndl.before) traffic_data = re.findall('sec ([.\d]+ .*?) ([.\d]+ .+)\r', deviceObj.expectHndl.before) # If client fails result is None and returnList == [] server_ip = None server_port = None client_ip = None client_port = None if ips_and_ports is not None: server_ip = ips_and_ports.group(1) server_port = ips_and_ports.group(2) client_ip = ips_and_ports.group(3) client_port = ips_and_ports.group(4) data_dict = {} data_dict['Server IP'] = server_ip data_dict['Server port'] = server_port data_dict['Client IP'] = client_ip data_dict['Client port'] = client_port data_dict['Traffic data'] = traffic_data command = '\003' deviceObj.expectHndl.send(command) deviceObj.expectHndl.expect('#') retBuffer += deviceObj.expectHndl.before # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=retBuffer, data=data_dict) return returnCls
def lacpAggregatesShow(**kwargs): """ Library function to display settings configured on 1 or several LAGs :param deviceObj : Device object :type deviceObj : object :param lagId : LAG identifier :type lagId : integer :return: returnStruct Object data Keys: LAG numeric identifier Values: interfaces: - List of interfaces part of LAG lacpFastFlag: - True for fast heartbeat, False for slow heartbeat fallbackFlag: - True when enabled, False otherwise hashType: - l2-src-dst/l3-src-dst depending on configured settings on LAG lacpMode: - LAG configured mode: off for static and active/passive for dynamic :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) # Variables overallBuffer = [] retStruct = dict() helperLagId = '' finalReturnCode = 0 results = '' counter = 0 # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass deviceObj to use this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Create command to query switch command = 'show lacp aggregates' if lagId is not None: command += ' lag' + str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Could not obtain LACP aggregates information") # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls if finalReturnCode == 0: # ######TEMPORARY### # consume output for results buffer2 = '' while True: result = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) buffer2 += str(deviceObj.expectHndl.before) if result == 1: break overallBuffer.append(buffer2) # ###END OF TEMPORARY # Parse information for desired results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) results = bufferString.split('\r\n') for i in results: if counter == 0: # LAG id match result = re.search('Aggregate-name[ ]+: lag([0-9])+', i) if result is None: continue helperLagId = str(result.group(1)) retStruct[helperLagId] = dict() counter += 1 continue if counter == 1: # Match for interfaces result = re.search( 'Aggregated-interfaces[ ]+:[ ]?([ ][a-zA-Z0-9 \-]*)', i) if result is None: opstestfw.LogOutput( 'error', "Error while obtaining LACP aggregates" " interfaces information on line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls retStruct[helperLagId]['interfaces'] = [] for k in re.split(' ', result.group(1)): if k != '': retStruct[helperLagId]['interfaces'].append(k) counter += 1 continue if counter == 2: # Match for Heartbeat speed result = re.search('Heartbeat rate[ ]+: (slow|fast)', i) if result is None: opstestfw.LogOutput( 'error', "Error while obtaining LACP " "aggregates heartbeat information " "on line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls if result.group(1) == 'fast': retStruct[helperLagId]['lacpFastFlag'] = True else: retStruct[helperLagId]['lacpFastFlag'] = False counter += 1 continue if counter == 3: # Match for fallback settings result = re.search('Fallback[ ]+: (true|false)', i) if result is None: opstestfw.LogOutput( 'error', "Error while obtaining LACP " "aggregates fallback information " "on line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls if result.group(1) == 'true': retStruct[helperLagId]['fallbackFlag'] = True else: retStruct[helperLagId]['fallbackFlag'] = False counter += 1 continue if counter == 4: # Match for Hashing algorithm result = re.search('Hash[ ]+: (l2-src-dst|l3-src-dst)', i) if result is None: opstestfw.LogOutput( 'error', "Error while obtaining LACP " "aggregates hash information on " "line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls retStruct[helperLagId]['hashType'] = result.group(1) counter += 1 continue if counter == 5: # Match for LAG mode result = re.search('Aggregate mode[ ]+: (off|passive|active)', i) if result is None: opstestfw.LogOutput( 'error', "Error while obtaining LACP " "aggregates hash information on " "line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls retStruct[helperLagId]['lacpMode'] = result.group(1) counter = 0 continue # Compile information to return bufferString = "" for curLin in overallBuffer: bufferString += str(curLin) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString, data=retStruct) return returnCls
def lacpAggregatesShow(** kwargs): """ Library function to display settings configured on 1 or several LAGs :param deviceObj : Device object :type deviceObj : object :param lagId : LAG identifier :type lagId : integer :return: returnStruct Object data Keys: LAG numeric identifier Values: interfaces: - List of interfaces part of LAG lacpFastFlag: - True for fast heartbeat, False for slow heartbeat fallbackFlag: - True when enabled, False otherwise hashType: - l2-src-dst/l3-src-dst depending on configured settings on LAG lacpMode: - LAG configured mode: off for static and active/passive for dynamic :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) # Variables overallBuffer = [] retStruct = dict() helperLagId = '' finalReturnCode = 0 results = '' counter = 0 # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass deviceObj to use this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Create command to query switch command = 'show lacp aggregates' if lagId is not None: command += ' lag' + str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Could not obtain LACP aggregates information") # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls if finalReturnCode == 0: # ######TEMPORARY### # consume output for results buffer2 = '' while True: result = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) buffer2 += str(deviceObj.expectHndl.before) if result == 1: break overallBuffer.append(buffer2) # ###END OF TEMPORARY # Parse information for desired results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) results = bufferString.split('\r\n') for i in results: if counter == 0: # LAG id match result = re.search('Aggregate-name[ ]+: lag([0-9])+', i) if result is None: continue helperLagId = str(result.group(1)) retStruct[helperLagId] = dict() counter += 1 continue if counter == 1: # Match for interfaces result = re.search('Aggregated-interfaces[ ]+:[ ]?([ ][a-zA-Z0-9 \-]*)', i) if result is None: opstestfw.LogOutput('error', "Error while obtaining LACP aggregates" " interfaces information on line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls retStruct[helperLagId]['interfaces'] = [] for k in re.split(' ', result.group(1)): if k != '': retStruct[helperLagId]['interfaces'].append(k) counter += 1 continue if counter == 2: # Match for Heartbeat speed result = re.search('Heartbeat rate[ ]+: (slow|fast)', i) if result is None: opstestfw.LogOutput('error', "Error while obtaining LACP " "aggregates heartbeat information " "on line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls if result.group(1) == 'fast': retStruct[helperLagId]['lacpFastFlag'] = True else: retStruct[helperLagId]['lacpFastFlag'] = False counter += 1 continue if counter == 3: # Match for fallback settings result = re.search('Fallback[ ]+: (true|false)', i) if result is None: opstestfw.LogOutput('error', "Error while obtaining LACP " "aggregates fallback information " "on line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls if result.group(1) == 'true': retStruct[helperLagId]['fallbackFlag'] = True else: retStruct[helperLagId]['fallbackFlag'] = False counter += 1 continue if counter == 4: # Match for Hashing algorithm result = re.search('Hash[ ]+: (l2-src-dst|l3-src-dst)', i) if result is None: opstestfw.LogOutput('error', "Error while obtaining LACP " "aggregates hash information on " "line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls retStruct[helperLagId]['hashType'] = result.group(1) counter += 1 continue if counter == 5: # Match for LAG mode result = re.search('Aggregate mode[ ]+: (off|passive|active)', i) if result is None: opstestfw.LogOutput('error', "Error while obtaining LACP " "aggregates hash information on " "line:\n" + i) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls retStruct[helperLagId]['lacpMode'] = result.group(1) counter = 0 continue # Compile information to return bufferString = "" for curLin in overallBuffer: bufferString += str(curLin) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString, data=retStruct) return returnCls
def VlanDescription(**kwargs): """ Library function to show the VLANs. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param description : string with the VLAN description. This is casted to string. :type description : string :param config : True if a VLAN description is to be added, False if a VLAN description is to be deleted. Defaults to True. :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) description = kwargs.get('description', None) config = kwargs.get('config', True) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None or description is None or vlanId is None: opstestfw.LogOutput( 'error', "Need to pass switch device object deviceObj, " "VLAN id vlanId and VLAN description description " "to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "vlan " + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to get into vlan prompt." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Created VLAN." + command) if config: command = "" else: command = "no " command = command + "description " + str(description) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: if config: opstestfw.LogOutput( 'error', "Failed to set the VLAN description." + command) else: opstestfw.LogOutput( 'error', "Failed to remove the VLAN description." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "VLAN description set." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit vlan context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited VLAN context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagCreation(**kwargs): """ Library function to create/delete a LAG :param deviceObj: device object :type deviceObj: VSwitch device object :param lagId: LAG identifier :type lagId: int :param configFlag: True for configuration / False for removing LAG :type configFlag: boolean :return: returnStruct object :rtype: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) configFlag = kwargs.get('configFlag', True) # Variables overallBuffer = [] finalReturnCode = 0 # If deviceObj, lagId or configFlag are not present, throw an error if deviceObj is None or lagId is None: opstestfw.LogOutput('error', "Need to pass deviceObj and lagId to use " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Verify if creating or deleting a LAG if configFlag is True: # create LAG command = "interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Failed to create LAG " + str(lagId) + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Created LAG " + str(lagId) + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: # delete LAG command = "no interface lag %s" % str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to delete LAG on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Deleted LAG context on device " + deviceObj.device) # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile results to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def UserAddRemove(**kwargs): """ Library function to add / remove user on switch The function also changes password for an existing user :param deviceObj : Device object :type deviceObj : object :param action : add - adds user(default) : password - changes password of an existing user : remove - removes local user on switch :type action : string :param user : username :type user : string :param password : password string :type password : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get("deviceObj", None) action = kwargs.get("action", "add") user = kwargs.get("user", "user1") password = kwargs.get("password", "openswitch") # Variables bufferString = "" overallBuffer = [] returnCode = 0 # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput("error", "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Get into vtyshell returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: LogOutput("error", "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls expectList = [ "Enter password:"******"Confirm password:"******"[A-Za-z0-9]+#", "User added successfully", "Enter new password:"******"Confirm new password:"******"add": command = "user add " + user opstestfw.LogOutput("debug", "Adding user %s on the device :%s " % (user, deviceObj.device)) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) bufferString += str(deviceObj.expectHndl.before) # Entering passwords for the user if index == 0: command = password deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 1: command = password deviceObj.expectHndl.sendline(command) bufferString += str(deviceObj.expectHndl.before) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 3: opstestfw.LogOutput( "info", "User : %s added successfully on device %s **" % (user, deviceObj.device) ) elif index == 6: # Got EOF opstestfw.LogOutput("error", "End of File") return None elif index == 7: # Got a Timeout opstestfw.LogOutput("error", "Connection timed out") return None elif action == "password": # Password change opstestfw.LogOutput("info", "Password Change ***") command = "password " + str(user) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 4: command = password deviceObj.expectHndl.sendline(command) bufferString += str(deviceObj.expectHndl.before) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 5: deviceObj.expectHndl.sendline(command) bufferString += str(deviceObj.expectHndl.before) index = deviceObj.expectHndl.expect(expectList, timeout=5) if index == 2: opstestfw.LogOutput( "info", "User : %s password changed successfully on device %s **" % (user, deviceObj.device) ) else: opstestfw.LogOutput( "error", "User : %s password not changed on device %s **" % (user, deviceObj.device) ) else: # Remove user opstestfw.LogOutput("info", "remove user %s on device %s" % (user, deviceObj.device)) command = "user remove " + user opstestfw.LogOutput("debug", "Removing user %s on the device :%s " % (user, deviceObj.device)) deviceObj.expectHndl.sendline(command) index = deviceObj.expectHndl.expect(expectList, timeout=5) bufferString += str(deviceObj.expectHndl.before) if index == 0: opstestfw.LogOutPut("info", "User %s removed from DUT " % (user)) deviceObj.expectHndl.expect(["$"], timeout=5) bufferString += str(deviceObj.expectHndl.before) bufferString += str(deviceObj.expectHndl.after) overallBuffer.append(bufferString) for curLine in overallBuffer: bufferString += str(curLine) errCheckRetStr = deviceObj.ErrorCheckCLI(buffer=bufferString) returnCode = errCheckRetStr["returnCode"] # Compile information to return returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=overallBuffer) return returnCls
def VlanStatus(**kwargs): """ Library function to set a VLAN status. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param status : True to set the status to up, False to set the status to down :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) status = kwargs.get('status', None) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None or vlanId is None: opstestfw.LogOutput( 'error', "Need to pass switch device object deviceObj and" " VLAN Id vlanId to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "vlan " + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to create VLAN." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Created VLAN." + command) if status: command = "no shutdown" else: command = "shutdown" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to set the VLAN status." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "VLAN status set." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit vlan context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited VLAN context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagMode(**kwargs): """ Library function to configure a LAGs mode (static/dynamic) :param deviceObj : Device object :type deviceObj : object :param lagId : LAG Identifier :type lagId : integer :param lacpMode : off: Static LAG active: Active dynamic LAG passive: Passive dynamic LAG :type lacpMode : string :return: returnStruct Object :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) lacpMode = kwargs.get('lacpMode', 'off') # Variables overallBuffer = [] initialStatus = '' finalReturnCode = 0 # If deviceObj, lagId or lacpMode are not present, thorw an error if deviceObj is None or lagId is None: opstestfw.LogOutput( 'error', "Need to pass deviceObj and lagId to use this " "routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Query switch for LAG configuration # Note this command is not the core of the function, but it is so # important that if the initial status of the LAG mode cannot be # determined, the other will always fail command = 'show lacp aggregates lag' + str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Could not obtain LAG LACP mode initial status") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) else: # TEMPORARY # Obtain result of command buffer2 = '' while True: result = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) buffer2 += str(deviceObj.expectHndl.before) + str( deviceObj.expectHndl.after) if result == 1: break overallBuffer.append(buffer2) # END OF TEMPORARY # Parse buffer for values of interest bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) result = re.search('Aggregate mode[ ]+: (off|passive|active)', bufferString) if result is None: opstestfw.LogOutput( 'error', "Could not identify LAG LACP mode initial " "status") returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: initialStatus = result.group(1) opstestfw.LogOutput( 'debug', "LAG LACP mode initial status identified as " + initialStatus) # mVerify if the LAG was already in static mode and will be changed # again if initialStatus == lacpMode and lacpMode == 'off': opstestfw.LogOutput( 'debug', "LACP mode is set to off already. No change " "is performed") else: # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag " + str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to enter LAG" + str(lagId) + " configuration context on device " + deviceObj.device) bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) else: opstestfw.LogOutput( 'debug', "Entered LAG" + str(lagId) + " configuration context on device " + deviceObj.device) # configure LAG mode if str(lacpMode) != 'off': command = "lacp mode " + str(lacpMode) else: command = "no lacp mode " + initialStatus returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput( 'error', "Failed to configure LACP mode to " + lacpMode + " on device " + deviceObj.device) else: opstestfw.LogOutput( 'debug', "Changed LACP mode to " + lacpMode + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to get out of vtysh config " "context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def InterfaceLagShow(**kwargs): """ Library function to configure LAG parameters on an interface :param deviceObj : Device object :type deviceObj : object :param interface : interface to configure :type interface : integer :return: returnStruct Object data: "localPort": "lagId","systemId","portId","key", "activeFlag","shortTimeFlag", "collectingFlag","stateExpiredFlag", "passiveFlag","longTimeOutFlag", "distributingFlag","aggregableFlag", "inSyncFlag","neighborStateFlag", "individualFlag","outSyncFlag" "remotePort":"lagId","systemId","portId","key", "activeFlag","shortTimeFlag", "collectingFlag","stateExpiredFlag", "passiveFlag","longTimeOutFlag", "distributingFlag","aggregableFlag", "inSyncFlag","neighborStateFlag", "individualFlag","outSyncFlag" :returnType: object """ deviceObj = kwargs.get('deviceObj', None) interface = kwargs.get('interface', None) overallBuffer = [] bufferString = "" data = dict() # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput( 'error', "Need to pass switch device object deviceObj to " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Send Command command = "show lacp interface" if interface is not None: command += " " + str(interface) opstestfw.LogOutput('info', "Show lacp interface.*****" + command) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) # temporaryBuffer = returnDevInt['buffer'] if retCode != 0: opstestfw.LogOutput('error', "Failed to get information ." + command) # Get out of the Shell # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # End Return Command # Return The Dict responds for curLine in overallBuffer: bufferString += str(curLine) bufferSplit = bufferString.split("\r\n") data['localPort'] = [] data['remotePort'] = [] localPort = dict() remotePort = dict() for curLine in bufferSplit: # Search System id lagIdLine = re.match("Aggregate-name\s* :\s*lag(\w*)", curLine) if lagIdLine: curLocalLagId = lagIdLine.group(1) curRemoteLagId = lagIdLine.group(1) localPort['lagId'] = curLocalLagId remotePort['lagId'] = curRemoteLagId systemIdLine = re.match("System-id\s*\|(.*)\|(.*)", curLine) if systemIdLine: curLocalSystemId = systemIdLine.group(1) curRemoteSystemId = systemIdLine.group(2) localPort['systemId'] = curLocalSystemId remotePort['systemId'] = curRemoteSystemId portIdLine = re.match("Port-id\s*\|(.*)\|(.*)", curLine) if portIdLine: curLocalPort = portIdLine.group(1) curRemotePort = portIdLine.group(2) localPort['portId'] = curLocalPort remotePort['portId'] = curRemotePort keyLine = re.match("Key\s*\|(.*)\|(.*)", curLine) if keyLine: curLocalKey = keyLine.group(1) curRemoteKey = keyLine.group(2) localPort['key'] = curLocalKey remotePort['key'] = curRemoteKey stateLine = re.match("State\s*\|(.*)\|(.*)", curLine) if stateLine: # Catch from local activeFlag = re.match("A", stateLine.group(1)) if activeFlag: localPort['activeFlag'] = True else: localPort['activeFlag'] = False shortTimeFlag = re.match("S", stateLine.group(1)) if shortTimeFlag: localPort['shortTimeFlag'] = True else: localPort['shortTimeFlag'] = False collectingFlag = re.match("C", stateLine.group(1)) if collectingFlag: localPort['collectingFlag'] = True else: localPort['collectingFlag'] = False stateExpiredFlag = re.match("X", stateLine.group(1)) if stateExpiredFlag: localPort['stateExpiredFlag'] = True else: localPort['stateExpiredFlag'] = False passiveFlag = re.match("P", stateLine.group(1)) if passiveFlag: localPort['passiveFlag'] = True else: localPort['passiveFlag'] = False longTimeOutFlag = re.match("L", stateLine.group(1)) if longTimeOutFlag: localPort['longTimeOutFlag'] = True else: localPort['longTimeOutFlag'] = False distributingFlag = re.match("D", stateLine.group(1)) if distributingFlag: localPort['distributingFlag'] = True else: localPort['distributingFlag'] = False aggregableFlag = re.match("F", stateLine.group(1)) if aggregableFlag: localPort['aggregableFlag'] = True else: localPort['aggregableFlag'] = False inSyncFlag = re.match("N", stateLine.group(1)) if inSyncFlag: localPort['inSyncFlag'] = True else: localPort['inSyncFlag'] = False neighborStateFlag = re.match("E", stateLine.group(1)) if neighborStateFlag: localPort['neighborStateFlag'] = True else: localPort['neighborStateFlag'] = False individualFlag = re.match("I", stateLine.group(1)) if individualFlag: localPort['individualFlag'] = True else: localPort['individualFlag'] = False outSyncFlag = re.match("O", stateLine.group(1)) if outSyncFlag: localPort['outSyncFlag'] = True else: localPort['outSyncFlag'] = False # Cath from remote activeFlag = re.match("A", stateLine.group(1)) if activeFlag: remotePort['activeFlag'] = True else: remotePort['activeFlag'] = False shortTimeFlag = re.match("S", stateLine.group(1)) if shortTimeFlag: remotePort['shortTimeFlag'] = True else: remotePort['shortTimeFlag'] = False collectingFlag = re.match("C", stateLine.group(1)) if collectingFlag: remotePort['collectingFlag'] = True else: remotePort['collectingFlag'] = False stateExpiredFlag = re.match("X", stateLine.group(1)) if stateExpiredFlag: remotePort['stateExpiredFlag'] = True else: remotePort['stateExpiredFlag'] = False passiveFlag = re.match("P", stateLine.group(1)) if passiveFlag: remotePort['passiveFlag'] = True else: remotePort['passiveFlag'] = False longTimeOutFlag = re.match("L", stateLine.group(1)) if longTimeOutFlag: remotePort['longTimeOutFlag'] = True else: remotePort['longTimeOutFlag'] = False distributingFlag = re.match("D", stateLine.group(1)) if distributingFlag: remotePort['distributingFlag'] = True else: remotePort['distributingFlag'] = False aggregableFlag = re.match("F", stateLine.group(1)) if aggregableFlag: remotePort['aggregableFlag'] = True else: remotePort['aggregableFlag'] = False inSyncFlag = re.match("N", stateLine.group(1)) if inSyncFlag: remotePort['inSyncFlag'] = True else: remotePort['inSyncFlag'] = False neighborStateFlag = re.match("E", stateLine.group(1)) if neighborStateFlag: remotePort['neighborStateFlag'] = True else: remotePort['neighborStateFlag'] = False individualFlag = re.match("I", stateLine.group(1)) if individualFlag: remotePort['individualFlag'] = True else: remotePort['individualFlag'] = False outSyncFlag = re.match("O", stateLine.group(1)) if outSyncFlag: remotePort['outSyncFlag'] = True else: remotePort['outSyncFlag'] = False data['localPort'] = localPort data['remotePort'] = remotePort # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=overallBuffer, data=data) return returnCls
def ServerConfig(** kwargs): """ Library function to configure workstations with server configuration. Take a backup of default server files and edit with customized configuration when the action = config (default) Start the respective service specified for the server (dhcpd/tftp/radiusd) When (action = "unconfig") move the backed up files to restore the workstation and stop the server services configured. :param deviceObj : Device object :type deviceObj : object :param serverConfigs : server string to be configured :type serverConfigs : string :param serviceConfig : server service configuration :type serviceConfig : string :param backupFile : backup file path for server configuration files :type backupFile : string :param serverConfigFile : Filepath of server configuration files :type serverConfigFile : string :param service : server service to be configured (restart/stop/start) :type service : string :param action : config(configure server parameters) , "unconfig" (to unconfigure) :type action : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) service = kwargs.get('service', None) serverConfigFile = kwargs.get('serverConfigFile', None) backupFile = kwargs.get('backupFile', None) serverConfigs = kwargs.get('serverConfigs', None) serviceConfig = kwargs.get('serviceConfig', None) action = kwargs.get('action', "config") # Variables bufferString = '' returnCode = 0 overallBuffer = [] retDictionary = [] # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device to configure") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Define the server configuration files depending on the service to be # configured/unconfigured if service == "dhcpd": serverConfigFile = "/etc/dhcp/dhcpd.conf" backupFile = "/etc/dhcp/dhcpd_bkup.conf" elif service == "tftp" : serverConfigFile = "/etc/default/tftpd-hpa" backupFile = "/etc/default/tftpd-hpa_bkup" #Configuring TFTP server if service == "tftp" : #Configure Tftp server configure serverConfigs = """ 'TFTP_USERNAME="******"\nTFTP_DIRECTORY="'/var/lib/tftpboot'"\nTFTP_ADDRESS="'0.0.0.0:69'"\nTFTP_OPTIONS="'\--secure \-c'"' """ #Appropriate permissions to the /var/lib/tftpboot directory command = "chmod 777 /var/lib/tftpboot/" returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') if returnCode != 0: opstestfw.LogOutput('error', " command %s not send on workstation" % (command)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput('info', "command %s executed " % (command)) command = "sudo chown -R nobody /var/lib/tftpboot/" returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') if returnCode != 0: opstestfw.LogOutput('error', " command %s not send on workstation" % (command)) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput('info', "command %s executed " % (command)) if action == "config": # Configure the server # Move the server file and take a backup returnStruct = opstestfw.host.MoveFile( deviceObj=deviceObj, sourceFilePath=serverConfigFile, destinationFilePath=backupFile) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to move file %s on %s ->" % (serverConfigFile, deviceObj.device)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Moved the file %s to %s-->" % (serverConfigFile, backupFile)) # Edit the server file returnStruct = opstestfw.host.FileEdit( deviceObj=deviceObj, stringEdit=str(serverConfigs), filename=serverConfigFile) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to edit server file %s ->" %(serverConfigFile)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls # Check the pid and kill the service of it is already running (Residue # process should be killed) if service is not None: if serviceConfig != "stop": # Stop the service if it already running # Killing the old pid is important , since the service needs to # resume newly after configuration edit retStruct = opstestfw.host.GetServicePID( deviceObj=deviceObj, service=service) retDictionary = retStruct.dataKeys() if retDictionary: ProcessID = retStruct.valueGet(key='pid') command = "kill " + ProcessID returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') if returnCode != 0: opstestfw.LogOutput( 'error', "running (residue) process for service %s not killed" % (service)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "killed the running process for service %s" % (service)) else: opstestfw.LogOutput( 'info', "Stop service %s explicitly before starting it after configuration change" % (service)) # Pass service configurations to workstations and get the PID to check # if the service is running/stopped if service is not None: returnStruct = opstestfw.host.ServicesConfig( deviceObj=deviceObj, service=service, action=serviceConfig) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to configure action %s on service %s for %s ->" % (serviceConfig, service, deviceObj.device)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: retStruct = opstestfw.host.GetServicePID( deviceObj=deviceObj, service=service) retDictionary = retStruct.dataKeys() if (retDictionary and serviceConfig == "start") or (retDictionary and serviceConfig == "restart"): opstestfw.LogOutput( 'info', "Service %s --> %s" % (service, serviceConfig)) elif retDictionary is None and serviceConfig == "stop": opstestfw.LogOutput( 'info', "Service %s --> %s" % (service, serviceConfig)) else: opstestfw.LogOutput( 'error', "Service %s --> %s failed" % (service, serviceConfig)) returnCls = opstestfw.returnStruct( returnCode=1, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Unconfigure Server configurations , restore backup files") # Move the backedup config file returnStruct = opstestfw.host.MoveFile( deviceObj=deviceObj, sourceFilePath=backupFile, destinationFilePath=serverConfigFile) returnCode = returnStruct.returnCode() buffer = returnStruct.buffer() overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to move backup file %s on ->" % (backupFile, deviceObj.device)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls # Stop the service if it already running if service is not None: retStruct = opstestfw.host.GetServicePID( deviceObj=deviceObj, service=service) retDictionary = retStruct.dataKeys() if retDictionary: ProcessID = retStruct.valueGet(key='pid') command = "kill " + ProcessID returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to kill %s service while unconfiguring " % (service)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "Kill %s service while unconfiguring " % (service)) bufferString = ' ' for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def InterfaceStatisticsShow(**kwargs): """ Library function get statistics for an specific interface :param deviceObj : Device object :type deviceObj : object :param interface : interface to configure :type interface : integer :return: returnStruct Object data: RX: inputPackets,inputErrors,CRC_FCS,bytes, dropped TX: outputPackets,inputError,collision,bytes,dropped :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) interface = kwargs.get('interface', None) # Variables overallBuffer = [] data = dict() bufferString = "" command = "" returnCode = 0 # Dictionary initialization data['RX'] = [] data['TX'] = [] if deviceObj is None: opstestfw.LogOutput('error', "Need to pass switch deviceObj to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Send Command command = "show interface" if interface is not None: command += " " + str(interface) opstestfw.LogOutput('info', "Show interface statistics.*****" + command) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) # temporaryBuffer = returnDevInt['buffer'] if retCode != 0: opstestfw.LogOutput('error', "Failed to get information ." + command) # Get out of the Shell # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # End Return Command # Return The Dict responds for curLine in overallBuffer: bufferString += str(curLine) bufferSplit = bufferString.split("\r\n") rx = dict() tx = dict() # Filling up the dictionaries rxTokens = re.findall( r'RX\s*\r\n\s*(\d*)\s*input\s*packets\s*(\d*)\s*bytes\s*\r\n\s*' + '(\d*)\s*input\s*error\s*(\d*)\s*dropped\s*\r\n\s*(\d*)', bufferString) txTokens = re.findall( r'TX\s*\r\n\s*(\d*)\s*output\s*packets\s*(\d*)\s*bytes\s*\r\n\s*' + '(\d*)\s*input\s*error\s*(\d*)\s*dropped\s*\r\n\s*(\d*)', bufferString) if rxTokens: rx['inputPackets'] = rxTokens[0][0] rx['bytes'] = rxTokens[0][1] rx['inputErrors'] = rxTokens[0][2] rx['dropped'] = rxTokens[0][3] rx['CRC_FCS'] = rxTokens[0][4] else: returnCode = 1 opstestfw.LogOutput('error', "Failed to get information ." + command) if txTokens: tx['outputPackets'] = txTokens[0][0] tx['bytes'] = txTokens[0][1] tx['inputErrors'] = txTokens[0][2] tx['dropped'] = txTokens[0][3] tx['collision'] = txTokens[0][4] else: returnCode = 1 opstestfw.LogOutput('error', "Failed to get information ." + command) data['RX'] = rx data['TX'] = tx # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=bufferString, data=data) return returnCls
def lagMode(**kwargs): """ Library function to configure a LAGs mode (static/dynamic) :param deviceObj : Device object :type deviceObj : object :param lagId : LAG Identifier :type lagId : integer :param lacpMode : off: Static LAG active: Active dynamic LAG passive: Passive dynamic LAG :type lacpMode : string :return: returnStruct Object :returnType: object """ # Params lagId = kwargs.get('lagId', None) deviceObj = kwargs.get('deviceObj', None) lacpMode = kwargs.get('lacpMode', 'off') # Variables overallBuffer = [] initialStatus = '' finalReturnCode = 0 # If deviceObj, lagId or lacpMode are not present, thorw an error if deviceObj is None or lagId is None: opstestfw.LogOutput('error', "Need to pass deviceObj and lagId to use this " "routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) overallBuffer.append(returnStructure.buffer()) returnCode = returnStructure.returnCode() if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Query switch for LAG configuration # Note this command is not the core of the function, but it is so # important that if the initial status of the LAG mode cannot be # determined, the other will always fail command = 'show lacp aggregates lag' + str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Could not obtain LAG LACP mode initial status") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) else: # TEMPORARY # Obtain result of command buffer2 = '' while True: result = deviceObj.expectHndl.expect(['# ', pexpect.TIMEOUT], timeout=5) buffer2 += str(deviceObj.expectHndl.before) + str(deviceObj.expectHndl.after) if result == 1: break overallBuffer.append(buffer2) # END OF TEMPORARY # Parse buffer for values of interest bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) result = re.search('Aggregate mode[ ]+: (off|passive|active)', bufferString) if result is None: opstestfw.LogOutput('error', "Could not identify LAG LACP mode initial " "status") returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: initialStatus = result.group(1) opstestfw.LogOutput('debug', "LAG LACP mode initial status identified as " + initialStatus) # mVerify if the LAG was already in static mode and will be changed # again if initialStatus == lacpMode and lacpMode == 'off': opstestfw.LogOutput('debug', "LACP mode is set to off already. No change " "is performed") else: # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # enter LAG configuration context command = "interface lag " + str(lagId) returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to enter LAG" + str(lagId) + " configuration context on device " + deviceObj.device) bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) else: opstestfw.LogOutput('debug', "Entered LAG" + str(lagId) + " configuration context on device " + deviceObj.device) # configure LAG mode if str(lacpMode) != 'off': command = "lacp mode " + str(lacpMode) else: command = "no lacp mode " + initialStatus returnDevInt = deviceObj.DeviceInteract(command=command) finalReturnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if finalReturnCode != 0: opstestfw.LogOutput('error', "Failed to configure LACP mode to " + lacpMode + " on device " + deviceObj.device) else: opstestfw.LogOutput('debug', "Changed LACP mode to " + lacpMode + " on device " + deviceObj.device) # exit LAG configuration context command = "exit" returnDevInt = deviceObj.DeviceInteract(command=command) returnCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit LAG " + str(lagId) + " configuration context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get out of vtysh config " "context") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vty shell") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Compile information to return bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=finalReturnCode, buffer=bufferString) return returnCls
def showInterface(**kwargs): """ Library function to get specific interface information from the device :param deviceObj : Device object :type deviceObj : object :param interface : interface number context (optional) :type interface : integer :return: returnStruct Object buffer :returnType: object """ deviceObj = kwargs.get('deviceObj', None) interface = kwargs.get('interface', None) overallBuffer = [] bufferString = "" # If Device object is not passed, we need to error out if deviceObj is None: opstestfw.LogOutput( 'error', "Need to pass switch deviceObj" + "to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls ########################################################################## # Send Command ########################################################################## if interface is None: command = "show interface" else: command = "show interface " + str(interface) opstestfw.LogOutput('debug', "Sending: " + command) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to get information ." + command) ########################################################################### # Get out of the Shell ########################################################################### returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls ########################################################################### # Exit for context and validate buffer with information ########################################################################### for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def ServicesConfig(** kwargs): """ Library function to start/stop/restart services on Ubuntu workstations :param deviceObj : Device object :type deviceObj : object :param service : Server service (dhcpd/tftp/radiusd) :type service : string :param action : service action (start/stop/restart) :type action : string :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) service = kwargs.get('service', None) action = kwargs.get('action', 'start') # Variables overallBuffer = [] bufferString = '' returnCode = 0 # If device is not passed, we need error message if deviceObj is None: opstestfw.LogOutput('error', "Need to pass device object") returnJson = opstestfw.returnStruct(returnCode=1) return returnJson # Move files on workstation to destination path # For DHCP service on Ubuntu workstations if service == "dhcpd": server_service = "isc-dhcp-server" elif service == "freeradius": # freeradius service on Ubuntu workstation server_service = "freeradius" elif service == "tftp" : #tftpd service for ubuntu server_service = "tftpd-hpa" command = "service %s %s" % (server_service, action) returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') overallBuffer.append(buffer) if returnCode != 0: opstestfw.LogOutput( 'error', "Failed to %s service %s on %s->" % (action, service, deviceObj.device)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput( 'info', "%s service %s , get the pid" % (action, service)) command = "pgrep " + service returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') # Configure service command = "pgrep " + service returnStruct = deviceObj.DeviceInteract(command=command) returnCode = returnStruct.get('returnCode') buffer = returnStruct.get('buffer') overallBuffer.append(buffer) if returnCode != 0 and service != "stop": opstestfw.LogOutput( 'error', "service %s on %s :: %s->" % (service, deviceObj.device, action)) returnCls = opstestfw.returnStruct( returnCode=returnCode, buffer=buffer) return returnCls else: opstestfw.LogOutput('info', "Service %s -> %s->" % (service, action)) for curLine in overallBuffer: bufferString += str(curLine) # Compile information to return returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def AddVlan(**kwargs): """ Library function to add a VLAN. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param config : True if a port is to be added to the VLAN, False if a port is to be removed from a VLAN. Defaults to True. :type config : boolean :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) config = kwargs.get('config', True) overallBuffer = [] resultCode = 0 # If Device object is not passed, we need to error out if deviceObj is None or vlanId is None: opstestfw.LogOutput('error', "Need to pass switch device object deviceObj and " "VLAN Id vlanId to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls if config: command = "" else: command = "no " command = command + "vlan " + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) bufferString = "" if retCode != 0: if config: opstestfw.LogOutput('error', "Failed to create VLAN or failed to get " "into VLAN context." + command) resultCode = 3 else: opstestfw.LogOutput('error', "Failed to delete VLAN." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) else: if config: opstestfw.LogOutput('debug', "Created VLAN or entered VLAN context." + command) else: opstestfw.LogOutput('debug', "Deleted VLAN." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit vlan context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited VLAN context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) if resultCode == 3: returnCls = opstestfw.returnStruct(returnCode=3, buffer=bufferString) return returnCls returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls
def lagpGlobalSystemPriority(**kwargs): """ Function to configure Global LACP system Priority :param deviceObj : Device object :type deviceObj : object :param systemPriority : Identification Default is system MAC address, can be changed for another one :type systemPriority : string :param configure : (Optional -Default is True) True to configure, False to unconfigure :type configure : boolean :return: returnStruct Object :returnType: object """ # Params deviceObj = kwargs.get('deviceObj', None) systemPriority = kwargs.get('systemPriority', None) configure = kwargs.get('configure', True) # Variables overallBuffer = [] data = dict() bufferString = "" command = "" # If Device object is not passed, we need to error out if deviceObj is None or systemPriority is None: opstestfw.LogOutput('error', "Need to pass switch deviceObj and systemPriority" " to this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtysh returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Uconfigure system ID if configure is False: command = "no " # Normal configuration command command += ("lacp system-priority " + str(systemPriority)) returnStructure = deviceObj.DeviceInteract(command=command) retCode = returnStructure['returnCode'] overallBuffer.append(returnStructure['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to configure LACP system priority: " + str(systemPriority)) else: opstestfw.LogOutput('debug', "LACP system priority configured: " + str(systemPriority)) # Get out of config context returnStructure = deviceObj.ConfigVtyShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit configure terminal prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.retStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit enable prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.retStruct(returnCode=returnCode, buffer=bufferString) return returnCls # Return results for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString, data=data) return returnCls
def AddPortToVlan(**kwargs): """ Library function to add a port to a VLAN. :param deviceObj : Device object :type deviceObj : object :param vlanId : Id of the VLAN to be added. This is casted to string (optional) :type vlanId : integer :param interface : Id of the interface to add to the VLAN. Routing will be disabled in the interface. Send here a string "lag X" to add a lag. :type interface : int :param access : True to add access to the command, False to add trunk to the command. Defaults to False. :type access : boolean :param allowed : True to add allowed after trunk, False to add native after trunk. Defaults to False. :type allowed : boolean :param tag : True to add tag after native. False to add nothing. Defaults to False. :type tag : boolean :param config : True if a port is to be added to the VLAN, False if a port is to be removed from a VLAN. Defaults to True. :type config : boolean :return: returnStruct Object :returnType: object """ deviceObj = kwargs.get('deviceObj', None) vlanId = kwargs.get('vlanId', None) interface = kwargs.get('interface', None) access = kwargs.get('access', False) allowed = kwargs.get('allowed', False) tag = kwargs.get('tag', False) config = kwargs.get('config', True) overallBuffer = [] # If Device object is not passed, we need to error out if deviceObj is None or vlanId is None or interface is None: opstestfw.LogOutput('error', "Need to pass switch device object deviceObj, " "interface interface and VLAN Id vlanId to " "this routine") returnCls = opstestfw.returnStruct(returnCode=1) return returnCls # Get into vtyshelll returnStructure = deviceObj.VtyshShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Get into config context returnStructure = deviceObj.ConfigVtyShell(enter=True) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to get vtysh config prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls command = "interface " + str(interface) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to get into interface prompt." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Got into interface prompt." + command) command = "no routing" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to disable routing in the interface." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited interface context." + command) if config: command = "" else: command = "no " command = command + "vlan " if access: command = command + "access " + str(vlanId) else: command = command + "trunk " if allowed: command = command + "allowed " + str(vlanId) else: command = command + "native " if tag: command = command + "tag" else: command = command + str(vlanId) returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: if config: opstestfw.LogOutput('error', "Failed to add the port to the VLAN." + command) else: opstestfw.LogOutput('error', "Failed to remove the port from the VLAN." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Added the port to the VLAN." + command) command = "end" returnDevInt = deviceObj.DeviceInteract(command=command) retCode = returnDevInt['returnCode'] overallBuffer.append(returnDevInt['buffer']) if retCode != 0: opstestfw.LogOutput('error', "Failed to exit interface context." + command) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls else: opstestfw.LogOutput('debug', "Exited interface context." + command) # Get out of vtyshell returnStructure = deviceObj.VtyshShell(enter=False) returnCode = returnStructure.returnCode() overallBuffer.append(returnStructure.buffer()) if returnCode != 0: opstestfw.LogOutput('error', "Failed to exit vtysh prompt") bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=1, buffer=bufferString) return returnCls # Return results bufferString = "" for curLine in overallBuffer: bufferString += str(curLine) returnCls = opstestfw.returnStruct(returnCode=0, buffer=bufferString) return returnCls