You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# SSH.NET中使用Windows ssh-agent存储的私钥建立连接

如何在C# SSH.NET中使用Windows ssh-agent存储的私钥建立连接

嗨,这个问题我之前也碰到过!SSH.NET本身是支持从Windows ssh-agent获取密钥的,不过确实不能直接用那种简单的构造函数,得稍微配置一下认证方式就行,我给你一步步说:

  1. 不要用带用户名密码/密钥文件的简单构造函数,我们需要手动构建ConnectionInfo并指定agent认证方式
  2. 添加AgentAuthentication到连接信息的认证方法列表中,这会让SSH.NET自动去调用Windows ssh-agent获取可用的私钥

直接上可用的代码示例:

using Renci.SshNet;
using Renci.SshNet.AgentAuthentication;

// 替换成你的服务器信息
string server = "your-server-ip-or-hostname";
int port = 22;
string username = "your-username";

// 构建连接信息,指定使用ssh-agent认证
var connectionInfo = new ConnectionInfo(
    server,
    port,
    username,
    new AgentAuthentication()
);

// 创建客户端并连接
using var sshClient = new SshClient(connectionInfo);
try
{
    sshClient.Connect();
    Console.WriteLine("连接成功!");

    // 这里可以执行你需要的SSH命令
    var command = sshClient.RunCommand("ls -la");
    Console.WriteLine("命令输出:\n" + command.Result);
}
catch (Exception ex)
{
    Console.WriteLine($"连接出错:{ex.Message}");
}
finally
{
    if (sshClient.IsConnected)
    {
        sshClient.Disconnect();
    }
}

另外给你几个小提示:

  • 确保Windows的OpenSSH Authentication Agent服务是运行状态:可以按下Win+R输入services.msc,找到这个服务,设置启动类型为自动并启动它
  • 验证你的私钥确实在agent里:打开命令提示符输入ssh-add -l,如果能看到你的私钥指纹就说明没问题
  • 建议使用较新版本的SSH.NET NuGet包,旧版本可能对Windows ssh-agent的兼容性不太好

备注:内容来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 07:53:04