示例#1
0
func ListenPorts() []int64 {
	bs, err := systool.CmdOutBytes("ss", "-n", "-l", "-t")
	if err != nil {
		log.Error("ss -n -l exec fail: %s", err)
		return []int64{}
	}

	reader := bufio.NewReader(bytes.NewBuffer(bs))

	// ignore the first line
	var line []byte
	line, _, err = reader.ReadLine()
	if err == io.EOF || err != nil {
		return []int64{}
	}

	ret := []int64{}

	for {
		line, _, err = reader.ReadLine()
		if err == io.EOF || err != nil {
			break
		}

		arr := strings.Fields(string(line))
		arrlen := len(arr)

		if arrlen != 4 && arrlen != 5 {
			log.Error("output of [ss -n -l -t] format error")
			continue
		}

		ci := 2
		if arrlen == 5 {
			ci = 3
		}

		location := strings.LastIndex(arr[ci], ":")
		port := arr[ci][location+1:]

		if p, e := strconv.ParseInt(port, 10, 64); e != nil {
			log.Error("parse port to int64 fail: %s", e)
			continue
		} else {
			ret = append(ret, p)
		}

	}

	ret = slicetool.SliceUniqueInt64(ret)

	log.Info("listening ports: %v", ret)
	return ret
}
示例#2
0
func AllProcs() (ps []*Proc, err error) {
	var dirs []string
	dirs, err = filetool.DirsUnder("/proc")
	if err != nil {
		return
	}

	// id dir is a number, it should be a pid. but don't trust it
	dirs_len := len(dirs)
	if dirs_len == 0 {
		return
	}

	var pid int
	var name_state [2]string
	var cmdline string
	for i := 0; i < dirs_len; i++ {
		if pid, err = strconv.Atoi(dirs[i]); err != nil {
			err = nil
			continue
		} else {
			status_file := fmt.Sprintf("/proc/%d/status", pid)
			cmdline_file := fmt.Sprintf("/proc/%d/cmdline", pid)
			if !filetool.IsExist(status_file) || !filetool.IsExist(cmdline_file) {
				continue
			}

			name_state, err = ReadProcStatus(status_file)
			if err != nil {
				log.Error("read %s fail: %s", status_file, err)
				continue
			}

			cmdline, err = filetool.ReadFileToStringNoLn(cmdline_file)
			if err != nil {
				log.Error("read %s fail: %s", cmdline_file, err)
				continue
			}

			p := Proc{Pid: pid, Name: name_state[0], State: name_state[1], Cmdline: cmdline}
			ps = append(ps, &p)
		}
	}

	return
}
示例#3
0
文件: command.go 项目: HYQMartin/star
func CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool) {
	done := make(chan error)
	go func() {
		done <- cmd.Wait()
	}()

	var err error
	select {
	case <-time.After(timeout):
		//timeout
		if err = cmd.Process.Kill(); err != nil {
			log.Error("failed to kill: %s, error: %s", cmd.Path, err)
		}
		go func() {
			<-done // allow goroutine to exit
		}()
		log.Info("process:%s killed", cmd.Path)
		return err, true
	case err = <-done:
		return err, false
	}
}