Skip to content

Instantly share code, notes, and snippets.

@virus-warnning
Created January 16, 2020 09:17
Show Gist options
  • Select an option

  • Save virus-warnning/873af29e15d789bbed2a61d6128d150d to your computer and use it in GitHub Desktop.

Select an option

Save virus-warnning/873af29e15d789bbed2a61d6128d150d to your computer and use it in GitHub Desktop.

Revisions

  1. virus-warnning created this gist Jan 16, 2020.
    70 changes: 70 additions & 0 deletions ps_exec.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    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()