TCP Port Scanner in Bash - good coders code, great reuse |
| Posted: 28 Aug 2012 06:02 AM PDT I just had this quick idea to write a tcp port scanner in bash. Bash supports the special So at first I wrote this quick script: for port in {1..65535}; do echo >/dev/tcp/google.com/$port && echo "port $port is open" || echo "port $port is closed" done This loops over ports 1-65535 and tries to open To solve this I needed something like alarm() { perl -e ' eval { $SIG{ALRM} = sub { die }; alarm shift; system(@ARGV); }; if ($@) { exit 1 } ' "$@"; } This Once I had this, I could take my earlier code and just call it through alarm: for port in {1..65535}; do alarm 1 "echo >/dev/tcp/google.com/$port && echo \"port $port is open\"" || echo "port $port is closed" done This is working! Now if bash freezes because of a closed port, the I went ahead and turned this into a proper scan() { if [[ -z $1 || -z $2 ]]; then echo "Usage: $0 <host> <port, ports, and/or port-range>" return fi host=$1 ports=() case $2 in *-*) IFS=- read start end <<< "$2" for ((port=start; port <= end; port++)); do ports+=($port) done ;; *,*) IFS=, read -ra ports <<< "$2" ;; *) ports+=($2) ;; esac for port in "${ports[@]}"; do alarm 1 "echo >/dev/tcp/$host/$port && echo \"port $port is open\"" || echo "port $port is closed" done } You can run the Here is what happens when I run $ scan google.com 78-82 port 78 is closed port 79 is closed port 80 is open port 81 is closed port 82 is closed Similarly you can write an udp port scanner. Just replace |
| You are subscribed to email updates from good coders code, great reuse To stop receiving these emails, you may unsubscribe now. | Email delivery powered by Google |
| Google Inc., 20 West Kinzie, Chicago IL USA 60610 | |
No comments:
Post a Comment
Keep a civil tongue.