Unable to establish connection using ssh2_connect() in PHP

Updated on December 21, 2021

I have used the ssh2_connect() function to establish a connection to a remote SSH server. But it works on one webserver and fails on another (let’s call it as webserver1 and webserver 2 hereafter).  I get this error – unable to establish connection error on webserver2. Both the webservers 1 & 2 are identical setups running Apache and what’s is strange is that the issue occured only after the reboot of the webserver2. The complete apache error_log of webserver2 is as follows:

ssh2_connect: unable to establish connection

[Wed Dec 15 10:30:35 2021] [error] [client 192.168.xxx.xx] PHP Warning:  ssh2_connect(): Unable to connect to 192.168.xx.xxx on port 22 in /var/www/html/process.php on line 9
[Wed Dec 15 10:30:35 2021] [error] [client 192.168.xxx.xx] PHP Warning:  ssh2_connect(): Unable to connect to 192.168.xx.xxx in /var/www/html/process.php on line 9

Below is the PHP-script:

if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
     if(!($con = ssh2_connect(REMOTE_IP, 22))){
           echo "fail: unable to establish connection\n";
     } else  {
          // try to authenticate with username root, password secretpassword
          if(!ssh2_auth_password($con, $username, $password)) {
                 echo "fail: unable to authenticate\n";
                 header('Location: ../../login/?error=1');
                 exit();
           } else {
                 echo "Logged in..\n";
           }
     }

How to solve ssh_connect() : unable to establish connection

Step 1: Check for the firewall on the remote server. A firewall rule might be blocking the connections from webserver2.

Step 2: Lets test the SSH from terminal of webserver2 as below:

# ssh <username>@<REMOTE_IP> -p 22

Step 3: If the above SSH command works, then check if SELinux is enabled. If enabled, make sure to bypass SELinux for web directories as it might be blocking.

Step 4: By default, SELinux prevents Apache web server from establishing network connections.

Don't disable SELinux!

On CentOS 7, SELinux is enabled by default. SELinux improves server security by restricting and defining how a server processes requests and users interact with sockets, network ports, and essential directories. It is not recommended to disable SELinux for security reasons as you will be allowing the entire system to be compromised.

Run the below command to allow HTTPD scripts and modules to connect to the network using any TCP port.

#  /usr/sbin/setsebool -P httpd_can_network_connect 1

That’s it!

Was this article helpful?

Related Articles

Leave a Comment