关于C# 使用 开源插件SharpSSH 的问题!

majo_11389747 2011-03-03 03:39:07
实现目的 就是 连接到 服务器linux 并返回值

一般实现这个功能大家都是用DOS窗口输入命令,让后在得到返回值。

但是我不是用DOS窗体 只需要吧返回值返回到某个控件上的TEXT。

问题:在我点击button1按钮时 程序就没有响应了!
我没有做过这个东西所以手生,轻各位高手帮帮忙。


我创建了一个窗体文件Form1.cs 代码如下

引用 using Tamir.SharpSsh.jsch;

按钮事件:
private void button1_Click(object sender, EventArgs e)
{
host = "192.168.0.222";
user = "root";
pwd = "*****";

//Ssh.RunExample(UserName, UserPwd, http);//连接服务器
if(Ssh.OpenShell(host,user,pwd))
{
Ssh.Shell("df -h");
string info = Ssh.GetAllString();

this.textBox1.Text = info;
Ssh.Close(); //关闭数据库
this.textBox2.Text = "111";
}
//Console.ReadLine();
}


然后建立了一个SSH.cs 类库文件
引用 using Tamir.SharpSsh.jsch;

写入以下代码

public class ssh
{
System.IO.MemoryStream outputstream = new System.IO.MemoryStream();
Tamir.SharpSsh.SshStream inputstream = null;
Channel channel = null;
Session session = null;
//命令等待标识
string waitMark = "]#";

//打开连接
public bool OpenShell(string host, string username, string pwd)
{
try
{
//连接
inputstream = new Tamir.SharpSsh.SshStream(host, username, pwd);


return inputstream != null;
}
catch
{
throw;
}
}

//执行命令
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;
}

//获取输出信息
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();
}

//关闭连接
public void Close()
{
if (inputstream != null) inputstream.Close();
}
}
...全文
622 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
家猫 2011-06-02
  • 打赏
  • 举报
回复
string waitMark = "]#";

这个有可能是]$...这二种情况都会出现的
majo_11389747 2011-03-03
  • 打赏
  • 举报
回复
第二个错误 同样 来自 Session.cs

public void connect(int connectTimeout)

在这个方法中 捕捉到了异常

内容是 无法从传输连接中读取数据:您的主机这个女的软件放弃了一个已建立的连接。
majo_11389747 2011-03-03
  • 打赏
  • 举报
回复
我测试了一下 SharpSSH插件中
Session.cs 文件里
internal Session(JSch jsch)
{
;
this.jsch=jsch;
buf=new Buffer();
packet=new Packet(buf);
}
运行上述代码是 弹出 窗口

不一致的行尾

以下文件中的行尾不一致。要将行尾标准化吗?
sugarforever 2011-03-03
  • 打赏
  • 举报
回复
很久以前用的SharpSSH了。根据我的揣测,可以调试一下。你看点了button后,进程是走到哪里卡着了。
另外建议把ssh操作封装到线程了操作。通过委托通知UI线程更新界面。

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧