C#实现SSH、SCP、FTP等操作

C#实现SSH、SCP、FTP等操作

C#没有自带的SSH、SCP、FTP等操作的方法库,自己编写又太麻烦,这里将使用第三方Renci.SshNet.dll动态链接库实现这些操作

参考博客http://blog.csdn.net/iuhiqnehc/article/details/21074427的代码,但该博客只给出了代码,其他啥也没说,我就当是补充一下。

一、获取Renci.SshNet.dll


网上下载或者在我的资源页中下载

在我的资源中下载的文件中包含有Renci.SshNet.dll文件,SshNet的官方文档和我自己测试时写的小例子

二、将Renci.SshNet.dll添加进C#工程


我使用visual studio 2015作为IDE,将Renci.SshNet.dll添加进C#工程并调用的方法如下:

1. 添加引用

添加引用

如上图所示,右键解决方案下项目中的引用,选择添加引用,在弹窗中选择浏览按钮,找到Renci.SshNet.dll动态链接库,点击添加得到如下图所示


这里写图片描述

勾选你添加的Renci.SshNet.dll,点击确定

2. 调用

在添加了引用后直接使用下面的语句即可调用Renci.SshNet.dll动态链接库

using Renci.SshNet;

三、使用Renci.SshNet.dll


下面以SCP为例,FTP的二次封装可以参考开头给出的博文

SshNet动态链接库已经将FTP的基本功能封装成一个SCP类,在官方的说明文档中的命名空间目录下可以找到SCP类的说明,包括方法、属性、事件等。在使用中,我根据需要对这些方法、属性等进行了二次封装。

1. 添加一个新类

public class SCPOperation
{
    #region 声明一个ScpClient类型的变量
    private ScpClient ssh;

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

    #region
    /// <summary>
    /// 构造方法
    /// </summary>
    /// <param name="ip">IP</param>
    /// <param name="port">端口</param>
    /// <param name="user">用户名</param>
    /// <param name="pwd">密码</param>
    public SCPOperation(string ip, string port, string user, string pwd)
    {
        ssh = new ScpClient(ip, Int32.Parse(port), user, pwd);
    }
    #endregion
}

以上类基于Renci.SshNet中的ScpClient类进行二次封装,构造方法调用了ScpClient类的构造方法SftpClient(String, Int32, String, String),我的试用环境适用于该构造方法,ScpClient类还提供了多个构造方法的重用,如下图所示,可根据需要使用不同的构造方法

构造方法

2. 连接与断开SCP

#region
/// <summary>
/// 连接SCP
/// </summary>
/// <returns>true成功</returns>
public bool Connect()
{
    try
    {
        if (!Connected)
        {
            ssh.Connect();
        }
        return true;
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
        //Console.WriteLine(string.Format("连接SFTP失败,原因:{0}", ex.Message));
    }
}
#endregion

#region 断开SCP
/// <summary>
/// 断开SCP
/// </summary> 
public bool Disconnect()
{
    try
    {
        if (ssh != null && Connected)
        {
            ssh.Disconnect();
        }
        return true;
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
    }
}
#endregion

调用了ScpClient类的连接方法Connect()和断开方法Disconnect(),增加了异常处理,避免程序的异常卡死。

3. 文件的上传与下载

#region SFTP上传文件
/// <summary>
/// SCP上传文件
/// </summary>
/// <param name="localPath">本地路径</param>
/// <param name="remotePath">远程路径</param>
public int Put(string localPath, string remotePath)
{
    try
    {
        FileInfo file = new FileInfo(localPath);
        Connect();
        ssh.Upload(file, remotePath);
        Disconnect();
        return 1;
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
        return 0;
    }
}
#endregion

#region SFTP获取文件
/// <summary>
/// SCP获取文件
/// </summary>
/// <param name="remotePath">远程路径</param>
/// <param name="localPath">本地路径</param>
public void Get(string remotePath, DirectoryInfo localPath)
{
    try
    {
        Connect();
        DirectoryInfo localdir = new DirectoryInfo(localPath);
        ssh.Download(remotePath, localdir);
        Disconnect();
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
    }

}
#endregion

文件的上传与下载,调用了Download(String, DirectoryInfo)和Upload(FileInfo, String)方法,这两种方法的输入不全是string类型,函数中增加了数据类型转化的操作。

4. 测试

namespace testFTP
{
    class Program
    {
        static void Main(string[] args)
        {
            string ftpIP = "192.168.1.144";
            string ftpPATH = @"/home/pi";
            string ftpUSER = "pi";
            string ftpPSD = "6333545998";
            string ftpPORT = "22";

            string remotePath = "/home/pi";
            string localPath = @"E:\无人机\UBNTprogram\testFTP\testFTP\test.txt";

            SCPOperation test = new SCPOperation(ftpIP, ftpPORT, ftpUSER, ftpPSD);
            bool ifcon = test.Connect();

            if (ifcon)
            {
                Console.WriteLine("connect success");
            }
            else
            {
                Console.WriteLine("failed");
            }

            test.Put(localPath, remotePath);

            Console.ReadLine();
        }
    }
}

完整代码可在我的资源页中下载

  • 1
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值