1

I am trying to ssh to a remote server to check to see if a specific file exists.

I am able to ssh in the command line but whenever I try to with my script it does not return anything / I have to type "exit" and hit enter to get back to the command line.

Steps:

  1. ssh root@website.com
  2. cd ..
  3. ls ATMEXTRACT

I put all of these commands into ouputs so they look like this:

$output = shell_exec("ssh root@website.com");
$ouput1 = shell_exec("cd ..");
$ouput2 = shell_exec("ls *ATMEXTRACT*");

echo($output2);

I am confused as to why this works directly in the command line but is failing in the script. Any help is much appreciated

jww
  • 97,681
  • 90
  • 411
  • 885
  • This question would ideally be answered with a very long explanation about how shell_exec really works, and would explain your misunderstanding here. I don't know where to start on that, but in the meantime, for what you're doing, consider PHP's [SSH2 extension](https://www.php.net/manual/en/book.ssh2.php) – Andrew Oct 29 '19 at 22:01
  • Also consider PHP's FTP functions, and [this other question](https://stackoverflow.com/questions/1688564/php-directory-list-from-remote-server) – Andrew Oct 29 '19 at 22:03

2 Answers2

0

Here's what you do interactively:

  • Run ssh root@website.com in the current shell
    • Input cd .. in ssh
    • Input ls *ATMEXTRACT* in ssh
    • Input exit in ssh, which now exits
  • Find yourself back in your original shell

Here's what you do in your script:

  • Run ssh root@website.com in a new shell and exit it
  • Run cd .. in a second shell and exit it
  • Run ls *ATMEXTRACT* in a third shell and exit it

You could try to open and interact with an ssh command, but you can also just save yourself the trouble and use ssh's command line feature for specifying the commands to run:

$output = shell_exec("ssh root@website.com 'cd .. && ls *ATMEXTRACT*'");

Be aware that this is likely to fail from a PHP website script because you need to set up an authentication mechanism. This true even if ssh root@website.com connects without a password when you manually log in to the web server and try it.

that other guy
  • 116,971
  • 11
  • 170
  • 194
0

I would recommend you to use ssh2 module of PHP. This will help you to connect any remote server which is reachable through appropriate SSH PORT.

You will need to check, if few modules like OpenSSL and ssh2 are installed on your host server. if not please check this https://ehikioya.com/install-ssh2-php/ and install above modules.

once these modules are installed and enabled.

follow this code.

$server="website.com";  
$server_pwd="Password";

//creating connection using server credentials
$connection = ssh2_connect($server, 22);

//authenticating username and password
if(ssh2_auth_password($connection, 'root', $server_pwd)){
    echo "connected"
}else{

    echo "could not connect to server";
}

ssh2_exec($connection, "ls /FULL_PATH/ATMEXTRACT"); //run your command here