#### 同一段代码,在linux 里运行正常, 在windows下面运行报 The handle is invalid.
![Capture.PNG](https://static.studygolang.com/190425/3eac479022d5a0e43e7fb40e85ee2e7d.PNG)
#### 下面是源码
```go
package main
import (
"go_ssh1/conn"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
"log"
"os"
)
func main() {
session, err := conn.Connect("root", "xxx", "192.168.1.1", 22)
if err != nil {
log.Fatal(err)
}
defer session.Close()
fd := int(os.Stdin.Fd())
oldState, err := terminal.MakeRaw(fd) // winodws 下MakeRam handle is invalid.
if err != nil {
panic(err)
}
defer terminal.Restore(fd, oldState)
//excute command
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Stdin = os.Stdin
termWidth, termHeight, err := terminal.GetSize(fd)
if err != nil {
panic(err)
}
//Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm-256color", termHeight, termWidth, modes); err != nil {
log.Fatal(err)
}
session.Run("top")
}
--------------------------------
connect.go
import (
"fmt"
"golang.org/x/crypto/ssh"
"net"
"time"
)
func Connect(user, password, host string, port int) (*ssh.Session, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
client *ssh.Client
session *ssh.Session
err error
)
// get auth method
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 30 * time.Second,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
addr = fmt.Sprintf("%s:%d", host, port)
if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
if session, err = client.NewSession(); err != nil {
return nil, err
}
return session, nil
}
```
#### 谢谢!
有疑问加站长微信联系(非本文作者)