Просмотр исходного кода

add login and password for all network devices

Roman Dmitriev 2 лет назад
Родитель
Сommit
232a77e692

+ 32 - 26
docs/mysql/mysql.sql

@@ -114,7 +114,7 @@ CREATE TABLE `config_options` (
 -- Дамп данных таблицы `config_options`
 --
 
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(1, 'KB', 'Еденица измерения трафика - Килобайт или кибибайт', 'Traffic measurement unit - Kilobyte (0) or kibibyte (1,default)', 1, 'bool', '1', 0, 1);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(1, 'KB', 'Еденица измерения трафика - Килобайт (0) или кибибайт (1,default)', 'Traffic measurement unit - Kilobyte (1000b) or kibibyte (1024b,default)', 1, 'bool', '1024', 1, 1);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(3, 'dns server', 'ip-адрес DNS-сервера', 'DNS server ip address', 1, 'text', '127.0.0.1', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(5, 'dhcp server', 'ip-адрес DHCP-сервера', 'ip address of the DHCP server', 1, 'text', '127.0.0.1', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(9, 'default snmp version', 'Версия snmp по умолчанию. В настоящий момент поддерживаются 1 и 2. Поддержка версии 3 в разработке.', 'The default version of snmp. Currently, 1 and 2 are supported. Support for version 3 is in development.', 1, 'int', '2', 1, 3);
@@ -126,17 +126,17 @@ INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `descr
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(23, 'save traffic detail', 'Сохранять ли детализацию трафика из netflow по ip-адресам пользователей', 'Whether to keep the details of traffic from netflow by ip addresses of users', 1, 'bool', '1', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(26, 'history detail traffic', 'Глубина хранения детализации в сутках. Установка значения больше 3-7 дней приведёт к разрастанию базы данных и увеличит время отображения детализации в интерфейсе администратора', 'Depth of detail storage in days. Setting a value greater than 3-7 days will cause the database to grow and increase the time about to display details in the admin interface', 1, 'int', '3', 1, 7);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(27, 'history dhcp lease', 'Глубина хранения аренды dhcp-сервера', 'Storage depth of the dhcp server lease', 1, 'int', '1', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(28, 'router_login', 'Логин для входа на маршрутизаторы Mikrotik для управления dhcp-сервером и контролем доступа', 'Login to Mikrotik routers to manage the dhcp server and access control', 1, 'text', 'admin', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(29, 'router_password', 'Пароль для входа на маршрутизаторы Mikrotik для управления dhcp-сервером и контролем доступа', 'Password to log in to Mikrotik routers for managing the dhcp server and access control', 1, 'text', 'admin', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(30, 'router_ssh_port', 'Порт ssh маршрутизатора', 'Router ssh port', 1, 'int', '22', 22, 0);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(28, 'router_login', 'Default login for to network devices', 'Login to Mikrotik routers to manage the dhcp server and access control', 1, 'text', 'admin', 0, 0);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(29, 'router_password', 'Default password for network devices', 'Password to log in to Mikrotik routers for managing the dhcp server and access control', 1, 'text', 'admin', 0, 0);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(30, 'router_ssh_port', 'SSH default port', 'Router ssh port', 1, 'int', '22', 22, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(32, 'org name', 'Название организации', 'Organization name', 1, 'text', 'ORG', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(33, 'office domain', 'Домен организации', 'Organization domain', 1, 'text', 'local', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(34, 'debug', 'Включить отладку', 'Enable debugging', 1, 'bool', '0', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(35, 'connections history, days', 'Время хранения истории мест подключения ip-адресов', 'Storage time of the history of connection locations of ip addresses', 1, 'int', '90', 1, 365);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(37, 'refresh access lists', 'Расположение скрипта управления контролем доступа для роутеров Mikrotik', 'Location of the access control script for Mikrotik routers', 1, 'text', '/opt/Eye/scripts/sync_mikrotik.pl', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(38, 'regenerate dhcp config', 'Расположение скрипта управления конфигурацией dhcp-серверами', 'Location of the dhcp server configuration management script', 1, 'text', '/opt/Eye/scripts/update-dnsmasq', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(39, 'regenerate dns config', 'Расположение скрипта управления dns-сервером', 'Location of the dns server management script', 1, 'text', '/opt/Eye/scripts/update-dns', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(40, 'regenerate nagios config', 'Расположение скрипта конфигурирования Nagios', 'Location of the Nagios configuration script', 1, 'text', '/etc/nagios/restart_nagios', 0, 0);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(38, 'regenerate dhcp cconfig', 'Расположение скрипта управления конфигурацией dhcp-серверами', 'Location of the dhcp server configuration management script', 1, 'text', '/opt/Eye/scripts/update-dnsmasq', 0, 0);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(39, 'regenerate dns cconfig', 'Расположение скрипта управления dns-сервером', 'Location of the dns server management script', 1, 'text', '/opt/Eye/scripts/update-dns', 0, 0);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(40, 'regenerate nagios cconfig', 'Расположение скрипта конфигурирования Nagios', 'Location of the Nagios configuration script', 1, 'text', '/etc/nagios/restart_nagios', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(41, 'discovery network', 'Расположение скрипта сканирования сети', 'Location of the network scan script', 1, 'text', '/opt/Eye/scripts/fetch_new_arp.pl', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(44, 'Ignore hotspot dhcp log', 'Не писать лог событий dhcp-сервера хотспота. Имеет смысл вклчючать, поскольку время аренды в хот-споте как правило маленькое и в записях хот-спота становятся незаметны логи обычных пользователей', 'Do not write the event log of the hotspot dhcp server. It makes sense to include it, since the rental time in the hotspot is usually small and the logs of ordinary users become invisible in the hotspot records', 1, 'bool', '1', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(45, 'ignore update dhcp event', 'Не писать события обновления ip-адреса dhcp-сервера. ', 'Do not write events for updating the IP address of the dhcp server. ', 1, 'bool', '0', 0, 0);
@@ -147,7 +147,7 @@ INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `descr
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(50, 'urgent sync access', 'Немедленное изменение списков доступа на роутере после правки записи пользователя', 'Immediate change of access lists on the router after editing the user record ', 1, 'bool', '0', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(51, 'Email_alert', 'Отправлять e-mail сообщения для уровней сообщений WARNING & ERROR', 'Send e-mail messages for message levels WARNING & ERROR', 1, 'bool', '1', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(52, 'Sender email', 'E-mail адрес, с которого рассылается почта', 'E-mail address from which mail is sent', 1, 'text', 'root', 0, 0);
-INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(53, 'log level', 'Каждый уровень включает в себя предыдущий:\n0 - ERROR - писать только ошибки\n1 - WARNING - писать предупреждения\n2 - INFO - писать информационные сообщения\n3 - VERBOSE - писать подробную информацию о выполняемых операциях', 'Each level includes the previous one:\r\n0 - ERROR - write only errors\r\n1 - WARNING - write warnings\r\n2 - INFO - write informational\r\n3 - VERBOSE - write detailed information about the operations performed ', 1, 'int', '2', 0, 3);
+INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(53, 'log level', 'Каждый уровень включает в себя предыдущий:\r\n0 - ERROR - писать только ошибки\r\n1 - WARNING - писать предупреждения\r\n2 - INFO - писать информационные сообщения\r\n3 - VERBOSE - писать подробную информацию о выполняемых операциях', 'Each level includes the previous one:\r\n0 - ERROR - write only errors\r\n1 - WARNING - write warnings\r\n2 - INFO - write informational\r\n3 - VERBOSE - write detailed information about the operations performed ', 1, 'int', '2', 0, 3);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(54, 'enable_quotes', 'Включить обработку квот по трафику', 'Enable traffic quota processing', 1, 'bool', '0', 0, 0);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(55, 'netflow_step', 'Интервал сброса данных из коллектора netflow, минуты', 'Data reset interval from netflow collector, minutes', 1, 'int', '10', 1, 60);
 INSERT INTO `config_options` (`id`, `option_name`, `description.russian`, `description.english`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES(56, 'traffic_ipstat_history', 'Время хранения полной статистики по трафику для каждого ip-адреса в сутках. Таблица в 6 раз больше обычной часовой статистики. Врядли кому-то потребуется глубина хранения более месяца.', 'The storage time of complete traffic statistics for each ip address in days. The table is 6 times larger than the usual hourly statistic Hardly anyone will need a storage depth of more than a month.', 1, 'int', '30', 7, 365);
@@ -206,28 +206,32 @@ CREATE TABLE `devices` (
   `id` int(11) NOT NULL,
   `device_type` int(11) NOT NULL DEFAULT 1,
   `device_model_id` int(11) DEFAULT 89,
-  `firmware` varchar(100) DEFAULT NULL,
+  `firmware` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `vendor_id` int(11) NOT NULL DEFAULT 1,
-  `device_name` varchar(50) DEFAULT NULL,
+  `device_name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `building_id` int(11) NOT NULL DEFAULT 1,
-  `ip` varchar(15) DEFAULT NULL,
+  `ip` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `login` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'admin',
+  `password` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `protocol` int(11) NOT NULL DEFAULT 0,
+  `control_port` int(11) NOT NULL DEFAULT 23,
   `port_count` int(11) NOT NULL DEFAULT 0,
-  `SN` varchar(80) DEFAULT NULL,
-  `comment` varchar(255) DEFAULT NULL,
+  `SN` varchar(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `comment` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `snmp_version` tinyint(4) NOT NULL DEFAULT 0,
-  `snmp3_user_rw` varchar(20) DEFAULT NULL,
-  `snmp3_user_rw_password` varchar(20) DEFAULT NULL,
-  `snmp3_user_ro` varchar(20) DEFAULT NULL,
-  `snmp3_user_ro_password` varchar(20) DEFAULT NULL,
-  `community` varchar(50) NOT NULL DEFAULT 'public',
-  `rw_community` varchar(50) NOT NULL DEFAULT 'private',
+  `snmp3_user_rw` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `snmp3_user_rw_password` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `snmp3_user_ro` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `snmp3_user_ro_password` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `community` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'public',
+  `rw_community` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'private',
   `fdb_snmp_index` tinyint(1) NOT NULL DEFAULT 0,
   `discovery` tinyint(1) NOT NULL DEFAULT 1,
   `user_acl` tinyint(1) NOT NULL DEFAULT 0,
   `dhcp` tinyint(1) NOT NULL DEFAULT 0,
   `nagios` tinyint(1) NOT NULL DEFAULT 0,
   `active` tinyint(1) NOT NULL DEFAULT 1,
-  `nagios_status` varchar(10) NOT NULL DEFAULT 'UP',
+  `nagios_status` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'UP',
   `queue_enabled` tinyint(1) NOT NULL DEFAULT 0,
   `connected_user_only` tinyint(1) NOT NULL DEFAULT 1,
   `user_id` int(11) DEFAULT NULL,
@@ -403,18 +407,20 @@ CREATE TABLE `device_ports` (
 
 CREATE TABLE `device_types` (
   `id` int(11) NOT NULL,
-  `name` varchar(50) DEFAULT NULL
+  `name.russian` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+  `name.english` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
 
 --
 -- Дамп данных таблицы `device_types`
 --
 
-INSERT INTO `device_types` (`id`, `name`) VALUES(1, 'Свич');
-INSERT INTO `device_types` (`id`, `name`) VALUES(2, 'Роутер');
-INSERT INTO `device_types` (`id`, `name`) VALUES(3, 'Сервер');
-INSERT INTO `device_types` (`id`, `name`) VALUES(4, 'Точка доступа');
-INSERT INTO `device_types` (`id`, `name`) VALUES(5, 'Сетевое устройство');
+INSERT INTO `device_types` (`id`, `name.russian`, `name.english`) VALUES(0, 'Маршрутизатор', 'Router');
+INSERT INTO `device_types` (`id`, `name.russian`, `name.english`) VALUES(1, 'Свич', 'Switch');
+INSERT INTO `device_types` (`id`, `name.russian`, `name.english`) VALUES(2, 'Роутер', 'Gateway');
+INSERT INTO `device_types` (`id`, `name.russian`, `name.english`) VALUES(3, 'Сервер', 'Server');
+INSERT INTO `device_types` (`id`, `name.russian`, `name.english`) VALUES(4, 'Точка доступа', 'Access Point');
+INSERT INTO `device_types` (`id`, `name.russian`, `name.english`) VALUES(5, 'Сетевое устройство', 'Network device');
 
 -- --------------------------------------------------------
 

+ 4 - 0
html/cfg/config.sample.php

@@ -26,4 +26,8 @@ define("SNMP_timeout","500000");
 #snmp retry after timeout
 define("SNMP_retry","1");
 
+#crypt config - CHANGE IT!!!
+define("ENCRYPTION_KEY","!!!CHANGE_ME!!!");
+define("ENCRYPTION_IV","123456782345");
+
 ?>

Разница между файлами не показана из-за своего большого размера
+ 386 - 272
html/inc/common.php


+ 5 - 30
scripts/Rstat/cmd.pm

@@ -26,7 +26,6 @@ log_cmd3
 log_cmd4
 flush_telnet
 run_command
-netdev_set_auth
 netdev_login
 netdev_cmd
 netdev_backup
@@ -255,33 +254,10 @@ return 1;
 
 #---------------------------------------------------------------------------------
 
-sub netdev_set_auth {
-my $device = shift;
-#router
-if ($device->{device_type} eq '2') {
-    #mikrotik
-    if ($device->{vendor_id} eq '9') { $device->{port}=$config_ref{router_port}; }
-    $device->{login}=$config_ref{router_login};
-    $device->{password}=$config_ref{router_password};
-    }
-#switch
-if ($device->{device_type} eq '1' or $device->{vendor_id} eq '3') {
-    #mikrotik
-#    if ($device->{vendor_id} eq '9') { $device->{port}=$config_ref{router_port}; }
-    $device->{login}=$sw_login;
-    $device->{password}=$sw_password;
-    }
-return $device;
-}
-
-#---------------------------------------------------------------------------------
-
 sub netdev_login {
 my $device = shift;
 #skip unknown vendor
 if (!$switch_auth{$device->{vendor_id}}) { return; }
-if (!$switch_auth{$device->{vendor_id}}{proto}) { $switch_auth{$device->{vendor_id}}{proto} = 'telnet'; }
-if (!$device->{port} and $switch_auth{$device->{vendor_id}}{port}) { $device->{port} = $switch_auth{$device->{vendor_id}}{port}; }
 
 my $t;
 
@@ -289,10 +265,9 @@ my $t;
 #$Net::OpenSSH::debug_fh = $out;
 #$Net::OpenSSH::debug = -1;
 
-if ($switch_auth{$device->{vendor_id}}{proto} eq 'telnet') {
+if ($device->{proto} eq 'telnet') {
     if (!$device->{port}) { $device->{port} = '23'; }
     log_info("Try login to $device->{device_name} $device->{ip}:$device->{port} by telnet...");
-
     #zyxel patch
     if ($device->{vendor_id} eq '4') {
         eval {
@@ -319,7 +294,7 @@ if ($switch_auth{$device->{vendor_id}}{proto} eq 'telnet') {
         $t->waitfor("/$switch_auth{$device->{vendor_id}}{prompt}/");
         if (exists $switch_auth{$device->{vendor_id}}{enable}) {
             $t->print($switch_auth{$device->{vendor_id}}{enable});
-            $t->print($device->{enable_password});
+            $t->print($device->{enable_password}) if ($device->{enable_password});
             $t->waitfor("/$switch_auth{$device->{vendor_id}}{prompt}/");
             }
         if ($device->{vendor_id} eq '2') {
@@ -342,7 +317,7 @@ if ($switch_auth{$device->{vendor_id}}{proto} eq 'telnet') {
     if ($@) { log_error("Login to $device->{device_name} ip: $device->{ip} by telnet aborted: $@"); } else { log_info("Login to $device->{device_name} ip: $device->{ip} by telnet success!"); }
     }
 
-if ($switch_auth{$device->{vendor_id}}{proto} eq 'ssh') {
+if ($device->{proto} eq 'ssh') {
     if (!$device->{port}) { $device->{port} = '22'; }
     log_info("Try login to $device->{device_name} $device->{ip}:$device->{port} by ssh...");
 	$t = Net::OpenSSH->new($device->{ip},
@@ -401,8 +376,8 @@ my $session = shift;
 my $device = shift;
 return if (!exists $switch_auth{$device->{vendor_id}}{enable});
 my $cmd = $switch_auth{$device->{vendor_id}}{enable};
-netdev_cmd($device,$session,$switch_auth{$device->{vendor_id}}{proto},$cmd,3);
-if ($device->{enable_password}) { netdev_cmd($device,$session,$switch_auth{$device->{vendor_id}}{proto},$device->{enable_password},3); }
+netdev_cmd($device,$session,$device->{proto},$cmd,3);
+if ($device->{enable_password}) { netdev_cmd($device,$session,$device->{proto},$device->{enable_password},3); }
 }
 
 #---------------------------------------------------------------------------------

+ 3 - 0
scripts/Rstat/config.pm

@@ -147,6 +147,9 @@ $config_ref{nagios_dir}=~s/\/$//;
 $config_ref{nagios_cmd}=$Config->{_}->{nagios_cmd} || '/var/spool/nagios/cmd/nagios.cmd';
 $config_ref{nagios_event_socket}=$Config->{_}->{nagios_event_socket} || '/var/spool/nagios/hoststate.socket';
 
+$config_ref{encryption_key}=Config->{_}->{encryption_key} || '!!!CHANGE_ME!!!';
+$config_ref{encryption_iv}=Config->{_}->{encryption_iv} || '123456782345';
+
 our $MY_NAME=$FN[-1];
 our $SPID="/var/run/".$FN[-1];
 

+ 64 - 0
scripts/Rstat/main.pm

@@ -15,6 +15,8 @@ use Rstat::config;
 use Socket;
 use IO::Select;
 use IO::Handle;
+use Crypt::CBC;
+use MIME::Base64;
 
 our @ISA = qw(Exporter);
 our @EXPORT = qw(
@@ -50,6 +52,9 @@ is_integer
 is_float
 run_in_parallel
 translit
+crypt_string
+decrypt_string
+netdev_set_auth
 );
 
 BEGIN
@@ -483,6 +488,8 @@ while ($start<=$count-1) {
 return (@result);
 }
 
+#---------------------------------------------------------------------------------
+
 sub translit {
 my $textline=shift;
 return if (!$textline);
@@ -523,6 +530,63 @@ $textline =~ s/Я/Ya/g;		$textline =~ s/я/ya/g;
 return $textline;
 }
 
+#---------------------------------------------------------------------------------
+
+sub netdev_set_auth {
+my $device = shift;
+$device->{login}=$config_ref{router_login} if (!$device->{login});
+$device->{password}=$config_ref{router_password} if (!$device->{password});
+$device->{password}=decrypt_string($device->{password});
+$device->{enable_password}='';
+#$device->{enable_password}=$device->{passowrd};
+$device->{proto} = 'ssh' if ($device->{protocol} eq '0');
+$device->{proto} = 'telnet' if ($device->{protocol} eq '1');
+$device->{port} = $device->{control_port} if ($device->{control_port});
+return $device;
+}
+
+#---------------------------------------------------------------------------------
+
+sub decrypt_string {
+    my $crypted_string = shift;
+    return if (!$crypted_string);
+    my $cipher_handle = Crypt::CBC->new(
+    {
+        'key'         => $config_ref{encryption_key},
+        'cipher'      => 'Cipher::AES',
+        'iv'          => $config_ref{encryption_iv},
+        'literal_key' => 1,
+        'header'      => 'none',
+        keysize       => 128 / 8
+    }
+    );
+
+my $result = $cipher_handle->decrypt(decode_base64($crypted_string));
+return $result;
+}
+
+#---------------------------------------------------------------------------------
+
+sub crypt_string {
+    my $simple_string = shift;
+    return if (!$simple_string);
+    my $cipher_handle = Crypt::CBC->new(
+    {
+        'key'         => $config_ref{encryption_key},
+        'cipher'      => 'Cipher::AES',
+        'iv'          => $config_ref{encryption_iv},
+        'literal_key' => 1,
+        'header'      => 'none',
+        keysize       => 128 / 8
+    }
+    );
+
+my $result = encode_base64($cipher_handle->encrypt($simple_string));
+return $result;
+}
+
+#---------------------------------------------------------------------------------
+
 #log_file($LOG_COMMON,"INFO:","----------------------------------------------------------------------------------------");
 #log_file($LOG_COMMON,"INFO:","Run script $0. Pid: $$ Pid file: $SPID.pid");
 #log_file($LOG_COMMON,"INFO:","User uid: $< Effective uid: $>");

+ 4 - 0
scripts/cfg/config.sample

@@ -40,3 +40,7 @@ sw_password=password
 nagios_dir=/etc/nagios4
 nagios_cmd=/var/spool/nagios4/cmd/nagios.cmd
 nagios_event_socket=/var/spool/nagios4/hoststate.socket
+
+#crypt config
+encryption_key="!!!CHANGE_ME!!!"
+encryption_iv="123456782345"

+ 1 - 1
scripts/fetch_new_arp.pl

@@ -65,7 +65,7 @@ if ($ARGV[0]) {
     run_in_parallel(@fping_cmd);
     }
 
-my @router_ref = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND device_type=2 AND discovery=1 AND snmp_version>0 ORDER by ip" );
+my @router_ref = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND (device_type=2 or device_type=0) AND discovery=1 AND snmp_version>0 ORDER by ip" );
 
 my @arp_array=();
 

+ 11 - 11
scripts/sync_mikrotik.pl

@@ -42,10 +42,10 @@ my $all_ok = 1;
 my @gateways =();
 #select undeleted mikrotik routers only
 if ($ARGV[0]) {
-    my $router = get_record_sql($dbh,'SELECT * FROM devices WHERE device_type=2 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9 and id='.$ARGV[0]);
+    my $router = get_record_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9 and id='.$ARGV[0]);
     if ($router) { push(@gateways,$router); }
     } else {
-    @gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE device_type=2 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9');
+    @gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9');
     }
 
 my $dhcp_networks = new Net::Patricia;
@@ -106,7 +106,7 @@ next if (!$int);
 $int=trim($int);
 
 #get ip addr at interface
-my @int_addr=netdev_cmd($gate,$t,'ssh','/ip address print terse without-paging where interface='.$int,1);
+my @int_addr=netdev_cmd($gate,$t,$gate->{proto},'/ip address print terse without-paging where interface='.$int,1);
 
 log_debug("Get interfaces: ".Dumper(\@int_addr));
 
@@ -135,7 +135,7 @@ db_log_verbose($dbh,"Analyze interface $int. Found: ".Dumper($dhcp_conf{$found_s
 if ($gate->{dhcp}) {
 
 #fetch current dhcp records
-my @ret_static_leases=netdev_cmd($gate,$t,'ssh','/ip dhcp-server lease print terse without-paging where server=dhcp-'.$int,1);
+my @ret_static_leases=netdev_cmd($gate,$t,$gate->{proto},'/ip dhcp-server lease print terse without-paging where server=dhcp-'.$int,1);
 
 log_debug("Get dhcp leases:".Dumper(\@ret_static_leases));
 
@@ -430,7 +430,7 @@ log_debug("Group filters: ".Dumper(\%group_filters));
 my %cur_users;
 
 foreach my $group_name (keys %lists) {
-my @address_lists=netdev_cmd($gate,$t,'ssh','/ip firewall address-list print terse without-paging where list='.$group_name,1);
+my @address_lists=netdev_cmd($gate,$t,$gate->{proto},'/ip firewall address-list print terse without-paging where list='.$group_name,1);
 
 log_debug("Get address lists:".Dumper(\@address_lists));
 
@@ -469,7 +469,7 @@ timestamp;
 #sync firewall rules
 
 #sync group chains
-my @chain_list=netdev_cmd($gate,$t,'ssh','/ip firewall filter  print terse without-paging where chain=Users and action=jump',1);
+my @chain_list=netdev_cmd($gate,$t,$gate->{proto},'/ip firewall filter  print terse without-paging where chain=Users and action=jump',1);
 
 log_debug("Get firewall chains:".Dumper(\@chain_list));
 
@@ -567,7 +567,7 @@ foreach my $group_name (keys %group_filters) {
 
 next if (!$group_name);
 
-my @get_filter=netdev_cmd($gate,$t,'ssh','/ip firewall filter print terse without-paging where chain='.$group_name,1);
+my @get_filter=netdev_cmd($gate,$t,$gate->{proto},'/ip firewall filter print terse without-paging where chain='.$group_name,1);
 chomp(@get_filter);
 
 my @cur_filter=();
@@ -631,7 +631,7 @@ my %get_queue_type=();
 my %get_queue_tree=();
 my %get_filter_mangle=();
 
-my @tmp=netdev_cmd($gate,$t,'ssh','/queue type print terse without-paging where name~"pcq_(down|up)load"',1);
+my @tmp=netdev_cmd($gate,$t,$gate->{proto},'/queue type print terse without-paging where name~"pcq_(down|up)load"',1);
 
 log_debug("Get queues: ".Dumper(\@tmp));
 
@@ -661,7 +661,7 @@ if ($row=~/name=pcq_(down|up)load_(\d){1,3}\s+/i) {
 }
 
 @tmp=();
-@tmp=netdev_cmd($gate,$t,'ssh','/queue tree print terse without-paging where parent~"(download|upload)_root"',1);
+@tmp=netdev_cmd($gate,$t,$gate->{proto},'/queue tree print terse without-paging where parent~"(download|upload)_root"',1);
 log_debug("Get root queues: ".Dumper(\@tmp));
 
 #print Dumper(\@tmp);
@@ -699,7 +699,7 @@ if ($row=~/queue=pcq_(down|up)load_(\d){1,3}/i) {
 
 @tmp=();
 
-@tmp=netdev_cmd($gate,$t,'ssh','/ip firewall mangle print terse without-paging where action=mark-packet and new-packet-mark~"(upload|download)_[0-9]{1,3}"',1);
+@tmp=netdev_cmd($gate,$t,$gate->{proto},'/ip firewall mangle print terse without-paging where action=mark-packet and new-packet-mark~"(upload|download)_[0-9]{1,3}"',1);
 log_debug("Get firewall mangle rules for queues:".Dumper(\@tmp));
 
 # 0    chain=forward action=mark-packet new-packet-mark=upload_0 passthrough=yes src-address-list=queue_0 out-interface=sfp-sfpplus1-wan log=no log-prefix=""
@@ -838,7 +838,7 @@ if (scalar(@cmd_list)) {
     log_debug("Apply:");
     if ($debug) { foreach my $cmd (@cmd_list) { log_debug("$cmd"); } }
     eval {
-        netdev_cmd($gate,$t,'ssh',\@cmd_list,1);
+        netdev_cmd($gate,$t,$gate->{proto},\@cmd_list,1);
     };
     if ($@) {
         $all_ok = 0;

+ 17 - 0
updates/2-4-12/mysql-devices-patch.sql

@@ -0,0 +1,17 @@
+ALTER TABLE `devices` ADD `login` VARCHAR(50) NOT NULL DEFAULT 'admin' AFTER `ip`, ADD `password` VARCHAR(250) DEFAULT NULL AFTER `login`, ADD `protocol` INT NOT NULL DEFAULT '0' AFTER `password`, ADD `control_port` INT NOT NULL DEFAULT '23' AFTER `protocol`;
+INSERT INTO `device_types` (`id`, `name`) VALUES ('6', 'Маршрутизатор');
+UPDATE `device_types` SET `id` = '0' WHERE `device_types`.`id` = 6;
+ALTER TABLE `device_types` CHANGE `name` `name.russian` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL;
+ALTER TABLE `device_types` ADD `name.english` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL AFTER `name.russian`;
+UPDATE `device_types` SET `name.english` = 'Router' WHERE `device_types`.`id` = 0;
+UPDATE `device_types` SET `name.english` = 'Switch' WHERE `device_types`.`id` = 1;
+UPDATE `device_types` SET `name.english` = 'Gateway' WHERE `device_types`.`id` = 2;
+UPDATE `device_types` SET `name.english` = 'Server' WHERE `device_types`.`id` = 3;
+UPDATE `device_types` SET `name.english` = 'WiFi Access Point' WHERE `device_types`.`id` = 4;
+UPDATE `device_types` SET `name.english` = 'Network device' WHERE `device_types`.`id` = 5;
+UPDATE `config_options` SET `description.russian` = 'Логин для входа на сетевые устройства по умолчанию' WHERE `config_options`.`id` = 28;
+UPDATE `config_options` SET `description.russian` = 'Пароль по умолчанию на сетевые устройства' WHERE `config_options`.`id` = 29;
+UPDATE `config_options` SET `description.russian` = 'Порт ssh по умолчанию' WHERE `config_options`.`id` = 30;
+UPDATE `config_options` SET `description.russian` = 'Default login for to network devices' WHERE `config_options`.`id` = 28;
+UPDATE `config_options` SET `description.russian` = 'Default password for network devices' WHERE `config_options`.`id` = 29;
+UPDATE `config_options` SET `description.russian` = 'SSH default port' WHERE `config_options`.`id` = 30;

+ 54 - 0
updates/2-4-12/upgrade-to-2-4-12.pl

@@ -0,0 +1,54 @@
+#!/usr/bin/perl
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+use utf8;
+use FindBin '$Bin';
+use lib "$Bin/";
+use Data::Dumper;
+use Rstat::config;
+use Rstat::main;
+use Rstat::mysql;
+use Rstat::net_utils;
+use strict;
+use warnings;
+
+if ($config_ref{encryption_key}=~/change_me/i)) { print "Set encryption key please!\n"; exit 100; }
+
+print "Stage 1: Migrate default password\n";
+
+my $current_password = get_option($dbh,29);
+my $crypted_password = crypt_string($current_password);
+
+do_sql($dbh,"UPDATE config set value='".$crypted_password."' WHERE id=29");
+
+print "Stage 2: Add default access settings for all netdevices\n";
+
+my $default_login = get_option($dbh,28);
+my $default_port = get_option($dbh,30);
+
+my @dev_list = get_records_sql($dbh,"SELECT * FROM devices WHERE device_type <= 2");
+foreach my $row (@dev_list) {
+#0 - 'Router'
+#1 - 'Switch'
+#2 - 'Gateway'
+my $device;
+$device->{login} = $default_login;
+$device->{password} = $crypted_password;
+#control
+#0 - ssh
+#1 - telnet
+#2 - api
+$device->{protocol} = 1;
+if ($row->{device_type} eq '2') { 
+    $device->{control_port} = $default_port;
+    $device->{protocol} = 0;
+    }
+update_record($dbh,'devices',$device,"id=".$row->{id});
+}
+
+print "Done!\n";
+
+exit;

Некоторые файлы не были показаны из-за большого количества измененных файлов