using Renci.SshNet; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace kawwa { public static class SshConnection { private static SshClient? Client { get; set; } = null; public static string User { get; set; } = string.Empty; private static PrivateKeyFile? Key { get; set; } = null; public static string? PublicKey { get; set; } = null; private readonly static string SshKeyPath = Path.Combine(App.AppDataPath, "key"); private readonly static string SshPubKeyPath = Path.Combine(App.AppDataPath, "key.pub"); public static bool KeyExists() => File.Exists(SshKeyPath) && File.Exists(SshPubKeyPath); public static void CreateSshKey() { var keygen = new SshKeyGenerator.SshKeyGenerator(2048); File.WriteAllText(SshKeyPath, keygen.ToPrivateKey()); File.WriteAllText(SshPubKeyPath, keygen.ToRfcPublicKey("kawwa")); } public static void DeleteSshKey() { if (File.Exists(SshKeyPath)) { File.Delete(SshKeyPath); } if (File.Exists(SshPubKeyPath)) { File.Delete(SshPubKeyPath); } Key = null; PublicKey = null; } public static void InitializeCredentials() { if (!File.Exists(SshKeyPath) || !File.Exists(SshPubKeyPath)) CreateSshKey(); PublicKey = File.ReadAllText(SshPubKeyPath); Key = new PrivateKeyFile(SshKeyPath); } public static void InitializeConnection() { if (Key == null || User == string.Empty) { throw new InvalidOperationException("No SSH key or user is empty."); } Client = new SshClient("tilde.town", User, Key); Client.Connect(); } 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; } } } }