
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)
{
ssh_cmd();
}
private void dl(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 ssh_cmd() {
SshClient ssh = new SshClient(this.Host, this.Username, this.Password);
ssh.Connect();
string command = "cd /root && ls";
string[] str_result;
string str_results;
char ptn ='\n';
int i =0;
var result = ssh.RunCommand(command);
//MessageBox.Show(result.Result);
str_results = result.Result;
str_result = str_results.Split(ptn);
ssh.Disconnect();
for ( i = 0; i < str_result.Length; i++) {
//MessageBox.Show((str_result[i]));
if (str_result[i] != "")
{
dl(str_result[i]);
}
}
}
}
}