当前位置:   article > 正文

C# Renci 的 SSH 库使用示例

renci

导包在这里插入图片描述

using Renci.SshNet;
  • 1
	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()));
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

写一条指令,收一条数据,不能用于一直运行指令

string ret = cmd.Execute();
 //cmd.Error

cmd.Dispose();
  • 1
  • 2
  • 3
  • 4

一直运行的指令,直接读终端上显示的信息

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;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/977677
推荐阅读
相关标签
  

闽ICP备14008679号