2017-03-10 09:08:51 +00:00
|
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
import (
|
2017-04-02 02:38:49 +00:00
|
|
|
|
"crypto/md5"
|
|
|
|
|
"encoding/hex"
|
|
|
|
|
"math/rand"
|
|
|
|
|
"os/exec"
|
|
|
|
|
"time"
|
2017-04-20 08:59:03 +00:00
|
|
|
|
"runtime"
|
|
|
|
|
"github.com/Tang-RoseChild/mahonia"
|
2017-03-10 09:08:51 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2017-04-17 08:13:43 +00:00
|
|
|
|
// 执行shell命令,可设置执行超时时间
|
|
|
|
|
func ExecShellWithTimeout(timeout int, command string, args... string) (string, error) {
|
|
|
|
|
cmd := exec.Command(command, args...)
|
2017-04-21 05:50:46 +00:00
|
|
|
|
|
|
|
|
|
// 不限制超时时间
|
|
|
|
|
if timeout <= 0 {
|
|
|
|
|
output ,err := cmd.CombinedOutput()
|
|
|
|
|
return string(output), err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2017-04-17 08:13:43 +00:00
|
|
|
|
d := time.Duration(timeout) * time.Second
|
|
|
|
|
timer := time.AfterFunc(d, func() {
|
2017-04-21 05:50:46 +00:00
|
|
|
|
// 超时kill进程
|
2017-04-17 08:13:43 +00:00
|
|
|
|
cmd.Process.Kill()
|
|
|
|
|
})
|
|
|
|
|
output ,err := cmd.CombinedOutput()
|
|
|
|
|
timer.Stop()
|
|
|
|
|
|
|
|
|
|
return string(output), err
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-10 09:08:51 +00:00
|
|
|
|
// 生成长度为length的随机字符串
|
|
|
|
|
func RandString(length int64) string {
|
2017-04-02 02:38:49 +00:00
|
|
|
|
sources := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
|
|
|
|
result := []byte{}
|
|
|
|
|
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
|
|
|
sourceLength := len(sources)
|
|
|
|
|
var i int64 = 0
|
|
|
|
|
for ; i < length; i++ {
|
|
|
|
|
result = append(result, sources[r.Intn(sourceLength)])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return string(result)
|
2017-03-10 09:08:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 生成32位MD5摘要
|
|
|
|
|
func Md5(str string) string {
|
2017-04-02 02:38:49 +00:00
|
|
|
|
m := md5.New()
|
|
|
|
|
m.Write([]byte(str))
|
2017-03-10 09:08:51 +00:00
|
|
|
|
|
2017-04-02 02:38:49 +00:00
|
|
|
|
return hex.EncodeToString(m.Sum(nil))
|
2017-03-10 09:08:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 生成0-max之间随机数
|
|
|
|
|
func RandNumber(max int) int {
|
2017-04-02 02:38:49 +00:00
|
|
|
|
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
2017-03-10 09:08:51 +00:00
|
|
|
|
|
2017-04-02 02:38:49 +00:00
|
|
|
|
return r.Intn(max)
|
2017-04-20 08:59:03 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 判断当前系统是否是windows
|
|
|
|
|
func IsWindows() bool {
|
|
|
|
|
return runtime.GOOS == "windows"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GBK编码转换为UTF8
|
|
|
|
|
func GBK2UTF8(s string) (string, bool) {
|
|
|
|
|
dec := mahonia.NewDecoder("gbk")
|
|
|
|
|
|
|
|
|
|
return dec.ConvertStringOK(s)
|
2017-04-03 07:27:19 +00:00
|
|
|
|
}
|