Determine if a port is open with bash

: </dev/tcp/127.0.0.1/80
For times when netcat isn't available. Will throw a Connection refused message if a port is closed. Scriptable: (: </dev/tcp/127.0.0.1/80) &>/dev/null && echo "OPEN" || echo "CLOSED"

14
By: zlemini
2015-08-28 19:07:27

1 Alternatives + Submit Alt

What Others Think

Great command, but should be: :</dev/tcp/127.0.0.1/80) &>/dev/null 2>&1 && echo "OPEN" || echo "CLOSED"
tlemerond · 163 weeks and 2 days ago
In bash4 its fine as it is, in older versions and korn shell your version would be more robust.
zlemini · 163 weeks and 1 day ago
I like this, however I have to act like the comic book guy from the Simpsons here and point out that this will only work if you have the service bound to your loopback interface.. In general a service will bind to all interfaces, but these days people actually take the security measure of binding a service to one or more specific IPs. It does work as long as you specify the IP: root@worstboxever:~# : root@worstboxever:~# : -su: connect: Connection refused -su: /dev/tcp/1.3.3.7/12345: Connection refused The first command gives no output, so: root@thebaine:~# (: /dev/null && echo "OPEN" || echo "CLOSED" OPEN Sweet.. I'll give you a plus one for this. I never knew you could actually do anything with /dev/tcp.
sonic · 161 weeks and 5 days ago
ugh, the HTML code mangled the crap out of what I typed.. The first command was (no spaces) : < /dev/tcp/1.3.3.7/80 And the last command (with added spaces) ( : < /dev/tcp/1.3.3.7/80 ) & > /dev/null & & echo "OPEN" || echo "CLOSED" OPEN (output)
sonic · 161 weeks and 5 days ago
(: /dev/null && echo "OPEN" || echo "CLOSED"
sonic · 161 weeks and 5 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: