Find the answer to your Linux question:
Results 1 to 6 of 6
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    ssh+commands in shell script

    Hi, I'm trying to write a script that ssh's to another server and does some commands.

    I have problems with this:

    LIST=´ls -l /DIR | grep -v gz | wc -l`
    ssh user(at)server <<EOT
    echo $LIST
    if [ $LIST -gt 1 ]
    echo " One or more files are not gzipped "
    echo " It's fine "
    I then run the script on the local server and outputs it to a .txt file.

    But the output is 0 everytime, even if there are files that's not gzipped in that directory.

    What am I missing?

  2. #2
    Is there a reason you chose to use Bash to do this?

    Perl offers some very easy to implement modules that will make you life much easier, and make maintenance easier.


    Here is an example I wrote a while ago:

    use strict;
    use warnings;
    use Net::SSH::Perl;
    my $host = "";
    my $user = 'root';
    my $pass = 'password';
    my $ssh = Net::SSH::Perl->new($host);
    $ssh->login($user, $pass);
    my ($stdout, $stderr, $exit) = $ssh->cmd("ls -l");
    print "$stdout, $stderr, $exit \n";
    ($stdout, $stderr, $exit) = $ssh->cmd("find -name 'somefile'");
    This is a basic example, but you could easily extend this for multiple hosts.

    Past that, I really need a better idea of what it is you are attempting to do.

  3. #3
    I agree w/three18ti - there are more sophisticated ways to do this.

    But looking at your example, I would modify it like so in order to get it work like you want (I think) - but most important is that you have to escape the variable holding your count value:
    #LIST='ls -l /tmp/DIR | grep -v gz|wc -l'
    ssh user(at)server <<EOT
    cnt=$(find /DIR -type f -not -iname '*.gz'|wc -l)
    echo \$cnt
    if [ \$cnt -gt 1 ]; then
     echo " One or more files are not gzipped "
     echo " It's fine "

  4. $spacer_open
  5. #4
    Linux User stokes's Avatar
    Join Date
    Oct 2004
    Hi, your script doesn't work because you defined your LIST variable locally. When you ssh'd to the remote server, you were in a new shell and $LIST didn't exist. Also rather than using ssh name@server <<EOT, I would use semicolons for line breaks. Something like:
    ssh user@server 'if [ "$(ls -l /DIR | grep -v gz | wc -l)" -gt 1 ]; then echo " One or more files are not gzipped "; else echo "its fine";fi'
    btw, I didn't test that. Might put you on the right lines though.
    Registered Linux user #389109
    My Semi-Linux Blog

  6. #5
    Thanks for the input, learned something atleast.
    I did it the "lazy" way and made a script on the remote server with the commands and called that script from a script on the local server.

  7. #6
    And ...

    + Net::OpenSSH
    + Net::SSH2

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts