3

Trying to connect to an Amazon EC2 instance using a .pem file, PHP, and phpseclib.

I have tried what's mentioned in this post: ssh access to ec2 from php

However, I keep getting "Error 111. Connection refused in..."

When I connect from my own machine using ssh and the same .pem file, there are no errors.

Here is the code from the original post that I am using:

include('Net/SSH2.php');
include('Crypt/RSA.php');

$key = new Crypt_RSA();

$key->loadKey(file_get_contents('/pathtokey.pem'));


$ssh = new Net_SSH2('ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com');
if (!$ssh->login('user', $key)) {
    exit('Login Failed');
}
Community
  • 1
  • 1
user883210
  • 94
  • 2
  • 10

2 Answers2

4

I just tested the sample code provided and it works with my Amazon EC2 Ubuntu instance.

You have to check the obvious as proposed:

  • Hostname
  • Username
  • PEM file path

Are they correct? Are you sure you are using the same ones that you use when connecting from your own machine?

If they are the same, are you testing the code from the same machine? If not, does the host from where you are running the code has the port 22 open for outbound connections?

adosaiguas
  • 1,331
  • 9
  • 13
  • I'm very sure all those obvious bases are covered. One note is that this is specifically for an FMS instance running CentOS. Not sure if that makes a difference. The outbound port issue does seem to be worth checking. Will come back after checking on that. – user883210 May 23 '12 at 04:05
  • According to my host, port 22 is open for outbound connections. What is strange, however, is that I can open an SSH connection through my terminal (local machine), but php (host) reports the same error 111 through either phpseclib's NET_SSH2 or directly through the fsockopen command used by phpseclib. – user883210 May 23 '12 at 06:59
  • 1
    looks like it was a host-specific problem, with a mis-informed support person responding to me the first time. port 22 was blocked by a hostgator firewall. This might help someone in the future: http://support.hostgator.com/articles/how-to-enable-fsockopen – user883210 May 23 '12 at 08:20
0

Obvious thing to check, is the port open and allowed for your user?

Try just doing:

wget ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:22

From the machine that's giving you trouble and see if you can open the socket.

I guess you may need to run that command through PHP with shell_exec() to make sure it's being called by the same user/security settings.

Danack
  • 24,939
  • 16
  • 90
  • 122