【问题标题】:Linux lsof Need help parsing outputLinux lsof 需要帮助解析输出
【发布时间】:2015-07-06 14:27:54
【问题描述】:

我在 linux 系统上使用以下命令:

lsof -i -n | egrep '\<ssh\>'|awk '{print $8,$9}'

它会产生如下输出:

192.168.199.52:ssh->192.168.199.254:17598 (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:17598 (ESTABLISHED)
192.168.199.52:56448->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56449->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56454->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56458->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56460->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56468->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:56671 (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:56671 (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:56672 (ESTABLISHED)

我只想提取左侧的 IP 地址和“->”字段右侧的 IP 地址。如何轻松提取这两个文件并将它们重新组合成以下格式:

192.168.199.52->192.168.199.254

【问题讨论】:

  • 最好显示lsof -i -n的原始输出,否则你会得到类似lsof | egrep | awk | awk的东西,这非常低效。
  • 为什么要打印 9 美元而不想要它?

标签: linux bash awk lsof


【解决方案1】:

类似:

lsof -i -n | awk '$9 ~ /:ssh(-|$)/{ gsub(/:[^-]*/, "", $9); print $9 }'

或者用 8 美元代替 9 美元。

awk 命令详情:

$9 ~ /:ssh(-|$)/ {           # when ":ssh" is at the end of field 9 or
                             # followed by an hyphen
    gsub(/:[^-]*/, "", $9);  # remove all the semi-colon followed by characters that
                             # are not an hyphen from the field 9
    print $9                 # and print it
}

【讨论】:

  • fedorqui 是对的——我不想要 9 美元的字段——不确定我当时在考虑什么。上面的效果很棒,我刚把 9 美元改成了 8 美元。
  • @Rick:仅供参考,在我的系统中,它仅适用于第 9 个字段。
  • @Rick:我犯了一个错误。 ":ssh" 也可以在连字符之前,看看正确的答案。
  • 为避免lsof 的各个版本出现字段编号问题,您可以使用-F option with n field specifier. See man lsof(8): OUTPUT FOR OTHER PROGRAMS。然后,您可以通过管道发送到 grep -E '^n' 来过滤它们。如果您想要更多输出,则必须将不同的字段说明符传递给-F,然后解析出信息。示例:sudo lsof -F 'n' -n -i:22 | grep -E '^n' 或更多字段,以 null 结尾 0 字符:sudo lsof -F 'PnLt0' -n -i:2222
猜你喜欢
  • 1970-01-01
  • 2021-10-23
  • 2011-08-15
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多