コード例 #1
0
ファイル: baseLinux.py プロジェクト: mr-liusg/forward
 def deleteUser(self, username):
     """Delete a user on the device
     """
     # set command
     commandDelUser = '******' % username
     result = {"status": False, "content": "", "errLog": ""}
     try:
         if not username:
             raise ForwardError(
                 "[Delete User Error]: %s: Username could NOT be blank." %
                 self.ip)
         # Login status check.
         if self.isLogin:
             # send command.
             delUserResult = self.execute(commandDelUser)
             if delUserResult['status']:
                 if not delUserResult['content']:
                     # success
                     pass
                 else:
                     # failed.
                     raise ForwardError("[Delete User Error]: %s: %s" %
                                        (self.ip, delUserResult['content']))
                 result['status'] = True
                 return result
             else:
                 raise ForwardError("[Delete User Error]: %s: %s" %
                                    (self.ip, delUserResult['errLog']))
         else:
             raise ForwardError("[Delete User Error]: %s: Not login yet." %
                                self.ip)
     except ForwardError, e:
         result['status'] = False
         result['errLog'] = str(e)
コード例 #2
0
ファイル: baseSSHV2.py プロジェクト: zhangalbert/forward
 def getPrompt(self):
     """Automatically get the current system prompt by sending a carriage return
     """
     if self.isLogin:
         # login status True
         result = ''
         self.cleanBuffer()
         self.shell.send('\n')
         # set recv timeout to self.timeout/10 fot temporary
         while not re.search(self.basePrompt, result):
             result += self.shell.recv(1024)
         if result:
             # recv() get something
             # select last line character,[ex]' >[localhost@labstill019~]$ '
             self.prompt = result.split('\n')[-1]
             # [ex]'>[localhost@labstill019~]$'
             # self.prompt=self.prompt.split()[0]
             # [ex]'[localhost@labstill019~]'
             # self.prompt=self.prompt[1:-1]
             # [ex]'\\[localhost\\@labstill019\\~\\]$'
             self.prompt = re.escape(self.prompt)
             return self.prompt
         else:
             # timeout,get nothing,raise error
             raise ForwardError(
                 '[Get Prompt Error]: %s: Timeout,can not get prompt.' %
                 self.ip)
     else:
         # login status failed
         raise ForwardError('[Get Prompt Error]: %s: Not login yet.' %
                            self.ip)
コード例 #3
0
 def deleteUser(self, username):
     """Delete a user on the device
     """
     data = {"status": False, "content": "", "errLog": ""}
     try:
         if not username:
             raise ForwardError('Please specify a username')
         # swith to config terminal mode.
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         # check terminal status
         if self.isConfigMode:
             # delete user
             self.channel.write(
                 'delete system login user {username}\n'.format(
                     username=username))
             i = self.channel.expect([r"%s" % self.prompt],
                                     timeout=self.timeout)
             result = i[-1]
             if re.search('error|invalid', result, flags=re.IGNORECASE):
                 # command failure
                 raise ForwardError(result)
             else:
                 # Save
                 data = self._commit()
                 # exit config terminal mode.
                 self._exitConfigMode()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
コード例 #4
0
 def isVlan(self, vlan):
     """Check if the Vlan exists.
     """
     info = {"status": False, "content": "", "errLog": ""}
     # swith to config mode
     # info = self._configMode()
     # if not info["status"]:
     #    raise ForwardError(info["errLog"])
     # switch to enable mode.
     tmp = self.privilegeMode()
     if not tmp:
         raise ForwardError(tmp["errLog"])
     while True:
         # Send command.
         tmp = self.execute("show vlan {vlan} verbose".format(vlan=vlan))
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         if re.search("VLAN ID:{vlan}".format(vlan=vlan), tmp["content"]):
             # vlan is exists
             info["status"] = True
             break
         elif re.search("Command is in use by", tmp["content"]):
             # check failed,recheck
             continue
         else:
             # vlan not is exitsts
             info["status"] = False
             info["errLog"] = tmp["content"]
             break
     return info
コード例 #5
0
 def isTrunkInInterface(self, port=None, vlan=None):
     """Check the relationship between interface and turnk.
     """
     info = {"status": False,
             "content": "",
             "errLog": ""}
     # Prameters check.
     if (vlan is None) or (port is None):
         raise ForwardError('Specify the `vlan` and `port` parameters')
     while True:
         # Execute command.
         info = self.execute("show  run")
         if not info["status"]:
             raise ForwardError(info["errLog"])
         try:
             # Keyword search.
             tmp = re.search("interface eth-trunk {port}[\r\n]+ mode .*[\r\n]+ por\
 t .*[\r\n]+ port .* vlan .*{vlan}".format(port=port, vlan=vlan), info['content'])
             if tmp:
                 # Exists.
                 info["status"] = True
                 break
             elif re.search('Command is in use by', info["content"]):
                 # Rechecking...
                 continue
             else:
                 info["errLog"] = info['errLog']
                 break
         except Exception as e:
             info["errLog"] = str(e)
             info["status"] = False
             break
     return info
コード例 #6
0
   def isVlanInPort(self, vlan=None, port=None):
       """Check that the Vlan exists in the port.
       """
       info = {"status": False,
               "content": "",
               "errLog": ""}
       # Parameters check.
       if (vlan is None) or (port is None):
           raise ForwardError('Specify the `vlan` and `port` parameters')
       # Execute command.
       info = self.execute("show  run")
       if not info["status"]:
           raise ForwardError(info["errLog"])
       try:
           # Keyword search
           tmp = re.search("\![\r\n]+interface gigaethernet {port}[\s\S]*por\
 link-type (access|trunk)[\s\S]*port .* vlan .*{vlan}".format(vlan=vlan, port=port), info["content"])
           if tmp:
               # Vlan in the port, case 1
               if tmp.group(1) == "access":
                   raise ForwardError("Configuration found, but port link - type is 'access', Not a trunk")
               info["content"] = tmp.group().split("ABCDEFG")
               info["status"] = True
           else:
               # No exists'
               raise ForwardError('No exists')
       except Exception as e:
           info["errLog"] = str(e)
           info["status"] = False
       return info
コード例 #7
0
    def command(self, cmd=None, prompt=None, timeout=30):
        """execute a command line, powerful and suitable for any scene,
        but need to define whole prompt dict list
        """
        result = {'status': True, 'content': '', 'errLog': '', "state": None}
        # Parameters check
        if (cmd is None) or (not isinstance(prompt, list)) or (not isinstance(
                timeout, int)):
            raise ForwardError("""You should pass such a form of argument: \
CMD = 'Your command', prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}] ,\
timeout=30""")
        for section in prompt:
            if not isinstance(section.values(), list):
                raise ForwardError("""you should pass such a form of argument:\
prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]"""
                                   )
        try:
            self.channel.write("{cmd}\r".format(cmd=cmd))
            try:
                info = ''
                while True:
                    """ First, the program accepts the return message based on the base prompt, and if you accept
                    it directly from the specified prompt, there will be many times out of time in the middle,
                    resulting in reduced efficiency"""
                    i = self.channel.expect(
                        [r'%s' % self.moreFlag,
                         r"%s" % self.basePrompt],
                        timeout=timeout)
                    info += i[-1]
                    if i[0] == 0:
                        tmp = self.newGetMore(prompt, timeout)
                        info += tmp[0]
                        result["state"] = tmp[1]
                        break
                    elif i[0] == -1:
                        raise ForwardError('Error: receive timeout ')
                    else:
                        for section in prompt:
                            # section.values() is : [ [p1,p2,p3] ]
                            for _prompt in section.values()[0]:
                                if re.search(_prompt, info.split("\n")[-1]):
                                    result["state"] = section.keys()[0]
                                    break
                            # Find the specified state type
                            if not result["state"] is None:
                                break
                        # Find the specified state type,exit
                        if not result["state"] is None:
                            break
                result['content'] += info
                result["content"] = re.sub("<--- More --->\\r +\\r", "",
                                           result["content"])
            # If you accept a timeout, cancel SSH
            except Exception, e:
                self.logout()
                raise ForwardError(str(e))
        except Exception, e:
            result["errLog"] = str(e)
            result["status"] = False
コード例 #8
0
 def createVlan(self, vlan=None, ascription=None):
     """Create a Vlan.
     """
     info = {"status": False, "content": "", "errLog": ""}
     if (vlan is None) or (ascription is None):
         raise ForwardError(
             "You must specify the `vlan` and `ascription` parameters")
     """Warning: that vlan should be checked
        by the 'self.isvlan(vlan) method
        before setting up the vlan"""
     # swith to config mode
     info = self._configMode()
     if not info["status"]:
         raise ForwardError(info["errLog"])
     try:
         # enter vlan
         info["content"] = ""
         self.shell.send("vlan {vlan}\n".format(vlan=vlan))
         while not re.search(self.basePrompt,
                             info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         # Get host prompt
         self.getPrompt()
         if not re.search('.*-vlan', self.prompt):
             raise ForwardError(
                 "Failed to enter vlan mode,command:vlan {vlan}".format(
                     vlan=vlan))
         # set host's ascription
         info["content"] = ""
         # Send command.
         self.shell.send(
             "name {ascription}\n".format(ascription=ascription))
         while not re.search(self.basePrompt,
                             info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         # Get host prompt.
         self.getPrompt()
         # save  the configuration.
         tmp = self._commit()
         if not tmp["status"]:
             raise ForwardError(
                 "The configuration command has been executed,\
                                 but the save configuration failed! [{info}]"
                 .format(info=info["content"]))
         else:
             if not self.isVlan(vlan)["status"]:
                 # check vlan
                 raise ForwardError(
                     "Vlan has been set and has been saved, but the final\
                                     check found no configuration, so failed.info:[%s]"
                     % tmp["content"])
             else:
                 # create successed. exit config mode
                 info["status"] = True
     except Exception as e:
         info["status"] = False
         info["errLog"] = str(e)
     return info
コード例 #9
0
 def createVlan(self, vlan):
     """Create a Vlan.
     """
     info = {"status": False,
             "content": "",
             "errLog": ""}
     """Warning: that vlan should be checked
        by the 'self.isvlan(vlan) method
        before setting up the vlan"""
     # swith to config mode
     info = self._configMode()
     if not info["status"]:
         raise ForwardError(info["errLog"])
     try:
         # enter vlan
         self.shell.send("vlan {vlan}\n".format(vlan=vlan))
         # Host prompt is modified
         info["content"] = ""
         while not re.search(self.basePrompt, info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         self.getPrompt()
         if not re.search('vlan.*{vlan}'.format(vlan=vlan), self.prompt):
             raise ForwardError("Failed to enter vlan mode,command:vlan {vlan}".format(vlan=vlan))
         # exit vlan,switch to config mode
         self.shell.send("quit\n")
         # Host prompt is modified
         info["content"] = ""
         while not re.search(self.basePrompt, info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         # Get host prompt.
         self.getPrompt()
         # Failure to search for Vlan information.
         if re.search('vlan.*{vlan}'.format(vlan=vlan), self.prompt):
             raise ForwardError("Failed to exit vlan mode,command:quit")
         # Save the configuration.
         tmp = self._commit()
         if not tmp["status"]:
             raise ForwardError("The configuration command has been executed,\
                                 but the save configuration failed!")
         else:
             # Check is Vlan.
             tmp = self.isVlan(vlan)
             if not tmp["status"]:
                 # check vlan
                 raise ForwardError("Vlan has been set and has been saved, but the final\
                                     check found no configuration, so failed.\
                                     show vlan {vlan} verbose: [{content}]".format(vlan=vlan, content=tmp["errLog"]))
             else:
                 # create successed. exit config mode
                 info["status"] = True
     except Exception as e:
         info["errLog"] = str(e)
         info["status"] = False
     return info
コード例 #10
0
 def execute(self, cmd):
     """execute a command line, only suitable for the scene when
     the prompt is equal before and after execution
     """
     dataPattern = '[\r\n]+([\s\S]*)[\r\n]+(\x1b\[m)?' + self.prompt
     # Spaces will produce special characters and re.escape('show ver') --> show \\ ver
     data = {'status': False, 'content': '', 'errLog': ''}
     if self.isLogin:
         # check login status
         # [ex] when send('ls\r'),get 'ls\r\nroot base etc \r\n[wangzhe@cloudlab100 ~]$ '
         # [ex] data should be 'root base etc '
         self.cleanBuffer()
         self.channel.write(cmd + "\n")
         i = self.channel.expect(
             [r'%s' % self.moreFlag,
              r"%s" % self.prompt],
             timeout=self.timeout)
         # Get result
         result = i[-1]
         try:
             if i[0] == 0:
                 # Receive more characters
                 result += self.getMore()
             elif i[0] == -1:
                 # Recvive timeout
                 raise ForwardError('Error: receive timeout ')
             data['content'] += result
             try:
                 # Intercept command result
                 tmp = re.search(dataPattern, data['content']).group(1)
                 # Delete special characters caused by More split screen.
                 tmp = re.sub("<--- More --->\\r +\\r", "", tmp)
                 tmp = re.sub('(\x00|\x08){0,}', "", tmp)
                 tmp = re.sub(re.escape("--More(CTRL+Cbreak)--"), "", tmp)
                 data['content'] = tmp
                 data['status'] = True
             except Exception as e:
                 # Not found host prompt
                 raise ForwardError('not found host prompt Errorr(%s)' %
                                    str(e))
         except Exception as e:
             # Not found host prompt
             data['status'] = False
             data['errLog'] = data[
                 'errLog'] + 'not found host prompt Errorr(%s)' % str(e)
     else:
         # Not login
         data['status'] = False
         data['content'] = 'ERROR:device not login'
     return data
コード例 #11
0
 def trunkOpenVlan(self, port=None, vlan=None):
     """Create a vlan on turnk.
     """
     info = {"status": False,
             "content": "",
             "errLog": ""}
     # Parameters check.
     if (vlan is None) or (port is None):
         raise ForwardError('Specify the `vlan` and `port` parameters')
     try:
         # switch to enable mode
         tmp = self.privilegeMode()
         if not tmp["status"]:
             raise ForwardError(tmp['errLog'])
         # else ,successed
         # switch to config mode
         tmp = self._configMode()
         if not tmp["status"]:
             raise ForwardError(tmp['errLog'])
         # else ,successed
         # switch to port mode
         self.shell.send("interface eth-trunk {port}\n".format(port=port))
         # Host prompt is modified
         while not re.search(self.basePrompt, info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         # release host prompt
         self.getPrompt()
         # Keyword search.
         if not re.search("config.*-eth.*-trunk.*-{port}".format(port=port), self.prompt):
             raise ForwardError('[trunkOpenVlan] Switch to port mode is failed [%s]' % info["content"])
         # Execute command.
         tmp = self.execute("port trunk allow-pass vlan {vlan}".format(vlan=vlan))
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         else:
             # Check the returned 'tmp['content']', which indicates failure if it contains' Failed '
             if re.search('%Failed', tmp["content"]):
                 raise ForwardError('Execute the command "port trunk allow-pass vlan" is failed ,\
                                     result is [%s] ' % tmp["content"])
         # quit port mode
         self.shell.send("quit\n")
         info["content"] = ""
         while not re.search(self.basePrompt, info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         # save configuration
         self.getPrompt()
         # Save the configuration.
         tmp = self._commit()
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         # Verify that it is correct
         tmp = self.isTrunkInInterface(port=port, vlan=vlan)
         if not tmp["status"]:
             raise ForwardError("The configuration command has been executed,\
                                 but the check configuration does not exist! [%s]" % tmp['errLog'])
         info["status"] = True
     except Exception as e:
         info["errLog"] = str(e)
         info["status"] = False
     return info
コード例 #12
0
ファイル: baseSSHV1.py プロジェクト: zhangalbert/forward
 def newGetMore(self, prompt, timeout):
     # Applies to the command method
     # The return message is received until there is no More character like More.
     result = ''
     state = None
     continueRecv = False
     while True:
         if not continueRecv:
             self.channel.send('\r')
         i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.basePrompt, pexpect.TIMEOUT], timeout=timeout)
         if i == 0:
             result += self.channel.before
             # After the encounter `moreFlag`, need to get the message
         elif i == 1:
             result += self.channel.before
             result += self.channel.after
             # After the encounter prompt, need to get the result
             for section in prompt:
                 # section.values() is : [ [p1,p2,p3] ]
                 for _prompt in section.values()[0]:
                     if re.search(_prompt, result.split("\n")[-1]):
                         state = section.keys()[0]
                         break
                 # Find the specified state type
                 if state is not None:
                     break
             # Find the specified state type,exit
             if state is not None:
                 break
             else:
                 # Not  found,Continue to receive
                 continueRecv = True
         else:
             raise ForwardError("function: getMore recv timeout")
     return (result, state)
コード例 #13
0
 def getPrompt(self):
     """Automatically get the current system prompt by sending a carriage return
     """
     if self.isLogin:
         # login status True
         self.cleanBuffer()
         self.channel.send('\n')
         """The host base prompt is the end of the received flag, and if the data is
         not received at the set time, the timeout is exceeded.
         """
         self.channel.expect([r"%s" % self.basePrompt, pexpect.TIMEOUT],
                             timeout=self.timeout)
         # select last line character,[ex]' >[localhost@labstill019~]$ '
         # [ex]'>[localhost@labstill019~]$'
         # self.prompt=self.prompt.split()[0]
         # [ex]'[localhost@labstill019~]'
         # self.prompt=self.prompt[1:-1]
         # [ex]'\\[localhost\\@labstill019\\~\\]$'
         self.prompt = self.channel.before.split(
             '\n')[-1] + self.channel.after
     else:
         raise ForwardError('[Get Prompt Error]: %s: Not login yet.' %
                            self.ip)
     if re.search("> ?$", self.prompt):
         # If last character of host prompt of the device ens in '>', the command line of device in gneral mode.
         self.mode = 1
     elif re.search("(#|\]) ?$", self.prompt):
         # If last character of host prompt of the device ens in '#', the command line of device in enable mode.
         self.mode = 2
     return self.prompt
コード例 #14
0
 def addUser(self, username, password, admin=False):
     """Create a user on the device.
     """
     # Set command.
     if admin:
         command = """user administrator {username} local {password} \
                    authorized-table admin\n""".format(username=username,
                                                       password=password)
     else:
         command = """user administrator {username} local {password} \
                    authorized-table admsee\n""".format(username=username,
                                                        password=password)
     data = {"status": False, "content": "", "errLog": ""}
     try:
         # parameters check.
         if not username or not password:
             # Spcify a user name and password parameters here.
             raise ForwardError(
                 'Please specify the username = your-username and password = your-password'
             )
         # swith to config terminal mode.
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         if self.isConfigMode:
             # check terminal status
             self.channel.write(command)
             # adduser
             data = self._recv(self.prompt)
             # recv result
             if not data['status']:
                 # break
                 raise ForwardError(data['errLog'])
             result = data['content']
             if re.search('error|invalid|assword',
                          result,
                          flags=re.IGNORECASE):
                 # command failure
                 raise ForwardError(result)
             # set password is successed, save the configuration.
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
コード例 #15
0
ファイル: baseSSHV2.py プロジェクト: zhangalbert/forward
    def command(self, cmd=None, prompt=None, timeout=30):
        """execute a command line, powerful and suitable for any scene,
        but need to define whole prompt dict list
        """
        result = {'status': True, 'content': '', 'errLog': '', "state": None}
        # Parameters check
        if (cmd is None) or (not isinstance(prompt, list)) or (not isinstance(
                timeout, int)):
            raise ForwardError("""You should pass such a form of argument: \
CMD = 'Your command', prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]"""
                               )
        for section in prompt:
            if not isinstance(section.values(), list):
                raise ForwardError("""you should pass such a form of argument:\
prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]"""
                                   )
        try:
            self.shell.send("{cmd}\r".format(cmd=cmd))
            try:
                while True:
                    self.getMore(result['content'])
                    result["content"] += self.shell.recv(1024)
                    for section in prompt:
                        # section.values() is : [ [p1,p2,p3] ]
                        for _prompt in section.values()[0]:
                            if re.search(_prompt,
                                         result["content"].split("\n")[-1]):
                                result["state"] = section.keys()[0]
                                break
                        # Find the specified state type
                        if not result["state"] is None:
                            break
                    # Find the specified state type,exit
                    if not result["state"] is None:
                        break
                result["content"] = re.sub("<--- More --->\\r +\\r", "",
                                           result["content"])
            # If you accept a timeout, cancel SSH
            except Exception, e:
                self.logout()
                raise ForwardError(str(e))
        except Exception, e:
            result["errLog"] = str(e)
            result["status"] = False
コード例 #16
0
ファイル: __init__.py プロジェクト: zhangalbert/forward
 def __init__(self, targets=None):
     # target: [[ip,model,user,pw,{port},{timeout}],...]
     super(Forward, self).__init__()
     self.instances = {}
     if (targets is None):
         self.targets = []
     elif paraCheck(targets):
         self.targets = targets
     else:
         raise ForwardError('[Forward Init Failed]: parameters type error')
コード例 #17
0
 def isTrunkInInterface(self, port=None, vlan=None):
     """Check the relationship between interface and turnk.
     """
     info = {"status": False, "content": "", "errLog": ""}
     if (vlan is None) or (port is None):
         raise ForwardError('Specify the `vlan` and `port` parameters')
     # switch to enable mode
     tmp = self.privilegeMode()
     if not tmp["status"]:
         raise ForwardError(tmp['errLog'])
     # else ,successed
     while True:
         tmp = self.execute(
             "display current-configuration interface Eth-Trunk")
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         if re.search("Command is in use by", tmp["content"]):
             # Recheck
             continue
         # Keyword search.
         data = re.search(
             "#[\r\n]+(interface Eth-Trunk{port}[\r\n]+[\s\S]*?)#".format(
                 port=port), tmp["content"])
         if not data:
             # No configuration found
             raise ForwardError(
                 "Not found port(port) info".format(port=port))
         try:
             if re.search(
                     "port trunk allow-pass vlan .*{vlan}".format(
                         vlan=vlan), data.group(1)):
                 # found it.
                 info["status"] = True
             else:
                 info["status"] = False
                 info["errLog"] = tmp["content"]
             break
         except Exception as e:
             info["errLog"] = str(e)
             info["status"] = False
             break
     return info
コード例 #18
0
 def _recv(self, _prompt):
     """The user receives the message returned by the device.
     """
     data = {"status": False, "content": "", "errLog": ""}
     # If the host prompt is received, the message is stopped.
     i = self.channel.expect([r"%s" % _prompt], timeout=self.timeout)
     try:
         if i[0] == -1:
             raise ForwardError('Error: receive timeout')
         data['status'] = True
         # Get result
         data['content'] = i[-1]
     except ForwardError, e:
         data['errLog'] = str(e)
コード例 #19
0
 def isVlan(self, vlan):
     """Check if the Vlan exists.
     """
     info = {"status": False, "content": "", "errLog": ""}
     # switch to enable mode.
     tmp = self.privilegeMode()
     if not tmp:
         raise ForwardError(tmp["errLog"])
     tmp = self.execute("display vlan {vlan}".format(vlan=vlan))
     if not tmp["status"]:
         raise ForwardError(tmp["errLog"])
     # If the above fails, exit immediately
     try:
         if re.search("Error: The VLAN does not exist", tmp["content"]):
             # vlan not is exitsts
             info["status"] = False
         else:
             # vlan is exists
             info["status"] = True
     except Exception as e:
         info["status"] = False
         info["errLog"] = str(e)
     return info
コード例 #20
0
 def deleteUser(self, username):
     """Delete a user on the device
     """
     data = {"status": False, "content": "", "errLog": ""}
     try:
         # swith to config terminal mode.
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         # Check config mode status.
         if self.isConfigMode:
             # check terminal status
             # deleteUser
             self.channel.write(
                 """no user administrator {username}\n""".format(
                     username=username))
             # recv result
             data = self._recv(self.prompt)
             if not data['status']:
                 # break
                 raise ForwardError(data['errLog'])
             # Get result.
             result = data['content']
             # Search for keywords to determine if the command execution is successful.
             if re.search('error|invalid|assword',
                          result,
                          flags=re.IGNORECASE):
                 # command failure
                 raise ForwardError(result)
             # delete user is successed, save the configuration.
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
コード例 #21
0
 def _recv(self, _prompt):
     # Gets the return message after the command is executed.
     data = {"status": False, "content": "", "errLog": ""}
     # If the received message contains the host prompt, stop receiving.
     i = self.channel.expect([r"%s" % _prompt], timeout=self.timeout)
     try:
         if i[0] == -1:
             # The supplied host prompt is incorrect, resulting in the receive message timeout.
             raise ForwardError('Error: receive timeout')
         # Successed.
         data['status'] = True
         # Get result.
         data['content'] = i[-1]
     except ForwardError, e:
         data['errLog'] = str(e)
コード例 #22
0
ファイル: baseSSHV2.py プロジェクト: zhangalbert/forward
 def cleanBuffer(self):
     """Clean the shell buffer whatever they are, by sending a carriage return
     """
     if self.shell.recv_ready():
         self.shell.recv(4096)
     self.shell.send('\n')
     buff = ''
     # When after switching mode, the prompt will change, it should be based on basePrompt to check and at last line
     while not re.search(self.basePrompt, buff.split('\n')[-1]):
         try:
             buff += self.shell.recv(1024)
         except Exception:
             raise ForwardError(
                 '[Clean Buffer Error]: %s: Receive timeout [%s]' %
                 (self.ip, buff))
コード例 #23
0
 def isGateway(self, vlan):
     """Check that the gateway exists.
     """
     info = {"status": False, "content": "", "errLog": ""}
     # switch to enable mode.
     tmp = self.privilegeMode()
     if not tmp:
         raise ForwardError(tmp["errLog"])
     # Execute command.
     tmp = self.execute(
         "display current-configuration interface Vlanif {vlan}".format(
             vlan=vlan))
     if not tmp["status"]:
         raise ForwardError(tmp["errLog"])
     # If the above fails, exit immediately
     try:
         if re.search("Error: Wrong parameter found at", tmp["content"]):
             info["status"] = False
         else:
             info["status"] = True
     except Exception as e:
         info["status"] = False
         info["errLog"] = str(e)
     return info
コード例 #24
0
ファイル: asa.py プロジェクト: zhangalbert/forward
 def cleanBuffer(self):
     """Since the device is inconsistent with the details
     of the other Cisco series, the method needs to be rewritten
     to fit the device of this type.
     """
     if self.shell.recv_ready():
             self.shell.recv(4096)
     self.shell.send('\r\n')
     buff = ''
     """ When after switching mode, the prompt will change,
     it should be based on basePromptto check and at last line"""
     while not re.search(self.basePrompt, buff.split('\n')[-1]):
         try:
             # Cumulative return result
             buff += self.shell.recv(1024)
         except Exception:
             raise ForwardError('Receive timeout [%s]' % (buff))
コード例 #25
0
ファイル: baseRuijie.py プロジェクト: zhangalbert/forward
 def cleanBuffer(self):
     """Because the device USES the cleanBuffer method in different details,
     it can be rewritten to modify the function.
     """
     if self.shell.recv_ready():
         self.shell.recv(4096)
     # Ruijie equipment does not support sending line, must be sent to some characters
     self.shell.send(' \n')
     buff = ''
     # When after switching mode, the prompt will change, it should be based on basePrompt to check and at last line
     while not re.search(self.basePrompt, buff.split('\n')[-1]):
         try:
             # Accumulative results
             buff += self.shell.recv(1024)
         except Exception:
             raise ForwardError(
                 '[Clean Buffer Error]: %s: Receive timeout [%s]' %
                 (self.ip, buff))
コード例 #26
0
 def login(self):
     """Login method.
     Creates a login session for the program to send commands to the target device.
     """
     result = {'status': False, 'errLog': ''}
     # sshv2(ip,username,password,timeout,port=22)
     sshChannel = sshv2(self.ip, self.username, self.password, self.timeout,
                        self.port)
     if sshChannel['status']:
         # Login succeed, init shell
         try:
             result['status'] = True
             self._channel = sshChannel['content']
             # resize virtual console window size to 10000*10000
             self.shell = self._channel.invoke_shell(width=10000,
                                                     height=10000)
             self.channel = self.shell
             tmpBuffer = ''
             while (not re.search(
                     self.basePrompt,
                     tmpBuffer.split('\n')[-1])) and (not re.search(
                         '(new +password)|(password.*change)',
                         tmpBuffer.split('\n')[-1],
                         flags=re.IGNORECASE)):
                 tmpBuffer += self.shell.recv(1024)
             # if prompt is 'New Password' ,raise Error.
             if re.search('(new +password)|(password.*change)',
                          tmpBuffer.split('\n')[-1],
                          flags=re.IGNORECASE):
                 raise ForwardError(
                     '[Login Error]: %s: Password expired, needed to be updated!'
                     % self.ip)
             self.shell.settimeout(self.timeout)
             # Record login status to True.
             self.isLogin = True
             self.getPrompt()
         except Exception as e:
             result['status'] = False
             result['errLog'] = str(e)
     else:
         # Login failed
         self.isLogin = False
         result['errLog'] = sshChannel['errLog']
     return result
コード例 #27
0
ファイル: baseSSHV1.py プロジェクト: zhangalbert/forward
 def getPrompt(self):
     """Automatically get the current system prompt by sending a carriage return
     """
     if self.isLogin:
         # login status True
         self.channel.send('\n')
         """The host base prompt is the end of the received flag, and if the data is
         not received at the set time, the timeout is exceeded.
         """
         self.channel.expect([r"%s" % self.basePrompt, pexpect.TIMEOUT], timeout=self.timeout)
         # select last line character,[ex]' >[localhost@labstill019~]$ '
         # [ex]'>[localhost@labstill019~]$'
         # self.prompt=self.prompt.split()[0]
         # [ex]'[localhost@labstill019~]'
         # self.prompt=self.prompt[1:-1]
         # [ex]'\\[localhost\\@labstill019\\~\\]$'
         self.prompt = self.channel.before.split('\n')[-1] + "(>|#|\$|\]|\)) *$"
     else:
         raise ForwardError('[Get Prompt Error]: %s: Not login yet.' % self.ip)
     return self.prompt
コード例 #28
0
 def newGetMore(self, prompt, timeout):
     # Applies to the command method
     """Automatically get more echo infos by sending a blank symbol
     """
     result = ''
     state = None
     continueRecv = False
     while True:
         # If the acceptance is not complete, you cannot send a space
         if not continueRecv:
             self.channel.send(' ')
         i = self.channel.expect([r'%s' % self.moreFlag, self.basePrompt],
                                 timeout=timeout)
         # Get result
         result += i[-1]
         if i[0] == 0:
             # Get more
             continue
         if i[0] == 1:
             # Find the base host prompt.
             for section in prompt:
                 # section.values() is : [ [p1,p2,p3] ]
                 for _prompt in section.values()[0]:
                     if re.search(_prompt, result.split("\n")[-1]):
                         state = section.keys()[0]
                         break
                 # Find the specified state type
                 if state is not None:
                     break
             # Find the specified state type,exit
             if state is not None:
                 break
             else:
                 # Not  found,Continue to receive
                 continueRecv = True
         else:
             raise ForwardError('getMore recv timeout:[%s]' % result)
     return (result, state)
コード例 #29
0
ファイル: s3300.py プロジェクト: zhangalbert/forward
 def _recv(self, _prompt):
     """A message returned after the receiving device has executed the command.
     """
     data = {'status': False, 'content': '', 'errLog': ''}
     # If the received message contains the host prompt, stop accepting.
     i = self.channel.expect([r"%s" % _prompt, pexpect.TIMEOUT],
                             timeout=self.timeout)
     result = ''
     try:
         if i == 0:
             # Get result.
             result = self.channel.before
             data['status'] = True
         elif i == 2:
             raise ForwardError('Error: receive timeout')
         else:
             """If the program does not receive the message correctly,
             and does not timeout, the program runs failed.
             """
             data['errLog'] = self.channel.before
         data['content'] = result
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
コード例 #30
0
 def createVlanInPort(self, port=None, vlan=None):
     """Create a vlan on the port.
     """
     # Prameters check.
     if (port is None) or (vlan is None):
         raise ForwardError('Specify the `port` parameter')
     info = {"status": False,
             "content": "",
             "errLog": ""}
     try:
         # switch to enable mode
         tmp = self.privilegeMode()
         if not tmp["status"]:
             raise ForwardError(tmp['errLog'])
         # else ,successed
         # switch to config mode
         tmp = self._configMode()
         if not tmp["status"]:
             raise ForwardError(tmp['errLog'])
         # else ,successed
         # switch to port mode
         info["content"] = ""
         self.shell.send("interface gigaethernet {port}\n".format(port=port))
         # Host prompt is modified
         while not re.search(self.basePrompt, info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         # release host prompt
         self.getPrompt()
         # Check the port mode
         if not re.search('config.*-ge', self.prompt):
             raise ForwardError('Switch to port mode is failed [%s]' % info["content"])
         # else successed.
         tmp = self.execute("port link-type trunk")
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         tmp = self.execute("port trunk allow-pass vlan {vlan}".format(vlan=vlan))
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         else:
             # Check the returned 'tmp['content']', which indicates failure if it contains' Failed '
             if re.search('%Failed', tmp["content"]):
                 raise ForwardError('Execute the command "port trunk allow-pass vlan" is failed ,\
                                     result is [%s] ' % tmp["content"])
             # else  successed
         tmp = self.execute("no shutdown")
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         # quit port mode
         self.shell.send("quit\n")
         info["content"] = ""
         while not re.search(self.basePrompt, info['content'].split('\n')[-1]):
             info['content'] += self.shell.recv(1024).decode()
         self.getPrompt()
         # save configuration
         tmp = self._commit()
         if not tmp["status"]:
             raise ForwardError(tmp["errLog"])
         # Verify that it is correct
         tmp = self.isVlanInPort(port=port, vlan=vlan)
         if not tmp["status"]:
             raise ForwardError("The configuration command has been executed,\
                                 but the check configuration does not exist! [%s]" % tmp["errLog"])
         else:
             # successed
             info["content"] = "successed"
             info["status"] = True
     except Exception as e:
         info["errLog"] = str(e)
         info["status"] = False
     return info