gpt4 book ai didi

linux - 如何向 SSH 提供密码?

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

我需要使用经过密码验证的 scp 从服务器下载文件。我如何使用 Go 来做到这一点?尝试了下面的代码,但它没有传入密码。

package main

import (
"os/exec"
"time"
)

func main() {
password := "password"
cmd := exec.Command("scp", "admin@192.168.1.150:file", "file")

in, err := cmd.StdinPipe()
if err != nil {
panic(err)
}

defer in.Close()

out, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}

defer out.Close()

if err = cmd.Run(); err != nil {
panic(err)
}

go func() {
time.Sleep(10 * time.Second)
_, err = in.Write([]byte(password + "\n"))
if err != nil {
panic(err)
}
}()
}

编辑:我最终使用了 gexpect (github.com/ThomasRooney/gexpect) 库。

package main

import (
"github.com/ThomasRooney/gexpect"
"log"
)

func main() {
child, err := gexpect.Spawn("scp admin@192.168.1.150:file file")
if err != nil {
log.Fatalln(err)
}
child.Expect("password:")
child.SendLine("password")
child.Interact()
child.Close()
}

最佳答案

这个 self 回答的问题的答案可能会有所帮助:

Golang write input and get output from terminal process

至少,他在回答中提到他“能够使用密码进行 ssh 访问”,问题中没有明确提及这一点 - 这就是为什么您在搜索该站点时可能没有找到它的原因?

关于linux - 如何向 SSH 提供密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786190/

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