【问题标题】:get time when a file was copied on sftp using SSH.NET library使用 SSH.NET 库在 sftp 上复制文件时获取时间
【发布时间】:2015-10-06 15:50:31
【问题描述】:

我需要获取使用SSH.NET 库在 sftp 上复制文件的时间。但是 SftpFile 类仅在文件被访问和修改时返回(也可以选择以 UTC 格式返回时间戳)。但是我需要在 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)。有没有其他方法可以使用这个库来实现这一点?

问候

【问题讨论】:

  • 您的代码对我有用。 remotePath 的确切值是多少?向我们展示异常调用堆栈。您使用的是什么版本的 SSH.NET?
  • 嗨 Martin,它崩溃了,因为我使用的用户没有运行 ssh 命令的权限。在我在 sftp 服务器上更改此设置后,代码也对我有用。

标签: c# ssh sftp


【解决方案1】:

我想这在一定程度上取决于远程端使用的系统。如果你看这个帖子: https://unix.stackexchange.com/questions/50177/birth-is-empty-on-ext4

我假设在远程端有某种 Unix,但指定它会有所帮助。

您看到的错误可能不是来自 SSH.NET 库本身,而是来自您正在生成的命令。您可以打印comm 变量以进行出现此错误的运行吗?引用论点可能是一个问题,例如remotepath 包含空格。

我拿了你的例子并在 Mono 上运行它,它工作正常。正如两篇文章中所讨论的,文件的诞生时间可能不会暴露给您系统上的stat 命令,它不在我的 Ubuntu 14.04.3 LTS 上。如果您的系统是这种情况,并且您可以在远程系统上存放脚本,请从引用的帖子中获取 get_crtime 脚本并通过 ssh 触发它。似乎在具有 ext4fs stat 的较新系统上将返回创建日期。

修改时间的工作示例:

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);
            }
        }
    }
}

【讨论】:

  • 它崩溃了,因为我使用的用户没有运行 ssh 命令的权限。在我在 sftp 服务器上更改此设置后,该代码也对我有用。所以我不能依赖这个实现,因为客户端可能随时更改这个设置,所以我会建议使用创建/访问时间。谢谢
猜你喜欢
  • 2014-07-05
  • 1970-01-01
  • 2011-06-17
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多