Python pexpect.TIMEOUT Examples
The following are 30
code examples of pexpect.TIMEOUT().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pexpect
, or try the search function
.
Example #1
Source File: tunnel.py From Computable with MIT License | 8 votes |
def _try_passwordless_openssh(server, keyfile): """Try passwordless login with shell ssh command.""" if pexpect is None: raise ImportError("pexpect unavailable, use paramiko") cmd = 'ssh -f '+ server if keyfile: cmd += ' -i ' + keyfile cmd += ' exit' p = pexpect.spawn(cmd) while True: try: p.expect('[Pp]assword:', timeout=.1) except pexpect.TIMEOUT: continue except pexpect.EOF: return True else: return False
Example #2
Source File: base.py From omniduct with MIT License | 7 votes |
def _prepare_smartcard(self, name, filename): import pexpect remover = pexpect.spawn('ssh-add -e "{}"'.format(filename)) i = remover.expect(["Card removed:", "Could not remove card", pexpect.TIMEOUT]) if i == 2: raise RuntimeError("Unable to reset card using ssh-agent. Output of ssh-agent was: \n{}\n\n" "Please report this error!".format(remover.before)) adder = pexpect.spawn('ssh-add -s "{}" -t 14400'.format(filename)) i = adder.expect(['Enter passphrase for PKCS#11:', pexpect.TIMEOUT]) if i == 0: adder.sendline(getpass.getpass('Please enter your passcode to unlock your "{}" smartcard: '.format(name))) else: raise RuntimeError("Unable to add card using ssh-agent. Output of ssh-agent was: \n{}\n\n" "Please report this error!".format(remover.before)) i = adder.expect(['Card added:', pexpect.TIMEOUT]) if i != 0: raise RuntimeError("Unexpected error while adding card. Check your passcode and try again.") return True
Example #3
Source File: ssh_connection.py From python-hacker with Apache License 2.0 | 7 votes |
def connect(user, host, password): ssh_newkey = 'Are you sure you want to continue connecting' connStr = 'ssh ' + user + '@' + host child = pexpect.spawn(connStr) ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:']) #超时,返回0 if ret == 0: print '[-] Error Connecting' return if ret == 1: child.sendline('yes') ret = child.expect([pexpect.TIMEOUT, '[P|p]assword:']) if ret == 0: print '[-] Error Connecting' return child.sendline(password) child.expect(PROMPT) return child
Example #4
Source File: delegator.py From pipenv with MIT License | 6 votes |
def _pexpect_out(self): if self.subprocess.encoding: result = "" else: result = b"" if self.subprocess.before: result += self.subprocess.before if self.subprocess.after and self.subprocess.after not in (pexpect.EOF, pexpect.TIMEOUT): try: result += self.subprocess.after except (pexpect.EOF, pexpect.TIMEOUT): pass result += self.subprocess.read() return result
Example #5
Source File: __init__.py From camr with GNU General Public License v2.0 | 6 votes |
def __init__(self, patterns): '''This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.''' self.eof_index = -1 self.timeout_index = -1 self._searches = [] for n, s in zip(list(range(len(patterns))), patterns): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._searches.append((n, s))
Example #6
Source File: __init__.py From camr with GNU General Public License v2.0 | 6 votes |
def __str__(self): '''This returns a human-readable string that represents the state of the object.''' #ss = [(n, ' %d: re.compile("%s")' % # (n, repr(s.pattern))) for n, s in self._searches] ss = list() for n, s in self._searches: try: ss.append((n, ' %d: re.compile("%s")' % (n, s.pattern))) except UnicodeEncodeError: # for test cases that display __str__ of searches, dont throw # another exception just because stdout is ascii-only, using # repr() ss.append((n, ' %d: re.compile(%r)' % (n, s.pattern))) ss.append((-1, 'searcher_re:')) if self.eof_index >= 0: ss.append((self.eof_index, ' %d: EOF' % self.eof_index)) if self.timeout_index >= 0: ss.append((self.timeout_index, ' %d: TIMEOUT' % self.timeout_index)) ss.sort() ss = list(zip(*ss))[1] return '\n'.join(ss)
Example #7
Source File: hpacucli.py From hardware with Apache License 2.0 | 6 votes |
def _sendline(self, line): '''Internal method to interact with hpacucli. Send a command to the hpacucli, wait for the prompt and returns the output string. ''' if self.debug: print(line) self.process.sendline(line) try: self.process.expect(PROMPT_REGEXP) ret = self.process.before[len(line):] except pexpect.TIMEOUT: ret = 'Error: timeout' parse_error(ret) return ret
Example #8
Source File: _pexpect.py From Computable with MIT License | 6 votes |
def __init__(self, patterns): """This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.""" self.eof_index = -1 self.timeout_index = -1 self._searches = [] for n, s in enumerate(patterns): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._searches.append((n, s))
Example #9
Source File: _pexpect.py From Computable with MIT License | 6 votes |
def __init__(self, strings): """This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types. """ self.eof_index = -1 self.timeout_index = -1 self._strings = [] for n, s in enumerate(strings): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._strings.append((n, s))
Example #10
Source File: _pexpect.py From Computable with MIT License | 6 votes |
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): """This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match.""" if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF): pattern_list = [pattern_list] return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
Example #11
Source File: __init__.py From camr with GNU General Public License v2.0 | 6 votes |
def __init__(self, strings): '''This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types. ''' self.eof_index = -1 self.timeout_index = -1 self._strings = [] for n, s in enumerate(strings): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._strings.append((n, s))
Example #12
Source File: pxssh.py From pipenv-sublime with MIT License | 6 votes |
def prompt(self, timeout=-1): '''Match the next shell prompt. This is little more than a short-cut to the :meth:`~pexpect.spawn.expect` method. Note that if you called :meth:`login` with ``auto_prompt_reset=False``, then before calling :meth:`prompt` you must set the :attr:`PROMPT` attribute to a regex that it will use for matching the prompt. Calling :meth:`prompt` will erase the contents of the :attr:`before` attribute even if no prompt is ever matched. If timeout is not given or it is set to -1 then self.timeout is used. :return: True if the shell prompt was matched, False if the timeout was reached. ''' if timeout == -1: timeout = self.timeout i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout) if i==1: return False return True
Example #13
Source File: pgn.py From pychess with GNU General Public License v3.0 | 6 votes |
def init_scoutfish(self): """ Create/open .scout database index file to help querying using scoutfish from https://github.com/mcostalba/scoutfish """ if scoutfish_path is not None and self.path and self.size > 0: try: if self.progressbar is not None: from gi.repository import GLib GLib.idle_add(self.progressbar.set_text, _("Creating .scout index file...")) self.scoutfish = Scoutfish(engine=(scoutfish_path, )) self.scoutfish.open(self.path) scout_path = os.path.splitext(self.path)[0] + '.scout' if getmtime(self.path) > getmtime(scout_path): self.scoutfish.make() except OSError as err: self.scoutfish = None log.warning("Failed to sart scoutfish. OSError %s %s" % (err.errno, err.strerror)) except pexpect.TIMEOUT: self.scoutfish = None log.warning("scoutfish failed (pexpect.TIMEOUT)") except pexpect.EOF: self.scoutfish = None log.warning("scoutfish failed (pexpect.EOF)")
Example #14
Source File: pexpect.py From smod-1 with GNU General Public License v2.0 | 6 votes |
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): """This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match.""" if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF): pattern_list = [pattern_list] return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
Example #15
Source File: pxssh.py From pipenv with MIT License | 6 votes |
def prompt(self, timeout=-1): '''Match the next shell prompt. This is little more than a short-cut to the :meth:`~pexpect.spawn.expect` method. Note that if you called :meth:`login` with ``auto_prompt_reset=False``, then before calling :meth:`prompt` you must set the :attr:`PROMPT` attribute to a regex that it will use for matching the prompt. Calling :meth:`prompt` will erase the contents of the :attr:`before` attribute even if no prompt is ever matched. If timeout is not given or it is set to -1 then self.timeout is used. :return: True if the shell prompt was matched, False if the timeout was reached. ''' if timeout == -1: timeout = self.timeout i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout) if i==1: return False return True
Example #16
Source File: brocade.py From ldpush with Apache License 2.0 | 6 votes |
def _Cmd(self, command, mode=None): def SendAndWait(command): """Sends a command and waits for a response.""" self._connection.child.send(command+'\r') self._connection.child.expect('\r\n', timeout=self.timeout_response) self._connection.child.expect(self._connection.re_prompt, timeout=self.timeout_response, searchwindowsize=128) return self._connection.child.before.replace('\r\n', os.linesep) _ = mode command = command.replace('?', '') if next((command for prefix in self.verboten_commands if command.startswith(prefix)), False): raise exceptions.CmdError( 'Command %s is not permitted on Brocade devices.' % command) result = '' try: result = SendAndWait(command) except pexpect.TIMEOUT, e: self.connected = False raise exceptions.CmdError('%s: %s' % (e.__class__, str(e)))
Example #17
Source File: brocade.py From ldpush with Apache License 2.0 | 6 votes |
def _Disconnect(self): if hasattr(self, '_connection'): try: self._connection.child.send('exit\r') # Loose prompt RE as prompt changes after first exit. self._connection.child.expect(self._success, timeout=self.timeout_act_user) self._connection.child.send('exit\r') self._connection.child.expect(self._connection.exit_list, timeout=self.timeout_act_user) self.connected = False # EOF is normal for a disconnect. Skip DisconnectError. except (pexpect.EOF), e: self.connected = False except (pexpect.TIMEOUT), e: self.connected = False raise exceptions.DisconnectError('%s: %s' % (e.__class__, str(e)))
Example #18
Source File: pexpect.py From smod-1 with GNU General Public License v2.0 | 6 votes |
def __init__(self, strings): """This creates an instance of searcher_string. This argument 'strings' may be a list; a sequence of strings; or the EOF or TIMEOUT types. """ self.eof_index = -1 self.timeout_index = -1 self._strings = [] for n, s in zip(range(len(strings)), strings): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._strings.append((n, s))
Example #19
Source File: pexpect.py From smod-1 with GNU General Public License v2.0 | 6 votes |
def __init__(self, patterns): """This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.""" self.eof_index = -1 self.timeout_index = -1 self._searches = [] for n, s in zip(range(len(patterns)), patterns): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._searches.append((n, s))
Example #20
Source File: pexpect_connection.py From ldpush with Apache License 2.0 | 6 votes |
def read_nonblocking(self, size=1, timeout=None): """See parent. This actually may or may not block based on timeout.""" if not self.isalive(): raise pexpect.EOF('End Of File (EOF) in read() - Not alive.') if timeout == -1: timeout = self.timeout self.channel.settimeout(timeout) try: s = self.channel.recv(size) except socket.timeout: raise pexpect.TIMEOUT('Timeout (%s) exceeded in read().' % timeout) except paramiko.SSHException as e: raise pexpect.EOF('Paramiko exception: %s' % e) except EOFError: raise pexpect.EOF('Paramiko reported End Of File (EOF) in read()') if not s: self.flag_eof = 1 raise pexpect.EOF('End Of File (EOF) in read().') return s
Example #21
Source File: pxssh.py From camr with GNU General Public License v2.0 | 5 votes |
def sync_original_prompt (self, sync_multiplier=1.0): '''This attempts to find the prompt. Basically, press enter and record the response; press enter again and record the response; if the two responses are similar then assume we are at the original prompt. This can be a slow function. Worst case with the default sync_multiplier can take 12 seconds. Low latency connections are more likely to fail with a low sync_multiplier. Best case sync time gets worse with a high sync multiplier (500 ms with default). ''' # All of these timing pace values are magic. # I came up with these based on what seemed reliable for # connecting to a heavily loaded machine I have. self.sendline() time.sleep(0.1) try: # Clear the buffer before getting the prompt. self.try_read_prompt(sync_multiplier) except TIMEOUT: pass self.sendline() x = self.try_read_prompt(sync_multiplier) self.sendline() a = self.try_read_prompt(sync_multiplier) self.sendline() b = self.try_read_prompt(sync_multiplier) ld = self.levenshtein_distance(a,b) len_a = len(a) if len_a == 0: return False if float(ld)/len_a < 0.4: return True return False ### TODO: This is getting messy and I'm pretty sure this isn't perfect. ### TODO: I need to draw a flow chart for this.
Example #22
Source File: pxssh.py From camr with GNU General Public License v2.0 | 5 votes |
def set_unique_prompt(self): '''This sets the remote prompt to something more unique than ``#`` or ``$``. This makes it easier for the :meth:`prompt` method to match the shell prompt unambiguously. This method is called automatically by the :meth:`login` method, but you may want to call it manually if you somehow reset the shell prompt. For example, if you 'su' to a different user then you will need to manually reset the prompt. This sends shell commands to the remote host to set the prompt, so this assumes the remote host is ready to receive commands. Alternatively, you may use your own prompt pattern. In this case you should call :meth:`login` with ``auto_prompt_reset=False``; then set the :attr:`PROMPT` attribute to a regular expression. After that, the :meth:`prompt` method will try to match your prompt pattern. ''' self.sendline("unset PROMPT_COMMAND") self.sendline(self.PROMPT_SET_SH) # sh-style i = self.expect ([TIMEOUT, self.PROMPT], timeout=10) if i == 0: # csh-style self.sendline(self.PROMPT_SET_CSH) i = self.expect([TIMEOUT, self.PROMPT], timeout=10) if i == 0: return False return True # vi:ts=4:sw=4:expandtab:ft=python:
Example #23
Source File: stata_session.py From stata_kernel with GNU General Public License v3.0 | 5 votes |
def init_console(self): """Start Stata in console mode Spawn stata console and then wait/scroll to initial dot prompt. It tries to find the dot prompt immediately; otherwise it assumes there's a `more` stopping it, and presses `q` until the more has gone away. """ self.child = pexpect.spawn( config.get('stata_path'), encoding='utf-8', codec_errors='replace') self.child.delaybeforesend = None self.child.logfile = ( config.get('cache_dir') / 'console_debug.log').open( 'w', encoding='utf-8') banner = [] try: self.child.expect(self.prompt, timeout=0.2) banner.append(self.child.before) except pexpect.TIMEOUT: try: while True: self.child.expect('more', timeout=0.1) banner.append(self.child.before) self.child.send('q') except pexpect.TIMEOUT: self.child.expect(self.prompt) banner.append(self.child.before) # Set banner to Stata's shell header self.banner += ansi_escape.sub('', '\n'.join(banner)) self.banner = re.sub(r'\r\n', '\n', self.banner)
Example #24
Source File: hp.py From ldpush with Apache License 2.0 | 5 votes |
def _Cmd(self, command, mode=None, called_already=False): _ = mode # Strip question marks and short-circuit if we have nothing more. command = command.replace('?', '') if not command: return '' try: self._connection.child.send(command+'\r') self._connection.child.expect(command+'\n') result = '' while True: i = self._connection.child.expect([self._connection.re_prompt, self.RE_PAGER], timeout=self.timeout_response, searchwindowsize=128) # HP prefers \n\r to \r\n. result += self._connection.child.before.replace('\n\r', os.linesep) if i == 1: self._connection.child.send(' ') else: break # Check if the device told us our command was not recognized. if self.RE_INVALID.search(result) is not None: raise exceptions.CmdError('Command %r invalid on %s(%s)' % (command, self.host, self.loopback_ipv4)) return result except pexpect.TIMEOUT, e: self.connected = False raise exceptions.CmdError('%s: %s' % (e.__class__, str(e)))
Example #25
Source File: pxssh.py From camr with GNU General Public License v2.0 | 5 votes |
def try_read_prompt(self, timeout_multiplier): '''This facilitates using communication timeouts to perform synchronization as quickly as possible, while supporting high latency connections with a tunable worst case performance. Fast connections should be read almost immediately. Worst case performance for this method is timeout_multiplier * 3 seconds. ''' # maximum time allowed to read the first response first_char_timeout = timeout_multiplier * 0.5 # maximum time allowed between subsequent characters inter_char_timeout = timeout_multiplier * 0.1 # maximum time for reading the entire prompt total_timeout = timeout_multiplier * 3.0 prompt = b'' begin = time.time() expired = 0.0 timeout = first_char_timeout while expired < total_timeout: try: prompt += self.read_nonblocking(size=1, timeout=timeout) expired = time.time() - begin # updated total time expired timeout = inter_char_timeout except TIMEOUT: break return prompt
Example #26
Source File: winpexpect.py From camr with GNU General Public License v2.0 | 5 votes |
def read_nonblocking(self, size=1, timeout=-1): """INTERNAL: Non blocking read.""" if len(self.chunk_buffer): return self.chunk_buffer.read(size) if self.stdout_eof and self.stderr_eof: assert self.child_output.qsize() == 0 return '' if timeout == -1: timeout = self.timeout try: handle, status, data = self.child_output.get(timeout=timeout) except Empty: raise TIMEOUT, 'Timeout exceeded in read_nonblocking().' if status == 'data': self.chunk_buffer.add(data) elif status == 'eof': self._set_eof(handle) raise EOF, 'End of file in read_nonblocking().' elif status == 'error': self._set_eof(handle) raise OSError, data buf = self.chunk_buffer.read(size) if self.logfile is not None: self.logfile.write(buf) self.logfile.flush() if self.logfile_read is not None: self.logfile_read.write(buf) self.logfile_read.flush() return buf
Example #27
Source File: winpexpect.py From camr with GNU General Public License v2.0 | 5 votes |
def wait(self, timeout=None): """Wait until the child exits. If timeout is not specified this blocks indefinately. Otherwise, timeout specifies the number of seconds to wait.""" if self.exitstatus is not None: return if timeout is None: timeout = INFINITE else: timeout = 1000 * timeout ret = WaitForSingleObject(self.child_handle, timeout) if ret == WAIT_TIMEOUT: raise TIMEOUT, 'Timeout exceeded in wait().' self.exitstatus = GetExitCodeProcess(self.child_handle) return self.exitstatus
Example #28
Source File: pgn.py From pychess with GNU General Public License v3.0 | 5 votes |
def init_chess_db(self): """ Create/open polyglot .bin file with extra win/loss/draw stats using chess_db parser from https://github.com/mcostalba/chess_db """ if chess_db_path is not None and self.path and self.size > 0: try: if self.progressbar is not None: from gi.repository import GLib GLib.idle_add(self.progressbar.set_text, _("Creating .bin index file...")) self.chess_db = Parser(engine=(chess_db_path, )) self.chess_db.open(self.path) bin_path = os.path.splitext(self.path)[0] + '.bin' if not os.path.isfile(bin_path): log.debug("No valid games found in %s" % self.path) self.chess_db = None elif getmtime(self.path) > getmtime(bin_path): self.chess_db.make() except OSError as err: self.chess_db = None log.warning("Failed to sart chess_db parser. OSError %s %s" % (err.errno, err.strerror)) except pexpect.TIMEOUT: self.chess_db = None log.warning("chess_db parser failed (pexpect.TIMEOUT)") except pexpect.EOF: self.chess_db = None log.warning("chess_db parser failed (pexpect.EOF)")
Example #29
Source File: tunnel.py From pySINDy with MIT License | 5 votes |
def _try_passwordless_openssh(server, keyfile): """Try passwordless login with shell ssh command.""" if pexpect is None: raise ImportError("pexpect unavailable, use paramiko") cmd = 'ssh -f '+ server if keyfile: cmd += ' -i ' + keyfile cmd += ' exit' # pop SSH_ASKPASS from env env = os.environ.copy() env.pop('SSH_ASKPASS', None) ssh_newkey = 'Are you sure you want to continue connecting' p = pexpect.spawn(cmd, env=env) while True: try: i = p.expect([ssh_newkey, _password_pat], timeout=.1) if i==0: raise SSHException('The authenticity of the host can\'t be established.') except pexpect.TIMEOUT: continue except pexpect.EOF: return True else: return False
Example #30
Source File: asa.py From ldpush with Apache License 2.0 | 5 votes |
def _Disconnect(self): if hasattr(self, '_connection'): try: self._connection.child.send('exit\r') self._connection.child.expect(self._connection.exit_list, timeout=self.timeout_act_user) self.connected = False except (pexpect.EOF, pexpect.TIMEOUT) as e: self.connected = False raise exceptions.DisconnectError('%s: %s' % (e.__class__, str(e)))