How to start a powershell process with administrator privileges and redirect stdin (os.exec)

王林
Release: 2024-02-10 19:03:19
forward
425 people have browsed it

如何使用管理员权限启动 powershell 进程并重定向 stdin (os.exec)

#php editor Zimo will share with you today a method to start the powershell process with administrator privileges and redirect stdin. In some cases, we need to run the powershell script with administrator rights, but running it directly may encounter permission issues. At this time, we can use the os.exec function to achieve this. The os.exec function starts a process and redirects input into a script. This way we can execute commands with administrator rights in the script and can receive input. In this article, we will introduce in detail how to use this method to solve permission problems, we hope it will be helpful to everyone.

Question content

I want to start a powershell process with administrator rights and redirect standard input to the writer, I have done everything except how to run it as administrator Work.

// 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()
Copy after login

Since there doesn't seem to be anything like process.verb that can be set to "runas", I tried creating a powershell using the powershell command start-process ... -verb runas The process and obtaining the pid of the process succeeded, but it seems that I cannot use the pid later to operate stdin and stdout.

Solution

Thanks to @jeroen-mostert, I kind of figured it out. I started the go executable as administrator and used StartProcess powershell.exe -verb RunAs, it didn't work like I wanted in the first place, but at least it no longer opens for powershell UAC.

The above is the detailed content of How to start a powershell process with administrator privileges and redirect stdin (os.exec). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!