63 lines
1.7 KiB
Go
63 lines
1.7 KiB
Go
package exec
|
|
|
|
import (
|
|
"net/url"
|
|
"strings"
|
|
|
|
"git.lxtend.com/qqbot/constants"
|
|
"git.lxtend.com/qqbot/handler"
|
|
"git.lxtend.com/qqbot/model"
|
|
"git.lxtend.com/qqbot/service/exec"
|
|
"git.lxtend.com/qqbot/util"
|
|
)
|
|
|
|
func init() {
|
|
handler.RegisterHandler("exec", runInDocker, constants.LEVEL_USER)
|
|
handler.RegisterHelpInform("exec", "docker", "exec <command> 执行命令")
|
|
handler.RegisterHandler("reboot", restartDocker, constants.LEVEL_USER)
|
|
handler.RegisterHelpInform("reboot", "docker", "reboot 重启环境")
|
|
}
|
|
|
|
func runInDocker(msg model.Message) (reply model.Reply) {
|
|
token := util.SplitN(msg.RawMsg, 2)
|
|
if len(token) < 2 {
|
|
reply.ReplyMsg = "Usage: exec <command>"
|
|
reply.FromMsg = msg
|
|
return
|
|
}
|
|
decodedCMD, _ := url.QueryUnescape(token[1])
|
|
decodedCMD = strings.ReplaceAll(decodedCMD, ",", ",")
|
|
decodedCMD = strings.ReplaceAll(decodedCMD, "[", "[")
|
|
decodedCMD = strings.ReplaceAll(decodedCMD, "]", "]")
|
|
decodedCMD = strings.ReplaceAll(decodedCMD, "&", "&")
|
|
if res, err := exec.DockerContainer.ExecCommandInContainer(decodedCMD); err != nil {
|
|
reply.ReplyMsg = "Error: " + err.Error()
|
|
reply.ReferOriginMsg = true
|
|
reply.FromMsg = msg
|
|
return
|
|
} else {
|
|
pos := strings.LastIndex(res, "\n")
|
|
if pos != -1 {
|
|
res = res[:pos-1]
|
|
}
|
|
reply.ReplyMsg = res
|
|
reply.ReferOriginMsg = true
|
|
reply.FromMsg = msg
|
|
return
|
|
}
|
|
}
|
|
|
|
func restartDocker(msg model.Message) (reply model.Reply) {
|
|
if err := exec.DockerContainer.RestartAndCleanContainer(); err != nil {
|
|
reply.ReplyMsg = "Error: " + err.Error()
|
|
reply.ReferOriginMsg = true
|
|
reply.FromMsg = msg
|
|
return
|
|
} else {
|
|
reply.ReplyMsg = "Restarted"
|
|
reply.ReferOriginMsg = true
|
|
reply.FromMsg = msg
|
|
return
|
|
}
|
|
}
|