en

Creating SSH connections with PHP

June 18, 2021

Tags: Managed Teams
php
Unsplash

 

SSH connections are very popular when you have VPS (Virtual Private Servers), all installations and configurations of our servers can be performed directly from the terminal with a root connection.

 

With PHP we can make SSH connections to these servers and execute commands from our local application or from another server, or we can schedule Cron Jobs to run a cleaning or download VPS backups to our machine.

 

Installing libssh2-php

 

We will install soport for SSH for PHP in Ubuntu 12.04 or later.

 

[prism:php]sudo apt-get install libssh2-1-dev libssh2-php[/prism:php]

 

Para verificar que está correctamente instalado:

 

[prism:php]php m |grep php[/prism:php]

 

If everything went right, it should return: ssh2

 

Our first connection

 

The first thing we should do is to verify the connection wiith ssh to php:

 

[prism:php]<?php if (!function_exists('ssh2_connect')) { die('No existe la funcion ssh2_connect.'); }[/prism:php]

 

If the function exists, we turn to verify that there can be an SSH connection to the server:

 

[prism:php]<?php if (!($connection = ssh2_connect('mivps.server.com', 22))) { die('No se puede conectar con el servidor VPS.'); }[/prism:php]

 

For this example, we will create the connection by username and password, remember that in this way we might have sensitive information available within our code and that is considered a security problem:

 

[prism:php]<?php if (!ssh2_auth_password($connection, 'root', 'mypassword')) { die('No se puede autenticar con el usuario y clave suministrados.'); }[/prism:php]

 

php

 

Our first command

 

If the connection is successful and we are within our VPS, we can execute our first command:

 

[prism:php]<?php if (!($exec = ssh_exec($connection, 'ls -l'))) { die('No se pudo ejecutar el comando.'); }[/prism:php]

 

If everything is correct, our first command ran on the server, but how do we know if it really worked?

 

To do this, let us first see how we can display VPS messages in our PHP console:

 

[prism:php]<?php if (!($exec = ssh_exec($connection, 'ls -l'))) { die('No se pudo ejecutar el comando.'); } else { stream_set_blocking($exec, true); $data = ''; while ($fread = fread($exec, 4096)) { $data .= $fread; } fclose($exec); }[/prism:php]

 

In the above code we use ssh_exec to execute the commands in the VPS terminal, but we can also use shel_exec:

 

[prism:php]<?php if (!$($shell_exec = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS))) { die('No se pudo ejecutar el comando'); }[/prism:php]

 

php

 

Connecting to the VPS with a public key

 

To make a little more secure our connection to our VPS we can use a public key.

 

In our computer terminal we run the following commands to create a pair of keys (private / public): [prism:php]cd ~/.ssh ssh-keygen[/prism:php]

 

We leave all the default values Once created our keys, we add an array as the third parameter to the connection and replace the ssh2_auth_password by the following:

 

[prism:php]<?php $connection = ssh2_connect('mivps.server.com', 22, array('hostkey' => 'ssh-rsa'));

 

if (ssh2_auth_pubkey_file($connection, 'root', 'home/nombredeusuario/.ssh/id_rsa.pub', 'home/nombredeusuario/.ssh/id_rsa')) { die('No se pudo realizar la conexión con el servidor.') }[/prism:php] With this we can run our VPS connections with SSH keys from PHP.

 

Conclusion

 

We can schedule and run many commands through SSH connections to maintain one or more servers from a PHP application located on our local server or another VPS.

 

Extra: SSH connection libraries

 

With these commands we can create SSH connections directly from our PHP, but there are already some libraries that ensure or improve these connections:

 

  • phpseclib: A library created in PHP that requires no additional libraries to create SSH connections.
  • Net_SSH2: PEAR connector.

 

We recommend you on video