加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

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

(2011-07-26 14:38:02)
标签:

linux

ssh

c

shell

分类: 学习笔记--远程连接

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

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

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

 

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

 

引用工程:SharpSSH

源代码:

static void Main(string[] args)

{

    try

    {

        //Create a new JSch instance 

        JSch jsch = new JSch();

        //Prompt for username and server host                

        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 given via UserInfo interface. 

        UserInfo ui = new ShellUserInfo();

        ui.setPassword(pwd);

        session.setUserInfo(ui);

        //Connect to remote SSH server 

        session.connect();

        //Open a new Shell channel on the SSH session           

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

        //Redirect standard I/O to the SSH channel 

        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 remote server 

        channel.disconnect();

        session.disconnect();

    }

    catch (Exception e)

    {

        Console.WriteLine(e);

    }

}

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

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

public void set_OutputStream(Stream stream){m_channel.setOutputStream(stream);} 

接下来封装一个类:

class ShellHelp

{

    System.IO.MemoryStream outputstream = new MemoryStream();

    Tamir.SharpSsh.SshStream inputstream = null;

    Channel channel = null;

    Session session = null;

    /// <summary> 

    /// 命令等待标识 

    /// </summary> 

    string waitMark = "]#";

    /// <summary> 

    /// 打开连接 

    /// </summary> 

    /// <param name="host"></param> 

    /// <param name="username"></param> 

    /// <param name="pwd"></param> 

    /// <returns></returns> 

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

    {

        try

        {

            ////Redirect standard I/O to the SSH channel 

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

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

            inputstream.set_OutputStream(outputstream);

            return inputstream != null;

        }

        catch{throw;}

    }

    /// <summary> 

    /// 执行命令 

    /// </summary> 

    /// <param name="cmd"></param> 

    public bool Shell(string cmd)

    {

        if (inputstream == null) return false;

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

        return outinfo.ToString();

    }

    /// <summary> 

    /// 关闭连接 

    /// </summary> 

    public void Close()

    {

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

    }

}

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

 

接下来执行shell命令:

static void Main(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 = new ShellHelp(); 

    //连接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(); 

}  

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有