hi,
i would like to create a bash script that check which port in my Linux server are closed (not in use) from a specific range, port range (3000-3010).
the print output need to be only 1 port, and it will be nice if the output will be saved as a variable or in same file.
my code is:
#!/bin/bash
IP=$1
first_port=$2
last_port=$3
function scanner
{
for ((port=$first_port; port<=$last_port; port++))
do
(echo >/dev/tcp/$IP/$port)> /dev/null 2>&1 && echo $port open || echo "$port closed"
done
}
scanner
than to run it i use: ./demo2.sh 127.0.0.1 3000 3010
In terms of your script itself as a solution to your problem, a change like this should work:
#!/bin/bash
IP=$1
first_port=$2
last_port=$3
function scanner
{
for ((port=$first_port; port<=$last_port; port++))
do
if ! (echo >/dev/tcp/$IP/$port)2>/dev/null
then
echo $port
return
fi
done
}
scanner
This will cause the first TCP port that cannot have a blank line written to it by the echo command to be echo ed out to standard output. The key is the return statement, which will cause the function to end as soon as it is executed. So once we find the first port we can't write a blank line to, we print it out and return control to the next line of the script (which doesn't exist, and so the script ends at that point).
Now, a better question: what is it you actually need to do here, and why ? This script might well work for certain ports in certain circumstances, but a far better bet here would be to use a utility that is dedicated to the purpose of port scanning (like nmap , for example) rather than trying to re-invent the wheel with a shell script.