简体   繁体   中英

PHP ssh2_exec() not working

I want connect and run command on a remote device with SSH from my server. When I try the command in SSH client like Putty, it works flawlessly. But when I write it using a PHP script, the command will not be executed. Any ideas?

<?php
  $host = "192.168.0.184";
  $user = "user";
  $password = "password";
  $cmd = "reboot";
  $ssh = ssh2_connect($host);
  $sshLogin = ssh2_auth_password($ssh, $user, $password);
  $sshExec = ssh2_exec($ssh, $cmd);
?>

In device log, I can see user is authenticated successfully but nothing else.

I solved my problem with this code... used interactive shell with sleep after command. And working OK.

<?php
        echo "SSH connection: ";
        if (!($resource=@ssh2_connect("your_host"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        echo "Athetication: ";
        if (!@ssh2_auth_password($resource,"your_user","your_password")) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        echo "Shell: ";
        if (!($stdio = @ssh2_shell($resource,"xterm"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";
        $command = "reboot\n";
        fwrite($stdio,$command);

        sleep(1);

        while($line = fgets($stdio)) {
                flush();
                echo $line."<br />";
        }

        fclose($stdio);
?>

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