nezha/cmd/agent/pty/pty.go

62 lines
1.1 KiB
Go
Raw Normal View History

2021-08-18 05:42:26 -04:00
//go:build !windows
//+build !windows
package pty
import (
2021-08-18 12:04:09 -04:00
"errors"
2021-08-18 05:42:26 -04:00
"os"
"os/exec"
opty "github.com/creack/pty"
)
2021-08-18 12:04:09 -04:00
var defaultShells = []string{"zsh", "fish", "bash", "sh"}
2021-08-18 05:42:26 -04:00
type Pty struct {
tty *os.File
cmd *exec.Cmd
}
func DownloadDependency() {
}
func Start() (*Pty, error) {
2021-08-18 12:04:09 -04:00
var shellPath string
for i := 0; i < len(defaultShells); i++ {
shellPath, _ = exec.LookPath(defaultShells[i])
if shellPath != "" {
break
}
}
2021-08-18 05:42:26 -04:00
if shellPath == "" {
2021-08-18 12:04:09 -04:00
return nil, errors.New("没有可用终端")
2021-08-18 05:42:26 -04:00
}
cmd := exec.Command(shellPath)
cmd.Env = append(os.Environ(), "TERM=xterm")
tty, err := opty.Start(cmd)
return &Pty{tty: tty, cmd: cmd}, err
}
func (pty *Pty) Write(p []byte) (n int, err error) {
return pty.tty.Write(p)
}
func (pty *Pty) Read(p []byte) (n int, err error) {
return pty.tty.Read(p)
}
func (pty *Pty) Setsize(cols, rows uint32) error {
return opty.Setsize(pty.tty, &opty.Winsize{
Cols: uint16(cols),
Rows: uint16(rows),
})
}
func (pty *Pty) Close() error {
if err := pty.tty.Close(); err != nil {
return err
}
return pty.cmd.Process.Kill()
}