Pure-PHP implementation of SSHv2.
Methods
Default Constructor.
__construct(mixed $host,integer $port = 22,integer $timeout = 10)
$host can either be a string, representing the host, or a stream resource.
Arguments
Destructor.
__destruct()
Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
disconnect().
Logs data packets
append_log(string $message_number,string $message)
Makes sure that only the last 1MB worth of packets will be logged
Arguments
Logs data packet helper
append_log_helper(integer $constant,string $message_number,string $message,array &$message_number_log,array &$message_log, &$log_size, &$realtime_log_file, &$realtime_log_wrap, &$realtime_log_size)
Arguments
$message_number_log
array
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.
array_intersect_first(array $array1,array $array2): mixed
static
Arguments
Response
mixed
False if intersection is empty, else intersected value.
bad_algorithm_candidate
bad_algorithm_candidate( $algorithm)
static
Closes and flushes a channel
close_channel(integer $client_channel,boolean $want_reply = false): void
\phpseclib3\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.
Arguments
Connect to an SSHv2 server
connect()
|
|
|
|
Throws |
- \UnexpectedValueException
on receipt of unexpected packets - \RuntimeException
on other errors
|
Define Array
define_array(array<mixed,mixed> $args)
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.
Arguments
Disable request-pty when using exec()
disablePTY()
Disable Quiet Mode
disableQuietMode()
Disables "smart" multi-factor authentication (MFA)
disableSmartMFA()
Disconnect
disconnect_helper(integer $reason): false
Enable request-pty when using exec()
enablePTY()
Enable Quiet Mode
enableQuietMode()
Suppress stderr from output
Enables "smart" multi-factor authentication (MFA)
enableSmartMFA()
Maps an encryption algorithm name to an instance of a subclass of
\phpseclib3\Crypt\Common\SymmetricKey.
encryption_algorithm_to_crypt_instance(string $algorithm): \phpseclib3\Crypt\Common\SymmetricKey|null
static
Maps an encryption algorithm name to the number of key bytes.
encryption_algorithm_to_key_size(string $algorithm): integer|null
Arguments
$algorithm
string
Name of the encryption algorithm
Response
integer|null
Number of bytes as an integer or null for unknown
Execute Command
exec(string $command,callable $callback = null): string|boolean
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.
psalm-return
|
($callback is callable ? bool : string|bool) |
Throws |
- \RuntimeException
on connection error
|
Arguments
Response
string|boolean
Filter Binary Packets
filter(string $payload,boolean $skip_channel_filter): string|boolean
Because some binary packets need to be ignored...
see
|
self::_get_binary_packet() |
Arguments
$skip_channel_filter
boolean
Response
string|boolean
Generates the SSH identifier
generate_identifier(): string
You should overwrite this method in your own class if you want to use another identifier
Response
string
Gets Binary Packets
get_binary_packet(boolean $skip_channel_filter = false): boolean|string
See '6. Binary Packet Protocol' of rfc4253 for more info.
see
|
self::_send_binary_packet() |
Arguments
$skip_channel_filter
boolean
Response
boolean|string
Gets channel data
get_channel_packet(integer $client_channel,boolean $skip_extended = false): mixed
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
Throws |
- \RuntimeException
on connection error
|
Arguments
Response
mixed
Return the channel to be used with read() / write()
get_interactive_channel(): integer
Return an available open channel
get_open_channel(): integer
Return list of negotiated algorithms
getAlgorithmsNegotiated(): array
Return the list of authentication methods that may productively continue authentication.
getAuthMethodsToContinue(): array|null
see
|
https://tools.ietf.org/html/rfc4252#section-5.1 |
|
|
Response
array|null
Returns the banner message.
getBannerMessage(): string
Quoting from the RFC, "in some jurisdictions, sending a warning message before
authentication may be relevant for getting legal protection."
Response
string
Return existing connection
getConnectionByResourceId(string $id): boolean|\phpseclib3\Net\SSH2
static
Return all excising connections
getConnections(): \phpseclib3\Net\array<string,
static
Response
\phpseclib3\Net\arraySSH2>
Returns all errors
getErrors(): array<mixed,string>
Response
array<mixed,string>
Returns the exit status of an SSH command or false.
getExitStatus(): false|integer
Returns the last error
getLastError(): string
Returns a log of the packets that have been sent and received.
getLog(): array|false|string
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')
Response
array|false|string
Get Resource ID
getResourceId(): string
We use {} because that symbols should not be in URL according to
RFC.
It will safe us from any conflicts, because otherwise regexp will
match all alphanumeric domains.
Response
string
Returns a list of algorithms the server supports
getServerAlgorithms(): array
Return the server identification.
getServerIdentification(): string|false
Returns the server public host key.
getServerPublicHostKey(): string|false
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.
|
|
Throws |
- \RuntimeException
on badly formatted keys - \phpseclib3\Exception\NoSupportedAlgorithmsException
when the key isn't in a supported format
|
Response
string|false
Get the output from stdError
getStdError()
Returns a list of compression algorithms that phpseclib supports
getSupportedCompressionAlgorithms(): array
static
Returns a list of symmetric key algorithms that phpseclib supports
getSupportedEncryptionAlgorithms(): array
static
Returns a list of host key algorithms that phpseclib supports
getSupportedHostKeyAlgorithms(): array
static
Returns a list of KEX algorithms that phpseclib supports
getSupportedKEXAlgorithms(): array
static
Returns a list of MAC algorithms that phpseclib supports
getSupportedMACAlgorithms(): array
static
Returns the number of columns for the terminal window size.
getWindowColumns(): integer
Returns the number of rows for the terminal window size.
getWindowRows(): integer
Creates an interactive shell
initShell(): boolean
Have you successfully been logged in?
isAuthenticated(): boolean
Is the connection still active?
isConnected(): boolean
Returns whether request-pty is enabled or not
isPTYEnabled(): boolean
Returns whether Quiet Mode is enabled or not
isQuietModeEnabled(): boolean
Is timeout?
isTimeout()
Did exec() or read() return because they timed out or because they encountered the end?
Key Exchange
key_exchange(string|boolean $kexinit_payload_server = false): boolean
Throws |
- \UnexpectedValueException
on receipt of unexpected packets - \RuntimeException
on other errors - \phpseclib3\Exception\NoSupportedAlgorithmsException
when none of the algorithms phpseclib has loaded are compatible
|
Arguments
$kexinit_payload_server
string|boolean
optional
Response
boolean
Login via keyboard-interactive authentication
keyboard_interactive_login(string $username,string|array $password): boolean
See RFC4256 for details. This is not a full-featured keyboard-interactive authenticator.
Arguments
Response
boolean
Handle the keyboard-interactive requests / responses.
keyboard_interactive_process(string|array $responses): boolean
Throws |
- \RuntimeException
on connection error
|
Arguments
Response
boolean
Login
login(string $username,string|\phpseclib3\Crypt\Common\AsymmetricKey|array<mixed,array>|\phpseclib3\System\SSH\Agent|null $args): boolean
The $password parameter can be a plaintext password, a \phpseclib3\Crypt\RSA|EC|DSA object, a \phpseclib3\System\SSH\Agent object or an array
Arguments
Response
boolean
Login Helper
login_helper(string $username, $password = null,string|\phpseclib3\Crypt\Common\AsymmetricKey|array<mixed,array>|\phpseclib3\System\SSH\Agent|null $args): boolean
{@internal It might be worthwhile, at some point, to protect against traffic analysis
by sending dummy SSH_MSG_IGNORE messages.}
Throws |
- \UnexpectedValueException
on receipt of unexpected packets - \RuntimeException
on other errors
|
Arguments
Response
boolean
Maps an encryption algorithm name to an instance of a subclass of
\phpseclib3\Crypt\Hash.
mac_algorithm_to_hash_instance(string $algorithm): \phpseclib3\Net\array{Hash,
static
Arguments
$algorithm
string
Name of the encryption algorithm
Response
\phpseclib3\Net\array{Hash,
int}|null
Helper function for agent->on_channel_open()
on_channel_open()
Used when channels are created to inform agent
of said channel opening. Must be called after
channel open confirmation received
Pings a server connection, or tries to reconnect if the connection has gone down
ping(): boolean
Login with an RSA private key
privatekey_login(string $username,\phpseclib3\Crypt\Common\PrivateKey $privatekey): boolean
{@internal It might be worthwhile, at some point, to protect against traffic analysis
by sending dummy SSH_MSG_IGNORE messages.}
Throws |
- \RuntimeException
on connection error
|
Arguments
Response
boolean
Returns the output of an interactive shell
read(string $expect = '',integer $mode = self::READ_SIMPLE): string|boolean|null
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.
Arguments
Response
string|boolean|null
Read Remaining Bytes
read_remaining_bytes(integer $remaining_length): string
Arguments
$remaining_length
integer
Response
string
In situ reconnect method
reconnect(): boolean
Request agent forwarding of remote server
requestAgentForwarding(): boolean
Closes a channel
reset()
If read() timed out you might want to just close the channel and have it auto-restart on the next read() call
Resets a connection for re-use
reset_connection(integer $reason)
Sends Binary Packets
send_binary_packet(string $data,string $logged = null): void
See '6. Binary Packet Protocol' of rfc4253 for more info.
see
|
self::_get_binary_packet() |
Arguments
Sends channel data
send_channel_packet(integer $client_channel,string $data): void
Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate
Arguments
Send Identification String First
sendIdentificationStringFirst()
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
Send Identification String Last
sendIdentificationStringLast()
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
Send SSH_MSG_KEXINIT First
sendKEXINITFirst()
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
Send SSH_MSG_KEXINIT Last
sendKEXINITLast()
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
Set Crypto Engine Mode
setCryptoEngine(integer $engine)
static
Possible $engine values:
OpenSSL, mcrypt, Eval, PHP
Arguments
Set Keep Alive
setKeepAlive(integer $interval)
Sends an SSH2_MSG_IGNORE message every x seconds, if x is a positive non-zero number.
Arguments
Accepts an associative array with up to four parameters as described at
<https://www.php.net/manual/en/function.ssh2-connect.php>
setPreferredAlgorithms(array $methods)
Allows you to set the terminal
setTerminal(string $term)
Set Timeout
setTimeout(mixed $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.
Arguments
Sets the number of columns for the terminal window size.
setWindowColumns(integer $value)
Sets the number of rows for the terminal window size.
setWindowRows(integer $value)
Sets the number of columns and rows for the terminal window size.
setWindowSize(integer $columns = 80,integer $rows = 24)
Login with an ssh-agent provided key
ssh_agent_login(string $username,\phpseclib3\System\SSH\Agent $agent): boolean
Arguments
Response
boolean
Start a subsystem.
startSubsystem(string $subsystem): boolean
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.
Arguments
Response
boolean
Stops a subsystem.
stopSubsystem(): boolean
Login Helper
sublogin(string $username,string $args): boolean
see
|
self::_login_helper() |
Arguments
Response
boolean
updateLogHistory
updateLogHistory( $old, $new)
Inputs a command into an interactive shell.
write(string $cmd): void
Constants
No compression
NET_SSH2_COMPRESSION_NONE
zlib compression
NET_SSH2_COMPRESSION_ZLIB
zlib@openssh.com
NET_SSH2_COMPRESSION_ZLIB_AT_OPENSSH
MASK_CONSTRUCTOR
MASK_CONSTRUCTOR
MASK_CONNECTED
MASK_CONNECTED
MASK_LOGIN_REQ
MASK_LOGIN_REQ
MASK_WINDOW_ADJUST
MASK_WINDOW_ADJUST
CHANNEL_EXEC
CHANNEL_EXEC
CHANNEL_SHELL
CHANNEL_SHELL
CHANNEL_SUBSYSTEM
CHANNEL_SUBSYSTEM
CHANNEL_AGENT_FORWARD
CHANNEL_AGENT_FORWARD
CHANNEL_KEEP_ALIVE
CHANNEL_KEEP_ALIVE
Returns the message numbers
LOG_SIMPLE
Returns the message content
LOG_COMPLEX
Outputs the content real-time
LOG_REALTIME
Dumps the content real-time to a file
LOG_REALTIME_FILE
Outputs the message numbers real-time
LOG_SIMPLE_REALTIME
Make sure that the log never gets larger than this
LOG_MAX_SIZE
Returns when a string matching $expect exactly is found
READ_SIMPLE
Returns when a string matching the regular expression $expect is found
READ_REGEX
Returns whenever a data packet is received.
READ_NEXT
Some data packets may only contain a single character so it may be necessary
to call read() multiple times when using this option
Properties
The SSH identifier
identifier :string
The Socket Object
fsock :resource|\phpseclib3\Net\closed-resource|null
Type(s)
resource|\phpseclib3\Net\closed-resource|null
Execution Bitmap
bitmap :integer
The bits that are set represent functions that have been called already. This is used to determine
if a requisite function has been successfully executed. If not, an error should be thrown.
Type(s)
integer
Error information
errors :array
Server Identifier
server_identifier :string|false
Key Exchange Algorithms
kex_algorithms :array|false
Key Exchange Algorithm
kex_algorithm :string|false
Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
kex_dh_group_size_min :integer
Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
kex_dh_group_size_preferred :integer
Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
kex_dh_group_size_max :integer
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|false
Preferred Algorithms
preferred :array
Block Size for Server to Client Encryption
encrypt_block_size :integer
"Note that the length of the concatenation of 'packet_length',
'padding_length', 'payload', and 'random padding' MUST be a multiple
of the cipher block size or 8, whichever is larger. This constraint
MUST be enforced, even when using stream ciphers."
-- http://tools.ietf.org/html/rfc4253#section-6
Type(s)
integer
Block Size for Client to Server Encryption
decrypt_block_size :integer
Server to Client Encryption Object
decrypt :\phpseclib3\Crypt\Common\SymmetricKey|false
Decryption Algorithm Name
decryptName :string|null
Decryption Invocation Counter
decryptInvocationCounter :string|null
Fixed Part of Nonce
decryptFixedPart :string|null
Server to Client Length Encryption Object
lengthDecrypt :object
Client to Server Encryption Object
encrypt :\phpseclib3\Crypt\Common\SymmetricKey|false
Encryption Algorithm Name
encryptName :string|null
Encryption Invocation Counter
encryptInvocationCounter :string|null
Fixed Part of Nonce
encryptFixedPart :string|null
Client to Server Length Encryption Object
lengthEncrypt :object
Client to Server HMAC Object
hmac_create :object
Client to Server HMAC Name
hmac_create_name :string|false
Client to Server ETM
hmac_create_etm :integer|false
Server to Client HMAC Object
hmac_check :object
Server to Client HMAC Name
hmac_check_name :string|false
Server to Client ETM
hmac_check_etm :integer|false
Size of server to client HMAC
hmac_size :integer
We need to know how big the HMAC will be for the server to client direction so that we know how many bytes to read.
For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is
append it.
Type(s)
integer
Server Public Host Key
server_public_host_key :string
Session identifier
session_id :string
Exchange hash
exchange_hash :string
The current exchange hash
Type(s)
string
Message Numbers
message_numbers :array
Disconnection Message 'reason codes' defined in RFC4253
disconnect_reasons :array
SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254
channel_open_failure_reasons :array
Terminal Modes
terminal_modes :array
SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes
channel_extended_data_type_codes :array
Send Sequence Number
send_seq_no :integer
See 'Section 6.4. Data Integrity' of rfc4253 for more info.
Type(s)
integer
Get Sequence Number
get_seq_no :integer
See 'Section 6.4. Data Integrity' of rfc4253 for more info.
Type(s)
integer
Server Channels
server_channels :array
Maps client channels to server channels
Type(s)
array
Channel Buffers
channel_buffers :array
If a client requests a packet from one channel but receives two packets from another those packets should
be placed in a buffer
Type(s)
array
Channel Status
channel_status :array
Contains the type of the last sent message
Type(s)
array
Packet Size
packet_size_client_to_server :array
Maximum packet size indexed by channel
Type(s)
array
Message Number Log
message_number_log :array
Message Log
message_log :array
The Window Size
window_size :integer
Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB)
Type(s)
integer
What we resize the window to
window_resize :integer
When PuTTY resizes the window it doesn't add an additional 0x7FFFFFFF bytes - it adds 0x40000000 bytes.
Some SFTP clients (GoAnywhere) don't support adding 0x7FFFFFFF to the window size after the fact so
we'll just do what PuTTY does
Type(s)
integer
Window size, server to client
window_size_server_to_client :array
Window size indexed by channel
Type(s)
array
Window size, client to server
window_size_client_to_server :array
Window size indexed by channel
Type(s)
array
Server signature
signature :string
Verified against $this->session_id
Type(s)
string
Interactive Buffer
interactiveBuffer :string
Current log size
log_size :integer
Should never exceed self::LOG_MAX_SIZE
Type(s)
integer
Current Timeout
curTimeout :
Keep Alive Interval
keepAlive :
Real-time log file pointer
realtime_log_file :resource|\phpseclib3\Net\closed-resource
Type(s)
resource|\phpseclib3\Net\closed-resource
Real-time log file size
realtime_log_size :integer
Has the signature been validated?
signature_validated :boolean
Real-time log file wrap boolean
realtime_log_wrap :boolean
Flag to suppress stderr from output
quiet_mode :
Time of first network activity
last_packet :float
Exit status returned from ssh if any
exit_status :integer
Flag to request a PTY when using exec()
request_pty :boolean
Flag set while exec() is running when using enablePTY()
in_request_pty_exec :boolean
Flag set after startSubsystem() is called
in_subsystem :boolean
Contents of stdError
stdErrorLog :string
The Last Interactive Response
last_interactive_response :string
Keyboard Interactive Request / Responses
keyboard_requests_responses :array
Banner Message
banner_message :string
Quoting from the RFC, "in some jurisdictions, sending a warning message before
authentication may be relevant for getting legal protection."
Type(s)
string
Did read() timeout or return normally?
is_timeout :boolean
Log Boundary
log_boundary :string
Log Long Width
log_long_width :integer
Log Short Width
log_short_width :integer
Port Number
port :integer
Number of columns for terminal window size
windowColumns :integer
Number of columns for terminal window size
windowRows :integer
Crypto Engine
crypto_engine :integer
static
A System_SSH_Agent for use in the SSH2 Agent Forwarding scenario
agent :\phpseclib3\System\SSH\Agent
Connection storage to replicates ssh2 extension functionality:
{@link http://php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-examples}
connections :\phpseclib3\Net\array<string,
static
Type(s)
\phpseclib3\Net\array
Send the identification string first?
send_id_string_first :boolean
Send the key exchange initiation packet first?
send_kex_first :boolean
Some versions of OpenSSH incorrectly calculate the key size
bad_key_size_fix :boolean
Should we try to re-connect to re-establish keys?
retry_connect :boolean
Binary Packet Buffer
binary_packet_buffer :string|false
Authentication Credentials
auth :array
The authentication methods that may productively continue authentication.
auth_methods_to_continue :array|null
Compression method
compress :integer
Decompression method
decompress :integer
Compression context
compress_context :resource|false|null
Type(s)
resource|false|null
Decompression context
decompress_context :resource|object
Regenerate Compression Context
regenerate_compression_context :boolean
Regenerate Decompression Context
regenerate_decompression_context :boolean
Smart multi-factor authentication flag
smartMFA :boolean