简体   繁体   中英

file_get_contents doesn't work with SSH Tunnel

I have created an tunnel(SSH) in order to access URL's that are blocked from my local PC. This works really well, I can for example access from the browser this url http://localhost:8888 and I will get the intended content. This URL also works with the REST Client that I'm using for testing. However, if I call it from PHP:

file_get_contents('http://localhost:8888') 

I get this error each time: failed to open stream: Connection refused

So my guess is that file_get_contents doesn't work well with SSH tunnels. Is there maybe an alternative function that I could use for this purpose ?

I solved this problem using php-ssh2 package.

Instalation on Ubuntu 16

sudo apt-get install php-ssh2

Usage with user name and password:

$conn = ssh2_connect($ip, 22);
ssh2_auth_password($conn, $user,$pass);
ssh2_scp_recv($conn, '/remote_path', '/local_path');

Usage with id_rsa (after ssh-copy-id)

I recommend use this method because of we probably do not want paste plain password in source code.

$conn = ssh2_connect($ip, 22);
ssh2_auth_pubkey_file($conn, $user,
    "/home/{$user}/.ssh/id_rsa.pub",
    "/home/{$user}/.ssh/id_rsa", 'secret')
ssh2_scp_recv($conn, '/remote_file', '/local_file');

Additional info

Old name of this package: libssh2-php

Docs:

http://php.net/manual/en/function.ssh2-scp-recv.php

Connected question:

How to SFTP with PHP?

Is there also possibility of use:

file_get_contents("ssh2.sftp://{$user}:{$pass}@{$ip}:22{$remote_path}"))

but I do not know how to use it with id_rsa.pub .

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