在 Golang 中使用 Exec 时如何隐藏命令提示符 window?

How to hide command prompt window when using Exec in Golang?

假设我有以下代码,使用 syscall 隐藏命令行 window

process := exec.Command(name, args...)
process.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
err := process.Start()
if err != nil {
    log.Print(err)
}

但是当我编译它并尝试在 Windows 中 运行 它时,命令行 window 再次出现

我能做些什么来防止命令行 window 出现?

PS 我已经知道如何使用 go build -ldflags -H=windowsgui 将 golang 源代码编译成 Windows GUI 可执行文件,但这样做只能确保程序本身不会启动命令行window、Exec 无论如何都会显示那些 windows

如果您使用 -ldflags -H=windowsgui 构建,每个 exec.Command 都会产生一个新控制台 window。

如果你在没有标志的情况下构建,你会得到 一个 控制台 window 并且所有 exec.Command 都会打印到那个控制台中。

因此,我目前的解决方案是在没有 标志的情况下构建 ,即在程序启动时有一个控制台 window,然后立即隐藏控制台 window我程序开始时的这段代码:

import "github.com/gonutz/w32/v2"

func hideConsole() {
    console := w32.GetConsoleWindow()
    if console == 0 {
        return // no console attached
    }
    // If this application is the process that created the console window, then
    // this program was not compiled with the -H=windowsgui flag and on start-up
    // it created a console along with the main application window. In this case
    // hide the console window.
    // See
    // 
    _, consoleProcID := w32.GetWindowThreadProcessId(console)
    if w32.GetCurrentProcessId() == consoleProcID {
        w32.ShowWindowAsync(console, w32.SW_HIDE)
    }
}

有关进程 ID 内容的详细信息,请参阅 this thread

现在所有 exec.Command 都将输出打印到隐藏控制台 window 而不是生成自己的输出。

这里的妥协是你的程序会在你启动时闪烁一次控制台 window,但在它隐藏之前只会闪烁一小会儿。

There 是一个更好的解决方案,它可以 运行 exec.Command() 而不会产生可见的 window,( ͡° ͜ʖ ͡°)。

这是我的代码:

首先import "syscall"

cmd_path := "C:\Windows\system32\cmd.exe"
cmd_instance := exec.Command(cmd_path, "/c", "notepad")
cmd_instance.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
cmd_output, err := cmd_instance.Output()

来源: https://www.reddit.com/r/golang/comments/2c1g3x/build_golang_app_reverse_shell_to_run_in_windows/

而不是隐藏控制台 window,你应该能够阻止它:

cmd := exec.Command(...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x08000000} // CREATE_NO_WINDOW