Ubuntu Pastebin

Paste from smoser at Tue, 12 Sep 2017 20:45:19 +0000

Download as text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python3

import base64
import sys
import subprocess

def shell_safe(cmd):
    # this uses getopt to give us a single string that can be
    # used as: set -- <string>
    # such that "$@" will include the the same value as cmd
    out = subprocess.check_output(
        ["getopt", "--shell", "sh", "--options", "", "--", "--"] + list(cmd))
    # trim trailing carriage return and leading ' -- '
    return out[4:-1].decode()

def shell_pack(cmd):
    """shell_pack(cmd): return a string that can shuffled through 'sh'
       and will execute cmd.
       
       in python subprocess terms:
           check_output(cmd) == check_output(shell_pack(cmd), shell=True)"""

    if isinstance(cmd, str):
        cmd = [cmd]
    else:
        cmd = list(cmd)

    stuffed = shell_safe(cmd)
    # for whatever reason b64encode returns bytes when it is clearly
    # representable as a string by nature of being base64 encoded.
    b64 = base64.b64encode(stuffed.encode()).decode()
    return 'eval set -- "$(echo %s | base64 --decode)" && exec "$@"' % b64


args = sys.argv[1:]
shell_packed = shell_pack(args)
print("input: %s" % args)
print("shellpack: %s" % shell_packed)
print("output: %s" % subprocess.check_output(shell_packed, shell=True))
Download as text