Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# send a simple SSH command

Tags:

c#

ssh

I'm a young a student and received my homework for this week. It's pretty difficult for me because I have to create a program, that is able to connect to an SSH server and send the command "etc/init.d/networking restart".

I should program this application in C# and I'm pretty new to it (Just have learned from some school lessons). I also should create a GUI.

I understand the basics of C# (loop, if etc...).

I've already created GUI, menus, buttons and a log listbox. GUI = 3 textboxes (ip, username, password) and a button to connect.

screenshot of ui

screenshot of code

I'm coding with Microsoft Vistual Studio.

My question is: How can I establish an SSH connection to my server?

like image 715
lucbas Avatar asked Jun 23 '12 12:06

lucbas


2 Answers

I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.

The original package website can be still found here, including the documentation (which currently isn't available on GitHub).

For your case the code would be something like this.

using (var client = new SshClient("hostnameOrIp", "username", "password")) {     client.Connect();     client.RunCommand("etc/init.d/networking restart");     client.Disconnect(); } 
like image 116
Karl-Johan Sjögren Avatar answered Oct 04 '22 15:10

Karl-Johan Sjögren


SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo"); cSSH.Connect(); SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\""); cSSH.Disconnect(); cSSH.Dispose(); 

//using SSH.Net

like image 21
Mario Palacios Avatar answered Oct 04 '22 16:10

Mario Palacios