Printing a variable line by line using a line before Python 2.7

I am writing a parsing tool in Python, and I ran into some problem trying to print a line before a multiline variable without editing the line itself

Here is my code code:

# ...
query1 = commands.getoutput("ls -1 modules/recon | grep '.*\.py$' | grep -v '__init__.py'")
print("module/%s/%s" % (module_type, query1.strip(".py"))

I want to add "module / # module_type / # module_name" and the module name is the only change. Thus, using the shodan module and bing (random), the result will look something like this:

modules/recon/shodan
modules/recon/bing

but instead i get

modules/recon/bing.py
shodan

Thank!

+4
source share
1 answer

You can do what you ask for:

from os import path

module_type = 'recon'
q = 'shoban.py\nbing.py'  # insert the your shell invocation here
modules = (path.splitext(m)[0] for m in q.split('\n'))
formatted = ('modules/%s/%s' % (module_type, m) for m in modules)
print('\n'.join(formatted))

output:

modules/recon/shodan
modules/recon/bing

But since you are already calling the unix shell from python, you can use sed to process the strings:

print(commands.getoutput("ls modules/recon/ | sed '/.py$/!d; /^__init__.py$/d; s/\.py$//; s/^/modules\/recon\//'"))

"globbing" , , , (, /), , :

print(commands.getoutput("ls modules/recon/*.py | sed 's/.py$//; /\/__init__$/d'"))

- python:

from os import path
import glob

module_type = 'recon'
module_paths = glob.iglob('modules/recon/*.py')
module_files = (m for m in map(path.basename, modules) if m != '__init___.py')
modules = (path.splitext(m)[0] for m in module_files)
formatted = ("modules/%s/%s" % (module_type, m) for m in modules)
print('\n'.join(formatted))
+1

Source: https://habr.com/ru/post/1659894/


All Articles