Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

grep log file in a remote host

General Tech Bugs & Fixes

Max. 2000 characters
Replies

usr_profile.png

User

( 6 months ago )

I'm trying to grep a string in the log file in a remote host. but I'm having trouble to return the echo to the host where I'm running the script.

#!/bin/bash
#dt=$(date +"%Y%m%d")
#HHMM=$(date '+%H:%M')
key="keys/cash_prod_key"



if
        ssh -o StrictHostKeyChecking=no -qni $key user@host "cat /var/log/FILE_send.log | grep FILENAME | grep -i success"\;
then
        echo "Success"
fi

I don't think this is the most correct way to do it.

usr_profile.png

User

( 6 months ago )

ssue was an incorrect host name.

This answer is instead focusing on how to write the code in a better way.

You don't need to run the complete pipeline on the remote host. Running complicated commands on the command line with ssh is rather error prone, not least from a quoting point of view.

Instead:

#!/bin/bash

key="keys/cash_prod_key"

ssh_args=( -o StrictHostKeyChecking=no -qni "$key" user@host )

if ssh "${ssh_args[@]}" cat /var/log/FILE_send.log |
   grep -F 'FILENAME' |
   grep -q -i -F 'success'
then
    echo 'Success'
fi

This would run only the cat on the remote host and then run the two grep commands locally.

I've also added the -F flag to the grep commands, assuming that the strings used as patterns are not regular expressions but literal strings that you'd like to search for. The last grep uses -q as we're not actually interested in seeing the output, just in whether it contains the string success or not.

To make it easier to read, I've put the arguments used with ssh into an array that I later use in the call, and I've also made the lines a bit shorter by simply inserting newlines after the pipe symbols. The script is still syntactically correct. Also note that any expansion of variable etc. should always be double quoted, unless you know in what contexts this is not needed.

Note that I'm assuming that the ssh command is invoked in the correct way.

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif