удаление управления удаленными хостами

This commit is contained in:
rsgrinko committed 2026-07-24 19:26:24 +03:00
1 parent 83c2d29f68
commit dc29aade3a
5 files changed
+1 -450

No files matched your search

+1 -2
View File
@@ -199,8 +199,7 @@ callback). `$callback` — это либо строка `'\Core\App::method'`,
### Внешние сервисы (`core/lib/Core/ExternalServices/`)
Тонкие клиенты для Telegram (`Telegram`, `Telegram2`, `TelegramSender`, `TelegramActions` — обратите внимание, есть
параллельные/устаревшие варианты, проверяйте, какой реально подключён, прежде чем расширять), `ChatGPT`,
`RemoteHosts`, а также пара HTTP `Request`/`RequestOLD` (для нового кода предпочитайте `Request/`, а не вариант
OLD).
а также пара HTTP `Request`/`RequestOLD` (для нового кода предпочитайте `Request/`, а не вариант OLD).
### Константы конфигурации
`core/config.php` определяет всю конфигурацию времени выполнения как глобальные константы (`DB_HOST`, `CACHE_*`,
-51
View File
@@ -1,51 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\ExternalServices\RemoteHosts;
require_once __DIR__ . '/../inc/bootstrap.php';
if(!isset($_REQUEST['hosts'])) {
die('Площадки не выбраны');
}
if(!isset($_REQUEST['cmd'])) {
die('Команда не задана');
}
$hostsList = $_REQUEST['hosts'];
$cmd = $_REQUEST['cmd'];
$result = [];
foreach($hostsList as $host) {
$objectHost = new RemoteHosts();
$objectHost->selectHost((int)$host);
$result[(int)$host] = [
'host' => $objectHost->getHostData(),
'result' => $objectHost->$cmd(),
];
unset($objectHost);
}
echo '<pre>';
print_r($result);
echo '</pre>';
-129
View File
@@ -1,129 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Helpers\Pagination;
use Core\ExternalServices\RemoteHosts;
use Core\SystemConfig;
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
?>
<div class="pageheader">
<div class="media">
<div class="pageicon pull-left">
<i class="fa fa-home"></i>
</div>
<div class="media-body">
<ul class="breadcrumb">
<li><a href=""><i class="glyphicon glyphicon-home"></i></a></li>
<li>Список удаленных площадок</li>
</ul>
<h4>Список площадок</h4>
</div>
</div><!-- media -->
</div><!-- pageheader -->
<div class="contentpanel">
<!-- table -->
<div class="row">
<div class="col-md-12r">
<form id="hostsForm">
<div class="table-responsive">
<table class="table table-primary table-hover mb30">
<thead>
<tr>
<th>Выбор</th>
<th>ID</th>
<th>Статус</th>
<th>URL</th>
<th>Название</th>
<th>Hostname</th>
<th>Дата создания</th>
<th>Дата обновления</th>
</tr>
</thead>
<tbody>
<?php
Pagination::execute($_REQUEST['page'], RemoteHosts::getAllCount(), SystemConfig::getValue('PAGINATION_LIMIT'));
$limit = Pagination::getLimit();
$arHosts = RemoteHosts::getHosts($limit);
foreach ($arHosts as $elHost) {
$hostObject = (new RemoteHosts())->selectHost($elHost['id']);
?>
<tr>
<td><input type="checkbox" name="hosts[]" value="<?= $elHost['id'] ?>"></td>
<td><?= $elHost['id'] ?></td>
<td><?php if ($hostObject->isOnline()) { ?>
<span class="badge badge-success">Online</span></td>
<?php } else { ?>
<span class="badge badge-danger">Offline</span></td>
<?php } ?>
<td><?= $elHost['url'] ?></td>
<td><?= $elHost['name'] ?></td>
<td><?= $hostObject->getHostname() ?></td>
<td><?= $elHost['date_created'] ? date('d.m.Y H:i:s', strtotime($elHost['date_created'])) : '-'; ?></td>
<td><?= $elHost['date_updated'] ? date('d.m.Y H:i:s', strtotime($elHost['date_updated'])) : '-'; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div><!-- table-responsive -->
<select name="cmd" class="form-control">
<option value="getUname">uname -a</option>
<option value="getUptime">uptime</option>
<option value="getHostname">hostname</option>
<option value="gethostInfo">Получить информацию о площадке</option>
</select>
<button class="btn btn-success form-control" id="execute">Выполнить</button>
</form>
<div class="result" id="result"></div>
<?php Pagination::show('page') ?>
</div>
</div>
<!-- end table -->
</div><!-- contentpanel -->
<script>
$(document).ready(function(){
var resultBox = $('#result');
$('#hostsForm').on('submit', function (e) {
e.preventDefault();
$.post(
'./ajax/executeRemoteHost.php',
$('#hostsForm').serialize(),
function(data) {
resultBox.html(data);
}
);
});
});
</script>
<?php require_once __DIR__ . '/inc/footer.php'; ?>
-1
View File
@@ -254,7 +254,6 @@
<li><a href="/admin/users.php"><i class="fa fa-home"></i> <span>Список пользователей</span></a></li>
<li><a href="/admin/groups.php"><i class="fa fa-home"></i> <span>Список ролей</span></a></li>
<li><a href="/admin/cacheInfo.php"><i class="fa fa-home"></i> <span>Кэширование</span></a></li>
<li><a href="/admin/hosts.php"><i class="fa fa-home"></i> <span>Управление хостами</span></a></li>
<li><a href="/admin/threads.php"><i class="fa fa-home"></i> <span>Диспетчер очереди</span></a></li>
<li><a href="/admin/phpcmd.php"><i class="fa fa-home"></i> <span>Командная PHP строка</span></a></li>
<li><a href="/admin/nginx.php"><i class="fa fa-home"></i> <span>Логи nginx</span></a></li>
@@ -1,267 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Класс для управления удаленными хостами
*
* @version 1.0.1
* @author Roman Grinko <rsgrinko@gmail.com>
*/
namespace Core\ExternalServices;
use Core\CoreException;
use Core\Database\DataBase;
class RemoteHosts
{
private const TABLE = 'remote_hosts';
private ?int $selectedHostId;
private array $selectedHostParams = [];
/** @var string $method Метод */
private string $method;
/** @var array $params Параметры */
private array $params = [];
/** @var int $httpCode Код ответа */
private int $httpCode = 0;
/** @var array $response Ответ */
private array $response = [];
public function __construct()
{
}
/**
* @throws CoreException
*/
public static function getHosts(string $limit = '10', string $sort = 'ASC'): array
{
/** @var DataBase $DB Объект БД */
$DB = DataBase::getInstance();
// ORDER BY/LIMIT не подставляются через плейсхолдер: направление сортировки идёт через
// белый список, лимит приводится к int.
$safeSort = strtoupper($sort) === 'DESC' ? 'DESC' : 'ASC';
$safeLimit = implode(', ', array_map('intval', explode(',', $limit)));
$res = $DB->query('SELECT * FROM `' . self::TABLE . '` ORDER BY `id` ' . $safeSort . ' LIMIT ' . $safeLimit);
return $res ?? [];
}
public static function getAllCount(): int
{
/** @var DataBase $DB Объект БД */
$DB = DataBase::getInstance();
$res = $DB->query('SELECT count(id) as count FROM ' . self::TABLE);
if ($res !== null) {
return (int)$res[0]['count'];
}
return 0;
}
public function getHostData(): array
{
/** @var DataBase $DB Объект БД */
$DB = DataBase::getInstance();
$res = $DB->get(self::TABLE, ['id' => $this->selectedHostId]);
if ($res !== null) {
return $res;
}
return [];
}
public function selectHost(int $id): self
{
/** @var DataBase $DB Объект БД */
$DB = DataBase::getInstance();
$this->selectedHostParams = $DB->get(self::TABLE, ['id' => $id]);
$this->selectedHostId = $id;
return $this;
}
private function sendRequest()
{
$queryFields = array_merge(['cmd' => $this->method], $this->params);
$ch = curl_init($this->selectedHostParams['url']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $queryFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
$this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($res, true);
if (!empty($result)) {
$this->response = $result;
} else {
$this->response = [];
}
}
/**
* Установка метода
*
* @param string $method Метод
*
* @return self
*/
public function setMethod(string $method): self
{
$this->method = $method;
return $this;
}
/**
* Установка параметров
*
* @param array $params Параметры
*
* @return self
*/
public function setParams(array $params): self
{
$this->params = $params;
return $this;
}
/**
* Выполнить
*
* @return $this
*/
public function execute(): self
{
$this->sendRequest();
return $this;
}
/**
* Получить ответ
*
* @return array
*/
public function getResponse(): array
{
return $this->response;
}
/**
* Получить результат выполнения
*
* @return mixed
*/
public function getResponseData()
{
return $this->response['data'];
}
/**
* Получить код ответа
*
* @return int
*/
public function getHttpCode(): int
{
return $this->httpCode;
}
/**
* Проверка площадки на доступность
*/
public function isOnline(): bool
{
$this->method = 'ping';
$this->execute();
return $this->getResponseData() === 'pong';
}
/**
* Выполнение произвольного кода
*
* @param string $code Код
*/
public function eval(string $code)
{
$this->method = 'eval';
$this->params = [
'evalString' => base64_encode($code),
];
$this->execute();
return $this->getResponseData();
}
/**
* Выполнение произвольного кода
*/
public function ping()
{
$this->method = 'ping';
$this->execute();
return $this->getResponseData();
}
/**
* Получение информации о площадке
*/
public function getHostInfo()
{
$this->method = 'getHostInfo';
$this->execute();
return $this->getResponseData();
}
/**
* Получение hostname площадки
*/
public function getHostname()
{
$this->method = 'getHostInfo';
$this->execute();
return $this->getResponseData()['hostname'];
}
/**
* Получение uptime площадки
*/
public function getUptime()
{
$this->method = 'getHostInfo';
$this->execute();
return $this->getResponseData()['uptime'];
}
/**
* Получение uname площадки
*/
public function getUname()
{
$this->method = 'getHostInfo';
$this->execute();
return $this->getResponseData()['uname'];
}
}