phpbatch-filewampexecplink

Plink fails to run when executed from PHP in wamp, but works when executed manually


I need to access a Linux machine from Windows 7 via PHP.

For that I created simple bat (MyScript.bat) script containing plink.

c:\wamp\www\abc\plink.exe user1@192.168.70.128 -pw l1c -C "df -h">11.txt

When I am executing the bat script, it's working fine, i.e. the output is written in file 11.txt

But when I am accessing it from PHP, the 11.txt is created without data

echo exec('MyScript.bat');

Moreover, in browser, the script commands are displayed as text. I even tried to use print_r for the display.

"c:\wamp\www\abc\plink.exe user1@192.168.70.128 -pw l1c -C "df -h">11.txt

Solution

  • Do not launch external tool for SSH.

    PHP has native support for SSH.

    Or use phpseclib:

    require __DIR__ . '/vendor/autoload.php';
    
    use phpseclib\Net\SSH2;
    
    $ssh = new SSH2($hostname);
    if ($ssh->login($username, $password))
    {
        echo $ssh->exec("df -h");
    }
    

    See:


    Anyway, if you want to use Plink, redirect also the standard error output to debug your problem:

    plink.exe .. dir > 11.txt 2>&1
    

    See How to redirect Windows cmd stdout and stderr to a single file?.

    You are for sure missing the -hostkey switch to explicitly specify a fingerprint of the trusted hostkey.