Files
domain_utility/Program.cs
2024-05-17 23:49:19 +07:00

159 lines
6.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string> strArr = new List<string> { };
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<ManagementObject>().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;
}
}
}
}
}