github.com/dim13/unifi@v0.0.0-20230308161331-9b04946f5e93/cmd/list-clients/main.go (about)

     1  // Copyright (c) 2014 Dimitri Sokolyuk. All rights reserved.
     2  // Use of this source code is governed by ISC-style license
     3  // that can be found in the LICENSE file.
     4  
     5  // Example command list-clients
     6  // list associated clients (stations) of a given site
     7  package main
     8  
     9  import (
    10  	"flag"
    11  	"fmt"
    12  	"log"
    13  	"os"
    14  	"strconv"
    15  	"strings"
    16  	"text/tabwriter"
    17  	"time"
    18  
    19  	"github.com/dim13/unifi"
    20  )
    21  
    22  var (
    23  	host    = flag.String("host", "unifi", "Controller hostname")
    24  	user    = flag.String("user", "admin", "Controller username")
    25  	pass    = flag.String("pass", "unifi", "Controller password")
    26  	version = flag.Int("version", 5, "Controller base version")
    27  	port    = flag.String("port", "8443", "Controller port")
    28  	siteid  = flag.String("siteid", "default", "Sitename or description")
    29  )
    30  
    31  func main() {
    32  	w := new(tabwriter.Writer)
    33  	w.Init(os.Stdout, 0, 8, 3, ' ', 0)
    34  	defer w.Flush()
    35  
    36  	flag.Parse()
    37  	u, err := unifi.Login(*user, *pass, *host, *port, *siteid, *version)
    38  	if err != nil {
    39  		log.Fatal("Login returned error: ", err)
    40  	}
    41  	defer u.Logout()
    42  
    43  	site, err := u.Site(*siteid)
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	devices, err := u.DeviceMap(site)
    49  	if err != nil {
    50  		log.Fatal(err)
    51  	}
    52  	sta, err := u.Sta(site)
    53  	if err != nil {
    54  		log.Fatal(err)
    55  	}
    56  
    57  	// Output headline
    58  	fmt.Fprintln(w, "Name\tIsWired\tRadio\tChannel\tESSID\tRoamCount\tSignal\tNoise\tRSSI\tDevicename\tIP\tFirstSeen\tLastSeen\tUptime")
    59  
    60  	for _, s := range sta {
    61  
    62  		deviceMac := ""
    63  
    64  		if s.ApMac != "" {
    65  			deviceMac = s.ApMac
    66  		} else if s.SwMac != "" {
    67  			deviceMac = s.SwMac
    68  		}
    69  
    70  		deviceName := devices[deviceMac].DeviceName()
    71  
    72  		p := []string{
    73  			s.Name(),
    74  			strconv.FormatBool(s.IsWired),
    75  			s.Radio,
    76  			strconv.Itoa(s.Channel),
    77  			s.ESSID,
    78  			strconv.Itoa(s.RoamCount),
    79  			strconv.Itoa(s.Signal),
    80  			strconv.Itoa(s.Noise),
    81  			strconv.Itoa(s.Rssi),
    82  			deviceName,
    83  			s.IP,
    84  			time.Unix(s.FirstSeen, 0).Format("2006-01-02 15:04:05"),
    85  			time.Unix(s.LastSeen, 0).Format("2006-01-02 15:04:05"),
    86  			(time.Duration(s.Uptime) * time.Second).String(),
    87  		}
    88  		fmt.Fprintln(w, strings.Join(p, "\t"))
    89  
    90  	}
    91  
    92  }