sharpssh远程linux监控系统,利用SharpSsh远程执行linux的shell命令

本文介绍了如何使用C#开源库SharpSSH连接到Linux服务器并执行shell命令。通过修改SharpSSH源码,实现了命令输出的捕获,以便于处理命令执行结果。文章提供了代码示例,展示如何创建SSH会话、执行命令以及关闭连接,并且定义了一个`ShellHelp`类来封装这些操作,使得命令执行和结果获取更加方便。
摘要由CSDN通过智能技术生成

利用SharpSsh远程执行linux的shell命令 (2011-07-26 14:38:02)

SharpSSH是一个C#的开源项目,可以利用SSH连接linux系统。并执行shell等命令。

而SharpSSH提供的例子的输入输出都是定向到console。因此不容易从其中取出它的结果。

因此需要对源码进行一定的修改,从而得到我们想要的结果。

执行SSH前,应确保linux主机上的服务已启动,命令:service sshdstart

引用工程:SharpSSH

源代码:

static voidMain(string[]args)

{

try

{

//Create a new JSch instance

JSch jsch = newJSch();

//Prompt for username and serverhost

Console.WriteLine("Please input hostname:");

String host = Console.ReadLine();

Console.WriteLine("Please input username:");

String user = Console.ReadLine();

Console.WriteLine("Please input password:");

String pwd = Console.ReadLine();

//Create a new SSH session

Session session = jsch.getSession(user, host,22);

// username and password will be givenvia UserInfo interface.

UserInfo ui = newShellUserInfo();

ui.setPassword(pwd);

session.setUserInfo(ui);

//Connect to remote SSHserver

session.connect();

//Open a new Shell channel on the SSHsession

Channel channel = session.openChannel("shell");

//Redirect standard I/O to the SSHchannel

channel.setInputStream(Console.OpenStandardInput());

channel.setOutputStream(Console.OpenStandardOutput());

//Connect the channel

channel.connect();

Console.WriteLine("-- Shell channel is connected using the {0}cipher", session.getCipher());

//Wait till channel is closed

while(!channel.isClosed())

{

System.Threading.Thread.Sleep(500);

}

//Disconnect from remoteserver

channel.disconnect();

session.disconnect();

}

catch (Exception e)

{

Console.WriteLine(e);

}

}

以上只能将输入输出定向到console。

修改:打开SharpSSH中的SshStream.cs,加一个方法

public voidset_OutputStream(Streamstream){m_channel.setOutputStream(stream);}

接下来封装一个类:

class ShellHelp

{

System.IO.MemoryStreamoutputstream = newMemoryStream();

Tamir.SharpSsh.SshStream inputstream = null;

Channel channel = null;

Session session = null;

///

/// 命令等待标识

///

string waitMark = "]#";

///

/// 打开连接

///

///

///

///

///

public bool OpenShell(string host, string username, string pwd)

{

try

{

Redirect standard I/O to the SSHchannel

inputstream = newTamir.SharpSsh.SshStream(host, username, pwd);

///我手动加进去的方法。。为了读取输出信息

inputstream.set_OutputStream(outputstream);

return inputstream != null;

}

catch{throw;}

}

///

/// 执行命令

///

///

public bool Shell(string cmd)

{

if (inputstream == null) returnfalse;

string initinfo =GetAllString();

inputstream.Write(cmd);

inputstream.Flush();

string currentinfo =GetAllString();

while (currentinfo ==initinfo)

{

System.Threading.Thread.Sleep(100);

currentinfo = GetAllString();

}

return true;

}

///

/// 获取输出信息

///

///

public string GetAllString()

{

string outinfo = Encoding.UTF8.GetString(outputstream.ToArray());

//等待命令结束字符

while(!outinfo.Trim().EndsWith(waitMark))

{

System.Threading.Thread.Sleep(200);

outinfo = Encoding.UTF8.GetString(outputstream.ToArray());

}

outputstream.Flush();

returnoutinfo.ToString();

}

///

/// 关闭连接

///

public void Close()

{

if (inputstream != null) inputstream.Close();

}

}

注意:string waitMark = "]#"; 在这里是用来标识命令是否执行完成的,,执行完成就会在后面输出这个字符,,有时也有可能是"]$"

接下来执行shell命令:

static voidMain(string[] args)

{

Console.WriteLine("Please input hostname:");

String host = Console.ReadLine();

Console.WriteLine("Please input username:");

String user = Console.ReadLine();

Console.WriteLine("Please input password:");

String pwd = Console.ReadLine();

ShellHelp shell = newShellHelp();

//连接linux成功

if (shell.OpenShell(host, user,pwd))

{

shell.Shell("df-h");//执行获取命令

//shell.Shell("dmidecode");//执行获取命令

string info =shell.GetAllString();//获取返回结果

Console.WriteLine(info);

shell.Close();//关闭连接

}

Console.ReadLine();

}

转自:http://blog.sina.com.cn/s/blog_6ffbfc880100tt85.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值