Update
Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
This commit is contained in:
214
Program.cs
214
Program.cs
@@ -27,104 +27,97 @@ namespace domain_utility
|
|||||||
static readonly string[,] computerNameRegex = new string[,] {
|
static readonly string[,] computerNameRegex = new string[,] {
|
||||||
{ "^[a-zA-Z]+\\d+$", "R54-630300" }, // THE01
|
{ "^[a-zA-Z]+\\d+$", "R54-630300" }, // THE01
|
||||||
{ "^\\d+[a-zA-Z]+\\d+$", "R54-" }, // 630300THE01
|
{ "^\\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)
|
private static string PingHost(string host)
|
||||||
{
|
{
|
||||||
string returnMessage = string.Empty;
|
string returnMessage = string.Empty;
|
||||||
//PingOptions pingOptions = new PingOptions(128, true); // TTL = 128
|
PingOptions pingOptions = new PingOptions() { DontFragment = true }; // TTL = 128
|
||||||
PingOptions pingOptions = new PingOptions() { DontFragment = true };
|
|
||||||
using (Ping ping = new Ping())
|
using (Ping ping = new Ping())
|
||||||
{
|
{
|
||||||
byte[] buffer = new byte[32];
|
byte[] buffer = new byte[32];
|
||||||
//here we will ping the host 4 times (standard)
|
|
||||||
//long averageTime = 0;
|
|
||||||
for (int i = 0; i < 4; i++)
|
for (int i = 0; i < 4; i++)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
PingReply pingReply = ping.Send(host, 1000, buffer, pingOptions);
|
PingReply pingReply = ping.Send(host, 1000, buffer, pingOptions);
|
||||||
if (pingReply != null)
|
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 = "Ошибка подключения по неизвестной причине.";
|
returnMessage = "Ошибка подключения по неизвестной причине.";
|
||||||
|
throw new Exception(message: string.Empty);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case IPStatus.TimedOut:
|
||||||
|
returnMessage = "Время подключения истекло.";
|
||||||
|
break;
|
||||||
|
case IPStatus.DestinationHostUnreachable:
|
||||||
|
returnMessage = "Заданный узел недоступен.";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
returnMessage = string.Format("Ошибка пинга: {0}", pingReply.Status.ToString());
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (PingException ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
returnMessage = string.Format("Ошибка подключения: {0}", ex.Message);
|
if (ex.Message != string.Empty)
|
||||||
}
|
returnMessage = string.Format("Ошибка подключения: {0}", ex.Message);
|
||||||
catch (SocketException ex)
|
|
||||||
{
|
|
||||||
returnMessage = string.Format("Ошибка подключения: {0}", ex.Message);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return returnMessage;
|
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()
|
public static void ResetAdminPassword()
|
||||||
{
|
{
|
||||||
string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString();
|
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)
|
DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор"));
|
||||||
//{
|
|
||||||
// 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.Properties["LockOutTime"].Value = 0;
|
||||||
|
directoryEntry.Invoke("SetPassword", "Qwe12345");
|
||||||
directoryEntry.CommitChanges();
|
directoryEntry.CommitChanges();
|
||||||
directoryEntry.Close();
|
directoryEntry.Close();
|
||||||
//Console.WriteLine("Пароль установлен.");
|
|
||||||
|
Console.WriteLine("Пароль сброшен.");
|
||||||
Main();
|
Main();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ShowDomainUserInfo()
|
private static void ShowDomainUserInfo()
|
||||||
{
|
{
|
||||||
Console.Write("\nВведите имя пользователя (пр. 'lev.rusanov'): ");
|
Console.Write("\nВведите имя пользователя (пр. 'lev.rusanov'): ");
|
||||||
string username = "user " + Console.ReadLine().Trim() + " /domain";
|
string username = Console.ReadLine().Trim();
|
||||||
if (username == string.Empty || username.Length == 0)
|
if (username == string.Empty || username.Length == 0)
|
||||||
{
|
{
|
||||||
ShowDomainUserInfo();
|
ShowDomainUserInfo();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Console.WriteLine();
|
Console.WriteLine();
|
||||||
|
|
||||||
|
username = $"user {username} /domain";
|
||||||
|
|
||||||
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
|
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
|
||||||
{
|
{
|
||||||
@@ -137,26 +130,10 @@ namespace domain_utility
|
|||||||
|
|
||||||
List<string> strArr = new List<string> {};
|
List<string> strArr = new List<string> {};
|
||||||
while (!proc.StandardOutput.EndOfStream)
|
while (!proc.StandardOutput.EndOfStream)
|
||||||
{
|
|
||||||
strArr.Add(proc.StandardOutput.ReadLine());
|
strArr.Add(proc.StandardOutput.ReadLine());
|
||||||
}
|
|
||||||
|
|
||||||
proc.Close();
|
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;
|
Match regex;
|
||||||
bool groupsFlag = false;
|
bool groupsFlag = false;
|
||||||
for (int i = 0; i < strArr.Count; i++)
|
for (int i = 0; i < strArr.Count; i++)
|
||||||
@@ -190,37 +167,37 @@ namespace domain_utility
|
|||||||
|
|
||||||
private static void ShowComputerBootupTime()
|
private static void ShowComputerBootupTime()
|
||||||
{
|
{
|
||||||
Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'R54-630300IT04'): ");
|
Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'IT04', '630300IT04', 'R54-630300IT04'): ");
|
||||||
string computerName = Console.ReadLine().Trim();
|
string remote = Console.ReadLine().Trim();
|
||||||
if (computerName == string.Empty || computerName.Length == 0 || !Regex.Match(computerName, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success)
|
if (remote == string.Empty || remote.Length == 0)
|
||||||
{
|
{
|
||||||
ShowComputerBootupTime();
|
ShowComputerBootupTime();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Console.WriteLine();
|
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
|
try
|
||||||
{
|
{
|
||||||
scope.Connect();
|
scope.Connect();
|
||||||
var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem");
|
var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem");
|
||||||
var searcher = new ManagementObjectSearcher(scope, query);
|
var searcher = new ManagementObjectSearcher(scope, query);
|
||||||
var firstResult = searcher.Get().OfType<ManagementObject>().First(); //assumes that we do have at least one result
|
var firstResult = searcher.Get().OfType<ManagementObject>().First()["LastBootUpTime"];
|
||||||
Console.WriteLine("Дата последней загрузки: " + ManagementDateTimeConverter.ToDateTime(firstResult["LastBootUpTime"].ToString()));
|
DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString());
|
||||||
/*ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
|
Console.WriteLine("Дата последней загрузки: " + lastBootUp);
|
||||||
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
|
Console.WriteLine("Время работы (д:ч:м:с): " + (DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime()).ToString(@"d\:hh\:mm\:ss"));
|
||||||
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)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
Console.WriteLine("Компьютер не найден. Попробуйте еще раз.");
|
Console.WriteLine("Компьютер не найден. Попробуйте еще раз.");
|
||||||
@@ -232,19 +209,31 @@ namespace domain_utility
|
|||||||
|
|
||||||
private static void StartPing()
|
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();
|
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();
|
StartPing();
|
||||||
return;
|
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)
|
if (Regex.Match(host, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
IPAddress ip = Dns.GetHostEntry(host).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);
|
IPAddress ip = Dns.GetHostEntry(host).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);
|
||||||
Console.WriteLine();
|
|
||||||
Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", host, ip);
|
Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", host, ip);
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
@@ -256,7 +245,6 @@ namespace domain_utility
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Console.WriteLine();
|
|
||||||
Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", host);
|
Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", host);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,23 +259,27 @@ namespace domain_utility
|
|||||||
|
|
||||||
private static void OpenComputerCups()
|
private static void OpenComputerCups()
|
||||||
{
|
{
|
||||||
Console.Write("\nВведите имя компьютера: ");
|
Console.WriteLine("\nВведите IP адрес или имя компьютера (пр. 'IT04', '630300IT04', 'R54-630300IT04'): ");
|
||||||
string input = Console.ReadLine().Trim();
|
string remote = Console.ReadLine().Trim();
|
||||||
if (input == string.Empty || input.Length == 0)
|
if (remote == string.Empty || remote.Length == 0)
|
||||||
{
|
{
|
||||||
OpenComputerCups();
|
OpenComputerCups();
|
||||||
return;
|
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");
|
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
|
||||||
break;
|
OpenComputerCups();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Process.Start($"http://{remote.ToUpper()}:631/printers");
|
||||||
|
|
||||||
Console.WriteLine();
|
Console.WriteLine();
|
||||||
Main();
|
Main();
|
||||||
}
|
}
|
||||||
@@ -298,22 +290,20 @@ namespace domain_utility
|
|||||||
"1 - посмотреть информацию о пользователе\n" +
|
"1 - посмотреть информацию о пользователе\n" +
|
||||||
"2 - посмотреть дату последней загрузки компьютера (только Windows)\n" +
|
"2 - посмотреть дату последней загрузки компьютера (только Windows)\n" +
|
||||||
"3 - ping компьютера\n" +
|
"3 - ping компьютера\n" +
|
||||||
//"4 - сброс пароля локального администратора\n" +
|
//"4 - сброс пароля локального администратора (только Windows)\n" +
|
||||||
"4 - открыть CUPS введенного компьютера");
|
"4 - открыть CUPS выбранного компьютера");
|
||||||
string choice;
|
int choice;
|
||||||
while(true)
|
while (!int.TryParse(Console.ReadLine(), out choice))
|
||||||
{
|
{
|
||||||
choice = Console.ReadLine().Trim();
|
Console.WriteLine("Введите цифру!");
|
||||||
if (choice != string.Empty || choice.Length != 0)
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
switch (Convert.ToInt32(choice))
|
switch (choice)
|
||||||
{
|
{
|
||||||
case 1: ShowDomainUserInfo(); break;
|
case 1: ShowDomainUserInfo(); break;
|
||||||
case 2: ShowComputerBootupTime(); break;
|
case 2: ShowComputerBootupTime(); break;
|
||||||
case 3: StartPing(); break;
|
case 3: StartPing(); break;
|
||||||
//case 4: ResetAdminPassword(); break;
|
|
||||||
case 4: OpenComputerCups(); break;
|
case 4: OpenComputerCups(); break;
|
||||||
|
case 564: ResetAdminPassword(); break;
|
||||||
default:
|
default:
|
||||||
{
|
{
|
||||||
Console.WriteLine("Неправильный выбор!");
|
Console.WriteLine("Неправильный выбор!");
|
||||||
|
|||||||
Reference in New Issue
Block a user