【问题标题】:Executing Shell commands using python In Linux [duplicate]在Linux中使用python执行Shell命令[重复]
【发布时间】:2020-10-10 05:33:52
【问题描述】:

所以我最近才开始感兴趣并在 OverTheWire 网站上玩 CTF,如果您考虑查看它,我仍处于称为 bandit Lvl5 的第一个挑战。所以教linux命令行等的使用

所以在这个挑战中,我的任务是在主目录中有隐藏文件,我必须找到它们,在其中一个文件中,我会找到进入下一个级别的密码,注意有 20 多个隐藏文件上来。

然后我认为没有人是的,我可以手动完成此操作,但这将花费很长时间,所以我尝试制作一个我认为可以获取隐藏文件并一个一个打开的脚本。但它没有按我的意愿工作。

我想将这些隐藏文件附加到一个列表中,然后运行一个 for 循环来打开每个文件,然后我将能够看到结果并找到密码

下面的代码

import os

a = []
for i in os.system('find .inhere/'):
    a.append(i)
for j in a:
    print("\n\n cat j ")

所以这是我第一次尝试使用 python 与命令行进行交互的这种方式的混乱代码,请你帮助我如何去做或者我的代码是否可以修复

【问题讨论】:

  • os.system() 不返回命令的输出。为此使用subprocess.Popen()。而且您需要将输出分成几行,它不会自动为您完成。
  • 您阅读文档了吗? os.system() 返回命令的退出状态。
  • 老实说,几分钟前遇到了这个挑战,我从来没有阅读过文档,然后想到了os.system(),所以我想我的错误也可能是不阅读文档

标签: python shell scripting


【解决方案1】:

os.system() 只返回命令的退出状态(不是STDOUT)。您应该使用subprocess 模块,尤其是subprocess.Popen。为了更好地理解,我为我的代码添加了几个 cmets。

代码:

import subprocess
import sys


def call_command(command):
    """
    Call a command the STDOUT
    :param command: The related command
    :return: STDOUT as string
    """

    result1 = subprocess.Popen(
        command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True
    )

    #  Get the STDOUT and STDERR descriptors of the command.
    std_out, std_err = result1.communicate()

    return std_out


# Find files in test1 folder.
find_result = call_command("find test1/ -type f")
for one_find in find_result.split("\n"):
    if one_find:
        # The result of cat command will be in "cat_result" variable.
        cat_result = call_command("cat {}".format(one_find))
        print(cat_result)

        # You can write the result directly to STDOUT with the following line.
        # sys.stdout.write("\n".join(call_command("cat {}".format(one_find))))

test1 文件夹的内容:

>>> ll test1/
total 8
drwxrwxr-x  2 user grp 4096 Jul  8 14:18 ./
drwxrwxr-x 18 user grp 4096 Jul  8 14:33 ../
-rw-rw-r--  1 user grp 29 Jul  8 14:18 test_file.txt

test_file.txt的内容:

>>> cat test1/test_file.txt 
Contents of test_file.txt file

代码输出:

>>> python3 test.py
Contents of test_file.txt file.

【讨论】:

  • 如果可以的话,实际上你应该更喜欢subprocess.run() 而不是Popen;这在文档中有明确说明。它基本上使您不必重新发明call_command(当然,这也复制了遗留的check_output,而没有您可能应该添加的check_部分)。
  • command.split() 也有问题;您应该改用shlex.split(command),或者只是传入一个字符串列表。或许也可以看看Actual meaning of shell=True in subprocess
猜你喜欢
  • 2017-05-27
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多