Please see the output of the net use
command below. Now I want to extract the expiration date out of this piece of text. Unfortunately the net use
command is unable to output as json, xml or whatever parsble format. Therefore I'm stuck to this text :(. I'm only interested in getting 10-6-2017 6:57:20
and convert it into Golang date format.
The problem: I don't know how to start? First find the row which contains "Password expires"? And then what?
User name jdoe
Full Name John Doe
Comment
User's comment
Country code (null)
Account active Yes
Account expires Never
Password last set 1-5-2017 6:57:20
Password expires 10-6-2017 6:57:20
Password changeable 1-5-2017 6:57:20
Password required Yes
User may change password Yes
Here you go:
import (
"fmt"
"strings"
)
func main() {
str := `
User name jdoe
Full Name John Doe
Comment
User's comment
Country code (null)
Account active Yes
Account expires Never
Password last set 1-5-2017 6:57:20
Password expires 10-6-2017 6:57:20
Password changeable 1-5-2017 6:57:20
Password required Yes
User may change password Yes`
lines := strings.Split(str, "
")
for _, line := range lines {
if strings.HasPrefix(line, "Password expires") {
elems := strings.Split(line, " ")
date := elems[len(elems)-2]
time := elems[len(elems)-1]
fmt.Println(date, time)
}
}
}
Alternatively you could use regex
.
For example, assuming dd-mm-yyyy, 24-hour clock, and local time location (Amsterdam),
package main
import (
"bufio"
"fmt"
"strings"
"time"
)
func passwordExpires(netuser string) time.Time {
const title = "Password expires"
scanner := bufio.NewScanner(strings.NewReader(netuser))
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, title) {
continue
}
value := strings.TrimSpace(line[len(title):])
format := "2-1-2006 15:04:05"
loc := time.Now().Location()
expires, err := time.ParseInLocation(format, value, loc)
if err == nil {
return expires
}
}
return time.Time{}
}
// Europe/Amsterdam
var netuser = `User name jdoe
Full Name John Doe
Comment
User's comment
Country code (null)
Account active Yes
Account expires Never
Password last set 1-5-2017 6:57:20
Password expires 10-6-2017 6:57:20
Password changeable 1-5-2017 6:57:20
Password required Yes
User may change password Yes`
func main() {
expires := passwordExpires(netuser)
fmt.Println(expires)
if expires.IsZero() {
fmt.Println("no password expiration")
}
}
Output:
>go run expire.go
2017-06-10 06:57:20 +0200 CEST