- 修复mysql模式下「资产授权列表」「用户授权列表」「用户组授权列表」无法使用的问题 fixed #315

- 修复资产新增、修改无权限的缺陷 fixed #314
- 修复执行动态指令时多行失败且无法自动执行的问题 fixed #313 #310
- 修复计划任务无法选择资产的问题 fixed #312
- 修复导入导出备份无效的问题 fixed #303
- 增加「资产详情」「资产授权」「用户详情」「用户授权」「用户组详情」「用户组授权」「角色详情」「授权策略详情」按钮
- 修复资产列表使用IP搜索无效的问题
- 资产列表增加最近接入时间排序、增加修改每页数量 fixed #311
- 修复登录页面双因素认证输入框无法自动获取焦点的问题 fixed #311
- 增加普通页面资产列表最后接入时间排序 fixed #311
- 计划任务增加执行本机系统命令
This commit is contained in:
dushixiang
2022-11-20 17:36:27 +08:00
parent 49797164ce
commit ded4dc492a
26 changed files with 421 additions and 112 deletions

View File

@ -27,6 +27,7 @@ const (
JobStatusNotRunning = "not-running" // 计划任务未运行状态
FuncCheckAssetStatusJob = "check-asset-status-job" // 检测资产是否在线
FuncShellJob = "shell-job" // 执行Shell脚本
JobModeSelf = "self" // 本机
JobModeAll = "all" // 全部资产
JobModeCustom = "custom" // 自定义选择资产

View File

@ -22,6 +22,7 @@ type Asset struct {
Active bool `json:"active"`
ActiveMessage string `gorm:"type:varchar(200)" json:"activeMessage"`
Created common.JsonTime `json:"created"`
LastAccessTime common.JsonTime `json:"lastAccessTime"`
Tags string `json:"tags"`
Owner string `gorm:"index,type:varchar(36)" json:"owner"`
Encrypted bool `json:"encrypted"`
@ -29,18 +30,19 @@ type Asset struct {
}
type AssetForPage struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
IP string `json:"ip"`
Protocol string `json:"protocol"`
Port int `json:"port"`
Active bool `json:"active"`
ActiveMessage string `json:"activeMessage"`
Created common.JsonTime `json:"created"`
Tags string `json:"tags"`
Owner string `json:"owner"`
OwnerName string `json:"ownerName"`
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
IP string `json:"ip"`
Protocol string `json:"protocol"`
Port int `json:"port"`
Active bool `json:"active"`
ActiveMessage string `json:"activeMessage"`
Created common.JsonTime `json:"created"`
LastAccessTime common.JsonTime `json:"lastAccessTime"`
Tags string `json:"tags"`
Owner string `json:"owner"`
OwnerName string `json:"ownerName"`
}
func (r *Asset) TableName() string {

View File

@ -6,6 +6,7 @@ import (
"strconv"
"strings"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/config"
@ -44,7 +45,7 @@ func (r assetRepository) FindByProtocolAndIds(c context.Context, protocol string
}
func (r assetRepository) Find(c context.Context, pageIndex, pageSize int, name, protocol, tags, ip, port, active, order, field string) (o []model.AssetForPage, total int64, err error) {
db := r.GetDB(c).Table("assets").Select("assets.id,assets.name,assets.ip,assets.port,assets.protocol,assets.active,assets.active_message,assets.owner,assets.created,assets.tags,assets.description, users.nickname as owner_name").Joins("left join users on assets.owner = users.id")
db := r.GetDB(c).Table("assets").Select("assets.id,assets.name,assets.ip,assets.port,assets.protocol,assets.active,assets.active_message,assets.owner,assets.created,assets.last_access_time,assets.tags,assets.description, users.nickname as owner_name").Joins("left join users on assets.owner = users.id")
dbCounter := r.GetDB(c).Table("assets")
if len(name) > 0 {
@ -104,7 +105,8 @@ func (r assetRepository) Find(c context.Context, pageIndex, pageSize int, name,
case "protocol":
case "ip":
case "active":
case "lastAccessTime":
field = "last_access_time"
default:
field = "created"
}
@ -285,7 +287,7 @@ func (r assetRepository) ExistById(c context.Context, id string) (bool, error) {
}
func (r assetRepository) FindMyAssets(c context.Context, pageIndex, pageSize int, name, protocol, tags string, assetIds []string, order, field string) (o []model.AssetForPage, total int64, err error) {
db := r.GetDB(c).Table("assets").Select("assets.id,assets.name,assets.protocol,assets.active,assets.active_message,assets.tags,assets.description").
db := r.GetDB(c).Table("assets").Select("assets.id,assets.name,assets.protocol,assets.active,assets.active_message,assets.tags,assets.description,assets.last_access_time,").
Where("id in ?", assetIds)
dbCounter := r.GetDB(c).Table("assets").Where("id in ?", assetIds)
@ -328,7 +330,8 @@ func (r assetRepository) FindMyAssets(c context.Context, pageIndex, pageSize int
case "protocol":
case "ip":
case "active":
case "lastAccessTime":
field = "last_access_time"
default:
field = "created"
}
@ -362,3 +365,8 @@ func (r assetRepository) FindMyAssetTags(c context.Context, assetIds []string) (
return utils.Distinct(o), nil
}
func (r assetRepository) UpdateLastAccessTime(ctx context.Context, assetId string, now common.JsonTime) error {
asset := &model.Asset{ID: assetId, LastAccessTime: now}
return r.GetDB(ctx).Table("assets").Updates(asset).Error
}

View File

@ -71,8 +71,7 @@ func (r authorisedRepository) FindAssetPage(c context.Context, pageIndex, pageSi
db := r.GetDB(c).Table("assets").
Select("authorised.id, authorised.created, assets.id as asset_id, assets.name as asset_name, strategies.id as strategy_id, strategies.name as strategy_name ").
Joins("left join authorised on authorised.asset_id = assets.id").
Joins("left join strategies on strategies.id = authorised.strategy_id").
Group("assets.id")
Joins("left join strategies on strategies.id = authorised.strategy_id")
dbCounter := r.GetDB(c).Table("assets").Joins("left join authorised on assets.id = authorised.asset_id").Group("assets.id")
if assetName != "" {
@ -110,8 +109,7 @@ func (r authorisedRepository) FindUserPage(c context.Context, pageIndex, pageSiz
db := r.GetDB(c).Table("users").
Select("authorised.id, authorised.created, users.id as user_id, users.nickname as user_name, strategies.id as strategy_id, strategies.name as strategy_name ").
Joins("left join authorised on authorised.user_id = users.id").
Joins("left join strategies on strategies.id = authorised.strategy_id").
Group("users.id")
Joins("left join strategies on strategies.id = authorised.strategy_id")
dbCounter := r.GetDB(c).Table("assets").Joins("left join authorised on assets.id = authorised.asset_id").Group("assets.id")
if userName != "" {
@ -140,8 +138,7 @@ func (r authorisedRepository) FindUserGroupPage(c context.Context, pageIndex, pa
db := r.GetDB(c).Table("user_groups").
Select("authorised.id, authorised.created, user_groups.id as user_group_id, user_groups.name as user_group_name, strategies.id as strategy_id, strategies.name as strategy_name ").
Joins("left join authorised on authorised.user_group_id = user_groups.id").
Joins("left join strategies on strategies.id = authorised.strategy_id").
Group("user_groups.id")
Joins("left join strategies on strategies.id = authorised.strategy_id")
dbCounter := r.GetDB(c).Table("assets").Joins("left join authorised on assets.id = authorised.asset_id").Group("assets.id")
if userName != "" {

View File

@ -55,7 +55,12 @@ func getJob(j *model.Job) (job cron.Job, err error) {
Metadata: j.Metadata,
}
case nt.FuncShellJob:
job = ShellJob{ID: j.ID, Mode: j.Mode, ResourceIds: j.ResourceIds, Metadata: j.Metadata}
job = ShellJob{
ID: j.ID,
Mode: j.Mode,
ResourceIds: j.ResourceIds,
Metadata: j.Metadata,
}
default:
return nil, errors.New("未识别的任务")
}

View File

@ -5,12 +5,12 @@ import (
"encoding/json"
"errors"
"fmt"
"next-terminal/server/common"
"next-terminal/server/common/nt"
"next-terminal/server/common/term"
"strings"
"time"
"next-terminal/server/common"
"next-terminal/server/common/nt"
"next-terminal/server/common/term"
"next-terminal/server/log"
"next-terminal/server/model"
"next-terminal/server/repository"
@ -35,13 +35,19 @@ func (r ShellJob) Run() {
return
}
var assets []model.Asset
if r.Mode == nt.JobModeAll {
assets, _ = repository.AssetRepository.FindByProtocol(context.TODO(), "ssh")
} else {
assets, _ = repository.AssetRepository.FindByProtocolAndIds(context.TODO(), "ssh", strings.Split(r.ResourceIds, ","))
switch r.Mode {
case nt.JobModeAll:
assets, _ := repository.AssetRepository.FindByProtocol(context.TODO(), "ssh")
r.executeShellByAssets(assets)
case nt.JobModeCustom:
assets, _ := repository.AssetRepository.FindByProtocolAndIds(context.TODO(), "ssh", strings.Split(r.ResourceIds, ","))
r.executeShellByAssets(assets)
case nt.JobModeSelf:
r.executeShellByLocal()
}
}
func (r ShellJob) executeShellByAssets(assets []model.Asset) {
if len(assets) == 0 {
return
}
@ -89,7 +95,7 @@ func (r ShellJob) Run() {
go func() {
t1 := time.Now()
result, err := exec(metadataShell.Shell, asset.AccessGatewayId, ip, port, username, password, privateKey, passphrase)
result, err := execute(metadataShell.Shell, asset.AccessGatewayId, ip, port, username, password, privateKey, passphrase)
elapsed := time.Since(t1)
var msg string
if err != nil {
@ -124,7 +130,36 @@ func (r ShellJob) Run() {
_ = repository.JobLogRepository.Create(context.TODO(), &jobLog)
}
func exec(shell, accessGatewayId, ip string, port int, username, password, privateKey, passphrase string) (string, error) {
func (r ShellJob) executeShellByLocal() {
var metadataShell MetadataShell
err := json.Unmarshal([]byte(r.Metadata), &metadataShell)
if err != nil {
log.Error("JSON数据解析失败", log.String("err", err.Error()))
return
}
now := time.Now()
var msg = ""
log.Debug("run local command", log.String("cmd", metadataShell.Shell))
output, outerr, err := utils.Exec(metadataShell.Shell)
if err != nil {
msg = fmt.Sprintf("命令执行失败,错误内容为:「%v」耗时「%v」", err.Error(), time.Since(now).String())
} else {
msg = fmt.Sprintf("命令执行成功stdout 返回值「%v」stderr 返回值「%v」耗时「%v」", output, outerr, time.Since(now).String())
}
_ = repository.JobRepository.UpdateLastUpdatedById(context.Background(), r.ID)
jobLog := model.JobLog{
ID: utils.UUID(),
JobId: r.ID,
Timestamp: common.NowJsonTime(),
Message: msg,
}
_ = repository.JobLogRepository.Create(context.Background(), &jobLog)
}
func execute(shell, accessGatewayId, ip string, port int, username, password, privateKey, passphrase string) (string, error) {
if accessGatewayId != "" && accessGatewayId != "-" {
g, err := GatewayService.GetGatewayById(accessGatewayId)
if err != nil {

View File

@ -33,10 +33,12 @@ var DefaultMenu = []*model.Menu{
),
model.NewMenu("asset-add", "新建", "asset",
model.NewPermission("POST", "/assets"),
model.NewPermission("GET", "/access-gateways"),
),
model.NewMenu("asset-edit", "编辑", "asset",
model.NewPermission("GET", "/assets/:id"),
model.NewPermission("PUT", "/assets/:id"),
model.NewPermission("GET", "/access-gateways"),
),
model.NewMenu("asset-del", "删除", "asset",
model.NewPermission("DELETE", "/assets/:id"),
@ -191,6 +193,10 @@ var DefaultMenu = []*model.Menu{
model.NewPermission("POST", "/storage-logs/clear"),
),
model.NewMenu("session-command", "命令日志", "log-audit",
model.NewPermission("GET", "/session-commands/paging"),
),
model.NewMenu("ops", "系统运维", "root"),
model.NewMenu("job", "计划任务", "ops",

View File

@ -366,6 +366,9 @@ func (service sessionService) Create(clientIp, assetId, mode string, user *model
if err := repository.SessionRepository.Create(context.TODO(), s); err != nil {
return nil, err
}
if err := repository.AssetRepository.UpdateLastAccessTime(context.Background(), s.AssetId, common.NowJsonTime()); err != nil {
return nil, err
}
return s, nil
}

18
server/utils/command.go Normal file
View File

@ -0,0 +1,18 @@
package utils
import (
"bytes"
"os/exec"
)
// Exec 执行shell命令
func Exec(command string) (string, string, error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command("bash", "-c", command)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), stderr.String(), err
}

View File

@ -0,0 +1,22 @@
package utils
import "testing"
func TestExec(t *testing.T) {
commands := []string{
`pwd`,
`whoami`,
`cat /etc/resolv.conf`,
`echo "test" > /tmp/ddtest`,
`rm -rf /tmp/ddtest`,
}
for _, command := range commands {
output, errout, err := Exec(command)
if err != nil {
t.Fatal(err)
}
t.Log("output:", output)
t.Log("errout:", errout)
}
}