20 | def powershell_execute(script, func): |
21 | """ |
22 | Execute a powershell script |
23 | """ |
24 | output = "" |
25 | try: |
26 | script = re.sub("Write-Verbose ", "Write-Output ", script, flags=re.I) |
27 | script = re.sub("Write-Error ", "Write-Output ", script, flags=re.I) |
28 | script = re.sub("Write-Warning ", "Write-Output ", script, flags=re.I) |
29 | |
30 | full_args = ["powershell.exe", "-NoProfile", "-NoLogo", "-C", "-"] |
31 | |
32 | info = subprocess.STARTUPINFO() |
33 | info.dwFlags = STARTF_USESHOWWINDOW |
34 | info.wShowWindow = SW_HIDE |
35 | |
36 | p = subprocess.Popen(full_args, startupinfo=info, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, |
37 | stdout=subprocess.PIPE, universal_newlines=True, shell=True) |
38 | p.stdin.write("$base64=\"\"" + "\n") |
39 | |
40 | n = 25000 |
41 | b64_script = base64.b64encode(script) |
42 | tab = [b64_script[i:i + n] for i in range(0, len(b64_script), n)] |
43 | for t in tab: |
44 | p.stdin.write("$base64+=\"%s\"\n" % t) |
45 | p.stdin.flush() |
46 | |
47 | p.stdin.write("$d=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($base64))\n") |
48 | p.stdin.write("Invoke-Expression $d\n") |
49 | |
50 | p.stdin.write("\n$a=Invoke-Expression \"%s\" | Out-String\n" % func) |
51 | p.stdin.write("$b=[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(\"$a\"))\n") |
52 | p.stdin.write("Write-Host \"[BEGIN]\"\n") |
53 | p.stdin.write("Write-Host $b\n") |
54 | |
55 | |
56 | if '[BEGIN]' in p.stdout.readline(): |
57 | |
58 | for i in p.stdout.readline(): |
59 | output += i |
60 | output = base64.b64decode(output) |
61 | except Exception: |
62 | pass |
63 | |
64 | return output |