Completed
Push — master ( 3a6611...ffb15c )
by Kamil
14:16
created

ssh_async_multi_command.php ➔ executeCommand()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 2
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * ---------------------------------------------------------------------------------------------------------------------
5
 * DESCRIPTION
6
 * ---------------------------------------------------------------------------------------------------------------------
7
 * This file contains the example of executing set of multiple commands.
8
 * ---------------------------------------------------------------------------------------------------------------------
9
 */
10
11
require __DIR__ . '/../vendor/autoload.php';
12
13
use Dazzle\Loop\Model\SelectLoop;
14
use Dazzle\Loop\Loop;
15
use Dazzle\SSH\Auth\SSH2Password;
16
use Dazzle\SSH\SSH2;
17
use Dazzle\SSH\SSH2Config;
18
use Dazzle\SSH\SSH2DriverInterface;
19
use Dazzle\SSH\SSH2Interface;
20
use Dazzle\SSH\SSH2ResourceInterface;
21
22
function executeCommand(SSH2DriverInterface $shell, $shellCommand) {
23
24
    $buffer = '';
25
    $command = $shell->open();
26
    $command->write($shellCommand);
27
    $command->on('data', function(SSH2ResourceInterface $command, $data) use(&$buffer) {
28
        $buffer .= $data;
29
    });
30
    $command->on('end', function(SSH2ResourceInterface $command) use(&$buffer) {
31
        echo "# COMMAND RETURNED:\n";
32
        echo $buffer;
33
        $command->close();
34
    });
35
}
36
37
$user = getenv('TEST_USER') ? getenv('TEST_USER') : 'Dazzle';
38
$pass = getenv('TEST_PASS') ? getenv('TEST_PASS') : 'Dazzle-1234';
39
40
$loop   = new Loop(new SelectLoop);
41
$auth   = new SSH2Password($user, $pass);
42
$config = new SSH2Config();
43
$ssh2   = new SSH2($auth, $config, $loop);
44
45
$ssh2->on('connect:shell', function(SSH2DriverInterface $shell) use($ssh2, $loop) {
46
    echo "# CONNECTED SHELL\n";
47
48
    $commands = [ 'ls -la', 'pwd' ];
49
    $commandsRemain = count($commands);
50
51
    $shell->on('resource:close', function(SSH2DriverInterface $shell) use(&$commandsRemain) {
52
        if (--$commandsRemain === 0) {
53
            $shell->disconnect();
54
        }
55
    });
56
57
    foreach ($commands as $command) {
58
        executeCommand($shell, $command);
59
    }
60
});
61
62
$ssh2->on('disconnect:shell', function(SSH2DriverInterface $shell) use($ssh2) {
63
    echo "# DISCONNECTED SHELL\n";
64
    $ssh2->disconnect();
65
});
66
67
$ssh2->on('connect', function(SSH2Interface $ssh2) {
68
    echo "# CONNECTED\n";
69
    $ssh2->createDriver(SSH2::DRIVER_SHELL)
70
         ->connect();
71
});
72
73
$ssh2->on('disconnect', function(SSH2Interface $ssh2) use($loop) {
74
    echo "# DISCONNECTED\n";
75
    $loop->stop();
76
});
77
78
$loop->onTick(function() use($ssh2) {
79
    $ssh2->connect();
80
});
81
82
$loop->start();
83