Frage

I have a bash script which is encoded in Python using the following code:

import tempfile
import subprocess
import zlib

with open("/root/test.sh") as inputfile:
    teststr = zlib.compress(inputfile.read()).encode('base64')
    print teststr

This gives me the encoded string which I then pass as a variable in my python script, like so (plz note, this is a sample script that installs pip):

piping="eJyNksFuwyAMhs/wFJ4qTdsBrG63HXLdY0yEEoKSAAJnXTvt3QdtNyWTWu2EkX//tj/Y3GHrPLYq95xz5zOpcXyLLj48fnLG2TTsXAKcc8IxaDViThq7kIqi6JneXcuxDbwaIuctZENzFBTCmIECXJpAPFAfvKhqtreGoCeK+QUxHqKT56wMyWJUelDWZMxhTtpgCarjyXARiq3cymdJKkl7BCF8ELo3ehDaJHKd04oMNM1y4K6borHlUpq4KMsJT839lrNiAseP9w6u2a991sUFyt8yzs77nBNluV8Kt4yWEJXf/dScmJ5QQKG94Ag3HmSNOKm9tI76uZU6TJW4qr1xUplMQh08JddiKam+dd5bc152+5+afy2/Gf8G8sjZTA=="
installpip=zlib.decompress(piping.decode('base64'))

with tempfile.NamedTemporaryFile() as scriptfile:
        scriptfile.write(installpip)
        scriptfile.flush()
        subprocess.call(['/bin/bash', scriptfile.name])

This python script is then encoded using pytinstaller 2.0. When the installation is run, it runs fine but the encoded variable is decoded and stored temporarily in /tmp as tmpXXXXX and this is shown to be running while running ps aux and top.

How can this be avoided?

War es hilfreich?

Lösung

Don't use a named temporary file, and instead pipe its contents in with stdin:

import tempfile, subprocess
installpip="echo 'hello'\n"

with tempfile.TemporaryFile() as scriptfile:
        scriptfile.write(installpip)
        scriptfile.flush()
        scriptfile.seek(0)
        subprocess.call(['/bin/bash', '-s'], stdin=scriptfile)

Of course this is not entirely bullet-proof either, but I'm sure you know that already.

Andere Tipps

Don't use temporary files. Instead, communicate with the process directly through a pipe:

import subprocess

content = "echo 'hello'\n"
p = subprocess.Popen(['/bin/bash', '-s'], stdin=subprocess.PIPE)
p.communicate(content)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top