phpseclib - exit callback?

1.2k views Asked by At

I'm using this code from the SSH2 examples:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

function packet_handler($str)
{
    echo $str;
}

$ssh->exec('ping 127.0.0.1', 'packet_handler');
?>

This working well, but I want to quit the stream after xx seconds.

So I've amended it as follows :

<?php
include('Net/SSH2.php');
$st = time();
$dur = 10;

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

function packet_handler($str)
{
    global $st, $dur, $ssh;
    echo $str;
    $now = ceil(time() - $st);
    if ($now >= $dur) { $ssh->disconnect(); unset($ssh); }
}

$ssh->exec('ping 127.0.0.1', 'packet_handler');
?>

This works and exits packet handler, BUT I get the folllowing notices being shown:

Notice: Connection closed prematurely in SSH2.php on line 2676

Notice: Connection closed by server in SSH2.php on line 2959

Can anyone advise how I can close this connection without the notice messages?

1

There are 1 answers

1
Alex Andrei On BEST ANSWER

you can either ignore the notices, prevent them from displaying from php.ini or go about it without a callback, using php sleep(x) seconds and that's about it.

$ssh->enablePTY(); 
$ssh->exec("ping 127.0.0.1"); //run the ping
sleep(3); // sleep for 3 seconds
$ssh->write("\x03"); //send CTRL+C to terminate the ping command

print $ssh->read(); // dump the output

$ssh->disconnect(); unset($ssh); //disconnect