PHP SSH2 ssh2_connect

user3786515 picture user3786515 · Jul 26, 2014 · Viewed 10.8k times · Source

So I have taken a example from php.net to see php ssh2 workings

so the code is

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
?>

When I am putting wrong information it is giving me some error instead of telling me Authentication Failed.

The Error is

Warning: ssh2_connect(): php_network_getaddresses: getaddrinfo failed: Name not known in 
/var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/ssh2.php on line 2 Warning: ssh2_connect(): Unable to connect to 
shell.example.com on port 22 in /var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/login/ssh2.php on 
line 2 Warning: ssh2_connect(): Unable to connect to shell.example.com in 
/var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/login/ssh2.php on line 2  Warning: 
ssh2_auth_password() expects parameter 1 to be resource, boolean given in /var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/login/ssh2.php 
on line 4 Authentication Failed...

But when I am putting correct information it is not giving any error.

Answer

Trowski picture Trowski · Jul 26, 2014

The problem is that shell.example.com doesn't actually exist and the call to ssh2_connect() fails to return a resource.

Your code should be checking to see if ssh2_connect() successfully makes a connection and returns a resource before attempting to use the resource with ssh2_auth_password().

$connection = ssh2_connect('some.valid.ssh.host', 22);

if (!$connection) {
    throw new Exception("Could not connect to server.");
}

if (!ssh2_auth_password($connection, 'name', 'password')) {
    throw new Exception("Authentication failed!");
}

// SSH connection authenticated and ready to be used.