ssh2_auth_pubkey_file() is broken when the public key file is protected with a password AND libssh2 is compiled with libgcrypt, which is what debian/ubuntu and probably others do. I’m working on a solution for this bug, but if you need this working rebuild libssh2 yourself with OpenSSL.

A workaround may be to store the private key unencrypted. To decrypt the key:

openssl rsa -in id_rsa -out id_rsaNOPASSWORD

and then use the file id_rsaNOPASSWORD without supplying the fifth parameter ‘passphrase’. It works, but you’ll have to be careful with your decrypted key file. Anyway, the level of security is not really terribly affected, because even with an encrypted key, you would still need to pass the passphrase unencrypted to the ssh2_auth_pubkey_file function …

Hope it helps.

===================

Establishing a Connection

Let’s begin by connecting to an SSH service. Establishing a connection is as simple as:

1

<?php

2

$conn= ssh2_connect('example.com', 22);

3

ssh2_auth_password($conn, 'username', 'password');

Some administrators prefer using public and private keys to authenticate logins. If the service is configured and you want to connect in this way, you would use the following instead:

1

<?php

2

$conn= ssh2_connect('example.com', 22);

3

ssh2_auth_pubkey_file(

4

$conn,

5

'username',

6

'/home/username/.ssh/id_rsa.pub',

7

'/home/username/.ssh/id_rsa'

8

);

Whether you use username/password or public/private key authentication,ssh2_auth_password() and ssh2_auth_pubkey_file() both return a Boolean value indicating whether authentication was successful.

Performing Basic Commands

Once you have successfully authenticated with the server, you can perform your file transfer operations. The SCP functions let you send or receive a file(s) like so:

1

<?php

2

// send a file

3

ssh2_scp_send($conn, '/local/filename', '/remote/filename', 0644);

4

5

// fetch file

6

ssh2_scp_recv($conn, '/remote/filename', '/local/filename');

ssh2_scp_send() has an additional parameter which you can specify what the file permission should be on the remote server when the file is copied.

More functionality is available with the SFTP functions; you can change file or directory permissions, fetch information about a file, create directories, rename items, remove items, etc. They work quite similar to the SCP functions above, but an additional connect via ssh2_sftp()must be made prior to using the functions:

ssh2_sftp() accepts the connection resource and returns an SFTP resource which is used in future ssh2_sftp_* calls. The calls then return a Boolean which allows you to determine whether the action was successful.

Using Wrapper Functions

When a specific file management function doesn’t exist for SFTP or SCP, generally the core file system function will work using a stream wrapper. Below are a few examples:

Before performing any of these calls, the connection to the SSH and SFTP server must be made as it uses the previously created $sftp variable.

Bring It All Together

Now that you are able to connect, authenticate, and run commands on an SSH server, we can create a few helper classes to simplify the process of executing these commands: one for performing SCP calls and one for SFTP calls, a parent class for common functionality, and a couple classes for encapsulating authentication information (password and keys).

Let’s create the authentication classes first since they will be used the other classes.

1

<?php

2

classSSH2Authentication

3

{

4

}

01

<?php

02

classSSH2Password extendsSSH2Authentication

03

{

04

protected$username;

05

protected$password;

06

07

publicfunction__construct($username, $password) {

08

$this->username = $username;

09

$this->password = $password;

10

}

11

12

publicfunctiongetUsername() {

13

return$this->username;

14

}

15

16

publicfunctiongetPassword() {

17

return$this->password;

18

}

19

}

01

<?

02

classSSH2Key extendsSSH2Authentication

03

{

04

protected$username;

05

protected$publicKey;

06

protected$privateKey;

07

08

publicfunction__construct($username, $publicKey, $privateKey) {

09

$this->username = $username;

10

$this->password = $password;

11

}

12

13

publicfunctiongetUsername() {

14

return$this->username;

15

}

16

17

publicfunctiongetPublicKey() {

18

return$this->publicKey;

19

}

20

21

publicfunctiongetPrivateKey() {

22

return$this->privateKey;

23

}

24

}

SSH2Password and SSH2Key simply wrap their respective authentication information. They share a common base class so we can take advantage of PHP’s type hinting when we pass instances to their consumers.

Moving on, let’s create an SSH2 to connect and authenticate with the SSH server.

A very simple SCP class will be created that extends SSH2 and will make use of the magic method __call(). This allows us to do two important things: automatically prepend “ssh_scp_” to the function call and supply the connection variable to the call.

01

<?php

02

classSSH2SCP extendsSSH2

03

{

04

publicfunction__call($func, $args) {

05

$func= 'ssh2_scp_'. $func;

06

if(function_exists($func)) {

07

array_unshift($args, $this->conn);

08

returncall_user_func_array($func, $args);

09

}

10

else{

11

thrownewException(

12

$func. ' is not a valid SCP function');

13

}

14

}

15

}

The SFTP class is quite similar, although its constructor is overloaded to also execute thessh2_sftp() function. The results are stored in a protected variable and automatically prepended to all SFTP function calls.

Once these classes are created they can be used to execute SCP and SFTP function calls. Thanks to the useful __call methods in both classes, we don’t need to pass the open connection or repeatedly type “ssh2_scp_” or “ssh2_ftp_” with each call.

01

<?php

02

// Create SCP connection using a username and password

03

$scp= newSCP(

04

'example.com',

05

newSSH2Password('username', 'password')

06

);

07

// Receive a file via SCP

08

if($scp->recv('remote/file', 'local/file')) {

09

echo'Successfully received file';

10

}

11

12

// Create SFTP connection using a public/private key

13

$sftp= newSSH2SFTP(

14

'example.com',

15

newSSH2Key('username', 'public_key', 'private_key')

16

);

17

// Create a directory via SFTP

18

if($sftp->mkdir('directory/name')) {

19

echo'Successfully created directory';

20

}

Summary

Installing the SSH2 PHP extension, it provides your scripts with the ability to connect to SSH2 servers. You can either leverage the handy classes that simplify the code for performing SFTP or SCP calls, or if a specific function isn’t provided by the library, most core file system operations can be used by leveraging the SSH2 wrapper functionality.