Execute the desired powershell command and ensure that it returns data
    in json format and load that into python
771785
def _pshell(cmd, cwd=None, json_depth=2):
    '''
    
    '''
    if 'convertto-json' not in cmd.lower():
        cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)
    log.debug('DSC: %s', cmd)
    results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)

    if 'pid' in results:
        del results['pid']

    if 'retcode' not in results or results['retcode'] != 0:
        # run_all logs an error to log.error, fail hard back to the user
        raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)

    try:
        ret = salt.utils.json.loads(results['stdout'], strict=False)
    except ValueError:
        raise CommandExecutionError('No JSON results from powershell', info=results)

    return ret
736272
def download_file_powershell(url, target):
    '''
    
    '''
    target = os.path.abspath(target)
    cmd = [
        'powershell',
        '-Command',
        '(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)' % vars(),
    ]
    subprocess.check_call(cmd)
1226074
def execute(self, input_data):
        '''  '''
        md5 = input_data['meta']['md5']
        response = requests.get('http://www.virustotal.com/vtapi/v2/file/report', 
                                params={'apikey':self.apikey,'resource':md5, 'allinfo':1})

        # Make sure we got a json blob back
        try:
            vt_output = response.json()
        except ValueError:
            return {'vt_error': 'VirusTotal Query Error, no valid response... past per min quota?'}
        
        # Just pull some of the fields
        output = {field:vt_output[field] for field in vt_output.keys() if field not in self.exclude}
        
        # Check for not-found
        not_found = False if output else True        

        # Add in file_type
        output['file_type'] = input_data['meta']['file_type']
        
        # Toss back a not found
        if not_found:
            output['not_found'] = True
            return output

        # Organize the scans fields
        scan_results = collections.Counter()
        for scan in vt_output['scans'].values():
            if 'result' in scan:
                if scan['result']:
                    scan_results[scan['result']] += 1
        output['scan_results'] = scan_results.most_common(5)
        return output
595379
def as_json(opts={})
      atts = {
        'id'                => id,
        'color'             => color,
        'status'            => display_status,
        'percent_complete'  => percent_complete,
        'work_units'        => work_units.count,
        'time_taken'        => time_taken
      }
      atts['outputs'] = JSON.parse(outputs) if outputs
      atts['email']   = email               if email
      atts
    end
59566
def _execute_cmd(plugin, args='', run_type='cmd.retcode'):
    '''
    
    '''
    data = {}

    all_plugins = list_plugins()
    if plugin in all_plugins:
        data = __salt__[run_type](
                '{0}{1} {2}'.format(PLUGINDIR, plugin, args),
                python_shell=False)

    return data
1009488
def execute(self, input_data):
        '''  '''
        string_output = input_data['strings']['string_list']
        flatten = ' '.join(string_output)
        urls = self.url_match.findall(flatten)
        return {'url_list': urls}
484616
def load_from_json(file_path):
    """"""
    if os.path.exists(file_path):
        raw_data = open(file_path, 'rb').read()
        return json.loads(base64.decodestring(raw_data).decode('utf-8'))
1265437
def load_result_json(result_path, json_file_name):
    """"""
    json_path = os.path.join(result_path, json_file_name)

    _list = []
    if os.path.isfile(json_path):
        with open(json_path) as json_data:
            try:
                _list = json.load(json_data)
            except ValueError as err:
                logger.error(
                    'Failed to load json: {}, {}'.format(json_path, err))

    return _list
640458
def execute(self, input_data):
        '''  '''

        # Grab the Bro log handles from the input
        bro_logs = input_data['pcap_bro']

        # Weird log
        if 'weird_log' in bro_logs:
            stream = self.workbench.stream_sample(bro_logs['weird_log'])
            self.weird_log_graph(stream)

        # HTTP log
        gsleep()
        stream = self.workbench.stream_sample(bro_logs['http_log'])
        self.http_log_graph(stream)

        # Files log
        gsleep()
        stream = self.workbench.stream_sample(bro_logs['files_log'])
        self.files_log_graph(stream)

        return {'output':'go to http://localhost:7474/browser and execute this query "match (s:origin), (t:file), p=allShortestPaths((s)--(t)) return p"'}
500343
async def _execute(self, api_command):
        """"""
        if api_command.observe:
            await self._observe(api_command)
            return

        method = api_command.method
        path = api_command.path
        data = api_command.data
        parse_json = api_command.parse_json
        url = api_command.url(self._host)

        kwargs = {}

        if data is not None:
            kwargs['payload'] = json.dumps(data).encode('utf-8')
            _LOGGER.debug('Executing %s %s %s: %s', self._host, method, path,
                          data)
        else:
            _LOGGER.debug('Executing %s %s %s', self._host, method, path)

        api_method = Code.GET
        if method == 'put':
            api_method = Code.PUT
        elif method == 'post':
            api_method = Code.POST
        elif method == 'delete':
            api_method = Code.DELETE
        elif method == 'fetch':
            api_method = Code.FETCH
        elif method == 'patch':
            api_method = Code.PATCH

        msg = Message(code=api_method, uri=url, **kwargs)

        _, res = await self._get_response(msg)

        api_command.result = _process_output(res, parse_json)

        return api_command.result
59891
def execute(self, input_data):
        '''  '''
        raw_bytes = input_data['sample']['raw_bytes']

        # Have the PE File module process the file
        try:
            pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
        except (AttributeError, pefile.PEFormatError), error:
            return {'error':  str(error), 'match_list': []}

        # Now get information from PEID module
        peid_match = self.peid_features(pefile_handle)
        return {'match_list': peid_match}
173664
def load_json(filename):
    """"""
    try:
        if PY2:
            args = 'rb'
        else:
            args = 'r'
        with open(filename, args) as fid:
            data = json.load(fid)
        return data, None
    except Exception as err:
        return None, str(err)
924552
def exec_cmd(self, command, **kwargs):
        """"""
        self._is_allowed_command(command)
        self._check_command_parameters(**kwargs)

        if command == 'load':
            kwargs['command'] = command
            self._check_exclusive_parameters(**kwargs)
            requests_params = self._handle_requests_params(kwargs)
            session = self._meta_data['bigip']._meta_data['icr_session']
            try:

                session.post(
                    self._meta_data['uri'], json=kwargs, **requests_params)

            except HTTPError as err:
                if err.response.status_code != 502:
                    raise
                return

        else:
            return self._exec_cmd(command, **kwargs)
387212
def execute_system_command(arg, **_):
    """"""
    usage = "Syntax: system [command].\n"

    if not arg:
      return [(None, None, None, usage)]

    try:
        command = arg.strip()
        if command.startswith('cd'):
            ok, error_message = handle_cd_command(arg)
            if not ok:
                return [(None, None, None, error_message)]
            return [(None, None, None, '')]

        args = arg.split(' ')
        process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, error = process.communicate()
        response = output if not error else error

        # Python 3 returns bytes. This needs to be decoded to a string.
        if isinstance(response, bytes):
            encoding = locale.getpreferredencoding(False)
            response = response.decode(encoding)

        return [(None, None, None, response)]
    except OSError as e:
        return [(None, None, None, 'OSError: %s' % e.strerror)]
1056269
def run_ps(self, script):
        
        # must use utf16 little endian on windows
        encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')
        rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
        if len(rs.std_err):
            # if there was an error message, clean it it up and make it human
            # readable
            rs.std_err = self._clean_error_msg(rs.std_err)
        return rs
988600
def loadJson(self, data):
        """"""
        if not isinstance(data, dict):
            data = json.loads(data)
        self.__dict__.update(data)
        self.inflate() # restore objects from str values
        #if self.ports:  self._gotPorts = True
        return self
339401
function execute(cmd) {
  var result = promise.defer();
  exec(cmd, function(err, stdout) {
    if (err) {
      result.reject(err);
    } else {
      result.fulfill(stdout);
    }
  });
  return result.promise;
}