简体   繁体   中英

Executing shell commands via PHP?

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

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.

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 

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