Files
nscan/main.go
T
mikeandClaude Opus 5.5 c91dbe9f7d Add self-update, release 1.0.2
nscan update installs the newest release from git.micw.org, nscan
update -c only checks; --update and --check-update work as well. The
download lands next to the running binary, is started once with
--version and only then replaces it.

Once a day an ordinary run asks in the background and mentions a newer
release in the title bar and on stderr, only on a terminal and not with
NSCAN_NO_UPDATE_CHECK set. selfupdate.go is goca's copyable template.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 16:25:36 +01:00

565 lines
15 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Command nscan is a terminal network scanner: it lists the devices on the
// local network with name, IP, MAC, vendor and Bonjour services, and offers
// ping, port scan, Wake-on-LAN, device tracking and a change history.
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"net"
"net/netip"
"os"
"os/signal"
"path/filepath"
"strings"
"text/tabwriter"
"time"
"nscan/internal/export"
"nscan/internal/oui"
"nscan/internal/scanner"
"nscan/internal/store"
"nscan/internal/tui"
)
const usage = `Usage:
nscan [options] interactive interface (default)
nscan scan [options] scan once and print a table
nscan ping [-c N] <host> ping (ICMP, falls back to TCP without permission)
nscan ports [-p top] <host> TCP port scan
nscan wol <mac|name> send a Wake-on-LAN magic packet
nscan interfaces list network interfaces
nscan oui update download the vendor database from the IEEE
nscan oui import <file> import oui.csv/oui.txt manually
nscan oui lookup <mac> show the vendor of a MAC address
nscan update [-c] install the newest release (-c: only check)
nscan version print the version
Options for the interface and "scan":
-i <iface> interface (default: the one with the default route)
-r <range> address range, e.g. 192.168.1.0/24, 10.0.0.10-50
-wait <dur> how long to wait for late replies (default 1.5s)
-no-names skip name resolution (mDNS, NetBIOS, DNS)
-no-bonjour skip Bonjour service discovery
-interval <dur> auto-scan interval of the interface, 0 = off (default 1m)
-export-dir <d> export directory (key e, default: current directory)
-json / -csv output format of "scan"
`
func main() {
if err := run(os.Args[1:]); err != nil {
if !errors.Is(err, flag.ErrHelp) {
fmt.Fprintln(os.Stderr, "nscan:", err)
}
os.Exit(1)
}
}
func printUsage(w io.Writer) {
fmt.Fprintf(w, "nscan %s – network scanner for the terminal\n\n%s", Version, usage)
}
func run(args []string) error {
cmd := ""
if len(args) > 0 {
switch args[0] {
case "-v", "-version", "--version":
args[0] = "version"
case "-h", "-help", "--help":
args[0] = "help"
case "-update", "--update":
args[0] = "update"
case "-check-update", "--check-update":
args = []string{"update", "-c"}
case updateRefreshFlag: // the background look, deliberately not in the help
selfUpdate.refresh()
return nil
}
}
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
cmd, args = args[0], args[1:]
}
var err error
switch cmd {
case "", "ui":
return runUI(args)
case "help":
printUsage(os.Stdout)
return nil
case "version":
fmt.Println("nscan " + Version)
return nil
case "update":
return runUpdate(args)
case "scan":
err = runScan(args)
case "ping":
err = runPing(args)
case "ports":
err = runPorts(args)
case "wol":
err = runWOL(args)
case "interfaces", "ifaces":
err = runInterfaces()
case "oui":
err = runOUI(args)
default:
return fmt.Errorf("unknown command %q (see nscan help)", cmd)
}
// Costs nothing: the hint comes from a note in the cache, and the asking
// happens at most once a day, in the background.
if hint := selfUpdate.daily(); hint != "" {
fmt.Fprintln(os.Stderr, hint)
}
return err
}
func runUpdate(args []string) error {
fl := newFlags("update")
checkOnly := fl.Bool("c", false, "only check")
if err := fl.Parse(args); err != nil {
return err
}
if *checkOnly {
return selfUpdate.check(os.Stdout)
}
return selfUpdate.install(os.Stdout)
}
func newFlags(name string) *flag.FlagSet {
fl := flag.NewFlagSet(name, flag.ContinueOnError)
fl.Usage = func() { printUsage(os.Stderr) }
return fl
}
type scanFlags struct {
iface, rng string
wait time.Duration
noNames bool
noBonjour bool
}
func (f *scanFlags) register(flags *flag.FlagSet) {
flags.StringVar(&f.iface, "i", "", "interface")
flags.StringVar(&f.rng, "r", "", "address range")
flags.DurationVar(&f.wait, "wait", 1500*time.Millisecond, "wait for late replies")
flags.BoolVar(&f.noNames, "no-names", false, "skip name resolution")
flags.BoolVar(&f.noBonjour, "no-bonjour", false, "skip Bonjour discovery")
}
// resolve detects the network and the addresses to scan.
func (f *scanFlags) resolve() (*scanner.Network, string, []netip.Addr, error) {
n, err := scanner.DetectNetwork(f.iface)
if err != nil {
return nil, "", nil, err
}
spec := f.rng
if spec == "" {
spec = n.DefaultRange().String()
}
targets, err := scanner.ParseRange(spec)
if err != nil {
return nil, "", nil, err
}
return n, spec, targets, nil
}
func openState() (*store.Store, *oui.DB, error) {
dir, err := store.Dir()
if err != nil {
return nil, nil, err
}
st, err := store.Open(dir)
if err != nil {
return nil, nil, fmt.Errorf("data in %s: %w", dir, err)
}
db, err := oui.Load(ouiPath(dir))
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, nil, err
}
return st, db, nil
}
func ouiPath(dir string) string { return filepath.Join(dir, "oui.tsv") }
func runUI(args []string) error {
fl := newFlags("nscan")
var sf scanFlags
sf.register(fl)
interval := fl.Duration("interval", time.Minute, "auto-scan interval")
exportDir := fl.String("export-dir", ".", "export directory")
if err := fl.Parse(args); err != nil {
return err
}
n, spec, targets, err := sf.resolve()
if err != nil {
return err
}
st, db, err := openState()
if err != nil {
return err
}
hint, newer := selfUpdate.daily(), ""
if hint != "" {
newer = selfUpdate.loadState().Latest
}
// The hint goes to the terminal again after the interface has closed,
// where `nscan update` can be typed right away.
defer func() {
if hint != "" {
fmt.Fprintln(os.Stderr, hint)
}
}()
return tui.Run(tui.Config{
Network: n,
Range: spec,
Targets: targets,
Auto: *interval > 0,
Interval: *interval,
Wait: sf.wait,
Names: !sf.noNames,
Bonjour: !sf.noBonjour,
Store: st,
OUI: db,
ExportDir: *exportDir,
Version: Version,
Update: newer,
})
}
func runScan(args []string) error {
fl := newFlags("scan")
var sf scanFlags
sf.register(fl)
asJSON := fl.Bool("json", false, "JSON output")
asCSV := fl.Bool("csv", false, "CSV output")
if err := fl.Parse(args); err != nil {
return err
}
n, spec, targets, err := sf.resolve()
if err != nil {
return err
}
st, db, err := openState()
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
fmt.Fprintf(os.Stderr, "Scanning %s (%s) on %s …\n", spec, plural(len(targets), "address", "addresses"), n.Iface.Name)
start := time.Now()
hosts, err := scanner.Scan(ctx, scanner.Options{
Network: n, Targets: targets, Wait: sf.wait,
Names: !sf.noNames, Bonjour: !sf.noBonjour, Vendor: db.Lookup,
})
if err != nil {
return err
}
targetSet := make(map[netip.Addr]bool, len(targets))
for _, ip := range targets {
targetSet[ip] = true
}
sightings := make([]store.Sighting, 0, len(hosts))
for _, h := range hosts {
sightings = append(sightings, sighting(h))
}
if _, err := st.Observe(time.Now(), sightings, func(ip netip.Addr) bool { return targetSet[ip] }); err != nil {
fmt.Fprintln(os.Stderr, "warning:", err)
}
recs := make([]export.Record, 0, len(hosts))
for _, h := range hosts {
r := export.FromHost(h)
r.Online = true
if d, ok := st.Device(sighting(h).Key); ok {
if d.Name != "" {
r.Name = d.Name
}
r.Tracked, r.Whitelisted, r.FirstSeen, r.LastSeen = d.Tracked, d.Whitelisted, d.FirstSeen, d.LastSeen
}
recs = append(recs, r)
}
switch {
case *asJSON:
return export.WriteJSON(os.Stdout, recs)
case *asCSV:
return export.WriteCSV(os.Stdout, recs)
}
printTable(os.Stdout, recs)
fmt.Fprintf(os.Stderr, "%s in %.1fs\n", plural(len(recs), "device", "devices"), time.Since(start).Seconds())
return nil
}
func sighting(h scanner.Host) store.Sighting {
s := store.Sighting{IP: h.IP.String(), Hostname: h.Name(), Vendor: h.Vendor, Model: h.Model, Key: "ip:" + h.IP.String()}
if len(h.MAC) > 0 {
s.MAC = h.MAC.String()
s.Key = strings.ToLower(s.MAC)
}
return s
}
func printTable(w io.Writer, recs []export.Record) {
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "IP ADDRESS\tMAC ADDRESS\tVENDOR\tNAME\tPING\tSERVICES")
for _, r := range recs {
rtt := "–"
if r.RTTms > 0 {
rtt = fmt.Sprintf("%.1f ms", r.RTTms)
}
var svcs []string
for _, s := range r.Services {
if short := s.Short(); !contains(svcs, short) {
svcs = append(svcs, short)
}
}
vendor := r.Vendor
if r.Model != "" {
if vendor == oui.Private {
vendor = ""
}
vendor = strings.TrimSpace(vendor + " " + r.Model)
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\n", r.IP, dash(r.MAC), dash(vendor), dash(r.Name), rtt, strings.Join(svcs, ","))
}
tw.Flush()
}
func contains(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}
// plural formats a count with the matching noun ("1 device", "3 devices").
func plural(n int, one, many string) string {
if n == 1 {
return "1 " + one
}
return fmt.Sprintf("%d %s", n, many)
}
func dash(s string) string {
if s == "" {
return "–"
}
return s
}
func resolveHost(ctx context.Context, host string) (netip.Addr, error) {
if ip, err := netip.ParseAddr(host); err == nil {
return ip, nil
}
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", host)
if err != nil {
return netip.Addr{}, err
}
if len(ips) == 0 {
return netip.Addr{}, fmt.Errorf("%s: no IPv4 address", host)
}
return ips[0].Unmap(), nil
}
func runPing(args []string) error {
fl := newFlags("ping")
count := fl.Int("c", 0, "count (0 = until Ctrl+C)")
interval := fl.Duration("interval", time.Second, "interval between requests")
timeout := fl.Duration("W", 2*time.Second, "timeout per reply")
if err := fl.Parse(args); err != nil {
return err
}
if fl.NArg() != 1 {
return errors.New("usage: nscan ping [-c N] <host>")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
ip, err := resolveHost(ctx, fl.Arg(0))
if err != nil {
return err
}
var sent, recv int
var lo, hi, sum time.Duration
err = scanner.Ping(ctx, ip, *count, *interval, *timeout, func(r scanner.PingResult) {
sent++
switch {
case r.Err != nil:
fmt.Printf("seq=%d error: %v\n", r.Seq, r.Err)
case r.Timeout:
fmt.Printf("seq=%d timeout\n", r.Seq)
default:
recv++
sum += r.RTT
if lo == 0 || r.RTT < lo {
lo = r.RTT
}
hi = max(hi, r.RTT)
fmt.Printf("reply from %s: seq=%d time=%.2f ms (%s)\n", ip, r.Seq, ms(r.RTT), r.Method)
}
})
if sent > 0 {
fmt.Printf("\n--- %s ---\n%d sent, %d received, %.0f%% loss\n", ip, sent, recv, 100*float64(sent-recv)/float64(sent))
if recv > 0 {
fmt.Printf("min/avg/max = %.2f/%.2f/%.2f ms\n", ms(lo), ms(sum/time.Duration(recv)), ms(hi))
}
}
return err
}
func ms(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 }
func runPorts(args []string) error {
fl := newFlags("ports")
spec := fl.String("p", "top", "Ports: top, all, 1-1024, 22,80,443")
timeout := fl.Duration("t", 800*time.Millisecond, "timeout per connection")
workers := fl.Int("c", 200, "parallel connections")
if err := fl.Parse(args); err != nil {
return err
}
if fl.NArg() != 1 {
return errors.New("usage: nscan ports [-p top|all|1-1024] <host>")
}
ports, err := scanner.ParsePorts(*spec)
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
ip, err := resolveHost(ctx, fl.Arg(0))
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Scanning %s on %s …\n", plural(len(ports), "port", "ports"), ip)
start := time.Now()
found := 0
results := make(chan scanner.PortResult)
done := make(chan struct{})
go func() {
for r := range results {
found++
fmt.Printf("%-10s %-16s %.2f ms\n", fmt.Sprintf("%d/tcp", r.Port), dash(r.Service), ms(r.RTT))
}
close(done)
}()
scanner.ScanPorts(ctx, ip, ports, *timeout, *workers, func(r scanner.PortResult) { results <- r }, nil)
close(results)
<-done
fmt.Fprintf(os.Stderr, "%s in %.1fs\n", plural(found, "open port", "open ports"), time.Since(start).Seconds())
return nil
}
func runWOL(args []string) error {
fl := newFlags("wol")
iface := fl.String("i", "", "interface")
bcast := fl.String("b", "", "broadcast address")
if err := fl.Parse(args); err != nil {
return err
}
if fl.NArg() != 1 {
return errors.New("usage: nscan wol [-b broadcast] <mac|name>")
}
target := fl.Arg(0)
mac, err := net.ParseMAC(target)
if err != nil {
// Allow the custom name given in the interface.
st, _, serr := openState()
if serr != nil {
return serr
}
for _, d := range st.Devices() {
if d.MAC != "" && (strings.EqualFold(d.Name, target) || strings.EqualFold(d.Hostname, target)) {
mac, err = net.ParseMAC(d.MAC)
break
}
}
if err != nil {
return fmt.Errorf("%q is neither a MAC address nor a known device", target)
}
}
var b netip.Addr
if *bcast != "" {
if b, err = netip.ParseAddr(*bcast); err != nil {
return err
}
} else if n, err := scanner.DetectNetwork(*iface); err == nil {
b = n.Broadcast()
}
if err := scanner.WakeOnLAN(mac, b); err != nil {
return err
}
fmt.Printf("magic packet sent to %s\n", mac)
return nil
}
func runInterfaces() error {
def, _ := scanner.DetectNetwork("")
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "INTERFACE\tADDRESS\tNETWORK\tMAC\t")
for _, n := range scanner.Interfaces() {
mark := ""
if def != nil && def.Iface.Name == n.Iface.Name {
mark = "(default)"
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", n.Iface.Name, n.LocalIP, n.Prefix.Masked(), dash(n.LocalMAC.String()), mark)
}
return tw.Flush()
}
func runOUI(args []string) error {
if len(args) == 0 {
return errors.New("usage: nscan oui update | import <file> | lookup <mac>")
}
dir, err := store.Dir()
if err != nil {
return err
}
path := ouiPath(dir)
switch args[0] {
case "update":
fmt.Fprintln(os.Stderr, "Downloading", oui.SourceURL, "…")
n, err := oui.Download(context.Background(), path)
if err != nil {
return fmt.Errorf("%w\nIf the download is blocked, fetch the file in a browser and run \"nscan oui import <file>\"", err)
}
fmt.Printf("%d vendors saved to %s\n", n, path)
case "import":
if len(args) != 2 {
return errors.New("usage: nscan oui import <oui.csv|oui.txt>")
}
f, err := os.Open(args[1])
if err != nil {
return err
}
defer f.Close()
n, err := oui.Install(f, path)
if err != nil {
return err
}
fmt.Printf("%d vendors saved to %s\n", n, path)
case "lookup":
if len(args) != 2 {
return errors.New("usage: nscan oui lookup <mac>")
}
mac, err := net.ParseMAC(args[1])
if err != nil {
return err
}
db, err := oui.Load(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
fmt.Println(dash(db.Lookup(mac)))
default:
return fmt.Errorf("unknown oui command %q", args[0])
}
return nil
}