客人要求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-----