2017-06-01 3 views
0

Bitte beachten Sie die Ausgabe des Befehls net use unten. Jetzt möchte ich das Ablaufdatum aus diesem Textabschnitt extrahieren. Leider kann der Befehl net use nicht als json, xml oder irgendein anderes Parsle-Format ausgegeben werden. Deshalb bleibe ich bei diesem Text :(Ich bin nur daran interessiert, 10-6-2017 6:57:20 zu bekommen und in Golang Datumsformat zu konvertieren.Datum aus dem Multiline-Ausgang in Go extrahieren

Das Problem: Ich weiß nicht, wie ich anfangen soll? Zuerst finden Sie die Zeile, die enthält " Kennwort läuft "Und was dann

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 

Antwort

1

Hier gehen Sie:?.

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, "\n") 

    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) 
     } 
    } 
} 

Alternativ können Sie regex verwenden

0

Zum Beispiel assumin g dd-mm-yyyy, 24-Stunden-Uhr, und die Ortszeit Lage (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 
Verwandte Themen