class SSH2 (View source)

Pure-PHP implementation of SSHv2.

Constants

MASK_CONSTRUCTOR

MASK_CONNECTED

MASK_LOGIN_REQ

MASK_LOGIN

MASK_SHELL

MASK_WINDOW_ADJUST

CHANNEL_EXEC

CHANNEL_SHELL

CHANNEL_SUBSYSTEM

CHANNEL_AGENT_FORWARD

CHANNEL_KEEP_ALIVE

LOG_SIMPLE

Returns the message numbers

LOG_COMPLEX

Returns the message content

LOG_REALTIME

Outputs the content real-time

LOG_REALTIME_FILE

Dumps the content real-time to a file

LOG_MAX_SIZE

Make sure that the log never gets larger than this

READ_SIMPLE

Returns when a string matching $expect exactly is found

READ_REGEX

Returns when a string matching the regular expression $expect is found

READ_NEXT

Returns whenever a data packet is received.

Some data packets may only contain a single character so it may be necessary to call read() multiple times when using this option

Properties

object $fsock The Socket Object
protected int $bitmap Execution Bitmap
protected array $server_channels Server Channels
protected array $channel_status Channel Status
protected int $window_size The Window Size
protected array $window_size_server_to_client Window size, server to client
protected $timeout Timeout
protected $curTimeout Current Timeout
protected string|false $preferred_signature_format Preferred Signature Format
protected array $auth Authentication Credentials

Methods

SSH2|void
__construct(mixed $host, int $port = 22, int $timeout = 10)

Default Constructor.

static 
setCryptoEngine(int $engine)

Set Crypto Engine Mode

sendIdentificationStringFirst()

Send Identification String First

sendIdentificationStringLast()

Send Identification String Last

sendKEXINITFirst()

Send SSH_MSG_KEXINIT First

sendKEXINITLast()

Send SSH_MSG_KEXINIT Last

bool
login(string $username, string|AsymmetricKey|array[]|Agent|null ...$args)

Login

bool
sublogin(string $username, string[] ...$args)

Login Helper

setTimeout(mixed $timeout)

Set Timeout

setKeepAlive(int $interval)

Set Keep Alive

getStdError()

Get the output from stdError

string
exec(string $command, callable $callback = null)

Execute Command

bool
requestAgentForwarding()

Request agent forwarding of remote server

string|bool|null
read(string $expect = '', int $mode = self::READ_SIMPLE)

Returns the output of an interactive shell

bool
write(string $cmd)

Inputs a command into an interactive shell.

bool
startSubsystem(string $subsystem)

Start a subsystem.

bool
stopSubsystem()

Stops a subsystem.

reset()

Closes a channel

isTimeout()

Is timeout?

disconnect()

Disconnect

__destruct()

Destructor.

bool
isConnected()

Is the connection still active?

bool
isAuthenticated()

Have you successfully been logged in?

bool
ping()

Pings a server connection, or tries to reconnect if the connection has gone down

reset_connection(int $reason)

Resets a connection for re-use

enableQuietMode()

Enable Quiet Mode

disableQuietMode()

Disable Quiet Mode

bool
isQuietModeEnabled()

Returns whether Quiet Mode is enabled or not

enablePTY()

Enable request-pty when using exec()

disablePTY()

Disable request-pty when using exec()

bool
isPTYEnabled()

Returns whether request-pty is enabled or not

mixed
get_channel_packet(int $client_channel, bool $skip_extended = false)

Gets channel data

bool
send_binary_packet(string $data, string $logged = null)

Sends Binary Packets

bool
send_channel_packet(int $client_channel, string $data)

Sends channel data

bool
disconnect_helper(int $reason)

Disconnect

define_array(array ...$args)

Define Array

array|false|string
getLog()

Returns a log of the packets that have been sent and received.

string
format_log(array $message_log, array $message_number_log)

Formats a log for printing

string[]
getErrors()

Returns all errors

string
getLastError()

Returns the last error

string
getServerIdentification()

Return the server identification.

array
getServerAlgorithms()

Returns a list of algorithms the server supports

static array
getSupportedKEXAlgorithms()

Returns a list of KEX algorithms that phpseclib supports

static array
getSupportedHostKeyAlgorithms()

Returns a list of host key algorithms that phpseclib supports

static array
getSupportedEncryptionAlgorithms()

Returns a list of symmetric key algorithms that phpseclib supports

static array
getSupportedMACAlgorithms()

Returns a list of MAC algorithms that phpseclib supports

static array
getSupportedCompressionAlgorithms()

Returns a list of compression algorithms that phpseclib supports

array
getAlgorithmsNegotiated()

Return list of negotiated algorithms

setTerminal(string $term)

Allows you to set the terminal

setPreferredAlgorithms(array $methods)

Accepts an associative array with up to four parameters as described at https://www.php.net/manual/en/function.ssh2-connect.php

string
getBannerMessage()

Returns the banner message.

mixed
getServerPublicHostKey()

Returns the server public host key.

false|int
getExitStatus()

Returns the exit status of an SSH command or false.

int
getWindowColumns()

Returns the number of columns for the terminal window size.

int
getWindowRows()

Returns the number of rows for the terminal window size.

setWindowColumns(int $value)

Sets the number of columns for the terminal window size.

setWindowRows(int $value)

Sets the number of rows for the terminal window size.

setWindowSize(int $columns = 80, int $rows = 24)

Sets the number of columns and rows for the terminal window size.

string
__toString()

To String Magic Method

string
getResourceId()

Get Resource ID

static bool|SSH2
getConnectionByResourceId(string $id)

Return existing connection

static SSH2[]
getConnections()

Return all excising connections

array|null
getAuthMethodsToContinue()

Return the list of authentication methods that may productively continue authentication.

Details

SSH2|void __construct(mixed $host, int $port = 22, int $timeout = 10)

Default Constructor.

$host can either be a string, representing the host, or a stream resource.

Parameters

mixed $host
int $port
int $timeout

Return Value

SSH2|void

See also

\self::login()

static setCryptoEngine(int $engine)

Set Crypto Engine Mode

Possible $engine values: OpenSSL, mcrypt, Eval, PHP

Parameters

int $engine

sendIdentificationStringFirst()

Send Identification String First

https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established, both sides MUST send an identification string". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

sendIdentificationStringLast()

Send Identification String Last

https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established, both sides MUST send an identification string". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

sendKEXINITFirst()

Send SSH_MSG_KEXINIT First

https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

sendKEXINITLast()

Send SSH_MSG_KEXINIT Last

https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

bool login(string $username, string|AsymmetricKey|array[]|Agent|null ...$args)

Login

The $password parameter can be a plaintext password, a \phpseclib3\Crypt\RSA|EC|DSA object, a \phpseclib3\System\SSH\Agent object or an array

Parameters

string $username
string|AsymmetricKey|array[]|Agent|null ...$args

Return Value

bool

See also

\self::_login()

protected bool sublogin(string $username, string[] ...$args)

Login Helper

Parameters

string $username
string[] ...$args

Return Value

bool

See also

\self::_login_helper()

setTimeout(mixed $timeout)

Set Timeout

$ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. Setting $timeout to false or 0 will mean there is no timeout.

Parameters

mixed $timeout

setKeepAlive(int $interval)

Set Keep Alive

Sends an SSH2_MSG_IGNORE message every x seconds, if x is a positive non-zero number.

Parameters

int $interval

getStdError()

Get the output from stdError

string exec(string $command, callable $callback = null)

Execute Command

If $callback is set to false then \phpseclib3\Net\SSH2::get_channel_packet(self::CHANNEL_EXEC) will need to be called manually. In all likelihood, this is not a feature you want to be taking advantage of.

Parameters

string $command
callable $callback

Return Value

string

Exceptions

RuntimeException on connection error

bool requestAgentForwarding()

Request agent forwarding of remote server

Return Value

bool

string|bool|null read(string $expect = '', int $mode = self::READ_SIMPLE)

Returns the output of an interactive shell

Returns when there's a match for $expect, which can take the form of a string literal or, if $mode == self::READ_REGEX, a regular expression.

Parameters

string $expect
int $mode

Return Value

string|bool|null

Exceptions

RuntimeException on connection error

See also

\self::write()

bool write(string $cmd)

Inputs a command into an interactive shell.

Parameters

string $cmd

Return Value

bool

Exceptions

RuntimeException on connection error

See also

\self::read()

bool startSubsystem(string $subsystem)

Start a subsystem.

Right now only one subsystem at a time is supported. To support multiple subsystem's stopSubsystem() could accept a string that contained the name of the subsystem, but at that point, only one subsystem of each type could be opened. To support multiple subsystem's of the same name maybe it'd be best if startSubsystem() generated a new channel id and returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented if there's sufficient demand for such a feature.

Parameters

string $subsystem

Return Value

bool

See also

\self::stopSubsystem()

bool stopSubsystem()

Stops a subsystem.

Return Value

bool

See also

\self::startSubsystem()

reset()

Closes a channel

If read() timed out you might want to just close the channel and have it auto-restart on the next read() call

isTimeout()

Is timeout?

Did exec() or read() return because they timed out or because they encountered the end?

disconnect()

Disconnect

__destruct()

Destructor.

Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call disconnect().

bool isConnected()

Is the connection still active?

Return Value

bool

bool isAuthenticated()

Have you successfully been logged in?

Return Value

bool

bool ping()

Pings a server connection, or tries to reconnect if the connection has gone down

Inspired by http://php.net/manual/en/mysqli.ping.php

Return Value

bool

protected reset_connection(int $reason)

Resets a connection for re-use

Parameters

int $reason

enableQuietMode()

Enable Quiet Mode

Suppress stderr from output

disableQuietMode()

Disable Quiet Mode

Show stderr in output

bool isQuietModeEnabled()

Returns whether Quiet Mode is enabled or not

Return Value

bool

See also

\self::enableQuietMode()
\self::disableQuietMode()

enablePTY()

Enable request-pty when using exec()

disablePTY()

Disable request-pty when using exec()

bool isPTYEnabled()

Returns whether request-pty is enabled or not

Return Value

bool

See also

\self::enablePTY()
\self::disablePTY()

protected mixed get_channel_packet(int $client_channel, bool $skip_extended = false)

Gets channel data

Returns the data as a string. bool(true) is returned if:

  • the server closes the channel
  • if the connection times out
  • if the channel status is CHANNEL_OPEN and the response was CHANNEL_OPEN_CONFIRMATION
  • if the channel status is CHANNEL_REQUEST and the response was CHANNEL_SUCCESS

bool(false) is returned if:

  • if the channel status is CHANNEL_REQUEST and the response was CHANNEL_FAILURE

Parameters

int $client_channel
bool $skip_extended

Return Value

mixed

Exceptions

RuntimeException on connection error

protected bool send_binary_packet(string $data, string $logged = null)

Sends Binary Packets

See '6. Binary Packet Protocol' of rfc4253 for more info.

Parameters

string $data
string $logged

Return Value

bool

See also

\self::_get_binary_packet()

protected bool send_channel_packet(int $client_channel, string $data)

Sends channel data

Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate

Parameters

int $client_channel
string $data

Return Value

bool

protected bool disconnect_helper(int $reason)

Disconnect

Parameters

int $reason

Return Value

bool

protected define_array(array ...$args)

Define Array

Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of named constants from it, using the value as the name of the constant and the index as the value of the constant. If any of the constants that would be defined already exists, none of the constants will be defined.

Parameters

array ...$args

array|false|string getLog()

Returns a log of the packets that have been sent and received.

Returns a string if NET_SSH2_LOGGING == self::LOG_COMPLEX, an array if NET_SSH2_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING')

Return Value

array|false|string

protected string format_log(array $message_log, array $message_number_log)

Formats a log for printing

Parameters

array $message_log
array $message_number_log

Return Value

string

string[] getErrors()

Returns all errors

Return Value

string[]

string getLastError()

Returns the last error

Return Value

string

string getServerIdentification()

Return the server identification.

Return Value

string

array getServerAlgorithms()

Returns a list of algorithms the server supports

Return Value

array

static array getSupportedKEXAlgorithms()

Returns a list of KEX algorithms that phpseclib supports

Return Value

array

static array getSupportedHostKeyAlgorithms()

Returns a list of host key algorithms that phpseclib supports

Return Value

array

static array getSupportedEncryptionAlgorithms()

Returns a list of symmetric key algorithms that phpseclib supports

Return Value

array

static array getSupportedMACAlgorithms()

Returns a list of MAC algorithms that phpseclib supports

Return Value

array

static array getSupportedCompressionAlgorithms()

Returns a list of compression algorithms that phpseclib supports

Return Value

array

array getAlgorithmsNegotiated()

Return list of negotiated algorithms

Uses the same format as https://www.php.net/ssh2-methods-negotiated

Return Value

array

setTerminal(string $term)

Allows you to set the terminal

Parameters

string $term

setPreferredAlgorithms(array $methods)

Accepts an associative array with up to four parameters as described at https://www.php.net/manual/en/function.ssh2-connect.php

Parameters

array $methods

string getBannerMessage()

Returns the banner message.

Quoting from the RFC, "in some jurisdictions, sending a warning message before authentication may be relevant for getting legal protection."

Return Value

string

mixed getServerPublicHostKey()

Returns the server public host key.

Caching this the first time you connect to a server and checking the result on subsequent connections is recommended. Returns false if the server signature is not signed correctly with the public host key.

Return Value

mixed

Exceptions

RuntimeException on badly formatted keys
NoSupportedAlgorithmsException when the key isn't in a supported format

false|int getExitStatus()

Returns the exit status of an SSH command or false.

Return Value

false|int

int getWindowColumns()

Returns the number of columns for the terminal window size.

Return Value

int

int getWindowRows()

Returns the number of rows for the terminal window size.

Return Value

int

setWindowColumns(int $value)

Sets the number of columns for the terminal window size.

Parameters

int $value

setWindowRows(int $value)

Sets the number of rows for the terminal window size.

Parameters

int $value

setWindowSize(int $columns = 80, int $rows = 24)

Sets the number of columns and rows for the terminal window size.

Parameters

int $columns
int $rows

string __toString()

To String Magic Method

Return Value

string

string getResourceId()

Get Resource ID

We use } because that symbols should not be in URL according to {@link http://tools.ietf.org/html/rfc3986#section-2 RFC}. It will safe us from any conflicts, because otherwise regexp will match all alphanumeric domains.

Return Value

string

static bool|SSH2 getConnectionByResourceId(string $id)

Return existing connection

Parameters

string $id

Return Value

bool|SSH2 will return false if no such connection

static SSH2[] getConnections()

Return all excising connections

Return Value

SSH2[]

array|null getAuthMethodsToContinue()

Return the list of authentication methods that may productively continue authentication.

Return Value

array|null

See also

https://tools.ietf.org/html/rfc4252#section-5.1