Exemple #1
0
 def deleteUser(self, username):
     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:
                 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
Exemple #2
0
 def addUser(self, username='', password='', addCommand='', admin=False):
     result = {
         "status": False,
         "content": "",
         "errLog": ""
     }
     try:
         if not addCommand:
             raise ForwardError("Please specify the add user's command")
         if not username or not password:
             # Specify 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'])
         # check terminal status
         if self.isConfigMode:
             self.cleanBuffer()
             # adduser
             self.shell.send(addCommand.format(username=username, password=password))
             while not re.search(self.prompt, result['content'].split('\n')[-1]):
                 result['content'] += self.shell.recv(1024)
             if re.search('error|invalid', result['content'], flags=re.IGNORECASE):
                 result['content'] = ''
                 raise ForwardError(result['content'])
             else:
                 # set password is successed.
                 result = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         result['status'] = False
         result['errLog'] = str(e)
Exemple #3
0
 def changePassword(self, username, password, userLevel=1):
     # user leve default 1
     data = {"status": False,
             "content": "",
             "errLog": ""}
     try:
         if not username or not password:
             # Specify a user name and password parameters here.
             raise ForwardError('Please specify the username = your-username and password = your-password')
         checkPermission = self._configMode()
         # swith to config terminal mode.
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         if self.isConfigMode:
             # check terminal status
             self.shell.send('local-user {username} password cipher {password}\n'.format(username=username,
                                                                                         password=password))
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and \
                    (re.search('local-user .* password cipher[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['status'] = False
         data['errLog'] = str(e)
Exemple #4
0
 def deleteUser(self, username):
     data = {"status": False,
             "content": "",
             "errLog": ""}
     try:
         # swith to config terminal mode.
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         if self.isConfigMode:
             # check terminal status
             self.cleanBuffer()
             self.shell.send('undo local-user {username}\n'.format(username=username))
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and \
                    (re.search('undo local-user[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             if re.search('error|invalid', data['content'], flags=re.IGNORECASE):
                 raise ForwardError(data['content'])
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['status'] = False
         data['errLog'] = str(e)
Exemple #5
0
 def deleteUser(self, username):
     data = {"status": False, "content": "", "errLog": ""}
     try:
         # swith to config terminal mode.
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         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'])
             result = data['content']
             if re.search('error|invalid|assword',
                          result,
                          flags=re.IGNORECASE):
                 # command failure
                 raise ForwardError(result)
             # delete user is successed.
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #6
0
 def deleteUser(self, username=''):
     result = {
         "status": False,
         "content": "",
         "errLog": ""
     }
     try:
         if not username:
             raise ForwardError("Please specify a username")
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         # check terminal status
         if self.isConfigMode:
             self.cleanBuffer()
             # delete username
             self.shell.send("no username {username}\n".format(username=username))
             while not re.search(self.prompt, result['content'].split('\n')[-1]):
                 result['content'] += self.shell.recv(1024)
             if re.search('error|invalid', result['content'], flags=re.IGNORECASE):
                 raise ForwardError(result['content'])
             else:
                 # deleted username
                 result = self._commit()
                 result['status'] = True
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         result['status'] = False
         result['errLog'] = str(e)
Exemple #7
0
    def deleteUser(self, username):
        commandDelUser = '******' % username

        result = {"status": False, "content": "", "errLog": ""}
        try:
            if not username:
                raise ForwardError(
                    "[Delete User Error]: %s: Username could NOT be blank." %
                    self.ip)
            if self.isLogin:
                delUserResult = self.execute(commandDelUser)
                if delUserResult['status']:
                    if not delUserResult['content']:
                        # success
                        pass
                    else:
                        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)
Exemple #8
0
 def execute(self, cmd):
     dataPattern = '[\r\n]+([\s\S]*)[\r\n]+' + self.prompt
     # Spaces will produce special characters and re.escape('show ver') --> show \\ ver
     data = {'status': False,
             'content': '',
             'errLog': ''}
     if self.isLogin:
         self.cleanBuffer()
         self.channel.write(cmd + "\n")
         i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.prompt], timeout=self.timeout)
         result = i[-1]
         try:
             if i[0] == 0:
                 result += self.getMore()
             elif i[0] == -1:
                 raise ForwardError('Error: receive timeout ')
             data['content'] += result
             try:
                 tmp = re.search(dataPattern, data['content']).group(1)
                 data['content'] = tmp
                 data['status'] = True
             except Exception, e:
                 raise ForwardError('not found host prompt Errorr(%s)' % str(e))
         except Exception, e:
             data['status'] = False
             data['errLog'] = data['errLog'] + 'not found host prompt Errorr(%s)' % str(e)
Exemple #9
0
 def _commit(self):
     data = {'status': False, 'content': '', 'errLog': ''}
     saveCommand = "copy running-config startup-config"
     try:
         if self.isConfigMode:
             self._exitConfigMode()
             self.channel.send('%s\n' % (saveCommand))
             # save setup to system
             data = self._recv(self.prompt)
             if re.search('user "admin" only', data['content']):
                 raise ForwardError(data['content'])
             else:
                 data['status'] = True
         else:
             raise ForwardError(
                 'Error: The current state is not configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #10
0
 def addUser(self, username, password, userLevel=1):
     data = {'status': False, 'content': '', 'errLog': ''}
     try:
         if not username or not password:
             raise ForwardError(
                 'Please specify the username = your-username \
                                and password = your-password')
             # Specify a user name and password parameters here.
         # swith to config terminal mode.
         checkPermission = self._configMode()
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         if self.isConfigMode:
             # check terminal status
             self.channel.send(
                 """username {username} privilege  {userLevel} \
                                  password 0 {password}\n""".format(
                     username=username,
                     password=password,
                     userLevel=userLevel))
             _result = self._recv(self.prompt)
             _tmp = re.search(
                 """This command can be used by user "admin" only""",
                 _result['content'])
             if _tmp:
                 raise ForwardError(_tmp.group())
             elif not _result['status']:
                 raise ForwardError(_result['errLog'])
             self.channel.send(
                 """username {username} terminal ssh\n""".format(
                     username=username,
                     password=password,
                     userLevel=userLevel))
             _result = self._recv(self.prompt)
             if _result['status']:
                 data = self._commit()
             else:
                 data = _result
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #11
0
 def _recv(self, _prompt):
     data = {"status": False, "content": "", "errLog": ""}
     i = self.channel.expect([r"%s" % _prompt], timeout=self.timeout)
     try:
         if i[0] == -1:
             raise ForwardError('Error: receive timeout')
         data['status'] = True
         data['content'] = i[-1]
     except ForwardError, e:
         data['errLog'] = str(e)
Exemple #12
0
 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')
Exemple #13
0
 def addUser(self, username, password, admin=False):
     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:
         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.
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #14
0
 def cleanBuffer(self):
     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:
             buff += self.shell.recv(1024)
         except:
             raise ForwardError('Receive timeout [%s]' % (buff))
Exemple #15
0
 def deleteUser(self, username):
     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'])
         if self.isConfigMode:
             # check terminal status
             self.channel.send(
                 """no username  {username}\n""".format(username=username))
             _result = self._recv(self.prompt)
             _tmp = re.search(
                 """This command can be used by user "admin" only""",
                 _result['content'])
             if _tmp:
                 raise ForwardError(_tmp.group())
             elif not _result['status']:
                 raise ForwardError(_result['errLog'])
             if re.search('error|invalid',
                          data['content'],
                          flags=re.IGNORECASE):
                 raise ForwardError(data['content'])
             if _result['status']:
                 data = self._commit()
             else:
                 data = _result
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #16
0
 def _exitConfigMode(self):
     data = {"status": False, "content": "", "errLog": ""}
     try:
         # Check current status
         if self.isConfigMode:
             self.channel.write("exit\n")
             data = self._recv(self.basePrompt)
             if data['status']:
                 self.isConfigMode = False
         else:
             raise ForwardError(
                 'Error: The current state is not configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
Exemple #17
0
 def _exitConfigMode(self):
     exitCommand = "end"
     data = {'status': False, 'content': '', 'errLog': ''}
     try:
         if self.isConfigMode:
             # Check current status
             self.channel.send("%s\n" % (exitCommand))
             data = self._recv(self.basePrompt)
             if data['status']:
                 self.isConfigMode = False
         else:
             raise ForwardError(
                 'Error: The current state is not configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
Exemple #18
0
 def _commit(self):
     data = {"status": False, "content": "", "errLog": ""}
     try:
         if self.isConfigMode:
             self.channel.write('commit\n')
             result = self._recv(self.prompt)
             if re.search('succeeds',
                          result['content'],
                          flags=re.IGNORECASE):
                 data['status'] = True
             else:
                 data['content'] = result['content']
         else:
             raise ForwardError(
                 'Error: The current state is not configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #19
0
 def _recv(self, _prompt):
     data = {'status': False, 'content': '', 'errLog': ''}
     i = self.channel.expect([r"%s" % _prompt, pexpect.TIMEOUT],
                             timeout=self.timeout)
     result = ''
     try:
         if i == 0:
             result = self.channel.before
             # get result
             data['status'] = True
         elif i == 2:
             raise ForwardError('Error: receive timeout')
         else:
             data['errLog'] = self.channel.before
         data['content'] = result
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False
Exemple #20
0
 def _exitConfigMode(self, cmd='end'):
     result = {
         "status": False,
         "content": "",
         "errLog": ""
     }
     try:
         # Check current status
         if self.isConfigMode:
             self.shell.send("%s\n" % (cmd))
             while not re.search(self.basePrompt, result['content'].split('\n')[-1]):
                 result['content'] += self.shell.recv(1024)
             self.isConfigMode = False
             result["status"] = True
         else:
             raise ForwardError('Error: The current state is not configuration mode')
     except ForwardError, e:
         result["status"] = False
         result['errLog'] = str(e)
Exemple #21
0
 def _commit(self, saveCommand='write', exitCommand='end'):
     result = {
         "status": False,
         "content": "",
         "errLog": ""
     }
     try:
         if self.isConfigMode:
             self._exitConfigMode(exitCommand)
             # save setup to system
             self.shell.send('%s\n' % (saveCommand))
             while not re.search(self.prompt, result['content'].split('\n')[-1]):
                 result['content'] += self.shell.recv(1024)
             if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE):
                 result['status'] = True
         else:
             raise ForwardError('[Commit Config Error]: The current state is not configuration mode')
     except ForwardError, e:
         result['errLog'] = str(e)
         result['status'] = False
Exemple #22
0
 def getUser(self, command="show running-config | in username"):
     result = {
         "status": False,
         "content": "",
         "errLog": ""
     }
     try:
         # [{"username":"******","secret":5},{}....]
         userList = []
         # execute query command
         info = self.execute(command)
         if not info["status"]:
             raise ForwardError("Error:get user list failed: %s" % info["errLog"])
         # process result
         result = info["content"]
         for line in result.split('\n'):
             # Each line
             index = 0
             # ['username' , 'test-user' , 'secret', '5','$.........']
             segments = line.split()
             for segment in segments:
                 if index <= 1:
                     index += 1
                     # Check after second fields username my-username secret/password .....
                     continue
                 else:
                     if segment == "secret" or segment == "password":
                         # get secret level
                         userData = {"username": segments[1], "secret": segments[index + 1]}
                         userList.append(userData)
                         break
                 index += 1
         result["content"] = userList
         result["status"] = True
     except ForwardError, e:
         result['status'] = False
         result['errLog'] = str(e)
Exemple #23
0
 def addUser(self, username, password, userLevel=1):
     # user leve default 1
     data = {"status": False,
             "content": "",
             "errLog": ""}
     try:
         if not username or not password:
             # Specify a user name and password parameters here.
             raise ForwardError('Please specify the username = your-username and password = your-password')
         checkPermission = self._configMode(cmd='sys\naaa')
         # swith to config terminal mode.
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         if self.isConfigMode:
             # check terminal status
             self.shell.send('local-user {username} password cipher {password}\n'.format(username=username,
                                                                                         password=password))
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and\
                    (re.search('local-user .* password cipher[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             self.shell.send('local-user {username} privilege level  {userLevel}\n'.format(username=username,
                                                                                           userLevel=userLevel))
             data['content'] = ''
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and\
                    (re.search('local-user .* privilege level[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             self.shell.send("local-user {username} service-type terminal ssh\n".format(username=username))
             data['content'] = ''
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and \
                    (re.search('local-user .* service-type terminal ssh[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             self.shell.send("quit\n")
             data['content'] = ''
             while True:
                 if (re.search(self.basePrompt, data['content'].split('\n')[-1])) and \
                    (re.search('quit.*[\s\S]+%s' % self.basePrompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             self.getPrompt()
             self.shell.send("ssh user {username} authentication-type password\n".format(username=username))
             data['content'] = ''
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and \
                    (re.search('ssh user .* authentication-type password[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             self.shell.send("ssh user {username} service-type all\n".format(username=username))
             data['content'] = ''
             while True:
                 if (re.search(self.prompt, data['content'].split('\n')[-1])) and \
                    (re.search('ssh user .* service-type all[\s\S]+%s' % self.prompt, data['content'])):
                     break
                 else:
                     data['content'] += self.shell.recv(1024)
             data = self._commit()
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['status'] = False
         data['errLog'] = str(e)
Exemple #24
0
    def addUser(self, username, password, **kwargs):
        # Extra parameters
        group = kwargs['group'] if 'group' in kwargs else username
        commandAdduser = '******' % username if group == username else 'adduser --gid %s %s' % (
            group, username)
        commandPw = 'passwd %s\n' % username

        result = {"status": False, "content": "", "errLog": ""}
        try:
            # legal check
            if not group:
                raise ForwardError(
                    "[Add User Error]: %s: Group could NOT be blank." %
                    self.ip)
            if not username or not password:
                raise ForwardError(
                    "[Add User Error]: %s: Username or Password could NOT be blank."
                    % self.ip)

            if self.isLogin:
                # execute adduser
                addUserResult = self.execute(commandAdduser)
                if addUserResult['status']:
                    dirExtPattern = '(目录已经存在|home directory already exists)'

                    if not addUserResult['content']:
                        # success
                        pass
                    elif re.search(dirExtPattern, addUserResult['content']):
                        # success, but homedir already exist
                        pass
                    else:
                        # other errors
                        raise ForwardError("[Add User Error]: %s: %s" %
                                           (self.ip, addUserResult['content']))

                    # set passwd
                    self.shell.send(commandPw)
                    buff = ''
                    while not (re.search(self.basePrompt, buff)
                               or re.search('New password:'******'New password:'******'\n')
                        buff = ''
                        while not (re.search(self.basePrompt, buff)
                                   or re.search('Retype new password:'******'Retype new password:'******'\n')
                            buff = ''
                            while not re.search(self.prompt, buff):
                                buff += self.shell.recv(256)
                            if re.search('updated successfully', buff):
                                result['status'] = True
                                return result

                    # error somewhere, raise
                    raise ForwardError("[Set Password Error]: %s: %s" %
                                       (self.ip, buff))
                else:
                    raise ForwardError("[Add User Error]: %s: %s" %
                                       (self.ip, addUserResult['errLog']))
            else:
                raise ForwardError("[Add User Error]: %s: Not login yet." %
                                   self.ip)
        except ForwardError, e:
            result['status'] = False
            result['errLog'] = str(e)
Exemple #25
0
 def addUser(self, username, password, admin=False):
     if admin:
         command = "set system login user {username} class read-only\n".format(
             username=username)
     else:
         command = "set system login user {username} class  ABC\n".format(
             username=username)
     data = {"status": False, "content": "", "errLog": ""}
     try:
         if not username or not password:
             # Specify a user name and password parameters here.
             raise ForwardError(
                 'Please specify the username = your-username and password = your-password'
             )
         checkPermission = self._configMode(
         )  # swith to config terminal mode.
         if not checkPermission['status']:
             raise ForwardError(checkPermission['errLog'])
         # check terminal status
         if self.isConfigMode:
             # adduser
             self.channel.write(command)
             # recv result
             data = self._recv(self.prompt)
             if not data['status']:
                 # break
                 raise ForwardError(data['errLog'])
             # execute useradd command
             self.channel.write('set system login user {username} \
                                authentication plain-text-password\n'.
                                format(username=username))
             i = self.channel.expect(
                 [r"New password:"******"%s" % self.prompt],
                 timeout=self.timeout)
             result = i[-1]
             if re.search('error|invalid', result, flags=re.IGNORECASE):
                 # command failure
                 raise ForwardError(result)
             # Enter password
             self.channel.write("{password}\n".format(password=password))
             # check password
             i = self.channel.expect(
                 [r"Retype new password:"******"%s" % self.prompt],
                 timeout=self.timeout)
             # repassword
             if i[0] == 0:
                 self.channel.write(
                     "{password}\n".format(password=password))
                 # check password
                 i = self.channel.expect([r"%s" % self.prompt],
                                         timeout=self.timeout)
                 if i[0] == 0:
                     result = i[-1]
                     if re.search('error|invalid',
                                  result,
                                  flags=re.IGNORECASE):
                         raise ForwardError(result)
                     else:
                         # set password is successed.
                         data = self._commit()
                         # exit config terminal mode.
                         self._exitConfigMode()
                 elif i[0] == -1:
                     raise ForwardError('Error: receive timeout')
             elif i[0] == 1:
                 # password wrong
                 raise ForwardError(i[-1])
             elif i[0] == -1:
                 # timeout
                 raise ForwardError('Error: receive timeout')
         else:
             raise ForwardError('Has yet to enter configuration mode')
     except ForwardError, e:
         data['errLog'] = str(e)
         data['status'] = False