How to parse strace in shell into plain text?

一个人想着一个人 提交于 2019-11-27 23:19:09
kenorb

The problem why read doesn't work, because shell is already escaping the characters, so the string is doubled escaped, therefore \r\n is printed as rn.

To ignore escaping of characters by shell, you can use read -r which allow backslashes to escape any characters (so they're treated literally). Here is example:

while read -r line; do printf "%b\n" "$line"; done < strace.log | strings

Since it's a binary data, above example also includes strings command to display only printable strings.

Strace also support printing all strings in hex when -x is specified, but it'll work the same.


Here is the version to parse strace output in real-time:

while read -r line;
    do printf "%b\n" "$line" | strings
done < <(sudo strace -e recvfrom,sendto -s 1000 -fp $(pgrep -n php) 2>/dev/stdout)

Further more strings, can be replaced by more specific filter using grep, to get only what is inside double quotes:

grep -o '".\+[^"]"' | grep -o '[^"]\+[^"]'

however this may still print binary formats.

To avoid that, lets simplify the whole process, so lets define the following formatter alias:

alias format-strace='grep --line-buffered -o '\''".\+[^"]"'\'' | grep --line-buffered -o '\''[^"]*[^"]'\'' | while read -r line; do printf "%b" $line; done | tr "\r\n" "\275\276" | tr -d "[:cntrl:]" | tr "\275\276" "\r\n"'

where:

  • grep -o '".\+[^"]"' - select double-quoted string with quotes
  • grep -o '[^"]*[^"]' - select text within the double quotes
  • while read -r line - store each line into $line and do some action (help read)
  • printf "%b" $line - print line by expanding backslash escape sequences
  • tr "\r\n" "\275\276" - temporarily replace \r\n into \275\276
  • tr -d "[:cntrl:]" - remove all control characters
  • tr "\275\276" "\r\n" - restore new line endings

then the complete example to trace some command (e.g. php) can look like:

strace -e trace=read,write,recvfrom,sendto -s 1000 -fp $(pgrep -n php) 2>&1 | format-strace

Check for similar example: How to view the output of a running process in another bash session? at Unix.SE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!