Click here to Skip to main content
Click here to Skip to main content

sharpSsh - A Secure Shell (SSH) library for .NET

By , 29 Oct 2005
 

Introduction

Recently there was a need to connect to a SSH server from my C# code. I needed to perform a simple task: login to a remote Linux device, execute a command and read the response. I knew there were a number of free Java SSH libraries out there and I hoped to find a free .NET one that will allow me to do just that, but all I could find were commercial components. After experimenting with an open source Java SSH library called JSch I decided to try and port it to C# just for the sake of exercise. The result is the attached sharpSsh library and this article which explains how to use it.

Background

SSH (Secure Shell) is a protocol to log into another computer over a network, to execute commands in a remote machine, and to move files from one machine to another. It provides strong authentication and secure communications over unsecured channels. The JSch library is a pure Java implementation of the SSH2 protocol suite; It contains many features such as port forwarding, X11 forwarding, secure file transfer and supports numerous cipher and MAC algorithms. JSch is licensed under BSD style license.

My C# version is not a full port of JSch. I ported only the minimal required features in order to complete my simple task. The following list summarizes the supported features of the library:

  • Key exchange: diffie-hellman-group-exchange-sha1, diffie-hellman-group1-sha1.
  • Cipher: 3des-cbc
  • MAC: hmac-md5
  • Host key type: ssh-rsa and partial ssh-dss.
  • Userauth: password, publickey (RSA)
  • Generating RSA key pairs.
  • Changing the passphrase for a private key.
  • SCP and SFTP

Please check my homepage for the latest version and feature list of SharpSSH.

Using the code

Let me begin with a small disclaimer. The code isn't fully tested, and I cannot guarantee any level of performance, security or quality. The purpose of this library and article is to educate myself (and maybe you) about the SSH protocol and the differences between C# and Java.

In order to provide the simplest API for SSH communication, I created two wrapper classes under the Tamir.SharpSsh namespace that encapsulates JSch's internal structures:

  • SshStream - A stream based class for reading and writing over the SSH channel.
  • Scp - A class for handling file transfers over the SSH channel.

Reading and writing data over the SSH channel

The SshStream class makes reading and writing of data over an SSH channel as easy as any I/O read/write task. Its constructor gets three parameters: The remote hostname or IP address, a username and a password. It connects to the remote server as soon as it is constructed.

//Create a new SSH stream
SshStream ssh = new SshStream("remoteHost", "username", "password");

//..The SshStream has successfully established the connection.

Now, we can set some properties:

//Set the end of response matcher character
ssh.Prompt = "#";
//Remove terminal emulation characters
ssh.RemoveTerminalEmulationCharacters = true;

The Prompt property is a string that matches the end of a response. Setting this property is useful when using the ReadResponse() method which keeps reading and buffering data from the SSH channel until the Prompt string is matched in the response, only then will it return the result string. For example, a Linux shell prompt usually ends with '#' or '$', so after executing a command it will be useful to match these characters to detect the end of the command response (this property actually gets any regular expression pattern and matches it with the response, so it's possible to match more complex patterns such as "\[[^@]*@[^]]*]#\s" which matches the bash shell prompt [user@host dir]# of a Linux host). The default value of the Prompt property is "\n", which simply tells the ReadResponse() method to return one line of response.

The response string will typically contain escape sequence characters which are terminal emulation signals that instruct the connected SSH client how to display the response. However, if we are only interested in the 'clean' response content we can omit these characters by setting the RemoveTerminalEmulationCharacters property to true.

Now, reading and writing to/from the SSH stream will be done as follows:

//Writing to the SSH channel
ssh.Write( command );

//Reading from the SSH channel
string response = ssh.ReadResponse();

Of course, it's still possible to use the SshStream's standard Read/Write I/O methods available in the System.IO.Stream API.

Transferring files using SCP

Transferring files to and from an SSH server is pretty straightforward with the Scp class. The following snippet demonstrates how it's done:

//Create a new SCP instance
Scp scp = new Scp();

//Copy a file from local machine to remote SSH server
scp.To("C:\fileName", "remoteHost", 
             "/pub/fileName", "username", "password");

//Copy a file from remote SSH server to local machine
scp.From("remoteHost", "/pub/fileName", 
               "username", "password", "C:\fileName");

The Scp class also has some events for tracking the progress of file transfer:

  • Scp.OnConnecting - Triggered on SSH connection initialization.
  • Scp.OnStart - Triggered on file transfer start.
  • Scp.OnEnd - Triggered on file transfer end.
  • Scp.OnProgress - Triggered on file transfer progress update (The ProgressUpdateInterval property can be set to modify the progress update interval time in milliseconds).

Running the examples

The demo project is a simple console application demonstrating the use of SshStream and Scp classes. It asks the user for the hostname, username and password for a remote SSH server and shows examples of a simple SSH session, and file transfers to/from a remote SSH machine.

Here is a screen shot of an SSH connection to a Linux shell:

And here is a file transfer from a Linux machine to my PC using SCP:

In the demo project zip file you will also find an examples directory containing some classes showing the use of the original JSch API. These examples were translated directly from the Java examples posted with the original JSch library and show the use of advanced options such as public key authentication, known hosts files, key generation, SFTP and others.

References

  • SharpSSH Homepage - New versions and bug fixes will be posted here, so please check this page for the latest updates.
  • JSch - JSch is a pure Java implementation of the SSH2 protocol suite. My C# library is based on this project.
  • Mentalis.org - Mentalis.org contains some great .NET projects for security and networking. I used their HMAC and Diffie Hellman classes as part of my SSH implementation.
  • Granados - A full featured open source SSH1 and SSH2 implementation in C#. I found this project after finishing my own library.

History

  • 2005-Oct-16
    • Initial version.
  • 2005-Oct-22
    • Fixed two bugs in Scp class.
  • 2005-Oct-29
    • Added the option to use DSA signatures ('ssh-dss') for authenticating the server during the key-exchange phase.
  • 2005-Oct-29
    • All future updates will be posted in my homepage.

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

Tamir Gal
Software Developer
Israel Israel
Member
Works as a Network Engineer for a leading networking company.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberayeks21 May '13 - 2:58 
BugWhat could be causing a System.TypeLoadException?membersqills1219 Apr '13 - 3:50 
QuestionNeed to send Control CharactersmemberNachiket Kulkarni8 Apr '13 - 19:40 
AnswerRe: Need to send Control CharactersmemberMember 1002084430 Apr '13 - 11:01 
QuestionAuth FailmembertheBoringCoder6 Mar '13 - 5:53 
QuestionError on Connecting to Oracle Solarismemberzgding10 Feb '13 - 4:14 
QuestionConnection errormemberhibaremanisha28 Jan '13 - 23:19 
QuestionDot Net Core library availabilitymemberAndrzej Pytel5 Nov '12 - 5:11 
QuestionTamir.SharpSsh.jsch.JSchException: Session.connect: System.OutOfMemoryExceptionmemberkiranchandran8512 Sep '12 - 11:51 
GeneralMy vote of 5memberMark E. Wood24 Aug '12 - 13:21 
Questionremote linux machinememberMember 856492412 Jun '12 - 4:56 
QuestionsshStream constructor JSchException was unhandledmemberMember 856492412 Jun '12 - 0:08 
QuestionException after server changememberBaracat11 Jun '12 - 10:44 
AnswerRe: Exception after server changememberMember 856492412 Jun '12 - 0:42 
AnswerRe: Exception after server changememberMember 856492413 Jun '12 - 1:55 
QuestionReading output from commandmemberMember 892329431 May '12 - 11:19 
GeneralMy vote of 5memberourstep10 Apr '12 - 22:07 
QuestionHow to maintain connection to ssh tunnel all time the application runmemberlpbinh6 Mar '12 - 5:14 
QuestionAuthfail exception with Red Hatmembervoast7 Feb '12 - 10:21 
QuestionPipe ClosememberMember 858177031 Jan '12 - 8:35 
GeneralMy vote of 5memberMember 43208446 Jan '12 - 0:29 
Bugerror when 3des-cbc encryption usedmembermlaheg5 Jan '12 - 6:24 
QuestionUpdating a file name on the sftp servermemberdinahubeishi18 Dec '11 - 3:19 
GeneralMy vote of 5membergiri_shiv27 Nov '11 - 5:45 
QuestionA bug found in the class "SshExec"memberdjhsu14 Nov '11 - 13:21 
AnswerRe: A bug found in the class "SshExec"memberiahsan18 Dec '11 - 2:19 
QuestionHow to confirm Comandsmemberneus8326 Oct '11 - 22:49 
QuestionSession.Connect Timeout in asp.net with c#membernaren913 Oct '11 - 5:19 
Questionsharpssh for classic aspmemberambaiaruvi15 Sep '11 - 23:52 
Questionsharpssh and web applicationmemberMember 81707991 Sep '11 - 0:31 
QuestionSHARPSSHmemberMember 817079929 Aug '11 - 22:46 
Questionconnecting errormemberGurgen Chlingaryan29 Aug '11 - 19:32 
QuestionSCP access is deniedmemberSujith_N29 Aug '11 - 4:46 
Questionsharpssh library does not support japanese and chinese [modified]membercristoht28 Aug '11 - 18:25 
QuestionTimeout on ConnectmemberMember 815692312 Aug '11 - 6:17 
AnswerRe: Timeout on Connectmembermuratdemirkiran26 Oct '11 - 3:46 
QuestionLong Timed Commandmemberyaj2226 Jul '11 - 20:02 
BugRe: Long Timed Commandmembermendorom3 Aug '11 - 11:39 
Questionpipe Closed when runtimememberselcukyazar14 Jul '11 - 1:31 
QuestionExecuting scriptsmembermendorom10 Jul '11 - 9:04 
QuestionWorking NSSH Server and Password AuthenticationmemberMancom23 Jun '11 - 16:59 
GeneralCommand is not workingmemberyokzu30 May '11 - 2:56 
GeneralRe: Command is not workingmemberbrilmayer11 Oct '12 - 1:56 
GeneralSCP - Error Openning Communication ChannelmemberIsnotrait19 May '11 - 6:05 
GeneralMy vote of 5memberairwolf20262 May '11 - 21:18 
GeneralMy vote of 1memberQuaQua24 Apr '11 - 7:37 
QuestionSFTP.Put - Seems to work, but no file uploaded?memberMember 78056981 Apr '11 - 9:52 
AnswerRe: SFTP.Put - Seems to work, but no file uploaded?memberwawlolo18 Apr '11 - 11:28 
GeneralCase Sensitive = FalsememberMember 77402159 Mar '11 - 10:33 
GeneralMy vote of 1memberEugene Mayeski8 Mar '11 - 5:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 29 Oct 2005
Article Copyright 2005 by Tamir Gal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid