Created
September 11, 2023 22:17
-
-
Save ljchuello/85aeb696c78524a9d8ff37552af7587b to your computer and use it in GitHub Desktop.
Método para conectarse desde C# a un terminal SSH en Linux utilizando llave privada
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Leemos la llave | |
string ssh = await File.ReadAllTextAsync(@"C:\UbicacionDeLaLlave\llave.ppk"); | |
// Pasamos a MemoryStream | |
MemoryStream keyStream = new MemoryStream(Encoding.UTF8.GetBytes(ssh)); | |
// Establecemos la conexión | |
ConnectionInfo connectionInfo = new ConnectionInfo("host", "Usuario | Suele ser root", new PrivateKeyAuthenticationMethod("root", new PrivateKeyFile(keyStream))); | |
// Entablamos la conexion | |
using (var client = new SshClient(connectionInfo)) | |
{ | |
// Conectamos | |
client.Connect(); | |
// Enviamos un comando | |
if (client.IsConnected) | |
{ | |
// Comando a enviar | |
string comando = "apt update && sudo upgrade -y"; | |
// Enviamos el comando | |
SshCommand sshCommand = client.RunCommand(comando); | |
// Esperamos la respuesta / mensaje de salida | |
Console.WriteLine(sshCommand.Result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment