2015-10-06 41 views
0

我需要使用SSH.NET庫來獲取文件在sftp上覆制的時間。但SftpFile類僅在文件被訪問和修改時返回(也可以選擇以UTC返回時間戳)。但是我需要在sftp上覆制文件時獲取時間戳。以下是我已經試過:當使用SSH.NET庫在sftp上覆制文件時獲取時間

using (var ssh = new SshClient(this.connectionInfo)) 
{  
    ssh.Connect(); 
    string comm = "ls -al " + @"/" + remotePath + " | awk '{print $6,$7,$8,$9}'"; 
    var cmd = ssh.RunCommand(comm); 
    var output = cmd.Result; 
} 

,但上面異常崩潰的代碼。「指定的參數超出有效值的範圍\ r \ n參數名:長度」在該行ssh.RunCommand(comm)。有沒有另一種方式來實現這個使用這個庫?

關注

+0

您的代碼爲我工作。 'remotePath'的確切值是多少?向我們展示異常調用堆棧。你使用的是什麼版本的SSH.NET? –

+1

您好Martin,它崩潰了,因爲我用的用戶沒有權限運行ssh命令。在我更改了sftp服務器上的這個設置後,代碼也爲我工作。 –

回答

0

我想這取決於在遠端使用的系統位。如果你看這篇文章: https://unix.stackexchange.com/questions/50177/birth-is-empty-on-ext4

我假設在遠程端有某種Unix,但指定它會有所幫助。

您看到的錯誤可能不是來自SSH.NET庫本身,而是來自您正在生成的命令。你可以打印comm變量的運行,你會得到這個錯誤?引用參數可能是一個問題,例如remotepath包含空格。

我把你的例子,運行在單聲道,它工作正常。正如在第二篇文章中所討論的,文件的出生時間可能不會暴露給系統上的stat命令,它不在我的系統中,它是Ubuntu 14.04.3 LTS。如果您的系統出現這種情況,並且您可以在遠程系統上存放腳本,請從引用的帖子中獲取get_crtime腳本並通過ssh觸發它。看來在新的系統與ext4fs統計將返回創建日期。對於修改時間

工作例如:

using System; 

using Renci.SshNet; 
using System.IO; 
namespace testssh 
{ 
    class MainClass 
    { 
     public static void Main (string[] args) 
     { 
      var privkey=new PrivateKeyFile (new FileStream ("/home/ukeller/.ssh/id_rsa", FileMode.Open)); 
      var authmethod=new PrivateKeyAuthenticationMethod ("ukeller", new PrivateKeyFile[] { privkey}); 
      var connectionInfo = new ConnectionInfo("localhost", "ukeller", new AuthenticationMethod[]{authmethod}); 
      var remotePath = "/etc/passwd"; 
      using (var ssh = new SshClient(connectionInfo)) 
      {  
       ssh.Connect(); 
       // Birth, depending on your Linux/unix variant, prints '-' on mine 
       // string comm = "stat -c %w " + @"/" + remotePath; 

       // modification time 
       string comm = "stat -c %y " + @"/" + remotePath; 
       var cmd = ssh.RunCommand(comm); 
       var output = cmd.Result; 
       Console.Out.WriteLine (output); 
      } 
     } 
    } 
} 
+0

它崩潰,因爲我使用的用戶沒有權限運行ssh命令。在我更改了sftp服務器上的這個設置後,代碼也爲我工作。所以我不能依賴這個實現,因爲客戶端可能會隨時更改這個設置,所以我會強制使用創建/訪問時間。謝謝 –