SSH2
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
string | $identifier | The SSH identifier | |
object | $fsock | The Socket Object | |
int | $bitmap | Execution Bitmap | |
string | $errors | Error information | |
array|false | $server_identifier | Server Identifier | |
array|false | $kex_algorithms | Key Exchange Algorithms | |
string|false | $kex_algorithm | Key Exchange Algorithm | |
int | $kex_dh_group_size_min | Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods | |
int | $kex_dh_group_size_preferred | Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods | |
int | $kex_dh_group_size_max | Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods | |
array|false | $server_host_key_algorithms | Server Host Key Algorithms | |
array|false | $encryption_algorithms_client_to_server | Encryption Algorithms: Client to Server | |
array|false | $encryption_algorithms_server_to_client | Encryption Algorithms: Server to Client | |
array|false | $mac_algorithms_client_to_server | MAC Algorithms: Client to Server | |
array|false | $mac_algorithms_server_to_client | MAC Algorithms: Server to Client | |
array|false | $compression_algorithms_client_to_server | Compression Algorithms: Client to Server | |
array|false | $compression_algorithms_server_to_client | Compression Algorithms: Server to Client | |
array|false | $languages_server_to_client | Languages: Server to Client | |
array|false | $languages_client_to_server | Languages: Client to Server | |
array | $preferred | Preferred Algorithms | |
int | $encrypt_block_size | Block Size for Server to Client Encryption | |
int | $decrypt_block_size | Block Size for Client to Server Encryption | |
object | $decrypt | Server to Client Encryption Object | |
object | $encrypt | Client to Server Encryption Object | |
object | $hmac_create | Client to Server HMAC Object | |
object | $hmac_check | Server to Client HMAC Object | |
int | $hmac_size | Size of server to client HMAC | |
string | $server_public_host_key | Server Public Host Key | |
string | $session_id | Session identifier | |
string | $exchange_hash | Exchange hash | |
array | $message_numbers | Message Numbers | |
array | $disconnect_reasons | Disconnection Message 'reason codes' defined in RFC4253 | |
array | $channel_open_failure_reasons | SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254 | |
array | $terminal_modes | Terminal Modes | |
array | $channel_extended_data_type_codes | SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes | |
int | $send_seq_no | Send Sequence Number | |
int | $get_seq_no | Get Sequence Number | |
array | $server_channels | Server Channels | |
array | $channel_buffers | Channel Buffers | |
array | $channel_status | Channel Status | |
array | $packet_size_client_to_server | Packet Size | |
array | $message_number_log | Message Number Log | |
array | $message_log | Message Log | |
int | $window_size | The Window Size | |
int | $window_resize | What we resize the window to | |
array | $window_size_server_to_client | Window size, server to client | |
array | $window_size_client_to_server | Window size, client to server | |
string | $signature | Server signature | |
string | $signature_format | Server signature format | |
array | $interactiveBuffer | Interactive Buffer | |
int | $log_size | Current log size | |
$timeout | Timeout | ||
$curTimeout | Current Timeout | ||
$keepAlive | Keep Alive Interval | ||
resource | $realtime_log_file | Real-time log file pointer | |
int | $realtime_log_size | Real-time log file size | |
bool | $signature_validated | Has the signature been validated? | |
$realtime_log_wrap | Real-time log file wrap boolean | ||
$quiet_mode | Flag to suppress stderr from output | ||
int | $last_packet | Time of first network activity | |
int | $exit_status | Exit status returned from ssh if any | |
bool | $request_pty | Flag to request a PTY when using exec() | |
bool | $in_request_pty_exec | Flag set while exec() is running when using enablePTY() | |
bool | $in_subsystem | Flag set after startSubsystem() is called | |
string | $stdErrorLog | Contents of stdError | |
string | $last_interactive_response | The Last Interactive Response | |
array | $keyboard_requests_responses | Keyboard Interactive Request / Responses | |
string | $banner_message | Banner Message | |
bool | $is_timeout | Did read() timeout or return normally? | |
string | $log_boundary | Log Boundary | |
int | $log_long_width | Log Long Width | |
int | $log_short_width | Log Short Width | |
string | $host | Hostname | |
int | $port | Port Number | |
int | $windowColumns | Number of columns for terminal window size | |
int | $windowRows | Number of columns for terminal window size | |
int | $crypto_engine | Crypto Engine | |
System_SSH_Agent | $agent | A System_SSH_Agent for use in the SSH2 Agent Forwarding scenario | |
bool | $send_id_string_first | Send the identification string first? | |
bool | $send_kex_first | Send the key exchange initiation packet first? | |
bool | $bad_key_size_fix | Some versions of OpenSSH incorrectly calculate the key size | |
bool | $retry_connect | Should we try to re-connect to re-establish keys? | |
string|false | $binary_packet_buffer | Binary Packet Buffer | |
string|false | $preferred_signature_format | Preferred Signature Format | |
array | $auth | Authentication Credentials |
Methods
Default Constructor.
Set Crypto Engine Mode
Send Identification String First
Send Identification String Last
Send SSH_MSG_KEXINIT First
Send SSH_MSG_KEXINIT Last
Connect to an SSHv2 server
Generates the SSH identifier
Key Exchange
Maps an encryption algorithm name to the number of key bytes.
Maps an encryption algorithm name to an instance of a subclass of \phpseclib\Crypt\Base.
Tests whether or not proposed algorithm has a potential for issues
Login
Login Helper
Login Helper
Login via keyboard-interactive authentication
Handle the keyboard-interactive requests / responses.
Set Timeout
Set Keep Alive
Get the output from stdError
Execute Command
Creates an interactive shell
Return the channel to be used with read() / write()
Return an available open channel
Returns the output of an interactive shell
Inputs a command into an interactive shell.
Start a subsystem.
Stops a subsystem.
Closes a channel
Is timeout?
Disconnect
Destructor.
Is the connection still active?
Have you successfully been logged in?
Pings a server connection, or tries to reconnect if the connection has gone down
In situ reconnect method
Resets a connection for re-use
Gets Binary Packets
Filter Binary Packets
Enable Quiet Mode
Disable Quiet Mode
Returns whether Quiet Mode is enabled or not
Enable request-pty when using exec()
Disable request-pty when using exec()
Returns whether request-pty is enabled or not
Gets channel data
Sends Binary Packets
Logs data packets
Sends channel data
Closes and flushes a channel
Disconnect
String Shift
Define Array
Returns a log of the packets that have been sent and received.
Formats a log for printing
Helper function for _format_log
Helper function for agent->_on_channel_open()
Returns the first value of the intersection of two arrays or false if the intersection is empty. The order is defined by the first parameter.
Returns all errors
Returns the last error
Return the server identification.
Return a list of the key exchange algorithms the server supports.
Return a list of the host key (public key) algorithms the server supports.
Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client.
Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client.
Return a list of the MAC algorithms the server supports, when receiving stuff from the client.
Return a list of the MAC algorithms the server supports, when sending stuff to the client.
Return a list of the compression algorithms the server supports, when receiving stuff from the client.
Return a list of the compression algorithms the server supports, when sending stuff to the client.
Return a list of the languages the server supports, when sending stuff to the client.
Return a list of the languages the server supports, when receiving stuff from the client.
Returns a list of algorithms the server supports
Returns a list of KEX algorithms that phpseclib supports
Returns a list of host key algorithms that phpseclib supports
Returns a list of symmetric key algorithms that phpseclib supports
Returns a list of MAC algorithms that phpseclib supports
Returns a list of compression algorithms that phpseclib supports
Return list of negotiated algorithms
Accepts an associative array with up to four parameters as described at https://www.php.net/manual/en/function.ssh2-connect.php
Returns the banner message.
Returns the server public host key.
Returns the exit status of an SSH command or false.
Returns the number of columns for the terminal window size.
Returns the number of rows for the terminal window size.
Sets the number of columns for the terminal window size.
Sets the number of rows for the terminal window size.
Sets the number of columns and rows for the terminal window size.
Update packet types in log history
Return the list of authentication methods that may productively continue authentication.
Details
SSH2
__construct(mixed $host, int $port = 22, int $timeout = 10)
Default Constructor.
$host can either be a string, representing the host, or a stream resource.
setCryptoEngine(int $engine)
Set Crypto Engine Mode
Possible $engine values: CRYPT_MODE_INTERNAL, CRYPT_MODE_MCRYPT
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
_connect()
Connect to an SSHv2 server
string
_generate_identifier()
Generates the SSH identifier
You should overwrite this method in your own class if you want to use another identifier
_key_exchange(string $kexinit_payload_server = false)
Key Exchange
int|null
_encryption_algorithm_to_key_size(string $algorithm)
Maps an encryption algorithm name to the number of key bytes.
mixed
_encryption_algorithm_to_crypt_instance(string $algorithm)
Maps an encryption algorithm name to an instance of a subclass of \phpseclib\Crypt\Base.
bool
_bad_algorithm_candidate(string $algorithm)
Tests whether or not proposed algorithm has a potential for issues
bool
login(string $username)
Login
The $password parameter can be a plaintext password, a \phpseclib\Crypt\RSA object or an array
bool
_login(string $username)
Login Helper
bool
_login_helper(string $username, string $password = null)
Login Helper
bool
_keyboard_interactive_login(string $username, string $password)
Login via keyboard-interactive authentication
See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details. This is not a full-featured keyboard-interactive authenticator.
bool
_keyboard_interactive_process()
Handle the keyboard-interactive requests / responses.
bool
_ssh_agent_login(string $username, Agent $agent)
Login with an ssh-agent provided key
bool
_privatekey_login(string $username, RSA $privatekey)
Login with an RSA private key
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.
setKeepAlive(int $interval)
Set Keep Alive
Sends an SSH2_MSG_IGNORE message every x seconds, if x is a positive non-zero number.
getStdError()
Get the output from stdError
string
exec(string $command, callable $callback = null)
Execute Command
If $callback is set to false then \phpseclib\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.
bool
_initShell()
Creates an interactive shell
int
_get_interactive_channel()
Return the channel to be used with read() / write()
int
_get_open_channel()
Return an available open channel
string|bool
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.
bool
write(string $cmd)
Inputs a command into an interactive shell.
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.
bool
stopSubsystem()
Stops a subsystem.
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?
bool
isAuthenticated()
Have you successfully been logged in?
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
bool
_reconnect()
In situ reconnect method
_reset_connection(int $reason)
Resets a connection for re-use
string
_get_binary_packet($skip_channel_filter = false)
Gets Binary Packets
See '6. Binary Packet Protocol' of rfc4253 for more info.
string
_filter($payload, $skip_channel_filter)
Filter Binary Packets
Because some binary packets need to be ignored...
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
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|bool
_get_channel_packet(int $client_channel, bool $skip_extended = false)
Gets channel data
Returns the data as a string if it's available and false if not.
bool
_send_binary_packet(string $data, string $logged = null)
Sends Binary Packets
See '6. Binary Packet Protocol' of rfc4253 for more info.
_append_log(string $message_number, string $message)
Logs data packets
Makes sure that only the last 1MB worth of packets will be logged
bool
_send_channel_packet(int $client_channel, string $data)
Sends channel data
Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate
bool
_close_channel(int $client_channel, bool $want_reply = false)
Closes and flushes a channel
\phpseclib\Net\SSH2 doesn't properly close most channels. For exec() channels are normally closed by the server and for SFTP channels are presumably closed when the client disconnects. This functions is intended for SCP more than anything.
bool
_disconnect(int $reason)
Disconnect
string
_string_shift(string $string, int $index = 1)
String Shift
Inspired by array_shift
_define_array()
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.
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')
string
_format_log(array $message_log, array $message_number_log)
Formats a log for printing
string
_format_log_helper(array $matches)
Helper function for _format_log
For use with preg_replace_callback()
_on_channel_open()
Helper function for agent->_on_channel_open()
Used when channels are created to inform agent of said channel opening. Must be called after channel open confirmation received
mixed
_array_intersect_first(array $array1, array $array2)
Returns the first value of the intersection of two arrays or false if the intersection is empty. The order is defined by the first parameter.
string[]
getErrors()
Returns all errors
string
getLastError()
Returns the last error
string
getServerIdentification()
Return the server identification.
array
getKexAlgorithms()
Return a list of the key exchange algorithms the server supports.
array
getServerHostKeyAlgorithms()
Return a list of the host key (public key) algorithms the server supports.
array
getEncryptionAlgorithmsClient2Server()
Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client.
array
getEncryptionAlgorithmsServer2Client()
Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client.
array
getMACAlgorithmsClient2Server()
Return a list of the MAC algorithms the server supports, when receiving stuff from the client.
array
getMACAlgorithmsServer2Client()
Return a list of the MAC algorithms the server supports, when sending stuff to the client.
array
getCompressionAlgorithmsClient2Server()
Return a list of the compression algorithms the server supports, when receiving stuff from the client.
array
getCompressionAlgorithmsServer2Client()
Return a list of the compression algorithms the server supports, when sending stuff to the client.
array
getLanguagesServer2Client()
Return a list of the languages the server supports, when sending stuff to the client.
array
getLanguagesClient2Server()
Return a list of the languages the server supports, when receiving stuff from the client.
array
getServerAlgorithms()
Returns a list of algorithms the server supports
array
getSupportedKEXAlgorithms()
Returns a list of KEX algorithms that phpseclib supports
array
getSupportedHostKeyAlgorithms()
Returns a list of host key algorithms that phpseclib supports
array
getSupportedEncryptionAlgorithms()
Returns a list of symmetric key algorithms that phpseclib supports
array
getSupportedMACAlgorithms()
Returns a list of MAC algorithms that phpseclib supports
array
getSupportedCompressionAlgorithms()
Returns a list of compression algorithms that phpseclib supports
array
getAlgorithmsNegotiated()
Return list of negotiated algorithms
Uses the same format as https://www.php.net/ssh2-methods-negotiated
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.
Quoting from the RFC, "in some jurisdictions, sending a warning message before authentication may be relevant for getting legal protection."
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.
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.
_updateLogHistory(string $old, string $new)
Update packet types in log history
array|null
getAuthMethodsToContinue()
Return the list of authentication methods that may productively continue authentication.