Sending commands is fairly straightforward. You just connect, authenticate, then execute commands. Authentication can be done using a password or public key. Executing commands is a little tricky since it returns a stream that you have to handle.
First, we need to connect:
Code: Select all
$ssh = ssh2_connect('127.0.0.1', 22);
Now we need to authenticate as a user. This can be done using a simple password or using a public key. I'll show you both methods:
Code: Select all
// Using a password
ssh2_auth_password($ssh, 'user', 'password');
// Using a public key
ssh2_auth_pubkey_file($ssh, 'user', '/var/www/.ssh/id_rsa.pub', '/var/www/.ssh/id_rsa', 'passphrase');
Now that we are connected and authenticated, we can send a command:
Code: Select all
// exec a command and return a stream
$stream = ssh2_exec($ssh, 'whoami');
// force PHP to wait for the output
stream_set_blocking($stream, true);
// read the output into a variable
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
// close the stream
fclose($stream);
// print the response
echo $data;
That's really all there is to it. The SSH2 extension can do many other things not covered in this tutorial, such as file transfers. It can be very useful when you want to automate some remote server administration tasks or something.
Here is a complete code example:
Code: Select all
<?php
if($ssh = ssh2_connect('127.0.0.1', 22)) {
if(ssh2_auth_password($ssh, 'user', 'password')) {
$stream = ssh2_exec($ssh, 'whoami');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data; // user
}
}
?>