How to use the pexpect.spawn 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 openweave / happy / tests / happy / test_07_happy_node_network_shell.py View on Github external
os.system("happy-node-leave node04 network03")
        os.system("happy-node-leave node05 network03")
        os.system("happy-node-leave node06 network03")

        os.system("happy-node-delete node01")
        os.system("happy-node-delete node02")
        os.system("happy-node-delete node03")
        os.system("happy-node-delete node04")
        os.system("happy-node-delete node05")
        os.system("happy-node-delete node06")

        os.system("happy-network-delete network01")
        os.system("happy-network-delete network02")
        os.system("happy-network-delete network03")

        child = pexpect.spawn("happy-state")
        child.expect('   Prefixes\r\n\r\nNODES      Name    Interface    Type                                          IPs\r\n\r\n')
        child.close(force=True)
github pexpect / pexpect / tests / test_expect.py View on Github external
def test_expect_setecho_off(self):
        '''This tests that echo may be toggled off.
        '''
        p = pexpect.spawn('cat', echo=True, timeout=5)
        try:
            self._expect_echo_toggle(p)
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise
github trustedsec / spraywmi / spraywmi.py View on Github external
established. If you do not specify a value, it will automatically create a listener for you.
""")
	print ("Usage: python spraywmi.py        \n\n")
	sys.exit()

print ("[*] Launching SprayWMI on the hosts specified.")

# Start Unicorn first.
if os.path.isfile(unicorn + "/unicorn.py"):
	os.chdir(unicorn)
	print ("[*] Generating shellcode through Unicorn, this could take a few seconds.")
	subprocess.Popen("python unicorn.py %s %s %s" % (meta, lhost, lport), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).wait()
	if optional == "":
		print ("[*] Launching the listener in the background.")	
		time.sleep(1)
		child = pexpect.spawn("msfconsole -r %s/unicorn.rc" % (unicorn))
	        print ("[*] Waiting for the listener to start first before we continue.")
	        print ("[*] Be patient, Metasploit takes a little bit to start.")
	        child.expect("Exploit running", timeout=30000)
	unicorn_code = file(unicorn + "/powershell_attack.txt", "r").read()
	# All back to normal.
	os.chdir(definepath)

# If not found, tell them to check it out.
else:
	print ("Unicorn was not found. Please run git clone https://github.com/trustedsec/unicorn, then edit spraywmi.py and point the unicorn = variable to your Unicorn installation.")
	sys.exit()

if not os.path.isfile(cidr):
	# If we have multiple CIDRs, then split them up for nmap.
	if "," in cidr:
		print ("[*] Multiple CIDR notations found, splitting them up.")
github linuxdynasty / Linuxdynasty / asanabria / Scripts / python / NetworkDeviceManager.py View on Github external
status = 0
    session = "ssh " + login+"@"+host
    command = pexpect.spawn( session, maxread=MAXREAD, searchwindowsize=WINDOWSIZE )
    if term == "ssh" or term == "both":
        if verbose:
            print "connecting to %s using %s" % (host, session)
        try:
            status = command.expect( [NEWSSHKEY, PASS, MODULUS_TO_SMALL, PROTOCOL_DIFFER, LOGIN_PROMPT, EOF, HOST_KEY_FAILED, CONNECTION_REFUSED, RESET_BY_PEER], timeout=tout )
        except:
            status = 10
            return( status, command )
        if status == 2:
            if verbose:
                print "Protocol Version 2 failed with host key to small, Trying to connect to host using ssh Protocol version 1"
            session = "ssh -1 " + login+"@"+host
            command = pexpect.spawn( session, maxread=MAXREAD, searchwindowsize=WINDOWSIZE )
            if verbose:
                print "connecting to %s using %s" % (host, session)
            status = command.expect( [NEWSSHKEY, PASS, MODULUS_TO_SMALL, PROTOCOL_DIFFER,  EOF], timeout=tout )
            if status == 3:
                if verbose:
                    print "Protocol MisMatch"
        if status == 0:
            if verbose:
                print "saying yes to accepting ssh key"
            command.sendline("yes")
            status = command.expect( [PASS, LOGIN_PROMPT, EOF] )
            if status == 0:
                command.sendline( passwd )
                status = command.expect( [USERNAME, PASS, PERMISSION_DENIED, LOGIN_PROMPT, EOF], timeout=tout )
                if status == 0 or status == 1 or status == 2:
                    if verbose:
github alibaba / ansible-provider-docs / lib / ansible / plugins / connection / winrm.py View on Github external
kinit_cmdline.append(principal)

        # pexpect runs the process in its own pty so it can correctly send
        # the password as input even on MacOS which blocks subprocess from
        # doing so. Unfortunately it is not available on the built in Python
        # so we can only use it if someone has installed it
        if HAS_PEXPECT:
            proc_mechanism = "pexpect"
            command = kinit_cmdline.pop(0)
            password = to_text(password, encoding='utf-8',
                               errors='surrogate_or_strict')

            display.vvvv("calling kinit with pexpect for principal %s"
                         % principal)
            try:
                child = pexpect.spawn(command, kinit_cmdline, timeout=60,
                                      env=krb5env, echo=False)
            except pexpect.ExceptionPexpect as err:
                err_msg = "Kerberos auth failure when calling kinit cmd " \
                          "'%s': %s" % (command, to_native(err))
                raise AnsibleConnectionFailure(err_msg)

            try:
                child.expect(".*:")
                child.sendline(password)
            except OSError as err:
                # child exited before the pass was sent, Ansible will raise
                # error based on the rc below, just display the error here
                display.vvvv("kinit with pexpect raised OSError: %s"
                             % to_native(err))

            # technically this is the stdout + stderr but to match the
github fmenabe / python-unix / unix / host.py View on Github external
def expect(self, command, *patterns):
        """Use *expect* from executing **command**. **\*patterns** is a list
        of pair which contain the expected prompt and the value to pass.

        Exemple:
            >>> # Executing 'passwd' command as not root user
            >>> import unix
            >>> localhost = unix.Local()
            >>> localhost.expect(
            >>>     'passwd',
            >>>     ('pass', 'old_password'),   # Ask of the old password
            >>>     ('pass', 'new_password'),   # First ask of the new password
            >>>     ('pass', 'new_password')    # Second ask of the new password
            >>> )
        """
        child = pexpect.spawn(command)
        for (pattern, value) in patterns:
            child.expect(pattern)
            child.sendline(value)
            time.sleep(.1)
        output = "\n".join(
            [line.replace('\r\n', '') for line in child.readlines()[1:]]
        )

        child.close()
        return_code = child.exitstatus
        if return_code != 0:
            return [False, '', output]
        return [True, '', '']
github 0xInfection / TIDoS-Framework / lib / pexpect_mod / examples / ssh_tunnel.py View on Github external
def main ():

    while True:
        ps = pexpect.spawn ('ps')
        time.sleep (1)
        index = ps.expect (['/usr/bin/ssh', pexpect.EOF, pexpect.TIMEOUT])
        if index == 2:
            print('TIMEOUT in ps command...')
            print(str(ps))
            time.sleep (13)
        if index == 1:
            print(time.asctime(), end=' ')
            print('restarting tunnel')
            start_tunnel ()
            time.sleep (11)
            print('tunnel OK')
        else:
            # print 'tunnel OK'
            time.sleep (7)
github apache / tashi / src / zoni / hardware / hpilo.py View on Github external
def __login(self):
		switchIp = "ssh " +  self.host
		child = pexpect.spawn(switchIp)

		if self.verbose:
			child.logfile = sys.stdout

		opt = child.expect(['password:',  pexpect.EOF, pexpect.TIMEOUT])


		#XXX  Doesn't seem to do what I want:(
		child.setecho(False)
		if opt == 0:
			child.sendline(self.password)
			time.sleep(.5)
			i=child.expect(['>', 'please try again.', pexpect.EOF, pexpect.TIMEOUT])
		else:
			mesg = "Error"
			self.log.error(mesg)
github leopck / Yee-Light-Blue / yeelightblue.py View on Github external
def connect(self, mac_str, device_no):
	call(['sudo', 'hciconfig', device_no, 'down'])
	call(['sudo', 'hciconfig', device_no, 'up'])
        call(['sudo', 'hcitool', '-i', device_no, 'lecc', mac_str])
        time.sleep(1)
        self.con = pexpect.spawn('sudo gatttool -i ' + device_no + ' -b ' + mac_str + ' -I')
        self.con.expect('\[LE\]>', timeout=600)
        self.con.sendline('connect')
        self.con.expect('\[LE\]>', timeout=600)
        #pass
github openstack / trove / trove / guestagent / strategies / restore / mysql_impl.py View on Github external
def _start_mysqld_safe_with_init_file(self, init_file, err_log_file):
        # This directory is added and removed by the mysql systemd service
        # as the database is started and stopped. The restore operation
        # takes place when the database is stopped, so the directory does
        # not exist, but it is assumed to exist by the mysqld_safe command
        # which starts the database. This command used to create this
        # directory if it didn't exist, but it was changed recently to
        # simply fail in this case.
        run_dir = "/var/run/mysqld"
        if not os.path.exists(run_dir):
            utils.execute("mkdir", run_dir,
                          run_as_root=True, root_helper="sudo")
            utils.execute("chown", "mysql:mysql", run_dir, err_log_file.name,
                          run_as_root=True, root_helper="sudo")
        child = pexpect.spawn(
            "sudo mysqld_safe --init-file=%s --log-error=%s" %
            (init_file.name, err_log_file.name))
        try:
            index = child.expect(['Starting mysqld daemon'])
            if index == 0:
                LOG.info("Starting MySQL")
        except pexpect.TIMEOUT:
            LOG.exception("Got a timeout launching mysqld_safe")
        finally:
            # There is a race condition here where we kill mysqld before
            # the init file been executed. We need to ensure mysqld is up.
            #
            # mysqld_safe will start even if init-file statement(s) fail.
            # We therefore also check for errors in the log file.
            self.poll_until_then_raise(
                self.mysql_is_running,