【问题标题】:Running a command as the first command in subprocess将命令作为子进程中的第一个命令运行
【发布时间】:2018-12-26 13:54:23
【问题描述】:

我有一个可以打开终端的函数:

def open_next_terminal():
    import subprocess

    def rand(path="/tmp"):
        acc = string.ascii_letters
        retval = []
        for _ in range(7):
            retval.append(random.choice(acc))
        return "{}/{}.sh".format(path, ''.join(retval))

    file_path = rand()
    with open(file_path, "a+") as data:
        data.write(
'''
#!/bin/bash
"$@"
exec $SHELL
'''
        )
    subprocess.call(["sudo", "bash", "{}".format(file_path)])
    return file_path

我想在这个新打开的终端中执行任何操作之前运行一个命令。例如:

subprocess.call(["sudo", "bash", "{}".format(file_path)]) #<= is called
ls #<= is run
 #<= some output of files and folders
root@host:~#  #<= the shell is now available

子进程是否允许我在 shell 初始化期间运行“第一个命令”?

【问题讨论】:

    标签: python python-2.7 command subprocess


    【解决方案1】:

    只需将shell=True 参数传递给subprocess.call,您就可以将多个命令(以分号或换行符分隔)作为单个字符串运行。

    subprocess.call('your_first_command.sh; your_real_work.sh', shell=True)
    

    【讨论】:

    • 命令注入只有在你的命令字符串来自用户输入的情况下才有可能。即使它来自用户输入,您也可以使用shlex.quote 转义来自用户输入的部分。
    • 那么除此之外,没有办法运行“第一个命令”吗?
    • 不幸的是,我想不到。
    猜你喜欢
    • 2015-08-10
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    相关资源
    最近更新 更多