Reputation: 337
How are all here .... I need to check if there is any directory exists on a specified path. e.g. if path is /root/home/ then check directory ABC if exists on this path. I need if there is no such dir exists then create it else skip creating.
I am using Net::SSH2
. I can create and save files using Net::SSH2
but I don't know how to check the existence of directories and files using Net::SSH2
in remote server.
Upvotes: 0
Views: 3248
Reputation: 43683
#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH2;
use Net::SSH2::SFTP;
use Net::SSH2::File;
my $host = 'sftp.somesite.com';
my $path = "/root/home/ABC";
my $user = "user";
my $password = "passwd";
my $ssh = Net::SSH2->new();
die "Can't Connect to $host" unless $ssh->connect($host);
if ($ssh->auth_password($user, $password))
{
my $sftp = $ssh->sftp();
$sftp->opendir($path) or $sftp->mkdir($path);
my $error = $sftp->error;
print "Error: $error\n" if (!$sftp->opendir($path));
}
Upvotes: 2
Reputation: 126742
I assume you're using the sftp
method to create an Net::SSH2::SFTP
object?
What I would do is to call Net::SSH2::SFTP->mkdir
method regardless of whether the directory exists: the overhead involved with attempting to create an already-existent directory is likely to be insignificant.
However if you must find whether a given directory is already in place, you can use the Net::SSH2::SFTP->opendir
method, which will return a valid Net::SSH2::Dir
object only if the directory exists.
Upvotes: 2