-1

When trying to perform the following command:

curl -v telnet docker.io:80 | grep -q 'connected to docker.io'

I can't get the "interesting part" where I only need the message I wanted to grep.

Screenshot

I want to use a built-in Centos command and not netcat to check if a port is open because it's port of a script that needs to run on pre-installation.

Niv
  • 27
  • 3
  • The `connected` string is written to stderr, not stdout. You're only piping stdout, so `grep` never sees it. – Charles Duffy Jul 16 '19 at 16:19
  • 1
    ...anyhow, there are much better ways to tell if a HTTP server is working; `if curl --fail http://whatever`, in particular, is your friend. – Charles Duffy Jul 16 '19 at 16:20

1 Answers1

0

You can use curl simply for checking port.

r=$(curl docker.io:80 --connect-timeout 5 2>/dev/null; echo $?)
if [ $r == 0 ]; 
then 
  echo opened; 
else 
  echo closed;
fi

if $r is 0, it is opened, otherwise it is closed. note that you can change connection timeout for your situation.

RyanKim
  • 1,557
  • 9
  • 10
  • 1
    `[ $r == 0 ]` is generally buggy. Use `[ "$r" = 0 ]` (`=` is POSIX-standardized, whereas `==` is not and doesn't work in dash or other POSIX-baseline shells; leaving out quotes means that if `curl` writes content to stdout before the `echo`, you'll have that content treated as extra arguments to `[`, which can make behavior quite unpredictable), or even better, just `if curl ...; then` with no use of `$?` at all. – Charles Duffy Jul 16 '19 at 16:19
  • 1
    Exactly my point. It's a bash extension, so it doesn't work with `/bin/sh`, as commonly used on Debian, Ubuntu, etc. If you're going to require bash extensions, go all the way and use `[[` -- that way you don't have bugs with failing to quote on the left-hand side &c. – Charles Duffy Jul 16 '19 at 16:26
  • 1
    BTW, even with `if curl docker.io:80 --connect-timeout 5 2>/dev/null; then echo opened; else echo closed; fi`, I'd worry about whether it would have a nonzero exit status when a server answers at the port but doesn't speak HTTP -- if the OP wanted to check for HTTP-ness rather than open-ness, presumably they wouldn't be asking for `telnet`. – Charles Duffy Jul 16 '19 at 16:30
  • 1
    ...and yes, curl *may* return nothing on stdout, but it also *may* return body content. If you write your code to work only for the one web server the OP uses in their example... well, that's awfully specific. – Charles Duffy Jul 16 '19 at 16:30
  • 1
    Thanks Charles. I have learned good point from you. I think he want to check if outbound rule of his servers are opened to docker.io:80. – RyanKim Jul 16 '19 at 16:45
  • Hi Guys, thanks for the comments. however, when I try to the same thing for jfrog.io I get an error of 'too many arguments' any idea what's causing this? – Niv Jul 18 '19 at 13:18