0

Without using any external programs, using solely the bash language, is it possible to perform a port scan on a remote host?

After looking through bash's builtins, I would say: no. But maybe there are workarounds or additional possible commands it's possible to carry out which aren't in the bash builtins.

1 Answer 1

9

You can use Bash’s TCP connection support to check for open ports:

if 2>/dev/null >"/dev/tcp/${IP}/${PORT}"; then echo open; fi

will check whether a connection can be opened to port ${PORT} on ${IP}.

The test itself is performed by attempting the redirection to /dev/tcp/${IP}/${PORT}; redirecting standard error to /dev/null (2>/dev/null) hides the resuling error message when the target port isn’t reachable.

This can be used in a loop to scan all ports.

6
  • I've never heard of bash's "built-in /dev/tcp device file" before. This is also the first time I am seeing this [n]<>word redirection operator. Guess I've got a lot of exploration and discovery to look forward to, thanks for the answer! Commented Feb 6, 2020 at 18:29
  • 1
    @theonlygusti in this case, the operator doesn't matter: /dev/tcp/host/port work the same with >, <, <> or >>. The file descriptor will be in read-write mode in any case. Commented Feb 6, 2020 at 19:12
  • 2
    and that could be done simpler without any exec, with if 2>/dev/null >"/dev/tcp/$IP/$PORT"; then echo open; fi Commented Feb 6, 2020 at 19:34
  • I have an Ubuntu 19.10 and inside /dev/ i dont have tcp. Its this normal? does the solution provided is specific to an OS release? Commented Feb 7, 2020 at 9:55
  • 1
    @BANJOSA Bash handles /dev/tcp itself, there is no corresponding directory in /dev. See also this Q&A and the links there. Commented Feb 7, 2020 at 9:57

You must log in to answer this question.