Score:3

Warn when new WiFi devices on LAN network

us flag

I connect through Ethernet. But almost all other devices use WiFi. Is it possible to get a list of devices connected to my router in Ubuntu 22.04? It would be great if there is some method to get an alert as well when a new device is connected to the WiFi network.

Edit 1: Interestingly arp -a is giving more details, but no device information. A few internal IPs and MAC IDs.

Edit 2: I think more details are available through arp -a because I ran the nmap command shared by @Raffa.

Edit 3: There is already a tool called Nutty that can do this, but last release was 2019.

screenshot

in flag
This is going to depend greatly on how the router is configured. Does every device on the network use the same subnet?
user227495 avatar
us flag
Yes, I believe so.
user227495 avatar
us flag
@matigo , any help would be great. thanks
Pilot6 avatar
cn flag
This question doesn't seem to be Ubuntu related. As it was mentioned before, it depends on your router. It is possible e.g. with OpenWrt.
user227495 avatar
us flag
I see that there is something called `arpwatch` that can be installed through `sudo apt install arpwatch`.
Pilot6 avatar
cn flag
It is not related to wireless directly. You can monitor devices in your network no matter they are wired or wireless.
user227495 avatar
us flag
That is something I would like to have. I use `arp -a` on Windows 10 and it lists devices. Was looking for something like that in Ubuntu.
Raffa avatar
jp flag
Arp tables are available on most network enabled OSes including Ubuntu and you can query them easily … The important thing in your use case is to know that newly connected devices to the network are not readily instantly added to these arp tables … You need to communicate with them e.g. by pinging them for the table to be updated … Please see https://askubuntu.com/a/1450800
user227495 avatar
us flag
thanks @Raffa , In Windows Avast detects any new devices connected. I am trying to mimic the same. Will check the link, thanks.
user227495 avatar
us flag
@Raffa , I tried ping, arp and nmap. But couldn't find any data that I can use. Thanks.
Raffa avatar
jp flag
“I use a software in Windows which scans 0-255 and reports the device name. ” … How do you connect on Windows Wifi or Ethernet?
user227495 avatar
us flag
@Raffa , I use ethernet mostly. I am the only ethernet user. Other devices are on WiFi. This is the tool I use on Windows 10 : https://www.nirsoft.net/utils/wireless_network_watcher.html
starkus avatar
de flag
Tried `sudo arp-scan -l`?
starkus avatar
de flag
There is a package called `arpalert` which lets you receive an alert via email. The package contains a script example for calling zenity and give you a desktop notification if configured correct. https://www.arpalert.org/arpalert.html http://ubuntuforums.org/showthread.php?t=464883 And there's also a tool on GitHub https://github.com/illethrias/arpalert-howto to let you manage the sendmail configuration.
user227495 avatar
us flag
Thanks, will check and update.
user227495 avatar
us flag
@starkus `arp-scan` didn't give any useful info. Tried `arpalert`, followed instructions, added email etc, but is saying `sudo cp ./arpalert-howto/arpwatch_mail.py /usr/local/bin/`
Score:4
jp flag

I hope this helps or at least educates :-) ... It should be run as a bash script ... It uses notify-send for notifications:

#!/bin/bash

# Start the main loop
while true; do
  # Change "10.0.0.0/24" to your network address and your netmask e.g. "192.168.1.0/24"
  # Use "nmap" to get discoverable devices on the network and parse the output to get only those with resolvable hostnames into an arry "a"
  readarray -t a < <(nmap -sn 10.0.0.0/24 | awk '/Nmap scan report for/ && NF == 6 {print $((NF-1)), $NF}')
  # To get even devices with un-resolvable/empty/unset hostnames, comment the above line and uncomment the below line
  # readarray -t a < <(nmap -sn 10.0.0.0/24 | awk '/Nmap scan report for/ {print $5, $6}')
  # Loop over items in array "a"
  for item in "${a[@]}"; do
    # Get device's MAC address from the already updated arp table
    ip=${item#*(}; ip=${ip%)*}; mac=$(arp -n "$ip" | awk '/.*:.*:.*:.*:.*:.*/{printf "%s", $3}')
    # Compare items to array "b" and send notification for recently connected devices.
    [[ ! "${b[*]}" =~ "${item}" ]] && notify-send -i network-wired "Connected device:" "Hostname (IP) MAC:\n ${item} ${mac}"
    done
  # Loop over items in array "b" ... Notice this array is not initially declared for simplicity and shortness.
  for item in "${b[@]}"; do
    # Compare items to array "a" and send notification for recently disconnected devices.
    [[ ! "${a[*]}" =~ "${item}" ]] && notify-send -i network-error "Disconnected device:" "Hostname (IP):\n ${item}"
    done
    # Copy array "a" to array "b"
    b=("${a[@]}")
    # Wait N seconds before continuing the main loop
    sleep 60
  done

A terminal display version(with extra features) of the above script would be like so:

#!/bin/bash

# This script depends on these commands/utilities (mktemp, nmap, awk, arp, column, sort, nl and notify-send)

nts="1" # Set this to "1" to enable sending desktop (notify-send) notifications on new or disconnected devices or to "0" to disable it.
network="10.0.0.0/24" # Change "10.0.0.0/24" to your network address and your netmask e.g. "192.168.1.0/24"
si="60" # Scan interval in seconds. Lower is NOT always better (between "30" and "300" is recommended for "/24" subnet). Devices are discovered at this interval and considered disconnected 3X this interval. 
logfile="$HOME/NetworkDevicesMonitor.log" # Pathe to the log file. It will be created if it dosen't exist.
# Path to Nmap MAC prefixes file on your system (It comes with nmap when installed). This is the default path and should work fine:
pdb="/usr/share/nmap/nmap-mac-prefixes"


### Don't edit below this line unless you know what you're doing ###
# Create a temporary file with "mktemp"
tmpfile=$(mktemp)
# Start the main loop
while true; do
  # Clear the temporary file
  > "$tmpfile"
  # Use "nmap" to get discoverable devices on the network and parse the output into an arry "a"
  readarray -t a < <(nmap -sn "$network" | \
  awk '/Nmap scan report for/ && (NF == 6) {print $5, $6} /Nmap scan report for/ && (NF == 5) {print "Unavailable", "("$5")"}')
  # Loop over items in array "a"
  for item in "${a[@]}"; do
    # Get device's MAC address from the already updated arp table
    ip=${item#*(}; ip=${ip%)*}; mac=$(arp -n "$ip" 2> /dev/null | awk '/.*:.*:.*:.*:.*:.*/{printf "%s", $3}'); [[ -z "$mac" ]] && mac="Unknown"
    # Lookup vendor
    if [[ "$mac" == "Unknown" ]]; then
      vendor="$mac"
    else
      awmac="${mac//:}"
      awmac="${awmac:0:6}"
      vendor=$(awk -v mac="${awmac}" 'BEGIN{IGNORECASE=1} $1 == mac {for(i=2;i<NF;++i) printf "%s_", $i; printf "%s", $NF }' "$pdb")
    fi
    [[ -z "$vendor" ]] && vendor="Unavailable"
    # Compare items to array "b" and write new and connected devices to file (and send notifications if enabled).
    if [[ ! "${b[*]}" =~ "${item}" ]] && [[ ! "${c[*]}" =~ "${item}" ]] && [[ ! "${d[*]}" =~ "${item}" ]]; then
      echo -e "1 \U2191 New ${item} ${mac} ${vendor}" >> "$tmpfile"
      echo -e "[$(date)] \U2191 Connected: ${item} ${mac} ${vendor}" >> "$logfile"
      [[ "$nts" == 1 ]] && notify-send -u critical -i network-wired "New device:" "${item}\n${mac}\n${vendor}\n$(date)"
    else
      echo -e "3 \U2194 Connected ${item} ${mac} ${vendor}" >> "$tmpfile"
      fi
    done
  # Loop over items in array "d" ...
  for item in "${d[@]}"; do
    # Get device's MAC address from the already updated arp table
    ip=${item#*(}; ip=${ip%)*}; mac=$(arp -n "$ip" 2> /dev/null | awk '/.*:.*:.*:.*:.*:.*/{printf "%s", $3}'); [[ -z "$mac" ]] && mac="Unknown"
        # Lookup vendor
    if [[ "$mac" == "Unknown" ]]; then
      vendor="$mac"
    else
      awmac="${mac//:}"
      awmac="${awmac:0:6}"
      vendor=$(awk -v mac="${awmac}" 'BEGIN{IGNORECASE=1} $1 == mac {for(i=2;i<NF;++i) printf "%s_", $i; printf "%s", $NF }' "$pdb")
    fi
    [[ -z "$vendor" ]] && vendor="Unavailable"
    # Compare items to array "a" and write disconnected devices to file (and send notifications if enabled).
    if [[ ! "${a[*]}" =~ "${item}" ]] && [[ ! "${b[*]}" =~ "${item}" ]] && [[ ! "${c[*]}" =~ "${item}" ]]; then
      echo -e "2 \U2193 Disconnected ${item} ${mac} ${vendor}" >> "$tmpfile"
      echo -e "[$(date)] \U2193 Disconnected: ${item} ${mac} ${vendor}" >> "$logfile"
      [[ "$nts" == 1 ]] && notify-send -u critical -i network-error "Disconnected device:" "${item}\n${mac}\n${vendor}\n$(date)"
      fi
    done
    # Copy to redundant arrays "c" and "d" used for more reliable status and notification
    d=("${c[@]}")
    c=("${b[@]}")
    # Copy array "a" to array "b"
    b=("${a[@]}")
    # Clear the terminal
    clear
    # Format and write output
    sort -k1 "$tmpfile" | nl | column -t -N '#,s,*,Status:,Hostname:,(IP):,MAC:,Vendor:' -H 's'
    # Wait N seconds before continuing the main loop
    sleep "$si"
  done

Notices:

  • There are alternative scripting methods some of which require the use of sudo for higher privileges e.g. nmap itself will print MAC addresses if it is run as root … I however avoided those methods at all costs and used safe workarounds that don’t require being run as root … It’s also worth noting that the example application linked in your question and others depend on and use nmap in the background … So, when all roads lead to Rome as such, I usually advocate the shortest, safest and straightest one :-).

  • Arp(Address Resolution Protocol) tables are implemented and available on most network enabled OSes including Ubuntu(cat /proc/net/arp will give you an idea) and you can query them easily and quickly … But, the important thing to know in your use case is that newly connected devices to the network are not necessarily readily/instantly added to these arp tables … Your host needs to communicate with these devices and exchange arp packets (e.g. by sending arp requests or echo requests to them) for its arp table to be updated accordingly ... Helpful information here as well.

  • Nowadays and by default, devices change their MAC addresses to random ones and/or hide their host/device names when they connect to different networks ... It's considered a security/privacy feature and it can usually be disabled/enabled under network connections settings.

user227495 avatar
us flag
Works!! Thanks. If I may, there is no device info shown. It is mostly the IP. Any chance we can get the MAC ID and Device Name so that we can recognise it and block it. I know you already help, sorry if asking too much.
user227495 avatar
us flag
Hi, Thanks. More than I could have asked for. The system won't allow me to share the bounty until 4 hours. Will add it once I am allowed. Really appreciate your help. :)
Raffa avatar
jp flag
@user227495 Those two characters at the end of your comment are my bounty (*the smile `:)`*) … Meanwhile if I may suggest you keep the bounty on until the bounty period ends to keep this post in the highlighted bounty tap and get more views … You and I both will benefit from peer reviews and critique … Plus somebody might come up with other ideas/alternatives to enrich the subject :-)
user227495 avatar
us flag
I have the first one saved. Please feel free to go ahead with the edit. I will try the second one in a few hours. Thanks for all the effort :)
user227495 avatar
us flag
I tested briefly. It works nice for me. The only trouble I am facing is the notification has a very small space. Sometimes half the message is hidden. Would it be possible to have a log for the same which we can access? Like in the beginning, list devices, then log change in activity. Not sure how hard it is. Thanks.
user227495 avatar
us flag
I get a lot of notifications. All WiFi devices are always connected. They are never out of the WiFi range. I got 8 notifications in 20 minutes. It is ok with me, just wanted to say that I was expecting lesser notifications as they are always connected. Thanks.
user227495 avatar
us flag
Hi @Raffa , it works nice. To check I turned off the WiFi on my phone and turned it back ON after 5 minutes, I got no notification. The device is listed as connected. Is it expected behaviour? Does it respond only to new devices? I could see the device name for my laptop, but no other device though. Thanks :)
Raffa avatar
jp flag
@user227495 I tested the second script and devices disconnection was not detected indeed :-) ... There was a small typo in arrays' names that caused that ... I corrected it now ... Please se the edit ... It's fixed now ... Please let me know if there is anything else with the second script needs fixing ... Meanwhile I will cleanup comments under the answer that have been already included in the answer.
user227495 avatar
us flag
Thanks, the notification text is still in a single line.
Raffa avatar
jp flag
@user227495 Fixed that ... Desktop notifications should be displayed in full and multi-line now ... Please check and let me know.
user227495 avatar
us flag
All good, thanks :)
Score:2
cg flag

This question is not directly Ubuntu related and may be a better fit elsewhere. It's quite broad and more focus would help get a better answer.

If you're running an OpenWrt router, you should be able to put together a script to do this. It could be run on the router to regularly query connected WiFi devices as a cron job: Listing devices connected in hotspot through terminal

I suspect, as you haven't mentioned your router OS, that you're running off the shelf firmware. In that case, you could scrape your router's web interface regularly to obtain a list of connected devices (if this information is available somewhere on the router's web interface). You could use requests or selenium, depending on how your router's webif is designed. This is likely to be quite brittle.

Another approach might be to regularly run nmap to scan your network and set up an alert for when a new address is detected on the network. This isn't limited to WiFi connections and would also flag if a new wired device connected.

All have pros and cons. It depends on what router you have. I personally would get an OpenWrt router then write a script to monitor new WiFI devices.

Score:0
mc flag

If your router doesn't have it's own Linux based router software,(and you don't have Wine installed(a windows emulation software,)) then here is the latest from Google search. https://openwrt.org/ WRTproject is for developers--- EHH!! nope it does:Users can replace the router firmware that comes with their stock routers and customize their devices.(and it is completely opensource) https://vyos.io/ https://mikrotik.com/software (top two other Linux based router software(may need make(hint your repository files ending end in DEV for supporting libraries and OTM dependencies.)))

user227495 avatar
us flag
It works fine while using Avast on Windows. Trying to find an equivalent. Thanks
user227495 avatar
us flag
There are also many software ( on Windows ) that can scan, find and warn of new devices while using the same router.
Score:0
gb flag

Install NetDiscover with:

sudo apt-get install netdiscover

Then assuming You router's IP is 192.168.0.1,
You can scan for devices connected to it by running:

netdiscover -r 192.168.0.1/24 # where -r is a flag for RANGE
or
netdiscover -r 192.168.0.1-192.168.0.254 # same as 192.168.0.1-254
or
netdiscover # with no argument, so as to auto discover.

Score:0
gb flag

I'm new in Linux , but i have idea

  1. Install telnet client
  2. Open telnet connection into your router
  3. Find and save number of connected wifi device into text file
  4. Create bash script and loop to save current connected wifi device into another text file
  5. use script to compare two text files if there are difference then show popup

Hope this help

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.