parsePsOutput parses the text output of tasklist/ps into a PsResponse.
(output, osName string)
| 165 | |
| 166 | // parsePsOutput parses the text output of tasklist/ps into a PsResponse. |
| 167 | func parsePsOutput(output, osName string) *implantpb.PsResponse { |
| 168 | resp := &implantpb.PsResponse{} |
| 169 | lines := strings.Split(output, "\n") |
| 170 | |
| 171 | if isWindows(osName) { |
| 172 | // Windows: tasklist /FO CSV /NH |
| 173 | // "System Idle Process","0","Services","0","8 K" |
| 174 | for _, line := range lines { |
| 175 | line = strings.TrimSpace(line) |
| 176 | if line == "" || !strings.HasPrefix(line, "\"") { |
| 177 | continue |
| 178 | } |
| 179 | r := csv.NewReader(strings.NewReader(line)) |
| 180 | record, err := r.Read() |
| 181 | if err != nil || len(record) < 2 { |
| 182 | continue |
| 183 | } |
| 184 | pid, _ := strconv.ParseUint(record[1], 10, 32) |
| 185 | proc := &implantpb.Process{ |
| 186 | Name: record[0], |
| 187 | Pid: uint32(pid), |
| 188 | } |
| 189 | if len(record) >= 3 { |
| 190 | proc.Owner = record[2] |
| 191 | } |
| 192 | resp.Processes = append(resp.Processes, proc) |
| 193 | } |
| 194 | } else { |
| 195 | // Linux: ps -eo pid,ppid,user,comm,args --no-headers |
| 196 | // 1 0 root systemd /sbin/init |
| 197 | for _, line := range lines { |
| 198 | line = strings.TrimSpace(line) |
| 199 | if line == "" { |
| 200 | continue |
| 201 | } |
| 202 | fields := strings.Fields(line) |
| 203 | if len(fields) < 4 { |
| 204 | continue |
| 205 | } |
| 206 | pid, err := strconv.ParseUint(fields[0], 10, 32) |
| 207 | if err != nil { |
| 208 | continue // skip non-numeric (header) |
| 209 | } |
| 210 | ppid, _ := strconv.ParseUint(fields[1], 10, 32) |
| 211 | proc := &implantpb.Process{ |
| 212 | Pid: uint32(pid), |
| 213 | Ppid: uint32(ppid), |
| 214 | Owner: fields[2], |
| 215 | Name: fields[3], |
| 216 | } |
| 217 | if len(fields) >= 5 { |
| 218 | proc.Args = strings.Join(fields[4:], " ") |
| 219 | proc.Path = fields[4] |
| 220 | } |
| 221 | resp.Processes = append(resp.Processes, proc) |
| 222 | } |
| 223 | } |
| 224 | return resp |