操作shell两种方式

交互式shell

package main import (
"golang.org/x/crypto/ssh" "log" "os" "fmt" ) func main() { ce := func(err error, msg string) { if err != nil { log.Fatalf("%s error: %v", msg, err) } } client, err := ssh.Dial("tcp", "192.168.154.131:22", &ssh.ClientConfig{ User: "root", Auth: []ssh.AuthMethod{ssh.Password("123456")}, }) if err !=nil{ fmt.Println("ERR") } session, err := client.NewSession() defer session.Close() session.Stdout = os.Stdout session.Stderr = os.Stderr session.Stdin = os.Stdin //下面的modes和RequestPty是为了防止出现交换机的时候错误 modes := ssh.TerminalModes{ ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400, } err = session.RequestPty("xterm", 25, 80, modes) //这里的session.Shell可以执行多条命令,但是session.Run只支持执行单条命令 err = session.Shell() ce(err, "start shell") err = session.Wait() }

执行命令式

package main

import (
    "golang.org/x/crypto/ssh"
    "os"
    "fmt"
    "bytes"
)

func main() {
    client, err := ssh.Dial("tcp", "192.168.154.131:22", &ssh.ClientConfig{
        User: "root",
        Auth: []ssh.AuthMethod{ssh.Password("123456")},
    })
    if err !=nil{
        fmt.Println("ssh Dial err",err)
    }
    session, err := client.NewSession()
    defer session.Close()
    var out bytes.Buffer
    session.Stdout = &out
    session.Stderr = os.Stderr
    session.Stdin = os.Stdin

  //下面的modes和RequestPty是为了防止出现交换机的时候错误,还有就是按照格式输出
    modes := ssh.TerminalModes{
        ssh.ECHO:          0,
        ssh.TTY_OP_ISPEED: 14400,
        ssh.TTY_OP_OSPEED: 14400,
    }
    err = session.RequestPty("xterm", 25, 80, modes)
    err=session.Run("ls")
    session.Run("ls")
    fmt.Println("ls output:",out.String())
    err = session.Wait()
}

 

posted @ 2018-08-27 18:00  pi-pi-miao-miao  阅读(1309)  评论(0编辑  收藏  举报