Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
This commit is contained in:
2024-11-01 15:13:35 +07:00
parent 19964226bb
commit 22452c057b
4 changed files with 148 additions and 11 deletions

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.vs
bin/
obj/
packages/
*.csproj.user

View File

@@ -10,6 +10,7 @@ using System.Threading;
using System.Net;
using System.DirectoryServices;
using System.Security.Principal;
using Renci.SshNet;
namespace domain_utility
{
@@ -30,14 +31,15 @@ namespace domain_utility
{ "^[rR]\\d*[-]\\d+[a-zA-Z]+\\d+$", "" } // R54-630300THE01
};
private static string InputRemoteComputer(string str, Action callback)
private static string InputData(string str, Action callback, bool withClear = true)
{
Console.Clear();
if (withClear)
Console.Clear();
Console.WriteLine(str);
Console.Write("> ");
string remote = Console.ReadLine().Trim();
if (remote == string.Empty || remote.Length == 0)
InputRemoteComputer(str, callback);
InputData(str, callback);
Console.WriteLine();
return remote;
}
@@ -136,15 +138,15 @@ namespace domain_utility
private static void ShowDomainUserInfo()
{
string username = InputRemoteComputer("\nВведите имя пользователя (пр. 'lev.rusanov'): ", ShowDomainUserInfo);
string username = InputData("\nВведите имя пользователя (пр. 'lev.rusanov'): ", ShowDomainUserInfo);
username = $"user {username} /domain";
ProcessStartInfo procStartInfo = new ProcessStartInfo("net", username)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
UseShellExecute = false
};
Process proc = new Process { StartInfo = procStartInfo };
proc.Start();
@@ -188,7 +190,7 @@ namespace domain_utility
private static void ShowComputerBootupTime()
{
string remote = InputRemoteComputer("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'): ",
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
ShowComputerBootupTime);
if (!IsStringContainIp(remote))
@@ -224,7 +226,7 @@ namespace domain_utility
private static void StartPing()
{
string remote = InputRemoteComputer("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'): ",
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
StartPing);
if (!IsStringContainIp(remote))
@@ -266,7 +268,7 @@ namespace domain_utility
private static void OpenComputerCups()
{
string remote = InputRemoteComputer("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'): ",
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
OpenComputerCups);
if (!IsStringContainIp(remote))
@@ -287,7 +289,7 @@ namespace domain_utility
private static void StartRDPConnection()
{
string remote = InputRemoteComputer("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'): ",
string remote = InputData("\nВведите IP адрес или имя компьютера (пр. 10.234.16.129, 'IT04', '630300IT04', 'R54-630300IT04'):",
StartRDPConnection);
if (!IsStringContainIp(remote))
@@ -310,17 +312,97 @@ namespace domain_utility
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 - сброс пароля локального администратора (только Windows)",
"4 - открыть CUPS выбранного компьютера (только Linux)",
"5 - удаленно подключиться к компьютеру (только Windows -> Windows, Windows -> Linux)"
"5 - удаленно подключиться к компьютеру (Windows -> Windows, Windows -> Linux)",
"6 - выполнить команду удаленно (только Windows -> Linux)",
"7 - удаленная перезагрузка компьютера (только Windows)",
};
for (int i = 0; i < menuList.Length; i++)
Console.WriteLine(menuList[i]);
@@ -334,6 +416,8 @@ namespace domain_utility
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:
{

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="packages\ILRepack.Lib.MSBuild.Task.2.0.34.2\build\ILRepack.Lib.MSBuild.Task.targets" Condition="Exists('packages\ILRepack.Lib.MSBuild.Task.2.0.34.2\build\ILRepack.Lib.MSBuild.Task.targets')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -12,6 +13,8 @@
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -33,10 +36,22 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.AsyncInterfaces.1.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Renci.SshNet, Version=2024.1.0.0, Culture=neutral, PublicKeyToken=1cee9f8bde3db106, processorArchitecture=MSIL">
<HintPath>packages\SSH.NET.2024.1.0\lib\net462\Renci.SshNet.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.Management" />
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
@@ -50,6 +65,35 @@
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\ILRepack.Lib.MSBuild.Task.2.0.34.2\build\ILRepack.Lib.MSBuild.Task.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\ILRepack.Lib.MSBuild.Task.2.0.34.2\build\ILRepack.Lib.MSBuild.Task.targets'))" />
</Target>
<!-- <Target Name="AfterBuild" Condition="'$(Configuration)' == 'Release'"> -->
<!-- <ItemGroup> -->
<!-- <InputAssemblies Include="$(OutputPath)\$(AssemblyName).exe" /> -->
<!-- <InputAssemblies Include="$(OutputPath)\Microsoft.Bcl.AsyncInterfaces.dll" /> -->
<!-- <InputAssemblies Include="$(OutputPath)\System.Threading.Tasks.Extensions.dll" /> -->
<!-- <InputAssemblies Include="$(OutputPath)\System.Runtime.CompilerServices.Unsafe.dll" /> -->
<!-- <InputAssemblies Include="$(OutputPath)\Renci.SshNet.dll" /> -->
<!-- <InputAssemblies Include="$(OutputPath)\*.dll" /> -->
<!-- </ItemGroup> -->
<!-- <ItemGroup> -->
<!-- Must be a fully qualified name -->
<!-- <DoNotInternalizeAssemblies Include="ExampleAssemblyToMerge3" /> -->
<!-- </ItemGroup> -->
<!-- InternalizeExclude="@(DoNotInternalizeAssemblies)" -->
<!-- <ILRepack -->
<!-- Parallel="true" -->
<!-- Internalize="true" -->
<!-- InputAssemblies="@(InputAssemblies)" -->
<!-- TargetKind="Exe" -->
<!-- OutputFile="$(OutputPath)\$(AssemblyName)_merged.exe" -->
<!-- /> -->
<!-- </Target> -->
</Project>

8
packages.config Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ILRepack.Lib.MSBuild.Task" version="2.0.34.2" targetFramework="net48" developmentDependency="true" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="1.0.0" targetFramework="net48" />
<package id="SSH.NET" version="2024.1.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.2" targetFramework="net48" />
</packages>