C# SCP访问SSH

C# SCP访问SSH


基本概念

SCP(secure copy)安全拷贝
  意思是用来进行安全远程文件拷贝。
SSH (Secure Shell )安全外壳协议
  他是建立在应用层基础上的安全协议。SSH 是较可靠,专为远程登录会话和其他网络服务提供安全性的协议。利用 SSH 协议可以有效防止远程管理过程中的信息泄露问题。


一、获取第三方链接库

  因为C#没有相关直接使用的库,因此,我们一般使用的是第三方库。
  获取第三方动态链接库Renci.SshNet.dll,可以在我的上传资料中获取。获取点这里


二、项目添加库

  通过项目菜单中引用或者在资源管理器中添加引用。添加后可以看到引用中添加的项目。在这里插入图片描述


三、添加代码调用

SshNet动态链接库已经添加后,就可以添加代码使用它了。可以听过添加新类来实现,下面是我实现的代码,可以参考,有比较详细的注释。


using System;
using System.IO;
//必须引用库文件
using Renci.SshNet;


namespace test
{    
    class SSH
    {
        private ScpClient _ScpClient;//实例化信息类
        public string _LocalPath = "";//本地文件路径
        private const int scpPort = 22;                           //SSH 端口号       
        private const string _RemoteDirectory = @"/home/upgrade"; //远程路径目录
        private const string scpUser = "root";                    //登录用户名  
        private const string defaultPassWord = "root";            //默认登录密码
        private string remoteLogName = "";                  	  //读取的远端文件名  

        /// <summary>
        /// SCP连接状态
        /// </summary>
        public bool Connected 
        { 
        	get { return _ScpClient.IsConnected; } 
        }

 
        /// <summary>
        /// 构造初始化参数
        /// </summary>
        /// <param name="ip">IP 参数</param>        
        public UpgradeFirmware(string ip)        
        {
             //准备参数:IP、端口、用户名、密码  
            _ScpClient = new ScpClient(ip, scpPort,scpUser,scpPassWord);
        }



        /// <summary>
        /// 连接复制文件上传到SSH服务器 或 连接SSH服务器并复制文件到本地
        /// </summary>
        /// <param name="upload_or_download">上传下载选择</param>
        /// <returns>返回值: 1==成功</returns>
        public int SSH_UploadOrDownloadFile(bool upload_or_download)
        {

            //连接到设备
            bool SSHCon = Connect();
            if (SSHCon == false)
            {
                return 2;
            }
            if (_LocalPath == "" || _RemoteDirectory == "")
            {
                return 3;
            }

            if (upload_or_download)
            {
                //上传文件
                if (Put(_LocalPath, _RemoteDirectory) == false)
                {
                    return 4;
                }
            }
            else 
            {               
                //下载文件
                if (Get(_RemoteDirectory + "/"+ remoteLogName + ".zip",  _LocalPath) == false) 
                {
                    return 5;
                }
            }
            return 1;
        }



        /// <summary>
        /// 连接SSH服务器
        /// </summary>
        /// <returns>true=成功</returns>
        public bool Connect()
        {
            try
            {   
                if (!Connected)
                {
                    _ScpClient.Connect();//连接
                }
                return true;
            }
            catch (Exception ex)
            {
            	//异常记录到自定义文件
                FileOperation fo = new FileOperation();
                fo._ErrCode = "Connect() " + ex.Message;
                return false;
            }
        }
 
 
        /// <summary>
        /// 断开SSH连接
        /// </summary> 
        public bool Disconnect()
        {
            try
            {
                if (_ScpClient != null && Connected)
                {
                    _ScpClient.Disconnect();//断开连接
                }
                return true;
            }
            catch (Exception ex)
            {
            	//异常记录到自定义文件
                FileOperation fo = new FileOperation();
                fo._ErrCode = "Disconnect() " + ex.Message;
                return false;
            }
        }
 


 
        /// <summary>
        /// SSH上传文件
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="remotePath">远程路径</param>
        public bool Put(string localPath, string remotePath)
        {
            try
            {
                FileInfo file = new FileInfo(localPath);
                Connect();//测试连接
                _ScpClient.Upload(file, remotePath);
                Disconnect();//断开连接
                return true;
            }
            catch (Exception ex)
            {
                //异常记录到自定义文件
                FileOperation fo = new FileOperation();
                fo._ErrCode = "Put() " + ex.Message;
                return false;
                
            }
 
        }
    

       
        /// <summary>
        /// SCP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public bool Get(string remotePath, string localPath)
        {
            try
            {   
            
                Connect();//测试连接
                DirectoryInfo localdir = new DirectoryInfo(localPath);
                _ScpClient.Download(remotePath, localdir);
                Disconnect();//断开连接
                return true;
            }
            catch (Exception ex)
            {
                //异常记录到自定义文件
                FileOperation fo = new FileOperation();
                fo._ErrCode = "Get() " + ex.Message;
                return false;
            }
            
        }
	}
}


小结:

1、在获取文件路径时候请注意文件名称和文件全路径名的区别;
2、调试过程中,如果遇到问题可以看看异常报出的字符串提示来找问题,也可以用XSHELL等工具直接登录查实际文件或路径是否存在;
3、大家也可以参考其它博客的说明来多方面理解,比如这位博主代码也整理得不错。链接如下: 实现SSH、SCP、FTP等操作.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火星papa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值