C# 中来自 SshNet 的 SshConnectionException

SshConnectionException from SshNet in C#

从我的脚本尝试连接到 unix 服务器以下载文件但出现以下错误..

Renci.SshNet.Common.SshConnectionException : Client not connected.

我可以使用相同的凭据从 WinScp 正确连接到该服务器。

不确定这里出了什么问题。任何 idea/pointer ?

代码

using (var client = new ScpClient(Config.UnixServer, Config.UnixUsername, Config.UnixPassword))
{
    client.Connect();
    client.Upload(new FileInfo(fileUpload), fileName);
    client.Disconnect();
}

错误

Renci.SshNet.Common.SshConnectionException : Client not connected.
at Renci.SshNet.Session.WaitOnHandle(WaitHandle waitHandle)
at Renci.SshNet.Session.Connect()
at Renci.SshNet.BaseClient.Connect()

WinSCP Session Log

也许这有帮助?

也许与 unix 路径有关?检查 client.RemotePathTransformation = RemotePathTransformation.ShellQuote;

快速阅读here

By default, SSH.NET applies a simple quoting mechanism for remote paths in ScpClient. More precisely, any remote path is enclosed in double quotes before it is passed to the scp command on the remote host.

也许信任不存在?在原始日志中,OP 具有以下内容: 2017-09-14 09:10:17.495 主机密钥匹配缓存密钥。

github 页:https://github.com/sshnet/SSH.NET 有关于如何建立预期指纹的信息。

我 运行 遇到的另一个问题是服务器有 IP 地址白名单并且服务器在上面,但我的测试环境没有。

@Lee,正如 Martin 所指出的,执行连接的应用程序的日志对于弄清楚这些事情最有帮助。

会话日志显示WinSCP正在使用sftp协议(WinSCP同时支持scp和sftp协议)。并非所有 sftp 服务器都接受 scp 连接。切换到 SftpClient class 并使用 UploadFile 方法。

我还怀疑您打算在 FileInfo 实例上调用 OpenRead() 来获取流。

using (var client = new SftpClient(Config.UnixServer, Config.UnixUsername, Config.UnixPassword))
{
    client.Connect();
    client.UploadFile(new FileInfo(fileUpload).OpenRead(), fileName);
    client.Disconnect();
}

更新仁慈参考库将解决问题。