Files
domain_utility/Program.cs

327 lines
15 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;
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(128, true); // TTL = 128
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:
{
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);
//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("Пароль установлен.");
Main();
}
private static void ShowDomainUserInfo()
{
Console.Write("\nВведите имя пользователя (пр. 'lev.rusanov'): ");
string username = "user " + Console.ReadLine().Trim() + " /domain";
if (username == string.Empty || username.Length == 0)
{
ShowDomainUserInfo();
return;
}
Console.WriteLine();
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
{
CreateNoWindow = true,
RedirectStandardOutput = true,
UseShellExecute = false
};
Process proc = new Process { StartInfo = procStartInfo };
proc.Start();
List<string> strArr = new List<string> {};
while (!proc.StandardOutput.EndOfStream)
{
strArr.Add(proc.StandardOutput.ReadLine());
}
proc.Close();
//for (int i = 0; i < strArr.Count; i++)
//{
// if (strArr[i].Contains("Системная ошибка 1355."))
// {
// Console.WriteLine("Программа работает только с доменом.");
// return;
// }
// if (strArr[i].Contains("Не найдено имя пользователя."))
// {
// 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);
}
}
}
ShowDomainUserInfo();
}
private static void ShowComputerBootupTime()
{
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
{
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("Дата последней загрузки: " + 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 (System.Runtime.InteropServices.COMException)
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 || (!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();
}
private static void OpenComputerCups()
{
Console.Write("\nВведите имя компьютера: ");
string input = Console.ReadLine().Trim();
if (input == string.Empty || input.Length == 0)
{
OpenComputerCups();
return;
}
for (int i = 0; i < computerNameRegex.GetLength(0); i++)
{
if (Regex.Match(input, computerNameRegex[i, 0]).Success)
{
Process.Start($"http://{computerNameRegex[i, 1]}{input.ToUpper()}:631/printers");
break;
}
}
Console.WriteLine();
Main();
}
static void Main()
{
Console.WriteLine("Выберите действие:\n" +
"1 - посмотреть информацию о пользователе\n" +
"2 - посмотреть дату последней загрузки компьютера (только Windows)\n" +
"3 - ping компьютера\n" +
//"4 - сброс пароля локального администратора\n" +
"4 - открыть CUPS введенного компьютера");
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;
case 4: OpenComputerCups(); break;
default:
{
Console.WriteLine("Неправильный выбор!");
Main();
break;
}
}
}
}
}