2014-10-07 181 views
0

我正嘗試使用SFTP將文件從一臺服務器傳輸到其他服務器。我使用的命令使用SFTP時出錯

sftp2 -i "public key path" "source file path" [email protected] "destination file path" 

當我使用命令該命令手動提示它工作正常,但我使用指定此服務在C#代碼我歌廳錯誤

帳戶相同的命令與在同一進程中運行的其他服務指定的帳戶 不同。

任何想法爲什麼我得到這個錯誤和分辨率相同。

在此先感謝。

回答

0

我的猜測是,您可能需要在調用SFTP時模擬其他用戶(username @ servername)?

using (new Impersonation(domain, username, password)) 
{ 
    // do the Sftp call. 
} 

其中採用馬特 - 約翰遜這個代碼。

using System; 
using System.Runtime.ConstrainedExecution; 
using System.Runtime.InteropServices; 
using System.Security; 
using System.Security.Permissions; 
using System.Security.Principal; 
using Microsoft.Win32.SafeHandles; 

namespace MyApplication 
{ 
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 
    public class Impersonation : IDisposable 
    { 
     private readonly SafeTokenHandle _handle; 
     private readonly WindowsImpersonationContext _context; 

     const int LOGON32_LOGON_NEW_CREDENTIALS = 9; 

     public Impersonation(string domain, string username, string password) 
     { 
      var ok = LogonUser(username, domain, password, 
          LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle); 
      if (!ok) 
      { 
       var errorCode = Marshal.GetLastWin32Error(); 
       throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); 
      } 

      this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle()); 
     } 

     public void Dispose() 
     { 
      this._context.Dispose(); 
      this._handle.Dispose(); 
     } 

     [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 
     private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken); 

     public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid 
     { 
      private SafeTokenHandle() 
       : base(true) { } 

      [DllImport("kernel32.dll")] 
      [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] 
      [SuppressUnmanagedCodeSecurity] 
      [return: MarshalAs(UnmanagedType.Bool)] 
      private static extern bool CloseHandle(IntPtr handle); 

      protected override bool ReleaseHandle() 
      { 
       return CloseHandle(handle); 
      } 
     } 
    } 
}