【问题标题】:Calling appcmd results in the wrong password being set调用 appcmd 会导致设置错误的密码
【发布时间】:2020-08-07 00:48:02
【问题描述】:

我正在尝试从 Go 中调用 appcmd。下面的代码显示成功,但密码设置错误。如果我删除内部引号(在 main 的第二行)它可以工作,但是当密码包含空格时它就不起作用了!现在加上引号,如果我在 cmd.exe 中输入与输出完全相同的命令,它就可以工作!那是什么鬼!为什么它可以直接在 cmd 中使用引号,而从 Go 调用时却不行?

我真的不想成为那种说你不能在密码中使用空格的人,因为我不知道为什么它不起作用!啊!

package main

import (
    "bytes"
    "fmt"
    "os/exec"
    "strconv"
    "strings"
    "syscall"
)

func main() {
    iisPath := "C:\\WINDOWS\\sysWOW64\\inetsrv\\"
    callAppcmd(iisPath, "-processModel.password:\"password\"")
}

func callAppcmd(iisPath string, param string) {
    stdOut, _, _, exitCode := runCommand(
        iisPath+"appcmd.exe",
        "set",
        "apppool",
        "/apppool.name:DefaultAppPool",
        param)

    printOut(stdOut)
    printOut(strconv.Itoa(exitCode))
}

func printOut(text string) {
    fmt.Println(text)
}

func runCommand(commands ...string) (string, string, error, int) {
    printOut(strings.Join(commands, " "))
    cmd := exec.Command(commands[0], commands[1:]...)
    cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()

    exitCode := 0

    if exitError, ok := err.(*exec.ExitError); ok {
        exitCode = exitError.ExitCode()
    }

    return out.String(), stderr.String(), err, exitCode
}

输出:

C:\WINDOWS\sysWOW64\inetsrv\appcmd.exe set apppool /apppool.name:DefaultAppPool -processModel.password:"password"
APPPOOL object "DefaultAppPool" changed

0

【问题讨论】:

  • 调用等效的 PowerShell cmdlet 可能是更好的选择。
  • 我不相信 PowerShell 适合我。
  • 那为什么其他人可以从 Go 调用 PowerShell? google.com/search?client=firefox-b-d&q=go+powershell
  • 我并不是说这不可能,我是说 PowerShell 不适用于该程序。我无法使用它。

标签: go iis appcmd


【解决方案1】:

似乎用反引号格式化字符串是一种解决方案,它不会自动转义并且可以正确处理引号。

cmd := exec.Command(`find`)
cmd.SysProcAttr.CmdLine = `find "SomeText" test.txt`

请参考以下链接。
exec with double quoted argument

【讨论】:

  • 谢谢!它实际上是使用 cmd.SysProcAttr.CmdLine 而不是仅仅将它全部推入 Command() 这对我来说有所不同。如果您可以更新您的答案以暗示这一点,我会接受它作为答案。
  • 对不起,我对 Go 不熟悉。感谢您的建议。我更新了它。另外,如果您愿意,请帮助我改进它。
猜你喜欢
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 2016-07-05
  • 2015-12-16
  • 2011-06-05
  • 2013-02-14
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多