Click here to Skip to main content
6,595,444 members and growing! (15,953 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Network     Intermediate License: The BSD License

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

By Tamir Gal

A C# implementation of the SSH2 protocol.
C#, VC7, .NET, Win2K, WinXP, Win2003, Visual Studio, Dev, QA
Posted:16 Oct 2005
Updated:29 Oct 2005
Views:357,481
Bookmarked:155 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
73 votes for this article.
Popularity: 8.58 Rating: 4.60 out of 5
4 votes, 5.5%
1

2
1 vote, 1.4%
3
9 votes, 12.3%
4
59 votes, 80.8%
5

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


Member
Works as a Network Engineer for a leading networking company.
Occupation: Software Developer
Location: Israel Israel

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 928 (Total in Forum: 928) (Refresh)FirstPrevNext
Generaltimout exception! Pinmemberibrahim.hamdy11:53 2 Nov '09  
GeneralRe: timout exception! Pinmemberibrahim.hamdy12:23 2 Nov '09  
GeneralDiifieHellman - Strongly-named assembly required error Pinmemberavanti_k9:04 28 Oct '09  
GeneralCannot connect using the library PinmemberSwordST11:39 24 Sep '09  
QuestionSharpSSH cant upload file Pinmemberspring 274:15 23 Sep '09  
GeneralDSA Key Login PinmemberMember 26483418:59 10 Sep '09  
GeneralChange Port PinmemberBlackHeart80515:10 7 Sep '09  
GeneralBanner Grab Pinmemberacemasterson12:16 26 Aug '09  
QuestionSShShell execution problem PinmemberDaniel Koós8:05 27 Jun '09  
NewsOpening the project to new contributors Pinmemberpicrap322:16 25 Jun '09  
General[Message Deleted] Pinmemberjeganinfo4:08 30 Jul '09  
GeneralRe: Opening the project to new contributors Pinmemberpicrap36:28 30 Jul '09  
GeneralRe: Opening the project to new contributors PinmemberTamir Gal9:56 1 Aug '09  
GeneralExecute sudo to restart server Pinmembermacho_guy21:12 17 Jun '09  
QuestionSession.connect: System.Security.Cryptography.CryptographicException: Bad Data. - on Windows 7 PinmemberDarked2:38 26 May '09  
GeneralSFTP - Problem download JPEG files PinmemberMember 45765320:48 12 May '09  
QuestionPortforward problem Pinmembermaercher22:19 11 May '09  
QuestionUrgent Help Please - .get not working Pinmembergkdgopi18:36 4 May '09  
GeneralUsing .p12 as identity file PinmemberMember 363583619:31 25 Apr '09  
GeneralEnvironment Variables Pinmembercrittedv6:41 24 Apr '09  
General10+ Seconds to open a sshExec connection [modified] PinmemberUndeadDevil14:53 14 Apr '09  
QuestionMultithreading problem for multiple sends ? NullReferenceException again PinmemberWedgeS7:32 31 Mar '09  
GeneralAnyone have problems with SSH since MS patch 9th March 2009? PinmemberFashtas14:05 22 Mar '09  
GeneralRe: Anyone have problems with SSH since MS patch 9th March 2009? Pinmemberscott.leckie1:21 13 Apr '09  
General.Get loop? PinmemberSiow Thian Choong18:55 11 Mar '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Oct 2005
Editor: Rinish Biju
Copyright 2005 by Tamir Gal
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project