码迷,mamicode.com
首页 > 其他好文 > 详细

golang ssh bak

时间:2021-06-10 18:09:09      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:rom   contains   lap   ble   main   cli   word   xterm   on()   

...

 

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

标签:rom   contains   lap   ble   main   cli   word   xterm   on()   

原文地址:https://www.cnblogs.com/eiguleo/p/14869471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!