V

2012-12-23
Searching for files on an sftp- / scp-only server

While converting old sh/bash scripts which handled files with user supplied file names, I had to delete the files also on a server which is only accessible via sftp and scp. A quick check with Net::SSH2 showed that it could easily be done in perl:


#!/usr/bin/perl -w
use strict;
use warnings;
use Net::SSH2;

my $ssh_key = "$ENV{HOME}/.ssh/id_rsa";
my $ssh = Net::SSH2->new();
$ssh->connect(shift @ARGV)
    or die "$0: failed to connect: $!\n";
$ssh->auth_publickey($ENV{USER}, "$ssh_key.pub", $ssh_key)
    or die "$0: auth failed...\n";
my $sftp = $ssh->sftp()
    or die "$0: failed to request sftp subsystem: ",($ssh->error)[2],"\n";
foreach (@ARGV) {
    next unless $sftp->stat($_);
    $sftp->unlink($_)
        or warn "$0: failed to unlink '$_': ",($ssh->error)[2],"\n";
}
$ssh->disconnect();

A few versions later I had a script which can search for files on an sftp-server like find can do it on a local file system: sfind

Permalink | perl, sftp, ssh.
$HOME
Archives

Tags