Skip to content

Instantly share code, notes, and snippets.

@abduelhamit
Created October 9, 2015 15:56
Show Gist options
  • Save abduelhamit/8273daac0e9ef72da30a to your computer and use it in GitHub Desktop.
Save abduelhamit/8273daac0e9ef72da30a to your computer and use it in GitHub Desktop.
UAC elevation in Go
package main
import (
"io/ioutil"
"log"
"os"
"syscall"
"unsafe"
)
func runAsAdmin(file, parameters string) error {
shellExecute := syscall.MustLoadDLL("Shell32.dll").MustFindProc("ShellExecuteW")
defer shellExecute.Dll.Release()
r, _, err := shellExecute.Call(
0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("runas"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(file))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(parameters))),
0,
syscall.SW_SHOWNORMAL,
)
if r <= 32 {
return err
}
return nil
}
func main() {
err := ioutil.WriteFile(
os.Getenv(`ProgramFiles`)+`\test.txt`, []byte("Hello World"), 0666)
if err == nil {
log.Println("File successfully written")
return
}
if !os.IsPermission(err) {
log.Fatalln(err)
}
log.Println("Start UAC elevation")
err = runAsAdmin(os.Args[0], "")
if err != nil {
log.Fatalln(err)
}
log.Println("UAC elevation succeeded")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment