SSH接続テスト (公開鍵認証) (SSH.NET) 2016/11
•2019/3 Key 'OPENSSH' is not supported. エラーについて
OpenSSHのssh-keygenで作成する秘密鍵のデフォルト方式が「OPENSSH」形式に変更されたたが、SSH.NETが未対応のため公開鍵方式でログインができなくなるエラーが発生。 ssh-keygenで'-M'オプションをつけると従来通りの形式で秘密鍵が生成されるので、下記コードでログインすることができる。
ソースコード
•2019/3 Key 'OPENSSH' is not supported. エラーについて
OpenSSHのssh-keygenで作成する秘密鍵のデフォルト方式が「OPENSSH」形式に変更されたたが、SSH.NETが未対応のため公開鍵方式でログインができなくなるエラーが発生。 ssh-keygenで'-M'オプションをつけると従来通りの形式で秘密鍵が生成されるので、下記コードでログインすることができる。
ソースコード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// ここまではデフォルト
using System.Net;
using Renci.SshNet;
// 以上の2つは追加
namespace ConsoleSSHTest2
{
class Program
{
static void Main(string[] args)
{
// サーバURL (IPアドレスも可)
string url = "hoge.kd2.jp";
//string url = "xxx.xxx.xxx.xxx";
// サーバポート
int port = 22;
// ユーザ
string username = "www";
// 秘密鍵
string privatekey = @"C:\path\to\private_key";
ConnectionInfo CInfo = new ConnectionInfo(url, port, username,
new AuthenticationMethod[] {
new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile[] {
new PrivateKeyFile(privatekey)
// パスフレーズがある場合は new PrivateKeyFile(privatekey, "passphrase")
})
}
);
string command = "ls -la";
using (SshClient sshClient = new SshClient(CInfo))
{
sshClient.Connect();
using (SshCommand cmd = sshClient.CreateCommand(command))
{
cmd.Execute();
Console.WriteLine(username + "@" + url + " > " + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("ExitStatus = {0}", cmd.ExitStatus);
}
sshClient.Disconnect();
}
}
}
}