nezha/cmd/agent/pty/pty.go

74 lines
1.4 KiB
Go
Raw Normal View History

2021-08-18 05:42:26 -04:00
//go:build !windows
// +build !windows
2021-08-18 05:42:26 -04:00
package pty
import (
2021-08-18 12:04:09 -04:00
"errors"
2021-08-18 05:42:26 -04:00
"os"
"os/exec"
"syscall"
2021-08-18 05:42:26 -04:00
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
}
2021-09-04 00:42:51 -04:00
cmd := exec.Command(shellPath) // #nosec
2021-08-18 05:42:26 -04:00
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) killChildProcess(c *exec.Cmd) error {
pgid, err := syscall.Getpgid(c.Process.Pid)
if err != nil {
// Fall-back on error. Kill the main process only.
c.Process.Kill()
}
// Kill the whole process group.
syscall.Kill(-pgid, syscall.SIGKILL) // SIGKILL 直接杀掉 SIGTERM 发送信号,等待进程自己退出
return c.Wait()
}
2021-08-18 05:42:26 -04:00
func (pty *Pty) Close() error {
if err := pty.tty.Close(); err != nil {
return err
}
return pty.killChildProcess(pty.cmd)
2021-08-18 05:42:26 -04:00
}