简体   繁体   中英

Golang Enter SSH Sudo Password on Prompt (or exit)

I'm trying to run a script via the SSH package in my Go program (so far I've had success).

My issue is, the script attempts to run a command with sudo if the user has sudo privileges, and this causes the bash script to pause until a password is entered by the user.

For example:

[ERROR ] Install cs-server: Checking dependencies: missing: lib32gcc1
# It attempts to install the missing dependencies with sudo but pauses here
[sudo] password for guest: 

In my Go program, I have written something that looks similar to this:

// Connect to SSH and retreive session...

out, err := session.StdoutPipe()
if err != nil {
    log.Fatal(err)
}

go func(out io.Reader) {
    r := bufio.NewScanner(out)
    for r.Scan() {
        fmt.Println(r.Text())
    }
}(out)

// Execute ssh command...

And I receive the exact same output as the example above, only in this case, I don't even see the line [sudo] password for guest: ... it only prints up to [ERROR ] Install cs-server: Checking dependencies: missing: lib32gcc1 and pauses forever.

How can I bypass this pause? My options are to either enter the password from my Go program automatically, or end the ssh execution and just receive the output.

I managed to fix this issue by making use of the session.StdoutPipe() and session.StdinPipe() . I wrote a go routine which scans each byte and checks if the last written line starts with "[sudo] password for " and ends with ": " . It will write the password + "\\n" to the session.StdinPipe() which continues execution of the script.

Here's all of the code I have for this.

package ssh

import (
    "bufio"
    "io"
    "log"
    "net"
    "strings"

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

type Connection struct {
    *ssh.Client
    password string
}

func Connect(addr, user, password string) (*Connection, error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err := ssh.Dial("tcp", addr, sshConfig)
    if err != nil {
        return nil, err
    }

    return &Connection{conn, password}, nil

}

func (conn *Connection) SendCommands(cmds ...string) ([]byte, error) {
    session, err := conn.NewSession()
    if err != nil {
        log.Fatal(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 {
        return []byte{}, err
    }

    in, err := session.StdinPipe()
    if err != nil {
        log.Fatal(err)
    }

    out, err := session.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }

    var output []byte

    go func(in io.WriteCloser, out io.Reader, output *[]byte) {
        var (
            line string
            r    = bufio.NewReader(out)
        )
        for {
            b, err := r.ReadByte()
            if err != nil {
                break
            }

            *output = append(*output, b)

            if b == byte('\n') {
                line = ""
                continue
            }

            line += string(b)

            if strings.HasPrefix(line, "[sudo] password for ") && strings.HasSuffix(line, ": ") {
                _, err = in.Write([]byte(conn.password + "\n"))
                if err != nil {
                    break
                }
            }
        }
    }(in, out, &output)

    cmd := strings.Join(cmds, "; ")
    _, err = session.Output(cmd)
    if err != nil {
        return []byte{}, err
    }

    return output, nil
}

And an example of how you could use it.

// ssh refers to the custom package above
conn, err := ssh.Connect("0.0.0.0:22", "username", "password")
if err != nil {
    log.Fatal(err)
}

output, err := conn.SendCommands("sleep 2", "echo Hello!")
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(output))

This is an issue that output stream can't be fully captured for @acidic's code. The updated code is as following

package main
import (
    "bytes"
    "fmt"
    "io"
    "log"
    "net"
    "strings"

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

type Connection struct {
    *ssh.Client
    password string
}

func Connect(addr, user, password string) (*Connection, error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err := ssh.Dial("tcp", addr, sshConfig)
    if err != nil {
        return nil, err
    }

    return &Connection{conn, password}, nil

}

func (conn *Connection) SendCommands(cmds string) ([]byte, error) {
    session, err := conn.NewSession()
    if err != nil {
        log.Fatal(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 {
        return []byte{}, err
    }

    stdoutB := new(bytes.Buffer)
    session.Stdout = stdoutB
    in, _ := session.StdinPipe()

    go func(in io.Writer, output *bytes.Buffer) {
        for {
            if strings.Contains(string(output.Bytes()), "[sudo] password for ") {
                _, err = in.Write([]byte(conn.password + "\n"))
                if err != nil {
                    break
                }
                fmt.Println("put the password ---  end .")
                break
            }
        }
    }(in, stdoutB)

    err = session.Run(cmds)
    if err != nil {
        return []byte{}, err
    }
    return stdoutB.Bytes(), nil
}

func main() {
    // ssh refers to the custom package above
    conn, err := Connect("0.0.0.0:22", "username", "password")
    if err != nil {
        log.Fatal(err)
    }

    output, err := conn.SendCommands("sudo docker ps")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(output))

}

A work around is converting sudo [cmd] to echo [password] | sudo -S [cmd] echo [password] | sudo -S [cmd] , it is not good, but working for me.

Another workaround if you dont want to use ssh library is to make a pseudo terminal using pty library. An extremely simple example as above

    import (
    "io"
    "os"
    "os/exec"
    "time"

    "github.com/creack/pty"
)

func main() {
    c := exec.Command("ssh", "<user>@<IP>")
    f, err := pty.Start(c)
    if err != nil {
        panic(err)
    }
    time.Sleep(2 * time.Second)
    f.Write([]byte("1234\n"))
    io.Copy(os.Stdout, f)
}


 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM