437 lines
19 KiB
C#
437 lines
19 KiB
C#
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;
|
||
using Renci.SshNet;
|
||
|
||
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 InputData(string str, Action callback, bool withClear = true)
|
||
{
|
||
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)
|
||
{
|
||
if (noMessage == false)
|
||
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)
|
||
{
|
||
for (int i = 0; i < computerNameRegex.GetLength(0); i++)
|
||
if (Regex.Match(pcName, computerNameRegex[i, 0]).Success)
|
||
return $"{computerNameRegex[i, 1]}{pcName}".ToUpper();
|
||
return string.Empty;
|
||
}
|
||
|
||
private static bool IsStringContainIp(string ip)
|
||
{
|
||
return Regex.Match(ip, @"^(\d+[.]\d+[.]\d+[.]\d+)$").Success;
|
||
}
|
||
|
||
private static string PingHost(string host)
|
||
{
|
||
string returnMessage = string.Empty;
|
||
PingOptions pingOptions = new PingOptions() { DontFragment = true }; // TTL = 128
|
||
using (Ping ping = new Ping())
|
||
{
|
||
byte[] buffer = new byte[32];
|
||
for (int i = 0; i < 4; i++)
|
||
{
|
||
try
|
||
{
|
||
PingReply pingReply = ping.Send(host, 1000, buffer, pingOptions);
|
||
if (pingReply == null)
|
||
{
|
||
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 (Exception ex)
|
||
{
|
||
if (ex.Message != string.Empty)
|
||
returnMessage = string.Format("Ошибка подключения: {0}", ex.Message);
|
||
}
|
||
}
|
||
}
|
||
return returnMessage;
|
||
}
|
||
|
||
public static void ResetAdminPassword()
|
||
{
|
||
string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString();
|
||
string machineName = machineNameAndUser.Substring(0, machineNameAndUser.IndexOf('\\'));
|
||
|
||
DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", machineName, "Администратор"));
|
||
directoryEntry.Properties["LockOutTime"].Value = 0;
|
||
directoryEntry.Invoke("SetPassword", "Qwe12345");
|
||
directoryEntry.CommitChanges();
|
||
directoryEntry.Close();
|
||
|
||
Console.WriteLine("Пароль сброшен.");
|
||
BackToMenu(Menu);
|
||
}
|
||
|
||
private static void ShowDomainUserInfo()
|
||
{
|
||
string username = InputData("\nВведите имя пользователя (пр. 'lev.rusanov'): ", ShowDomainUserInfo);
|
||
|
||
username = $"user {username} /domain";
|
||
|
||
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
|
||
{
|
||
CreateNoWindow = true,
|
||
UseShellExecute = false,
|
||
RedirectStandardOutput = true,
|
||
};
|
||
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();
|
||
|
||
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);
|
||
}
|
||
}
|
||
}
|
||
|
||
BackToMenu(ShowDomainUserInfo);
|
||
}
|
||
|
||
private static void ShowComputerBootupTime()
|
||
{
|
||
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
|
||
ShowComputerBootupTime);
|
||
|
||
if (!IsStringContainIp(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
|
||
{
|
||
scope.Connect();
|
||
var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem");
|
||
var searcher = new ManagementObjectSearcher(scope, query);
|
||
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 (Exception)
|
||
{
|
||
Console.WriteLine("Компьютер не найден. Попробуйте еще раз.");
|
||
BackToMenu(ShowComputerBootupTime);
|
||
}
|
||
|
||
BackToMenu(ShowComputerBootupTime);
|
||
}
|
||
|
||
private static void StartPing()
|
||
{
|
||
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
|
||
StartPing);
|
||
|
||
if (!IsStringContainIp(remote))
|
||
{
|
||
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
|
||
{
|
||
IPAddress ip = Dns.GetHostEntry(remote).AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);
|
||
Console.WriteLine("Обмен пакетами с {0} [{1}] по с 32 байтами данных:", remote, ip);
|
||
}
|
||
catch (Exception)
|
||
{
|
||
Console.WriteLine("Компьютер не найден.");
|
||
BackToMenu(StartPing);
|
||
return;
|
||
}
|
||
}
|
||
else
|
||
Console.WriteLine("Обмен пакетами с {0} по с 32 байтами данных:", remote);
|
||
|
||
for (int i = 0; i < 10; i++)
|
||
{
|
||
Console.WriteLine(PingHost(remote));
|
||
Thread.Sleep(1000);
|
||
}
|
||
|
||
BackToMenu(StartPing);
|
||
}
|
||
|
||
private static void OpenComputerCups()
|
||
{
|
||
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
|
||
OpenComputerCups);
|
||
|
||
if (!IsStringContainIp(remote))
|
||
{
|
||
remote = СheckComputerName(remote);
|
||
if (remote == string.Empty)
|
||
{
|
||
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
|
||
BackToMenu(OpenComputerCups);
|
||
return;
|
||
}
|
||
}
|
||
|
||
Process.Start($"http://{remote}:631/printers");
|
||
|
||
BackToMenu(OpenComputerCups);
|
||
}
|
||
|
||
private static void StartRDPConnection()
|
||
{
|
||
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
|
||
StartRDPConnection);
|
||
|
||
if (!IsStringContainIp(remote))
|
||
{
|
||
remote = СheckComputerName(remote);
|
||
if (remote == string.Empty)
|
||
{
|
||
Console.WriteLine("Имя компьютера или IP-адрес не распознаны! Попробуйте еще раз.");
|
||
BackToMenu(StartRDPConnection);
|
||
return;
|
||
}
|
||
}
|
||
|
||
remote = $"/v:{remote} /f";
|
||
Process proc = new Process {
|
||
StartInfo = new ProcessStartInfo("mstsc", remote)
|
||
};
|
||
proc.Start();
|
||
|
||
BackToMenu(StartRDPConnection);
|
||
}
|
||
|
||
private static void ExecuteCommandViaSSH()
|
||
{
|
||
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.Write("> ");
|
||
string password = string.Empty;
|
||
while (true)
|
||
{
|
||
var key = Console.ReadKey(true);
|
||
if (key.Key == ConsoleKey.Enter)
|
||
break;
|
||
if (key.Key == ConsoleKey.Backspace && password.Length > 0)
|
||
password = password.Substring(0, password.Length - 1);
|
||
else if (key.Key != ConsoleKey.Backspace)
|
||
password += key.KeyChar;
|
||
}
|
||
Console.Write("\n\n");
|
||
|
||
string commandToExecute = InputData("Введите команду для выполнения:", ExecuteCommandViaSSH, false);
|
||
|
||
string machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString();
|
||
int indexOfUserName = machineNameAndUser.IndexOf('\\') + 1;
|
||
string machineUser = machineNameAndUser.Substring(indexOfUserName, machineNameAndUser.Length - indexOfUserName).ToLower();
|
||
|
||
using (var client = new SshClient(remote, machineUser, password))
|
||
{
|
||
client.Connect();
|
||
// "sudo sed -i 's/update_interval = 0.5,/update_interval = 300,/' /etc/conky/conky.conf"
|
||
SshCommand command = client.RunCommand(commandToExecute);
|
||
Console.WriteLine(command.Result);
|
||
client.Disconnect();
|
||
}
|
||
Console.WriteLine("Вроде что-то произошло, но это не точно");
|
||
|
||
BackToMenu(ExecuteCommandViaSSH);
|
||
}
|
||
|
||
private static void RemoteRebootWindows()
|
||
{
|
||
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
|
||
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 минуты будет произведена перезагрузка ПК!'";
|
||
Process proc = new Process
|
||
{
|
||
StartInfo = new ProcessStartInfo("shutdown", remote)
|
||
};
|
||
proc.Start();
|
||
|
||
Console.WriteLine("Команда перезагрузки успешно отправлена!");
|
||
|
||
BackToMenu(RemoteRebootWindows);
|
||
}
|
||
|
||
private static void Menu()
|
||
{
|
||
Console.Clear();
|
||
string[] menuList = {
|
||
//"4 - сброс пароля локального администратора (только Windows)",
|
||
"Выберите действие:",
|
||
"1 - посмотреть информацию о пользователе (только Windows)",
|
||
"2 - посмотреть дату последней загрузки компьютера (только Windows)",
|
||
"3 - ping компьютера",
|
||
"4 - открыть CUPS выбранного компьютера (только Linux)",
|
||
"5 - удаленно подключиться к компьютеру (Windows -> Windows, Windows -> Linux)",
|
||
"6 - выполнить команду удаленно (только Windows -> Linux)",
|
||
"7 - удаленная перезагрузка компьютера (только Windows)",
|
||
};
|
||
for (int i = 0; i < menuList.Length; i++)
|
||
Console.WriteLine(menuList[i]);
|
||
int choice;
|
||
while (!int.TryParse(Console.ReadLine(), out choice))
|
||
Console.WriteLine("Введите цифру!");
|
||
switch (choice)
|
||
{
|
||
case 1: ShowDomainUserInfo(); break;
|
||
case 2: ShowComputerBootupTime(); break;
|
||
case 3: StartPing(); break;
|
||
case 4: OpenComputerCups(); break;
|
||
case 5: StartRDPConnection(); break;
|
||
case 6: ExecuteCommandViaSSH(); break;
|
||
case 7: RemoteRebootWindows(); break;
|
||
case 51422415: ResetAdminPassword(); break;
|
||
default:
|
||
{
|
||
Console.WriteLine("Неправильный выбор!");
|
||
Menu();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
static void Main()
|
||
{
|
||
Menu();
|
||
}
|
||
}
|
||
}
|