Check Whether Directory Exists In Remote Server Fo

2019-09-20 06:53发布

问题:

I wish to check whether a path given is exists or is a directory in another site server in Perl. My code is as below.

my $destination_path = "<path>";
my $ssh = "usr/bin/ssh";
my $user_id = getpwuid( $< );
my $site = "<site_name>";
my $host = "rsync.$site.com";

if ($ssh $user_id\@$host [-d $destination_path]){
  print "Is a directory.\n";
}
else{
  print "Is not a directory.\n";
}

I am sure my code is wrong as I modify the code according to bash example I see from another question but I have no clue how to fix it. Thanks for everyone that helps here.

回答1:

[ is the name of a command, and it must be separated from other words on the command line. So just use more spaces:

$ssh $user\@$host [ -d $destination_path ]

To actually execute this command, you'll want to use the builtin system function. system returns 0 when the command it executes is successful (see the docs at the link)

if (0 == system("$ssh $user\@$host [ -d $destination_path ]")) {
    print "Is a directory.\n";
} else {
    print "Is not a directory.\n";
}


回答2:

Accessing the remote file system through SFTP:

use Net::SFTP::Foreign;

$sftp = Net::SFTP::Foreign->new("rsync.$site.com");
if ($sftp->test_d($destination_path)) {
    "print $destination_path is a directory!\n";
}


标签: linux perl ssh