NET6.0 SFTP 使用私钥连接并实现文件的上传与下载
使用Openssh 私钥连接SFTP服务器
如果使用的是.ppk(PuTTY Private Key)的私钥格式,可以使用puttygen转成openssh,
或者直接使用winscp来实现,
使用的是SSH.NET库https://www.nuget.org/packages/SSH.NET
dotnet add package SSH.NET --version 2020.0.2
下载文件
using Renci.SshNet;
/// <summary>
/// 下载所有文件到本地
/// </summary>
public void DownloadFiles(string remotePath ,string localPath)
{
try
{
// 使用私钥文件创建一个PrivateKeyFile对象
PrivateKeyFile privateKeyFile = new PrivateKeyFile(PrivateKeyFilePath);
// 使用私钥文件创建一个PrivateKeyFile对象
PrivateKeyAuthenticationMethod privateKeyAuth = new PrivateKeyAuthenticationMethod(Username, privateKeyFile);
// 创建一个连接信息对象
ConnectionInfo connectionInfo = new ConnectionInfo(Host, 22, Username, privateKeyAuth);
// 创建一个SftpClient对象并连接到SFTP服务器
using (var sftpClient = new SftpClient(connectionInfo))
{
sftpClient.Connect();
// 创建远程目录和本地目录
if (!sftpClient.Exists(remotePath))
{
sftpClient.CreateDirectory(remotePath);
}
if (!Directory.Exists(localPath))
{
Directory.CreateDirectory(localPath);
}
//复制文件到本地
var fileList = sftpClient.ListDirectory(remotePath);
foreach (var file in fileList)
{
if (!file.IsDirectory)
{
string localFilePath = Path.Combine(localPath, file.Name);
using (var fs = new FileStream(localFilePath, FileMode.Create))
{
string remoteFilePath = file.FullName;
sftpClient.DownloadFile(remoteFilePath, fs); }
}
}
sftpClient.Disconnect();
}
}
catch (Exception e)
{
throw;
}
}
上传文件
using Renci.SshNet;
/// <summary>
/// 上传所有文件到sftp服务器
/// </summary>
public void UploadFiles( string localPath, string remotePath)
{
try
{
// 使用私钥文件创建一个PrivateKeyFile对象
PrivateKeyFile privateKeyFile = new PrivateKeyFile(PrivateKeyFilePath);
// 使用私钥文件创建一个PrivateKeyFile对象
PrivateKeyAuthenticationMethod privateKeyAuth = new PrivateKeyAuthenticationMethod(Username, privateKeyFile);
// 创建一个连接信息对象
ConnectionInfo connectionInfo = new ConnectionInfo(Host, 22, Username, privateKeyAuth);
// 创建一个SftpClient对象并连接到SFTP服务器
using (var sftpClient = new SftpClient(connectionInfo))
{
sftpClient.Connect();
// 创建远程目录和本地目录
if (!sftpClient.Exists(remotePath))
{
sftpClient.CreateDirectory(remotePath);
}
if (!Directory.Exists(localPath))
{
Directory.CreateDirectory(localPath);
}
/复制的文件到远程目录
IEnumerable<FileSystemInfo> infos = new DirectoryInfo(localPath).EnumerateFileSystemInfos();
foreach (var info in infos)
{
using (var fs = File.OpenRead(info.FullName))
{
string remotfilepath = Path.Combine(remotePath, info.Name);
sftpClient.UploadFile(fs, remotfilepath);
}
}
sftpClient.Disconnect();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
相关属性
public string Host = "192.168.0.1";
public string Username = "yourName";
public string PrivateKeyFilePath = "opensshkey"; // 如果是ppk必须转为openssh