feat: 移除ssh客户端改为本地bash

This commit is contained in:
TsMask
2025-05-13 17:22:04 +08:00
parent 552abb411c
commit f7f63f1950
21 changed files with 526 additions and 590 deletions

View File

@@ -4,11 +4,11 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"be.ems/src/framework/cmd"
"be.ems/src/framework/constants" "be.ems/src/framework/constants"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/token" "be.ems/src/framework/token"
"be.ems/src/framework/utils/cmd"
"be.ems/src/framework/utils/machine" "be.ems/src/framework/utils/machine"
"be.ems/src/modules/auth/service" "be.ems/src/modules/auth/service"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
@@ -137,7 +137,7 @@ func (s *BootloaderController) Reset(c *gin.Context) {
// return fmt.Errorf("not support window") // return fmt.Errorf("not support window")
} else { } else {
// 重置数据库 // 重置数据库
if _, err := cmd.Execf("sudo cp -rf /usr/local/omc/etc/db/omc_db.sqlite /usr/local/omc/database/omc_db.sqlite"); err != nil { if _, err := cmd.Exec("sudo cp -rf /usr/local/omc/etc/db/omc_db.sqlite /usr/local/omc/database/omc_db.sqlite"); err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -575,25 +575,29 @@ func (s *UDMAuthController) Import(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFileAbsPath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath)) neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { // if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
// c.JSON(200, resp.ErrMsg("error uploading file"))
// return
// }
if err := file.CopyFile(localFilePath, neFilePath); err != nil {
c.JSON(200, resp.ErrMsg("error uploading file")) c.JSON(200, resp.ErrMsg("error uploading file"))
return return
} }

View File

@@ -573,25 +573,29 @@ func (s *UDMSubController) Import(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFileAbsPath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath)) neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { // if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
// c.JSON(200, resp.ErrMsg("error uploading file"))
// return
// }
if err := file.CopyFile(localFilePath, neFilePath); err != nil {
c.JSON(200, resp.ErrMsg("error uploading file")) c.JSON(200, resp.ErrMsg("error uploading file"))
return return
} }

View File

@@ -503,25 +503,29 @@ func (s *UDMVOIPController) Import(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFileAbsPath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath)) neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { // if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
// c.JSON(200, resp.ErrMsg("error uploading file"))
// return
// }
if err := file.CopyFile(localFilePath, neFilePath); err != nil {
c.JSON(200, resp.ErrMsg("error uploading file")) c.JSON(200, resp.ErrMsg("error uploading file"))
return return
} }

View File

@@ -532,25 +532,29 @@ func (s *UDMVolteIMSController) Import(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFileAbsPath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath)) neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { // if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
// c.JSON(200, resp.ErrMsg("error uploading file"))
// return
// }
if err := file.CopyFile(localFilePath, neFilePath); err != nil {
c.JSON(200, resp.ErrMsg("error uploading file")) c.JSON(200, resp.ErrMsg("error uploading file"))
return return
} }

View File

@@ -9,10 +9,10 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"be.ems/src/framework/cmd"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/generate" "be.ems/src/framework/utils/generate"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -66,27 +66,32 @@ func (s *NeActionController) PushFile(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFileAbsPath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
// 网元端临时目录 // 网元端临时目录
sshClient.RunCMD("mkdir -p /tmp/omc/push && sudo chmod 777 -R /tmp/omc") // sshClient.RunCMD("mkdir -p /tmp/omc/push && sudo chmod 777 -R /tmp/omc")
cmd.Exec("mkdir -p /tmp/omc/push && sudo chmod 777 -R /tmp/omc")
neFilePath := filepath.ToSlash(filepath.Join("/tmp/omc/push", filepath.Base(localFilePath))) neFilePath := filepath.ToSlash(filepath.Join("/tmp/omc/push", filepath.Base(localFilePath)))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { // if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
// c.JSON(200, resp.ErrMsg("Please check if the file exists or if scp is allowed to copy remotely"))
// return
// }
if err := file.CopyFile(localFilePath, neFilePath); err != nil {
c.JSON(200, resp.ErrMsg("Please check if the file exists or if scp is allowed to copy remotely")) c.JSON(200, resp.ErrMsg("Please check if the file exists or if scp is allowed to copy remotely"))
return return
} }
@@ -139,19 +144,19 @@ func (s *NeActionController) PullFile(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName)) nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName))
fileName := generate.Code(6) + "_" + querys.FileName fileName := generate.Code(6) + "_" + querys.FileName
@@ -160,7 +165,11 @@ func (s *NeActionController) PullFile(c *gin.Context) {
localFilePath = fmt.Sprintf("C:%s", localFilePath) localFilePath = fmt.Sprintf("C:%s", localFilePath)
} }
// 复制到本地 // 复制到本地
if err = sftpClient.CopyFileRemoteToLocal(nePath, localFilePath); err != nil { // if err = sftpClient.CopyFileRemoteToLocal(nePath, localFilePath); err != nil {
// c.JSON(200, resp.ErrMsg(err.Error()))
// return
// }
if err := file.CopyFile(nePath, localFilePath); err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -211,19 +220,19 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
nePath := querys.Path nePath := querys.Path
dirName := generate.Code(6) dirName := generate.Code(6)
@@ -233,7 +242,11 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
} }
// 复制到本地 // 复制到本地
localDirFilePath := filepath.Join(localFilePath, "zip") localDirFilePath := filepath.Join(localFilePath, "zip")
if err = sftpClient.CopyDirRemoteToLocal(nePath, localDirFilePath); err != nil { // if err = sftpClient.CopyDirRemoteToLocal(nePath, localDirFilePath); err != nil {
// c.JSON(200, resp.ErrMsg(err.Error()))
// return
// }
if err := file.CopyDir(nePath, localDirFilePath); err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -292,17 +305,17 @@ func (s *NeActionController) ViewFile(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元端文件 // 网元端文件
nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName)) nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName))
// 网元端临时目录 // 网元端临时目录
output, err := sshClient.RunCMD(fmt.Sprintf("cat %s", nePath)) output, err := cmd.Execf("cat %s", nePath)
output = strings.TrimSpace(output) output = strings.TrimSpace(output)
if err != nil || strings.HasPrefix(output, "ls: ") { if err != nil || strings.HasPrefix(output, "ls: ") {
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "file view cat error"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "file view cat error")))
@@ -330,7 +343,6 @@ func (s *NeActionController) ViewFile(c *gin.Context) {
// @Description List of files on the network element side // @Description List of files on the network element side
// @Router /ne/action/files [get] // @Router /ne/action/files [get]
func (s *NeActionController) Files(c *gin.Context) { func (s *NeActionController) Files(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var querys struct { var querys struct {
NeType string `form:"neType" binding:"required"` NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"` NeID string `form:"neId" binding:"required"`
@@ -345,28 +357,28 @@ func (s *NeActionController) Files(c *gin.Context) {
return return
} }
// 查询网元获取IP // // 查询网元获取IP
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID) // neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { // if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) // c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return // return
} // }
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 获取文件列表 // 获取文件列表
rows, err := ssh.FileList(sshClient, querys.Path, querys.Search) rows, err := file.FileList(querys.Path, querys.Search)
if err != nil { if err != nil {
c.JSON(200, resp.OkData(map[string]any{ c.JSON(200, resp.OkData(map[string]any{
"path": querys.Path, "path": querys.Path,
"total": len(rows), "total": len(rows),
"rows": []ssh.FileListRow{}, "rows": []file.FileListRow{},
})) }))
return return
} }
@@ -375,9 +387,9 @@ func (s *NeActionController) Files(c *gin.Context) {
lenNum := int64(len(rows)) lenNum := int64(len(rows))
start := (querys.PageNum - 1) * querys.PageSize start := (querys.PageNum - 1) * querys.PageSize
end := start + querys.PageSize end := start + querys.PageSize
var splitRows []ssh.FileListRow var splitRows []file.FileListRow
if start >= lenNum { if start >= lenNum {
splitRows = []ssh.FileListRow{} splitRows = []file.FileListRow{}
} else if end >= lenNum { } else if end >= lenNum {
splitRows = rows[start:] splitRows = rows[start:]
} else { } else {

View File

@@ -1,7 +1,6 @@
package controller package controller
import ( import (
"encoding/json"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@@ -10,7 +9,6 @@ import (
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/modules/network_element/model" "be.ems/src/modules/network_element/model"
@@ -209,133 +207,3 @@ func (s NeConfigBackupController) Export(c *gin.Context) {
s.neConfigBackupService.Insert(item) s.neConfigBackupService.Insert(item)
c.FileAttachment(item.Path, item.Name) c.FileAttachment(item.Path, item.Name)
} }
// 网元配置文件备份-设置FTP配置
//
// POST /ftp
func (s NeConfigBackupController) SetFTP(c *gin.Context) {
var body struct {
Password string `json:"password" `
Username string `json:"username" binding:"required"`
ToIp string `json:"toIp" binding:"required"`
ToPort int64 `json:"toPort" binding:"required"`
Enable bool `json:"enable"`
Dir string `json:"dir" binding:"required"`
}
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 获取配置
cfg := s.sysConfigService.FindByKey("ne.neConfigBackupFTP")
if cfg.ConfigId > 0 {
byteData, err := json.Marshal(body)
if err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
cfg.ConfigValue = string(byteData)
cfg.UpdateBy = reqctx.LoginUserToUserName(c)
systemService.NewSysConfig.UpdateEncryptValue(cfg)
}
c.JSON(200, resp.Ok(nil))
}
// 网元配置文件备份-获取FTP配置
//
// GET /ftp
func (s NeConfigBackupController) GetFTP(c *gin.Context) {
// 获取配置
cfg := s.sysConfigService.FindByKeyDecryptValue("ne.neConfigBackupFTP")
if cfg.ConfigId > 0 {
var body struct {
Password string `json:"password" `
Username string `json:"username" binding:"required"`
ToIp string `json:"toIp" binding:"required"`
ToPort int64 `json:"toPort" binding:"required"`
Enable bool `json:"enable"`
Dir string `json:"dir" binding:"required"`
}
if err := json.Unmarshal([]byte(cfg.ConfigValue), &body); err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, resp.OkData(body))
return
}
c.JSON(200, resp.Ok(nil))
}
// 网元配置文件备份-文件FTP发送
//
// PUT /ftp
func (s NeConfigBackupController) PutFTP(c *gin.Context) {
var body struct {
FilePath string `json:"path" binding:"required"`
}
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 判断文件是否存在
if _, err := os.Stat(body.FilePath); os.IsNotExist(err) {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
// 获取配置
var cfgData struct {
Password string `json:"password" `
Username string `json:"username" binding:"required"`
ToIp string `json:"toIp" binding:"required"`
ToPort int64 `json:"toPort" binding:"required"`
Enable bool `json:"enable"`
Dir string `json:"dir" binding:"required"`
}
cfg := s.sysConfigService.FindByKeyDecryptValue("ne.neConfigBackupFTP")
if cfg.ConfigId > 0 {
if err := json.Unmarshal([]byte(cfg.ConfigValue), &cfgData); err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
}
if !cfgData.Enable {
c.JSON(200, resp.ErrMsg("Setting Remote Backup is disabled"))
return
}
connSSH := ssh.ConnSSH{
User: cfgData.Username,
Password: cfgData.Password,
Addr: cfgData.ToIp,
Port: cfgData.ToPort,
AuthMode: "0",
}
sshClient, err := connSSH.NewClient()
if err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sftpClient.Close()
// 远程文件
remotePath := filepath.Join(cfgData.Dir, "/ne_config", filepath.Base(body.FilePath))
// 复制到远程
if err = sftpClient.CopyFileLocalToRemote(body.FilePath, remotePath); err != nil {
c.JSON(200, resp.ErrMsg("error uploading file"))
return
}
c.JSON(200, resp.Ok(nil))
}

View File

@@ -7,6 +7,7 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/utils/date" "be.ems/src/framework/utils/date"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/modules/network_element/model" "be.ems/src/modules/network_element/model"
@@ -80,23 +81,27 @@ func (s NeConfigBackup) FileLocalToNe(neInfo model.NeInfo, localFile string) err
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := NewNeInfo.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := NewNeInfo.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
return fmt.Errorf("ne info ssh client err") // return fmt.Errorf("ne info ssh client err")
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return fmt.Errorf("ne info sftp client err") // return fmt.Errorf("ne info sftp client err")
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 网元配置端上的临时目录 // 网元配置端上的临时目录
neDirTemp := fmt.Sprintf("/tmp/omc/ne_config/%s/%s", neTypeLower, neInfo.NeId) neDirTemp := fmt.Sprintf("/tmp/omc/ne_config/%s/%s", neTypeLower, neInfo.NeId)
sshClient.RunCMD(fmt.Sprintf("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc && sudo rm -rf %s", neDirTemp)) // sshClient.RunCMD(fmt.Sprintf("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc && sudo rm -rf %s", neDirTemp))
cmd.Execf("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc && sudo rm -rf %s", neDirTemp)
// 复制到网元端 // 复制到网元端
if err = sftpClient.CopyDirLocalToRemote(localDirPath, neDirTemp); err != nil { // if err = sftpClient.CopyDirLocalToRemote(localDirPath, neDirTemp); err != nil {
// return fmt.Errorf("copy config to ne err")
// }
if err := file.CopyDir(localDirPath, neDirTemp); err != nil {
return fmt.Errorf("copy config to ne err") return fmt.Errorf("copy config to ne err")
} }
@@ -105,45 +110,45 @@ func (s NeConfigBackup) FileLocalToNe(neInfo model.NeInfo, localFile string) err
// ims目录 // ims目录
imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manages.yaml", "pcscf", "scscf", "vars.cfg", "zlog"} imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manages.yaml", "pcscf", "scscf", "vars.cfg", "zlog"}
for _, v := range imsDirArr { for _, v := range imsDirArr {
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p /usr/local/etc/ims && sudo cp -rf %s/ims/%s /usr/local/etc/ims/%v && sudo chmod 755 -R /usr/local/etc/ims/%s", neDirTemp, v, v, v)) cmd.Execf("sudo mkdir -p /usr/local/etc/ims && sudo cp -rf %s/ims/%s /usr/local/etc/ims/%v && sudo chmod 755 -R /usr/local/etc/ims/%s", neDirTemp, v, v, v)
} }
// mf目录 // mf目录
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p /usr/local/etc/mf && sudo cp -rf %s/mf/* /usr/local/etc/mf && sudo chmod 755 -R /usr/local/etc/mf", neDirTemp)) cmd.Execf("sudo mkdir -p /usr/local/etc/mf && sudo cp -rf %s/mf/* /usr/local/etc/mf && sudo chmod 755 -R /usr/local/etc/mf", neDirTemp)
// rtproxy目录 // rtproxy目录
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p /usr/local/etc/rtproxy && sudo cp -rf %s/rtproxy/* /usr/local/etc/rtproxy && sudo chmod 755 /usr/local/etc/rtproxy/rtproxy.conf", neDirTemp)) cmd.Execf("sudo mkdir -p /usr/local/etc/rtproxy && sudo cp -rf %s/rtproxy/* /usr/local/etc/rtproxy && sudo chmod 755 /usr/local/etc/rtproxy/rtproxy.conf", neDirTemp)
// iwf目录 // iwf目录
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p /usr/local/etc/iwf && sudo cp -rf %s/iwf/* /usr/local/etc/iwf && sudo chmod 755 /usr/local/etc/iwf/*.yaml", neDirTemp)) cmd.Execf("sudo mkdir -p /usr/local/etc/iwf && sudo cp -rf %s/iwf/* /usr/local/etc/iwf && sudo chmod 755 /usr/local/etc/iwf/*.yaml", neDirTemp)
} else if neTypeLower == "smsc" { } else if neTypeLower == "smsc" {
chmodFile := "sudo chmod 755 /usr/local/etc/smsc/{*sys.conf,*conf.txt,conf/is41_operation.conf}" chmodFile := "sudo chmod 755 /usr/local/etc/smsc/{*sys.conf,*conf.txt,conf/is41_operation.conf}"
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p /usr/local/etc/smsc/conf && sudo cp -rf %s/* /usr/local/etc/smsc && %s", neDirTemp, chmodFile)) cmd.Execf("sudo mkdir -p /usr/local/etc/smsc/conf && sudo cp -rf %s/* /usr/local/etc/smsc && %s", neDirTemp, chmodFile)
} else { } else {
neEtcPath := fmt.Sprintf("/usr/local/etc/%s", neTypeLower) neEtcPath := fmt.Sprintf("/usr/local/etc/%s", neTypeLower)
chmodFile := fmt.Sprintf("sudo chmod 755 %s/*.yaml", neEtcPath) chmodFile := fmt.Sprintf("sudo chmod 755 %s/*.yaml", neEtcPath)
if neTypeLower == "mme" { if neTypeLower == "mme" {
chmodFile = fmt.Sprintf("sudo chmod 755 %s/*.{yaml,conf}", neEtcPath) chmodFile = fmt.Sprintf("sudo chmod 755 %s/*.{yaml,conf}", neEtcPath)
} }
sshClient.RunCMD(fmt.Sprintf("sudo cp -rf %s/* %s && %s", neDirTemp, neEtcPath, chmodFile)) cmd.Execf("sudo cp -rf %s/* %s && %s", neDirTemp, neEtcPath, chmodFile)
} }
_ = os.RemoveAll(localDirPath) // 删除本地临时目录 _ = os.RemoveAll(localDirPath) // 删除本地临时目录
sshClient.RunCMD(fmt.Sprintf("sudo rm -rf %s", neDirTemp)) // 删除临时目录 cmd.Execf("sudo rm -rf %s", neDirTemp) // 删除临时目录
return nil return nil
} }
// FileNeToLocal 网元备份文件网元端复制到本地 // FileNeToLocal 网元备份文件网元端复制到本地
func (s NeConfigBackup) FileNeToLocal(neInfo model.NeInfo) (string, error) { func (s NeConfigBackup) FileNeToLocal(neInfo model.NeInfo) (string, error) {
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := NewNeInfo.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := NewNeInfo.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
return "", fmt.Errorf("ne info ssh client err") // return "", fmt.Errorf("ne info ssh client err")
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return "", fmt.Errorf("ne info sftp client err") // return "", fmt.Errorf("ne info sftp client err")
} // }
defer sftpClient.Close() // defer sftpClient.Close()
neTypeLower := strings.ToLower(neInfo.NeType) neTypeLower := strings.ToLower(neInfo.NeType)
// 网管本地路径 // 网管本地路径
@@ -154,34 +159,34 @@ func (s NeConfigBackup) FileNeToLocal(neInfo model.NeInfo) (string, error) {
localDirPath := fmt.Sprintf("%s/%s/%s/from_ne_tmp", omcPath, neTypeLower, neInfo.NeId) localDirPath := fmt.Sprintf("%s/%s/%s/from_ne_tmp", omcPath, neTypeLower, neInfo.NeId)
// 网元配置文件先复制到临时目录 // 网元配置文件先复制到临时目录
sshClient.RunCMD("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc") cmd.Exec("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc")
neDirTemp := fmt.Sprintf("/tmp/omc/ne_config/%s/%s", neTypeLower, neInfo.NeId) neDirTemp := fmt.Sprintf("/tmp/omc/ne_config/%s/%s", neTypeLower, neInfo.NeId)
if neTypeLower == "ims" { if neTypeLower == "ims" {
// ims目录 // ims目录
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s/ims", neDirTemp)) cmd.Execf("mkdir -p %s/ims", neDirTemp)
imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manages.yaml", "pcscf", "scscf", "vars.cfg", "zlog"} imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manages.yaml", "pcscf", "scscf", "vars.cfg", "zlog"}
for _, v := range imsDirArr { for _, v := range imsDirArr {
sshClient.RunCMD(fmt.Sprintf("sudo cp -rf /usr/local/etc/ims/%s %s/ims", v, neDirTemp)) cmd.Execf("sudo cp -rf /usr/local/etc/ims/%s %s/ims", v, neDirTemp)
} }
// mf目录 // mf目录
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s/mf && sudo cp -rf /usr/local/etc/mf %s", neDirTemp, neDirTemp)) cmd.Execf("mkdir -p %s/mf && sudo cp -rf /usr/local/etc/mf %s", neDirTemp, neDirTemp)
// rtproxy目录 // rtproxy目录
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s/rtproxy && sudo cp -rf /usr/local/etc/rtproxy/rtproxy.conf %s/rtproxy", neDirTemp, neDirTemp)) cmd.Execf("mkdir -p %s/rtproxy && sudo cp -rf /usr/local/etc/rtproxy/rtproxy.conf %s/rtproxy", neDirTemp, neDirTemp)
// iwf目录 // iwf目录
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s/iwf && sudo cp -rf /usr/local/etc/iwf/*.yaml %s/iwf", neDirTemp, neDirTemp)) cmd.Execf("mkdir -p %s/iwf && sudo cp -rf /usr/local/etc/iwf/*.yaml %s/iwf", neDirTemp, neDirTemp)
} else if neTypeLower == "smsc" { } else if neTypeLower == "smsc" {
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s && sudo cp -rf /usr/local/etc/smsc/{*.yaml,*.conf,*conf.txt} %s", neDirTemp, neDirTemp)) cmd.Execf("mkdir -p %s && sudo cp -rf /usr/local/etc/smsc/{*.yaml,*.conf,*conf.txt} %s", neDirTemp, neDirTemp)
sshClient.RunCMD(fmt.Sprintf("sudo cp -rf /usr/local/etc/smsc/conf %s/conf", neDirTemp)) cmd.Execf("sudo cp -rf /usr/local/etc/smsc/conf %s/conf", neDirTemp)
} else { } else {
nePath := fmt.Sprintf("/usr/local/etc/%s/*.yaml", neTypeLower) nePath := fmt.Sprintf("/usr/local/etc/%s/*.yaml", neTypeLower)
if neTypeLower == "mme" { if neTypeLower == "mme" {
nePath = fmt.Sprintf("/usr/local/etc/%s/*.{yaml,conf}", neTypeLower) nePath = fmt.Sprintf("/usr/local/etc/%s/*.{yaml,conf}", neTypeLower)
} }
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s && sudo cp -rf %s %s", neDirTemp, nePath, neDirTemp)) cmd.Execf("mkdir -p %s && sudo cp -rf %s %s", neDirTemp, nePath, neDirTemp)
} }
// 网元端复制到本地 // 网元端复制到本地
if err = sftpClient.CopyDirRemoteToLocal(neDirTemp, localDirPath); err != nil { if err := file.CopyDir(neDirTemp, localDirPath); err != nil {
return "", fmt.Errorf("copy config err") return "", fmt.Errorf("copy config err")
} }
@@ -192,7 +197,7 @@ func (s NeConfigBackup) FileNeToLocal(neInfo model.NeInfo) (string, error) {
return "", fmt.Errorf("compress zip err") return "", fmt.Errorf("compress zip err")
} }
_ = os.RemoveAll(localDirPath) // 删除本地临时目录 _ = os.RemoveAll(localDirPath) // 删除本地临时目录
sshClient.RunCMD(fmt.Sprintf("sudo rm -rf %s", neDirTemp)) // 删除临时目录 cmd.Execf("sudo rm -rf %s", neDirTemp) // 删除临时目录
return zipFilePath, nil return zipFilePath, nil
} }

View File

@@ -9,11 +9,13 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/constants" "be.ems/src/framework/constants"
"be.ems/src/framework/database/redis" "be.ems/src/framework/database/redis"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/ssh" "be.ems/src/framework/ssh"
"be.ems/src/framework/telnet" "be.ems/src/framework/telnet"
"be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/generate" "be.ems/src/framework/utils/generate"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
@@ -395,15 +397,16 @@ func (r NeInfo) NeRunSSHClient(neType, neId string) (*ssh.ConnSSH, error) {
} }
// NeRunSSHCmd 网元主机的SSH客户端发送cmd命令 // NeRunSSHCmd 网元主机的SSH客户端发送cmd命令
func (r NeInfo) NeRunSSHCmd(neType, neId, cmd string) (string, error) { func (r NeInfo) NeRunSSHCmd(neType, neId, cmdStr string) (string, error) {
sshClient, err := r.NeRunSSHClient(neType, neId) // sshClient, err := r.NeRunSSHClient(neType, neId)
if err != nil { // if err != nil {
return "", err // return "", err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 执行命令 // // 执行命令
output, err := sshClient.RunCMD(cmd) // output, err := sshClient.RunCMD(cmd)
output, err := cmd.Exec(cmdStr)
if err != nil { if err != nil {
logger.Errorf("NeRunSSHCmd RunCMD %s err => %s", output, err.Error()) logger.Errorf("NeRunSSHCmd RunCMD %s err => %s", output, err.Error())
return "", fmt.Errorf("neinfo ssh run cmd err") return "", fmt.Errorf("neinfo ssh run cmd err")
@@ -600,24 +603,28 @@ func (r NeInfo) neConfOAMRead(neType, neId string, sync bool) (map[string]any, e
// 从网元端同步到本地 // 从网元端同步到本地
if sync { if sync {
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := r.NeRunSSHClient(neType, neId) // sshClient, err := r.NeRunSSHClient(neType, neId)
if err != nil { // if err != nil {
return nil, fmt.Errorf("ne info ssh client err") // return nil, fmt.Errorf("ne info ssh client err")
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return nil, fmt.Errorf("ne info sftp client err") // return nil, fmt.Errorf("ne info sftp client err")
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 网元端文件路径 // 网元端文件路径
neFilePath := fmt.Sprintf("/usr/local/etc/%s/%s", neTypeLower, fileName) neFilePath := fmt.Sprintf("/usr/local/etc/%s/%s", neTypeLower, fileName)
// 修改网元文件权限 // 修改网元文件权限
sshClient.RunCMD(fmt.Sprintf("sudo touch %s && sudo chmod o+rw %s", neFilePath, neFilePath)) // sshClient.RunCMD(fmt.Sprintf("sudo touch %s && sudo chmod o+rw %s", neFilePath, neFilePath))
cmd.Execf("sudo touch %s && sudo chmod o+rw %s", neFilePath, neFilePath)
// 网元端复制到本地 // 网元端复制到本地
if err = sftpClient.CopyFileRemoteToLocal(neFilePath, localFilePath); err != nil { // if err = sftpClient.CopyFileRemoteToLocal(neFilePath, localFilePath); err != nil {
// return nil, fmt.Errorf("copy oam config err")
// }
if err := file.CopyFile(neFilePath, localFilePath); err != nil {
return nil, fmt.Errorf("copy oam config err") return nil, fmt.Errorf("copy oam config err")
} }
} }
@@ -661,26 +668,30 @@ func (r NeInfo) neConfOAMWirte(neType, neId string, content any, sync bool) erro
// 同步到网元端 // 同步到网元端
if sync { if sync {
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := r.NeRunSSHClient(neType, neId) // sshClient, err := r.NeRunSSHClient(neType, neId)
if err != nil { // if err != nil {
return err // return err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return err // return err
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 网元端配置路径 // 网元端配置路径
neFilePath := fmt.Sprintf("/usr/local/etc/%s/%s", neTypeLower, fileName) neFilePath := fmt.Sprintf("/usr/local/etc/%s/%s", neTypeLower, fileName)
neFileDir := filepath.ToSlash(filepath.Dir(neFilePath)) neFileDir := filepath.ToSlash(filepath.Dir(neFilePath))
// 修改网元文件权限 // // 修改网元文件权限
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neFileDir, neFileDir, neFilePath, neFilePath)) // sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neFileDir, neFileDir, neFilePath, neFilePath))
// 复制到网元进行覆盖 cmd.Execf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neFileDir, neFileDir, neFilePath, neFilePath)
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { // // 复制到网元进行覆盖
// if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
// return fmt.Errorf("please check if scp remote copy is allowed")
// }
if err := file.CopyFile(localFilePath, neFilePath); err != nil {
return fmt.Errorf("please check if scp remote copy is allowed") return fmt.Errorf("please check if scp remote copy is allowed")
} }
} }
@@ -837,28 +848,33 @@ func (r *NeInfo) NeConfPara5GWirte(content map[string]any, syncNE []string) erro
errMsg := []string{} errMsg := []string{}
for _, neTI := range syncNE { for _, neTI := range syncNE {
ti := strings.SplitN(neTI, "@", 2) ti := strings.SplitN(neTI, "@", 2)
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := r.NeRunSSHClient(ti[0], ti[1]) // sshClient, err := r.NeRunSSHClient(ti[0], ti[1])
if err != nil { // if err != nil {
errMsg = append(errMsg, fmt.Sprintf("%s : %s", ti, err.Error())) // errMsg = append(errMsg, fmt.Sprintf("%s : %s", ti, err.Error()))
continue // continue
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
errMsg = append(errMsg, fmt.Sprintf("%s : %s", ti, err.Error())) // errMsg = append(errMsg, fmt.Sprintf("%s : %s", ti, err.Error()))
continue // continue
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 网元端配置路径 // 网元端配置路径
neFilePath := "/usr/local/etc/conf/para5G.yaml" neFilePath := "/usr/local/etc/conf/para5G.yaml"
neFileDir := filepath.ToSlash(filepath.Dir(neFilePath)) neFileDir := filepath.ToSlash(filepath.Dir(neFilePath))
// 修改网元文件权限 // 修改网元文件权限
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neFileDir, neFileDir, neFilePath, neFilePath)) // sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neFileDir, neFileDir, neFilePath, neFilePath))
cmd.Execf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neFileDir, neFileDir, neFilePath, neFilePath)
// 复制到网元进行覆盖 // 复制到网元进行覆盖
if err = sftpClient.CopyFileLocalToRemote(omcFilePath, neFilePath); err != nil { // if err = sftpClient.CopyFileLocalToRemote(omcFilePath, neFilePath); err != nil {
// errMsg = append(errMsg, fmt.Sprintf("%s : please check if scp remote copy is allowed", ti))
// continue
// }
if err := file.CopyFile(omcFilePath, neFilePath); err != nil {
errMsg = append(errMsg, fmt.Sprintf("%s : please check if scp remote copy is allowed", ti)) errMsg = append(errMsg, fmt.Sprintf("%s : please check if scp remote copy is allowed", ti))
continue continue
} }

View File

@@ -8,6 +8,7 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/modules/network_element/model" "be.ems/src/modules/network_element/model"
"be.ems/src/modules/network_element/repository" "be.ems/src/modules/network_element/repository"
@@ -109,20 +110,20 @@ func (r *NeLicense) ReadLicenseInfo(neLicense model.NeLicense) (string, string)
nePath := fmt.Sprintf("/usr/local/etc/%s/license", neTypeLower) nePath := fmt.Sprintf("/usr/local/etc/%s/license", neTypeLower)
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := NewNeInfo.NeRunSSHClient(neLicense.NeType, neLicense.NeId) // sshClient, err := NewNeInfo.NeRunSSHClient(neLicense.NeType, neLicense.NeId)
if err != nil { // if err != nil {
return "", "" // return "", ""
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return "", "" // return "", ""
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 复制授权申请码到本地 // 复制授权申请码到本地
if err = sftpClient.CopyFileRemoteToLocal(nePath+"/Activation_request_code.txt", omcPath+"/Activation_request_code.txt"); err != nil { if err := file.CopyFile(nePath+"/Activation_request_code.txt", omcPath+"/Activation_request_code.txt"); err != nil {
return "", "" return "", ""
} }
// 读取文件内容 // 读取文件内容
@@ -133,7 +134,7 @@ func (r *NeLicense) ReadLicenseInfo(neLicense model.NeLicense) (string, string)
// 复制激活文件到本地 // 复制激活文件到本地
licensePath := "" licensePath := ""
if err = sftpClient.CopyFileRemoteToLocal(nePath+"/system.ini", omcPath+"/system.ini"); err == nil { if err := file.CopyFile(nePath+"/system.ini", omcPath+"/system.ini"); err == nil {
licensePath = omcPath + "/system.ini" licensePath = omcPath + "/system.ini"
} }
return strings.TrimSpace(string(bytes)), licensePath return strings.TrimSpace(string(bytes)), licensePath
@@ -147,32 +148,32 @@ func (r *NeLicense) UploadLicense(neLicense model.NeLicense) error {
return fmt.Errorf("file read failure") return fmt.Errorf("file read failure")
} }
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := NewNeInfo.NeRunSSHClient(neLicense.NeType, neLicense.NeId) // sshClient, err := NewNeInfo.NeRunSSHClient(neLicense.NeType, neLicense.NeId)
if err != nil { // if err != nil {
return err // return err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return err // return err
} // }
defer sftpClient.Close() // defer sftpClient.Close()
// 网元端授权文件路径 // 网元端授权文件路径
neTypeLower := strings.ToLower(neLicense.NeType) neTypeLower := strings.ToLower(neLicense.NeType)
neLicensePath := fmt.Sprintf("/usr/local/etc/%s/license/system.ini", neTypeLower) neLicensePath := fmt.Sprintf("/usr/local/etc/%s/license/system.ini", neTypeLower)
neLicenseDir := filepath.ToSlash(filepath.Dir(neLicensePath)) neLicenseDir := filepath.ToSlash(filepath.Dir(neLicensePath))
// 修改网元文件权限 // 修改网元文件权限
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neLicenseDir, neLicenseDir, neLicensePath, neLicensePath)) cmd.Execf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neLicenseDir, neLicenseDir, neLicensePath, neLicensePath)
// 尝试备份授权文件 // 尝试备份授权文件
neLicensePathBack := fmt.Sprintf("%s/system_%s.ini", neLicensePath, time.Now().Format("20060102_150405")) neLicensePathBack := fmt.Sprintf("%s/system_%s.ini", neLicensePath, time.Now().Format("20060102_150405"))
sshClient.RunCMD(fmt.Sprintf("sudo cp -rf %s/system.ini %s", neLicensePath, neLicensePathBack)) cmd.Execf("sudo cp -rf %s/system.ini %s", neLicensePath, neLicensePathBack)
// 上传授权文件去覆盖 // 上传授权文件去覆盖
if err := sftpClient.CopyFileLocalToRemote(omcLicensePath, neLicensePath); err != nil { if err := file.CopyFile(omcLicensePath, neLicensePath); err != nil {
return fmt.Errorf("please check if scp remote copy is allowed") return fmt.Errorf("please check if scp remote copy is allowed")
} }
@@ -184,7 +185,7 @@ func (r *NeLicense) UploadLicense(neLicense model.NeLicense) error {
} else if neTypeLower == "omc" { } else if neTypeLower == "omc" {
cmdStr = "sudo systemctl restart omc" cmdStr = "sudo systemctl restart omc"
} }
sshClient.RunCMD(cmdStr) cmd.Exec(cmdStr)
} }
return nil return nil
} }

View File

@@ -7,7 +7,7 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/ssh" "be.ems/src/framework/cmd"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
"be.ems/src/modules/network_element/model" "be.ems/src/modules/network_element/model"
@@ -135,12 +135,12 @@ func (r NeVersion) FindByNeTypeAndNeID(neType, neId string) model.NeVersion {
// //
// action 安装行为install upgrade rollback // action 安装行为install upgrade rollback
func (r NeVersion) Operate(action string, neVersion model.NeVersion, preinput map[string]string) (string, error) { func (r NeVersion) Operate(action string, neVersion model.NeVersion, preinput map[string]string) (string, error) {
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := r.neInfoService.NeRunSSHClient(neVersion.NeType, neVersion.NeId) // sshClient, err := r.neInfoService.NeRunSSHClient(neVersion.NeType, neVersion.NeId)
if err != nil { // if err != nil {
return "", err // return "", err
} // }
defer sshClient.Close() // defer sshClient.Close()
// ========= 文件传输阶段 ========= // ========= 文件传输阶段 =========
softwarePath := neVersion.Path softwarePath := neVersion.Path
@@ -150,7 +150,7 @@ func (r NeVersion) Operate(action string, neVersion model.NeVersion, preinput ma
if action == "rollback" { if action == "rollback" {
softwarePath = neVersion.PrePath softwarePath = neVersion.PrePath
} }
neFilePaths, err := r.operateFile(sshClient, softwarePath) neFilePaths, err := r.operateFile(softwarePath)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -174,7 +174,7 @@ func (r NeVersion) Operate(action string, neVersion model.NeVersion, preinput ma
} }
// ========= 执行阶段 ========= // ========= 执行阶段 =========
commandLine, err := r.operateRun(sshClient, preinput, cmdStrArr, neVersion.NeType, okFlagStr) commandLine, err := r.operateRun(preinput, cmdStrArr, neVersion.NeType, okFlagStr)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -189,16 +189,18 @@ func (r NeVersion) Operate(action string, neVersion model.NeVersion, preinput ma
} }
// operateFile 操作版本-文件传输阶段 // operateFile 操作版本-文件传输阶段
func (r NeVersion) operateFile(sshClient *ssh.ConnSSH, softwarePath string) ([]string, error) { func (r NeVersion) operateFile(softwarePath string) ([]string, error) {
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
defer sftpClient.Close() // defer sftpClient.Close()
nePath := "/tmp" // nePath := "/tmp"
copyFileToNeMap := map[string]string{} // copyFileToNeMap := map[string]string{}
neFilePaths := []string{}
// 统一处理多个文件和单个文件的情况 // 统一处理多个文件和单个文件的情况
var softwarePaths []string var softwarePaths []string
@@ -215,19 +217,20 @@ func (r NeVersion) operateFile(sshClient *ssh.ConnSSH, softwarePath string) ([]s
return nil, fmt.Errorf("file read failure") return nil, fmt.Errorf("file read failure")
} }
fileName := filepath.Base(path) // fileName := filepath.Base(path)
neFilePath := fmt.Sprintf("%s/%s", nePath, fileName) // neFilePath := fmt.Sprintf("%s/%s", nePath, fileName)
copyFileToNeMap[localFilePath] = neFilePath // copyFileToNeMap[localFilePath] = neFilePath
neFilePaths = append(neFilePaths, localFilePath)
} }
// 上传软件包到 /tmp // // 上传软件包到 /tmp
neFilePaths := []string{} // neFilePaths := []string{}
for k, v := range copyFileToNeMap { // for k, v := range copyFileToNeMap {
if err = sftpClient.CopyFileLocalToRemote(k, v); err != nil { // if err = sftpClient.CopyFileLocalToRemote(k, v); err != nil {
return nil, fmt.Errorf("error uploading package") // return nil, fmt.Errorf("error uploading package")
} // }
neFilePaths = append(neFilePaths, v) // neFilePaths = append(neFilePaths, v)
} // }
return neFilePaths, nil return neFilePaths, nil
} }
@@ -587,9 +590,9 @@ func (r NeVersion) operateCommand(action, neType string, neFilePaths []string) (
} }
// operateRun 操作版本-执行阶段 // operateRun 操作版本-执行阶段
func (r NeVersion) operateRun(sshClient *ssh.ConnSSH, preinput map[string]string, cmdStrArr []string, neType string, okFlagStr string) (string, error) { func (r NeVersion) operateRun(preinput map[string]string, cmdStrArr []string, neType string, okFlagStr string) (string, error) {
// ssh连接会话 // ssh连接会话
clientSession, err := sshClient.NewClientSession(127, 42) clientSession, err := cmd.NewClientSession(127, 42)
if err != nil { if err != nil {
return "", fmt.Errorf("neinfo ssh client session new err") return "", fmt.Errorf("neinfo ssh client session new err")
} }

View File

@@ -6,11 +6,11 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
neService "be.ems/src/modules/network_element/service"
"be.ems/src/modules/tool/service" "be.ems/src/modules/tool/service"
wsService "be.ems/src/modules/ws/service" wsService "be.ems/src/modules/ws/service"
@@ -140,14 +140,14 @@ func (s *IPerfController) Run(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := neService.NewNeInfo.NeRunSSHClient(query.NeType, query.NeId) // sshClient, err := neService.NewNeInfo.NeRunSSHClient(query.NeType, query.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// ssh连接会话 // ssh连接会话
clientSession, err := sshClient.NewClientSession(query.Cols, query.Rows) clientSession, err := cmd.NewClientSession(query.Cols, query.Rows)
if err != nil { if err != nil {
c.JSON(200, resp.ErrMsg("neinfo ssh client session new err")) c.JSON(200, resp.ErrMsg("neinfo ssh client session new err"))
return return

View File

@@ -5,11 +5,11 @@ import (
"fmt" "fmt"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
neService "be.ems/src/modules/network_element/service"
"be.ems/src/modules/tool/model" "be.ems/src/modules/tool/model"
"be.ems/src/modules/tool/service" "be.ems/src/modules/tool/service"
wsService "be.ems/src/modules/ws/service" wsService "be.ems/src/modules/ws/service"
@@ -175,14 +175,14 @@ func (s *PingController) Run(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := neService.NewNeInfo.NeRunSSHClient(query.NeType, query.NeId) // sshClient, err := neService.NewNeInfo.NeRunSSHClient(query.NeType, query.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// ssh连接会话 // ssh连接会话
clientSession, err := sshClient.NewClientSession(query.Cols, query.Rows) clientSession, err := cmd.NewClientSession(query.Cols, query.Rows)
if err != nil { if err != nil {
c.JSON(200, resp.ErrMsg("neinfo ssh client session new err")) c.JSON(200, resp.ErrMsg("neinfo ssh client session new err"))
return return

View File

@@ -4,14 +4,14 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"os"
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/config" "be.ems/src/framework/config"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
neService "be.ems/src/modules/network_element/service"
wsModel "be.ems/src/modules/ws/model" wsModel "be.ems/src/modules/ws/model"
) )
@@ -26,20 +26,20 @@ func (s *IPerf) Version(meType, neId, version string) (string, error) {
if version != "V2" && version != "V3" { if version != "V2" && version != "V3" {
return "", fmt.Errorf("iperf version is required V2 or V3") return "", fmt.Errorf("iperf version is required V2 or V3")
} }
cmd := "iperf3 --version" cmdStr := "iperf3 --version"
if version == "V2" { if version == "V2" {
cmd = "iperf -v" cmdStr = "iperf -v"
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := neService.NewNeInfo.NeRunSSHClient(meType, neId) // sshClient, err := neService.NewNeInfo.NeRunSSHClient(meType, neId)
if err != nil { // if err != nil {
return "", err // return "", err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 检查是否安装iperf // 检查是否安装iperf
output, err := sshClient.RunCMD(cmd) output, err := cmd.Exec(cmdStr)
if err != nil { if err != nil {
if version == "V2" && strings.HasSuffix(err.Error(), "status 1") { // V2 版本 if version == "V2" && strings.HasSuffix(err.Error(), "status 1") { // V2 版本
return strings.TrimSpace(output), nil return strings.TrimSpace(output), nil
@@ -56,28 +56,28 @@ func (s *IPerf) Install(meType, neId, version string) error {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := neService.NewNeInfo.NeRunSSHClient(meType, neId) // sshClient, err := neService.NewNeInfo.NeRunSSHClient(meType, neId)
if err != nil { // if err != nil {
return err // return err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return err // return err
} // }
defer sftpClient.Close() // defer sftpClient.Close()
nePath := "/tmp" nePath := "/tmp"
depPkg := "sudo dpkg -i" depPkg := "sudo dpkg -i"
depDir := "assets/dependency/iperf3/deb" depDir := "assets/dependency/iperf3/deb"
// 检查平台类型 // 检查平台类型
if _, err := sshClient.RunCMD("sudo dpkg --version"); err == nil { if _, err := cmd.Exec("sudo dpkg --version"); err == nil {
depPkg = "sudo dpkg -i" depPkg = "sudo dpkg -i"
depDir = "assets/dependency/iperf3/deb" depDir = "assets/dependency/iperf3/deb"
// sudo apt remove iperf3 libiperf0 libsctp1 libsctp-dev lksctp-tools // sudo apt remove iperf3 libiperf0 libsctp1 libsctp-dev lksctp-tools
} else if _, err := sshClient.RunCMD("sudo yum --version"); err == nil { } else if _, err := cmd.Exec("sudo yum --version"); err == nil {
depPkg = "sudo rpm -Uvh --nosignature --reinstall --force" depPkg = "sudo rpm -Uvh --nosignature --reinstall --force"
depDir = "assets/dependency/iperf3/rpm" depDir = "assets/dependency/iperf3/rpm"
// yum remove iperf3 iperf3-help.noarch // yum remove iperf3 iperf3-help.noarch
@@ -106,7 +106,7 @@ func (s *IPerf) Install(meType, neId, version string) error {
defer localFile.Close() defer localFile.Close()
// 创建远程文件 // 创建远程文件
remotePath := fmt.Sprintf("%s/%s", nePath, d.Name()) remotePath := fmt.Sprintf("%s/%s", nePath, d.Name())
remoteFile, err := sftpClient.Client.Create(remotePath) remoteFile, err := os.Create(remotePath)
if err != nil { if err != nil {
return fmt.Errorf("iperf %s file remote error", version) return fmt.Errorf("iperf %s file remote error", version)
} }
@@ -120,13 +120,12 @@ func (s *IPerf) Install(meType, neId, version string) error {
// 删除软件包 // 删除软件包
defer func() { defer func() {
pkgRemove := fmt.Sprintf("sudo rm %s", strings.Join(neFilePaths, " ")) cmd.Execf("sudo rm %s", strings.Join(neFilePaths, " "))
sshClient.RunCMD(pkgRemove)
}() }()
// 安装软件包 // 安装软件包
pkgInstall := fmt.Sprintf("%s %s", depPkg, strings.Join(neFilePaths, " ")) _, err = cmd.Execf("%s %s", depPkg, strings.Join(neFilePaths, " "))
if _, err := sshClient.RunCMD(pkgInstall); err != nil { if err != nil {
return fmt.Errorf("iperf %s install error", version) return fmt.Errorf("iperf %s install error", version)
} }
return err return err
@@ -160,13 +159,13 @@ func (s *IPerf) Run(client *wsModel.WSClient, reqMsg wsModel.WSRequest) {
var command string var command string
command, err = s.parseOptions(reqMsg.Data) command, err = s.parseOptions(reqMsg.Data)
if command != "" && err == nil { if command != "" && err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = sshClientSession.Write(command) _, err = localClientSession.Write(command)
} }
case "ctrl-c": case "ctrl-c":
// 模拟按下 Ctrl+C // 模拟按下 Ctrl+C
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = sshClientSession.Write("\u0003\n") _, err = localClientSession.Write("\u0003\n")
case "resize": case "resize":
// 会话窗口重置 // 会话窗口重置
msgByte, _ := json.Marshal(reqMsg.Data) msgByte, _ := json.Marshal(reqMsg.Data)
@@ -176,8 +175,8 @@ func (s *IPerf) Run(client *wsModel.WSClient, reqMsg wsModel.WSRequest) {
} }
err = json.Unmarshal(msgByte, &data) err = json.Unmarshal(msgByte, &data)
if err == nil { if err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) localClientSession := client.ChildConn.(*cmd.LocalClientSession)
err = sshClientSession.Session.WindowChange(data.Rows, data.Cols) localClientSession.WindowChange(data.Cols, data.Rows)
} }
default: default:
err = fmt.Errorf("message type %s not supported", reqMsg.Type) err = fmt.Errorf("message type %s not supported", reqMsg.Type)

View File

@@ -7,9 +7,9 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"be.ems/src/modules/tool/model" "be.ems/src/modules/tool/model"
wsModel "be.ems/src/modules/ws/model" wsModel "be.ems/src/modules/ws/model"
@@ -173,13 +173,17 @@ func (s *Ping) Run(client *wsModel.WSClient, reqMsg wsModel.WSRequest) {
var command string var command string
command, err = s.parseOptions(reqMsg.Data) command, err = s.parseOptions(reqMsg.Data)
if command != "" && err == nil { if command != "" && err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
_, err = sshClientSession.Write(command) // _, err = sshClientSession.Write(command)
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = localClientSession.Write(command)
} }
case "ctrl-c": case "ctrl-c":
// 模拟按下 Ctrl+C // 模拟按下 Ctrl+C
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
_, err = sshClientSession.Write("\u0003\n") // _, err = sshClientSession.Write("\u0003\n")
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = localClientSession.Write("\u0003\n")
case "resize": case "resize":
// 会话窗口重置 // 会话窗口重置
msgByte, _ := json.Marshal(reqMsg.Data) msgByte, _ := json.Marshal(reqMsg.Data)
@@ -189,8 +193,10 @@ func (s *Ping) Run(client *wsModel.WSClient, reqMsg wsModel.WSRequest) {
} }
err = json.Unmarshal(msgByte, &data) err = json.Unmarshal(msgByte, &data)
if err == nil { if err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
err = sshClientSession.Session.WindowChange(data.Rows, data.Cols) // err = sshClientSession.Session.WindowChange(data.Rows, data.Cols)
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
localClientSession.WindowChange(data.Cols, data.Rows)
} }
default: default:
err = fmt.Errorf("message type %s not supported", reqMsg.Type) err = fmt.Errorf("message type %s not supported", reqMsg.Type)

View File

@@ -9,6 +9,7 @@ import (
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/generate" "be.ems/src/framework/utils/generate"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -206,19 +207,19 @@ func (s *TraceTaskHlrController) FilePull(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sftpClient.Close() // defer sftpClient.Close()
nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName)) nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName))
fileName := generate.Code(6) + "_" + querys.FileName fileName := generate.Code(6) + "_" + querys.FileName
@@ -227,7 +228,7 @@ func (s *TraceTaskHlrController) FilePull(c *gin.Context) {
localFilePath = fmt.Sprintf("C:%s", localFilePath) localFilePath = fmt.Sprintf("C:%s", localFilePath)
} }
// 复制到本地 // 复制到本地
if err = sftpClient.CopyFileRemoteToLocal(nePath, localFilePath); err != nil { if err := file.CopyFile(nePath, localFilePath); err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -8,8 +8,8 @@ import (
"sync" "sync"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/ssh"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
) )
@@ -33,20 +33,20 @@ func (s *TCPdump) DumpStart(neType, neId, cmdStr string) (string, error) {
return "", fmt.Errorf("command cannot contain -w") return "", fmt.Errorf("command cannot contain -w")
} }
// 查询网元获取IP // // 查询网元获取IP
neInfo := s.neInfoService.FindByNeTypeAndNeID(neType, neId) // neInfo := s.neInfoService.FindByNeTypeAndNeID(neType, neId)
if neInfo.NeId != neId || neInfo.IP == "" { // if neInfo.NeId != neId || neInfo.IP == "" {
return "", fmt.Errorf("app.common.noNEInfo") // return "", fmt.Errorf("app.common.noNEInfo")
} // }
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
return "", err // return "", err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 检查是否安装tcpdump // 检查是否安装tcpdump
if msg, err := sshClient.RunCMD("sudo tcpdump --version"); err != nil { if msg, err := cmd.Exec("sudo tcpdump --version"); err != nil {
// bash: tcpdump: command not found // bash: tcpdump: command not found
msg = strings.TrimSpace(msg) msg = strings.TrimSpace(msg)
logger.Errorf("DumpStart err: %s => %s", msg, err.Error()) logger.Errorf("DumpStart err: %s => %s", msg, err.Error())
@@ -55,8 +55,8 @@ func (s *TCPdump) DumpStart(neType, neId, cmdStr string) (string, error) {
taskCode := time.Now().Format("20060102150405") taskCode := time.Now().Format("20060102150405")
// 存放文件目录 /tmp/omc/tcpdump/udm/001/20240817104241 // 存放文件目录 /tmp/omc/tcpdump/udm/001/20240817104241
neDirTemp := fmt.Sprintf("/tmp/omc/tcpdump/%s/%s/%s", strings.ToLower(neInfo.NeType), neInfo.NeId, taskCode) neDirTemp := fmt.Sprintf("/tmp/omc/tcpdump/%s/%s/%s", strings.ToLower(neType), neId, taskCode)
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s && sudo chmod 777 -R /tmp/omc", neDirTemp)) cmd.Exec(fmt.Sprintf("mkdir -p %s && sudo chmod 777 -R /tmp/omc", neDirTemp))
// 命令拼装 // 命令拼装
logPath := fmt.Sprintf("%s/tcpdump.log", neDirTemp) logPath := fmt.Sprintf("%s/tcpdump.log", neDirTemp)
@@ -71,7 +71,7 @@ func (s *TCPdump) DumpStart(neType, neId, cmdStr string) (string, error) {
// timeout 超时60分钟后发送kill命令1分钟后强制终止命令。tcpdump -G 文件轮转间隔时间(秒) -W 文件轮转保留最近数量 // timeout 超时60分钟后发送kill命令1分钟后强制终止命令。tcpdump -G 文件轮转间隔时间(秒) -W 文件轮转保留最近数量
// sudo timeout --kill-after=1m 60m sudo tcpdump -i any -n -s 0 -v -G 10 -W 7 -w /tmp/part_%Y%m%d%H%M%S.pcap > /tmp/part.log 2>&1 & echo $! // sudo timeout --kill-after=1m 60m sudo tcpdump -i any -n -s 0 -v -G 10 -W 7 -w /tmp/part_%Y%m%d%H%M%S.pcap > /tmp/part.log 2>&1 & echo $!
// sudo kill $(pgrep -P 722729) // sudo kill $(pgrep -P 722729)
outputPID, err := sshClient.RunCMD(sendCmd) outputPID, err := cmd.Exec(sendCmd)
outputPID = strings.TrimSpace(outputPID) outputPID = strings.TrimSpace(outputPID)
if err != nil || strings.HasPrefix(outputPID, "stderr:") { if err != nil || strings.HasPrefix(outputPID, "stderr:") {
logger.Errorf("DumpStart err: %s => %s", outputPID, err.Error()) logger.Errorf("DumpStart err: %s => %s", outputPID, err.Error())
@@ -79,36 +79,36 @@ func (s *TCPdump) DumpStart(neType, neId, cmdStr string) (string, error) {
} }
// 日志文件行号 // 日志文件行号
PIDMap := s.logFileLastLine(neType, sshClient) PIDMap := s.logFileLastLine(neType)
PIDMap["neType"] = neInfo.NeType PIDMap["neType"] = neType
PIDMap["neId"] = neInfo.NeId PIDMap["neId"] = neId
PIDMap["taskCode"] = taskCode PIDMap["taskCode"] = taskCode
PIDMap["pid"] = outputPID PIDMap["pid"] = outputPID
PIDMap["cmd"] = sendCmd PIDMap["cmd"] = sendCmd
// 检查进程 ps aux | grep tcpdump // 检查进程 ps aux | grep tcpdump
// 强杀 sudo pkill tcpdump // 强杀 sudo pkill tcpdump
pidKey := fmt.Sprintf("%s_%s_%s", strings.ToLower(neInfo.NeType), neInfo.NeId, taskCode) pidKey := fmt.Sprintf("%s_%s_%s", strings.ToLower(neType), neId, taskCode)
dumpPIDMap.Store(pidKey, PIDMap) dumpPIDMap.Store(pidKey, PIDMap)
return taskCode, err return taskCode, err
} }
// DumpStop 停止已存在抓包句柄 // DumpStop 停止已存在抓包句柄
func (s *TCPdump) DumpStop(neType, neId, taskCode string) ([]string, error) { func (s *TCPdump) DumpStop(neType, neId, taskCode string) ([]string, error) {
// 查询网元获取IP // // 查询网元获取IP
neInfo := s.neInfoService.FindByNeTypeAndNeID(neType, neId) // neInfo := s.neInfoService.FindByNeTypeAndNeID(neType, neId)
if neInfo.NeId != neId || neInfo.IP == "" { // if neInfo.NeId != neId || neInfo.IP == "" {
return []string{}, fmt.Errorf("app.common.noNEInfo") // return []string{}, fmt.Errorf("app.common.noNEInfo")
} // }
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
return []string{}, err // return []string{}, err
} // }
defer sshClient.Close() // defer sshClient.Close()
// 是否存在执行过的进程 // 是否存在执行过的进程
pidKey := fmt.Sprintf("%s_%s_%s", strings.ToLower(neInfo.NeType), neInfo.NeId, taskCode) pidKey := fmt.Sprintf("%s_%s_%s", strings.ToLower(neType), neId, taskCode)
PIDMap, ok := dumpPIDMap.Load(pidKey) PIDMap, ok := dumpPIDMap.Load(pidKey)
if !ok || PIDMap == nil { if !ok || PIDMap == nil {
return []string{}, fmt.Errorf("tcpdump is not running") return []string{}, fmt.Errorf("tcpdump is not running")
@@ -117,14 +117,14 @@ func (s *TCPdump) DumpStop(neType, neId, taskCode string) ([]string, error) {
if !ok || pid == "" { if !ok || pid == "" {
return []string{}, fmt.Errorf("tcpdump is not running") return []string{}, fmt.Errorf("tcpdump is not running")
} }
s.logFileLastLineToFile(PIDMap.(map[string]string), sshClient) s.logFileLastLineToFile(PIDMap.(map[string]string))
// 存放文件目录 /tmp/omc/tcpdump/udm/001/20240817104241 // 存放文件目录 /tmp/omc/tcpdump/udm/001/20240817104241
neDirTemp := fmt.Sprintf("/tmp/omc/tcpdump/%s/%s/%s", strings.ToLower(neInfo.NeType), neInfo.NeId, taskCode) neDirTemp := fmt.Sprintf("/tmp/omc/tcpdump/%s/%s/%s", strings.ToLower(neType), neId, taskCode)
// 命令拼装 // 命令拼装
sendCmd := fmt.Sprintf("pids=$(pgrep -P %s) && [ -n \"$pids\" ] && sudo kill $pids;sudo timeout 2s ls %s", pid, neDirTemp) sendCmd := fmt.Sprintf("pids=$(pgrep -P %s) && [ -n \"$pids\" ] && sudo kill $pids;sudo timeout 2s ls %s", pid, neDirTemp)
// pids=$(pgrep -P 1914341) && [ -n "$pids" ] && sudo kill $pids;sudo timeout 2s ls /tmp/omc/tcpdump/udm/001/20240817104241 // pids=$(pgrep -P 1914341) && [ -n "$pids" ] && sudo kill $pids;sudo timeout 2s ls /tmp/omc/tcpdump/udm/001/20240817104241
output, err := sshClient.RunCMD(sendCmd) output, err := cmd.Exec(sendCmd)
output = strings.TrimSpace(output) output = strings.TrimSpace(output)
if err != nil || strings.HasPrefix(output, "ls: ") { if err != nil || strings.HasPrefix(output, "ls: ") {
logger.Errorf("DumpStop err: %s => %s", output, err.Error()) logger.Errorf("DumpStop err: %s => %s", output, err.Error())
@@ -136,7 +136,7 @@ func (s *TCPdump) DumpStop(neType, neId, taskCode string) ([]string, error) {
} }
// logFileLastLine 日志文件最后行号 // logFileLastLine 日志文件最后行号
func (s *TCPdump) logFileLastLine(neType string, sshClient *ssh.ConnSSH) map[string]string { func (s *TCPdump) logFileLastLine(neType string) map[string]string {
logFileArr := make([]string, 0) logFileArr := make([]string, 0)
mapFile := make(map[string]string, 0) mapFile := make(map[string]string, 0)
@@ -158,7 +158,7 @@ func (s *TCPdump) logFileLastLine(neType string, sshClient *ssh.ConnSSH) map[str
} }
for _, v := range logFileArr { for _, v := range logFileArr {
lastLine, err := sshClient.RunCMD(fmt.Sprintf("sed -n '$=' %s", v)) lastLine, err := cmd.Exec(fmt.Sprintf("sed -n '$=' %s", v))
lastLine = strings.TrimSpace(lastLine) lastLine = strings.TrimSpace(lastLine)
if err != nil || strings.HasPrefix(lastLine, "sed: can't") { if err != nil || strings.HasPrefix(lastLine, "sed: can't") {
logger.Errorf("logFileLastLine err: %s => %s", lastLine, err.Error()) logger.Errorf("logFileLastLine err: %s => %s", lastLine, err.Error())
@@ -170,22 +170,22 @@ func (s *TCPdump) logFileLastLine(neType string, sshClient *ssh.ConnSSH) map[str
} }
// logFileLastLine 日志文件最后行号 // logFileLastLine 日志文件最后行号
func (s *TCPdump) logFileLastLineToFile(PIDMap map[string]string, sshClient *ssh.ConnSSH) error { func (s *TCPdump) logFileLastLineToFile(PIDMap map[string]string) error {
// 网元主机的SSH客户端进行文件传输 // // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() // sftpClient, err := sshClient.NewClientSFTP()
if err != nil { // if err != nil {
return fmt.Errorf("ne info sftp client err") // return fmt.Errorf("ne info sftp client err")
} // }
defer sftpClient.Close() // defer sftpClient.Close()
neType := PIDMap["neType"] neType := PIDMap["neType"]
neId := PIDMap["neId"] neId := PIDMap["neId"]
taskCode := PIDMap["taskCode"] taskCode := PIDMap["taskCode"]
// 存放文件目录 /tmp/omc/tcpdump/udm/001/20240817104241 // 存放文件目录 /tmp/omc/tcpdump/udm/001/20240817104241
sshClient.RunCMD("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc") cmd.Exec("mkdir -p /tmp/omc && sudo chmod 777 -R /tmp/omc")
neDirTemp := fmt.Sprintf("/tmp/omc/tcpdump/%s/%s/%s", strings.ToLower(neType), neId, taskCode) neDirTemp := fmt.Sprintf("/tmp/omc/tcpdump/%s/%s/%s", strings.ToLower(neType), neId, taskCode)
lastLineMap := s.logFileLastLine(neType, sshClient) lastLineMap := s.logFileLastLine(neType)
for lastLogFile, lastFileLine := range lastLineMap { for lastLogFile, lastFileLine := range lastLineMap {
for startLogFile, startFileLine := range PIDMap { for startLogFile, startFileLine := range PIDMap {
if lastLogFile == startLogFile && lastFileLine != "" { if lastLogFile == startLogFile && lastFileLine != "" {
@@ -195,7 +195,7 @@ func (s *TCPdump) logFileLastLineToFile(PIDMap map[string]string, sshClient *ssh
outputFile := fmt.Sprintf("%s/%s", neDirTemp, filepath.Base(lastLogFile)) outputFile := fmt.Sprintf("%s/%s", neDirTemp, filepath.Base(lastLogFile))
sendCmd := fmt.Sprintf("sed -n \"%s,%sp\" \"%s\" > \"%s\"", startFileLine, lastFileLine, lastLogFile, outputFile) sendCmd := fmt.Sprintf("sed -n \"%s,%sp\" \"%s\" > \"%s\"", startFileLine, lastFileLine, lastLogFile, outputFile)
// sed -n "1,5p" "/var/log/amf.log" > "/tmp/omc/tcpdump/amf/001/20241008141336/amf.log" // sed -n "1,5p" "/var/log/amf.log" > "/tmp/omc/tcpdump/amf/001/20241008141336/amf.log"
output, err := sshClient.RunCMD(sendCmd) output, err := cmd.Exec(sendCmd)
if err != nil || strings.HasPrefix(output, "stderr:") { if err != nil || strings.HasPrefix(output, "stderr:") {
logger.Errorf("logFileLastLineToFile err: %s => %s", strings.TrimSpace(output), err.Error()) logger.Errorf("logFileLastLineToFile err: %s => %s", strings.TrimSpace(output), err.Error())
continue continue

View File

@@ -5,8 +5,8 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"be.ems/src/framework/ssh"
"be.ems/src/framework/utils/date" "be.ems/src/framework/utils/date"
"be.ems/src/framework/utils/file"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
neModel "be.ems/src/modules/network_element/model" neModel "be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -175,18 +175,18 @@ func (r *TraceTaskHlr) File(traceId, dirPath string) ([]map[string]any, error) {
"err": "", "err": "",
} }
// 网元主机的SSH客户端 // // 网元主机的SSH客户端
sshClient, err := r.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) // sshClient, err := r.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { // if err != nil {
hlrItem["err"] = "ssh link fail" // hlrItem["err"] = "ssh link fail"
hlrList = append(hlrList, hlrItem) // hlrList = append(hlrList, hlrItem)
continue // continue
} // }
defer sshClient.Close() // defer sshClient.Close()
// 获取文件列表 // 获取文件列表
fileName := fmt.Sprintf("%s_%s", neInfo.NeName, traceId) fileName := fmt.Sprintf("%s_%s", neInfo.NeName, traceId)
rows, err := ssh.FileList(sshClient, filepath.ToSlash(dirPath), fileName) rows, err := file.FileList(filepath.ToSlash(dirPath), fileName)
if err != nil { if err != nil {
hlrItem["err"] = "file not found" hlrItem["err"] = "file not found"
hlrList = append(hlrList, hlrItem) hlrList = append(hlrList, hlrItem)

View File

@@ -5,12 +5,11 @@ import (
"fmt" "fmt"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -44,32 +43,32 @@ func (s *WSController) SSH(c *gin.Context) {
return return
} }
neHost := neService.NewNeHost.FindById(query.HostId) // neHost := neService.NewNeHost.FindById(query.HostId)
if neHost.ID != query.HostId || neHost.HostType != "ssh" { // if neHost.ID != query.HostId || neHost.HostType != "ssh" {
// 没有可访问主机信息数据! // // 没有可访问主机信息数据!
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.noData"))) // c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.noData")))
return // return
} // }
// 创建链接SSH客户端 // // 创建链接SSH客户端
var connSSH ssh.ConnSSH // var connSSH ssh.ConnSSH
neHost.CopyTo(&connSSH) // neHost.CopyTo(&connSSH)
var client *ssh.ConnSSH // var client *ssh.ConnSSH
var clientErr error // var clientErr error
if neHost.AuthMode == "2" { // if neHost.AuthMode == "2" {
client, clientErr = connSSH.NewClientByLocalPrivate() // client, clientErr = connSSH.NewClientByLocalPrivate()
} else { // } else {
client, clientErr = connSSH.NewClient() // client, clientErr = connSSH.NewClient()
} // }
if clientErr != nil { // if clientErr != nil {
// 连接主机失败,请检查连接参数后重试 // // 连接主机失败,请检查连接参数后重试
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo"))) // c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return // return
} // }
defer client.Close() // defer client.Close()
// 创建SSH客户端会话 // 创建SSH客户端会话
clientSession, err := client.NewClientSession(query.Cols, query.Rows) clientSession, err := cmd.NewClientSession(query.Cols, query.Rows)
if err != nil { if err != nil {
// 连接主机失败,请检查连接参数后重试 // 连接主机失败,请检查连接参数后重试
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
@@ -98,7 +97,7 @@ func (s *WSController) SSH(c *gin.Context) {
if len(outputByte) > 0 { if len(outputByte) > 0 {
outputStr := string(outputByte) outputStr := string(outputByte)
msgByte, _ := json.Marshal(resp.Ok(map[string]any{ msgByte, _ := json.Marshal(resp.Ok(map[string]any{
"requestId": fmt.Sprintf("ssh_%d_%d", neHost.ID, ms.UnixMilli()), "requestId": fmt.Sprintf("ssh_%d_%d", query.HostId, ms.UnixMilli()),
"data": outputStr, "data": outputStr,
})) }))
wsClient.MsgChan <- msgByte wsClient.MsgChan <- msgByte

View File

@@ -5,11 +5,11 @@ import (
"fmt" "fmt"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/reqctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -58,14 +58,14 @@ func (s *WSController) ShellView(c *gin.Context) {
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := neService.NewNeInfo.NeRunSSHClient(query.NeType, query.NeId) // sshClient, err := neService.NewNeInfo.NeRunSSHClient(query.NeType, query.NeId)
if err != nil { // if err != nil {
c.JSON(200, resp.ErrMsg(err.Error())) // c.JSON(200, resp.ErrMsg(err.Error()))
return // return
} // }
defer sshClient.Close() // defer sshClient.Close()
// ssh连接会话 // ssh连接会话
clientSession, err := sshClient.NewClientSession(query.Cols, query.Rows) clientSession, err := cmd.NewClientSession(query.Cols, query.Rows)
if err != nil { if err != nil {
c.JSON(200, resp.ErrMsg("neinfo ssh client session new err")) c.JSON(200, resp.ErrMsg("neinfo ssh client session new err"))
return return

View File

@@ -8,10 +8,10 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/cmd"
"be.ems/src/framework/database/redis" "be.ems/src/framework/database/redis"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/resp" "be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
"be.ems/src/framework/telnet" "be.ems/src/framework/telnet"
"be.ems/src/modules/ws/model" "be.ems/src/modules/ws/model"
"be.ems/src/modules/ws/processor" "be.ems/src/modules/ws/processor"
@@ -113,8 +113,10 @@ func (s *WSReceive) Shell(client *model.WSClient, reqMsg model.WSRequest) {
case "ssh": case "ssh":
// SSH会话消息接收写入会话 // SSH会话消息接收写入会话
command := reqMsg.Data.(string) command := reqMsg.Data.(string)
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
_, err = sshClientSession.Write(command) // _, err = sshClientSession.Write(command)
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = localClientSession.Write(command)
case "resize": case "resize":
// SSH会话窗口重置 // SSH会话窗口重置
msgByte, _ := json.Marshal(reqMsg.Data) msgByte, _ := json.Marshal(reqMsg.Data)
@@ -124,8 +126,10 @@ func (s *WSReceive) Shell(client *model.WSClient, reqMsg model.WSRequest) {
} }
err = json.Unmarshal(msgByte, &data) err = json.Unmarshal(msgByte, &data)
if err == nil { if err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
err = sshClientSession.Session.WindowChange(data.Rows, data.Cols) // err = sshClientSession.Session.WindowChange(data.Rows, data.Cols)
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
localClientSession.WindowChange(data.Cols, data.Rows)
} }
default: default:
err = fmt.Errorf("message type %s not supported", reqMsg.Type) err = fmt.Errorf("message type %s not supported", reqMsg.Type)
@@ -174,13 +178,17 @@ func (s *WSReceive) ShellView(client *model.WSClient, reqMsg model.WSRequest) {
command, err = processor.ParseTail(reqMsg.Data) command, err = processor.ParseTail(reqMsg.Data)
} }
if command != "" && err == nil { if command != "" && err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
_, err = sshClientSession.Write(command) // _, err = sshClientSession.Write(command)
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = localClientSession.Write(command)
} }
case "ctrl-c": case "ctrl-c":
// 模拟按下 Ctrl+C // 模拟按下 Ctrl+C
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
_, err = sshClientSession.Write("\u0003\n") // _, err = sshClientSession.Write("\u0003\n")
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
_, err = localClientSession.Write("\u0003\n")
case "resize": case "resize":
// 会话窗口重置 // 会话窗口重置
msgByte, _ := json.Marshal(reqMsg.Data) msgByte, _ := json.Marshal(reqMsg.Data)
@@ -190,8 +198,10 @@ func (s *WSReceive) ShellView(client *model.WSClient, reqMsg model.WSRequest) {
} }
err = json.Unmarshal(msgByte, &data) err = json.Unmarshal(msgByte, &data)
if err == nil { if err == nil {
sshClientSession := client.ChildConn.(*ssh.SSHClientSession) // sshClientSession := client.ChildConn.(*ssh.SSHClientSession)
err = sshClientSession.Session.WindowChange(data.Rows, data.Cols) // err = sshClientSession.Session.WindowChange(data.Rows, data.Cols)
localClientSession := client.ChildConn.(*cmd.LocalClientSession)
localClientSession.WindowChange(data.Cols, data.Rows)
} }
default: default:
err = fmt.Errorf("message type %s not supported", reqMsg.Type) err = fmt.Errorf("message type %s not supported", reqMsg.Type)