Запустите удаленный сервис через PHP - PullRequest
0 голосов
/ 29 апреля 2018

В основном я хочу передавать различные команды на сервер через функцию PHP ssh2_connect. Но мне нужно пройти через использование разных кнопок для разных команд, но я не могу этого сделать.

Ниже мой код с кнопкой:

<?php
$connection = ssh2_connect('ipaddress', 22);
ssh2_auth_password($connection, 'root', 'password');

if (isset($_POST['button'])) ssh2_exec($stream = ssh2_exec($connection, 'systemctl stop apache2'));
?>
<form action="" method="post">
<button type="submit" name="button">Apache2</button

Код работает без кнопки:

<?php
$connection = ssh2_connect('ipaddress', 22);
ssh2_auth_password($connection, 'root', 'password');
$stream = ssh2_exec($connection, 'systemctl stop apache2');

1 Ответ

0 голосов
/ 29 апреля 2018

Пара вещей:

  • Ваши коды не завершены, отсутствует остальная часть HTML.
  • Ваше вложение ssh2_exec($stream = ssh2_exec(, скорее всего опечатка.
  • Ваш Apache не запускается.

Следующее поможет вам начать, надеюсь, это поможет.

<code><?php
class ssh {

    public function __construct($ip, $user, $pass, $port = 22)
    {
        // connect
        $this->connection = ssh2_connect($ip, $port);
        ssh2_auth_password($this->connection, $user, $pass);
    }

    public function exec($cmd = null)
    {
        // define streams
        $this->stream = ssh2_exec($this->connection, $cmd);
        $this->err_stream = ssh2_fetch_stream($this->stream, SSH2_STREAM_STDERR);

        // get streams
        $this->output = stream_get_contents($this->stream);
        $this->error = stream_get_contents($this->err_stream);

        return $this;
    }
}

// define cmds
$commands = [
    'stop_apache' => [
        'description' => 'Stop Apache2',
        'cmd' => 'systemctl stop apache2'
    ],
    'restart_apache' => [
        'description' => 'Restart Apache2',
        'cmd' => 'systemctl restart apache2'
    ],
    'start_apache' => [
        'description' => 'Start Apache2',
        'cmd' => 'systemctl start apache2'
    ]
];

// handle post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $error = [];
    $result = '';

    // validate input
    if (empty($_POST['service'])) {
        $error = [
            'service' => 'Service type required!'    
        ];
    } elseif (!array_key_exists($_POST['service'], $commands)) {
        $error = [
            'service' => 'Invalid Service!'    
        ];
    }

    // run cmd - $result->output will have stdout, $result->error will have stderr
    if (empty($error)) {
        $ssh = new ssh('127.0.0.1', 'root', 'password');
        $result = $ssh->exec($commands[$_POST['service']]['cmd']);
    }
}
?>

<form action="" method="post">
    <?php if (!empty($error)): ?>
    <h3>Error</h3>
    <pre><?= print_r($error, true) ?>
<? php endif?> <? php foreach ($ commands as $ key => $ command):?> <? php endforeach?> <? php if (! empty ($ result)):?>
<?= print_r($result, true) ?>
<? php endif?>
...