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;
///
/// 命令等待标识
///
string waitMark = "]#";
///
/// 打开连接
///
///
name="host">
///
name="username">
///
name="pwd">
///
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;}
}
///
/// 执行命令
///
///
name="cmd">
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();
}
}
注意: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();
}