using System; using System.Collections.Generic; using System.Management; using System.Linq; using System.Text.RegularExpressions; using System.Diagnostics; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Net; using System.DirectoryServices; using System.Security.Principal; namespace domain_utility { internal class Program { static readonly string regularDateTime = @"(\d+[.]\d+[.]\d+[ ]\d+[:]\d+[:]\d+)"; static readonly string[,] stringsToFind = new string[,] { { "Учетная запись активна", @"(Yes|No)", "Учетная запись работает: " }, { "Последний пароль задан", regularDateTime, "Когда был сменен пароль: " }, { "Действие пароля завершается", regularDateTime, "Когда нужно менять пароль (крайний срок): "}, { "Членство в глобальных группах", @"([*].+)", "Член групп:\t" } }; static readonly string[,] computerNameRegex = new string[,] { { "^[a-zA-Z]+\\d+$", "R54-630300" }, // THE01 { "^\\d+[a-zA-Z]+\\d+$", "R54-" }, // 630300THE01 { "^[rR]\\d*[-]\\d+[a-zA-Z]+\\d+$", "" } // R54-630300THE01 }; private static string PingHost(string host) { string returnMessage = string.Empty; PingOptions pingOptions = new PingOptions() { DontFragment = true }; // TTL = 128 using (Ping ping = new Ping()) { byte[] buffer = new byte[32]; for (int i = 0; i < 4; i++) { try { PingReply pingReply = ping.Send(host, 1000, buffer, pingOptions); if (pingReply == null) { returnMessage = "Ошибка подключения по неизвестной причине."; throw new Exception(message: string.Empty); } switch (pingReply.Status) { case IPStatus.Success: { if (pingReply.RoundtripTime < 1) returnMessage = string.Format("Ответ от {0}: число байт={1} время<1ms TTL={2}", pingReply.Address, pingReply.Buffer.Length, pingReply.Options.Ttl); else returnMessage = string.Format("Ответ от {0}: число байт={1} время={2}ms TTL={3}", pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl); break; } case IPStatus.TimedOut: returnMessage = "Время подключения истекло."; break; case IPStatus.DestinationHostUnreachable: returnMessage = "Заданный узел недоступен."; break; default: returnMessage = string.Format("Ошибка пинга: {0}", pingReply.Status.ToString()); break; } } catch (Exception ex) { if (ex.Message != string.Empty) returnMessage = string.Format("Ошибка подключения: {0}", ex.Message); } } } return returnMessage; } private static string СheckComputerName(string pcName) { for (int i = 0; i < computerNameRegex.GetLength(0); i++) if (Regex.Match(pcName, computerNameRegex[i, 0]).Success) return $"{computerNameRegex[i, 1]}{pcName}"; return string.Empty; } private static bool IsStringContainIp(string ip) { return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success; } public static void ResetAdminPassword() { string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); string machineName = machineNameAndUser.Substring(0, machineNameAndUser.IndexOf('\\')); DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор")); directoryEntry.Properties["LockOutTime"].Value = 0; directoryEntry.Invoke("SetPassword", "Qwe12345"); directoryEntry.CommitChanges(); directoryEntry.Close(); Console.WriteLine("Пароль сброшен."); Main(); } private static void ShowDomainUserInfo() { Console.Write("\nВведите имя пользователя (пр. 'lev.rusanov'): "); string username = Console.ReadLine().Trim(); if (username == string.Empty || username.Length == 0) { ShowDomainUserInfo(); return; } Console.WriteLine(); username = $"user {username} /domain"; ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username) { CreateNoWindow = true, RedirectStandardOutput = true, UseShellExecute = false }; Process proc = new Process { StartInfo = procStartInfo }; proc.Start(); List strArr = new List {}; while (!proc.StandardOutput.EndOfStream) strArr.Add(proc.StandardOutput.ReadLine()); proc.Close(); Match regex; bool groupsFlag = false; for (int i = 0; i < strArr.Count; i++) { for (int j = 0; j < stringsToFind.GetLength(0); j++) { if (strArr[i].Contains(stringsToFind[j, 0])) { regex = Regex.Match(strArr[i], stringsToFind[j, 1]); if (regex.Success) { Console.WriteLine(stringsToFind[j, 2] + regex.Value); if (j == 3) { groupsFlag = true; continue; } } } if (j == 3 && groupsFlag) { regex = Regex.Match(strArr[i], stringsToFind[j, 1]); if (regex.Success) Console.WriteLine("\t\t" + regex.Value); } } } ShowDomainUserInfo(); } private static void ShowComputerBootupTime() { Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'IT04', '630300IT04', 'R54-630300IT04'): "); string remote = Console.ReadLine().Trim(); if (remote == string.Empty || remote.Length == 0) { ShowComputerBootupTime(); return; } Console.WriteLine(); if (!IsStringContainIp(remote)) { remote = СheckComputerName(remote); if (remote == string.Empty) { Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); ShowComputerBootupTime(); return; } } var 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); 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")); } catch (Exception) { Console.WriteLine("Компьютер не найден. Попробуйте еще раз."); ShowComputerBootupTime(); } ShowComputerBootupTime(); } private static void StartPing() { Console.Write("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129): "); string host = Console.ReadLine().Trim(); if (host == string.Empty || host.Length == 0) { StartPing(); return; } if (!IsStringContainIp(host)) { host = СheckComputerName(host); if (host == string.Empty) { Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); StartPing(); return; } } Console.WriteLine(); if (Regex.Match(host, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success) { try { IPAddress ip = Dns.GetHostEntry(host).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", host, ip); } catch (Exception) { Console.WriteLine("Компьютер не найден."); StartPing(); return; } } else { Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", host); } for (int i = 0; i < 10; i++) { Console.WriteLine(PingHost(host)); Thread.Sleep(1000); } StartPing(); } private static void OpenComputerCups() { Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'IT04', '630300IT04', 'R54-630300IT04'): "); string remote = Console.ReadLine().Trim(); if (remote == string.Empty || remote.Length == 0) { OpenComputerCups(); return; } if (!IsStringContainIp(remote)) { remote = СheckComputerName(remote); if (remote == string.Empty) { Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз."); OpenComputerCups(); return; } } Process.Start($"http://{remote.ToUpper()}:631/printers"); Console.WriteLine(); Main(); } static void Main() { Console.WriteLine("Выберите действие:\n" + "1 - посмотреть информацию о пользователе\n" + "2 - посмотреть дату последней загрузки компьютера (только Windows)\n" + "3 - ping компьютера\n" + //"4 - сброс пароля локального администратора (только Windows)\n" + "4 - открыть CUPS выбранного компьютера"); int choice; while (!int.TryParse(Console.ReadLine(), out choice)) { Console.WriteLine("Введите цифру!"); } switch (choice) { case 1: ShowDomainUserInfo(); break; case 2: ShowComputerBootupTime(); break; case 3: StartPing(); break; case 4: OpenComputerCups(); break; case 564: ResetAdminPassword(); break; default: { Console.WriteLine("Неправильный выбор!"); Main(); break; } } } } }