func AmAdmin() bool {
_, err := os.Open("\\\\.\\PHYSICALDRIVE0")
if err != nil {
fmt.Println("admin no")
return false
}
fmt.Println("admin yes")
return true
}
func RunMeElevated() {
verb := "runas"
exe, _ := os.Executable()
cwd, _ := os.Getwd()
args := strings.Join(os.Args[1:], " ")
verbPtr, _ := syscall.UTF16PtrFromString(verb)
exePtr, _ := syscall.UTF16PtrFromString(exe)
cwdPtr, _ := syscall.UTF16PtrFromString(cwd)
argPtr, _ := syscall.UTF16PtrFromString(args)
var showCmd int32 = 1 //SW_NORMAL
err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd)
if err != nil {
fmt.Println(err)
}
}
调用
func main() {
if !common.AmAdmin() {
fmt.Printf("is not admin ,will close and open again as admin")
common.RunMeElevated()
return
}
// 写你的业务逻辑
}
标签:err,windows,UTF16PtrFromString,fmt,syscall,管理员,go,os,admin
From: https://www.cnblogs.com/ifnk/p/17616380.html