SSH_MSG_IGNORE = 2
962023
public function handle(
        $msgType,
        \fpoirotte\Pssht\Wire\Decoder $decoder,
        \fpoirotte\Pssht\Transport $transport,
        array &$context
    ) {
        return true;
    }
718649
async def remove_ssh_key(self, user, key):
        
        key_facade = client.KeyManagerFacade.from_connection(self.connection())
        key = base64.b64decode(bytes(key.strip().split()[1].encode('ascii')))
        key = hashlib.md5(key).hexdigest()
        key = ':'.join(a + b for a, b in zip(key[::2], key[1::2]))
        await key_facade.DeleteKeys([key], user)
244949
def needs_ssh(hostname, _socket=None):
    
    if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:
        return False
    _socket = _socket or socket
    fqdn = _socket.getfqdn()
    if hostname == fqdn:
        return False
    local_hostname = _socket.gethostname()
    local_short_hostname = local_hostname.split('.')[0]
    if local_hostname == hostname or local_short_hostname == hostname:
        return False
    return True
625717
def AreHostsReachable(hostnames, ssh_key):
  
  # validate input
  for hostname in hostnames:
    assert(len(hostname))
  ssh_ok = [exit_code == 0 for (exit_code, _) in
            RunCommandOnHosts('echo test > /dev/null', hostnames, ssh_key)]
  return ssh_ok
96926
def wait_for_ssh(host, port=22, timeout=600):
    
    log_yellow('waiting for ssh...')
    for iteration in xrange(1, timeout): #noqa
        sleep(1)
        if is_ssh_available(host, port):
            return True
        else:
            log_yellow('waiting for ssh...')
206974
def MsgUser(msg):
  
  msg_tested_versions = ['xp', 'vista', '2008', '2003']
  msg_args = ['/c', '%SystemRoot%\\System32\\msg.exe', '*', '/TIME:0']
  host_version = platform.platform().lower()
  if not msg:
    return ('Command not ran.', 'Empty message.', -1)
  else:
    msg_args.extend([msg])
  for version in msg_tested_versions:
    if host_version.find(version) != -1:
      # pylint: disable=undefined-variable
      res = client_utils_common.Execute(
          'cmd', msg_args, time_limit=-1, bypass_whitelist=True)
      return res
  return ('', 'Command not available for this version.', -1)
275113
function _list($dir, $raw = true, $realpath = true)
    {
        if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
            return false;
        }

        $dir = $this->_realpath($dir . '/');
        if ($dir === false) {
            return false;
        }

        // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2
        if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) {
            return false;
        }

        $response = $this->_get_sftp_packet();
        switch ($this->packet_type) {
            case NET_SFTP_HANDLE:
                // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2
                // since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that
                // represent the length of the string and leave it at that
                $handle = substr($response, 4);
                break;
            case NET_SFTP_STATUS:
                // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
                $this->_logError($response);
                return false;
            default:
                user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS', E_USER_NOTICE);
                return false;
        }

        $this->_save_dir($dir);

        $contents = array();
        while (true) {
            // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2
            // why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many
            // SSH_MSG_CHANNEL_DATA messages is not known to me.
            if (!$this->_send_sftp_packet(NET_SFTP_READDIR, pack('Na*', strlen($handle), $handle))) {
                return false;
            }

            $response = $this->_get_sftp_packet();
            switch ($this->packet_type) {
                case NET_SFTP_NAME:
                    extract(unpack('Ncount', $this->_string_shift($response, 4)));
                    for ($i = 0; $i < $count; $i++) {
                        extract(unpack('Nlength', $this->_string_shift($response, 4)));
                        $shortname = $this->_string_shift($response, $length);
                        extract(unpack('Nlength', $this->_string_shift($response, 4)));
                        $longname = $this->_string_shift($response, $length);
                        $attributes = $this->_parseAttributes($response); // we also don't care about the attributes
                        if (!$raw) {
                            $contents[] = $shortname;
                        } else {
                            $contents[$shortname] = $attributes;
                            $fileType = $this->_parseLongname($longname);
                            if ($fileType) {
                                if ($fileType == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) {
                                    $this->_save_dir($dir . '/' . $shortname);
                                }
                                $contents[$shortname]['type'] = $fileType;
                            }
                        }
                        // SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the
                        // final SSH_FXP_STATUS packet should tell us that, already.
                    }
                    break;
                case NET_SFTP_STATUS:
                    extract(unpack('Nstatus', $this->_string_shift($response, 4)));
                    if ($status != NET_SFTP_STATUS_EOF) {
                        $this->_logError($response, $status);
                        return false;
                    }
                    break 2;
                default:
                    user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS', E_USER_NOTICE);
                    return false;
            }
        }

        if (!$this->_send_sftp_packet(NET_SFTP_CLOSE, pack('Na*', strlen($handle), $handle))) {
            return false;
        }

        // "The client MUST release all resources associated with the handle regardless of the status."
        //  -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.3
        $response = $this->_get_sftp_packet();
        if ($this->packet_type != NET_SFTP_STATUS) {
            user_error('Expected SSH_FXP_STATUS', E_USER_NOTICE);
            return false;
        }

        extract(unpack('Nstatus', $this->_string_shift($response, 4)));
        if ($status != NET_SFTP_STATUS_OK) {
            $this->_logError($response, $status);
            return false;
        }

        return $contents;
    }
331252
def _prep_ssh(
            self,
            tgt,
            fun,
            arg=(),
            timeout=None,
            tgt_type='glob',
            kwarg=None,
            **kwargs):
        '''
        
        '''
        opts = copy.deepcopy(self.opts)
        opts.update(kwargs)
        if timeout:
            opts['timeout'] = timeout
        arg = salt.utils.args.condition_input(arg, kwarg)
        opts['argv'] = [fun] + arg
        opts['selected_target_option'] = tgt_type
        opts['tgt'] = tgt
        opts['arg'] = arg
        return salt.client.ssh.SSH(opts)
1018786
def ssh_command(ip, command)
      configure_ssh_command(ip, command) do |ch, success|
        return 1 unless success

        if_debug(2) do
          ch.on_data do |ch, data|
            $stderr.puts data
          end
        end

        ch.on_request("exit-status") do |ch, data|
          return data.read_long
        end
      end
    end
1058847
def cli(env, identifier):
    """"""
    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
    if not (env.skip_confirmations or formatting.no_going_back(key_id)):
        raise exceptions.CLIAbort('Aborted')

    mgr.delete_key(key_id)
713553
def handle_ssh(self, mine=False):
        '''
        
        '''
        que = multiprocessing.Queue()
        running = {}
        target_iter = self.targets.__iter__()
        returned = set()
        rets = set()
        init = False
        while True:
            if not self.targets:
                log.error('No matching targets found in roster.')
                break
            if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
                try:
                    host = next(target_iter)
                except StopIteration:
                    init = True
                    continue
                for default in self.defaults:
                    if default not in self.targets[host]:
                        self.targets[host][default] = self.defaults[default]
                if 'host' not in self.targets[host]:
                    self.targets[host]['host'] = host
                if self.targets[host].get('winrm') and not HAS_WINSHELL:
                    returned.add(host)
                    rets.add(host)
                    log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
                    log.debug(log_msg)
                    no_ret = {'fun_args': [],
                              'jid': None,
                              'return': log_msg,
                              'retcode': 1,
                              'fun': '',
                              'id': host}
                    yield {host: no_ret}
                    continue
                args = (
                        que,
                        self.opts,
                        host,
                        self.targets[host],
                        mine,
                        )
                routine = MultiprocessingProcess(
                                target=self.handle_routine,
                                args=args)
                routine.start()
                running[host] = {'thread': routine}
                continue
            ret = {}
            try:
                ret = que.get(False)
                if 'id' in ret:
                    returned.add(ret['id'])
                    yield {ret['id']: ret['ret']}
            except Exception:
                # This bare exception is here to catch spurious exceptions
                # thrown by que.get during healthy operation. Please do not
                # worry about this bare exception, it is entirely here to
                # control program flow.
                pass
            for host in running:
                if not running[host]['thread'].is_alive():
                    if host not in returned:
                        # Try to get any returns that came through since we
                        # last checked
                        try:
                            while True:
                                ret = que.get(False)
                                if 'id' in ret:
                                    returned.add(ret['id'])
                                    yield {ret['id']: ret['ret']}
                        except Exception:
                            pass

                        if host not in returned:
                            error = ('Target \'{0}\' did not return any data, '
                                     'probably due to an error.').format(host)
                            ret = {'id': host,
                                   'ret': error}
                            log.error(error)
                            yield {ret['id']: ret['ret']}
                    running[host]['thread'].join()
                    rets.add(host)
            for host in rets:
                if host in running:
                    running.pop(host)
            if len(rets) >= len(self.targets):
                break
            # Sleep when limit or all threads started
            if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
                time.sleep(0.1)
790235
function _append_log($message_number, $message)
    {
        // remove the byte identifying the message type from all but the first two messages (ie. the identification strings)
        if (strlen($message_number) > 2) {
            $this->_string_shift($message);
        }

        switch (NET_SSH2_LOGGING) {
            // useful for benchmarks
            case self::LOG_SIMPLE:
                $this->message_number_log[] = $message_number;
                break;
            // the most useful log for SSH2
            case self::LOG_COMPLEX:
                $this->message_number_log[] = $message_number;
                $this->log_size+= strlen($message);
                $this->message_log[] = $message;
                while ($this->log_size > self::LOG_MAX_SIZE) {
                    $this->log_size-= strlen(array_shift($this->message_log));
                    array_shift($this->message_number_log);
                }
                break;
            // dump the output out realtime; packets may be interspersed with non packets,
            // passwords won't be filtered out and select other packets may not be correctly
            // identified
            case self::LOG_REALTIME:
                switch (PHP_SAPI) {
                    case 'cli':
                        $start = $stop = "\r\n";
                        break;
                    default:
                        $start = '<pre>';
                        $stop = '</pre>';
                }
                echo $start . $this->_format_log(array($message), array($message_number)) . $stop;
                @flush();
                @ob_flush();
                break;
            // basically the same thing as self::LOG_REALTIME with the caveat that self::LOG_REALTIME_FILE
            // needs to be defined and that the resultant log file will be capped out at self::LOG_MAX_SIZE.
            // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily
            // at the beginning of the file
            case self::LOG_REALTIME_FILE:
                if (!isset($this->realtime_log_file)) {
                    // PHP doesn't seem to like using constants in fopen()
                    $filename = self::LOG_REALTIME_FILENAME;
                    $fp = fopen($filename, 'w');
                    $this->realtime_log_file = $fp;
                }
                if (!is_resource($this->realtime_log_file)) {
                    break;
                }
                $entry = $this->_format_log(array($message), array($message_number));
                if ($this->realtime_log_wrap) {
                    $temp = "<<< START >>>\r\n";
                    $entry.= $temp;
                    fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp));
                }
                $this->realtime_log_size+= strlen($entry);
                if ($this->realtime_log_size > self::LOG_MAX_SIZE) {
                    fseek($this->realtime_log_file, 0);
                    $this->realtime_log_size = strlen($entry);
                    $this->realtime_log_wrap = true;
                }
                fputs($this->realtime_log_file, $entry);
        }
    }
764394
def _legacy_pubs(buf):
    """"""
    leftover = buf.read()
    if leftover:
        log.warning('skipping leftover: %r', leftover)
    code = util.pack('B', msg_code('SSH_AGENT_RSA_IDENTITIES_ANSWER'))
    num = util.pack('L', 0)  # no SSH v1 keys
    return util.frame(code, num)
504892
def ssh(self, enable=True, comment=None):
        
        self.make_request(
            NodeCommandFailed,
            method='update',
            resource='ssh',
            params={'enable': enable, 'comment': comment})
108801
protected boolean processChannelMessage(SshChannelMessage msg)
			throws SshException {

		try {
			switch (msg.getMessageId()) {
			case SSH_MSG_CHANNEL_REQUEST:

				String requesttype = msg.readString();
				boolean wantreply = msg.read() != 0;
				byte[] requestdata = new byte[msg.available()];
				msg.read(requestdata);

				if (Log.isDebugEnabled()) {
					Log.debug(this,
							"Received SSH_MSG_CHANNEL_REQUEST id=" + channelid
									+ " rid=" + remoteid + " request="
									+ requesttype + " wantreply=" + wantreply);
				}
				channelRequest(requesttype, wantreply, requestdata);
				return true;
			case SSH_MSG_WINDOW_ADJUST:

				if (Log.isDebugEnabled()) {
					msg.mark(4);
					int len = (int) msg.readInt();
					Log.debug(this,
							"Received SSH_MSG_WINDOW_ADJUST id=" + channelid
									+ " rid=" + remoteid + " window="
									+ remotewindow.available() + " adjust="
									+ len);
					msg.reset();
				}

				return false;
			case SSH_MSG_CHANNEL_DATA:

				if (Log.isDebugEnabled()) {
					Log.debug(
							this,
							"Received SSH_MSG_CHANNEL_DATA id=" + channelid
									+ " rid=" + remoteid + " len="
									+ (msg.available() - 4) + " window="
									+ localwindow.available());
				}

				// Is the channels InputStream currently in a blocking read
				// operation? if it is then we can leave the message for it
				// to process (and subsequently break out of the block) or
				// if not we should process it here so that data events
				// are fired in a timely fashion
				if (autoConsumeInput) {
					localwindow.consume(msg.available() - 4);
					if (localwindow.available() <= localwindow.getInitialSize() / 2) {
						adjustWindow(localwindow.getInitialSize()
								- localwindow.available());
					}
				}

				for (Enumeration<ChannelEventListener> e = listeners.elements(); e
						.hasMoreElements();) {
					(e.nextElement()).dataReceived(Ssh2Channel.this,
							msg.array(), msg.getPosition() + 4,
							msg.available() - 4);
				}

				return autoConsumeInput;

			case SSH_MSG_CHANNEL_EXTENDED_DATA:

				if (Log.isDebugEnabled()) {
					Log.debug(this,
							"Received SSH_MSG_CHANNEL_EXTENDED_DATA id="
									+ channelid + " rid=" + remoteid + " len="
									+ (msg.available() - 4) + " window="
									+ localwindow.available());
				}

				int type = (int) ByteArrayReader.readInt(msg.array(),
						msg.getPosition());

				if (autoConsumeInput) {
					localwindow.consume(msg.available() - 8);
					if (localwindow.available() <= localwindow.getInitialSize() / 2) {
						adjustWindow(localwindow.getInitialSize()
								- localwindow.available());
					}
				}

				for (Enumeration<ChannelEventListener> e = listeners.elements(); e
						.hasMoreElements();) {
					(e.nextElement()).extendedDataReceived(Ssh2Channel.this,
							msg.array(), msg.getPosition() + 8,
							msg.available() - 8, type);
				}

				return autoConsumeInput;

			case SSH_MSG_CHANNEL_CLOSE:

				if (Log.isDebugEnabled()) {
					Log.debug(this,
							"Received SSH_MSG_CHANNEL_CLOSE id=" + channelid
									+ " rid=" + remoteid);
				}

				// Synchronize on message store and close
				synchronized (this) {
					if (!closing) {
						synchronized (ms) {
							if (!ms.isClosed())
								ms.close();
						}
					}
				}

				checkCloseStatus(true);
				return false;

			case SSH_MSG_CHANNEL_EOF:

				if (Log.isDebugEnabled()) {
					Log.debug(this, "Received SSH_MSG_CHANNEL_EOF id="
							+ channelid + " rid=" + remoteid);
				}

				isRemoteEOF = true;

				for (Enumeration<ChannelEventListener> e = listeners.elements(); e
						.hasMoreElements();) {
					(e.nextElement()).channelEOF(Ssh2Channel.this);
				}

				// Fire the EOF event, do we need this on the listener?
				channelEOF();

				if (isLocalEOF) {
					close();
				}
				return false;

			default:
				return false;
			}
		} catch (IOException ex) {
			throw new SshException(ex, SshException.INTERNAL_ERROR);
		}

	}
408878
def change_ssh_port():
    
    host = normalize(env.host_string)[1]

    after = env.port
    before = str(env.DEFAULT_SSH_PORT)
    

    host_string=join_host_strings(env.user,host,before)
    with settings(host_string=host_string, user=env.user):
        if env.verbosity:
            print env.host, "CHANGING SSH PORT TO: "+str(after)
        sed('/etc/ssh/sshd_config','Port '+ str(before),'Port '+str(after),use_sudo=True)
        if env.verbosity:
            print env.host, "RESTARTING SSH on",after

        sudo('/etc/init.d/ssh restart')
        return True
1068167
def is_ssh_available(host, port=22):
    
    s = socket.socket()
    try:
        s.connect((host, port))
        return True
    except:
        return False