赞
踩
导包
using Renci.SshNet;
void Test ()
{
ShellStream shellStream;
using (SftpClient sftp = new SftpClient(ip, Port, UserName, UserPwd))
{
UploadData(sftp, SrcFilePath, LinuxFilePath);
}
using (var sshClient = new SshClient(ip, port, UserName, UserPwd))
{
sshClient.Connect();
shellStream = sshClient.CreateShellStream("Terminal", 80, 500, 500, 500, 1024);
shellStream.DataReceived += EventDataReceived;
SSH_ExecuteCmds(shellStream);
try
{
}
catch (Exception)
{
throw;
}
shellStream.Close(); //关闭
}
}
/// <summary>
/// 执行多条命令
/// </summary>
/// <param name="shellStream"></param>
/// <param name="cmds"></param>
private void SSH_ExecuteCmds(ShellStream shellStream)
{
for (int i = 0; i < cmds.Count; i++)
{
shellStream.WriteLine(cmds[i]);
Thread.Sleep(intervalTime[i]);
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="sftp"></param>
/// <param name="filename"></param>
/// <param name="linuxfilepath"></param>
private void UploadData(SftpClient sftp, string filename, string linuxfilepath)
{
sftp.Connect();
FileInfo fi = new FileInfo(filename);
var allLength = fi.Length;
sftp.UploadFile(new System.IO.FileStream(fi.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite), linuxfilepath/* "/home/sindrol/aa.zip"*/, (pro) => { Console.WriteLine((pro * 1.0d / allLength * 1.0d).ToString("P")); });
}
/// <summary>
/// 接收返回数据
/// </summary>
/// <param name="send"></param>
/// <param name="e"></param>
private void EventDataReceived(object send, ShellDataEventArgs e)
{
//判断数据是否有效 长度,字符串是否为空,排除\r\n
if (e.Data.Length > 0 &&
!string.IsNullOrEmpty(Encoding.ASCII.GetString(e.Data.ToArray())) &&
Encoding.ASCII.GetString(e.Data.ToArray()) != "\r\n"
)
{
listRetStr.Add(Encoding.ASCII.GetString(e.Data.ToArray()));
}
写一条指令,收一条数据,不能用于一直运行指令
string ret = cmd.Execute();
//cmd.Error
cmd.Dispose();
一直运行的指令,直接读终端上显示的信息
public List<ShellStream> _shellStreams { get; set; }
public bool ShellStreamsInit(int shellNum)
{
_shellStreams.Clear();
if (this.SshConnect())
{
for (int i = 0; i < shellNum; i++)
{
_shellStreams.Add(_sshClient.CreateShellStream("Terminal" + i.ToString(), 80, 500, 500, 500, 1024));
}
}
if(_shellStreams.Count()>0)
{
return true;
}
return false;
}
string GetResult(ShellStream shellStream,string fileName)
{
List<string> listStr = new List<string>();
shellStream.WriteLine("cmds");
for (int i = 0; ; i++)
{
listStr.Add(shellStream.ReadLine(TimeSpan.FromSeconds(1)));
if (string.IsNullOrEmpty(listStr[i]))
{
listStr.RemoveAt(i);
break;
}
}
string result = "";
foreach (var item in listStr)
{
if (!string.IsNullOrEmpty(item))
{
string tmp = Regex.Match(item, @"").Groups["a"].ToString();
if (!string.IsNullOrEmpty(tmp))
{
result = tmp;
}
}
}
return result;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。