From 1d35170d6da530ba2bc686a486e07b40c9fa454c Mon Sep 17 00:00:00 2001 From: Lev Rusanov <30170278+JDM170@users.noreply.github.com> Date: Wed, 6 Nov 2024 21:17:12 +0700 Subject: [PATCH] Update Program.cs Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com> --- Program.cs | 265 +++++++++++++++++++++++++++-------------------------- 1 file changed, 133 insertions(+), 132 deletions(-) diff --git a/Program.cs b/Program.cs index 43bcdff..d3cfb14 100644 --- a/Program.cs +++ b/Program.cs @@ -31,33 +31,12 @@ namespace domain_utility { "^[rR]\\d*[-]\\d+[a-zA-Z]+\\d+$", "" } // R54-630300THE01 }; - private static string InputData(string str, Action callback, bool withClear = true) - { - if (withClear) - Console.Clear(); - Console.WriteLine(str); - Console.Write("> "); - string remote = Console.ReadLine().Trim(); - if (remote == string.Empty || remote.Length == 0) - InputData(str, callback); - Console.WriteLine(); - return remote; - } + //private static volatile bool _ping_stop = false; + private static bool _ping_stop = false; - private static void BackToMenu(Action callback, bool noMessage = false) + private static bool IsStringContainIp(string ip) { - if (noMessage == false) - Console.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную."); - var key = Console.ReadKey(true).Key; - if (key == ConsoleKey.Enter) - callback.Invoke(); - else if (key == ConsoleKey.Escape) - Menu(); - else - { - Console.WriteLine("Нажмите Enter или ESC!"); - BackToMenu(callback, true); - } + return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success; } private static string СheckComputerName(string pcName) @@ -68,9 +47,43 @@ namespace domain_utility return string.Empty; } - private static bool IsStringContainIp(string ip) + private static string InputData(string message, Action callback, bool withClear = true, bool withChecks = true) { - return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success; + if (withClear) + Console.Clear(); + Console.WriteLine(message); + Console.Write("> "); + string remote = Console.ReadLine().Trim(); + if (remote == string.Empty || remote.Length == 0) + InputData(message, callback, withClear, withChecks); + Console.WriteLine(); + if (withChecks) + if (!IsStringContainIp(remote)) + { + remote = СheckComputerName(remote); + if (remote == string.Empty) + { + Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); + BackToMenu(callback); + } + } + return remote; + } + + private static void BackToMenu(Action callback, bool withMessage = true) + { + if (withMessage) + Console.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную."); + ConsoleKey key = Console.ReadKey(true).Key; + if (key == ConsoleKey.Enter) + callback.Invoke(); + else if (key == ConsoleKey.Escape) + Menu(); + else + { + Console.WriteLine("Нажмите Enter или ESC!"); + BackToMenu(callback, false); + } } private static string PingHost(string host) @@ -126,7 +139,7 @@ namespace domain_utility string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); string machineName = machineNameAndUser.Substring(0, machineNameAndUser.IndexOf('\\')); - using (var directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор"))) + using (DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор"))) { //directoryEntry.Properties["LockOutTime"].Value = 0; directoryEntry.Invoke("SetPassword", "Qwe12345"); @@ -195,23 +208,12 @@ namespace domain_utility string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", ShowComputerBootupTime); - if (!IsStringContainIp(remote)) - { - remote = СheckComputerName(remote); - if (remote == string.Empty) - { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); - BackToMenu(ShowComputerBootupTime); - return; - } - } - - var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", remote)); + ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", remote)); try { scope.Connect(); - var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem"); - var searcher = new ManagementObjectSearcher(scope, query); + ObjectQuery query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem"); + ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); var firstResult = searcher.Get().OfType().First()["LastBootUpTime"]; DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString()); Console.WriteLine("Дата последней загрузки: " + lastBootUp); @@ -219,35 +221,32 @@ namespace domain_utility } catch (Exception) { - Console.WriteLine("Компьютер не найден. Попробуйте еще раз."); + Console.WriteLine("Произошла ошибка. Попробуйте еще раз."); BackToMenu(ShowComputerBootupTime); } BackToMenu(ShowComputerBootupTime); } + private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) + { + e.Cancel = true; + _ping_stop = true; + } + private static void StartPing() { string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", StartPing); - if (!IsStringContainIp(remote)) - { - remote = СheckComputerName(remote); - if (remote == string.Empty) - { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); - BackToMenu(StartPing); - return; - } - } - - if (Regex.Match(remote, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success) + string correctName = СheckComputerName(remote); + if (correctName != string.Empty) { try { - IPAddress ip = Dns.GetHostEntry(remote).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); - Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", remote, ip); + IPAddress ip = Dns.GetHostEntry(correctName).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); + remote = ip.ToString(); + Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", correctName, remote); } catch (Exception) { @@ -259,11 +258,15 @@ namespace domain_utility else Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote); - for (int i = 0; i < 10; i++) + Console.CancelKeyPress += Console_CancelKeyPress; + for (int i = 0; i < 4; i++) { + if (_ping_stop) break; Console.WriteLine(PingHost(remote)); Thread.Sleep(1000); } + Console.CancelKeyPress -= Console_CancelKeyPress; + _ping_stop = false; BackToMenu(StartPing); } @@ -273,17 +276,6 @@ namespace domain_utility string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", OpenComputerCups); - if (!IsStringContainIp(remote)) - { - remote = СheckComputerName(remote); - if (remote == string.Empty) - { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); - BackToMenu(OpenComputerCups); - return; - } - } - Process.Start($"https://{remote}:631/printers"); BackToMenu(OpenComputerCups); @@ -294,17 +286,6 @@ namespace domain_utility string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", StartRDPConnection); - if (!IsStringContainIp(remote)) - { - remote = СheckComputerName(remote); - if (remote == string.Empty) - { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); - BackToMenu(StartRDPConnection); - return; - } - } - remote = $"/v:{remote} /f"; Process proc = new Process(); proc.StartInfo = new ProcessStartInfo("mstsc", remote); @@ -313,54 +294,77 @@ namespace domain_utility BackToMenu(StartRDPConnection); } - private static void ExecuteCommandViaSSH() + private static string InputPassword() { - string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", - ExecuteCommandViaSSH); - - if (!IsStringContainIp(remote)) - { - remote = СheckComputerName(remote); - if (remote == string.Empty) - { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); - BackToMenu(ExecuteCommandViaSSH); - return; - } - } - Console.WriteLine("Введите пароль от СВОЕЙ учетной записи:"); Console.Write("> "); string password = string.Empty; - while (true) + ConsoleKeyInfo key; + do { - var key = Console.ReadKey(true); - if (key.Key == ConsoleKey.Enter) - break; + key = Console.ReadKey(true); + if (key.KeyChar < 32 || key.KeyChar > 126) + continue; if (key.Key == ConsoleKey.Backspace && password.Length > 0) password = password.Substring(0, password.Length - 1); else if (key.Key != ConsoleKey.Backspace) password += key.KeyChar; } + while (key.Key != ConsoleKey.Enter); Console.Write("\n\n"); + return password; + } - string commandToExecute = InputData("Введите команду для выполнения:", ExecuteCommandViaSSH, false); - + private static void ExecuteCommandViaSSH(string remote, string password, string commandToExecute) + { string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); int indexOfUserName = machineNameAndUser.IndexOf('\\') + 1; string machineUser = machineNameAndUser.Substring(indexOfUserName, machineNameAndUser.Length - indexOfUserName).ToLower(); - using (var client = new SshClient(remote, machineUser, password)) + using (SshClient client = new SshClient(remote, machineUser, password)) { client.Connect(); - // "sudo sed -i 's/update_interval = 0.5,/update_interval = 300,/' /etc/conky/conky.conf" SshCommand command = client.RunCommand(commandToExecute); Console.WriteLine(command.Result); client.Disconnect(); } - Console.WriteLine("Вроде что-то произошло, но это не точно"); + } - BackToMenu(ExecuteCommandViaSSH); + private static void FixConky() + { + string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", + FixConky); + + string password = InputPassword(); + + ExecuteCommandViaSSH(remote, password, "sudo sed -i 's/update_interval = 0.5,/update_interval = 300,/' /etc/conky/conky.conf"); + + BackToMenu(FixConky); + } + + private static void RemoteRebootLinux() + { + string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", + RemoteRebootLinux); + + string password = InputPassword(); + + ExecuteCommandViaSSH(remote, password, "sudo shutdown -r +3 \"Через 3 минуты будет произведена перезагрузка ПК!\""); + + BackToMenu(RemoteRebootLinux); + } + + private static void ExecuteCustomCommandViaSSH() + { + string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", + ExecuteCustomCommandViaSSH); + + string commandToExecute = InputData("Введите команду для выполнения:", ExecuteCustomCommandViaSSH, withClear: true, withChecks: false); + string password = InputPassword(); + + ExecuteCommandViaSSH(remote, password, commandToExecute); + + BackToMenu(ExecuteCustomCommandViaSSH); } private static void RemoteRebootWindows() @@ -368,17 +372,6 @@ namespace domain_utility string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", RemoteRebootWindows); - if (!IsStringContainIp(remote)) - { - remote = СheckComputerName(remote); - if (remote == string.Empty) - { - Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); - BackToMenu(RemoteRebootWindows); - return; - } - } - remote = $"/m \\\\{remote} /r /f /t 180 /c 'Через 3 минуты будет произведена перезагрузка ПК!'"; Process proc = new Process(); proc.StartInfo = new ProcessStartInfo("shutdown", remote); @@ -390,15 +383,17 @@ namespace domain_utility } static readonly string[] menuList = { - //"4 - сброс пароля локального администратора (только Windows)", + //"630300 - сброс пароля локального администратора (только Windows)", // ResetAdminPassword "Выберите действие:", - "1 - посмотреть информацию о пользователе (только Windows)", - "2 - посмотреть дату последней загрузки компьютера (только Windows)", - "3 - ping компьютера", - "4 - открыть CUPS выбранного компьютера (только Linux)", - "5 - удаленно подключиться к компьютеру (Windows -> Windows, Windows -> Linux)", - "6 - выполнить команду удаленно (только Windows -> Linux)", - "7 - удаленная перезагрузка компьютера (только Windows)", + "1 - ping компьютера", // StartPing + "2 - посмотреть информацию о пользователе (только Windows)", // ShowDomainUserInfo + "3 - посмотреть дату последней загрузки компьютера (только Windows)", // ShowComputerBootupTime + "4 - удаленно подключиться к компьютеру (Windows -> Windows, Windows -> Linux)", // StartRDPConnection + "5 - удаленная перезагрузка компьютера (только Windows)", // RemoteRebootWindows + "6 - открыть CUPS выбранного компьютера (только Linux)", // OpenComputerCups + "7 - изменить время обновления conky с 0.5 на 300", // FixConky + "8 - удаленная перезагрузка компьютера (только Linux)", // RemoteRebootLinux + "9 - выполнить команду удаленно (только Windows -> Linux)", // ExecuteCustomCommandViaSSH }; private static void Menu() @@ -407,18 +402,24 @@ namespace domain_utility for (int i = 0; i < menuList.Length; i++) Console.WriteLine(menuList[i]); int choice; + Console.Write("> "); while (!int.TryParse(Console.ReadLine(), out choice)) + { Console.WriteLine("Введите цифру!"); + Console.Write("> "); + } switch (choice) { - case 1: ShowDomainUserInfo(); break; - case 2: ShowComputerBootupTime(); break; - case 3: StartPing(); break; - case 4: OpenComputerCups(); break; - case 5: StartRDPConnection(); break; - case 6: ExecuteCommandViaSSH(); break; - case 7: RemoteRebootWindows(); break; - case 51422415: ResetAdminPassword(); break; + case 1: StartPing(); break; + case 2: ShowDomainUserInfo(); break; + case 3: ShowComputerBootupTime(); break; + case 4: StartRDPConnection(); break; + case 5: RemoteRebootWindows(); break; + case 6: OpenComputerCups(); break; + case 7: FixConky(); break; + case 8: RemoteRebootLinux(); break; + case 9: ExecuteCustomCommandViaSSH(); break; + case 630300: ResetAdminPassword(); break; default: { Console.WriteLine("Неправильный выбор!");