2017-02-28 256 views
3

說我有下面的代碼,使用syscall隱藏命令行窗口在Golang中使用Exec時如何隱藏命令提示符窗口?

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

,但是當我編譯它,並試圖在Windows中運行它,命令行窗口中出現了再次

我能做些什麼防止出現命令行窗口?

PS我已經知道如何使用go build -ldflags -H=windowsgui,但這樣做既保證了程序本身不彈出一個命令行窗口,Exec將顯示這些窗口反正

+0

能否請您更精確地瞭解哪些提示您要隱藏? 你已經說過,正確的命令隱藏了兩個,Go命令行窗口和exec生成的窗口。我現在最好的猜測是你正在執行的命令會產生一個額外的窗口。 – Marco

+0

這也是可能的,我將檢查哪個命令產生命令提示符(儘管很快消失) –

+0

@ jm33_m0我剛剛嘗試過,在您的問題中的sysProcAttr方法,它是一個巨大的改進 - 窗口只是簡要地閃爍。你有沒有找到完全防止閃光的解決方案 – WebweaverD

回答

2

如果編譯golang源到一個Windows GUI可執行文件你用-ldflags -H=windowsgui構建,每個exec.Command將產生一個新的控制檯窗口。

如果你沒有標誌建立,你會得到一個控制檯窗口和所有exec.Commands打印到那個。

我目前的解決方案是這樣建立的標誌,即必須在程序啓動控制檯窗口,然後立即隱藏與此代碼在控制檯窗口中,在我的程序的啓動:

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

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) 
    } 
} 

this thread以獲取有關進程標識的詳細信息。

會發生什麼情況是所有exec.Commands現在將其輸出打印到隱藏的控制檯窗口而不是自己產生。

這裏的妥協是,當你啓動它時,你的程序會刷新一個控制檯窗口,但是隻有在它進入隱藏之前的一小段時間。

+0

@WebweaverD從什麼時候發生?我目前在Windows 8.1上,並沒有這樣的問題。該程序正常運行。 – gonutz

+1

我只在Win 7上看到過一個問題,而不是8,但我只是在Windows 7機器上重新測試了它,它確實在那裏工作 - 我不確定爲什麼我在之前嘗試過時出現錯誤 - 評論已移除避免混淆。回答upvoted,因爲我現在將使用這種方法 – WebweaverD

1

There是一個更好的解決方案,它可以運行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() 

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