feat: 添加UPF N3 Ping测试功能
This commit is contained in:
@@ -4,7 +4,9 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
gossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
@@ -50,6 +52,57 @@ func (s *SSHClientSession) Read() []byte {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
// RunCMD 执行单次命令
|
||||
func (s *SSHClientSession) RunCMD(cmd string) (string, error) {
|
||||
// 写入命令
|
||||
if cmd != "" {
|
||||
if _, err := s.Write(cmd + "\n"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
// 超时退出 120s
|
||||
timeoutTicker := time.NewTicker(120 * time.Second)
|
||||
defer timeoutTicker.Stop()
|
||||
// 实时读取SSH消息直接输出
|
||||
msTicker := time.NewTicker(100 * time.Millisecond)
|
||||
defer msTicker.Stop()
|
||||
// 消息缓冲区
|
||||
var buf bytes.Buffer
|
||||
defer buf.Reset()
|
||||
for {
|
||||
select {
|
||||
case <-timeoutTicker.C:
|
||||
return "", fmt.Errorf("ssh session timeout")
|
||||
case <-msTicker.C:
|
||||
outputByte := s.Read()
|
||||
if len(outputByte) <= 0 {
|
||||
continue
|
||||
}
|
||||
outputStr := string(outputByte)
|
||||
buf.WriteString(outputStr)
|
||||
|
||||
// 命令终止符后继续执行命令
|
||||
// "~]# ":麒麟, "~]$ ":欧拉, "~# ":NXP, "~$ ":Ubuntu
|
||||
suffixStr := []string{"~]# ", "~]$ ", "~# ", "~$ "}
|
||||
suffix := false
|
||||
for _, v := range suffixStr {
|
||||
if strings.HasSuffix(outputStr, v) {
|
||||
suffix = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !suffix {
|
||||
suffix = strings.LastIndex(outputStr, "# ") != -1 // 特殊内容中的终端终止符
|
||||
}
|
||||
if suffix {
|
||||
return buf.String(), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// singleWriter SSH客户端会话消息
|
||||
type singleWriter struct {
|
||||
b bytes.Buffer
|
||||
|
||||
Reference in New Issue
Block a user