7 Sep 2010

.NET SSH Connection using SharpSSH

Last week, I’ve been assigned to a new project. I must be able to parse the text output of a router, get the settings, and then doing something magic in .NET, either save it to Active Directory or something. Then, I found this .NET component, for free. You don’t have to pay for it, called SharpSSH. Well, I don’t care about how the DLL connect to the router and get the command output, but I do care of the result of the command output.

You can download the component in the website. The code are really simple, in this example is written in C#.NET. Oh… I almost forgot, you must add the Reference to Tamir.SharpSSH.DLL, and make sure that you add too the DiffieHellman.dll and Org.Mentalis.Security.dll. Actually we don’t really need those 2 DLLs, but Tamir.SharpSSH.dll does. So you must add the reference, or just include the DLL into the Debug folder in order to make your application runs well.

So here you go the code. First, add the “using” directive into top of your code.

using Tamir.SharpSsh;

And you’re ready to make the magic. First of all, there’s so many SSH class objects defined in the Tamir.SharpSSH.dll, but I choose SshShell. This is the code…

SshShell SSHConn = new SshShell("10.2.54.123", "dean");
SSHConn.Password = "deanp@w";
SSHConn.Connect();

Insert the IP, username, and the password, and Connect. Then you might want to look carefully before writing the code, you must first know the router output behaviour. In my environment, first login to the router, the prompt ended with the character like this “>”, and I must type “enable” and Enter, and then insert the password, and the ending prompt changing to “#”. This is important to make your code not “hanging” because of wrong character assigned to the SshShell object.

SSHConn.ExpectPattern = ">";
SSHConn.RemoveTerminalEmulationCharacters = true;
if (SSHConn.ShellOpened)
{
SSHConn.WriteLine("enable");
SSHConn.Expect(">");
SSHConn.WriteLine("deanp@w");
SSHConn.Expect("#");
SSHConn.WriteLine("term length 0");
SSHConn.Expect("#");
SSHConn.WriteLine("show run");
sOut = SSHConn.Expect("#");
SSHConn.WriteLine("exit");
SSHConn.Expect("#");
}

That’s what I’m talking about. After you’ve connected to the router, then the important thing is you must write your line of command to the router. To get the return and probably get the output to a string variable, you can assign variable like in my example, sOut. When you don’t want to get the return, just “apply” the command you’ve set for the router, just execute the “Expect” method, with the ending response of the router like “#” character.


After all, you must close the object using “Close” method, and you’re done.

1 komentar:

[give me your ideas, hopes, comments and compliments below...]
[aaand...... +1 if you need to....]