简体   繁体   中英

SSH2 in PHP to connect to remote server

I'm using the following code to connect locally using SSH2, but I'm trying to work out how public/private keys are handled when connecting to a remote server.

$SSH_CONNECTION = ssh2_connect('localhost', 22, array('hostkey'=>'ssh-rsa'));
ssh2_auth_pubkey_file($SSH_CONNECTION, 'username','/path/to/id_rsa.pub','/path/to/id_rsa')

If I'm connecting to a remote server, does there need to be a key file (public or private?) on the remote server, and how do I reference it? I'm not sure if the code is the same or exactly how it works.

Appreciate any explanation.

In order for the remote server to accept the keys, you need to put a copy of the public key in a file called authorized_keys in the .ssh directory in the home folder of the user you are logging in as.

So to authenticate as bob on a remote server, you would have a file called authorized_keys in /home/bob/.ssh on the remote with the public key in it (eg ssh-rsa AAAA..<long-string-of-text>..cXrTp bob@host ) (you can have more than one authorized keys, each one goes on it's own line in the file).

The id_rsa and id_rsa.pub files need to be on the client system where you call ssh2_auth_pubkey_file and readable by your PHP script.

This article about SSH Keys gives a good explanation about how to generate a keypair for key based authentication and how you can transfer the key to the host as well.

Without the public key in the authorized_keys file for the user you are trying to authenticate as, the authentication will not work.

Also, be sure to take the necessary security precautions by protecting the private key with a passphrase, making the private key unreadble by other users on the system, and protecting the passphrase in your script or controlling access to the file your script will read it from if it will be stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM