package main import ( "flag" "fmt" "os" "path/filepath" "strings" ) var fileName = filepath.Base(os.Args[0]) func init() { fmt.Println("DNSHelper v1.0") fmt.Println("Copyright (c) 2024 Emberkom LLC") fmt.Println("") if len(os.Args) < 2 { printUsage() defer os.Exit(1) } } func printUsage() { fmt.Println("This utility will update the local hosts file with DNS entries obtained by the specified DNS server.") fmt.Println("Usage: " + fileName + " [add|delete] -host hostname [-server dns.example.com]") fmt.Println("Example:") fmt.Println(" " + fileName + " add -host xyz.acme.com -server dns.example.com") fmt.Println(" This will use dns.example.com to find and add all IP addresses for xyz.acme.com to the local hosts file.") fmt.Println(" " + fileName + " delete -host hostname.example.com") fmt.Println(" This will delete all entries for hostname.example.com from the local hosts file.") fmt.Println(" " + fileName + " delete all") fmt.Println(" This will delete all entries from the local hosts file that were added by this utility.") fmt.Println("Note: Adding a hostname will first remove all entries in the hosts file that match the same hostname.") fmt.Println(" This utility will only remove entries from the hosts file that it added.") } func term(err error) { fmt.Println("Error: " + err.Error()) defer os.Exit(1) } func main() { modePing := flag.NewFlagSet("ping", flag.ExitOnError) modeAdd := flag.NewFlagSet("add", flag.ExitOnError) hostToAdd := modeAdd.String("host", "", "Comma separated list of hostnames to add") dnsResolver := modeAdd.String("server", "", "DNS resolver to use") modeDelete := flag.NewFlagSet("delete", flag.ExitOnError) hostToDelete := modeDelete.String("host", "", "Comma separated list of hostnames to delete") data := new(workingData) var err error data.HostsFileLocation, err = getHostsFileLocation() if err != nil { term(err) } data.DefaultContent, err = getFileContentLines(data.HostsFileLocation) if err != nil { term(err) } if err = extractLinesToEdit(data); err != nil { term(err) } switch strings.ToLower(os.Args[1]) { case "a", "add": err = modeAdd.Parse(os.Args[2:]) if err != nil { term(err) } addHostsToWorkingData(data, hostToAdd) addResolversToWorkingData(data, dnsResolver) removeHostsFromExistingContent(data) addNameToIPMappingsToNewContent(data) case "d", "del", "delete": err = modeDelete.Parse(os.Args[2:]) if err != nil { term(err) } if strings.ToLower(*hostToDelete) != "all" && strings.ToLower(*hostToDelete) != "a" { addHostsToWorkingData(data, hostToDelete) removeHostsFromExistingContent(data) } default: printUsage() } err = writeHostsFile(data) if err != nil { term(err) } }