MCPcopy Create free account
hub / github.com/OpenAtomFoundation/SmartIDE / parseCmdOutput

Function parseCmdOutput

cli/pkg/tunnel/forwarding.go:195–260  ·  view source on GitHub ↗

解析netstat的运行结果

(cmdOutput string)

Source from the content-addressed store, hash-verified

193
194// 解析netstat的运行结果
195func parseCmdOutput(cmdOutput string) (result []NetstatInfo) {
196 startInex := strings.Index(cmdOutput, "Active Internet connections")
197 if startInex < 0 {
198 return nil
199 }
200 strArray := strings.Split(cmdOutput[startInex+1:], "\n")
201
202 header := strArray[1]
203 indexs := []int{
204 strings.Index(header, "Proto"),
205 strings.Index(header, "Recv-Q"),
206 strings.Index(header, "Send-Q"),
207 strings.Index(header, "Local Address"),
208 strings.Index(header, "Foreign Address"),
209 strings.Index(header, "State"),
210 strings.Index(header, "PID/Program name"),
211 }
212
213 for _, index := range indexs {
214 if index < 0 {
215 common.SmartIDELog.Error(cmdOutput)
216 }
217 }
218
219 for _, str := range strArray[2:] {
220
221 if strings.Contains(str, "Not all processes could be identified, non-owned process info") ||
222 strings.Contains(str, "you would have to be root to see it all.") ||
223 strings.Contains(str, "No info could be read for \"-p\": geteuid()=1000 but you should be root.") {
224 continue
225 }
226
227 if len(strings.ReplaceAll(str, " ", "")) == 0 {
228 continue
229 }
230 if indexs[6] > len(str) { // 当最后1列的数据位置 比 当前数据还小 时
231 //common.SmartIDELog.Debug(cmdOutput)
232 common.SmartIDELog.Importance(str)
233 }
234 tmp := strings.ReplaceAll(str[indexs[6]:], " ", "")
235 pid, programName := "", ""
236 if tmp != "-" {
237 tmpArray := strings.Split(tmp, "/")
238 pid = tmpArray[0]
239 programName = tmpArray[1]
240 }
241 localAddress := strings.ReplaceAll(str[indexs[3]:indexs[4]], " ", "")
242 lastColonIndex := strings.LastIndex(localAddress, ":")
243 host := localAddress[0:lastColonIndex]
244 port, _ := strconv.Atoi(localAddress[lastColonIndex+1:]) // 从最后一个“:”开始截取
245 info := NetstatInfo{
246 Proto: strings.ReplaceAll(str[0:indexs[1]], " ", ""),
247 RecvQ: strings.ReplaceAll(str[indexs[1]:indexs[2]], " ", ""),
248 SendQ: strings.ReplaceAll(str[indexs[2]:indexs[3]], " ", ""),
249 LocalAddress: localAddress,
250 Host: host,
251 Port: port,
252 ForeignAddress: strings.ReplaceAll(str[indexs[4]:indexs[5]], " ", ""),

Callers 1

scanServerPortsFunction · 0.85

Calls 2

ImportanceMethod · 0.80
ErrorMethod · 0.45

Tested by

no test coverage detected