Update Program.cs

Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
This commit is contained in:
2024-11-06 21:17:12 +07:00
parent 60369432a8
commit 1d35170d6d

View File

@@ -31,33 +31,12 @@ namespace domain_utility
{ "^[rR]\\d*[-]\\d+[a-zA-Z]+\\d+$", "" } // R54-630300THE01 { "^[rR]\\d*[-]\\d+[a-zA-Z]+\\d+$", "" } // R54-630300THE01
}; };
private static string InputData(string str, Action callback, bool withClear = true) //private static volatile bool _ping_stop = false;
{ private static bool _ping_stop = false;
if (withClear)
Console.Clear();
Console.WriteLine(str);
Console.Write("> ");
string remote = Console.ReadLine().Trim();
if (remote == string.Empty || remote.Length == 0)
InputData(str, callback);
Console.WriteLine();
return remote;
}
private static void BackToMenu(Action callback, bool noMessage = false) private static bool IsStringContainIp(string ip)
{ {
if (noMessage == false) return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success;
Console.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную.");
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Enter)
callback.Invoke();
else if (key == ConsoleKey.Escape)
Menu();
else
{
Console.WriteLine("Нажмите Enter или ESC!");
BackToMenu(callback, true);
}
} }
private static string СheckComputerName(string pcName) private static string СheckComputerName(string pcName)
@@ -68,9 +47,43 @@ namespace domain_utility
return string.Empty; return string.Empty;
} }
private static bool IsStringContainIp(string ip) private static string InputData(string message, Action callback, bool withClear = true, bool withChecks = true)
{ {
return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success; if (withClear)
Console.Clear();
Console.WriteLine(message);
Console.Write("> ");
string remote = Console.ReadLine().Trim();
if (remote == string.Empty || remote.Length == 0)
InputData(message, callback, withClear, withChecks);
Console.WriteLine();
if (withChecks)
if (!IsStringContainIp(remote))
{
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(callback);
}
}
return remote;
}
private static void BackToMenu(Action callback, bool withMessage = true)
{
if (withMessage)
Console.WriteLine("\nНажмите Enter чтобы продолжить, ESC чтобы вернуться на главную.");
ConsoleKey key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Enter)
callback.Invoke();
else if (key == ConsoleKey.Escape)
Menu();
else
{
Console.WriteLine("Нажмите Enter или ESC!");
BackToMenu(callback, false);
}
} }
private static string PingHost(string host) private static string PingHost(string host)
@@ -126,7 +139,7 @@ namespace domain_utility
string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString();
string machineName = machineNameAndUser.Substring(0, machineNameAndUser.IndexOf('\\')); string machineName = machineNameAndUser.Substring(0, machineNameAndUser.IndexOf('\\'));
using (var directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор"))) using (DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор")))
{ {
//directoryEntry.Properties["LockOutTime"].Value = 0; //directoryEntry.Properties["LockOutTime"].Value = 0;
directoryEntry.Invoke("SetPassword", "Qwe12345"); directoryEntry.Invoke("SetPassword", "Qwe12345");
@@ -195,23 +208,12 @@ namespace domain_utility
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
ShowComputerBootupTime); ShowComputerBootupTime);
if (!IsStringContainIp(remote)) ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", remote));
{
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(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"); ObjectQuery query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem");
var searcher = new ManagementObjectSearcher(scope, query); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
var firstResult = searcher.Get().OfType<ManagementObject>().First()["LastBootUpTime"]; var firstResult = searcher.Get().OfType<ManagementObject>().First()["LastBootUpTime"];
DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString()); DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(firstResult.ToString());
Console.WriteLine("Дата последней загрузки: " + lastBootUp); Console.WriteLine("Дата последней загрузки: " + lastBootUp);
@@ -219,35 +221,32 @@ namespace domain_utility
} }
catch (Exception) catch (Exception)
{ {
Console.WriteLine("Компьютер не найден. Попробуйте еще раз."); Console.WriteLine("Произошла ошибка. Попробуйте еще раз.");
BackToMenu(ShowComputerBootupTime); BackToMenu(ShowComputerBootupTime);
} }
BackToMenu(ShowComputerBootupTime); BackToMenu(ShowComputerBootupTime);
} }
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
_ping_stop = true;
}
private static void StartPing() private static void StartPing()
{ {
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
StartPing); StartPing);
if (!IsStringContainIp(remote)) string correctName = СheckComputerName(remote);
{ if (correctName != string.Empty)
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(StartPing);
return;
}
}
if (Regex.Match(remote, @"^([rR]\d*[-]\d+[a-zA-Z]+\d+)$").Success)
{ {
try try
{ {
IPAddress ip = Dns.GetHostEntry(remote).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); IPAddress ip = Dns.GetHostEntry(correctName).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);
Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", remote, ip); remote = ip.ToString();
Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", correctName, remote);
} }
catch (Exception) catch (Exception)
{ {
@@ -259,11 +258,15 @@ namespace domain_utility
else else
Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote); Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote);
for (int i = 0; i < 10; i++) Console.CancelKeyPress += Console_CancelKeyPress;
for (int i = 0; i < 4; i++)
{ {
if (_ping_stop) break;
Console.WriteLine(PingHost(remote)); Console.WriteLine(PingHost(remote));
Thread.Sleep(1000); Thread.Sleep(1000);
} }
Console.CancelKeyPress -= Console_CancelKeyPress;
_ping_stop = false;
BackToMenu(StartPing); BackToMenu(StartPing);
} }
@@ -273,17 +276,6 @@ namespace domain_utility
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
OpenComputerCups); OpenComputerCups);
if (!IsStringContainIp(remote))
{
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(OpenComputerCups);
return;
}
}
Process.Start($"https://{remote}:631/printers"); Process.Start($"https://{remote}:631/printers");
BackToMenu(OpenComputerCups); BackToMenu(OpenComputerCups);
@@ -294,17 +286,6 @@ namespace domain_utility
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
StartRDPConnection); StartRDPConnection);
if (!IsStringContainIp(remote))
{
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(StartRDPConnection);
return;
}
}
remote = $"/v:{remote} /f"; remote = $"/v:{remote} /f";
Process proc = new Process(); Process proc = new Process();
proc.StartInfo = new ProcessStartInfo("mstsc", remote); proc.StartInfo = new ProcessStartInfo("mstsc", remote);
@@ -313,54 +294,77 @@ namespace domain_utility
BackToMenu(StartRDPConnection); BackToMenu(StartRDPConnection);
} }
private static void ExecuteCommandViaSSH() private static string InputPassword()
{ {
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
ExecuteCommandViaSSH);
if (!IsStringContainIp(remote))
{
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(ExecuteCommandViaSSH);
return;
}
}
Console.WriteLine("Введите пароль от СВОЕЙ учетной записи:"); Console.WriteLine("Введите пароль от СВОЕЙ учетной записи:");
Console.Write("> "); Console.Write("> ");
string password = string.Empty; string password = string.Empty;
while (true) ConsoleKeyInfo key;
do
{ {
var key = Console.ReadKey(true); key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter) if (key.KeyChar < 32 || key.KeyChar > 126)
break; continue;
if (key.Key == ConsoleKey.Backspace && password.Length > 0) if (key.Key == ConsoleKey.Backspace && password.Length > 0)
password = password.Substring(0, password.Length - 1); password = password.Substring(0, password.Length - 1);
else if (key.Key != ConsoleKey.Backspace) else if (key.Key != ConsoleKey.Backspace)
password += key.KeyChar; password += key.KeyChar;
} }
while (key.Key != ConsoleKey.Enter);
Console.Write("\n\n"); Console.Write("\n\n");
return password;
}
string commandToExecute = InputData("Введите команду для выполнения:", ExecuteCommandViaSSH, false); private static void ExecuteCommandViaSSH(string remote, string password, string commandToExecute)
{
string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString();
int indexOfUserName = machineNameAndUser.IndexOf('\\') + 1; int indexOfUserName = machineNameAndUser.IndexOf('\\') + 1;
string machineUser = machineNameAndUser.Substring(indexOfUserName, machineNameAndUser.Length - indexOfUserName).ToLower(); string machineUser = machineNameAndUser.Substring(indexOfUserName, machineNameAndUser.Length - indexOfUserName).ToLower();
using (var client = new SshClient(remote, machineUser, password)) using (SshClient client = new SshClient(remote, machineUser, password))
{ {
client.Connect(); client.Connect();
// "sudo sed -i 's/update_interval = 0.5,/update_interval = 300,/' /etc/conky/conky.conf"
SshCommand command = client.RunCommand(commandToExecute); SshCommand command = client.RunCommand(commandToExecute);
Console.WriteLine(command.Result); Console.WriteLine(command.Result);
client.Disconnect(); client.Disconnect();
} }
Console.WriteLine("Вроде что-то произошло, но это не точно"); }
BackToMenu(ExecuteCommandViaSSH); private static void FixConky()
{
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
FixConky);
string password = InputPassword();
ExecuteCommandViaSSH(remote, password, "sudo sed -i 's/update_interval = 0.5,/update_interval = 300,/' /etc/conky/conky.conf");
BackToMenu(FixConky);
}
private static void RemoteRebootLinux()
{
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
RemoteRebootLinux);
string password = InputPassword();
ExecuteCommandViaSSH(remote, password, "sudo shutdown -r +3 \"Через 3 минуты будет произведена перезагрузка ПК!\"");
BackToMenu(RemoteRebootLinux);
}
private static void ExecuteCustomCommandViaSSH()
{
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
ExecuteCustomCommandViaSSH);
string commandToExecute = InputData("Введите команду для выполнения:", ExecuteCustomCommandViaSSH, withClear: true, withChecks: false);
string password = InputPassword();
ExecuteCommandViaSSH(remote, password, commandToExecute);
BackToMenu(ExecuteCustomCommandViaSSH);
} }
private static void RemoteRebootWindows() private static void RemoteRebootWindows()
@@ -368,17 +372,6 @@ namespace domain_utility
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):", string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
RemoteRebootWindows); RemoteRebootWindows);
if (!IsStringContainIp(remote))
{
remote = СheckComputerName(remote);
if (remote == string.Empty)
{
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
BackToMenu(RemoteRebootWindows);
return;
}
}
remote = $"/m \\\\{remote} /r /f /t 180 /c 'Через 3 минуты будет произведена перезагрузка ПК!'"; remote = $"/m \\\\{remote} /r /f /t 180 /c 'Через 3 минуты будет произведена перезагрузка ПК!'";
Process proc = new Process(); Process proc = new Process();
proc.StartInfo = new ProcessStartInfo("shutdown", remote); proc.StartInfo = new ProcessStartInfo("shutdown", remote);
@@ -390,15 +383,17 @@ namespace domain_utility
} }
static readonly string[] menuList = { static readonly string[] menuList = {
//"4 - сброс пароля локального администратора (только Windows)", //"630300 - сброс пароля локального администратора (только Windows)", // ResetAdminPassword
"Выберите действие:", "Выберите действие:",
"1 - посмотреть информацию о пользователе (только Windows)", "1 - ping компьютера", // StartPing
"2 - посмотреть дату последней загрузки компьютера (только Windows)", "2 - посмотреть информацию о пользователе (только Windows)", // ShowDomainUserInfo
"3 - ping компьютера", "3 - посмотреть дату последней загрузки компьютера (только Windows)", // ShowComputerBootupTime
"4 - открыть CUPS выбранного компьютера (только Linux)", "4 - удаленно подключиться к компьютеру (Windows -> Windows, Windows -> Linux)", // StartRDPConnection
"5 - удаленно подключиться к компьютеру (Windows -> Windows, Windows -> Linux)", "5 - удаленная перезагрузка компьютера (только Windows)", // RemoteRebootWindows
"6 - выполнить команду удаленно (только Windows -> Linux)", "6 - открыть CUPS выбранного компьютера (только Linux)", // OpenComputerCups
"7 - удаленная перезагрузка компьютера (только Windows)", "7 - изменить время обновления conky с 0.5 на 300", // FixConky
"8 - удаленная перезагрузка компьютера (только Linux)", // RemoteRebootLinux
"9 - выполнить команду удаленно (только Windows -> Linux)", // ExecuteCustomCommandViaSSH
}; };
private static void Menu() private static void Menu()
@@ -407,18 +402,24 @@ namespace domain_utility
for (int i = 0; i < menuList.Length; i++) for (int i = 0; i < menuList.Length; i++)
Console.WriteLine(menuList[i]); Console.WriteLine(menuList[i]);
int choice; int choice;
Console.Write("> ");
while (!int.TryParse(Console.ReadLine(), out choice)) while (!int.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Введите цифру!"); Console.WriteLine("Введите цифру!");
Console.Write("> ");
}
switch (choice) switch (choice)
{ {
case 1: ShowDomainUserInfo(); break; case 1: StartPing(); break;
case 2: ShowComputerBootupTime(); break; case 2: ShowDomainUserInfo(); break;
case 3: StartPing(); break; case 3: ShowComputerBootupTime(); break;
case 4: OpenComputerCups(); break; case 4: StartRDPConnection(); break;
case 5: StartRDPConnection(); break; case 5: RemoteRebootWindows(); break;
case 6: ExecuteCommandViaSSH(); break; case 6: OpenComputerCups(); break;
case 7: RemoteRebootWindows(); break; case 7: FixConky(); break;
case 51422415: ResetAdminPassword(); break; case 8: RemoteRebootLinux(); break;
case 9: ExecuteCustomCommandViaSSH(); break;
case 630300: ResetAdminPassword(); break;
default: default:
{ {
Console.WriteLine("Неправильный выбор!"); Console.WriteLine("Неправильный выбор!");