def getIPv4Interfaces():
    cmd = "netsh interface ip show config"
    session = PopenSpawn(cmd)
    output = session.read(200000)
    lines = output.splitlines()
    intname = None
    intjson = {}
    outputjson = {}
    for line in lines:
        line = line.decode("utf-8")
        splited = line.split(': ')
        if "Configuration for interface " in line:
            intname = line.split("Configuration for interface ")[-1].replace(
                '"', "")
            # print('Found ' + intname)
            intjson = {}
            continue
        elif "" == line:
            if intname is not None:
                outputjson.update({intname: intjson})
            intname = None
            intjson = {}
            continue

        if intname:
            intjson.update({splited[0].strip(): splited[-1].strip()})

    return outputjson
示例#2
0
    def run(self, block=True, binary=False, cwd=None, env=None):
        """Runs the given command, with or without pexpect functionality enabled."""
        self.blocking = block

        # Use subprocess.
        if self.blocking:
            popen_kwargs = self._default_popen_kwargs.copy()
            popen_kwargs["universal_newlines"] = not binary
            if cwd:
                popen_kwargs["cwd"] = cwd
            if env:
                popen_kwargs["env"].update(env)
            s = subprocess.Popen(self._popen_args, **popen_kwargs)
        # Otherwise, use pexpect.
        else:
            pexpect_kwargs = self._default_pexpect_kwargs.copy()
            if binary:
                pexpect_kwargs["encoding"] = None
            if cwd:
                pexpect_kwargs["cwd"] = cwd
            if env:
                pexpect_kwargs["env"].update(env)
            # Enable Python subprocesses to work with expect functionality.
            pexpect_kwargs["env"]["PYTHONUNBUFFERED"] = "1"
            s = PopenSpawn(self._popen_args, **pexpect_kwargs)
        self.subprocess = s
        self.was_run = True
示例#3
0
    def __init__(self, args, no_output=False):

        if opt.direct_exec:
            msg('')
            from subprocess import run, DEVNULL
            run([args[0]] + args[1:],
                check=True,
                stdout=DEVNULL if no_output else None)
        else:
            timeout = int(opt.pexpect_timeout or 0) or (60, 5)[bool(
                opt.debug_pexpect)]
            if opt.pexpect_spawn:
                self.p = pexpect.spawn(args[0],
                                       args[1:],
                                       encoding='utf8',
                                       timeout=timeout)
                self.p.delaybeforesend = 0
            else:
                self.p = PopenSpawn(args, encoding='utf8', timeout=timeout)
#				self.p.delaybeforesend = 0 # TODO: try this here too

            if opt.exact_output: self.p.logfile = sys.stdout

        self.req_exit_val = 0
        self.skip_ok = False
        self.sent_value = None
示例#4
0
    def __init__(self, args, no_output=False):

        if opt.direct_exec:
            msg('')
            from subprocess import call, check_output
            f = (call, check_output)[bool(no_output)]
            ret = f([args[0]] + args[1:])
            if f == call and ret != 0:
                die(
                    1,
                    red('ERROR: process returned a non-zero exit status ({})'.
                        format(ret)))
        else:
            if opt.pexpect_spawn:
                self.p = pexpect.spawn(args[0], args[1:], encoding='utf8')
                self.p.delaybeforesend = 0
            else:
                self.p = PopenSpawn(args, encoding='utf8')
#				self.p.delaybeforesend = 0 # TODO: try this here too

            if opt.exact_output: self.p.logfile = sys.stdout

        self.req_exit_val = 0
        self.skip_ok = False
        self.timeout = int(opt.pexpect_timeout or 0) or (60, 5)[bool(
            opt.debug_pexpect)]
        self.sent_value = None
示例#5
0
 def __init__(self, engine=''):
     if not engine:
         engine = './scoutfish'
     self.p = PopenSpawn(engine, timeout=TIME_OUT_SECOND, encoding="utf-8")
     self.wait_ready()
     self.pgn = ''
     self.db = ''
示例#6
0
 def __init__(self, engine=''):
     if not engine:
         engine = './parser'
     self.engine = engine
     self.p = PopenSpawn(engine, encoding="utf-8")
     self.pgn = ''
     self.db = ''
示例#7
0
    def __init__(self, timeout, debug=False):
        'Initialize the SerAPI subprocess'
        self.debug = debug
        try:
            self.proc = PopenSpawn('sertop --implicit --omit_loc --print0',
                                   encoding='utf-8',
                                   timeout=timeout,
                                   maxread=10000000)
        except FileNotFoundError:
            log(
                'Please make sure the "sertop" program is in the PATH.\nYou may have to run "eval $(opam env)".',
                'ERROR')
            sys.exit(1)
        self.proc.expect_exact(
            '(Feedback((doc_id 0)(span_id 1)(route 0)(contents Processed)))\0')
        self.send('Noop')
        self.states_stack = []

        # global printing options
        self.execute('Unset Printing Notations.')
        self.execute('Unset Printing Wildcard.')
        self.execute('Set Printing Coercions.')
        self.execute('Unset Printing Allow Match Default Clause.')
        self.execute('Unset Printing Factorizable Match Patterns.')
        self.execute('Unset Printing Compact Contexts.')
        self.execute('Set Printing Implicit.')
        self.execute('Set Printing Depth 999999.')
        self.execute('Unset Printing Records.')

        # initialize the state stack
        self.push()

        self.ast_cache = {}
        self.dead = False
示例#8
0
    def __enter__(self):
        from pexpect.popen_spawn import PopenSpawn

        cwd = os.getcwd()
        env = os.environ.copy()
        env['PATH'] = self.activator.pathsep_join(
            self.activator.path_conversion(
                concatv(
                    self.activator._get_path_dirs(join(cwd, 'shell')),
                    (dirname(sys.executable), ),
                    self.activator._get_starting_path_list(),
                )))
        env['PYTHONPATH'] = CONDA_PACKAGE_ROOT
        env = {str(k): str(v) for k, v in iteritems(env)}

        p = PopenSpawn(self.shell_name,
                       timeout=6,
                       maxread=2000,
                       searchwindowsize=None,
                       logfile=sys.stdout,
                       cwd=cwd,
                       env=env,
                       encoding=None,
                       codec_errors='strict')
        if self.init_command:
            p.sendline(self.init_command)
        self.p = p
        return self
示例#9
0
	def __init__(self,name,mmgen_cmd,cmd_args,desc,no_output=False,passthru_args=[],msg_only=False,no_msg=False):
		cmd_args = ['--{}{}'.format(k.replace('_','-'),
			'='+getattr(opt,k) if getattr(opt,k) != True else ''
			) for k in passthru_args if getattr(opt,k)] \
			+ ['--data-dir='+data_dir] + cmd_args

		if g.platform == 'win': cmd,args = 'python',[mmgen_cmd]+cmd_args
		else:                   cmd,args = mmgen_cmd,cmd_args

		for i in args:
			if type(i) not in (str,unicode):
				m1 = 'Error: missing input files in cmd line?:'
				m2 = '\nName: {}\nCmd: {}\nCmd args: {}'
				die(2,(m1+m2).format(name,cmd,args))

		if opt.popen_spawn:
			args = [u'{q}{}{q}'.format(a,q="'" if ' ' in a else '') for a in args]

		cmd_str = u'{} {}'.format(cmd,u' '.join(args)).replace('\\','/')
		if opt.coverage:
			fs = 'python -m trace --count --coverdir={} --file={} {c}'
			cmd_str = fs.format(*init_coverage(),c=cmd_str)

		if opt.log:
			log_fd.write(cmd_str+'\n')

		if not no_msg:
			if opt.verbose or opt.print_cmdline or opt.exact_output:
				clr1,clr2,eol = ((green,cyan,'\n'),(nocolor,nocolor,' '))[bool(opt.print_cmdline)]
				sys.stderr.write(green('Testing: {}\n'.format(desc)))
				if not msg_only:
					s = repr(cmd_str) if g.platform == 'win' else cmd_str
					sys.stderr.write(clr1(u'Executing {}{}'.format(clr2(s),eol)))
			else:
				m = 'Testing {}: '.format(desc)
				msg_r(m)

		if msg_only: return

		if opt.direct_exec:
			msg('')
			from subprocess import call,check_output
			f = (call,check_output)[bool(no_output)]
			ret = f([cmd] + args)
			if f == call and ret != 0:
				die(1,red('ERROR: process returned a non-zero exit status ({})'.format(ret)))
		else:
			if opt.traceback:
				cmd,args = g.traceback_cmd,[cmd]+args
				cmd_str = g.traceback_cmd + ' ' + cmd_str
#			Msg('\ncmd_str: {}'.format(cmd_str))
			if opt.popen_spawn:
				# PopenSpawn() requires cmd string to be bytes.  However, it autoconverts unicode
				# input to bytes, though this behavior seems to be undocumented.  Setting 'encoding'
				# to 'UTF-8' will cause pexpect to reject non-unicode string input.
				self.p = PopenSpawn(cmd_str.encode('utf8'))
			else:
				self.p = pexpect.spawn(cmd,args)
			if opt.exact_output: self.p.logfile = sys.stdout
示例#10
0
def genarate_key(key_name='debug.keystore', alias='release'):
    """使用keytool生成随机证书

    Returns:
        type: 无

    """
    cmd = ('keytool -genkeypair -keystore {} '
           '-alias {} -validity 3000').format(key_name, alias)
    child = PopenSpawn(cmd)

    result = child.expect('Enter keystore password:'******'Enter keystore password:'******'Re-enter new password:'******'Re-enter new password:'******']:')
    # print('What is your first and last name?\r\n  [Unknown]:')
    child.sendline(random_str())

    child.expect(']:')
    # print('What is the name of your organizational unit?\r\n  [Unknown]:')
    child.sendline(random_str())

    child.expect(']:')
    # print('What is the name of your organization?\r\n  [Unknown]:')
    child.sendline(random_str())

    child.expect(']:')
    # print('What is the name of your City or Locality?\r\n  [Unknown]:')
    child.sendline(random_str())

    child.expect(']:')
    # print('What is the name of your State or Province?\r\n  [Unknown]:')
    child.sendline(random_str())

    child.expect(']:')
    # print('What is the two-letter country code for this unit?\r\n  [Unknown]:')
    child.sendline(random_str())

    child.expect(']:')
    print(child.before[5:-15].decode(), end=' ')
    child.sendline('yes')

    child.expect('Enter key password for')
    # print('Enter key password for <release>\r\n\t(RETURN if same as keystore password):')
    child.sendline(PWD)

    child.expect('password:'******'Re - enter new password:')
    child.sendline(PWD)
    child.wait()

    # print(PWD)

    return (key_name, alias)
示例#11
0
def pingIPv4(host):
    session = PopenSpawn('ping -n 1 ' + str(host))
    output = session.read(2000)
    output = output.decode('utf-8')
    if "100% loss" in output or "timed out" in output or "unreachable" in output:
        return None
    else:
        return str(host)
示例#12
0
def ping(host):
    # For Windows, IPv6 neighbors can be discovered by sending a link-local packet across the whole L2 network.
    # Response time should be <1ms since the toolkit needs to physically be near the nodes.
    session = PopenSpawn('ping -w 1 -n 8 ' + host)
    output = session.read(2000)
    output = output.decode('utf-8')
    print(output)
    return output
示例#13
0
 def test_unexpected_eof(self):
     p = PopenSpawn("ls -l /bin")
     try:
         p.expect("_Z_XY_XZ")  # Probably never see this in ls output.
     except pexpect.EOF:
         pass
     else:
         self.fail("Expected an EOF exception.")
示例#14
0
 def test_unexpected_eof(self):
     p = PopenSpawn('ls -l /bin')
     try:
         p.expect('_Z_XY_XZ')  # Probably never see this in ls output.
     except pexpect.EOF:
         pass
     else:
         self.fail('Expected an EOF exception.')
示例#15
0
文件: pandora.py 项目: Josh0729/Viper
    def start(self,user,password):
#523680852782251507
        try:
            #self.pianobarInstance = pexpect.spawn ('pianobar')
            self.pianobarInstance = PopenSpawn ('cmd')
            #self.pianobarInstance.expect('#   -\d\d:\d\d/\d\d:\d\d')
            self.started = True
        except Exception as e:
            print (e.strerror)
示例#16
0
def spawn(command,
          args=[],
          timeout=30,
          maxread=2000,
          searchwindowsize=None,
          logfile=None,
          cwd=None,
          env=None,
          ignore_sighup=True,
          echo=True,
          encoding='utf-8',
          **kwargs):
    '''This is the main entry point for Pexpect. Use this functio to start
    and control child applications.

    See https://github.com/pexpect/pexpect/blob/master/pexpect/pty_spawn.py
    for more information.
    '''
    codec_errors = kwargs.get('codec_errors', kwargs.get('errors', 'strict'))
    if pty is None:
        command = shlex.split(command, posix=os.name == 'posix')
        command += args
        child = PopenSpawn(command,
                           timeout=timeout,
                           maxread=maxread,
                           searchwindowsize=searchwindowsize,
                           logfile=logfile,
                           cwd=cwd,
                           env=env,
                           encoding=encoding,
                           codec_errors=codec_errors)
        child.echo = echo
    else:
        try:
            # Signal handlers are inherited by forked processes, and we can't easily
            # reset it from the subprocess. Since kernelapp ignores SIGINT except in
            # message handlers, we need to temporarily reset the SIGINT handler here
            # so that the child and its children are interruptible.
            try:
                sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
            except ValueError:
                # Only Main Thread can handle signals
                sig = None
            child = pty_spawn(command,
                              args=args,
                              timeout=timeout,
                              maxread=maxread,
                              searchwindowsize=searchwindowsize,
                              logfile=logfile,
                              cwd=cwd,
                              env=env,
                              encoding=encoding,
                              codec_errors=codec_errors)
        finally:
            if sig:
                signal.signal(signal.SIGINT, sig)
    return child
示例#17
0
    def run_file(self, q):
        outputs = []

        for test in [str(t) for t in q.test_cases]:
            p = PopenSpawn(f"python {self.get_path(q.file)}")
            p.sendline(test)
            outputs.append(str(p.read().decode('utf-8')))

        return outputs
示例#18
0
def getIPv6Neighbors(interface=None):
    # Get Interfaces if interface is None, otherwise program Interface from input
    NICs = []
    if interface is None:
        NICs = getNICInterfaces()
    else:
        NICs.append(str(interface))
    # Send link-local ping to each NIC
    print('Discovering IPv6 devices on the following interfaces:')
    print(NICs)
    # Set and start ping threads
    hosts = []
    if 'win' in sys.platform:
        for NIC in NICs:
            host = 'ff02::1%' + NIC
            hosts.append((host, ))
        pool = multiprocessing.Pool(processes=10)
        pool.starmap(ping, hosts)
        pool.close()
        pool.join()
        # Get IPv6 Neighbors for each NIC
        IPv6Devices = []
        for NIC in NICs:
            print('Getting IPv6 Neighbors for NIC#' + NIC)
            # Get output from netsh command
            session = PopenSpawn('netsh interface ipv6 show neighbors ' + NIC)
            output = session.read(200000)
            # Split output by newlines
            splitline = output.splitlines()
            # Remove lines without ...
            # https://stackoverflow.com/questions/3416401/removing-elements-from-a-list-containing-specific-characters
            splitline = [x for x in splitline if b'fe80::' in x]
            # Create IPv6 Regular Expression
            for line in splitline:
                # Get IPv6 Device from line
                IPv6Device = line[:44].rstrip().decode("utf-8") + '%' + NIC
                print(IPv6Device)
                IPv6Devices.append(IPv6Device)
    # Assume everything else is linux platform
    else:
        IPv6Devices = []
        for NIC in NICs:
            session = pexpect.spawn('ping6 -c 2 ff02::1%' + str(NIC))
            session.wait()
            output = session.read(20000)
            output = output.decode('utf-8')
            output = output.splitlines()
            for line in output:
                if line.startswith("64 bytes from fe80:"):
                    IPv6Devices.append(line.split()[3][:-1] + '%' + str(NIC))

    #return IPv6Devices
    return [
        'fe80::dac4:97ff:feb6:b262%27', 'fe80::dac4:97ff:feb5:ccc7%27',
        'fe80::dac4:97ff:feb6:b276%27'
    ]
示例#19
0
 def test_expect_eof(self):
     the_old_way = subprocess.Popen(
         args=['ls', '-l',
               '/bin'], stdout=subprocess.PIPE).communicate()[0].rstrip()
     p = PopenSpawn('ls -l /bin')
     # This basically tells it to read everything. Same as pexpect.run()
     # function.
     p.expect(pexpect.EOF)
     the_new_way = p.before.rstrip()
     assert the_old_way == the_new_way, len(the_old_way) - len(the_new_way)
示例#20
0
 def test_expect_exact_basic(self):
     p = PopenSpawn('cat', timeout=5)
     p.sendline(b'Hello')
     p.sendline(b'there')
     p.sendline(b'Mr. Python')
     p.expect_exact(b'Hello')
     p.expect_exact(b'there')
     p.expect_exact(b'Mr. Python')
     p.sendeof()
     p.expect_exact(pexpect.EOF)
示例#21
0
    def test_expect_exact(self):
        the_old_way = subprocess.Popen(
            args=['ls', '-l',
                  '/bin'], stdout=subprocess.PIPE).communicate()[0].rstrip()
        p = PopenSpawn('ls -l /bin')
        the_new_way = b''
        while 1:
            i = p.expect_exact([b'\n', pexpect.EOF])
            the_new_way = the_new_way + p.before
            if i == 1:
                break
            the_new_way += b'\n'
        the_new_way = the_new_way.rstrip()

        assert the_old_way == the_new_way, len(the_old_way) - len(the_new_way)
        p = PopenSpawn('echo hello.?world')
        i = p.expect_exact(b'.?')
        self.assertEqual(p.before, b'hello')
        self.assertEqual(p.after, b'.?')
示例#22
0
 def test_bad_arg(self):
     p = PopenSpawn("cat")
     with self.assertRaisesRegexp(TypeError, ".*must be one of"):
         p.expect(1)
     with self.assertRaisesRegexp(TypeError, ".*must be one of"):
         p.expect([1, b"2"])
     with self.assertRaisesRegexp(TypeError, ".*must be one of"):
         p.expect_exact(1)
     with self.assertRaisesRegexp(TypeError, ".*must be one of"):
         p.expect_exact([1, b"2"])
示例#23
0
 def test_bad_arg(self):
     p = PopenSpawn('cat')
     with self.assertRaisesRegexp(TypeError, '.*must be one of'):
         p.expect(1)
     with self.assertRaisesRegexp(TypeError, '.*must be one of'):
         p.expect([1, b'2'])
     with self.assertRaisesRegexp(TypeError, '.*must be one of'):
         p.expect_exact(1)
     with self.assertRaisesRegexp(TypeError, '.*must be one of'):
         p.expect_exact([1, b'2'])
示例#24
0
 def test_expect_exact_basic(self):
     p = PopenSpawn("cat", timeout=5)
     p.sendline(b"Hello")
     p.sendline(b"there")
     p.sendline(b"Mr. Python")
     p.expect_exact(b"Hello")
     p.expect_exact(b"there")
     p.expect_exact(b"Mr. Python")
     p.sendeof()
     p.expect_exact(pexpect.EOF)
示例#25
0
    def test_expect_exact(self):
        the_old_way = (subprocess.Popen(
            args=["ls", "-l",
                  "/bin"], stdout=subprocess.PIPE).communicate()[0].rstrip())
        p = PopenSpawn("ls -l /bin")
        the_new_way = b""
        while 1:
            i = p.expect_exact([b"\n", pexpect.EOF])
            the_new_way = the_new_way + p.before
            if i == 1:
                break
            the_new_way += b"\n"
        the_new_way = the_new_way.rstrip()

        assert the_old_way == the_new_way, len(the_old_way) - len(the_new_way)
        p = PopenSpawn("echo hello.?world")
        i = p.expect_exact(b".?")
        self.assertEqual(p.before, b"hello")
        self.assertEqual(p.after, b".?")
示例#26
0
 def __init__(self, times=5):
     # 执行进程
     self.process = PopenSpawn('cmd', timeout=10)
     # 日志
     self.logFile = open("logfile.txt", 'wb')
     self.process.logfile = self.logFile
     # 功能序列
     self.d = self.reverse_dict()
     self.seq = ('login', 'register')
     # 测试次数
     self.times = times
示例#27
0
	def __init__(self,name,mmgen_cmd,cmd_args,desc,no_output=False,passthru_args=[],msg_only=False):
		cmd_args = ['--{}{}'.format(k.replace('_','-'),
			'='+getattr(opt,k) if getattr(opt,k) != True else ''
			) for k in passthru_args if getattr(opt,k)] \
			+ ['--data-dir='+os.path.join('test','data_dir')] + cmd_args

		if g.platform == 'win': cmd,args = 'python',[mmgen_cmd]+cmd_args
		else:                   cmd,args = mmgen_cmd,cmd_args

		for i in args:
			if type(i) not in (str,unicode):
				m1 = 'Error: missing input files in cmd line?:'
				m2 = '\nName: {}\nCmd: {}\nCmd args: {}'
				die(2,(m1+m2).format(name,cmd,args))

		if opt.popen_spawn:
			args = [(a,"'{}'".format(a))[' ' in a] for a in args]

		cmd_str = '{} {}'.format(cmd,' '.join(args)).replace('\\','/')

		if opt.log:
			log_fd.write(cmd_str+'\n')

		if opt.verbose or opt.print_cmdline or opt.exact_output:
			clr1,clr2,eol = ((green,cyan,'\n'),(nocolor,nocolor,' '))[bool(opt.print_cmdline)]
			sys.stderr.write(green('Testing: {}\n'.format(desc)))
			if not msg_only:
				sys.stderr.write(clr1('Executing {}{}'.format(clr2(cmd_str),eol)))
		else:
			m = 'Testing %s: ' % desc
			msg_r(m)

		if msg_only: return

		if opt.direct_exec:
			msg('')
			from subprocess import call,check_output
			f = (call,check_output)[bool(no_output)]
			ret = f([cmd] + args)
			if f == call and ret != 0:
				m = 'ERROR: process returned a non-zero exit status (%s)'
				die(1,red(m % ret))
		else:
			if opt.traceback:
				cmd,args = g.traceback_cmd,[cmd]+args
				cmd_str = g.traceback_cmd + ' ' + cmd_str
#			Msg('\ncmd_str: {}'.format(cmd_str))
			if opt.popen_spawn:
				self.p = PopenSpawn(cmd_str)
			else:
				self.p = pexpect.spawn(cmd,args)
			if opt.exact_output: self.p.logfile = sys.stdout
示例#28
0
def run_file(f, test):
    p = PopenSpawn(f"python {f}")
    if type(test) == type([]):
        p.send("\n".join(test))
    else:
        p.send(test)
    p.sendeof()

    out = p.read().decode('utf-8')
    if not out:
        return f"No output received from file {f}."

    return out
示例#29
0
def apksigner(jar_path, key_path, alias):
    """使用apksigner签名

    Returns:
        type: None
    """
    cmd = ('apksigner sign --ks {} '
           '--ks-key-alias {} {}').format(key_path, alias, jar_path)
    child = PopenSpawn(cmd)
    result = child.expect('Keystore password for signer #1:')
    child.sendline(PWD)
    child.wait()
    os.remove(key_path)
示例#30
0
    def run(self, block=True):
        """Runs the given command, with or without pexpect functionality enabled."""
        self.blocking = block

        # Use subprocess.
        if self.blocking:
            s = subprocess.Popen(self._popen_args, **self._default_popen_kwargs)

        # Otherwise, use pexpect.
        else:
            s = PopenSpawn(self._popen_args, **self._default_pexpect_kwargs)
        self.subprocess = s
        self.was_run = True