104 lines
2.7 KiB
Go
104 lines
2.7 KiB
Go
package ssh
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"be.ems/src/framework/logger"
|
|
"be.ems/src/framework/utils/cmd"
|
|
"be.ems/src/framework/utils/parse"
|
|
)
|
|
|
|
// FileListRow 文件列表行数据
|
|
type FileListRow struct {
|
|
FileType string `json:"fileType"` // 文件类型
|
|
FileMode string `json:"fileMode"` // 文件的权限
|
|
LinkCount int64 `json:"linkCount"` // 硬链接数目
|
|
Owner string `json:"owner"` // 所属用户
|
|
Group string `json:"group"` // 所属组
|
|
Size string `json:"size"` // 文件的大小
|
|
ModifiedTime int64 `json:"modifiedTime"` // 最后修改时间,单位为秒
|
|
FileName string `json:"fileName"` // 文件的名称
|
|
}
|
|
|
|
// 文件列表
|
|
// search 文件名后模糊*
|
|
//
|
|
// return 行记录,异常
|
|
func FileList(sshClient *ConnSSH, path, search string) ([]FileListRow, error) {
|
|
var rows []FileListRow
|
|
rowStr := ""
|
|
|
|
// 发送命令
|
|
searchStr := "*"
|
|
if search != "" {
|
|
searchStr = search + searchStr
|
|
}
|
|
// cd /var/log && find. -maxdepth 1 -name'mme*' -exec ls -lthd --time-style=+%s {} +
|
|
cmdStr := fmt.Sprintf("cd %s && find . -maxdepth 1 -name '%s' -exec ls -lthd --time-style=+%%s {} +", path, searchStr)
|
|
// cd /var/log && ls -lthd --time-style=+%s mme*
|
|
// cmdStr := fmt.Sprintf("cd %s && ls -lthd --time-style=+%%s %s", path, searchStr)
|
|
|
|
// 是否远程客户端读取
|
|
if sshClient == nil {
|
|
resultStr, err := cmd.Execf(cmdStr)
|
|
if err != nil {
|
|
logger.Errorf("Ne FileList Path: %s, Search: %s, Error:%s", path, search, err.Error())
|
|
return rows, err
|
|
}
|
|
rowStr = resultStr
|
|
} else {
|
|
resultStr, err := sshClient.RunCMD(cmdStr)
|
|
if err != nil {
|
|
logger.Errorf("Ne FileList Path: %s, Search: %s, Error:%s", path, search, err.Error())
|
|
return rows, err
|
|
}
|
|
rowStr = resultStr
|
|
}
|
|
|
|
// 遍历组装
|
|
rowStrList := strings.Split(rowStr, "\n")
|
|
for _, rowStr := range rowStrList {
|
|
if rowStr == "" {
|
|
continue
|
|
}
|
|
// 使用空格对字符串进行切割
|
|
fields := strings.Fields(rowStr)
|
|
|
|
// 拆分不足7位跳过
|
|
if len(fields) != 7 {
|
|
continue
|
|
}
|
|
|
|
// 文件类型
|
|
fileMode := fields[0]
|
|
fileType := "file"
|
|
if fileMode[0] == 'd' {
|
|
fileType = "dir"
|
|
} else if fileMode[0] == 'l' {
|
|
fileType = "symlink"
|
|
}
|
|
|
|
// 文件名
|
|
fileName := fields[6]
|
|
if fileName == "." {
|
|
continue
|
|
} else if strings.HasPrefix(fileName, "./") {
|
|
fileName = strings.TrimPrefix(fileName, "./")
|
|
}
|
|
|
|
// 提取各个字段的值
|
|
rows = append(rows, FileListRow{
|
|
FileMode: fileMode,
|
|
FileType: fileType,
|
|
LinkCount: parse.Number(fields[1]),
|
|
Owner: fields[2],
|
|
Group: fields[3],
|
|
Size: fields[4],
|
|
ModifiedTime: parse.Number(fields[5]),
|
|
FileName: fileName,
|
|
})
|
|
}
|
|
return rows, nil
|
|
}
|