How to use the pexpect.ExceptionPexpect function in pexpect

To help you get started, we’ve selected a few pexpect examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / grr / grr / client_builder / grr_response_client_builder / signing.py View on Github external
args = [
        "-certs", self.cert, "-key", self.key, "-n", self.application, "-t",
        "http://timestamp.verisign.com/scripts/timestamp.dll", "-h", "sha1",
        "-in", in_filename, "-out", out_filename
    ]

    try:
      output_log = io.StringIO()
      ossl = pexpect.spawn("osslsigncode", args)
      # Use logfile_read so we don't get the password we're injecting.
      ossl.logfile_read = output_log
      ossl.expect("Enter PEM pass phrase")
      ossl.sendline(self.password)
      ossl.wait()
    except pexpect.ExceptionPexpect:
      output_log.seek(0)
      logging.exception(output_log.read())
      raise

    if not os.path.exists(out_filename):
      raise Error("Expected output %s not created" % out_filename)

    try:
      subprocess.check_call(["osslsigncode", "verify", "-in", out_filename])
    except subprocess.CalledProcessError:
      logging.exception("Bad signature verification on %s", out_filename)
      raise Error("Bad signature verification on %s" % out_filename)

    return out_filename
github xflux-gui / fluxgui / src / fluxgui / xfluxcontroller.py View on Github external
def _start(self, startup_args=None):
        if not startup_args:
            startup_args = self._create_startup_arg_list(self._current_color,
                **self.init_kwargs)
        try:
            previous_instances = pexpect.run('pgrep -d, -u %s xflux' % pexpect.run('whoami')).strip()
            if previous_instances != "":
                for process in previous_instances.split(","):
                    pexpect.run('kill -9 %s' % process)
                   
            self._xflux = pexpect.spawn("xflux", startup_args)
                    #logfile=file("tmp/xfluxout.txt",'w'))

        except pexpect.ExceptionPexpect:
            raise FileNotFoundError(
                    "\nError: Please install xflux in the PATH \n")
github emlid / ReachView / Str2StrController.py View on Github external
def stop(self):
        # terminate the stream

        if self.started:
            self.child.kill(signal.SIGUSR2)
            try:
                self.child.wait()
            except pexpect.ExceptionPexpect:
                print("Str2str already down")

            self.started = False
            return 1

        # str2str already stopped
        return 2
github google / ldpush / asa.py View on Github external
self._connection.child.expect([r'Delete .*\[confirm\]'],
                                      timeout=self.timeout_act_user)
        logging.debug('DeleteFile: answering second confirmation.')
        self._connection.child.send('\r')
      elif pindex == 1:
        raise DeleteFileError('DeleteFile operation failed. %s' %
                              self._connection.child.match)

      pindex = self._connection.child.expect([self._connection.re_prompt,
                                              r'%.*Error.*'],
                                             timeout=self.timeout_act_user)
      if pindex == 1:
        raise DeleteFileError('DeleteFile operation failed. %s' %
                              self._connection.child.match)
      logging.debug('DeleteFile: success.')
    except pexpect.ExceptionPexpect:
      raise DeleteFileError('DeleteFile operation failed. %s' %
                            self._connection.child)
github osrf / rocker / src / rocker / core.py View on Github external
%(image)s %(command)s" % locals()
#   $DOCKER_OPTS \
        if kwargs.get('noexecute', False):
            print("Run this command: \n\n\n")
            print(cmd)
            return 0
        else:
            try:
                print("Executing command: ")
                print(cmd)
                p = pexpect.spawn(cmd)
                with SIGWINCHPassthrough(p):
                    p.interact()
                p.close(force=True)
                return p.exitstatus
            except pexpect.ExceptionPexpect as ex:
                print("Docker run failed\n", ex)
                return 1
github ebellm / ipython-idlmagic / idlmagic.py View on Github external
def __init__(self, shell, gdl=False):
        """
        Parameters
        ----------
        shell : IPython shell

        """
        super(IDLMagics, self).__init__(shell)
        #TODO: allow specifying path, executible on %load_ext
        try:
            self._idl = pidly.IDL()
        except ExceptionPexpect:
            try:
                # NB that pidly returns when it reads the text prompt--needs to 
                # match that of the interpreter!
                self._idl = pidly.IDL('gdl',idl_prompt='GDL>')
                print 'IDL not found, using GDL'
            except ExceptionPexpect:
                raise IDLMagicError('Neither IDL or GDL interpreters found')
        self._plot_format = 'png'

        # Allow publish_display_data to be overridden for
        # testing purposes.
        self._publish_display_data = publish_display_data
github pexpect / pexpect / pexpect / pxssh.py View on Github external
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

'''

from pexpect import ExceptionPexpect, TIMEOUT, EOF, spawn
import time
import os

__all__ = ['ExceptionPxssh', 'pxssh']

# Exception classes used by this module.
class ExceptionPxssh(ExceptionPexpect):
    '''Raised for pxssh exceptions.
    '''

class pxssh (spawn):
    '''This class extends pexpect.spawn to specialize setting up SSH
    connections. This adds methods for login, logout, and expecting the shell
    prompt. It does various tricky things to handle many situations in the SSH
    login process. For example, if the session is your first login, then pxssh
    automatically accepts the remote certificate; or if you have public key
    authentication setup then pxssh won't wait for the password prompt.

    pxssh uses the shell prompt to synchronize output from the remote host. In
    order to make this more robust it sets the shell prompt to something more
    unique than just $ or #. This should work on most Borne/Bash or Csh style
    shells.
github openstack / trove / trove / guestagent / datastore / experimental / couchbase / service.py View on Github external
def set_password(self, root_password):
        self.ip_address = netutils.get_my_ipv4()
        child = pexpect.spawn(system.cmd_reset_pwd % {'IP': self.ip_address})
        try:
            child.expect('.*password.*')
            child.sendline(root_password)
            child.expect('.*(yes/no).*')
            child.sendline('yes')
            child.expect('.*successfully.*')
        except pexpect.TIMEOUT:
            child.delayafterclose = 1
            child.delayafterterminate = 1
            try:
                child.close(force=True)
            except pexpect.ExceptionPexpect:
                # Close fails to terminate a sudo process on some OSes.
                subprocess.call(['sudo', 'kill', str(child.pid)])

        self.write_password_to_file(root_password)
github foglamp / FogLAMP / python / foglamp / plugins / south / common / sensortag_cc2650.py View on Github external
self.con = pexpect.spawn('gatttool -b ' + bluetooth_adr + ' --interactive')
            self.con.expect('\[LE\]>', timeout=int(timeout))

            msg_debug = 'SensorTagCC2650 {} Connecting... If nothing happens, please press the power button.'.\
                        format(self.bluetooth_adr)
            print(msg_debug)
            _LOGGER.debug(msg_debug)

            self.con.sendline('connect')
            self.con.expect('.*Connection successful.*\[LE\]>', timeout=int(timeout))
            self.is_connected = True
            msg_success = 'SensorTagCC2650 {} connected successfully'.format(self.bluetooth_adr)
            print(msg_success)
            _LOGGER.debug(msg_success)
        except (ExceptionPexpect, EOF, TIMEOUT, Exception) as ex:
            self.is_connected = False
            self.con.sendline('quit')
            # TODO: Investigate why SensorTag goes to sleep often and find a suitable software solution to awake it.
            msg_failure = 'SensorTagCC2650 {} connection failure. Timeout={} seconds.'.format(self.bluetooth_adr, timeout)
            print(msg_failure)
            _LOGGER.exception(msg_failure)
github pypa / pipenv / pipenv / vendor / pexpect / pxssh.py View on Github external
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

'''

from pexpect import ExceptionPexpect, TIMEOUT, EOF, spawn
import time
import os
import sys
import re

__all__ = ['ExceptionPxssh', 'pxssh']

# Exception classes used by this module.
class ExceptionPxssh(ExceptionPexpect):
    '''Raised for pxssh exceptions.
    '''

if sys.version_info > (3, 0):
    from shlex import quote
else:
    _find_unsafe = re.compile(r'[^\w@%+=:,./-]').search

    def quote(s):
        """Return a shell-escaped version of the string *s*."""
        if not s:
            return "''"
        if _find_unsafe(s) is None:
            return s

        # use single quotes, and put single quotes into double quotes