gpt4 book ai didi

ssh - GO - 通过 ssh 连接执行命令时出现未知错误

转载 作者:IT王子 更新时间:2023-10-29 02:23:45 24 4
gpt4 key购买 nike

我正在尝试通过 ssh 连接通过 session.Run() 函数执行命令。到目前为止,我可以成功执行一些命令,但在执行其他命令时,我不断收到以下错误:"Process exited with: 1. Reason was: () exit status 1"

func (p *project) connect(config *ssh.ClientConfig) {

log.Printf("Trying connection...\n")

conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", p.hostname.name, p.port.name), config)
checkError("Failed to dial: ", err)
log.Printf("Connection established.\n")

for step := range p.typ.program.setup {
p.install(step, conn)
}
}

func (p *project) install(step int, conn *ssh.Client) {
session, err := conn.NewSession()
checkError("Failed to build session: ", err)
defer session.Close()

var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf

log.Printf("Executing command: %s", p.typ.program.setup[step])

if err := session.Run(p.typ.program.setup[step]); err != nil {
log.Println(session.Stdout)
log.Fatal("Error on command execution", err.Error())
}
}


// That would be an example of a command which returns me an error
// "cd ~/www/www/ && git commit -m 'on the beginning was the commit'"
// That comes inside a slice on p.typ.program.setup accessed by the step(index).

命令输出 (session.Stdout) 是我所期望的:

 "# On branch master nothing to commit, working directory clean"

请注意,我已经尝试直接在控制台上执行该命令,而且效果很好。

所以,代码似乎没问题,命令在 Remote 上运行,但无论如何我仍然有错误。

有人知道为什么会这样吗?

提前致谢。

最佳答案

也许我的图书馆会对您有所帮助:https://github.com/shagabutdinov/shell ;它涵盖了在一个 session 中运行 ssh 命令的基本情况。

尝试以下操作:

handler := func(outputType int, message string) {
if(outputType == shell.Stdout) {
log.Println("stdout: ", message)
} else if(outputType == shell.Stdout) {
log.Println("stderr: ", message)
}
}

key, err := ssh.ParsePrivateKey([]byte(YOUR_PRIVATE_KEY))
if(err != nil) {
panic(err)
}

auth := []ssh.AuthMethod{ssh.PublicKeys(key)}
shell = shell.NewRemote(shell.RemoteConfig{
Host: "root@example.com:22",
Auth: auth,
})

if(err != nil) {
panic(err)
}

status, err := shell.Run("cd ~/www/www/", handler)
if(err != nil) {
panic(err)
}

status, err := shell.Run("git commit -m 'on the beginning was the commit'", handler)
if(err != nil) {
panic(err)
}

if(status == 0) {
console.log("command executed successfully")
} else {
console.log("command execution failed")
}

关于ssh - GO - 通过 ssh 连接执行命令时出现未知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com