csharp ssh.net示例 - 基于密钥的身份验证,文件上载,Shell命令

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp ssh.net示例 - 基于密钥的身份验证,文件上载,Shell命令相关的知识,希望对你有一定的参考价值。

/*
    get SSH.NET (BSD License: http://sshnet.codeplex.com/license)
    
    with NuGet:
    >Install-Package SSH.NET -Version 2013.4.7
    
    or just get the dll from here: http://j.mp/sshNet
    
*/
using System;
using System.Collections.Generic;
using Renci.SshNet; /* reference needed: Renci.SshNet.dll */

class Program
{
    static void Main(string[] args){

        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("hostOrIP",22,"username",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("username","password"),

                // Key Based Authentication (using keys in OpenSSH Format)
                new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{ 
                    new PrivateKeyFile(@"..\openssh.key","passphrase")
                }),
            }
        );

        // Execute a (SHELL) Command - prepare upload directory
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();
            using(var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest")){
                cmd.Execute();
                Console.WriteLine("Command>" + cmd.CommandText);
                Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
            }            
            sshclient.Disconnect();
        }

        // Upload A File
        using (var sftp = new SftpClient(ConnNfo)){
            string uploadfn = "Renci.SshNet.dll";

            sftp.Connect();
            sftp.ChangeDirectory("/tmp/uploadtest");
            using (var uplfileStream = System.IO.File.OpenRead(uploadfn)){
                sftp.UploadFile(uplfileStream, uploadfn, true);
            }
            sftp.Disconnect();
        }

        // Execute (SHELL) Commands
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();

            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
            Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
            Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }
}

以上是关于csharp ssh.net示例 - 基于密钥的身份验证,文件上载,Shell命令的主要内容,如果未能解决你的问题,请参考以下文章

使用 SSH 公钥/私钥连接到 sFTP 服务器。错误 Invalid private key file. 使用 SSH.NET

在 Perl 的 ssh 连接中捕获错误主机名的错误消息(使用 Net::OpenSSH)

csharp 使用openssl rsa密钥的C#RSACryptoService

如何在 CSharp 中制作自己的许可证密钥

我们是不是应该在很大程度上基于本地 jwt 令牌到期日期来验证用户

sftp