本文有问题,请不要尝试源码
package main
import (
"fmt"
"os"
"syscall"
"unsafe"
)
func main() {
for i := 1; i < 3; i++ {
check()
}
}
func check() {
if os.Geteuid() == 0 {
fmt.Println("Already running as root")
return
}
// 获取程序的路径
path, err := os.Executable()
if err != nil {
fmt.Println(err)
return
}
// 获取当前进程的句柄
handle, err := syscall.LoadLibrary("shell32.dll")
if err != nil {
fmt.Println(err)
return
}
defer syscall.FreeLibrary(handle)
// 获取ShellExecuteW函数的地址
proc, err := syscall.GetProcAddress(handle, "ShellExecuteW")
if err != nil {
fmt.Println(err)
return
}
// 调用ShellExecuteW函数以请求管理员权限
args := []uintptr{
0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("runas"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))),
0,
0,
0,
}
ret, _, err := syscall.Syscall6(uintptr(proc), 6, args[0], args[1], args[2], args[3], args[4], args[5])
if ret != 0 {
fmt.Println("Successfully requested admin privileges")
return
} else {
fmt.Println("Failed to request admin privileges")
fmt.Println(err)
}
}