From ac97396686698341378d4d68558b575eb9715540 Mon Sep 17 00:00:00 2001 From: Lev Rusanov <30170278+JDM170@users.noreply.github.com> Date: Thu, 6 Mar 2025 21:26:32 +0700 Subject: [PATCH] Update Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com> --- CHANGELOG.md | 6 ++ Program.cs | 172 +++++++++++++++++++++++++-------------------------- 2 files changed, 90 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 223b97d..f8b784d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 06-03-2025 (Релиз 1.0) +* Refactor: Замена Console на AnsiConsole +* Refactor: Изменена реализация ввода паролей +* Refactor: Замена Regex.Match на Regex.IsMatch +* Feat: Массовая смена пароля 802.1x + ## 02-03-2025 * Refactor: Изменены области видимости методов * Refactor: Переписано основное меню diff --git a/Program.cs b/Program.cs index b30d139..ca9574a 100644 --- a/Program.cs +++ b/Program.cs @@ -42,13 +42,13 @@ namespace domain_utility static bool IsStringContainIp(string ip) { - return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success; + return Regex.IsMatch(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$"); } static string CheckComputerName(string pcName) { for (int i = 0; i < computerNameRegex.GetLength(0); i++) - if (Regex.Match(pcName, computerNameRegex[i, 0]).Success) + if (Regex.IsMatch(pcName, computerNameRegex[i, 0])) return $"{computerNameRegex[i, 1]}{pcName}".ToUpper(); return string.Empty; } @@ -56,21 +56,21 @@ namespace domain_utility static string InputData(string message, Action callback, bool withClear = true, bool withChecks = true) { if (withClear) - Console.Clear(); - Console.WriteLine(message); - Console.Write("> "); - string data = Console.ReadLine(); + AnsiConsole.Clear(); + string data = AnsiConsole.Prompt( + new TextPrompt(message + "\n> ") + ); if (string.IsNullOrWhiteSpace(data)) return InputData(message, callback, withClear, withChecks); data = data.Trim(); - Console.WriteLine(); + AnsiConsole.WriteLine(); if (withChecks) if (!IsStringContainIp(data)) { data = CheckComputerName(data); if (data == string.Empty) { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); + AnsiConsole.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); BackToMenu(callback); } } @@ -80,7 +80,7 @@ namespace domain_utility static void BackToMenu(Action callback, bool withMessage = true) { if (withMessage) - Console.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную."); + AnsiConsole.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную."); ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Enter) callback.Invoke(); @@ -88,7 +88,7 @@ namespace domain_utility Menu(); else { - Console.WriteLine("Нажмите Enter или ESC!"); + AnsiConsole.WriteLine("Нажмите Enter или ESC!"); BackToMenu(callback, false); } } @@ -103,29 +103,10 @@ namespace domain_utility } if (domain_password != string.Empty) return; - Console.WriteLine("Введите пароль от ТЕКУЩЕЙ учетной записи:"); - Console.Write("> "); - string password = string.Empty; - ConsoleKeyInfo key; - do - { - key = Console.ReadKey(true); - if (key.Key == ConsoleKey.Backspace && password.Length > 0) - { - password = password.Substring(0, password.Length - 1); - Console.Write("\b \b"); - } - else if (key.KeyChar < 32 || key.KeyChar > 126) - continue; - else if (key.Key != ConsoleKey.Backspace) - { - password += key.KeyChar; - Console.Write("*"); - } - } - while (key.Key != ConsoleKey.Enter); - Console.Write("\n\n"); - domain_password = password; + domain_password = AnsiConsole.Prompt( + new TextPrompt("\nВведите пароль от ТЕКУЩЕЙ учетной записи:\n> ") + .Secret() + ); } static void ExecuteCommandViaSSH(string remote, string commandToExecute) @@ -137,13 +118,13 @@ namespace domain_utility { client.Connect(); SshCommand command = client.RunCommand(commandToExecute); - Console.WriteLine(command.Result); + AnsiConsole.WriteLine(command.Result); client.Disconnect(); } } catch (Exception ex) { - Console.WriteLine("Произошла ошибка: " + ex.Message); + AnsiConsole.WriteLine("Произошла ошибка: " + ex.Message); } } @@ -160,7 +141,7 @@ namespace domain_utility directoryEntry.Close(); } - Console.WriteLine("Пароль сброшен."); + AnsiConsole.WriteLine("Пароль сброшен."); BackToMenu(Menu); } @@ -223,7 +204,7 @@ namespace domain_utility string remote = InputData("ping компьютера\n\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", StartPing); - Console.WriteLine("Нажмите Ctrl + C чтобы остановить\n"); + AnsiConsole.WriteLine("Нажмите Ctrl + C чтобы остановить\n"); string correctName = CheckComputerName(remote); if (correctName != string.Empty) { @@ -231,23 +212,23 @@ namespace domain_utility { IPAddress ip = Dns.GetHostEntry(correctName).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); remote = ip.ToString(); - Console.WriteLine("Обмен пакетами с {0}.main.russianpost.ru [{1}] с 32 байтами данных:", correctName, remote); + AnsiConsole.WriteLine("Обмен пакетами с {0}.main.russianpost.ru [{1}] с 32 байтами данных:", correctName, remote); } catch (Exception) { - Console.WriteLine("Компьютер не найден."); + AnsiConsole.WriteLine("Компьютер не найден."); BackToMenu(StartPing); return; } } else - Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote); + AnsiConsole.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote); Console.CancelKeyPress += PingClickCancel; for (int i = 0; i < 4; i++) { if (_click_cancel) break; - Console.WriteLine(PingHost(remote)); + AnsiConsole.WriteLine(PingHost(remote)); Thread.Sleep(1000); } Console.CancelKeyPress -= PingClickCancel; @@ -266,7 +247,7 @@ namespace domain_utility proc.StartInfo = new ProcessStartInfo("mstsc", remote); proc.Start(); - Console.WriteLine("Подключение открыто."); + AnsiConsole.WriteLine("Подключение открыто."); BackToMenu(StartRDPConnection); } @@ -301,7 +282,7 @@ namespace domain_utility regex = Regex.Match(strArr[i], stringsToFind[j, 1]); if (regex.Success) { - Console.WriteLine(stringsToFind[j, 2] + regex.Value); + AnsiConsole.WriteLine(stringsToFind[j, 2] + regex.Value); if (j == 3) { groupsFlag = true; @@ -313,7 +294,7 @@ namespace domain_utility { regex = Regex.Match(strArr[i], stringsToFind[j, 1]); if (regex.Success) - Console.WriteLine("\t\t" + regex.Value); + AnsiConsole.WriteLine("\t\t" + regex.Value); } } } @@ -335,12 +316,12 @@ namespace domain_utility ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); var firstResult = searcher.Get().OfType().First()["LastBootUpTime"]; DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString()); - Console.WriteLine("Дата последней загрузки: " + lastBootUp); - Console.WriteLine("Время работы (д:ч:м:с): " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).ToString(@"d\:hh\:mm\:ss")); + AnsiConsole.WriteLine("Дата последней загрузки: " + lastBootUp); + AnsiConsole.WriteLine("Время работы (д:ч:м:с): " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).ToString(@"d\:hh\:mm\:ss")); } catch (Exception) { - Console.WriteLine("Произошла ошибка. Попробуйте еще раз."); + AnsiConsole.WriteLine("Произошла ошибка. Попробуйте еще раз."); } BackToMenu(ShowComputerBootupTime); @@ -356,7 +337,7 @@ namespace domain_utility proc.StartInfo = new ProcessStartInfo("shutdown", remote); proc.Start(); - Console.WriteLine("Команда перезагрузки отправлена."); + AnsiConsole.WriteLine("Команда перезагрузки отправлена."); BackToMenu(RemoteRebootWindows); } @@ -368,7 +349,7 @@ namespace domain_utility Process.Start($"https://{remote}:631/printers"); - Console.WriteLine($"CUPS {remote} открыт."); + AnsiConsole.WriteLine($"CUPS {remote} открыт."); BackToMenu(OpenComputerCups); } @@ -382,7 +363,7 @@ namespace domain_utility ExecuteCommandViaSSH(remote, commandToExecute); - Console.WriteLine("Команда выполнена."); + AnsiConsole.WriteLine("Команда выполнена."); BackToMenu(ExecuteCustomCommandViaSSH); } @@ -394,7 +375,7 @@ namespace domain_utility ExecuteCommandViaSSH(remote, "sudo sed -i 's/update_interval = 0.5,/update_interval = 300,/' /etc/conky/conky.conf"); - Console.WriteLine("Команда исправления Conky отправлена."); + AnsiConsole.WriteLine("Команда исправления Conky отправлена."); BackToMenu(FixConky); } @@ -406,7 +387,7 @@ namespace domain_utility ExecuteCommandViaSSH(remote, "sudo shutdown -r +3 \"Через 3 минуты будет произведена перезагрузка ПК!\""); - Console.WriteLine("Команда перезагрузки отправлена."); + AnsiConsole.WriteLine("Команда перезагрузки отправлена."); BackToMenu(RemoteRebootLinux); } @@ -436,44 +417,59 @@ namespace domain_utility } } - string new802password = InputData("\nВведите новый пароль от УЗ:", ChangeRemote802Password, withClear: false, withChecks: false); + string new802password = AnsiConsole.Prompt( + new TextPrompt("\nВведите новый пароль от УЗ:\n> ") + .Secret() + ); if (remote == "all") { - //InputDomainCredentials(); - // load json file with pc names - //string[] pc_names = { "it01", "it02" }; - //string pc_name; - //foreach (var item in pc_names) - //{ - // pc_name = CheckComputerName(item); - // if (pc_name == string.Empty) - // continue; - // try - // { - // using (SshClient client = new SshClient(pc_name, domain_user, domain_password)) - // { - // client.Connect(); - // SshCommand command = client.RunCommand($"sudo sed -i 's/password=.\\+/password={new802password}/' /etc/NetworkManager/system-connections/Проводное\\ подключение\\ 1.nmconnection"); - // Console.WriteLine(command.Result); - // command = client.RunCommand("sudo nmcli connection reload"); - // Console.WriteLine(command.Result); - // command.Dispose(); - // client.Disconnect(); - // } - // Console.WriteLine(pc_name + ": "); - // } - // catch (Exception ex) - // { - // Console.WriteLine(pc_name + ": " + ex.Message); - // } - //} - Console.WriteLine("Пока не реализовано :("); + InputDomainCredentials(); + string path = Path.Combine(Environment.CurrentDirectory, "settings.json"); + if (!File.Exists(path)) + { + AnsiConsole.WriteLine("Файл с настройками не найден!"); + BackToMenu(ChangeRemote802Password); + } + JsonFile data = JsonConvert.DeserializeObject(File.ReadAllText(path)); + string unitKey; + int sleep_time = data.sleep_time; + foreach (KeyValuePair> unit in data.arm_list) + { + unitKey = unit.Key; + foreach (int position in unit.Value) + { + remote = CheckComputerName($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}"); + if (remote == string.Empty) + { + AnsiConsole.WriteLine($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}: имя ПК не распознано."); + continue; + } + try + { + using (SshClient client = new SshClient(remote, domain_user, domain_password)) + { + client.Connect(); + SshCommand command = client.RunCommand($"sudo sed -i 's/password=.\\+/password={new802password}/' /etc/NetworkManager/system-connections/Проводное\\ подключение\\ 1.nmconnection"); + //AnsiConsole.WriteLine(command.Result); + command = client.RunCommand("sudo nmcli connection reload"); + //AnsiConsole.WriteLine(command.Result); + command.Dispose(); + client.Disconnect(); + } + AnsiConsole.WriteLine(remote + ": "); + } + catch (Exception ex) + { + AnsiConsole.WriteLine(remote + ": " + ex.Message); + } + } + } } else { ExecuteCommandViaSSH(remote, $"sudo sed -i 's/^password=.\\+/password={new802password}/' /etc/NetworkManager/system-connections/Проводное\\ подключение\\ 1.nmconnection && sudo nmcli connection reload"); - Console.WriteLine("Команда отправлена."); + AnsiConsole.WriteLine("Команда отправлена."); } BackToMenu(ChangeRemote802Password); @@ -486,7 +482,7 @@ namespace domain_utility ExecuteCommandViaSSH(remote, "sudo sed -i 's/^Exec=/#Exec=/' /usr/share/dbus-1/services/org.kde.kwalletd5.service"); - Console.WriteLine("Команда отключения кошелька отправлена."); + AnsiConsole.WriteLine("Команда отключения кошелька отправлена."); BackToMenu(DisableKdeWallet); } @@ -521,7 +517,7 @@ namespace domain_utility static void Menu() { - Console.Clear(); + AnsiConsole.Clear(); MenuItem choice = AnsiConsole.Prompt( new SelectionPrompt() .Title("Выберите действие:") @@ -546,7 +542,7 @@ namespace domain_utility string path = Path.Combine(Environment.CurrentDirectory, "settings.json"); if (!File.Exists(path)) { - Console.WriteLine("Файл с настройками не найден!"); + AnsiConsole.WriteLine("Файл с настройками не найден!"); Console.ReadKey(); return; } @@ -561,10 +557,10 @@ namespace domain_utility remote = CheckComputerName($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}"); if (remote == string.Empty) { - Console.WriteLine($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}: имя ПК не распознано."); + AnsiConsole.WriteLine($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}: имя ПК не распознано."); continue; } - //Console.WriteLine($"{remote}: shutdown -r +{data.restart_time} \"{data.message}\""); + //AnsiConsole.WriteLine($"{remote}: shutdown -r +{data.restart_time} \"{data.message}\""); ExecuteCommandViaSSH(remote, $"sudo shutdown -r +{data.restart_time} \"{data.message}\""); Thread.Sleep(sleep_time); }