V

2012-11-25
ssh draining stdin

We had a script which does some remote commands based on preconditions. It stopped processing the loop after the first time the condition was true:

#!/bin/sh
DATA="host1 1
host2 2
host3 3
host4 4
host5 5"

echo "$DATA" | while read host num; do
    if [ $(( num % 2 )) -eq 1 ]; then
        ssh $host "echo $num"
    fi
done
$ sh test1.txt 
1
$

I found that ssh was reading all the remaining data and the next read failed and the loop ended. When redirecting ssh's stdin from /dev/null everything worked as expected. As alternative to redirecting stdin you can also use the -n switch for ssh (i.e. run ssh -n $host "echo $num" ):

#!/bin/sh
DATA="host1 1
host2 2
host3 3
host4 4
host5 5"

echo "$DATA" | while read host num; do
    if [ $(( num % 2 )) -eq 1 ]; then
        ssh -n $host "echo $num"
    fi
done
$ sh test1.sh
1
3
5
$
Permalink | shell, ssh.
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