Monthly Archives: September 2012

Tamir.SharpSSH, C# and some linux shell command

I’ve found some interesting .NET class for accessing the linux server via SSH tunnel on this site – http://www.tamirgal.com/blog/page/SharpSSH.aspx. I’ve almost gave my task after experimenting the WinSCP active x plugin. I’ve decided to search again another code and found this library.
There are samples there on the source code but I’ve found the code ‘SSHExeTest.cs’ helpful for me.
Here is the revise code I have :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Tamir.SharpSsh;
namespace WinSCP_Test
{
public partial class Form1 : Form
{
string _ipAddress = "192.168.0.160";
string _username = "root"; // :) dont worry i'mjust playing on virtualbox I think its better not to use root in production
string _password = "xxxxxxx";
SshExec exec;

public Form1()
{
InitializeComponent();
exec = new SshExec(_ipAddress, _username);
exec.Password = _password;
exec.Connect();
}
private bool isScriptRunning()
{

string command = "ps ax | grep -e '[t]est.py'";
string output = exec.RunCommand(command);
string[] output_arr = output.Trim().Split(' ');
return output != "";
}
private void runScript()
{

string command = "/usr/bin/python /root/test.py > /dev/null &";
exec.RunCommand(command);
//Console.WriteLine(output);

}
private void killScript()
{
string command = "ps ax | grep -e '[t]est.py'";

string output = exec.RunCommand(command);
string[] output_arr = output.Trim().Split(' ');
output = exec.RunCommand("kill -9 " + output_arr[0]);
}

 

private void button1_Click(object sender, EventArgs e)
{
if (this.isScriptRunning())
{
if (MessageBox.Show("Script is running kill it?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.killScript();
}
}
else
{
if (MessageBox.Show("Script is is not running,run it?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.runScript();
}

}
}

private void button2_Click(object sender, EventArgs e)
{
this.Close();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
exec.Close();
}
}
}