summaryrefslogtreecommitdiff
path: root/shell.go
blob: 3492b33aa062efde7f800ed4cfc8e344bfbb0a0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main

import (
	"fmt"
	"net"
	"os"
	"os/exec"

	"golang.org/x/crypto/ssh"
)

func shell(conn net.Conn, config *ssh.ServerConfig) {
	sshConn, chans, reqs, err := ssh.NewServerConn(conn, config)
	if err != nil {
		fmt.Println("不能创建连接:", err)
		return
	}
	defer sshConn.Close()

	fmt.Println("New connection from", sshConn.RemoteAddr(), "with client version", sshConn.ClientVersion())

	go ssh.DiscardRequests(reqs)

	for newChannel := range chans {
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}

		channel, requests, err := newChannel.Accept()
		if err != nil {
			fmt.Println("Can not accept channel:", err)
			continue
		}
		defer channel.Close()

		shell := os.Getenv("SHELL")
		if shell == "" {
			shell = "cmd.exe"
		}

		command := exec.Command(shell)
		command.Stdin = channel
		command.Stdout = channel
		command.Stderr = channel

		if err := command.Start(); err != nil {
			fmt.Println("Failed to start shell:", err)
			return
		}

		go func() {
			if err := command.Wait(); err != nil {
				fmt.Println("Run shell failed:", err)
			}
			channel.Close()
		}()

		go func() {
			for req := range requests {
				switch req.Type {
				case "shell":
					req.Reply(true, nil)
				default:
					req.Reply(false, nil)
				}
			}
		}()
	}
}