Created
January 16, 2020 09:17
-
-
Save virus-warnning/873af29e15d789bbed2a61d6128d150d to your computer and use it in GitHub Desktop.
使用 PowerShell 執行程式, 回傳 STDOUT, 並且支援系統管理員身分執行
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import random | |
import subprocess | |
def ps_exec(cmd, adminPriv=False): | |
""" 使用 Windows PowerShell Start-Process 執行程式, 回傳 STDOUT, 並且支援以系統管理員身分執行 """ | |
# 產生隨機檔名, 用來儲存 stdout | |
existed = True | |
while existed: | |
r = random.randint(0,65535) | |
stdout_path = os.path.expanduser('~\\stdout-%04x.txt' % r) | |
existed = os.path.isfile(stdout_path) | |
open(stdout_path, 'w').close() | |
if adminPriv: | |
# 產生底層參數 | |
deep_args = list(map(lambda n: "'{}'".format(n), cmd[1:])) | |
deep_args = ','.join(deep_args) | |
# 產生表層參數 | |
surface_args = [ | |
'Start-Process', | |
'-FilePath', cmd[0], | |
'-ArgumentList', deep_args, | |
'-RedirectStandardOutput', stdout_path, | |
'-NoNewWindow' | |
] | |
surface_args = list(map(lambda n: '"{}"'.format(n), surface_args)) | |
surface_args = ','.join(surface_args) | |
# 產生完整執行程式指令 | |
cmd = [ | |
'powershell.exe', 'Start-Process', | |
'-FilePath', 'powershell.exe', | |
'-ArgumentList', surface_args, | |
'-Verb', 'RunAs', | |
'-Wait' | |
] | |
else: | |
# 產生表層參數 | |
surface_args = list(map(lambda n: '"{}"'.format(n), cmd[1:])) | |
surface_args = ','.join(surface_args) | |
# 產生完整執行程式指令 | |
cmd = [ | |
'powershell.exe', 'Start-Process', | |
'-FilePath', cmd[0], | |
'-ArgumentList', surface_args, | |
'-RedirectStandardOutput', stdout_path, | |
'-NoNewWindow', | |
'-Wait' | |
] | |
# 取 stdout | |
completed = subprocess.run(cmd) | |
stdout_content = '' | |
with open(stdout_path, 'r') as stdout_file: | |
stdout_content = stdout_file.read() | |
os.remove(stdout_path) | |
return stdout_content | |
def main(): | |
cmd = [ 'netstat.exe', '-a', '-n', '-p', 'tcp' ] | |
stdout = ps_exec(cmd, adminPriv=True) | |
print(stdout) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment