SSH.Net пример запуска команды на C#

C Sharp > SSH.Net пример запуска команды на C#
13.12.2017 12:02:40


Наиболее часто встречающиеся слова в статье:

[username] [password] [SftpClient] [Console] [WriteLine] [directory] [Connect] [Disconnect] ["yourSftpServer] ["p4ssw0rd"]


Статья:

Прекрасная  библиотека находится по адресу  http://sshnet.codeplex.com/

Установка библиотеки :

  • PM>Install-Package SSH.NET -Version 2016.1.0
  •  NET CLI> dotnet add package SSH.NET --version 2016.1.0
  • Paket CLI> paket add SSH.NET --version 2016.1.0

Install SSH.NET with nuGet

Install SSH.NET from the nuGet repository by renci

Пример кода запуска команды на рестарт сервиса удалённой  linux системы

using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
   client.Connect();
   client.RunCommand("etc/init.d/networking restart");
   client.Disconnect();
}

[скачть справку по библиотеке ENG] The CHM file, at least in windows 7, when downloaded, will show broken links and empty pages unless you unblock the file.
Right click on: SshClient.chm # two
Near the bottom of the dialog on the right, you will see an "Unblock" button. Click it!

Пример  вывода спика файлов sftp SFTPClient.ListDirectory method: (synchronously)

using Renci.SshNet;
using Renci.SshNet.Sftp;
using System.IO;
/// <summary>
/// List a remote directory in the console.
/// </summary>
private void listFiles()
{
    string host = @"yourSftpServer.com";
    string username = "root";
    string password = @"p4ssw0rd";

    string remoteDirectory = "/some/example/directory";

    using (SftpClient sftp = new SftpClient(host, username, password))
    {
        try
        {
            sftp.Connect();

            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                Console.WriteLine(file.Name);
            }

            sftp.Disconnect();
        }
        catch (Exception e)
        {
            Console.WriteLine("An exception has been caught " + e.ToString());
        }
    }
}

asynchronously

Thread myThread = new System.Threading.Thread(delegate () {
    string remoteDirectory = "/some/example/directory";

    string host = @"yourSftpServer.com";
    string username = "root";
    string password = @"p4ssw0rd";

    using (SftpClient sftp = new SftpClient(host, username, password))
    {
        try
        {
            sftp.Connect();

            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                Console.WriteLine(file.Name);
            }

            sftp.Disconnect();
        }
        catch (Exception er)
        {
            Console.WriteLine("An exception has been caught " + er.ToString());
        }
    }
});

myThread.Start();

Пример  с использованием key file and password

string host = @"yourSftpServer.com";
string username = "root";
string password = @"p4ssw0rd";

PrivateKeyFile keyFile = new PrivateKeyFile(@"path/to/OpenSsh-RSA-key.ppk");
var keyFiles = new[] { keyFile };

var methods = new List<AuthenticationMethod>();
methods.Add(new PasswordAuthenticationMethod(username, password));
methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));

ConnectionInfo con = new ConnectionInfo(host, 22, username, methods.ToArray());
using (var client = new SftpClient(con))
{
    client.Connect();

    // Do what you need with the client !

    client.Disconnect();
}

Пример скачивания  файла

/// <summary>
/// Downloads a file in the desktop synchronously
/// </summary>
public void downloadFile()
{
    string host = @"yourSftpServer.com";
    string username = "root";
    string password = @"p4ssw0rd";

    // Path to file on SFTP server
    string pathRemoteFile = "/var/www/vhosts/some-folder/file_server.txt";
    // Path where the file should be saved once downloaded (locally)
    string pathLocalFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download_sftp_file.txt");

    using (SftpClient sftp = new SftpClient(host, username, password))
    {
        try
        {
            sftp.Connect();

            Console.WriteLine("Downloading {0}", pathRemoteFile);

            using (Stream fileStream = File.OpenWrite(pathLocalFile))
            {
                sftp.DownloadFile(pathRemoteFile, fileStream);
            }

            sftp.Disconnect();
        }
        catch (Exception er)
        {
            Console.WriteLine("An exception has been caught " + er.ToString());
        }
    }
}

 

Загрузка всего каталога
Если вам нужно загрузить весь каталог (даже вложенные папки и подфайлы), вам нужно будет создать 2 функции, а один из них - рекурсивный.

/// <summary>
/// Downloads a remote directory into a local directory
/// </summary>
/// <param name="client"></param>
/// <param name="source"></param>
/// <param name="destination"></param>
private void DownloadDirectory(SftpClient client, string source, string destination, bool recursive = false)
{
    // List the files and folders of the directory
    var files = client.ListDirectory(source);

    // Iterate over them
    foreach (SftpFile file in files)
    {
        // If is a file, download it
        if (!file.IsDirectory && !file.IsSymbolicLink)
        {
            DownloadFile(client, file, destination);
        }
        // If it''s a symbolic link, ignore it
        else if (file.IsSymbolicLink)
        {
            Console.WriteLine("Symbolic link ignored: {0}", file.FullName);
        }
        // If its a directory, create it locally (and ignore the .. and .=) 
        //. is the current folder
        //.. is the folder above the current folder -the folder that contains the current folder.
        else if (file.Name != "." && file.Name != "..")
        {
            var dir = Directory.CreateDirectory(Path.Combine(destination, file.Name));
            // and start downloading it''s content recursively :) in case it''s required
            if (recursive)
            {
                DownloadDirectory(client, file.FullName, dir.FullName);
            }
        }
    }
}

/// <summary>
/// Downloads a remote file through the client into a local directory
/// </summary>
/// <param name="client"></param>
/// <param name="file"></param>
/// <param name="directory"></param>
private void DownloadFile(SftpClient client, SftpFile file, string directory)
{
    Console.WriteLine("Downloading {0}", file.FullName);

    using (Stream fileStream = File.OpenWrite(Path.Combine(directory, file.Name)))
    {
        client.DownloadFile(file.FullName, fileStream);
    }
}

В дальнейшем вы можете приступить к созданию клиента с вашими учетными данными и начать загрузку удаленного каталога с использованием ранее
созданного метода. Обратите внимание: поскольку загрузка целого каталога
займет время, рекомендуется использовать его только асинхронным способом (создание потока), однако это всего лишь рекомендация

Thread myThread = new System.Threading.Thread(delegate () {
    string host = @"yourSftpServer.com";
    string username = "root";
    string password = @"p4ssw0rd";

    // Path to folder on SFTP server
    string pathRemoteDirectory = "/var/www/vhosts/some-folder-to-download";
    // Path where the file should be saved once downloaded (locally)
    string pathLocalDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "example-local-folder");

    using (SftpClient sftp = new SftpClient(host, username, password))
    {
        try
        {
            sftp.Connect();

            // By default, the method doesn''t download subdirectories
            // therefore you need to indicate that you want their content too
            bool recursiveDownload = true;

            // Start download of the directory
            DownloadDirectory(
                sftp,
                pathRemoteDirectory,
                pathLocalDirectory,
                recursiveDownload
            );
            
            sftp.Disconnect();
        }
        catch (Exception er)
        {
            Console.WriteLine("An exception has been caught " + er.ToString());
        }
    }
});

myThread.Start();

 

кудаление файла

/// <summary>
/// Delete a remote file
/// </summary>
private void deleteFile()
{
    string host = @"yourSftpServer.com";
    string username = "root";
    string password = @"p4ssw0rd";

    // Path to folder on SFTP server
    string pathRemoteFileToDelete = "/var/www/vhosts/folder/somefile.txt";

    using (SftpClient sftp = new SftpClient(host, username, password))
    {
        try
        {
            sftp.Connect();

            // Delete file
            sftp.DeleteFile(pathRemoteFileToDelete);

            sftp.Disconnect();
        }
        catch (Exception er)
        {
            Console.WriteLine("An exception has been caught " + er.ToString());
        }
    }
}