如何使用管理员权限启动 PowerShell 进程并重定向标准输入(stdin)?

huangapple go评论111阅读模式
英文:

How do I start a powershell process with administrator privilges and redirect stdin (os.exec)

问题

我想要以管理员权限启动一个 PowerShell 进程,并将标准输入重定向到一个写入器,除了如何以管理员身份运行它之外,其他都已经搞定。

// 启动 PowerShell
powershell := exec.Command("powershell")
// 添加一个将打开 UAC 并给予进程管理员权限的内容

powershell.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
powershell.Env = os.Environ()

// 创建管道以供稍后写入
stdin, err := powershell.StdinPipe()
if err != nil {
    log.Fatal(err)
}

defer stdin.Close()

似乎没有 Process.Verb 这样的东西可以设置为 "runas",我尝试使用 PowerShell 命令 Start-Process ... -Verb runas 创建一个 PowerShell 进程,并成功获取了进程的 PID,但似乎没有办法稍后使用 PID 操纵标准输入和标准输出。

英文:

I want to start a powershell process with administrator priviliges and redirect stdin to a writer, I have everything working except how to run it as admin.

// Start powershell
powershell := exec.Command("powershell")
// Add something that will open UAC and give the process admin priviliges

powershell.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
powershell.Env = os.Environ()

// Create pipe to write to it later
stdin, err := powershell.StdinPipe()
if err != nil {
    log.Fatal(err)
}

defer stdin.Close()

As it seems there is no such thing as Process.Verb that I can set to "runas", I tried creating a powershell process by using powershell commands Start-Process ... -Verb runas and got the pid of the process successfully, but it seems like there's no way to manipulate stdin and stdout later with a pid.

答案1

得分: 1

感谢@jeroen-mostert的帮助,我有点弄明白了。我以管理员身份启动了我的go可执行文件,并使用了StartProcess powershell.exe -verb RunAs,虽然一开始它并不像我想的那样工作,但至少不再为powershell打开UAC了。

英文:

Thanks to @jeroen-mostert I kinda figured it out. I started my go executeable as admin and used StartProcess powershell.exe -verb RunAs, it isn't working like I wanted in the beginning, but at least it doesnt open UAC for powershell anymore.

huangapple
  • 本文由 发表于 2023年3月1日 22:23:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75604946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定