5
\$\begingroup\$

I want to use the output of the terminal command ldd:

root@kali-vm:~/Desktop# ldd simple
    linux-gate.so.1 =>  (0xb7722000)
    libcurl-gnutls.so.4 => /usr/lib/i386-linux-gnu/libcurl-gnutls.so.4 (0xb769c000)
    libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7539000)
    libidn.so.11 => /usr/lib/i386-linux-gnu/libidn.so.11 (0xb7505000)

And use it to build a dictionary that uses the library name as key and the path to the library as value. I've come up with this little Python snippet:

  # Get List of Librairies in Dictionary
  lddOut = subprocess.check_output(['ldd', fileName])
  libraries = {}
  for line in lddOut.splitlines():
    arr = line.split(" => ")
    library = arr[0].strip('\t')
    try:
      path = arr[1].split(' (0x')[0]
    except:
      pass
    libraries[library] = path

It works fine for my needs but I'm at the point where I don't want my code to just work but want it optimized and well structured/programmed. How can I improve this snippet?

EDIT: Note that I do not want the address (ie 0xbxxxxxx) in my dictionary

\$\endgroup\$
0

1 Answer 1

5
\$\begingroup\$

This kind of parsing by pattern matching is much better done using a regular expression.

import re

libraries = {}
for line in ldd_out.splitlines():
    match = re.match(r'\t(.*) => (.*) \(0x', line)
    if match:
        libraries[match.group(1)] = match.group(2)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.