【问题标题】:How to create a file in remote host along with the creation of directory using ssh如何在远程主机中创建文件以及使用 ssh 创建目录
【发布时间】:2011-03-09 19:18:54
【问题描述】:

我的主机中有一个文件,例如 /a/b/c/file。我想在 dest 目录中的远程主机上创建一个文件。现在的问题是,如何使用 perl 脚本和 ssh 在远程主机中创建一个文件为 /dest/a/b/c/d/file。知道如何在脚本中创建目录吗?

谢谢。

【问题讨论】:

    标签: perl file ssh file-handling net-ssh


    【解决方案1】:

    要重现目录结构,请使用File::Spec 模块中的catfileabs2relcatfile 将部分连接起来形成路径,abs2rel 给出相对于某个基本目录的路径。

    File::Copy 模块的copy 将复制到句柄。这与sshopen3 在目标端打开标准输入、输出和错误句柄的方式非常吻合。

    远程命令有 3 个部分:

    • mkdir -p $dst_dir,在目标路径中创建文件前面的所有目录
    • cat >$dst_file,将SEND句柄连接到目标文件
    • md5sum $dst_file,表示数据安全到达

    下面的示例程序:

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    use File::Basename;
    use File::Copy;
    use File::Spec::Functions qw/ abs2rel catfile /;
    use Net::SSH qw/ sshopen3 /;
    
    my $HOST     = "user\@host.com";
    my $SRC_BASE = "/tmp/host";
    my $SRC_FILE = "$SRC_BASE/a/b/c/file";
    my $DST_BASE = "/tmp/dest";
    system("md5sum", $SRC_FILE) == 0 or exit 1;
    
    my $dst_file = catfile $DST_BASE, abs2rel $SRC_FILE, $SRC_BASE;
    my $dst_dir  = dirname $dst_file;
    sshopen3 $HOST, *SEND, *RECV, *ERRORS,
             "mkdir -p $dst_dir && cat >$dst_file && md5sum $dst_file"
      or die "$0: ssh: $!";
    
    binmode SEND;
    copy $SRC_FILE, \*SEND or die  "$0: copy failed: $!";
    close SEND             or warn "$0: close: $!";  # later reads hang without this
    
    undef $/;
    my $errors = <ERRORS>;
    warn $errors if $errors =~ /\S/;
    close ERRORS or warn "$0: close: $!";
    
    print <RECV>;
    close RECV or warn "$0: close: $!";
    

    示例运行:

    $ ./create-file
    746308829575e17c3331bbcb00c0898b /tmp/host/a/b/c/file
    746308829575e17c3331bbcb00c0898b /tmp/dest/a/b/c/file

    【讨论】:

    • 谢谢。我可以得到你的代码。对不起。但我对所有这些文件和目录处理都很陌生。例如,我如何处理其中的情况。假设我在变量 $src_dir 主机目录文件中的主机目录 /src ./a/b/f1 在变量 $src_file 目标目录 /dst 在变量 $dst_dir 现在我需要像 /dst/a/b/c/f1 这样的文件现在是第一个问题..我做了 $dst_dir/$src_file 我得到 /dst/./a/b/c/f1 我需要摆脱额外的 ./ 并通过某种方式获取目录路径来创建目录 /dst/a/b/c从 $src_file 并在其下创建一个文件 f1 。我该如何解决这个问题。谢谢。
    • 嗨,我可以得到解决方案。我按照您的建议使用了使用 File::Basename 模块来获取文件名和目录。然后我使用 ssh 使用 mkdir -p "dir" 在远程主机中创建目录。然后创建文件。那效果很好。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2019-05-21
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多