phpsshcmdputty

How to get result from a command executed in PHP on remote SSH server using PuTTY?


I'm trying to execute a command on my Raspberry Pi via SSH and get the result of it in my PHP script on my Windows machine. Currently I can execute the command on my RasPi, but I do not get any results back into the PHP script.

The code I'm Using for this:

<?php

$cmd = "C:\\path_to_putty\\putty.exe -ssh pi@RasPiIP -pw raspberry -m C:\\path_to_test.txt\\test.txt";
$result = shell_exec($cmd);
echo $result;

?>

For sending commands to my RasPi the code works. I have tested multiple times by as example changing test.txt to sudo reboot and it worked as intended. I'm using PuTTY to send my command (test.txt is currently nfc-list which returns connected Scanners etc not important right here) to the RasPi.

What I want to achieve is that $result contains the returned data when my command is executed.

Is it even possible to do that? If yes how (any help appreciated). If no, are they maybe other ways to approach this?

Addressing the possible duplicate: I am using a Windows Machine and also I'm trying to get the result (of the one command) to reuse in my PHP script. In the other question, user is trying to save the full console log and save it to another file.


Solution

  • First, do not use PuTTY. PuTTY is a GUI application intended for an interactive use. Use Plink, which is command-line/console equivalent of PuTTY intended for command automation. Being a console application, it has a standard output, which can be read in PHP (PuTTY as a GUI application does not have standard output).

    With Plink, you can also specify the command on Plink command line, so you do not need to create the test.txt command file.

    In any case, there's no way to make PuTTY or Plink separate an output of command only (at least not from a command-line).

    But what you can do, is to print some header/trailer to distinguish the start and end of the command output, like:

    plink.exe -ssh pi@RasPiIP -pw raspberry "echo start-of-command && command && echo end-of-command"
    

    And then in PHP, you can look for the start-of-command and end-of-command to identify what part of Plink output is really the command output.


    In any case, you better use a PHP SSH library to achieve what you want, rather than driving an external application. For example phpseclib. But that's a completely different question.