gpt4 book ai didi

go - SSH 脚本使用 pty 和 io.Copy 通过菜单流式输出

转载 作者:行者123 更新时间:2023-12-01 22:20:29 34 4
gpt4 key购买 nike

我有两个问题需要帮助。我想我已经把它缩小到在 goroutine 中使用 io.Copy 。它的行为就像标准输入需要使用回车键“重新激活”。

  • 在循环的第一次迭代中,一切都按预期工作。它登录到 localhost,运行命令,goroutine 打印 stdout 和 stderr。但在随后的迭代中,我必须先按回车键“退出 goroutine”,然后才能在提示符下输入响应。我怀疑它与 os.Stdin 有关。有人可以提供一些建议吗?
  • 我可以在不中断脚本的情况下向 ssh 命令发送 sigterm 吗?例如,我可以中断 ping 输出,然后在菜单提示符处返回吗?

  • 感谢您提供的任何帮助。这是我在这里的第一篇文章。
    package main

    import (
    "fmt"
    "io"
    "log"
    "net"
    "os"
    "time"

    "golang.org/x/crypto/ssh"
    )

    var (
    stdout, stderr io.Reader
    stdin io.WriteCloser
    timeout = 30 * time.Second
    )

    func sshConfig() *ssh.ClientConfig {
    config := &ssh.ClientConfig{
    User: MYUSER,
    Auth: []ssh.AuthMethod{
    ssh.Password(MYPASS),
    },
    HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    Timeout: timeout,
    }
    return config
    }

    func options() {
    menuString := `
    Enter 1 for "uptime"
    Enter 2 for "ping -c 20 www.google.com"
    Type exit to exit
    `
    for i := 0; i <= 5; i++ {
    var num, cmd string
    fmt.Println(menuString)
    if i == 0 {
    fmt.Print("Select an option from above: ")
    } else {
    fmt.Println("You'll have to press enter before entering your option. Why?")
    fmt.Print("Select an option from above: ")
    }

    fmt.Scanln(&num)
    switch num {
    case "1":
    cmd = "uptime"
    connect(cmd)
    case "2":
    cmd = "ping -c 20 www.google.com"
    connect(cmd)
    case "exit":
    fmt.Println("exiting")
    os.Exit(0)
    default:
    fmt.Println("Invalid response")
    fmt.Println("Select an option from above: ")
    }
    }
    }

    func connect(c string) {
    config := sshConfig()
    conn, err := ssh.Dial("tcp", "127.0.0.1:22", config)
    defer conn.Close()
    if err != nil {
    log.Fatal("dial target error:", err)
    }
    session, err := conn.NewSession()
    defer session.Close()
    if err != nil {
    log.Fatalf("session failed:%v", err)
    }
    defer session.Close()
    modes := ssh.TerminalModes{
    ssh.ECHO: 0, // disable echoing
    ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
    ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
    }
    err = session.RequestPty("xterm", 80, 40, modes)
    if err != nil {
    log.Fatalf("Pty request failed:%v", err)
    }

    stdin, err = session.StdinPipe()
    if err != nil {
    log.Fatalf("Unable to setup stdin for session: %v", err)
    }
    stdout, err = session.StdoutPipe()
    if err != nil {
    log.Fatalf("Unable to setup stdout for session: %v", err)
    }
    stderr, err = session.StderrPipe()
    if err != nil {
    log.Fatalf("Unable to setup stderr for session: %v", err)
    }

    quit := make(chan bool)
    go func() {
    for {
    select {
    case <-quit:
    fmt.Println("exiting goroutine")
    return
    default:
    fmt.Println("go routine is running")
    io.Copy(os.Stdout, stdout)
    io.Copy(stdin, os.Stdin)
    io.Copy(os.Stderr, stderr)
    }
    }
    }()

    if err := session.Run(c); err != nil {
    log.Fatal("Failed to run: " + err.Error())
    }
    fmt.Println("closing the channel")
    close(quit)
    fmt.Println("the channel is closed")
    }

    func main() {
    options()
    }

    最佳答案

    首先,io.Copy 是一个阻塞调用,它将 io.writer 的缓冲区复制到 io.reader 直到在 src 上达到 EOF 或发生错误。 Here's来自 golang 的 io 模块的片段:

    // copyBuffer is the actual implementation of Copy and CopyBuffer.
    // if buf is nil, one is allocated.

    func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
    // If the reader has a WriteTo method, use it to do the copy.
    // Avoids an allocation and a copy.
    if wt, ok := src.(WriterTo); ok {
    return wt.WriteTo(dst)
    }
    // Similarly, if the writer has a ReadFrom method, use it to do the copy.
    if rt, ok := dst.(ReaderFrom); ok {
    return rt.ReadFrom(src)
    }
    if buf == nil {
    size := 32 * 1024
    if l, ok := src.(*LimitedReader); ok && int64(size) > l.N {
    if l.N < 1 {
    size = 1
    } else {
    size = int(l.N)
    }
    }
    buf = make([]byte, size)
    }
    for {
    nr, er := src.Read(buf)
    if nr > 0 {
    nw, ew := dst.Write(buf[0:nr])
    if nw > 0 {
    written += int64(nw)
    }
    if ew != nil {
    err = ew
    break
    }
    if nr != nw {
    err = ErrShortWrite
    break
    }
    }
    if er != nil {
    if er != EOF {
    err = er
    }
    break
    }
    }
    return written, err
    }
    现在回答你的问题
    当在第一次迭代中对 session 的 stdin 和 stderr 进行 io.copy 调用时,它会等到 stderr 和 stdin 上有一条消息被复制并被阻止。
    只需将您的 goroutine 替换为复制 stdout 即可为您提供每次迭代的预期行为。类似地,stderr,stdin 需要由它们自己的 goroutine 管理:
    go func() {
    for {
    io.Copy(os.Stdout, stdout)
    }
    }()
    SigTerm 将用于终止 session ,有一个称为中断的 posix 信号可用于中断 cmd。 Here's一个列表 os all POSIX 表明您使用的 ssh 库支持。
    这是中断信号和预期行为的演示:
    package main

    import (
    "fmt"
    "io"
    "log"
    "net"
    "os"
    "time"

    "golang.org/x/crypto/ssh"
    )

    var (
    stdout, stderr io.Reader
    stdin io.WriteCloser
    timeout = 30 * time.Second
    )

    const (
    MYUSER = ""
    MYPASS = ""
    )

    func sshConfig() *ssh.ClientConfig {
    config := &ssh.ClientConfig{
    User: MYUSER,
    Auth: []ssh.AuthMethod{
    ssh.Password(MYPASS),
    },
    HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    Timeout: timeout,
    }
    return config
    }

    func options() {
    menuString := `
    Enter 1 for "uptime"
    Enter 2 for "ping -c 20 www.google.com"
    Type exit to exit
    `
    for i := 0; i <= 5; i++ {
    var num, cmd string
    fmt.Println(menuString)
    if i == 0 {
    fmt.Print("Select an option from above: ")
    } else {
    fmt.Println("You'll have to press enter before entering your option. Why?")
    fmt.Print("Select an option from above: ")
    }

    fmt.Scanln(&num)
    switch num {
    case "1":
    cmd = "uptime"
    connect(cmd)
    case "2":
    cmd = "ping -c 20 www.google.com"
    connect(cmd)
    case "exit":
    fmt.Println("exiting")
    os.Exit(0)
    default:
    fmt.Println("Invalid response")
    fmt.Println("Select an option from above: ")
    }
    }
    }

    func connect(c string) {
    config := sshConfig()
    conn, err := ssh.Dial("tcp", "127.0.0.1:22", config)
    defer conn.Close()
    if err != nil {
    log.Fatal("dial target error:", err)
    }
    session, err := conn.NewSession()
    defer session.Close()
    if err != nil {
    log.Println("session failed:%v", err)
    }
    defer session.Close()
    modes := ssh.TerminalModes{
    ssh.ECHO: 0, // disable echoing
    ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
    ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
    }
    err = session.RequestPty("xterm", 80, 40, modes)
    if err != nil {
    log.Fatalf("Pty request failed:%v", err)
    }

    stdin, err = session.StdinPipe()
    if err != nil {
    log.Fatalf("Unable to setup stdin for session: %v", err)
    }
    stdout, err = session.StdoutPipe()
    if err != nil {
    log.Fatalf("Unable to setup stdout for session: %v", err)
    }
    stderr, err = session.StderrPipe()
    if err != nil {
    log.Fatalf("Unable to setup stderr for session: %v", err)
    }

    go func() {
    for {
    io.Copy(os.Stdout, stdout)
    }
    }()

    c = "echo 'go is awesome' && sleep 10 && " + c
    go func() {
    time.Sleep(1 * time.Second)
    session.Signal(ssh.SIGINT)
    }()

    if err := session.Run(c); err != nil {
    log.Println("Failed to run: " + err.Error())
    }
    fmt.Println("closing the channel")
    fmt.Println("the channel is closed")
    }

    func main() {
    options()
    }

    关于go - SSH 脚本使用 pty 和 io.Copy 通过菜单流式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63865791/

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