利用SharpSsh远程执行linux的shell命令

利用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;

   /// <summary> 

   /// 命令等待标识 

   /// </summary> 

   string waitMark = "]#";

   /// <summary> 

   /// 打开连接 

   /// </summary> 

   /// <paramname="host"></param> 

   /// <paramname="username"></param> 

   /// <paramname="pwd"></param> 

   /// <returns></returns> 

   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;}

   }

   /// <summary> 

   /// 执行命令 

   /// </summary> 

   /// <paramname="cmd"></param> 

   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;

   }

   /// <summary> 

   /// 获取输出信息 

   /// </summary> 

   /// <returns></returns> 

   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();

   }

   /// <summary> 

   /// 关闭连接 

   /// </summary> 

   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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值