package sys
|
|
import (
|
"errors"
|
"os/exec"
|
|
"fmt"
|
"net"
|
"strings"
|
"time"
|
)
|
|
// 检查 root权限
|
func CheckRootPermissions() bool {
|
showRootCMD := exec.Command("/bin/sh", "-c", "ls /root/")
|
if _, err := showRootCMD.Output(); err != nil {
|
return false
|
}
|
|
return true
|
}
|
|
// 配置时区
|
func TimeZone() (string, int64) {
|
cmd := exec.Command("/bin/sh", "-c", "echo -n $TZ")
|
tz, _ := cmd.Output()
|
if tzstr := string(tz); tzstr != "" {
|
return tzstr, time.Now().Unix()
|
}
|
|
zone, _ := time.Now().Zone()
|
return zone, time.Now().Unix()
|
}
|
|
func NTPConfig() (bool, string, string) {
|
status, server, interval := false, "", ""
|
|
cmd := exec.Command("/bin/sh", "-c", "crontab -l | grep ntpdate | tr -d '\n'")
|
cron, _ := cmd.Output()
|
if task := string(cron); task != "" {
|
status = true
|
slice := strings.Split(task, " ")
|
interval, server = slice[0][2:], slice[len(slice)-1]
|
}
|
|
return status, server, interval
|
}
|
|
// 设置时区
|
func SetTimeZone(tz string) bool {
|
if _, err := time.LoadLocation(tz); err != nil {
|
return false
|
}
|
|
// set env
|
envCMD := exec.Command("/bin/sh", "-c", "TZ=%s", tz)
|
envCMD.Run()
|
// change permanent to the file '.profile'
|
|
cleanTZ := exec.Command("/bin/sh", "-c", "sed -i '/^TZ=.*$/d' ~/.profile")
|
cleanTZ.Run()
|
|
TZ := "TZ='" + tz + "'; export TZ"
|
appendTZCMD := fmt.Sprintf("echo \"%s\" >> ~/.profile;", TZ)
|
appendTZ := exec.Command("/bin/sh", "-c", appendTZCMD)
|
appendTZ.Run()
|
|
return true
|
}
|
|
// 配置系统时间
|
func SetLocalTime(newTime string) bool {
|
const TimeLayout = "2006-01-02 15:04:05"
|
_, err := time.Parse(TimeLayout, newTime)
|
if err != nil {
|
return false
|
}
|
|
args := []string{"-s", newTime}
|
exec.Command("date", args...).Run()
|
stopNTPCron()
|
|
return true
|
}
|
|
const NTPCRONTABFILE = "~/.webServer.crontab"
|
|
func EnableNTPCron(server string, interval int) bool {
|
stopNTPCron()
|
|
if ip := net.ParseIP(server); ip == nil {
|
return false
|
}
|
|
addTask := fmt.Sprintf("echo \"*/%d * * * * /usr/sbin/ntpdate %s\" >> %s; crontab %s", interval, server, NTPCRONTABFILE, NTPCRONTABFILE)
|
exec.Command("/bin/sh", "-c", addTask).Run()
|
|
return true
|
}
|
|
func stopNTPCron() {
|
cleanTask := fmt.Sprintf("crontab -l | grep -v /usr/sbin/ntpdate > %s; crontab %s", NTPCRONTABFILE, NTPCRONTABFILE)
|
exec.Command("/bin/sh", "-c", cleanTask).Run()
|
}
|
|
func RunNTPDate(server string) (bool, error) {
|
if ip := net.ParseIP(server); ip == nil {
|
return false, errors.New("参数错误")
|
}
|
|
ntpdate := fmt.Sprintf("/usr/sbin/ntpdate %s", server)
|
return true, exec.Command("/bin/sh", "-c", ntpdate).Run()
|
}
|