golang ssh bak

Posted Cluster Note

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang ssh bak相关的知识,希望对你有一定的参考价值。

...

 

from https://stackoverflow.com/questions/44471749/golang-enter-ssh-sudo-password-on-prompt-or-exit

golang ssh sudo 

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("1.1.13.20:22", "uos", "uosuos")
	if err != nil {
		log.Fatal(err)
	}

	output, err := conn.SendCommands("sleep 3; ls /tmp")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(string(output)))

}

  

以上是关于golang ssh bak的主要内容,如果未能解决你的问题,请参考以下文章

golang代码片段(摘抄)

代码片段 - Golang 实现简单的 Web 服务器

代码片段 - Golang 实现集合操作

golang 实现ssh公钥登录

golang通过ssh实现远程文件传输

ansible Failed to connect to the host via ssh: no such identity: /root/.ssh/id_rsa.bak