Internal util to run pcap control command
345866
def _pcap_service_control(action, askadmin=True):
    """"""
    command = action + ' ' + pcap_service_name()
    res, code = _exec_cmd(_encapsulate_admin(command) if askadmin else command)
    if code != 0:
        warning(res.decode("utf8", errors="ignore"))
    return (code == 0)
935100
public static void run(String aplicationName, String applicationDisplayName, String applicationVersion, Builder<Pcap, Void> builder) {
        Validate.notIllegalArgument(builder != null,
                new IllegalArgumentException("Pcap builder should be not null."));
        instance.context = new ApplicationContext(aplicationName, applicationDisplayName, applicationVersion, builder);
    }
92899
def main(argv=None):
    
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.remote",
        parents=[make_common_parser()],
        description="Pelix Remote Shell ({} SSL support)".format(
            "with" if ssl is not None else "without"
        ),
    )

    # Remote shell options
    group = parser.add_argument_group("Remote Shell options")
    group.add_argument(
        "-a",
        "--address",
        default="localhost",
        help="The remote shell binding address",
    )
    group.add_argument(
        "-p",
        "--port",
        type=int,
        default=9000,
        help="The remote shell binding port",
    )

    if ssl is not None:
        # Remote Shell TLS options
        group = parser.add_argument_group("TLS Options")
        group.add_argument("--cert", help="Path to the server certificate file")
        group.add_argument(
            "--key",
            help="Path to the server key file "
            "(can be omitted if the key is in the certificate)",
        )
        group.add_argument(
            "--key-password",
            help="Password of the server key."
            "Set to '-' for a password request.",
        )
        group.add_argument(
            "--ca-chain",
            help="Path to the CA chain file to authenticate clients",
        )

    # Local options
    group = parser.add_argument_group("Local options")
    group.add_argument(
        "--no-input",
        action="store_true",
        help="Run without input (for daemon mode)",
    )

    # Parse them
    args = parser.parse_args(argv)

    # Handle arguments
    init = handle_common_arguments(args)

    # Set the initial bundles
    bundles = [
        "pelix.ipopo.core",
        "pelix.shell.core",
        "pelix.shell.ipopo",
        "pelix.shell.remote",
    ]
    bundles.extend(init.bundles)

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        utilities.remove_duplicates(bundles), init.properties
    )
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    # Instantiate a Remote Shell, if necessary
    with use_ipopo(context) as ipopo:
        rshell_name = "remote-shell"
        try:
            ipopo.get_instance_details(rshell_name)
        except ValueError:
            # Component doesn't exist, we can instantiate it.

            if ssl is not None:
                # Copy parsed arguments
                ca_chain = args.ca_chain
                cert = args.cert
                key = args.key

                # Normalize the TLS key file password argument
                if args.key_password == "-":
                    import getpass

                    key_password = getpass.getpass(
                        "Password for {}: ".format(args.key or args.cert)
                    )
                else:
                    key_password = args.key_password
            else:
                # SSL support is missing:
                # Ensure the SSL arguments are defined but set to None
                ca_chain = None
                cert = None
                key = None
                key_password = None

            # Setup the component
            rshell = ipopo.instantiate(
                pelix.shell.FACTORY_REMOTE_SHELL,
                rshell_name,
                {
                    "pelix.shell.address": args.address,
                    "pelix.shell.port": args.port,
                    "pelix.shell.ssl.ca": ca_chain,
                    "pelix.shell.ssl.cert": cert,
                    "pelix.shell.ssl.key": key,
                    "pelix.shell.ssl.key_password": key_password,
                },
            )

            # Avoid loose reference to the password
            del key_password
        else:
            logging.error(
                "A remote shell component (%s) is already "
                "configured. Abandon.",
                rshell_name,
            )
            return 1

    # Prepare a banner
    host, port = rshell.get_access()
    try:
        if args.no_input:
            # No input required: just print the access to the shell
            print("Remote shell bound to:", host, "- port:", port)

            try:
                while not framework.wait_for_stop(1):
                    # Awake from wait every second to let KeyboardInterrupt
                    # exception to raise
                    pass
            except KeyboardInterrupt:
                print("Got Ctrl+C: exiting.")
                return 127
        else:
            # Prepare interpreter variables
            variables = {
                "__name__": "__console__",
                "__doc__": None,
                "__package__": None,
                "framework": framework,
                "context": context,
                "use_ipopo": use_ipopo,
            }

            banner = (
                "{lines}\nPython interpreter with Pelix Remote Shell\n"
                "Remote shell bound to: {host}:{port}\n{lines}\n"
                "Python version: {version}\n".format(
                    lines="-" * 80, version=sys.version, host=host, port=port
                )
            )

            # Run an interpreter
            _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
111180
function PclZip($p_zipname)
  {

    // ----- Tests the zlib
    if (!function_exists('gzopen'))
    {
      die('Abort '.basename(__FILE__).' : Missing zlib extensions');
    }

    // ----- Set the attributes
    $this->zipname = $p_zipname;
    $this->zip_fd = 0;
    $this->magic_quotes_status = -1;

    // ----- Return
    return;
  }
1189175
def read_pcap_from_source(self):
        
        if self._capture_node:
            compute = self._capture_node["node"].compute
            return compute.stream_file(self._project, "tmp/captures/" + self._capture_file_name)
580163
public Map<String, Object> executeCdpCommand(String commandName, Map<String, Object> parameters) {
    Objects.requireNonNull(commandName, "Command name must be set.");
    Objects.requireNonNull(parameters, "Parameters for command must be set.");

    @SuppressWarnings("unchecked")
    Map<String, Object> toReturn = (Map<String, Object>) getExecuteMethod().execute(
        ChromeDriverCommand.EXECUTE_CDP_COMMAND,
        ImmutableMap.of("cmd", commandName, "params", parameters));

    return ImmutableMap.copyOf(toReturn);
  }
97698
def setup_pcap_inputs(self, input_data):
        '''  '''

        # Setup the pcap in the input data for processing by Bro. The input
        # may be either an individual sample or a sample set.
        file_list = []
        if 'sample' in input_data:
            raw_bytes = input_data['sample']['raw_bytes']
            filename = os.path.basename(input_data['sample']['filename'])
            file_list.append({'filename': filename, 'bytes': raw_bytes})
        else:
            for md5 in input_data['sample_set']['md5_list']:
                sample = self.workbench.get_sample(md5)['sample']
                raw_bytes = sample['raw_bytes']
                filename = os.path.basename(sample['filename'])
                file_list.append({'filename': filename, 'bytes': raw_bytes})

        # Write the pcaps to disk and keep the filenames for Bro to process
        for file_info in file_list:
            with open(file_info['filename'], 'wb') as pcap_file:
                pcap_file.write(file_info['bytes'])

        # Return filenames
        return [file_info['filename'] for file_info in file_list]
203771
def run(exe, args, capturestd=False, env=None):
        
        command = [exe] + args
        if env:
            log.info("Executing [custom environment]: %s", " ".join(command))
        else:
            log.info("Executing : %s", " ".join(command))
        start = time.time()

        # Temp files will be automatically deleted on close()
        # If run() throws the garbage collector should call close(), so don't
        # bother with try-finally
        outfile = None
        errfile = None
        if capturestd:
            outfile = tempfile.TemporaryFile()
            errfile = tempfile.TemporaryFile()

        # Use call instead of Popen so that stdin is connected to the console,
        # in case user input is required
        # On Windows shell=True is needed otherwise the modified environment
        # PATH variable is ignored. On Unix this breaks things.
        r = subprocess.call(
            command, env=env, stdout=outfile, stderr=errfile, shell=WINDOWS)

        stdout = None
        stderr = None
        if capturestd:
            outfile.seek(0)
            stdout = outfile.read()
            outfile.close()
            errfile.seek(0)
            stderr = errfile.read()
            errfile.close()

        end = time.time()
        if r != 0:
            log.error("Failed [%.3f s]", end - start)
            raise RunException(
                "Non-zero return code", exe, args, r, stdout, stderr)
        log.info("Completed [%.3f s]", end - start)
        return stdout, stderr
909802
def run(bam, chrom, pos1, pos2, reffa, chr_reffa, parameters):
    """"""

    # check for chr ref
    is_chr_query = chrom.startswith('chr')
    if is_chr_query and chr_reffa is None:
        chr_reffa = reffa

    # check bam ref type
    bam_header = subprocess.check_output("samtools view -H {}".format(bam), shell=True)
    is_chr_bam = bam_header.find('SN:chr') != -1
    if is_chr_bam:
        reffa = chr_reffa
    if not is_chr_query and is_chr_bam:
        chrom = 'chr' + chrom
    if is_chr_query and not is_chr_bam:
        chrom = re.sub(r'^chr', '', chrom)

    posmin = min(pos1, pos2)
    posmax = max(pos1, pos2)
    cmd = "samtools view -bh {bam} {chrom}:{pos1}-{pos2} " \
        "| samtools mpileup {parameters} -f {reffa} -".format(bam=bam, chrom=chrom,
                                                              pos1=posmin, pos2=posmax,
                                                              reffa=reffa, parameters=parameters)
    if pos1 == pos2:
        cmd += " | awk '$2 == {pos}'".format(pos=pos1)
    else:
        cmd += " | tail -n +2 | awk '$2 >= {posmin} && $2 <= {posmax}'".format(posmin=posmin, posmax=posmax)
    sys.stderr.write("Running:\n{}\n".format(cmd))
    child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    stdout, stderr = child.communicate()
    if child.returncode != 0:
        if len(stdout) == 0 and stderr is None:
            warnings.warn("Command:\n{cmd}\n did not exit with zero exit code. "
                          "Possibly no coverage for sample.".format(cmd=cmd))
        else:
            raise(Exception("Command:\n{cmd}\n did not exit with zero exit code. "
                            "Check command.".format(cmd=cmd)))
    else:
        return stdout
1368462
def _pcap_check(cls):
        """"""
        if not conf.use_winpcapy:
            # Winpcap/Npcap isn't installed
            return

        _detect = pcap_service_status()

        def _ask_user():
            if not conf.interactive:
                return False
            msg = "Do you want to start it ? (yes/no) [y]: "
            try:
                # Better IPython compatibility
                import IPython
                return IPython.utils.io.ask_yes_no(msg, default='y')
            except (NameError, ImportError):
                while True:
                    _confir = input(msg)
                    _confir = _confir.lower().strip()
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
                return False
        _error_msg = ("No match between your pcap and windows "
                      "network interfaces found. ")
        if _detect:
            # No action needed
            return
        else:
            warning(
                "Scapy has detected that your pcap service is not running !"
            )
            if not conf.interactive or _ask_user():
                succeed = pcap_service_start(askadmin=conf.interactive)
                if succeed:
                    log_loading.info("Pcap service started !")
                    return
            _error_msg = "Could not start the pcap service ! "
        warning(_error_msg +
                "You probably won't be able to send packets. "
                "Deactivating unneeded interfaces and restarting "
                "Scapy might help. Check your winpcap/npcap installation "
                "and access rights.")
177058
def iprompt(self, out=sys.stdout):
        """"""

        cmds = """
        Commands:
          i -- index: print current iteration index
          p -- pause: interrupt sampling and return to the main console.
                      Sampling can be resumed later with icontinue().
          h -- halt:  stop sampling and truncate trace. Sampling cannot be
                      resumed for this chain.
          b -- bg:    return to the main console. The sampling will still
                      run in a background thread. There is a possibility of
                      malfunction if you interfere with the Sampler's
                      state or the database during sampling. Use this at your
                      own risk.
        """

        print_("""==============
 PyMC console
==============

        PyMC is now sampling. Use the following commands to query or pause the sampler.
        """, file=out)
        print_(cmds, file=out)

        prompt = True
        try:
            while self.status in ['running', 'paused']:
                    # sys.stdout.write('pymc> ')
                if prompt:
                    out.write('pymc > ')
                    out.flush()

                if self._exc_info is not None:
                    a, b, c = self._exc_info
                    reraise(a, b, c)

                cmd = utils.getInput().strip()
                if cmd == 'i':
                    print_(
                        'Current iteration: %i of %i' %
                        (self._current_iter, self._iter), file=out)
                    prompt = True
                elif cmd == 'p':
                    self.status = 'paused'
                    break
                elif cmd == 'h':
                    self.status = 'halt'
                    self._halt()
                    break
                elif cmd == 'b':
                    return
                elif cmd == '\n':
                    prompt = True
                    pass
                elif cmd == '':
                    prompt = False
                else:
                    print_('Unknown command: ', cmd, file=out)
                    print_(cmds, file=out)
                    prompt = True

        except KeyboardInterrupt:
            if not self.status == 'ready':
                self.status = 'halt'
                self._halt()

        if self.status == 'ready':
            print_("Sampling terminated successfully.", file=out)
        else:
            print_('Waiting for current iteration to finish...', file=out)
            while self._sampling_thread.isAlive():
                sleep(.1)
            print_('Exiting interactive prompt...', file=out)
            if self.status == 'paused':
                print_(
                    'Call icontinue method to continue, or call halt method to truncate traces and stop.',
                    file=out)
198361
def cli(ctx, pattern, arguments, safe):
    """"""

    matches = utils.grep_commands(pattern)
    if matches:
        selected = utils.select_command(matches)
        if selected >= 0:
            cmd, desc = matches[selected]
            pcmd = utils.create_pcmd(cmd)
            raw_params, params, defaults = utils.get_params_in_pcmd(pcmd)

            arguments = list(arguments)
            kargs = {}
            for r, p, d in zip(raw_params, params, defaults):
                if arguments:
                    val = arguments.pop(0)
                    click.echo("{}: {}".format(p, val))
                    kargs[r] = val
                elif safe:
                    if d:
                        kargs[r] = d
                else:
                    p_default = d if d else None
                    val = click.prompt("Enter value for '{}'".format(p), default=p_default)
                    kargs[r] = val
            click.echo("\n")

            final_cmd = utils.substitute_pcmd(pcmd, kargs, safe)

            command = "$ {} :: {}".format(final_cmd, desc)
            if click.confirm("Execute\n\t{}\n\n?".format(command), default=True):
                os.system(final_cmd)
    elif matches == []:
        click.echo('No saved commands matches the pattern {}'.format(pattern))
    else:
        click.echo("No commands to run, Add one by 'keep new'. ")
175872
function(psRec,sProcId){
            if(!sProcId){throw new Error("No Proc Id found in data");}
            var iFind,sArgs
            iFind=psRec.CommandLine.indexOf(psRec.Name);
            sArgs = psRec.CommandLine.substring(iFind+psRec.Name.length+1);
            psRecs[sProcId]={
                pid: psRec.ProcessId
               ,ppid: psRec.ParentProcessId
               ,commandPath: psRec.ExecutablePath
               ,command: psRec.Name
               ,args: sArgs
            }
        }
233163
async def runItemCmdr(item, outp=None, **opts):
    '''
    

    '''
    cmdr = await getItemCmdr(item, outp=outp, **opts)
    await cmdr.runCmdLoop()
729531
def run(self):
    """"""

    module = self.distribution.ext_modules[0]

    building_for_windows = self.plat_name in ['win32', 'win-amd64']
    if building_for_windows:
      module.define_macros.append(('_CRT_SECURE_NO_WARNINGS', '1'))
      module.libraries.append('advapi32')

    if self.dynamic_linking:
      module.libraries.append('yara')
    else:
      for source in yara_sources:
        module.sources.append(source)

    build_ext.build_ext.run(self)
801528
def _exec_ipmitool(driver_info, command):
    
    ipmi_cmd = ("ipmitool -H %(address)s"
                " -I lanplus -U %(user)s -P %(passwd)s %(cmd)s"
                % {'address': driver_info['address'],
                   'user': driver_info['username'],
                   'passwd': driver_info['password'],
                   'cmd': command})

    out = None
    try:
        out = subprocess.check_output(ipmi_cmd, shell=True)
    except Exception:
        pass
    return out
1243759
def run_command(self, args=None, node_paths=None):
    """"""
    return command_gen(
      self.tool_installations,
      self.name,
      args=args,
      node_paths=node_paths
    )