#### 同一段代码,在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
}
```
#### 谢谢!
1. 为什么你的代码放在 goroot 下面?
2. 排版混乱,一部分源码在代码板块里 一部分又不在
3. 学会自己Google Google搜索 crypto/ssh/terminal windows invalid handler 可以看到答案:https://github.com/golang/go/issues/20388
#2
更多评论
看到不好好排版的就不想看内容~~ markdown 语法能好好了解下吗?https://studygolang.com/markdown 几分钟的事情。而且网站发布前可以预览效果。
#1