2015-10-06 99 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服务器上的这个设置后,代码也为我工作。所以我不能依赖这个实现,因为客户端可能会随时更改这个设置,所以我会强制使用创建/访问时间。谢谢 –