普通网友 2016-11-07 23:09
浏览 47
已采纳

向同一子进程golang写入两次

I have a simple scp function that is just a wrapper over the scp cli tool.

type credential struct {
    username string
    password string
    host     string
    port     string
}

func scpFile(filepath, destpath string, c *credential) error {
    cmd := exec.Command("scp", filepath, c.username+"@"+c.host+":"+destpath)

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

    fmt.Println("done")
    return nil
}

This works just fine now I want to add the capability of putting in a password the SSH if scp needs it. This is what I came up with

func scpFile(filepath, destpath string, c *credential) error {
    cmd := exec.Command("scp", filepath, c.username+"@"+c.host+":"+destpath)
    stdin, err := cmd.StdinPipe()
    if err != nil {
        return err
    }
    defer stdin.Close()

    if err := cmd.Start(); err != nil {
        return err
    }

    io.WriteString(stdin, c.password+"
")
    cmd.Wait()
    fmt.Println("done")
    return nil
}

This does not work as the password prompt just hangs there. I tried adding a 1 second sleep before I re write to stdin thinking maybe I was writing the password to fast but did not make a difference.

  • 写回答

1条回答 默认 最新

  • douzong6649 2016-11-09 00:55
    关注

    So I was able to find a work around by instead of trying to send the password to stdin I create a ssh session and scp a file through the ssh session. Here is the new scpFile function:

    func scpFile(filePath, destinationPath string, session *ssh.Session) error {
        defer session.Close()
    
        f, err := os.Open(filePath)
        if err != nil {
            return err
        }
        defer f.Close()
    
        s, err := f.Stat()
        if err != nil {
            return err
        }
    
        go func() {
            w, _ := session.StdinPipe()
            defer w.Close()
            fmt.Fprintf(w, "C%#o %d %s
    ", s.Mode().Perm(), s.Size(), path.Base(filePath))
            io.Copy(w, f)
            fmt.Fprint(w, "\x00")
        }()
        cmd := fmt.Sprintf("scp -t %s", destinationPath)
        if err := session.Run(cmd); err != nil {
            return err
        }
        return nil
    }
    

    This could probably be made better but the main idea is there

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)