客人要求sftp需要User/Password + SSH私钥文件 方式登入,面向百度编程的程序员在网上找了一圈下来,单独User/Password
或者 SSH私钥文件方式登入的例子很多,但是双重认证的比较少,能找到的就是如下代码:
PrivateKeyFile privateKeyFile = new PrivateKeyFile(@"d:\\aaaaa.key", "aaaaaa"); var keybInterMethod = new KeyboardInteractiveAuthenticationMethod(sftpUserID); keybInterMethod.AuthenticationPrompt += (sender, e) => { e.Prompts.First().Response = "password"; }; AuthenticationMethod[] methods = new AuthenticationMethod[] { new PrivateKeyAuthenticationMethod("userName", privateKeyFile), keybInterMethod }; ConnectionInfo connectionInfo = new ConnectionInfo("ip", "userName", methods);
还有delegate另外的写法. 但是很奇怪的是,我测试的都无效,报错为password没有输入.
后面在 https://blog.csdn.net/qq_40409189/article/details/131106129 看到了一段代码 new PasswordAuthenticationMethod("userName","Password"),
灵光一闪,感觉摸到了门槛了,将代码修改为:
PrivateKeyFile privateKeyFile = new PrivateKeyFile(@"d:\\aaaaa.key", "aaaaaa"); AuthenticationMethod[] methods = new AuthenticationMethod[] { new PrivateKeyAuthenticationMethod(sftpUserID, privateKeyFile), new PasswordAuthenticationMethod(sftpUserID,sftpPassword) }; ConnectionInfo connectionInfo = new ConnectionInfo(sftpServerIP, sftpUserID, methods);
后面加上写入文件,到服务器上去查看了下,终于看到文件了.
using (SftpClient sftp = new SftpClient(connectionInfo)) { sftp.Connect(); sftp.UploadFile(file, remotePath); if (sftp != null && sftp.IsConnected) { sftp.Disconnect(); } }
其它问题:
1).key文件需要使用工具转为以下开头(这个文件全部都是可以使用vscode/记事本等作为txt文件打开的)
-----BEGIN RSA PRIVATE KEY-----
后面可能下一行是直接接数据的,也可能是下一行为下面的格式,两种格式都是可以接受的.
Proc-Type: 4,ENCRYPTED DEK-Info: xxxxxx
如果文件为下面这种格式,Renci.SshNet会报错,需要使用工具进行转换,
-----BEGIN ENCRYPTED PRIVATE KEY-----