wakka/SshConnection.cs
2025-05-17 19:17:45 -05:00

106 lines
3.1 KiB
C#

using Renci.SshNet;
using Renci.SshNet.Common;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace wakka
{
public static class SshConnection
{
public static string User { get; set; } = string.Empty;
public static SshClient? Client { get; set; } = null;
public readonly static string SshKeyPath = Path.Combine(App.LocalStroageData.Path, "key");
public static PrivateKeyFile? Key { get; set; } = null;
public static string? PublicKey { get; set; } = null;
public static bool KeyExists() => File.Exists(SshKeyPath);
public static void InitializeConnection(string user)
{
if (!File.Exists(SshKeyPath) || user == string.Empty)
{
throw new InvalidOperationException("No SSH key or user is empty");
}
else
{
User = user;
Key = new PrivateKeyFile(SshKeyPath);
Client = new SshClient("tilde.town", User, Key);
try
{
Client.Connect();
}
catch (SshAuthenticationException)
{
Key = null;
throw;
}
}
}
public static string RunCommand(string command)
{
if (Client == null || !Client.IsConnected)
{
throw new InvalidOperationException("SSH client is not connected.");
}
var rc = Client.RunCommand(command);
return rc.Result;
}
public static bool DoesFileExist(string path)
{
if (Client == null || !Client.IsConnected)
{
throw new InvalidOperationException("SSH client is not connected.");
}
var command = Client.CreateCommand($"test -e {path} && echo 1 || echo 0");
var result = command.Execute();
return result.Trim() == "1";
}
public static async void RunCommandWithInput(string command, string input)
{
if (Client == null || !Client.IsConnected)
{
throw new InvalidOperationException("SSH client is not connected.");
}
using (SshCommand task = Client.CreateCommand(command))
{
Task executeTask = task.ExecuteAsync(CancellationToken.None);
using (Stream inputStream = task.CreateInputStream())
{
inputStream.Write(Encoding.UTF8.GetBytes(input));
}
await executeTask;
}
}
public static string CreateSshKey()
{
var keygen = new SshKeyGenerator.SshKeyGenerator(2048);
var privateKey = keygen.ToPrivateKey();
File.WriteAllText(SshKeyPath, privateKey);
return keygen.ToRfcPublicKey("wakka");
}
public static void DeleteSshKey()
{
if (File.Exists(SshKeyPath))
{
File.Delete(SshKeyPath);
}
}
}
}