Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
This commit is contained in:
2025-03-06 21:26:32 +07:00
parent 151f312883
commit ac97396686
2 changed files with 90 additions and 88 deletions

View File

@@ -1,3 +1,9 @@
## 06-03-2025 (Релиз 1.0)
* Refactor: Замена Console на AnsiConsole
* Refactor: Изменена реализация ввода паролей
* Refactor: Замена Regex.Match на Regex.IsMatch
* Feat: Массовая смена пароля 802.1x
## 02-03-2025 ## 02-03-2025
* Refactor: Изменены области видимости методов * Refactor: Изменены области видимости методов
* Refactor: Переписано основное меню * Refactor: Переписано основное меню

View File

@@ -42,13 +42,13 @@ namespace domain_utility
static bool IsStringContainIp(string ip) 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) static string CheckComputerName(string pcName)
{ {
for (int i = 0; i < computerNameRegex.GetLength(0); i++) 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 $"{computerNameRegex[i, 1]}{pcName}".ToUpper();
return string.Empty; return string.Empty;
} }
@@ -56,21 +56,21 @@ namespace domain_utility
static string InputData(string message, Action callback, bool withClear = true, bool withChecks = true) static string InputData(string message, Action callback, bool withClear = true, bool withChecks = true)
{ {
if (withClear) if (withClear)
Console.Clear(); AnsiConsole.Clear();
Console.WriteLine(message); string data = AnsiConsole.Prompt(
Console.Write("> "); new TextPrompt<string>(message + "\n> ")
string data = Console.ReadLine(); );
if (string.IsNullOrWhiteSpace(data)) if (string.IsNullOrWhiteSpace(data))
return InputData(message, callback, withClear, withChecks); return InputData(message, callback, withClear, withChecks);
data = data.Trim(); data = data.Trim();
Console.WriteLine(); AnsiConsole.WriteLine();
if (withChecks) if (withChecks)
if (!IsStringContainIp(data)) if (!IsStringContainIp(data))
{ {
data = CheckComputerName(data); data = CheckComputerName(data);
if (data == string.Empty) if (data == string.Empty)
{ {
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); AnsiConsole.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(callback); BackToMenu(callback);
} }
} }
@@ -80,7 +80,7 @@ namespace domain_utility
static void BackToMenu(Action callback, bool withMessage = true) static void BackToMenu(Action callback, bool withMessage = true)
{ {
if (withMessage) if (withMessage)
Console.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную."); AnsiConsole.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную.");
ConsoleKey key = Console.ReadKey(true).Key; ConsoleKey key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Enter) if (key == ConsoleKey.Enter)
callback.Invoke(); callback.Invoke();
@@ -88,7 +88,7 @@ namespace domain_utility
Menu(); Menu();
else else
{ {
Console.WriteLine("Нажмите Enter или ESC!"); AnsiConsole.WriteLine("Нажмите Enter или ESC!");
BackToMenu(callback, false); BackToMenu(callback, false);
} }
} }
@@ -103,29 +103,10 @@ namespace domain_utility
} }
if (domain_password != string.Empty) if (domain_password != string.Empty)
return; return;
Console.WriteLine("Введите пароль от ТЕКУЩЕЙ учетной записи:"); domain_password = AnsiConsole.Prompt(
Console.Write("> "); new TextPrompt<string>("\nВведите пароль от ТЕКУЩЕЙ учетной записи:\n> ")
string password = string.Empty; .Secret()
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;
} }
static void ExecuteCommandViaSSH(string remote, string commandToExecute) static void ExecuteCommandViaSSH(string remote, string commandToExecute)
@@ -137,13 +118,13 @@ namespace domain_utility
{ {
client.Connect(); client.Connect();
SshCommand command = client.RunCommand(commandToExecute); SshCommand command = client.RunCommand(commandToExecute);
Console.WriteLine(command.Result); AnsiConsole.WriteLine(command.Result);
client.Disconnect(); client.Disconnect();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Произошла ошибка: " + ex.Message); AnsiConsole.WriteLine("Произошла ошибка: " + ex.Message);
} }
} }
@@ -160,7 +141,7 @@ namespace domain_utility
directoryEntry.Close(); directoryEntry.Close();
} }
Console.WriteLine("Пароль сброшен."); AnsiConsole.WriteLine("Пароль сброшен.");
BackToMenu(Menu); BackToMenu(Menu);
} }
@@ -223,7 +204,7 @@ namespace domain_utility
string remote = InputData("ping компьютера\n\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", string remote = InputData("ping компьютера\n\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
StartPing); StartPing);
Console.WriteLine("Нажмите Ctrl + C чтобы остановить\n"); AnsiConsole.WriteLine("Нажмите Ctrl + C чтобы остановить\n");
string correctName = CheckComputerName(remote); string correctName = CheckComputerName(remote);
if (correctName != string.Empty) if (correctName != string.Empty)
{ {
@@ -231,23 +212,23 @@ namespace domain_utility
{ {
IPAddress ip = Dns.GetHostEntry(correctName).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); IPAddress ip = Dns.GetHostEntry(correctName).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);
remote = ip.ToString(); 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) catch (Exception)
{ {
Console.WriteLine("Компьютер не найден."); AnsiConsole.WriteLine("Компьютер не найден.");
BackToMenu(StartPing); BackToMenu(StartPing);
return; return;
} }
} }
else else
Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote); AnsiConsole.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote);
Console.CancelKeyPress += PingClickCancel; Console.CancelKeyPress += PingClickCancel;
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
if (_click_cancel) break; if (_click_cancel) break;
Console.WriteLine(PingHost(remote)); AnsiConsole.WriteLine(PingHost(remote));
Thread.Sleep(1000); Thread.Sleep(1000);
} }
Console.CancelKeyPress -= PingClickCancel; Console.CancelKeyPress -= PingClickCancel;
@@ -266,7 +247,7 @@ namespace domain_utility
proc.StartInfo = new ProcessStartInfo("mstsc", remote); proc.StartInfo = new ProcessStartInfo("mstsc", remote);
proc.Start(); proc.Start();
Console.WriteLine("Подключение открыто."); AnsiConsole.WriteLine("Подключение открыто.");
BackToMenu(StartRDPConnection); BackToMenu(StartRDPConnection);
} }
@@ -301,7 +282,7 @@ namespace domain_utility
regex = Regex.Match(strArr[i], stringsToFind[j, 1]); regex = Regex.Match(strArr[i], stringsToFind[j, 1]);
if (regex.Success) if (regex.Success)
{ {
Console.WriteLine(stringsToFind[j, 2] + regex.Value); AnsiConsole.WriteLine(stringsToFind[j, 2] + regex.Value);
if (j == 3) if (j == 3)
{ {
groupsFlag = true; groupsFlag = true;
@@ -313,7 +294,7 @@ namespace domain_utility
{ {
regex = Regex.Match(strArr[i], stringsToFind[j, 1]); regex = Regex.Match(strArr[i], stringsToFind[j, 1]);
if (regex.Success) 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); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
var firstResult = searcher.Get().OfType<ManagementObject>().First()["LastBootUpTime"]; var firstResult = searcher.Get().OfType<ManagementObject>().First()["LastBootUpTime"];
DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString()); DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString());
Console.WriteLine("Дата последней загрузки: " + lastBootUp); AnsiConsole.WriteLine("Дата последней загрузки: " + lastBootUp);
Console.WriteLine("Время работы (д:ч:м:с): " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).ToString(@"d\:hh\:mm\:ss")); AnsiConsole.WriteLine("Время работы (д:ч:м:с): " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).ToString(@"d\:hh\:mm\:ss"));
} }
catch (Exception) catch (Exception)
{ {
Console.WriteLine("Произошла ошибка. Попробуйте еще раз."); AnsiConsole.WriteLine("Произошла ошибка. Попробуйте еще раз.");
} }
BackToMenu(ShowComputerBootupTime); BackToMenu(ShowComputerBootupTime);
@@ -356,7 +337,7 @@ namespace domain_utility
proc.StartInfo = new ProcessStartInfo("shutdown", remote); proc.StartInfo = new ProcessStartInfo("shutdown", remote);
proc.Start(); proc.Start();
Console.WriteLine("Команда перезагрузки отправлена."); AnsiConsole.WriteLine("Команда перезагрузки отправлена.");
BackToMenu(RemoteRebootWindows); BackToMenu(RemoteRebootWindows);
} }
@@ -368,7 +349,7 @@ namespace domain_utility
Process.Start($"https://{remote}:631/printers"); Process.Start($"https://{remote}:631/printers");
Console.WriteLine($"CUPS {remote} открыт."); AnsiConsole.WriteLine($"CUPS {remote} открыт.");
BackToMenu(OpenComputerCups); BackToMenu(OpenComputerCups);
} }
@@ -382,7 +363,7 @@ namespace domain_utility
ExecuteCommandViaSSH(remote, commandToExecute); ExecuteCommandViaSSH(remote, commandToExecute);
Console.WriteLine("Команда выполнена."); AnsiConsole.WriteLine("Команда выполнена.");
BackToMenu(ExecuteCustomCommandViaSSH); 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"); 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); BackToMenu(FixConky);
} }
@@ -406,7 +387,7 @@ namespace domain_utility
ExecuteCommandViaSSH(remote, "sudo shutdown -r +3 \"Через 3 минуты будет произведена перезагрузка ПК!\""); ExecuteCommandViaSSH(remote, "sudo shutdown -r +3 \"Через 3 минуты будет произведена перезагрузка ПК!\"");
Console.WriteLine("Команда перезагрузки отправлена."); AnsiConsole.WriteLine("Команда перезагрузки отправлена.");
BackToMenu(RemoteRebootLinux); BackToMenu(RemoteRebootLinux);
} }
@@ -436,44 +417,59 @@ namespace domain_utility
} }
} }
string new802password = InputData("\nВведите новый пароль от УЗ:", ChangeRemote802Password, withClear: false, withChecks: false); string new802password = AnsiConsole.Prompt(
new TextPrompt<string>("\nВведите новый пароль от УЗ:\n> ")
.Secret()
);
if (remote == "all") if (remote == "all")
{ {
//InputDomainCredentials(); InputDomainCredentials();
// load json file with pc names string path = Path.Combine(Environment.CurrentDirectory, "settings.json");
//string[] pc_names = { "it01", "it02" }; if (!File.Exists(path))
//string pc_name; {
//foreach (var item in pc_names) AnsiConsole.WriteLine("Файл с настройками не найден!");
//{ BackToMenu(ChangeRemote802Password);
// pc_name = CheckComputerName(item); }
// if (pc_name == string.Empty) JsonFile data = JsonConvert.DeserializeObject<JsonFile>(File.ReadAllText(path));
// continue; string unitKey;
// try int sleep_time = data.sleep_time;
// { foreach (KeyValuePair<string, List<int>> unit in data.arm_list)
// using (SshClient client = new SshClient(pc_name, domain_user, domain_password)) {
// { unitKey = unit.Key;
// client.Connect(); foreach (int position in unit.Value)
// SshCommand command = client.RunCommand($"sudo sed -i 's/password=.\\+/password={new802password}/' /etc/NetworkManager/system-connections/Проводное\\ подключение\\ 1.nmconnection"); {
// Console.WriteLine(command.Result); remote = CheckComputerName($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}");
// command = client.RunCommand("sudo nmcli connection reload"); if (remote == string.Empty)
// Console.WriteLine(command.Result); {
// command.Dispose(); AnsiConsole.WriteLine($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}: имя ПК не распознано.");
// client.Disconnect(); continue;
// } }
// Console.WriteLine(pc_name + ": "); try
// } {
// catch (Exception ex) using (SshClient client = new SshClient(remote, domain_user, domain_password))
// { {
// Console.WriteLine(pc_name + ": " + ex.Message); client.Connect();
// } SshCommand command = client.RunCommand($"sudo sed -i 's/password=.\\+/password={new802password}/' /etc/NetworkManager/system-connections/Проводное\\ подключение\\ 1.nmconnection");
//} //AnsiConsole.WriteLine(command.Result);
Console.WriteLine("Пока не реализовано :("); 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 else
{ {
ExecuteCommandViaSSH(remote, $"sudo sed -i 's/^password=.\\+/password={new802password}/' /etc/NetworkManager/system-connections/Проводное\\ подключение\\ 1.nmconnection && sudo nmcli connection reload"); 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); 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"); ExecuteCommandViaSSH(remote, "sudo sed -i 's/^Exec=/#Exec=/' /usr/share/dbus-1/services/org.kde.kwalletd5.service");
Console.WriteLine("Команда отключения кошелька отправлена."); AnsiConsole.WriteLine("Команда отключения кошелька отправлена.");
BackToMenu(DisableKdeWallet); BackToMenu(DisableKdeWallet);
} }
@@ -521,7 +517,7 @@ namespace domain_utility
static void Menu() static void Menu()
{ {
Console.Clear(); AnsiConsole.Clear();
MenuItem choice = AnsiConsole.Prompt( MenuItem choice = AnsiConsole.Prompt(
new SelectionPrompt<MenuItem>() new SelectionPrompt<MenuItem>()
.Title("Выберите действие:") .Title("Выберите действие:")
@@ -546,7 +542,7 @@ namespace domain_utility
string path = Path.Combine(Environment.CurrentDirectory, "settings.json"); string path = Path.Combine(Environment.CurrentDirectory, "settings.json");
if (!File.Exists(path)) if (!File.Exists(path))
{ {
Console.WriteLine("Файл с настройками не найден!"); AnsiConsole.WriteLine("Файл с настройками не найден!");
Console.ReadKey(); Console.ReadKey();
return; return;
} }
@@ -561,10 +557,10 @@ namespace domain_utility
remote = CheckComputerName($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}"); remote = CheckComputerName($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}");
if (remote == string.Empty) if (remote == string.Empty)
{ {
Console.WriteLine($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}: имя ПК не распознано."); AnsiConsole.WriteLine($"{unitKey}{(position < 10 ? $"0{position}" : position.ToString())}: имя ПК не распознано.");
continue; 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}\""); ExecuteCommandViaSSH(remote, $"sudo shutdown -r +{data.restart_time} \"{data.message}\"");
Thread.Sleep(sleep_time); Thread.Sleep(sleep_time);
} }