Created
December 31, 2024 09:02
-
-
Save monotykamary/27f4a76f49accc25784b4a902c78df8f to your computer and use it in GitHub Desktop.
nmap with Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"time" | |
"internal/config" | |
"github.com/Ullaakut/nmap/v3" | |
) | |
// viewAndLogActiveDevices retrieves and logs all active devices in the network | |
func viewAndLogActiveDevices(cfg *config.Config) error { | |
// Create a context with a 5-minute timeout | |
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) | |
defer cancel() | |
// Create a new nmap scanner with target subnet and options | |
scanner, err := nmap.NewScanner( | |
ctx, | |
nmap.WithTargets(cfg.NetworkSubnet), // e.g. "192.4.1.0/24" | |
nmap.WithCustomDNSServers(cfg.RouterIP), // --dns-servers | |
nmap.WithPingScan(), // -sn | |
nmap.WithPrivileged(), // run as privileged user | |
) | |
if err != nil { | |
return fmt.Errorf("error creating nmap scanner: %v", err) | |
} | |
// Run the scan | |
result, warnings, err := scanner.Run() | |
if len(*warnings) > 0 { | |
log.Printf("Scan completed with warnings: %v\n", *warnings) | |
} | |
if err != nil { | |
return fmt.Errorf("error running nmap scan: %v", err) | |
} | |
// Log active devices | |
log.Println("Active devices in the network:") | |
activeCount := 0 | |
for _, host := range result.Hosts { | |
// Skip hosts that are not up, don't have addresses, or don't have hostnames | |
if len(host.Addresses) == 0 || host.Status.State != "up" || len(host.Hostnames) == 0 { | |
continue | |
} | |
hostname := host.Hostnames[0].Name | |
if hostname == "" { | |
continue | |
} | |
// Get IP and MAC addresses | |
var ip, mac string | |
for _, addr := range host.Addresses { | |
if addr.AddrType == "ipv4" { | |
ip = addr.Addr | |
} else if addr.AddrType == "mac" { | |
mac = addr.Addr | |
} | |
} | |
// Log device information | |
log.Printf("- Name: %s, MAC: %s, IP: %s\n", hostname, mac, ip) | |
activeCount++ | |
} | |
log.Printf("Total active devices: %d\n", activeCount) | |
log.Printf("Total hosts scanned: %d\n", len(result.Hosts)) | |
return nil | |
} | |
func main() { | |
cfg, err := config.Load() | |
if err != nil { | |
log.Fatalf("Failed to load config: %v", err) | |
} | |
err = viewAndLogActiveDevices(cfg) | |
if err != nil { | |
log.Fatalf("Failed to view and log active devices: %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment