【问题标题】:Perl file transfer to remote server using Net::OpenSSH使用 Net::OpenSSH 将 Perl 文件传输到远程服务器
【发布时间】:2020-09-17 08:26:15
【问题描述】:

我有一个脚本,它使用 Perl 模块 Net::OpenSSH 建立与远程服务器的连接,并将文件从本地服务器传输到远程机器。这工作得很好。

...
my $ssh = ConnectToServer( $host, $user, $password );

my $remote_dir = "/home/shared/some/path/"

if ( $ssh->system('mkdir', '-p', $remote_dir) ) {
    print "Directory $remote_dir created!\n";
} else {
   print "Can't create $remote_dir on $host : ".$ssh->error."\n";
}

$ssh->scp_put({glob => 1}, "/home/shared/Test_Vinod/LOG/*.zip", $remote_dir)
        or die "scp failed: " . $ssh->error;

undef $ssh;

sub ConnectToServer {
    my ( $host, $user, $passwd ) = @_;
    my $ssh = Net::OpenSSH->new($host,
                                user => $user,
                                password => $passwd,
                                master_opts => [-o => "StrictHostKeyChecking=no"]
    );
    $ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;

    return $ssh;
}

但每当我执行此脚本时,我都会收到消息:

Directory /home/shared/some/path/ created!

我在if ($ssh->system('mkdir', '-p', $remote_dir)) {线上的理解是:

如果$remote_dir 不存在,则在远程机器上递归创建它。

但是即使目录已经存在,$ssh->system('mkdir', '-p', $remote_dir) 的值如何变成1

也许我对-p 标志感到困惑。专家 cmets 预计。谢谢。

【问题讨论】:

    标签: perl ssh


    【解决方案1】:

    -p 标志并不关心目录是否已经存在。只要最后存在,就成功退出。

    $ mkdir -p test/a/b/c
    $ echo $?
    0
    
    $ mkdir -p test/a/b/c
    $ echo $?
    0
    

    macOS 上 mkdir 的手册页记录了这种行为:

    -p      Create intermediate directories as required.  If this
    option is not specified, the full path prefix of each operand must
    already exist. On the other hand, with this option specified, no
    error will be reported if a directory given as an operand already
    exists.  Intermediate directories are created with permission bits
    of rwxrwxrwx (0777) as modified by the current umask, plus write
    and search permission for the owner.
    

    Net::Openssl::system 如果远程命令成功退出(退出 0,如上所示),则返回 true,因此如果目录存在于 mkdir 调用结束时,它将始终返回 true。

    这是一个很好的幂等特性。您可以随意运行mkdir -p,而不必担心现有目录。您希望该目录树存在,只要它存在,mkdir 就会成功退出。

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 2022-11-05
      相关资源
      最近更新 更多