txeh

package module
v1.5.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2023 License: Apache-2.0 Imports: 8 Imported by: 58

README

txeh - /etc/hosts mangement

Etc Hosts Management Utility & Go Library

GoDoc

/etc/hosts Management

It is easy to open your /etc/hosts file in text editor and add or remove entries. However, if you make heavy use of /etc/hosts for software development or DevOps purposes, it can sometimes be difficult to automate and validate large numbers of host entries.

txeh was initially built as a golang library to support kubefwd, a Kubernetes port-forwarding utility utilizing /etc/hosts heavily, to associate custom hostnames with multiple local loopback IP addresses and remove these entries when it terminates.

A computer's /etc/hosts file is a powerful utility for developers and system administrators to create localized, custom DNS entries. This small go library and utility were developed to encapsulate the complexity of working with /etc/hosts directly by providing a simple interface for adding and removing entries in a /etc/hosts file.

txeh Utility

Install

MacOS homebrew users can brew install txn2/tap/txeh, otherwise see releases for packages and binaries for a number of distros and architectures including Windows, Linux and Arm based systems.

Install with go install

When installing with Go please use the latest stable Go release. At least go1.16 or greater is required.

To install use: go install github.com/txn2/txeh/txeh@master

If you are building from a local source clone, use go install ./txeh from the top-level directory of the clone.

go install will typically put the txeh binary inside the bin directory under go env GOPATH, see Go’s Compile and install packages and dependencies for more on this. You may need to add that directory to your $PATH if you encounter the error txeh: command not found after installation, you can find a guide for adding a directory to your PATH at https://gist.github.com/nex3/c395b2f8fd4b02068be37c961301caa7#file-path-md.

Compile and run from source

dependencies are vendored:

go run ./txeh/txeh.go
Use

The txeh CLI application allows command line or scripted access to /etc/hosts file modification.

Example CLI Usage:

 _            _
| |___  _____| |__
| __\ \/ / _ \ '_ \
| |_ >  <  __/ | | |
 \__/_/\_\___|_| |_| v1.5.0

Add, remove and re-associate hostname entries in your /etc/hosts file.
Read more including usage as a Go library at https://github.com/txn2/txeh

Usage:
  txeh [flags]
  txeh [command]

Available Commands:
  add         Add hostnames to /etc/hosts
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  list        List hostnames or IP addresses
  remove      Remove a hostname or ip address
  show        Show hostnames in /etc/hosts
  version     Print the version number of txeh


Flags:
  -d, --dryrun         dry run, output to stdout (ignores quiet)
  -h, --help           help for txeh
  -q, --quiet          no output
  -r, --read string    (override) Path to read /etc/hosts file.
  -w, --write string   (override) Path to write /etc/hosts file.
# point the hostnames "test" and "test.two" to the local loopback
sudo txeh add 127.0.0.1 test test.two

# remove the hostname "test"
sudo txeh remove host test

# remove multiple hostnames
sudo txeh remove host test test2 test.two

# remove an IP address and all the hosts that point to it
sudo txeh remove ip 93.184.216.34

# remove multiple IP addresses
sudo txeh remove ip 93.184.216.34 127.1.27.1

# remove CIDR ranges
sudo txeh remove cidr 93.184.216.0/24 127.1.27.0/28

# quiet mode will suppress output
sudo txeh remove ip 93.184.216.34 -q

# dry run will print a rendered /etc/hosts with your changes without
# saving it.
sudo txeh remove ip 93.184.216.34 -d

# use quiet mode and dry-run to direct the rendered /etc/hosts file
# to another file
sudo txeh add 127.1.27.100 dev.example.com -q -d > hosts.test

# specify an alternate /etc/hosts file to read. writing will
# default to the specified read path.
txeh add 127.1.27.100 dev2.example.com -q -r ./hosts.test

# specify a separate read and write oath
txeh add 127.1.27.100 dev3.example.com -r ./hosts.test -w ./hosts.test2

txeh Go Library

Dependency:

go get github.com/txn2/txeh

Example Golang Implementation:


package main

import (
    "fmt"
    "strings"

    "github.com/txn2/txeh"
)

func main() {
    hosts, err := txeh.NewHostsDefault()
    if err != nil {
        panic(err)
    }

    hosts.AddHost("127.100.100.100", "test")
    hosts.AddHost("127.100.100.101", "logstash")
    hosts.AddHosts("127.100.100.102", []string{"a", "b", "c"})

    hosts.RemoveHosts([]string{"example", "example.machine", "example.machine.example.com"})
    hosts.RemoveHosts(strings.Fields("example2 example.machine2 example.machine.example.com2"))


    hosts.RemoveAddress("127.1.27.1")

    removeList := []string{
        "127.1.27.15",
        "127.1.27.14",
        "127.1.27.13",
    }

    hosts.RemoveAddresses(removeList)

    hfData := hosts.RenderHostsFile()

    // if you like to see what the outcome will
    // look like
    fmt.Println(hfData)

    hosts.Save()
    // or hosts.SaveAs("./test.hosts")
}

Build Release

Build test release:

goreleaser --skip-publish --clean --skip-validate

Build and release:

GITHUB_TOKEN=$GITHUB_TOKEN goreleaser --rm-dist
License

Apache License 2.0

Documentation

Index

Constants

View Source
const ADDRESS = 30
View Source
const COMMENT = 20
View Source
const EMPTY = 10
View Source
const UNKNOWN = 0

Variables

This section is empty.

Functions

This section is empty.

Types

type AddressLocations

type AddressLocations map[string]int

AddressLocations the location of an address in the HFL

type HostFileLine

type HostFileLine struct {
	OriginalLineNum int
	LineType        int
	Address         string
	Parts           []string
	Hostnames       []string
	Raw             string
	Trimmed         string
	Comment         string
}

func ParseHosts

func ParseHosts(path string) ([]HostFileLine, error)

func ParseHostsFromString added in v1.5.3

func ParseHostsFromString(input string) ([]HostFileLine, error)

type HostFileLines

type HostFileLines []HostFileLine

type HostLocations

type HostLocations map[string]int

HostLocations maps a hostname to an original line number

type Hosts

type Hosts struct {
	sync.Mutex
	*HostsConfig
	// contains filtered or unexported fields
}

func NewHosts

func NewHosts(hc *HostsConfig) (*Hosts, error)

NewHosts returns a new hosts object

func NewHostsDefault

func NewHostsDefault() (*Hosts, error)

NewHostsDefault returns a hosts object with default configuration

func (*Hosts) AddHost

func (h *Hosts) AddHost(addressRaw string, hostRaw string)

AddHost adds a host to an address and removes the host from any existing address is may be associated with

func (*Hosts) AddHosts

func (h *Hosts) AddHosts(address string, hosts []string)

AddHosts adds an array of hosts to the first matching address it finds or creates the address and adds the hosts

func (*Hosts) GetHostFileLines

func (h *Hosts) GetHostFileLines() *HostFileLines

func (*Hosts) HostAddressLookup

func (h *Hosts) HostAddressLookup(host string, ipFamily IPFamily) (bool, string, int)

HostAddressLookup returns true if the host is found, a string containing the address and the index of the hfl

func (*Hosts) ListAddressesByHost added in v1.5.2

func (h *Hosts) ListAddressesByHost(hostname string, exact bool) [][]string

ListAddressesByHost returns a list of IPs associated with a given hostname

func (*Hosts) ListHostsByCIDR added in v1.5.2

func (h *Hosts) ListHostsByCIDR(cidr string) [][]string

ListHostsByCIDR returns a list of IPs and hostnames associated with a given CIDR

func (*Hosts) ListHostsByIP added in v1.5.2

func (h *Hosts) ListHostsByIP(address string) []string

ListHostsByIP returns a list of hostnames associated with a given IP address

func (*Hosts) Reload

func (h *Hosts) Reload() error

Reload hosts file

func (*Hosts) RemoveAddress

func (h *Hosts) RemoveAddress(address string)

RemoveAddress removes all entries (lines) with the provided address.

func (*Hosts) RemoveAddresses

func (h *Hosts) RemoveAddresses(addresses []string)

RemoveAddresses removes all entries (lines) with the provided address.

func (*Hosts) RemoveCIDRs added in v1.5.4

func (h *Hosts) RemoveCIDRs(cidrs []string) error

RemoveCIDRs Remove CIDR Range (Classless inter-domain routing) examples:

127.1.0.0/16  = 127.1.0.0  -> 127.1.255.255
127.1.27.0/24 = 127.1.27.0 -> 127.1.27.255

func (*Hosts) RemoveFirstAddress

func (h *Hosts) RemoveFirstAddress(address string) bool

RemoveFirstAddress removes the first entry (line) found with the provided address.

func (*Hosts) RemoveFirstHost

func (h *Hosts) RemoveFirstHost(host string) bool

RemoveFirstHost the first hostname entry found and returns true if successful

func (*Hosts) RemoveHost

func (h *Hosts) RemoveHost(host string)

RemoveHost removes all hostname entries of provided host

func (*Hosts) RemoveHosts

func (h *Hosts) RemoveHosts(hosts []string)

RemoveHosts removes all hostname entries of the provided host slice

func (*Hosts) RenderHostsFile

func (h *Hosts) RenderHostsFile() string

func (*Hosts) Save

func (h *Hosts) Save() error

Save rendered hosts file

func (*Hosts) SaveAs

func (h *Hosts) SaveAs(fileName string) error

SaveAs saves rendered hosts file to the filename specified

type HostsConfig

type HostsConfig struct {
	ReadFilePath  string
	WriteFilePath string
	// RawText for input. If RawText is set ReadFilePath, WriteFilePath are ignored. Use RenderHostsFile rather
	// than save to get the results.
	RawText *string
}

type IPFamily added in v1.4.0

type IPFamily int64
const (
	IPFamilyV4 IPFamily = iota
	IPFamilyV6
)

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL