Py学习  »  Python

在Linux中使用python执行Shell命令

x_CrazyTeddy_x • 3 年前 • 203 次点击  

所以我最近才开始有兴趣在OverTheWire的网站上玩CTF,我仍然在第一个挑战中被称为

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

以下代码

import os

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/99353
 
203 次点击  
文章 [ 1 ]  |  最新文章 3 年前
HoldOffHunger
Reply   •   1 楼
HoldOffHunger    3 年前

os.system() 只返回命令的退出状态(而不是 STDOUT ). 你应该使用 subprocess 模块,尤其是 subprocess.Popen

代码:

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.