I'm trying to understand what
grep -v grep does below:
ssh $server -p $port -o "ConnectTimeout 5" | grep -v "Connection refused" | grep "Connected to" | grep -v grep | wc -l
Or is there a better way to find TCP connection test?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
If you want to check that you can establish a ssh connection within 5 seconds and run a command, just do:
if ssh -o BatchMode=yes -o ConnectTimeout=5 -p "$port" "$server" true; then printf '%s\n' "$server is up" fi
Your command as it is makes little sense. As you don't provide with a command to run on the remote server,
ssh will run in the
rlogin mode, where a pseudo-terminal is requested and the login shell of the remote user is started (or possibly a ForcedCommand).
Then, you're applying several filters to the output:
grep -v "Connection refused": filter out any line from the output that contains
Connection refused. That makes little sense as that error message if it appeared would be written on stderr, not the standard output that
grepis filtering, and also because:
grep "Connected to": select only the lines that contain
Connected to. That would also exclude the lines that contain
Connection refusedas it's unlikely for a line to contain both.
grep -v grep, also remove the lines that contain
grep(so that would be lines that contain both
wc -l: count the number of resulting lines (so the lines in
ssh's stdout that contain
Connected toexcept those that also contain
Connection refused). Note that
wcwill only output that number when the connection is closed, when the shell session has been terminated, like when the user enters
exit. But then again, since the user won't see any output (since it all goes to
wceventually), the user will have little clue that he needs to enter
exitto terminate that session.