Wrapper for NX-API show method.

        Allows more code sharing between NX-API and SSH.
197196
def _send_command(self, command, raw_text=False):
        
        return self.device.show(command, raw_text=raw_text)
61468
def show(name, root=None):
    '''
    
    '''
    ret = {}
    out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root),
                              python_shell=False)
    for line in salt.utils.itertools.split(out, '\n'):
        comps = line.split('=')
        name = comps[0]
        value = '='.join(comps[1:])
        if value.startswith('{'):
            value = value.replace('{', '').replace('}', '')
            ret[name] = {}
            for item in value.split(' ; '):
                comps = item.split('=')
                ret[name][comps[0].strip()] = comps[1].strip()
        elif name in ('Before', 'After', 'Wants'):
            ret[name] = value.split()
        else:
            ret[name] = value

    return ret
381478
async def jsk_show(self, ctx: commands.Context):
        

        if not self.jsk.hidden:
            return await ctx.send("Jishaku is already visible.")

        self.jsk.hidden = False
        await ctx.send("Jishaku is now visible.")
245546
def parse_response(self, response, command_list):
        '''
        
        '''
        # Check for 500 level NX-API Server Errors
        if isinstance(response, collections.Iterable) and 'status' in response:
            if int(response['status']) >= 500:
                raise NxosError('{}'.format(response))
            else:
                raise NxosError('NX-API Request Not Supported: {}'.format(response))

        if isinstance(response, collections.Iterable):
            body = response['dict']
        else:
            body = response

        if self.nxargs['connect_over_uds']:
            body = json.loads(response.read().decode('utf-8'))

        # Proceed with caution.  The JSON may not be complete.
        # Don't just return body['ins_api']['outputs']['output'] directly.
        output = body.get('ins_api')
        if output is None:
            raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
        if output.get('outputs'):
            output = output['outputs']
        if output.get('output'):
            output = output['output']

        # The result list stores results for each command that was sent to
        # nxapi.
        result = []
        # Keep track of successful commands using previous_commands list so
        # they can be displayed if a specific command fails in a chain of
        # commands.
        previous_commands = []

        # Make sure output and command_list lists to be processed in the
        # subesequent loop.
        if not isinstance(output, list):
            output = [output]
        if isinstance(command_list, string_types):
            command_list = [cmd.strip() for cmd in command_list.split(';')]
        if not isinstance(command_list, list):
            command_list = [command_list]

        for cmd_result, cmd in zip(output, command_list):
            code = cmd_result.get('code')
            msg = cmd_result.get('msg')
            log.info('command %s:', cmd)
            log.info('PARSE_RESPONSE: %s %s', code, msg)
            if code == '400':
                raise CommandExecutionError({
                    'rejected_input': cmd,
                    'code': code,
                    'message': msg,
                    'cli_error': cmd_result.get('clierror'),
                    'previous_commands': previous_commands,
                })
            elif code == '413':
                raise NxosRequestNotSupported('Error 413: {}'.format(msg))
            elif code != '200':
                raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
            else:
                previous_commands.append(cmd)
                result.append(cmd_result['body'])

        return result
171770
def ssh_wrapper(opts, functions=None, context=None):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(
            opts,
            'wrapper',
            base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')),
        ),
        opts,
        tag='wrapper',
        pack={
            '__salt__': functions,
            '__grains__': opts.get('grains', {}),
            '__pillar__': opts.get('pillar', {}),
            '__context__': context,
            },
    )
563141
def show_code(self, x, file=None):
        
        return _show_code(x, self.opc.version, file)
739749
function Net_SSH2($host, $port = 22, $timeout = 10)
    {
        $this->message_numbers = array(
            1 => 'NET_SSH2_MSG_DISCONNECT',
            2 => 'NET_SSH2_MSG_IGNORE',
            3 => 'NET_SSH2_MSG_UNIMPLEMENTED',
            4 => 'NET_SSH2_MSG_DEBUG',
            5 => 'NET_SSH2_MSG_SERVICE_REQUEST',
            6 => 'NET_SSH2_MSG_SERVICE_ACCEPT',
            20 => 'NET_SSH2_MSG_KEXINIT',
            21 => 'NET_SSH2_MSG_NEWKEYS',
            30 => 'NET_SSH2_MSG_KEXDH_INIT',
            31 => 'NET_SSH2_MSG_KEXDH_REPLY',
            50 => 'NET_SSH2_MSG_USERAUTH_REQUEST',
            51 => 'NET_SSH2_MSG_USERAUTH_FAILURE',
            52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS',
            53 => 'NET_SSH2_MSG_USERAUTH_BANNER',

            80 => 'NET_SSH2_MSG_GLOBAL_REQUEST',
            81 => 'NET_SSH2_MSG_REQUEST_SUCCESS',
            82 => 'NET_SSH2_MSG_REQUEST_FAILURE',
            90 => 'NET_SSH2_MSG_CHANNEL_OPEN',
            91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION',
            92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE',
            93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST',
            94 => 'NET_SSH2_MSG_CHANNEL_DATA',
            95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA',
            96 => 'NET_SSH2_MSG_CHANNEL_EOF',
            97 => 'NET_SSH2_MSG_CHANNEL_CLOSE',
            98 => 'NET_SSH2_MSG_CHANNEL_REQUEST',
            99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS',
            100 => 'NET_SSH2_MSG_CHANNEL_FAILURE'
        );
        $this->disconnect_reasons = array(
            1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT',
            2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR',
            3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED',
            4 => 'NET_SSH2_DISCONNECT_RESERVED',
            5 => 'NET_SSH2_DISCONNECT_MAC_ERROR',
            6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR',
            7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE',
            8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED',
            9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE',
            10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST',
            11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION',
            12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS',
            13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER',
            14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE',
            15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME'
        );
        $this->channel_open_failure_reasons = array(
            1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED'
        );
        $this->terminal_modes = array(
            0 => 'NET_SSH2_TTY_OP_END'
        );
        $this->channel_extended_data_type_codes = array(
            1 => 'NET_SSH2_EXTENDED_DATA_STDERR'
        );

        $this->_define_array(
            $this->message_numbers,
            $this->disconnect_reasons,
            $this->channel_open_failure_reasons,
            $this->terminal_modes,
            $this->channel_extended_data_type_codes,
            array(60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'),
            array(60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'),
            array(60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
                  61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE')
        );

        $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
        $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$this->fsock) {
            user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"), E_USER_NOTICE);
            return;
        }
        $elapsed = strtok(microtime(), ' ') + strtok('') - $start;

        $timeout-= $elapsed;

        if ($timeout <= 0) {
            user_error(rtrim("Cannot connect to $host. Timeout error"), E_USER_NOTICE);
            return;
        }

        $read = array($this->fsock);
        $write = $except = NULL;

        $sec = floor($timeout);
        $usec = 1000000 * ($timeout - $sec);

        // on windows this returns a "Warning: Invalid CRT parameters detected" error
        // the !count() is done as a workaround for <https://bugs.php.net/42682>
        if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
            user_error(rtrim("Cannot connect to $host. Banner timeout"), E_USER_NOTICE);
            return;
        }

        /* According to the SSH2 specs,

          "The server MAY send other lines of data before sending the version
           string.  Each line SHOULD be terminated by a Carriage Return and Line
           Feed.  Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
           in ISO-10646 UTF-8 [RFC3629] (language is not specified).  Clients
           MUST be able to process such lines." */
        $temp = '';
        $extra = '';
        while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) {
            if (substr($temp, -2) == "\r\n") {
                $extra.= $temp;
                $temp = '';
            }
            $temp.= fgets($this->fsock, 255);
        }

        if (feof($this->fsock)) {
            user_error('Connection closed by server', E_USER_NOTICE);
            return false;
        }

        $ext = array();
        if (extension_loaded('mcrypt')) {
            $ext[] = 'mcrypt';
        }
        if (extension_loaded('gmp')) {
            $ext[] = 'gmp';
        } else if (extension_loaded('bcmath')) {
            $ext[] = 'bcmath';
        }

        if (!empty($ext)) {
            $this->identifier.= ' (' . implode(', ', $ext) . ')';
        }

        if (defined('NET_SSH2_LOGGING')) {
            $this->message_number_log[] = '<-';
            $this->message_number_log[] = '->';

            if (NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) {
                $this->message_log[] = $extra . $temp;
                $this->message_log[] = $this->identifier . "\r\n";
            }
        }

        $this->server_identifier = trim($temp, "\r\n");
        if (!empty($extra)) {
            $this->errors[] = utf8_decode($extra);
        }

        if ($matches[1] != '1.99' && $matches[1] != '2.0') {
            user_error("Cannot connect to SSH $matches[1] servers", E_USER_NOTICE);
            return;
        }

        fputs($this->fsock, $this->identifier . "\r\n");

        $response = $this->_get_binary_packet();
        if ($response === false) {
            user_error('Connection closed by server', E_USER_NOTICE);
            return;
        }

        if (ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
            user_error('Expected SSH_MSG_KEXINIT', E_USER_NOTICE);
            return;
        }

        if (!$this->_key_exchange($response)) {
            return;
        }

        $this->bitmap = NET_SSH2_MASK_CONSTRUCTOR;
    }
70601
def _init_ssh(opts):
    '''
    
    '''
    if opts is None:
        opts = __opts__
    try:
        this_prompt = None
        if 'prompt_regex' in opts['proxy']:
            this_prompt = opts['proxy']['prompt_regex']
        elif 'prompt_name' in opts['proxy']:
            this_prompt = '{0}.*#'.format(opts['proxy']['prompt_name'])
        else:
            log.warning('nxos proxy configuration does not specify a prompt match.')
            this_prompt = '.+#$'

        DEVICE_DETAILS[_worker_name()] = SSHConnection(
            host=opts['proxy']['host'],
            username=opts['proxy']['username'],
            password=opts['proxy']['password'],
            key_accept=opts['proxy'].get('key_accept', False),
            ssh_args=opts['proxy'].get('ssh_args', ''),
            prompt=this_prompt)
        out, err = DEVICE_DETAILS[_worker_name()].sendline('terminal length 0')
        log.info('SSH session establised for process %s', _worker_name())
    except Exception as ex:
        log.error('Unable to connect to %s', opts['proxy']['host'])
        log.error('Please check the following:\n')
        log.error('-- Verify that "feature ssh" is enabled on your NX-OS device: %s', opts['proxy']['host'])
        log.error('-- Exception Generated: %s', ex)
        log.error(ex)
        exit()
    DEVICE_DETAILS['initialized'] = True
    DEVICE_DETAILS['no_save_config'] = opts['proxy'].get('no_save_config', False)
1124282
def cmd_shodan_open(ip, no_cache, json_output, nmap_command, verbose, output):
    

    habucfg = loadcfg()

    if 'SHODAN_APIKEY' not in habucfg:
        print('You must provide a shodan apikey. Use the ~/.habu.json file (variable SHODAN_APIKEY), or export the variable HABU_SHODAN_APIKEY')
        print('Get your API key from https://www.shodan.io/')
        sys.exit(1)

    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    data = shodan_get_result(ip, habucfg['SHODAN_APIKEY'], no_cache, verbose)
    ports = []

    if 'data' in data:
        for service in data['data']:
            ports.append('{}:{}'.format(
                service['transport'][0].upper(),
                service['port']
            ))

    if nmap_command:
        if ports:
            output.write('nmap -A -v -p {} {}'.format(','.join(ports), ip))
    else:
        if json_output:
            output.write(json.dumps(ports, indent=4))
            output.write('\n')
        else:
            output.write(','.join(ports))
473870
private void npnReceived(ServerHello mesg) throws IOException
    {
        NextProtoNegoExtension extension = (NextProtoNegoExtension)mesg.extensions.get(ExtensionType.EXT_NEXT_PROTOCOL_NEGOTIATION);
        if (extension != null)
        {
            protocols = extension.getProtocols();
            if (NextProtoNego.debug)
                System.err.println(new StringBuilder("[C] NPN protocols ").append(protocols).append(" received from server for ").append(conn != null ? conn : engine));
        }
        else
        {
            if (NextProtoNego.debug)
                System.err.println(new StringBuilder("[C] NPN protocols not sent by server for ").append(conn != null ? conn : engine));
        }
    }
732836
def show(ctx, service, remote):
    """"""
    logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
                 extra={"command": ctx.command.name, "params": ctx.params})

    home = ctx.obj["HOME"]
    service_path = plugin_utils.get_plugin_path(home, defs.SERVICES, service)

    def collect_local_info(service, service_path):
        logger.debug("loading {} from {}".format(service, service_path))
        service = register_service(service_path)
        try:
            with open(os.path.join(service_path, "requirements.txt"), "r") as fh:
                info["requirements"] = " ".join(fh.readlines())
        except IOError:
            pass
        info["name"] = service.name
        info["label"] = service.label
        info["location"] = service_path

        return info

    def collect_remote_info(service):
        rsession = requests.Session()
        rsession.mount("https://", HTTPAdapter(max_retries=3))

        try:
            r = rsession.get(defs.GITHUB_RAW_URL.format(plugin_type=defs.SERVICES,
                                                        plugin=service, filename="config.json"))
            service_config = r.json()
            info["name"] = service_config[defs.SERVICE][defs.NAME]
            info["label"] = service_config[defs.SERVICE][defs.LABEL]
            info["location"] = defs.GITHUB_URL.format(plugin_type=defs.SERVICES, plugin=info["name"])
        except requests.exceptions.HTTPError as exc:
            logger.debug(str(exc), exc_info=True)
            raise click.ClickException("Cannot find package {}".format(service))
        except requests.exceptions.ConnectionError as exc:
            logger.debug(str(exc), exc_info=True)
            raise click.ClickException("Unable to reach remote repository {}".format(service))

        try:
            r = rsession.get(defs.GITHUB_RAW_URL.format(plugin_type=defs.SERVICES, plugin=info["name"],
                                                        filename="requirements.txt"))
            r.raise_for_status()
            info["requirements"] = " ".join(r.text.split("\n"))
        except requests.exceptions.HTTPError as exc:
            logger.debug(str(exc), exc_info=True)
            info["requirements"] = None
        except requests.exceptions.ConnectionError as exc:
            logger.debug(str(exc), exc_info=True)
            raise click.ClickException("Unable to reach remote repository {}".format(service))

        return info

    info = {"commit_revision": "N/A", "commit_date": "N/A", "requirements": "None"}

    if os.path.exists(service_path):
        info["installed"] = True
        if remote:
            click.secho("[*] Fetching info from online repository")
            info.update(collect_remote_info(service))
        else:
            info.update(collect_local_info(service, service_path))
    else:
        logger.debug("cannot find {} locally".format(service))
        if not remote:
            click.secho("[*] Cannot find service locally, checking online repository")
        info["installed"] = False
        info.update(collect_remote_info(service))
    logger.debug(info)
    click.secho(PKG_INFO_TEMPLATE.format(**info))
225456
def _ssh_client(self):
        
        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
        return ssh
504396
def _python_psk_client_callback(ssl_id, hint):
    
    if ssl_id not in _callbacks:
        return ("", "")
    else:
        res = _callbacks[ssl_id](hint)
        return res if isinstance(res, tuple) else (res, "")
896970
def ssh_invite(ctx, code_length, user, **kwargs):
    
    for name, value in kwargs.items():
        setattr(ctx.obj, name, value)
    from . import cmd_ssh
    ctx.obj.code_length = code_length
    ctx.obj.ssh_user = user
    return go(cmd_ssh.invite, ctx.obj)
1315999
def api_start(working_dir, host, port, thread=True):
    
    api_srv = BlockstackdAPIServer( working_dir, host, port )
    log.info("Starting API server on port {}".format(port))
    if thread:
        api_srv.start()

    return api_srv
1233972
def system_describe_executions(input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/system/describeExecutions', input_params, always_retry=always_retry, **kwargs)
270111
def cli_error_check(result)
      # Check for messages that can be safely ignored.
      # The NXOS interface private-vlan cli does not raise an exception
      # in some conditions and instead just displays a STDOUT error message
      # thus NXAPI does not detect the failure.
      # We must catch it by inspecting the "body" hash entry returned by NXAPI.
      # This vlan cli behavior is unlikely to change.

      errors = /(ERROR:|VLAN:|Eth)/
      return unless
        result[1].is_a?(Hash) && errors.match(result[1]['body'].to_s)
      # Split errors into a list, but keep the delimiter as part of the message.
      error_list =
        (result[1]['body'].split(errors) - ['']).each_slice(2).map(&:join)
      error_list.each do |_msg|
        fail result[1]['body']
      end
    end