More efficient way of looping over SSH in KSH?
I currently have the following lines of code in a script:
set -A ARRAY OPTION1 OPTION2 OPTION3 OPTION4
set -A matches
for OPTION in ${ARRAY[@]}; do
DIFF=$(ssh $USER@$host " diff $PERSONALCONF $PRESETS$OPTION" )
if [[ $DIFF == "" ]]; then
set -A matches"${matches[@]}" $OPTION
fi
done
Basically, I have a loop that goes through each element in a pre-def开发者_JAVA百科ined array, connects to a remote server (same server each time), and then compares a file with a file as defined by the loop using the diff command. Basically, it compares a personal.conf file with personal.conf.option1, personal.conf.option2, etc. If there is no difference, it adds it to the array. If there is a difference, nothing happens.
I was wondering if its possible to execute this or get the same result (storing the matching files in an array ON THE HOST MACHINE, not the server that's being connected to) by way of only connecting once via SSH. I cannot store anything on the remote server, nor can I execute a remote script on that server. I can only issue commands via ssh (kind of a goofy setup). Currently, it connects as many times as there are options. This seems inefficient. If anyone has a better solution I'd love to hear it.
Several options:
You can use OpenSSH multiplexing feature (see
ssh(1)
).Also, most shells will gladly accept a script to run over stdin, so you could just run something like
cat script.sh | ssh $HOST /bin/sh
Most scripting languages (Perl, Python, Ruby, etc.) have some SSH module that allows connection reuse:
#!/usr/bin/perl use Net::OpenSSH; my ($user, $host) = (...); my @options = (...); my @matches; my $ssh = Net::OpenSSH->new("$user\@$host"); for my $option (@options) { my $diff = $ssh->capture("diff $personal_conf $presets$option"); if ($ssh->error) { warn "command failed: " . $ssh->error; } else { push @matches, $option if $diff eq ''; } } print "@matches\n";
精彩评论