Cisco – Ejecutar script o guion de comandos en router Cisco via ssh con C# y libreria Renci.SshNet
Posted in cisco, Networking, Scripting, Sistemas, Utilidades on Jun 27th, 2012
- Descargar proyecto en c# bajo SharpDevelop miniClienteSSH: ClienteSSH
Referencias:
- Renci.SshNet
- Discursion en foro sshnet.codeplex.com
- Habilitar SSH en IOS o dispositivo Cisco
- Cisco – Ejecutar comando en router Cisco via ssh con c# y libreria Renci.SshNet
El código:
//Solo posteo el código relevante
using ConsoleWidget;
using Renci.SshNet;
using Renci.SshNet.Common;
void Button4Click(object sender, EventArgs e)
{
if (richTextBox2.Text.Length > 0)
{
//
int puerto;
if ((textBox4.Text == "") || (textBox4.Text == null)){
textBox4.Text = "22";
}
//convertimos puerto del textBox4 a int
puerto = Convert.ToInt32(textBox4.Text);
puerto = int.Parse(textBox4.Text);
if (comboBox1.Text=="ssh") {
//ssh.net
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(textBox5.Text,
puerto,textBox2.Text, textBox3.Text);
connectionInfo.Timeout = TimeSpan.FromSeconds(60);
connectionInfo.RetryAttempts = 3;
SshClient mysshclient = new SshClient(connectionInfo);
richTextBox1.ResetText();
//https://sshnet.codeplex.com/discussions/301739
try {
//he definido un usuario en el router
// con provilegios de acceso level 15 y evito la password de 'enable'
mysshclient.Connect();
var stream = mysshclient.CreateShellStream("cisco", 80, 24, 800, 600, 10024);
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
while (stream.Length == 0)
{
Thread.Sleep(500);
}
// Simple line read
var line = reader.ReadLine();
while (line != null)
{
Console.WriteLine(line);
richTextBox1.Text += line + "\r\n";
line = reader.ReadLine();
}
//ejecutamos linea a linea el richtextbox2
foreach (string linea in richTextBox2.Lines) {
string comando = linea;
writer.WriteLine(comando);
while (stream.Length == 0)
{
Thread.Sleep(500);
}
line = reader.ReadLine();
while (line != null)
{
Console.WriteLine(line);
richTextBox1.Text += line + "\n";
line = reader.ReadLine();
}
} //for
//try
} catch (Exception mye) {
mysshclient.Disconnect();
MessageBox.Show(mye.ToString(),"Ha habido un error: ");
throw;
}
mysshclient.Disconnect();
}
// if
} else {
MessageBox.Show("Nada a ejecutar");
}
}
He definido un usuario en el router Cisco con privilegios de acceso level 15 y evito la password de ‘enable’
username Cisco privilege 15 password 0 class
Y por último indicar que se supone que este mini cliente ssh solo se va a conectar a servidores ssh donde ya se confia en la rsa2 key
Por ejemplo, efectuando una conexion con otro cliente ssh (putty) se puede indicar si se confia en la host key.
Y voila




















