shellone-liner

How to grep multiple words from a remote file in a SSH command to a target server


I wanted to execute the below command. I have a file with server names.

for i in \`cat /tmp/srv_list\`; do ssh $i "uname -a; uptime;  grep -E "warn|error|failed|issues" /var/log/messages ; echo "======================= "" \>\> /var/tmp/hst.out; done

I couldn't get the above working. The one-liner breaks after the first word in the grep sequence and waits indefinitely.

Output

========

# for i in `cat /tmp/srv_list`; do ssh $i "uname -a; uptime; grep -E "warn|error|completed|issues|rollback" /var/adm/messages/*unix " >> /var/tmp/new.out; done

-bash: error: command not found

-bash: issues: command not found

Access to this computer is prohibited unless authorised

Accessing programs or data unrelated to your job is prohibited


Solution

  • Bash is able to serialize function into string. That way you can send any commands to the remote side.

    Do not use backticks. Use $(...).

    for i in $(..) is an antipattern. Check your scripts with ShellCheck.

    work() {
       uname -a
       uptime
       grep -E "warn|error|completed|issues|rollback" /var/adm/messages/*unix
    }
    for i in $(cat /tmp/srv_list); do
       ssh "$i" "$(declare -f work);work" >> /var/tmp/new.out
    done
    

    You might also be interested in pssh and ansible.