[Python] Running a bash scripts content from within python script. Not executing a .sh file...

Discussão em 'Python' iniciado por Stack, Setembro 13, 2024.

  1. Stack

    Stack Membro Participativo

    I have an encrypted bash script inside a .pkl file which my python script needs to decrypt and execute. The bash script consists multiple lines and is complex. I need a way to execute this script from within python, without a .sh file.

    Using a raw string to store the script works as in the example below, but there is no way of turning an already initialized string object(I get it from the .pkl as I mentioned) to a raw string programmatically as far as I could understand.

    bash_script = r"""
    multi
    line
    bash
    script
    """

    # Run the script
    process = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate(bash_script.encode())

    # Output the result
    print(stdout.decode())


    Some of the errors I get when I store the script in a normal str object and run it are below.

    /bin/bash: line 105: unexpected EOF while looking for matching `"'
    /bin/bash: line 106: syntax error: unexpected end of file


    One solution is to export the script into a temp file under /tmp/, make it executable and execute the file but I want to keep it as simle as possible.

    Continue reading...

Compartilhe esta Página