How to get Netcat to return unused ports - linux

I tried this command to try to find unused ports. What I want it to do is run netcat on a range of ports, find the ones that are not running services, grep the first one of those lines of output, and then use sed to output the port number only.
nc -z <my url> 5000-5010 | grep -m 1 succeeded | sed 's/[^0-9]//g'
But when I try and launch a service using the port that is returned, I get a message saying the port is currently in use.
I found out netcat success means a service is running on the port, but when I try this instead
nc -zv <my url> 5000-5010 | grep -m 1 failed | sed 's/[^0-9]//g'
I get nothing, even though most lines of output contain the word failed.
Going through the man pages revealed that netcat -z only returns output for successful results, though why line after line of failed connection appears on my terminal window is still beyond me.
How can I use netcat to view the first port a connection failed on?

To get a list of closed (unused) ports on a linux system you can use:
Realtime Output:
#!/bin/bash
remoteHost=stackoverflow.com
for i in {80..100}
do
nc -v -z -w 1 $remoteHost $i &> /dev/null && echo "Port $i Open" || echo "Port $i Closed"
done
You can change the timeout, currently set to 1 sec (-w 1), to a higher value if needed.
Output:
Port 80 Open
Port 81 Closed
Port 82 Closed
Port 83 Closed
Port 84 Closed
Port 85 Closed
etc..
nc arguments:
-v Have nc give more verbose output.
-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunction with the -l option.
-w timeout
If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed. The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag. The default is no timeout.
Resources
nc man

The nc -v command writes the failed/succeeded messages on standard error, not the standard output. You can redirect stderr to stdout using 2>&1.
nc -zv <my url> 5000-5010 2>&1 | grep -m 1 failed
to get the failed line.
See http://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/
By the way, I suggest you use awk to get the port number from the output line:
nc -zv <my url> 5000-5010 2>&1 | grep -m 1 failed | awk '{print $6}'
which prints the value in the 6th column of the output line.

Related

Why is the shell output txt file empty?

Kindly assist. I am working on a script that will perform a telnet test to a specific ip address on a specific TCP port and below is my script.
#! /bin/sh
nc -z -v -w5 192.168.88.55 3389 | tee results.txt
During execution, a "results.txt" file is created but it is empty. I want it to have the output of the script after execution.
I have managed to resolve it by making the below modifications to the script
#! /bin/sh
nc -z -v -w5 192.168.88.55 3389 2>&1 | tee results.txt
sleep 5
exit
It is now able to write the output to the results.txt file.
Thank you.

Search and kill process, and start new process on bash script

I need a script for running a new process every hour.
I created a bash script that is scheduled to run every hour through cron. It only works the first time but fails otherwise.
If run from shell, it works perfectly.
Here is the script:
#!/bin/sh
ps -ef | grep tcpdump | grep -v grep | awk '{print $2}' | xargs kill
sleep 2
echo "Lanzando tcpdump"
tcpdump -ni eth0 -s0 proto TCP and port 25 -w /root/srv108-$(date +%Y%m%d%H%M%S).smtp.pcap
cron
#hourly /root/analisis.sh > /dev/null 2>&1
Why is the cron job failing?
This is the answer the OP added to the question itself.
Correction of the script after the comments (it works fine)
#!/bin/bash
pkill -f tcpdump
/usr/sbin/tcpdump -ni eth0 -s0 proto TCP and port 25 -w /root/srv108-$(date +%Y%m%d%H%M%S).smtp.pcap
That is, I just needed to use the full path to tcpdump.
The failure may be related to the cron job never finishing - you are starting a new tcpdump in the foreground, which will run forever.
Try this simplified script:
#!/bin/bash
killall tcpdump
tcpdump -ni eth0 -s0 proto TCP and port 25 -w /root/srv108-$(date +%Y%m%d%H%M%S).smtp.pcap&

bash: checking host availability over tcp [duplicate]

I'm looking for a quick and simple method for properly testing if a given TCP port is open on a remote server, from inside a Shell script.
I've managed to do it with the telnet command, and it works fine when the port is opened, but it doesn't seem to timeout when it's not and just hangs there...
Here's a sample:
l_TELNET=`echo "quit" | telnet $SERVER $PORT | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
echo "Connection to $SERVER on port $PORT failed"
exit 1
else
echo "Connection to $SERVER on port $PORT succeeded"
exit 0
fi
I either need a better way, or a way to force telnet to timeout if it doesn't connect in under 8 seconds for example, and return something I can catch in Shell (return code, or string in stdout).
I know of the Perl method, which uses the IO::Socket::INET module and wrote a successful script that tests a port, but would rather like to avoid using Perl if possible.
Note: This is what my server is running (where I need to run this from)
SunOS 5.10 Generic_139556-08 i86pc i386 i86pc
As pointed by B. Rhodes, nc (netcat) will do the job. A more compact way to use it:
nc -z <host> <port>
That way nc will only check if the port is open, exiting with 0 on success, 1 on failure.
For a quick interactive check (with a 5 seconds timeout):
nc -z -v -w5 <host> <port>
It's easy enough to do with the -z and -w TIMEOUT options to nc, but not all systems have nc installed. If you have a recent enough version of bash, this will work:
# Connection successful:
$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/80'
$ echo $?
0
# Connection failure prior to the timeout
$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/sfsfdfdff.com/80'
bash: sfsfdfdff.com: Name or service not known
bash: /dev/tcp/sfsfdfdff.com/80: Invalid argument
$ echo $?
1
# Connection not established by the timeout
$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/81'
$ echo $?
124
What's happening here is that timeout will run the subcommand and kill it if it doesn't exit within the specified timeout (1 second in the above example). In this case bash is the subcommand and uses its special /dev/tcp handling to try and open a connection to the server and port specified. If bash can open the connection within the timeout, cat will just close it immediately (since it's reading from /dev/null) and exit with a status code of 0 which will propagate through bash and then timeout. If bash gets a connection failure prior to the specified timeout, then bash will exit with an exit code of 1 which timeout will also return. And if bash isn't able to establish a connection and the specified timeout expires, then timeout will kill bash and exit with a status of 124.
TOC:
Using bash and timeout
Command
Examples
Using nc
Command
RHEL 6 (nc-1.84)
Installation
Examples
RHEL 7 (nmap-ncat-6.40)
Installation
Examples
Remarks
Using bash and timeout:
Note that timeout should be present with RHEL 6+, or is alternatively found in GNU coreutils 8.22. On MacOS, install it using brew install coreutils and use it as gtimeout.
Command:
$ timeout $TIMEOUT_SECONDS bash -c "</dev/tcp/${HOST}/${PORT}"; echo $?
If parametrizing the host and port, be sure to specify them as ${HOST} and ${PORT} as is above. Do not specify them merely as $HOST and $PORT, i.e. without the braces; it won't work in this case.
Example:
Success:
$ timeout 2 bash -c "</dev/tcp/canyouseeme.org/80"; echo $?
0
Failure:
$ timeout 2 bash -c "</dev/tcp/canyouseeme.org/81"; echo $?
124
If you must preserve the exit status of bash,
$ timeout --preserve-status 2 bash -c "</dev/tcp/canyouseeme.org/81"; echo $?
143
Using nc:
Note that a backward incompatible version of nc gets installed on RHEL 7.
Command:
Note that the command below is unique in that it is identical for both RHEL 6 and 7. It's just the installation and output that are different.
$ nc -w $TIMEOUT_SECONDS -v $HOST $PORT </dev/null; echo $?
RHEL 6 (nc-1.84):
Installation:
$ sudo yum install nc
Examples:
Success:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Connection to canyouseeme.org 80 port [tcp/http] succeeded!
0
Failure:
$ nc -w 2 -v canyouseeme.org 81 </dev/null; echo $?
nc: connect to canyouseeme.org port 81 (tcp) timed out: Operation now in progress
1
If the hostname maps to multiple IPs, the above failing command will cycle through many or all of them. For example:
$ nc -w 2 -v microsoft.com 81 </dev/null; echo $?
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
1
RHEL 7 (nmap-ncat-6.40):
Installation:
$ sudo yum install nmap-ncat
Examples:
Success:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connected to 52.202.215.126:80.
Ncat: 0 bytes sent, 0 bytes received in 0.22 seconds.
0
Failure:
$ nc -w 2 -v canyouseeme.org 81 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connection timed out.
1
If the hostname maps to multiple IPs, the above failing command will cycle through many or all of them. For example:
$ nc -w 2 -v microsoft.com 81 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connection to 104.43.195.251 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 23.100.122.175 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 23.96.52.53 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 191.239.213.197 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection timed out.
1
Remarks:
The -v (--verbose) argument and the echo $? command are of course for illustration only.
With netcat you can check whether a port is open like this:
nc my.example.com 80 < /dev/null
The return value of nc will be success if the TCP port was opened, and failure (typically the return code 1) if it could not make the TCP connection.
Some versions of nc will hang when you try this, because they do not close the sending half of their socket even after receiving the end-of-file from /dev/null. On my own Ubuntu laptop (18.04), the netcat-openbsd version of netcat that I have installed offers a workaround: the -N option is necessary to get an immediate result:
nc -N my.example.com 80 < /dev/null
In Bash using pseudo-device files for TCP/UDP connections is straight forward. Here is the script:
#!/usr/bin/env bash
SERVER=example.com
PORT=80
</dev/tcp/$SERVER/$PORT
if [ "$?" -ne 0 ]; then
echo "Connection to $SERVER on port $PORT failed"
exit 1
else
echo "Connection to $SERVER on port $PORT succeeded"
exit 0
fi
Testing:
$ ./test.sh
Connection to example.com on port 80 succeeded
Here is one-liner (Bash syntax):
</dev/tcp/localhost/11211 && echo Port open. || echo Port closed.
Note that some servers can be firewall protected from SYN flood attacks, so you may experience a TCP connection timeout (~75secs). To workaround the timeout issue, try:
timeout 1 bash -c "</dev/tcp/stackoverflow.com/81" && echo Port open. || echo Port closed.
See: How to decrease TCP connect() system call timeout?
I needed a more flexible solution for working on multiple git repositories so I wrote the following sh code based on 1 and 2. You can use your server address instead of gitlab.com and your port in replace of 22.
SERVER=gitlab.com
PORT=22
nc -z -v -w5 $SERVER $PORT
result1=$?
#Do whatever you want
if [ "$result1" != 0 ]; then
echo 'port 22 is closed'
else
echo 'port 22 is open'
fi
check ports using bash
Example
$ ./test_port_bash.sh 192.168.7.7 22
the port 22 is open
Code
HOST=$1
PORT=$2
exec 3> /dev/tcp/${HOST}/${PORT}
if [ $? -eq 0 ];then echo "the port $2 is open";else echo "the port $2 is closed";fi
If you're using ksh or bash they both support IO redirection to/from a socket using the /dev/tcp/IP/PORT construct. In this Korn shell example I am redirecting no-op's (:) std-in from a socket:
W$ python -m SimpleHTTPServer &
[1] 16833
Serving HTTP on 0.0.0.0 port 8000 ...
W$ : </dev/tcp/127.0.0.1/8000
The shell prints an error if the socket is not open:
W$ : </dev/tcp/127.0.0.1/8001
ksh: /dev/tcp/127.0.0.1/8001: cannot open [Connection refused]
You can therefore use this as the test in an if condition:
SERVER=127.0.0.1 PORT=8000
if (: < /dev/tcp/$SERVER/$PORT) 2>/dev/null
then
print succeeded
else
print failed
fi
The no-op is in a subshell so I can throw std-err away if the std-in redirection fails.
I often use /dev/tcp for checking the availability of a resource over HTTP:
W$ print arghhh > grr.html
W$ python -m SimpleHTTPServer &
[1] 16863
Serving HTTP on 0.0.0.0 port 8000 ...
W$ (print -u9 'GET /grr.html HTTP/1.0\n';cat <&9) 9<>/dev/tcp/127.0.0.1/8000
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/2.6.1
Date: Thu, 14 Feb 2013 12:56:29 GMT
Content-type: text/html
Content-Length: 7
Last-Modified: Thu, 14 Feb 2013 12:55:44 GMT
arghhh
W$
This one-liner opens file descriptor 9 for reading from and writing to the socket, prints the HTTP GET to the socket and uses cat to read from the socket.
While an old question, I've just dealt with a variant of it, but none of the solutions here were applicable, so I found another, and am adding it for posterity. Yes, I know the OP said they were aware of this option and it didn't suit them, but for anyone following afterwards it might prove useful.
In my case, I want to test for the availability of a local apt-cacher-ng service from a docker build. That means absolutely nothing can be installed prior to the test. No nc, nmap, expect, telnet or python. perl however is present, along with the core libraries, so I used this:
perl -MIO::Socket::INET -e 'exit(! defined( IO::Socket::INET->new("172.17.42.1:3142")))'
In some cases where tools like curl, telnet, nc o nmap are unavailable you still have a chance with wget
if [[ $(wget -q -t 1 --spider --dns-timeout 3 --connect-timeout 10 host:port; echo $?) -eq 0 ]]; then echo "OK"; else echo "FAIL"; fi
If you want to use nc but don't have a version that support -z, try using --send-only:
nc --send-only <IP> <PORT> </dev/null
and with timeout:
nc -w 1 --send-only <IP> <PORT> </dev/null
and without DNS lookup if it's an IP:
nc -n -w 1 --send-only <IP> <PORT> </dev/null
It returns the codes as the -z based on if it can connect or not.
Building on the most highly voted answer, here is a function to wait for two ports to be open, with a timeout as well. Note the two ports that mus be open, 8890 and 1111, as well as the max_attempts (1 per second).
function wait_for_server_to_boot()
{
echo "Waiting for server to boot up..."
attempts=0
max_attempts=30
while ( nc 127.0.0.1 8890 < /dev/null || nc 127.0.0.1 1111 < /dev/null ) && [[ $attempts < $max_attempts ]] ; do
attempts=$((attempts+1))
sleep 1;
echo "waiting... (${attempts}/${max_attempts})"
done
}
I needed short script which was run in cron and hasn't output. I solve my trouble using nmap
open=`nmap -p $PORT $SERVER | grep "$PORT" | grep open`
if [ -z "$open" ]; then
echo "Connection to $SERVER on port $PORT failed"
exit 1
else
echo "Connection to $SERVER on port $PORT succeeded"
exit 0
fi
To run it You should install nmap because it is not default installed package.
I'm guessing that it's too late for an answer, and this might not be a good one, but here you go...
What about putting it inside of a while loop with a timer on it of some sort. I'm more of a Perl guy than Solaris, but depending on the shell you're using, you should be able to do something like:
TIME = 'date +%s' + 15
while TIME != `date +%s'
do whatever
And then just add a flag in the while loop, so that if it times out before completing, you can cite the timeout as reason for failure.
I suspect that the telnet has a timeout switch as well, but just off the top of my head, I think the above will work.
This uses telnet behind the scenes, and seems to work fine on mac/linux. It doesn't use netcat because of the differences between the versions on linux/mac, and this works with a default mac install.
Example:
$ is_port_open.sh 80 google.com
OPEN
$ is_port_open.sh 8080 google.com
CLOSED
is_port_open.sh
PORT=$1
HOST=$2
TIMEOUT_IN_SEC=${3:-1}
VALUE_IF_OPEN=${4:-"OPEN"}
VALUE_IF_CLOSED=${5:-"CLOSED"}
function eztern()
{
if [ "$1" == "$2" ]
then
echo $3
else
echo $4
fi
}
# cross platform timeout util to support mac mostly
# https://gist.github.com/jaytaylor/6527607
function eztimeout() { perl -e 'alarm shift; exec #ARGV' "$#"; }
function testPort()
{
OPTS=""
# find out if port is open using telnet
# by saving telnet output to temporary file
# and looking for "Escape character" response
# from telnet
FILENAME="/tmp/__port_check_$(uuidgen)"
RESULT=$(eztimeout $TIMEOUT_IN_SEC telnet $HOST $PORT &> $FILENAME; cat $FILENAME | tail -n1)
rm -f $FILENAME;
SUCCESS=$(eztern "$RESULT" "Escape character is '^]'." "$VALUE_IF_OPEN" "$VALUE_IF_CLOSED")
echo "$SUCCESS"
}
testPort
My machine does not support nc or /dev/tcp/$hostname/$port but timeout, so I came back to telnet as follows:
if echo "quit" | timeout 2 telnet $SERVER $PORT 2>&1 | grep -q 'Connected to'; then
echo "Connection to $SERVER on port $PORT succeeded"
exit 0
else
echo "Connection to $SERVER on port $PORT failed"
exit 1
fi
nmap-ncat to test for local port that is not already in use
availabletobindon() {
port="$1"
nc -w 2 -i 1 localhost "$port" 2>&1 | grep -v -q 'Idle timeout expired'
return "$?"
}

BASH - how can i make the log file accessable via TCP port when-ever requires?

How can i have a logs on TCP port available, so that it can be remotely tested by someone else ? for example:
MAINSERVER> tail -f /etc/httpd/logs/access_log | grep -e fruit_Python -e fruit_BASH -e fruit_C | .... TCP 9999 ... make this available ....??
NOW, from my Laptop remotely i want to do this temporary:
MYLAPTOP> tail -f http://MAINSERVER:9999 | grep -e grab_BASH
Any idea please?
You can use netcat (nc) to do this:
Server side (listen for connection):
tail -f /foo/bar |nc -l -k -p 9999
-l listen
-k listen for another connection after current completed
Client side (connecting):
nc MAINSERVER 9999 | grep whatever_you_like
You can use bash as well to connect to /dev/tcp/host/port but sometimes it's not suported (compiled in to Bash) for security reasons.
Client:
grep whatever_you_like < /dev/tcp/MAINSERVER/9999

How can I write a Linux bash script that tells me which computers are ON in my LAN?

How can I write a Linux Bash script that tells me which computers are ON in my LAN?
It would help if I could give it a range of IP addresses as input.
I would suggest using nmap's ping-scan flag,
$ nmap -sn 192.168.1.60-70
Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2009-04-09 20:13 BST
Host machine1.home (192.168.1.64) appears to be up.
Host machine2.home (192.168.1.65) appears to be up.
Nmap finished: 11 IP addresses (2 hosts up) scanned in 0.235 seconds
That said, if you want to write it yourself (which is fair enough), this is how I would do it:
for ip in 192.168.1.{1..10}; do ping -c 1 -t 1 $ip > /dev/null && echo "${ip} is up"; done
..and an explanation of each bit of the above command:
Generating list of IP addresses
You can use the {1..10} syntax to generate a list of numbers, for example..
$ echo {1..10}
1 2 3 4 5 6 7 8 9 10
(it's also useful for things like mkdir {dir1,dir2}/{sub1,sub2} - which makes dir1 and dir2, each containing sub1 and sub2)
So, to generate a list of IP's, we'd do something like
$ echo 192.168.1.{1..10}
192.168.1.1 192.168.1.2 [...] 192.168.1.10
Loops
To loop over something in bash, you use for:
$ for thingy in 1 2 3; do echo $thingy; done
1
2
3
Pinging
Next, to ping.. The ping command varies a bit with different operating-systems, different distributions/versions (I'm using OS X currently)
By default (again, on the OS X version of ping) it will ping until interrupted, which isn't going to work for this, so ping -c 1 will only try sending one packet, which should be enough to determine if a machine is up.
Another problem is the timeout value, which seems to be 11 seconds on this version of ping.. It's changed using the -t flag. One second should be enough to see if a machine on the local network is alive or not.
So, the ping command we'll use is..
$ ping -c 1 -t 1 192.168.1.1
PING 192.168.1.1 (192.168.1.1): 56 data bytes
--- 192.168.1.1 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
Checking ping result
Next, we need to know if the machine replied or not..
We can use the && operator to run a command if the first succeeds, for example:
$ echo && echo "It works"
It works
$ nonexistantcommand && echo "This should not echo"
-bash: nonexistantcommand: command not found
Good, so we can do..
ping -c 1 -t 1 192.168.1.1 && echo "192.168.1.1 is up!"
The other way would be to use the exit code from ping.. The ping command will exit with exit-code 0 (success) if it worked, and a non-zero code if it failed. In bash you get the last commands exit code with the variable $?
So, to check if the command worked, we'd do..
ping -c 1 -t 1 192.168.1.1;
if [ $? -eq 0 ]; then
echo "192.168.1.1 is up";
else
echo "ip is down";
fi
Hiding ping output
Last thing, we don't need to see the ping output, so we can redirect stdout to /dev/null with the > redirection, for example:
$ ping -c 1 -t 1 192.168.1.1 > /dev/null && echo "IP is up"
IP is up
And to redirect stderr (to discard the ping: sendto: Host is down messages), you use 2> - for example:
$ errorcausingcommand
-bash: errorcausingcommand: command not found
$ errorcausingcommand 2> /dev/null
$
The script
So, to combine all that..
for ip in 192.168.1.{1..10}; do # for loop and the {} operator
ping -c 1 -t 1 192.168.1.1 > /dev/null 2> /dev/null # ping and discard output
if [ $? -eq 0 ]; then # check the exit code
echo "${ip} is up" # display the output
# you could send this to a log file by using the >>pinglog.txt redirect
else
echo "${ip} is down"
fi
done
Or, using the && method, in a one-liner:
for ip in 192.168.1.{1..10}; do ping -c 1 -t 1 $ip > /dev/null && echo "${ip} is up"; done
Problem
It's slow.. Each ping command takes about 1 second (since we set the -t timeout flag to 1 second). It can only run one ping command at a time.. The obvious way around this is to use threads, so you can run concurrent commands, but that's beyond what you should use bash for..
"Python threads - a first example" explains how to use the Python threading module to write a multi-threaded ping'er.. Although at that point, I would once again suggest using nmap -sn..
In the real world, you could use nmap to get what you want.
nmap -sn 10.1.1.1-255
This will ping all the addresses in the range 10.1.1.1 to 10.1.1.255 and let you know which ones answer.
Of course, if you in fact want to do this as a bash exercise, you could run ping for each address and parse the output, but that's a whole other story.
Assuming my network is 10.10.0.0/24, if i run a ping on the broadcast address like
ping -b 10.10.0.255
I'll get an answer from all computers on this network that did not block their ICMP ping port.
64 bytes from 10.10.0.6: icmp_seq=1 ttl=64 time=0.000 ms
64 bytes from 10.10.0.12: icmp_seq=1 ttl=64 time=0.000 ms
64 bytes from 10.10.0.71: icmp_seq=1 ttl=255 time=0.000 ms
So you just have to extract the 4th column, with awk for example:
ping -b 10.10.0.255 | grep 'bytes from' | awk '{ print $4 }'
10.10.0.12:
10.10.0.6:
10.10.0.71:
10.10.0.95:
Well, you will get duplicate, and you may need to remove the ':'.
EDIT from comments :
the -c option limits the number of pings
since the script will end, we can also limit ourself on unique IPs
ping -c 5 -b 10.10.0.255 | grep 'bytes from' | awk '{ print $4 }' | sort | uniq
There is also fping:
fping -g 192.168.1.0/24
or:
fping -g 192.168.1.0 192.168.1.255
or show only hosts that are alive:
fping -ag 192.168.1.0/24
It pings hosts in parallel so the scan is very fast. I don't know a distribution which includes fping in its default installation but in most distributions you can get it through the package manager.
Also using the "ping the broadcast address" method pointed out by chburd, this pipe should do the trick for you:
ping -c 5 -b 10.11.255.255 | sed -n 's/.* \([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\).*/\1/p' | sort | uniq
Of course, you'd have to change the broadcast address to that of your network.
Just for fun, here's an alternate
#!/bin/bash
nmap -sP 192.168.1.0/24 > /dev/null 2>&1 && arp -an | grep -v incomplete | awk '{print$2}' | sed -e s,\(,, | sed -e s,\),,
If you're limiting yourself to only having the last octet changing, this script should do it. It should be fairly obvious how to extend it from one to multiple octets.
#! /bin/bash
BASE=$1
START=$2
END=$3
counter=$START
while [ $counter -le $END ]
do
ip=$BASE.$counter
if ping -qc 2 $ip
then
echo "$ip responds"
fi
counter=$(( $counter + 1 ))
done
ip neighbor
arp -a
Arpwatch
As other posters pointed out, nmap is the way to go, but here's how to do the equivalent of a ping scan in bash. I wouldn't use the broadcast ping, as a lot of systems are configured not to respond to broadcast ICMP nowadays.
for i in $(seq 1 254); do
host="192.168.100.$i"
ping -c 1 -W 1 $host &> /dev/null
echo -n "Host $host is "
test $? -eq 0 && echo "up" || echo "down"
done
#!/bin/bash
#Get the ip address for the range
ip=$(/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}' | cut -d"." -f1,2,3)
# ping test and list the hosts and echo the info
for range in $ip ; do [ $? -eq 0 ] && ping -c 1 -w 1 $range > /dev/null 2> /dev/null && echo "Node $range is up"
done
Although an old question, it still seems to be important (at least important enough for me to deal with this). My script relies on nmap too, so nothing special here except that ou can define which interface you want to scan and the IP Range is created automagically (at least kind of).
This is what I came up with
#!/bin/bash
#Script for scanning the (local) network for other computers
command -v nmap >/dev/null 2>&1 || { echo "I require nmap but it's not installed. Aborting." >&2; exit 1; }
if [ -n ""$#"" ]; then
ip=$(/sbin/ifconfig $1 | grep 'inet ' | awk '{ print $2}' | cut -d"." -f1,2,3 )
nmap -sP $ip.1-255
else
echo -e "\nThis is a script for scanning the (local) network for other computers.\n"
echo "Enter Interface as parameter like this:"
echo -e "\t./scannetwork.sh $(ifconfig -lu | awk '{print $2}')\n"
echo "Possible interfaces which are up are: "
for i in $(ifconfig -lu)
do
echo -e "\033[32m \t $i \033[39;49m"
done
echo "Interfaces which could be used but are down at the moment: "
for i in $(ifconfig -ld)
do
echo -e "\033[31m \t $i \033[39;49m"
done
echo
fi
One remark: This script is created on OSX, so there might be some changes to linux environments.
If you want to provide a list of hosts it can be done with nmap, grep and awk.
Install nmap:
$ sudo apt-get install nmap
Create file hostcheck.sh like this:
hostcheck.sh
#!/bin/bash
nmap -sP -iL hostlist -oG pingscan > /dev/null
grep Up pingscan | awk '{print $2}' > uplist
grep Down pingscan | awk '{print $2}' > downlist
-sP: Ping Scan - go no further than determining if host is online
-iL : Input from list of hosts/networks
-oG : Output scan results in Grepable format, to the given filename.
/dev/null : Discards output
Change the access permission:
$ chmod 775 hostcheck.sh
Create file hostlist with the list of hosts to be checked (hostname or IP):
hostlist (Example)
192.168.1.1-5
192.168.1.101
192.168.1.123
192.168.1.1-5 is a range of IPs
Run the script:
./hostcheck.sh hostfile
Will be generated files pingscan with all the information, uplist with the hosts online (Up) and downlist with the hosts offline (Down).
uplist (Example)
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.101
downlist (Example)
192.168.1.5
192.168.1.123
Some machines don't answer pings (e.g. firewalls).
If you only want the local network you can use this command:
(for n in $(seq 1 254);do sudo arping -c1 10.0.0.$n & done ; wait) | grep reply | grep --color -E '([0-9]+\.){3}[0-9]+'
Explanations part !
arping is a command that sends ARP requests. It is present on most of linux.
Example:
sudo arping -c1 10.0.0.14
the sudo is not necessary if you are root ofc.
10.0.0.14 : the ip you want to test
-c1 : send only one request.
&: the 'I-don't-want-to-wait' character
This is a really useful character that give you the possibility to launch a command in a sub-process without waiting him to finish (like a thread)
the for loop is here to arping all 255 ip addresses. It uses the seq command to list all numbers.
wait: after we launched our requests we want to see if there are some replies. To do so we just put wait after the loop.
wait looks like the function join() in other languages.
(): parenthesis are here to interpret all outputs as text so we can give it to grep
grep: we only want to see replies. the second grep is just here to highlight IPs.
hth
Edit 20150417: Maxi Update !
The bad part of my solution is that it print all results at the end. It is because grep have a big enough buffer to put some lines inside.
the solution is to add --line-buffered to the first grep.
like so:
(for n in $(seq 1 254);do sudo arping -c1 10.0.0.$n & done ; wait) | grep --line-buffered reply | grep --color -E '([0-9]+\.){3}[0-9]+'
#!/bin/bash
for ((n=0 ; n < 30 ; n+=1))
do
ip=10.1.1.$n
if ping -c 1 -w 1 $ip > /dev/null 2> /dev/null >> /etc/logping.txt; then
echo "${ip} is up" # output up
# sintax >> /etc/logping.txt log with .txt format
else
echo "${ip} is down" # output down
fi
done
The following (evil) code runs more than TWICE as fast as the nmap method
for i in {1..254} ;do (ping 192.168.1.$i -c 1 -w 5 >/dev/null && echo "192.168.1.$i" &) ;done
takes around 10 seconds, where the standard nmap
nmap -sP 192.168.1.1-254
takes 25 seconds...
Well, this is part of a script of mine.
ship.sh 🚢 A simple, handy network addressing 🔎 multitool with plenty of features 🌊
Pings network, displays online hosts on that network with their local IP and MAC address
It doesn't require any edit. Needs root permission to run.
GOOGLE_DNS="8.8.8.8"
ONLINE_INTERFACE=$(ip route get "${GOOGLE_DNS}" | awk -F 'dev ' 'NR == 1 {split($2, a, " "); print a[1]}')
NETWORK_IP=$(ip route | awk "/${ONLINE_INTERFACE}/ && /src/ {print \$1}" | cut --fields=1 --delimiter="/")
NETWORK_IP_CIDR=$(ip route | awk "/${ONLINE_INTERFACE}/ && /src/ {print \$1}")
FILTERED_IP=$(echo "${NETWORK_IP}" | awk 'BEGIN{FS=OFS="."} NF--')
ip -statistics neighbour flush all &>/dev/null
echo -ne "Pinging ${NETWORK_IP_CIDR}, please wait ..."
for HOST in {1..254}; do
ping "${FILTERED_IP}.${HOST}" -c 1 -w 10 &>/dev/null &
done
for JOB in $(jobs -p); do wait "${JOB}"; done
ip neighbour | \
awk 'tolower($0) ~ /reachable|stale|delay|probe/{printf ("%5s\t%s\n", $1, $5)}' | \
sort --version-sort --unique

Resources