diff --git a/Program.cs b/Program.cs index b1e4637..8418a12 100644 --- a/Program.cs +++ b/Program.cs @@ -4,6 +4,12 @@ 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 { @@ -18,19 +24,99 @@ namespace domain_utility { "Членство в глобальных группах", @"([*].+)", "Член групп:\t" } }; + private static string PingHost(string host) + { + string returnMessage = string.Empty; + //PingOptions pingOptions = new PingOptions(128, true); + PingOptions pingOptions = new PingOptions() { DontFragment = true }; + using (Ping ping = new Ping()) + { + byte[] buffer = new byte[32]; + //here we will ping the host 4 times (standard) + //long averageTime = 0; + for (int i = 0; i < 4; i++) + { + try + { + PingReply pingReply = ping.Send(host, 1000, buffer, pingOptions); + if (pingReply != null) + { + switch (pingReply.Status) + { + case IPStatus.Success: + { + returnMessage = string.Format("Ответ от {0}: число байт={1} время={2}ms TTL={3}", pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl); + //averageTime += pingReply.RoundtripTime; + break; + } + case IPStatus.TimedOut: + returnMessage = "Время подключения истекло."; + break; + case IPStatus.DestinationHostUnreachable: + returnMessage = "Заданный узел недоступен."; + break; + default: + returnMessage = string.Format("Ошибка пинга: {0}", pingReply.Status.ToString()); + break; + } + //if (pingReply.Status == IPStatus.Success) + //{ + // returnMessage = string.Format("Ответ от {0}: число байт={1} время={2}ms TTL={3}", pingReply.Address, pingReply.Buffer.Length, averageTime / 4, pingReply.Options.Ttl); + // averageTime = 0; + //} + } + else + returnMessage = "Ошибка подключения по неизвестной причине."; + } + catch (PingException ex) + { + returnMessage = string.Format("Ошибка подключения: {0}", ex.Message); + } + catch (SocketException ex) + { + returnMessage = string.Format("Ошибка подключения: {0}", ex.Message); + } + } + } + return returnMessage; + } + + public static void ResetAdminPassword() + { + string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); + string machineName = WindowsIdentity.GetCurrent().Name.ToString().Substring(0, machineNameAndUser.IndexOf('\\')); + DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор")); + + //foreach(PropertyValueCollection prep in directoryEntry.Properties) + //{ + // Console.WriteLine(prep.PropertyName + ": " + prep.Value); + //} + + //Console.WriteLine("PasswordExpired: " + directoryEntry.Properties["PasswordExpired"].Value); + //Console.WriteLine("PasswordAge: " + directoryEntry.Properties["PasswordAge"].Value); + //Console.WriteLine("MaxPasswordAge: " + directoryEntry.Properties["MaxPasswordAge"].Value); + //Console.WriteLine("MinPasswordAge: " + directoryEntry.Properties["MinPasswordAge"].Value); + //Console.WriteLine(TimeSpan.FromSeconds((int)directoryEntry.Properties["MinPasswordAge"].Value) - TimeSpan.FromSeconds((int)directoryEntry.Properties["PasswordAge"].Value)); + + //directoryEntry.Invoke("SetPassword", "Qwe12345"); + //directoryEntry.Properties["LockOutTime"].Value = 0; + //directoryEntry.CommitChanges(); + directoryEntry.Close(); + //Console.WriteLine("Пароль установлен."); + string[] str = {}; + Main(str); + } + private static void ShowDomainUserInfo() { - string username; - //if (args.Length == 0) - //{ Console.Write("\nВведите имя пользователя (пр. 'lev.rusanov'): "); - username = "user " + Console.ReadLine().Trim() + " /domain"; - Console.WriteLine("\n"); - //} - //else - //{ - // username = "user JDM17"; - //} + string username = "user " + Console.ReadLine().Trim() + " /domain"; + if (username == string.Empty || username.Length == 0) + { + ShowDomainUserInfo(); + return; + } + Console.WriteLine(); ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username) { @@ -41,18 +127,13 @@ namespace domain_utility Process proc = new Process { StartInfo = procStartInfo }; proc.Start(); - List strArr = new List { }; + List strArr = new List {}; while (!proc.StandardOutput.EndOfStream) { strArr.Add(proc.StandardOutput.ReadLine()); } proc.Close(); - proc.Dispose(); - - //if (args.Length > 0) - // for (int i = 0; i < strArr.Count; i++) - // Console.WriteLine(strArr[i]); //for (int i = 0; i < strArr.Count; i++) //{ @@ -96,7 +177,6 @@ namespace domain_utility } } - Console.ReadLine(); ShowDomainUserInfo(); } @@ -104,6 +184,13 @@ namespace domain_utility { Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'R54-630300IT04'): "); string computerName = Console.ReadLine().Trim(); + if (computerName == string.Empty || computerName.Length == 0 || !Regex.Match(computerName, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success) + { + ShowComputerBootupTime(); + return; + } + Console.WriteLine(); + var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName)); try { @@ -114,7 +201,6 @@ namespace domain_utility Console.WriteLine("Дата последней загрузки: " + ManagementDateTimeConverter.ToDateTime(firstResult["LastBootUpTime"].ToString())); /*ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); - ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { @@ -126,31 +212,81 @@ namespace domain_utility Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]); }*/ } - catch (System.Runtime.InteropServices.COMException) + //catch (System.Runtime.InteropServices.COMException) + catch (Exception) { - //Console.WriteLine(ex.Message); Console.WriteLine("Компьютер не найден. Попробуйте еще раз."); ShowComputerBootupTime(); } - Console.ReadLine(); 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 || (!Regex.Match(host, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success && !Regex.Match(host, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success)) + { + StartPing(); + return; + } + 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(); + Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", host, ip); + } + catch (Exception) + { + Console.WriteLine("Компьютер не найден."); + StartPing(); + return; + } + } + else + { + Console.WriteLine(); + Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", host); + } + + for (int i = 0; i < 10; i++) + { + Console.WriteLine(PingHost(host)); + Thread.Sleep(1000); + } + + StartPing(); + } + static void Main(string[] args) { - Console.WriteLine("Выберите действие:\n1 - посмотреть информацию о пользователе\n2 - посмотреть дату последней загрузки компьютера"); - string choice = Console.ReadLine(); + Console.WriteLine("Выберите действие:\n" + + "1 - посмотреть информацию о пользователе\n" + + "2 - посмотреть дату последней загрузки компьютера\n" + + "3 - ping компьютера\n" + + "4 - сброс пароля локального администратора"); + string choice; + while(true) + { + choice = Console.ReadLine().Trim(); + if (choice != string.Empty || choice.Length != 0) + break; + } switch (Convert.ToInt32(choice)) { case 1: ShowDomainUserInfo(); break; case 2: ShowComputerBootupTime(); break; + case 3: StartPing(); break; + case 4: ResetAdminPassword(); break; default: - { - Console.WriteLine("Неправильный выбор!"); - Main(args); - break; - } + { + Console.WriteLine("Неправильный выбор!"); + Main(args); + break; + } } } } diff --git a/domain_utility.csproj b/domain_utility.csproj index 11fec75..cdce015 100644 --- a/domain_utility.csproj +++ b/domain_utility.csproj @@ -35,6 +35,7 @@ +