From 17b4e9424ce895b572991381cd9e7c747b82219b Mon Sep 17 00:00:00 2001 From: Lev Rusanov <30170278+JDM170@users.noreply.github.com> Date: Fri, 17 May 2024 10:50:01 +0700 Subject: [PATCH] Initial commit --- .gitignore | 4 + App.config | 6 ++ Program.cs | 158 +++++++++++++++++++++++++++++++++++++ Properties/AssemblyInfo.cs | 36 +++++++++ domain_utility.csproj | 54 +++++++++++++ domain_utility.sln | 25 ++++++ 6 files changed, 283 insertions(+) create mode 100644 .gitignore create mode 100644 App.config create mode 100644 Program.cs create mode 100644 Properties/AssemblyInfo.cs create mode 100644 domain_utility.csproj create mode 100644 domain_utility.sln diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d75b79a --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.vs +bin/ +obj/ +*.csproj.user diff --git a/App.config b/App.config new file mode 100644 index 0000000..193aecc --- /dev/null +++ b/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..2ac494a --- /dev/null +++ b/Program.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Management; +using System.Linq; +using System.Text.RegularExpressions; + +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" } + }; + + 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"; + //} + + System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("net", username); + procStartInfo.CreateNoWindow = true; + procStartInfo.RedirectStandardOutput = true; + procStartInfo.UseShellExecute = false; + System.Diagnostics.Process proc = new System.Diagnostics.Process { StartInfo = procStartInfo }; + proc.Start(); + + List strArr = new List { }; + while (!proc.StandardOutput.EndOfStream) + { + strArr.Add(proc.StandardOutput.ReadLine()); + } + + //if (args.Length > 0) + // for (int i = 0; i < strArr.Count; i++) + // Console.WriteLine(strArr[i]); + + //for (int i = 0; i < strArr.Count; i++) + //{ + // if (strArr[i].Contains("Системная ошибка 1355.")) + // { + // proc.Close(); + // proc.Dispose(); + // Console.WriteLine("Программа работает только с доменом."); + // return; + // } + // if (strArr[i].Contains("Не найдено имя пользователя.")) + // { + // proc.Close(); + // proc.Dispose(); + // Console.WriteLine("Пользователь не найден! Попробуйте еще раз."); + // return; + // } + //} + + 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); + } + } + } + + proc.Close(); + proc.Dispose(); + + Console.WriteLine("\nНажмите чтобы закрыть..."); + Console.ReadLine(); + } + + private static void ShowComputerBootupTime() + { + Console.WriteLine("\nВведите имя компьютера (пр. 'R54-630300IT04'): "); + string computerName = Console.ReadLine().Trim(); + var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName)); + try + { + scope.Connect(); + var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem"); + var searcher = new ManagementObjectSearcher(scope, query); + var firstResult = searcher.Get().OfType().First(); //assumes that we do have at least one result + Console.WriteLine("Last bootup time: " + 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) + { + // Display the remote computer information + Console.WriteLine("Computer Name : {0}", m["csname"]); + Console.WriteLine("Windows Directory : {0}", m["WindowsDirectory"]); + Console.WriteLine("Operating System: {0}", m["Caption"]); + Console.WriteLine("Version: {0}", m["Version"]); + Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]); + }*/ + } + catch (Exception) + { + //Console.WriteLine(ex.Message); + Console.WriteLine("Компьютер не найден. Попробуйте еще раз."); + ShowComputerBootupTime(); + } + + Console.WriteLine("\nНажмите чтобы закрыть..."); + Console.ReadLine(); + } + + static void Main(string[] args) + { + Console.WriteLine("Выберите действие:\n1 - посмотреть информацию о пользователе\n2 - посмотреть дату последней загрузки компьютера"); + string choice = Console.ReadLine(); + switch(Convert.ToInt32(choice)) + { + case 1: ShowDomainUserInfo(); break; + case 2: ShowComputerBootupTime(); break; + default: + { + Console.WriteLine("Неправильный выбор!"); + Main(args); + break; + } + } + } + } +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..aa2476c --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов для изменения сведений, +// связанные с этой сборкой. +[assembly: AssemblyTitle("Утилита для получения информации о пользователе или ПК")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Lev Rusanov © 2024")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// из модели COM задайте для атрибута ComVisible этого типа значение true. +[assembly: ComVisible(false)] + +// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM +[assembly: Guid("44ac1131-4709-4310-851f-642ed8409c67")] + +// Сведения о версии сборки состоят из указанных ниже четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Номер редакции +// +// Можно задать все значения или принять номера сборки и редакции по умолчанию +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/domain_utility.csproj b/domain_utility.csproj new file mode 100644 index 0000000..11fec75 --- /dev/null +++ b/domain_utility.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {44AC1131-4709-4310-851F-642ED8409C67} + Exe + domain_utility + domain_utility + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/domain_utility.sln b/domain_utility.sln new file mode 100644 index 0000000..2e2121a --- /dev/null +++ b/domain_utility.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34723.18 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "domain_utility", "domain_utility.csproj", "{44AC1131-4709-4310-851F-642ED8409C67}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {44AC1131-4709-4310-851F-642ED8409C67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {44AC1131-4709-4310-851F-642ED8409C67}.Debug|Any CPU.Build.0 = Debug|Any CPU + {44AC1131-4709-4310-851F-642ED8409C67}.Release|Any CPU.ActiveCfg = Release|Any CPU + {44AC1131-4709-4310-851F-642ED8409C67}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {DB74BA96-5FFE-45AC-98E0-4AC6F249DE00} + EndGlobalSection +EndGlobal