SSH.NETでSFTPとSSHの接続を確立させるまでの過程。
この投稿は1年以上前に公開されました。 現在の情報とは異なる可能性がありますので、ご了承ください。

SSH.NETでSFTPとSSHの接続を確立させるまでの過程。
ソースコードは下記です、あくまでも触りなのでココからご自分で考えて作り変えてください。ちなみにSSH.NETのライブラリを入手するには拡張機能からNuGet Package Managerという拡張機能を追加するとツールのNuGetパッケージマネージャーが現れるので、ソリューションのNuGetパッケージ管理からSSH.NETと検索しインストールすることによりライブラリが使用できます。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Renci.SshNet;
using Renci.SshNet.Common;
using Renci.SshNet.Sftp;
namespace ftp
{
public partial class Form1 : Form
{
String host = "168.192.11.1";
int port = 22;
String remoteFileDIR = "/root/";
String localDestinationDIR = "C:\\Users\\hoge\\Documents\\BACKUP\\";
String userName = "admin";
String passWord = "hogehoge";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
sshCommand();
}
private void fileDownload(string fileName) {
using (var sftp = new SftpClient(this.host, this.port, this.userName, this.passWord))
{
sftp.Connect();
using (var file = File.OpenWrite(this.localDestinationDIR + fileName))
{
sftp.DownloadFile(this.remoteFileDIR + fileName, file);
}
sftp.Disconnect();
}
}
private void sshCommand() {
SshClient ssh = new SshClient(this.host, this.userName, this.passWord);
ssh.Connect();
string command = "cd /root && ls";
string[] fileNames;
string result;
char pattern ='\n';
var resultData = ssh.RunCommand(command);
//MessageBox.Show(resultData.Result);
result = resultData.Result;
fileNames = result.Split(pattern);
ssh.Disconnect();
for (int i = 0; i < fileNames.Length; i++) {
if (fileNames[i] != "")
{
fileDownload(fileNames[i]);
}
}
}
}
}