diff --git a/bin/node/server.go b/bin/node/server.go index f8d5649..9067cf3 100644 --- a/bin/node/server.go +++ b/bin/node/server.go @@ -24,6 +24,7 @@ func main() { //set cpu usage runtime.GOMAXPROCS(*gomax) + models.InitPwd() if err := models.Init(); err != nil { log.Error(err.Error()) return diff --git a/models/common.go b/models/common.go index a4e910d..643b865 100644 --- a/models/common.go +++ b/models/common.go @@ -1,15 +1,29 @@ package models import ( - "sunteng/commons/db/imgo" + "errors" + "os/exec" + "sunteng/commons/db/imgo" + "sunteng/commons/log" "sunteng/cronsun/conf" ) var ( initialized bool + + needPassword = false + SudoErr = errors.New("sudo need password") ) +func InitPwd() { + // 不支持 windows + if _, err := exec.Command("sh", "-c", "echo |sudo -S echo &>/dev/null").Output(); err != nil { + log.Warnf("当前用户 sudo 需要密码,所有指定用户执行的命令都将失败") + needPassword = true + } +} + func Init() (err error) { if initialized { return diff --git a/models/job.go b/models/job.go index 5881985..602e40f 100644 --- a/models/job.go +++ b/models/job.go @@ -25,6 +25,7 @@ type Job struct { Name string `json:"name"` Group string `json:"group"` Command string `json:"cmd"` + User string `json:"user"` Rules []*JobRule `json:"rules"` Pause bool `json:"pause"` // 可手工控制的状态 @@ -170,8 +171,20 @@ func (j *Job) String() string { // Run 执行任务 func (j *Job) Run() { - cmd, t := strings.Split(j.Command, " "), time.Now() - out, err := exec.Command(cmd[0], cmd[1:]...).Output() + t := time.Now() + var cmd *exec.Cmd + if len(j.User) > 0 { + if needPassword { + j.Fail(t, SudoErr) + return + } + cmd = exec.Command("sudo", "su", j.User, "-c", j.Command) + } else { + args := strings.Split(j.Command, " ") + cmd = exec.Command(args[0], args[1:]...) + } + + out, err := cmd.Output() if err != nil { j.Fail(t, err) return