Interactive Shell
Package Mainimport ("Golang.org/x/crypto/ssh" "Log" "OS" "FMT"Func Main () {CE:= Func (err error, MSGstring) { ifErr! =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")}, }) ifErr! =nil{FMT. Println ("ERR")} session, err:=client. NewSession () Defer session. Close () session. Stdout=OS. Stdout session. Stderr=OS. Stderr session. Stdin=OS. Stdin//the following modes and Requestpty are designed to prevent errors when the switch is presentModes: =ssh. terminalmodes{ssh. ECHO:0, SSH. Tty_op_ispeed:14400, SSH. Tty_op_ospeed:14400,} Err= Session. Requestpty ("xterm", -, the, modes)//here's the session. The shell can execute multiple commands, but the session. Run only supports single command executionErr =session. Shell () CE (err,"Start Shell") Err=session. Wait ()}
To execute an imperative
Package Mainimport ("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")}, }) ifErr! =nil{FMT. Println ("ssh Dial Err", Err)} Session, ERR:=client. NewSession () Defer session. Close ()var outbytes. Buffer session. Stdout= & outsession. Stderr=OS. Stderr session. Stdin=OS. Stdin//the following modes and Requestpty are designed to prevent errors when the switch is present, as well as to output in the formatModes: =ssh. terminalmodes{ssh. ECHO:0, SSH. Tty_op_ispeed:14400, SSH. Tty_op_ospeed:14400,} Err= Session. Requestpty ("xterm", -, the, modes) Err=session. Run ("ls") session. Run ("ls") fmt. Println ("ls output:", out. String ()) Err=session. Wait ()}
Operation of the Shell two ways