golang編寫一個window定時關機

demon_h發表於2021-02-03
package main

import (
    "flag"
    "fmt"
    "github.com/robfig/cron"
    "time"
)

import (
    . "github.com/CodyGuo/win"
)

var (
    arg string
)

func init() {
    flag.StringVar(&arg, "uFlags", "shutdown", "shutdown logoff reboot")
}

func main() {
    flag.Parse()

    c := cron.New(cron.WithSeconds())
    c.AddFunc("0 40 18 * * ?", shutdown)
    c.Start()
    select {}

    switch arg {
    case "logoff":
        logoff()
    case "reboot":
        reboot()
    case "shutdown":
        shutdown()
    default:
        fmt.Println("您輸入的引數有誤.")
    }
}

func Test(){
    fmt.Println(time.Now())
}

func logoff() {
    ExitWindowsEx(EWX_LOGOFF, 0)
}

func reboot() {
    getPrivileges()
    ExitWindowsEx(EWX_REBOOT, 0)
}

func shutdown() {
    getPrivileges()
    ExitWindowsEx(EWX_SHUTDOWN, 0)
}

func getPrivileges() {
    var hToken HANDLE
    var tkp TOKEN_PRIVILEGES

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken)
    LookupPrivilegeValueA(nil, StringToBytePtr(SE_SHUTDOWN_NAME), &tkp.Privileges[0].Luid)
    tkp.PrivilegeCount = 1
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
    AdjustTokenPrivileges(hToken, false, &tkp, 0, nil, nil)
}

cron表示式

c.AddFunc("0 40 18 * * ?", shutdown)
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章