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

jm3*_*_m0 7 windows command-line system-calls go

说我有以下代码,syscall用于隐藏命令行窗口

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

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

我该怎么做才能防止命令行窗口出现?

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

Yu *_*hen 13

一个更好的解决方案,可以在exec.Command()不产生可见窗口的情况下运行(͡°͜ʖ͡°).

这是我的代码:

首先 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()
Run Code Online (Sandbox Code Playgroud)

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


And*_*lay 6

您应该能够通过以下方式阻止它,而不是隐藏控制台窗口:

cmd := exec.Command(...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x08000000} // CREATE_NO_WINDOW
Run Code Online (Sandbox Code Playgroud)


gon*_*utz 5

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

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

因此,我当前的解决方案是在没有标志的情况下进行构建,即在程序启动时有一个控制台窗口,然后在我的程序开始时立即使用以下代码隐藏控制台窗口:

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
    // http://stackoverflow.com/questions/9009333/how-to-check-if-the-program-is-run-from-a-console
    _, consoleProcID := w32.GetWindowThreadProcessId(console)
    if w32.GetCurrentProcessId() == consoleProcID {
        w32.ShowWindowAsync(console, w32.SW_HIDE)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

发生的情况是所有 exec.Commands 现在将其输出打印到隐藏的控制台窗口,而不是生成自己的。

这里的妥协是,当您启动它时,您的程序将闪烁一次控制台窗口,但只会在它隐藏之前短暂闪烁。