using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Renci.SshNet; namespace TestSFTP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} public class sFtpHelper { public static int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword) { string localFileName = localPath + "\\" + fileName; string remoteFileName = filePath+ "/"+ fileName;
try { using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword)) { sftp.Connect(); using (var file = File.Open(localFileName,FileMode.OpenOrCreate)) { sftp.DownloadFile(remoteFileName, file); } sftp.Disconnect(); Console.WriteLine("下载文件成功,文件路径:"+localFileName); return 0; } } catch (Exception e) { MessageBox.Show("下载失败,原因:"+e.Message ); return -2; } } public static int UploadFtp(string filePath, string localPath, string filename, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword) { string localFileName = localPath + "\\" + filename;
string remoteFileName = "/"+filePath+"/"+filename; try { using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword)) { sftp.Connect(); using (var file = File.OpenWrite(localFileName)) { sftp.UploadFile(file, remoteFileName); } sftp.Disconnect(); Console.WriteLine("上传文件成功,文件路径:"+localFileName); return 0; } } catch (Exception ex) { Console.WriteLine("上传失败,原因:"+ex.Message ); return -2; } } } private void button1_Click(object sender, EventArgs e)
{
string sftpHost = "sftp.xxx.com";
string sFile= "aaa.txt";
sFtpHelper.DownloadFtp("/upload/weblicense/dd", "d:\\",sFile , sftpHost, "22", "username222", "pwd123"); } } }

  

完整实例(包含显示下载进度):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Renci.SshNet;
using System.Threading.Tasks;
using Renci.SshNet.Sftp;
using System.Diagnostics; namespace TestSFTP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} public int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{ string localFileName = localPath + "\\" + fileName; string remoteFileName = filePath + "/" + fileName;
try
{ using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.Open(localFileName, FileMode.OpenOrCreate))
{ sftp.DownloadFile(remoteFileName, file);
//sftp.BeginDownloadFile(
}
sftp.Disconnect(); display("下载文件成功,文件路径:" + localFileName); return 0; } } catch (Exception e)
{
display("下载失败,原因:" + e.Message);
return -2; } } public int UploadFtp(string filePath, string localPath, string filename, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{ string localFileName = localPath + "\\" + filename;
string remoteFileName = "/" + filePath + "/" + filename; try
{ using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{ sftp.Connect(); using (var file = File.OpenWrite(localFileName))
{ sftp.UploadFile(file, remoteFileName); } sftp.Disconnect(); Console.WriteLine("上传文件成功,文件路径:" + localFileName); return 0; } } catch (Exception ex)
{ Console.WriteLine("上传失败,原因:" + ex.Message); return -2; } } public int DownloadFtpWithProgress(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{ string localFileName = localPath + "\\" + fileName; string remoteFileName = filePath + "/" + fileName;
try
{ using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
bool IsExists = sftp.Exists(remoteFileName);
if (!IsExists)
{ return 0;
} //get the attributes of the file (namely the size)
SftpFileAttributes att = sftp.GetAttributes(remoteFileName);
long fileSize = att.Size;
//download the file as a memory stream and convert to a file stream
using (MemoryStream ms = new MemoryStream())
{
IAsyncResult asyncr = sftp.BeginDownloadFile(remoteFileName, ms);
SftpDownloadAsyncResult sftpAsyncr = (SftpDownloadAsyncResult)asyncr;
while (!sftpAsyncr.IsCompleted)
{
int pct = (int)(((double)sftpAsyncr.DownloadedBytes / fileSize) * 100);
Debug.Print("Downloaded {0} of {1} ({2}%).", sftpAsyncr.DownloadedBytes, fileSize, pct);
Text=string.Format ("Downloaded {0} of {1} ({2}%).", sftpAsyncr.DownloadedBytes, fileSize, pct);
pgbMain.Value = pct;//pgbMain is the progressBar ui control
Application.DoEvents();
} sftp.EndDownloadFile(asyncr);
//write the memory stream to the file stream
var fs = File.Open(localFileName, FileMode.Create);
ms.WriteTo(fs);
fs.Close();
ms.Close(); }
sftp.Disconnect(); display("下载文件成功,文件路径:" + localFileName);
return 0; } } catch (Exception e)
{
display("下载失败,原因:" + e.Message);
return -2; } } void display(string s)
{ richTextBox1.AppendText(s + "\r\n");
} private void button1_Click(object sender, EventArgs e)
{
string sftpHost = "sftp.xxx.com";
string sFile = "SWMM7ActiveProductDevelopment-GuangshuWang.mem";
DownloadFtpWithProgress("/upload/weblicense/swmm7000", "d:\\", sFile, sftpHost, "22", "username", "pwd..."); } private void Form1_Load(object sender, EventArgs e)
{ } } }

  

界面代码:

namespace TestSFTP
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows Form Designer generated code /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.pgbMain = new System.Windows.Forms.ProgressBar();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(293, 23);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(241, 67);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(76, 151);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(639, 244);
this.richTextBox1.TabIndex = 1;
this.richTextBox1.Text = "";
//
// pgbMain
//
this.pgbMain.Location = new System.Drawing.Point(106, 107);
this.pgbMain.Name = "pgbMain";
this.pgbMain.Size = new System.Drawing.Size(609, 23);
this.pgbMain.TabIndex = 2;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pgbMain);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button button1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.ProgressBar pgbMain;
}
}

  

SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism.

【从nuget中下载SSH.NET】

摘自 http://www.cnblogs.com/cbread/p/6202069.html

c# SSH ,SFTP的更多相关文章

  1. 【SSH/SFTP】SSH协议和SFTP

    [SSH和SFTP] ■ 设置一个只允许访问部分目录的SFTP服务器 由于SSH和SFTP之间的紧密联系,一个SFTP服务器必然会导致开放一定的SSH服务,而SSH的风险显然比SFTP要大一些.自然, ...

  2. ssh & sftp & MacOS

    ssh & sftp & MacOS https://www.technoduet.com/a-simple-way-to-connect-to-remote-ftp-sever-on ...

  3. Winscp开源的SSH|SFTP

    WinSCP 主要功能 图形用户界面 多语言与 Windows 完美集成(拖拽, URL, 快捷方式) 支持所有常用文件操作,支持基于 SSH-1.SSH-2 的 SFTP 和 SCP 协议 支持批处 ...

  4. CentOS的ssh sftp配置及权限设置(流程相当完整)(关闭了SElinux才能上传了)

    从技术角度来分析,几个要求: 1.从安全方面看,sftp会更安全一点 2.线上服务器提供在线服务,对用户需要控制,只能让用户在自己的home目录下活动 3.用户只能使用sftp,不能ssh到机器进行操 ...

  5. CentOS的ssh sftp配置及权限设置[转载-验证可用]

    从技术角度来分析,几个要求:1.从安全方面看,sftp会更安全一点2.线上服务器提供在线服务,对用户需要控制,只能让用户在自己的home目录下活动3.用户只能使用sftp,不能ssh到机器进行操作 提 ...

  6. CentOS下ssh sftp配置及权限设置

    运营有异地传输文件的需求,但如果通过QQ等即时通讯软件,不利于文件的集中管理,不方便.而我们办公室的内网机器无法提供外网访问方法,且传输的内容不合适放到公共的网盘或者是云存储上,所以只能用线上负载较低 ...

  7. SSH&SFTP服务分离+家目录锁定

    Step 1 在root用户下创建维护账号的家目录,此处以创建userftp帐号的家目录为例. mkdir -p /chroot/home/user Step 2 在root用户根目录下执行以下命令设 ...

  8. Linut ssh sftp服务重启

    在网上,收了半天,终于找到这个,记录一下~哈~ RedHat Linux 重启SSH /etc/init.d/sshd restart 重启SFTP /etc/init.d/vsftpd restar ...

  9. linux下ssh/sftp配置和权限设置

    基于 ssh 的 sftp 服务相比 ftp 有更好的安全性(非明文帐号密码传输)和方便的权限管理(限制用户的活动目录). 1.开通 sftp 帐号,使用户只能 sftp 操作文件, 而不能 ssh ...

随机推荐

  1. Android项目实战(三十):Fresco加载gif图片并播放

    前言: 项目中图文混合使用的太多太多了,但是绝大部分都是静态图片. 然而项目开发中有这么一个需求:显示一个出一个简短的动画(一般都不超过3秒)演示 比如说:一个功能提供很多步骤来教用户做广播体操,那么 ...

  2. 从托管映像创建 VM

    可以从 Azure 中托管的 VM 映像创建多个 VM. 托管 VM 映像包含创建 VM 所需的信息,包括 OS 和数据磁盘. 构成映像的 VHD(包括 OS 磁盘和任何数据磁盘)存储为托管磁盘. 先 ...

  3. Java中几种常用数据类型之间转换的方法

    Java中几种常用的数据类型之间转换方法: 1. short-->int 转换 exp: short shortvar=0; int intvar=0; shortvar= (short) in ...

  4. CSS 居中大全(转)

    引用:http://jinlong.github.io/blog/2013/08/13/centering-all-the-directions/ CSS 居中大全 AUG 13TH, 2013 |  ...

  5. 阿里八八Alpha阶段Scrum(8/12)

    今日进度 叶文滔: 已经成功解决兼容性问题,目前正在嵌入多级按钮API,预计明天可以完成 王国超: 今天终于debug了,被卡了几天的fragment嵌套listview终于成功了 俞鋆: 研究了一下 ...

  6. 团队作业——Alpha冲刺 3/12

    团队作业--Alpha冲刺 冲刺任务安排 杨光海天 今日任务:完成Android开发环境的搭建,学习基础开发知识 明日任务:继续学习Android开发知识,与其他成员协商,了解自己需要完成的开发任务, ...

  7. linux sqlplus查询数据中文乱码解决方法记录

    locale-gen -lang en.US.UTF-8 重启.

  8. BZOJ1007:[HNOI2008]水平可见直线(计算几何)

    Description 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为 可见的,否则Li为被覆盖的. 例如,对于直线: L1:y ...

  9. Object Detection API 相关

    训练官方提供的数据集: http://blog.csdn.net/LiJiancheng0614/article/details/77756252 训练自己的数据集(墙外): https://medi ...

  10. 更改Apache默认起始(索引)页面:DirectoryIndex

    Apache默认索引页面是index.html,修改成其他文件需要修改httpd.conf文件: # # DirectoryIndex: sets the file that Apache will ...