Skip to content

Instantly share code, notes, and snippets.

@egeneralov
Created March 28, 2020 20:52
Show Gist options
  • Select an option

  • Save egeneralov/bd16e37554a7e4ecfabeea47deff445d to your computer and use it in GitHub Desktop.

Select an option

Save egeneralov/bd16e37554a7e4ecfabeea47deff445d to your computer and use it in GitHub Desktop.
dhcpd_leases golang parser example
package main
import (
"encoding/json"
"strings"
"bufio"
"fmt"
"os"
)
const (
filename = "/var/db/dhcpd_leases"
)
var (
leases = []Lease{}
)
type Lease struct {
ID string
Name string
IPAddress string
MACAddress string
Identifier string
}
// FromString("name=localhost ip_address=192.168.64.2 hw_address=1,62:8:cb:94:c3:b3 identifier=1,62:8:cb:94:c3:b3 lease=0x5e41f346") (lease)
func FromString(src string) Lease {
self := Lease{}
for _, some := range strings.Split(src, "\t") {
if some == "" {
continue
}
line := strings.Split(some, "=")
switch line[0] {
default:
continue
case "name":
self.Name = line[1]
case "ip_address":
self.IPAddress = line[1]
case "hw_address":
self.MACAddress = line[1]
case "identifier":
self.Identifier = line[1]
case "lease":
self.ID = line[1]
}
}
return self
}
func main() {
fileHandle, _ := os.Open(filename)
defer fileHandle.Close()
fileScanner := bufio.NewScanner(fileHandle)
block := ""
for fileScanner.Scan() {
line := fileScanner.Text()
switch line {
case "":
continue
case "{":
block = ""
case "}":
leases = append(leases, FromString(block))
default:
block += line
}
}
b, _ := json.Marshal(leases)
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment