示例#1
0
 def login(self):
     logger = logging.getLogger("protocols")
     try:
         match = self.terminal.expect(
             ['[Ll]ogin:', '[Pp]assword:', self.prompt])
     except pexpect.TIMEOUT:
         raise exceptions.NetworkException(
             "Time-out while connecting to host ('telnet %s %d')" %
             (self.hostname, self.port))
     if match == 0:  # Login prompt
         try:
             self.terminal.sendline(self.username)
             match = 1 + self.terminal.expect(['[Pp]assword:', self.prompt])
         except pexpect.TIMEOUT:
             raise exceptions.MalformedIO(
                 "Unexpected time-out while waiting for prompt from %s" %
                 (self.hostname))
     if match == 1:  # Password prompt
         try:
             self.terminal.sendline(self.password)
             match = 1 + self.terminal.expect(
                 ['Permission denied', self.prompt])
             if match == 1:  # permission denied
                 if self.password:
                     raise exceptions.NetworkException(
                         "Password failed when connecting to %s@%s" %
                         (self.username, self.hostname))
                 else:
                     raise exceptions.NetworkException(
                         "No password given for %s@%s. Unable to connect" %
                         (self.username, self.hostname))
         except pexpect.TIMEOUT, pexpect.EOF:
             raise exceptions.MalformedIO(
                 "Unexpected time-out (>%d sec) while authenticating to %s"
                 % (self.timeout, self.hostname))
示例#2
0
 def login(self):
     logger = logging.getLogger("protocols")
     try:
         match = self.terminal.expect([
             'The authenticity of host .* can\'t be established',
             '[Pp]assword:', self.prompt
         ])
     except pexpect.TIMEOUT:
         raise exceptions.NetworkException(
             "Time-out (>%d sec) while connecting to host ('ssh %s@%s')" %
             (self.timeout, self.username, self.hostname))
     if match == 0:  # 'The authenticity of host .* can\'t be established'
         try:
             self.terminal.expect(
                 'Are you sure you want to continue connecting')
             self.terminal.sendline('yes')
         except pexpect.TIMEOUT, pexpect.EOF:
             raise exceptions.MalformedIO(
                 "Authenticity of host %s can't be established. Expected question, but got time-out"
                 % (self.hostname))
         try:
             match = 1 + self.terminal.expect(['[Pp]assword:', self.prompt])
         except pexpect.TIMEOUT, pexpect.EOF:
             raise exceptions.MalformedIO(
                 "Unexpected time-out (>%d sec) while waiting for prompt from %s"
                 % (self.timeout, self.hostname))
示例#3
0
文件: emulate.py 项目: vanceinc/Pynt
 def sendcommand(self, string):
     # IF SYNCHRONOUS
     if len(self.responses) > 0:
         raise exceptions.NetworkException(
             "Can't send another command as long as response of previous command is not read"
         )
     # END IF
     self.writetolog(string, input=True)
     self.logger.debug("Sending command %s" % (repr(string)))
     string = string.strip()
     if string in self.commands:
         self.acquireMemLock()
         self.responses.append(self.commands[string])
         self.releaseMemLock()
     else:
         raise exceptions.NetworkException(
             "Command '%s' not found in log file %s." %
             (string, self.filename))
示例#4
0
 def connect(self):
     """Extremely simple connect procedure; you should override this"""
     try:
         self.terminal = pexpect.spawn('telnet "%s"' % (self.hostname))
         self.terminal.timeout = int(self.timeout)
     except pexpect.ExceptionPexpect:
         raise exceptions.NetworkException(
             "Problem spawning a new process ('telnet %s %d')" %
             (self.hostname, self.port))
示例#5
0
文件: emulate.py 项目: vanceinc/Pynt
 def connect(self):
     """Read log file, and parses it. Store the command, result pairs in self.commands"""
     try:
         io = file(self.filename, 'r')
     except (IOError, OSError):
         raise exceptions.NetworkException("Problem opening to file %s" %
                                           (self.filename))
     contents = io.read()
     io.close()
     # Emulate a TTY: all line delimeters are \r\n.
     # ugly, but fast: replace \n with \r\n, only if the 'n wasn't already part of \r\n
     contents = contents.replace("\n", "\r\n").replace("\r\r\n", "\r\n")
     delimiter = re.compile(self.delimiter)
     contents = delimiter.split(contents)
     # The first match may be a simple prompt, as opposed to be a delimiter.
     # TODO: handle empty prompt
     promptdelimiter = re.compile(self.prompt)
     firstmatch = promptdelimiter.split(contents[0], 1)  # maxsplit=1
     if len(firstmatch) > 1:
         #self.logger.debug("deleting first part %s" % (repr(firstmatch[0])))
         contents[0] = firstmatch[
             1]  # remove everything before first prompt
     else:
         #self.logger.debug("no %s in first part; deleting %s" % (repr(self.prompt), contents[0]))
         del contents[0]  # remove everything before first delimiter/prompt
     lastmatch = contents[-1].split(self.terminator, 1)  # maxsplit=1
     if len(lastmatch) > 1:
         #self.logger.debug("deleting last part %s" % (repr(lastmatch[1])))
         contents[-1] = lastmatch[0]
     else:
         #self.logger.debug("no %s in last part; deleting %s" % (repr(self.terminator), repr(contents[-1])))
         del contents[-1]
     for commandresponse in contents:
         commandresponse = commandresponse.split("\r\n", 1)  # maxsplit = 1
         command = commandresponse[0].strip()
         if len(command) == 0:
             continue
         (identifier, command) = self.makeCommand(command)
         command = command.strip()
         # Note: previous code returned "False" as identifier in case command string could not be parsed.
         # That is bad practice.
         assert (
             identifier != False
         )  # makeCommand should simply raise an exception, instead of passing False in the identifier.
         #if identifier == False:  # False means the command is invalid; None means all is well, but there is no identifier.
         #    self.logger.debug("skip command '%s': invalid format" % (command))
         #    continue
         # TODO: remove 6 lines of obsolete code and comments above.
         if len(commandresponse) == 2:
             response = commandresponse[1]
         else:
             response = ""
         self.logger.debug("caching command '%s': %d bytes" %
                           (command, len(response)))
         self.commands[command] = response
     self.logger.debug("cached %d commands" % len(self.commands))
示例#6
0
def send_request(method: str,
                 url: str,
                 params=None,
                 data=None,
                 cookies=None,
                 headers=None,
                 data_type: str = "form",
                 **kwargs):
    if params is None:
        params = {}
    if data is None:
        data = {}
    if cookies is None:
        cookies = {}
    if headers is None:
        headers = copy.deepcopy(DEFAULT_HEADERS)
    if data_type.lower() == "json":
        headers['Content-Type'] = "application/json"
    st = {
        "url": url,
        "params": params,
        "headers": headers,
        "verify": request_settings["use_https"],
        "data": data,
        "proxies": request_settings["proxies"],
        "cookies": cookies
    }
    st.update(kwargs)

    req = requests.request(method, **st)
    if req.ok:
        content = req.content.decode("utf8")
        if req.headers.get("content-length") == 0:
            return None
        if 'jsonp' in params and 'callback' in params:
            con = json.loads(re.match(".*?({.*}).*", content, re.S).group(1))
        else:
            con = json.loads(content)
        if con["code"] != 0:
            if "message" in con:
                msg = con["message"]
            elif "msg" in con:
                msg = con["msg"]
            else:
                msg = "请求失败,服务器未返回失败原因"
            raise exceptions.BilibiliException(con["code"], msg)
        else:
            if 'data' in con.keys():
                return con['data']
            else:
                if 'result' in con.keys():
                    return con["result"]
                else:
                    return None
    else:
        raise exceptions.NetworkException(req.status_code)
示例#7
0
文件: tl1.py 项目: vanceinc/Pynt
 def authorize(self):
     command = "act-user::%s:ctag::%s;" % (self.username, self.password)
     try:
         resultlines = self.send_and_receive(command, self.timeout)
     except exceptions.CommandFailed:
         # disconnect, but not logout: handled upstream
         # self.disconnect()
         raise exceptions.NetworkException(
             "Password failed when connecting to %s@%s" %
             (self.username, self.hostname))
示例#8
0
文件: tl1.py 项目: vanceinc/Pynt
 def connect(self):
     try:
         self.terminal = telnetlib.Telnet(self.hostname, self.port)
     except socket.error:
         raise exceptions.NetworkException(
             "Problem connecting to host ('telnet %s %d')" %
             (self.hostname, self.port))
     # Clear input log. The Glimmerglass gives garbage a short while after the connection is established.
     # [62;1"p >        [?4l [?5l [?7h [?8h [1;50r [50;1H [50;0H [4l <--- garbage
     time.sleep(0.01)
     self.writetolog(self.terminal.read_very_eager(), input=True)
 def inner(*args, **kwargs):
     num_tries:int = 0
     function_name:str = func.__name__
     while num_tries < max_tries:
         try:
             return func(*args, **kwargs)
         except Exception:
             op.log_error(f"Decorator error --> {function_name}")
             num_tries = num_tries + 1
             time.sleep(WAIT_TIME)
     raise exceptions.NetworkException(f"Could not retrieve data from function {function_name} "
                                       f"values with {max_tries} re-tries")
示例#10
0
 def connect(self):
     try:
         if not self.username:
             raise AttributeError(
                 "username is not set for %s. Please call setLoginCredentials() before getSubject()."
                 % self.hostname)
         self.terminal = pexpect.spawn(
             'ssh -p %d %s@%s' % (self.port, self.username, self.hostname))
         self.terminal.timeout = int(self.timeout)
     except pexpect.ExceptionPexpect:
         raise exceptions.NetworkException(
             "Problem spawning a new process ('ssh %s@%s')" %
             (self.username, self.hostname))
示例#11
0
文件: emulate.py 项目: vanceinc/Pynt
 def readmessage(self, timeout):
     """Returns """
     # IF SYNCHRONOUS
     if len(self.responses) == 0:
         raise exceptions.NetworkException(
             "Can't retrieve response, since no command was send")
     # ELSE
     # wait till len(self.responses) > 0. not implemented here.
     # END IF
     self.acquireMemLock()
     # "Pop" from the beginning of the responses array
     result = self.responses[0]
     del self.responses[0]
     self.releaseMemLock()
     self.writetolog(result, output=True)
     self.logger.debug("Received %d bytes of data" % len(result))
     return result
示例#12
0
             % (self.hostname))
     try:
         match = 1 + self.terminal.expect(['[Pp]assword:', self.prompt])
     except pexpect.TIMEOUT, pexpect.EOF:
         raise exceptions.MalformedIO(
             "Unexpected time-out (>%d sec) while waiting for prompt from %s"
             % (self.timeout, self.hostname))
 if match == 1:  # Password prompt
     try:
         self.terminal.sendline(self.password)
         match = 1 + self.terminal.expect(
             ['Permission denied', self.prompt])
         if match == 1:  # permission denied
             if self.password:
                 raise exceptions.NetworkException(
                     "Password failed when connecting to %s@%s" %
                     (self.username, self.hostname))
             else:
                 raise exceptions.NetworkException(
                     "No password given for %s@%s. Unable to connect" %
                     (self.username, self.hostname))
     except pexpect.TIMEOUT, pexpect.EOF:
         raise exceptions.MalformedIO(
             "Unexpected time-out (>%d sec) while authenticating to %s"
             % (self.timeout, self.hostname))
 if match != 2:  # haven't gotten a prompt yet
     try:
         self.terminal.expect(self.prompt)
     except pexpect.TIMEOUT, pexpect.EOF:
         raise exceptions.MalformedIO(
             "Unexpected time-out (>%d sec) while waiting for prompt from %s"