new features (ping, reset local admin pwd)

Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
This commit is contained in:
2024-05-20 03:24:24 +07:00
parent 2d00fb51b0
commit 663bbc92c8
2 changed files with 165 additions and 28 deletions

View File

@@ -4,6 +4,12 @@ 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
{
@@ -18,19 +24,99 @@ namespace domain_utility
{ "Членство в глобальных группах", @"([*].+)", "Член групп:\t" }
};
private static string PingHost(string host)
{
string returnMessage = string.Empty;
//PingOptions pingOptions = new PingOptions(128, true);
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:
{
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("Пароль установлен.");
string[] str = {};
Main(str);
}
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";
//}
string username = "user " + Console.ReadLine().Trim() + " /domain";
if (username == string.Empty || username.Length == 0)
{
ShowDomainUserInfo();
return;
}
Console.WriteLine();
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
{
@@ -48,11 +134,6 @@ namespace domain_utility
}
proc.Close();
proc.Dispose();
//if (args.Length > 0)
// for (int i = 0; i < strArr.Count; i++)
// Console.WriteLine(strArr[i]);
//for (int i = 0; i < strArr.Count; i++)
//{
@@ -96,7 +177,6 @@ namespace domain_utility
}
}
Console.ReadLine();
ShowDomainUserInfo();
}
@@ -104,6 +184,13 @@ namespace domain_utility
{
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
{
@@ -114,7 +201,6 @@ namespace domain_utility
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)
{
@@ -126,25 +212,75 @@ namespace domain_utility
Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]);
}*/
}
catch (System.Runtime.InteropServices.COMException)
//catch (System.Runtime.InteropServices.COMException)
catch (Exception)
{
//Console.WriteLine(ex.Message);
Console.WriteLine("Компьютер не найден. Попробуйте еще раз.");
ShowComputerBootupTime();
}
Console.ReadLine();
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();
}
static void Main(string[] args)
{
Console.WriteLine("Выберите действие:\n1 - посмотреть информацию о пользователе\n2 - посмотреть дату последней загрузки компьютера");
string choice = Console.ReadLine();
Console.WriteLine("Выберите действие:\n" +
"1 - посмотреть информацию о пользователе\n" +
"2 - посмотреть дату последней загрузки компьютера\n" +
"3 - ping компьютера\n" +
"4 - сброс пароля локального администратора");
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;
default:
{
Console.WriteLine("Неправильный выбор!");

View File

@@ -35,6 +35,7 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />