package main
import (
"fmt"
cssh "golang.org/x/crypto/ssh"
"io"
"time"
)
func handleError(err error) {
if err != nil {
panic(err)
}
}
func readBuffForString(sshOut io.Reader) string {
buf := make([]byte, 1000)
n, err := sshOut.Read(buf) //this reads the ssh terminal
waitingString := ""
if err == nil {
for _, v := range buf[:n] {
fmt.Printf("%c", v)
}
waitingString = string(buf[:n])
}
for err == nil {
// this loop will not end!!
n, err = sshOut.Read(buf)
waitingString += string(buf[:n])
for _, v := range buf[:n] {
fmt.Printf("%c", v)
}
if err != nil {
fmt.Println(err)
}
}
return waitingString
}
func write(cmd string, sshIn io.WriteCloser) {
_, err := sshIn.Write([]byte(cmd + "\r"))
handleError(err)
}
func main() {
// create a new connection
conn, err := cssh.Dial("tcp", "172.16.240.189:22", &cssh.ClientConfig{
User: "admin",
Auth: []cssh.AuthMethod{cssh.Password("r00ttest")},
HostKeyCallback: cssh.InsecureIgnoreHostKey(),
Timeout: 5 * time.Second,
})
if err != nil {
fmt.Println(err)
}
session, err := conn.NewSession()
handleError(err)
sshOut, err := session.StdoutPipe()
handleError(err)
sshIn, err := session.StdinPipe()
err = session.Shell()
handleError(err)
write("configure", sshIn)
readBuffForString(sshOut)
session.Close()
conn.Close()
}
the loop in readBuffForString will not end