Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Enter SSH Sudo Password on Prompt (or exit)

Tags:

linux

bash

ssh

go

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.

like image 292
Ari Seyhun Avatar asked Jan 22 '26 11:01

Ari Seyhun


2 Answers

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))
like image 144
Ari Seyhun Avatar answered Jan 24 '26 03:01

Ari Seyhun


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))

}
like image 26
Yanan Xu Avatar answered Jan 24 '26 05:01

Yanan Xu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!