Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
This commit is contained in:
2024-10-27 01:00:48 +07:00
parent 5580d2cb9c
commit 1e17ab39c8

View File

@@ -27,26 +27,26 @@ namespace domain_utility
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
{ "^[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 };
PingOptions pingOptions = new PingOptions() { DontFragment = true }; // TTL = 128
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)
if (pingReply == null)
{
returnMessage = "Ошибка подключения по неизвестной причине.";
throw new Exception(message: string.Empty);
}
switch (pingReply.Status)
{
case IPStatus.Success:
@@ -55,7 +55,6 @@ namespace domain_utility
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:
@@ -68,21 +67,10 @@ namespace domain_utility
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)
catch (Exception ex)
{
if (ex.Message != string.Empty)
returnMessage = string.Format("Ошибка подключения: {0}", ex.Message);
}
}
@@ -90,35 +78,38 @@ namespace domain_utility
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 = WindowsIdentity.GetCurrent().Name.ToString().Substring(0, machineNameAndUser.IndexOf('\\'));
string machineName = machineNameAndUser.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.Invoke("SetPassword", "Qwe12345");
directoryEntry.CommitChanges();
directoryEntry.Close();
//Console.WriteLine("Пароль установлен.");
Console.WriteLine("Пароль сброшен.");
Main();
}
private static void ShowDomainUserInfo()
{
Console.Write("\nВведите имя пользователя (пр. 'lev.rusanov'): ");
string username = "user " + Console.ReadLine().Trim() + " /domain";
string username = Console.ReadLine().Trim();
if (username == string.Empty || username.Length == 0)
{
ShowDomainUserInfo();
@@ -126,6 +117,8 @@ namespace domain_utility
}
Console.WriteLine();
username = $"user {username} /domain";
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
{
CreateNoWindow = true,
@@ -137,26 +130,10 @@ namespace domain_utility
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++)
@@ -190,37 +167,37 @@ namespace domain_utility
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)
Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'IT04', '630300IT04', 'R54-630300IT04'): ");
string remote = Console.ReadLine().Trim();
if (remote == string.Empty || remote.Length == 0)
{
ShowComputerBootupTime();
return;
}
Console.WriteLine();
var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName));
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<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"]);
}*/
var firstResult = searcher.Get().OfType<ManagementObject>().First()["LastBootUpTime"];
DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString());
Console.WriteLine("Дата последней загрузки: " + lastBootUp);
Console.WriteLine("Время работы (д:ч:м:с): " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).ToString(@"d\:hh\:mm\:ss"));
}
//catch (System.Runtime.InteropServices.COMException)
catch (Exception)
{
Console.WriteLine("Компьютер не найден. Попробуйте еще раз.");
@@ -232,19 +209,31 @@ namespace domain_utility
private static void StartPing()
{
Console.Write("\nВведите IP адрес компьютера (пр. 10.234.16.129): ");
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))
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();
Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", host, ip);
}
catch (Exception)
@@ -256,7 +245,6 @@ namespace domain_utility
}
else
{
Console.WriteLine();
Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", host);
}
@@ -271,23 +259,27 @@ namespace domain_utility
private static void OpenComputerCups()
{
Console.Write("\nВведите имя компьютера: ");
string input = Console.ReadLine().Trim();
if (input == string.Empty || input.Length == 0)
Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'IT04', '630300IT04', 'R54-630300IT04'): ");
string remote = Console.ReadLine().Trim();
if (remote == string.Empty || remote.Length == 0)
{
OpenComputerCups();
return;
}
for (int i = 0; i < computerNameRegex.GetLength(0); i++)
if (!IsStringContainIp(remote))
{
if (Regex.Match(input, computerNameRegex[i, 0]).Success)
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Process.Start($"http://{computerNameRegex[i, 1]}{input.ToUpper()}:631/printers");
break;
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
OpenComputerCups();
return;
}
}
Process.Start($"http://{remote.ToUpper()}:631/printers");
Console.WriteLine();
Main();
}
@@ -298,22 +290,20 @@ namespace domain_utility
"1 - посмотреть информацию о пользователе\n" +
"2 - посмотреть дату последней загрузки компьютера (только Windows)\n" +
"3 - ping компьютера\n" +
//"4 - сброс пароля локального администратора\n" +
"4 - открыть CUPS введенного компьютера");
string choice;
while(true)
//"4 - сброс пароля локального администратора (только Windows)\n" +
"4 - открыть CUPS выбранного компьютера");
int choice;
while (!int.TryParse(Console.ReadLine(), out choice))
{
choice = Console.ReadLine().Trim();
if (choice != string.Empty || choice.Length != 0)
break;
Console.WriteLine("Введите цифру!");
}
switch (Convert.ToInt32(choice))
switch (choice)
{
case 1: ShowDomainUserInfo(); break;
case 2: ShowComputerBootupTime(); break;
case 3: StartPing(); break;
//case 4: ResetAdminPassword(); break;
case 4: OpenComputerCups(); break;
case 564: ResetAdminPassword(); break;
default:
{
Console.WriteLine("Неправильный выбор!");