def __init__( self ): self.antsVersion = "0.61 (beta)" self.phrase1 = "" self.phrase2 = "" systemPass = False if os.name == "nt": systemPass = True else: checkWin = wx.MessageDialog(None, 'ANTS is designed to be run on Windows XP SP2 and later with NTFS filesystems. Other systems are likely to experience errors. Do you want to continue anyway?', 'ANTS is designed for Windows.', wx.YES_NO | wx.YES_DEFAULT | wx.ICON_EXCLAMATION) if checkWin.ShowModal() == wx.ID_YES: systemPass = True else: sys.exit() if systemPass == True: #setup working directory appDataPath = os.path.join(os.getenv("APPDATA"), "ANTS-Transfer_System") if not os.path.isdir(appDataPath): os.mkdir(appDataPath) self.appData = appDataPath #move config.xml if configured remotely if os.path.isfile("config.xml"): print "moving config.xml" shutil.copy2("config.xml", self.appData) os.remove("config.xml") #check if opened with parameters if len(sys.argv) > 1: #opened with file or directory parameter if len(sys.argv) > 2: antsPath = sys.argv[0] cmdList = sys.argv del cmdList[0] param = " ".join(cmdList) else: antsPath, param = sys.argv #get path where ants.py or ants.exe was opened from in order to call antsFromBoot fullPath = os.path.dirname(antsPath) #if param is a file, take parent directory if os.path.isdir(param): openDir = param else: openDir = os.path.dirname(param) #for debugging #pathDialog = wx.MessageDialog(None, fullPath + "\n" + param, "path example", wx.OK | wx.ICON_ERROR) #pathDialog.ShowModal() if getattr(sys, 'frozen', False): boot = [os.path.join(fullPath, "antsFromBoot.exe"), openDir] elif __file__: boot = ["python", os.path.join(fullPath, "antsFromBoot.py"), openDir] try: admin.runAsAdmin(self, boot) except TypeError, e: raise except: subprocess.Popen(boot, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def runRoot(funcion): #funcion() if not admin.isUserAdmin(): #admin.runAsAdmin(cmdLine=funcion()) admin.runAsAdmin(cmdLine=funcion()) funcion()
def installWinOcr(self, ): admin.runAsAdmin([ "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe ", """ $Capability = Get-WindowsCapability -Online | Where-Object { $_.Name -Like 'Language.OCR*ja-JP*' }; $Result = $Capability | Add-WindowsCapability -Online; if ($Result.RestartNeeded -eq $True) { Restart-Computer -Force }; """ ])
def renameComp(self, name): rename_cmd = r'wmic computersystem where name="%computername%" call rename name={0}'.format(name) windows_version = getWinV() print u'Версия ОС: Windows '+windows_version print u'Переименовываем комьютер' if windows_version == 'XP': self.callBatchFile('\\\\192.168.1.20\\1c_bd\AIDA64\\rename_xp.bat %s' % str(name)) else: if not admin.isUserAdmin(): admin.runAsAdmin(['\\\\192.168.1.20\\1c_bd\AIDA64\\rename.bat', ' '+str(name)])
def runANTS( self, event ): if getattr(sys, 'frozen', False): boot = ["antsFromBoot.exe"] elif __file__: boot = ["python", "antsFromBoot.py"] try: admin.runAsAdmin(self, boot) except: subprocess.Popen(boot, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.Close()
def __init__(self, fileName=None, parent=None): super(UnlockDialog, self).__init__(parent) if not admin.isUserAdmin(): admin.runAsAdmin() # end the current instance of the program because it isn't uac. Results in two app windows otherwise. sys.exit(0) self.setupUi(self) # print psutil.Process(os.getpid()).parent fileArgPos = self._getRelevantCmdArgument(sys.argv) if fileArgPos != None: self.fileName = sys.argv[fileArgPos] self.stackedWidget.setCurrentIndex(0) self.setUnlockTextLabel(self.fileName) self.sameLocation = False # elif self._checkScriptNameInFolder(): # parentProcessName = psutil.Process(os.getpid()).parent().exe() # if parentProcessName != "python.exe": # scriptName = os.path.basename(parentProcessName) # else: # scriptName = os.path.basename(__file__) # # get the script name without file extension # scriptName = os.path.splitext(scriptName)[0] + ".exelocker" # self.fileName = os.path.basename(scriptName) # self.sameLocation = False # self.setUnlockTextLabel(self.fileName) # self.stackedWidget.setCurrentIndex(0) else: self.fileName = None self.sameLocation = True self.stackedWidget.setCurrentIndex(1) if self._argsHasDirectory(): index = self._getRelevantDirectoryArg() self.fillListWidget(sys.argv[index]) else: self.fillListWidget() self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.setFixedSize(self.width(), self.height()) # connect the unlock button self.unlockButton.clicked.connect(self.unlockFile) # self.passwordLineEdit.returnPressed.connect(self.unlockFile) # <-- This line of code ruined my whole f*****g day # The above line made two events fire when the exelocker filename is same as the script name. I don't f*****g understand it. F**K self.browseButton.clicked.connect(self.browseFiles) self.listWidgetUnlockButton.clicked.connect(self.listWidgetSelectedEvent) # connect with the thread self.signal.connect(self.fileUnlockedEvent)
def __init__(self, fileName=None, parent=None): super(UnlockDialog, self).__init__(parent) if not admin.isUserAdmin(): admin.runAsAdmin() # end the current instance of the program because it isn't uac. Results in two app windows otherwise. sys.exit(0) self.setupUi(self) # print psutil.Process(os.getpid()).parent fileArgPos = self._getRelevantCmdArgument(sys.argv) if fileArgPos != None: self.fileName = sys.argv[fileArgPos] self.stackedWidget.setCurrentIndex(0) self.setUnlockTextLabel(self.fileName) self.sameLocation = False # elif self._checkScriptNameInFolder(): # parentProcessName = psutil.Process(os.getpid()).parent().exe() # if parentProcessName != "python.exe": # scriptName = os.path.basename(parentProcessName) # else: # scriptName = os.path.basename(__file__) # # get the script name without file extension # scriptName = os.path.splitext(scriptName)[0] + ".exelocker" # self.fileName = os.path.basename(scriptName) # self.sameLocation = False # self.setUnlockTextLabel(self.fileName) # self.stackedWidget.setCurrentIndex(0) else: self.fileName = None self.sameLocation = True self.stackedWidget.setCurrentIndex(1) if self._argsHasDirectory(): index = self._getRelevantDirectoryArg() self.fillListWidget(sys.argv[index]) else: self.fillListWidget() self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.setFixedSize(self.width(), self.height()) # connect the unlock button self.unlockButton.clicked.connect(self.unlockFile) # self.passwordLineEdit.returnPressed.connect(self.unlockFile) # <-- This line of code ruined my whole f*****g day # The above line made two events fire when the exelocker filename is same as the script name. I don't f*****g understand it. F**K self.browseButton.clicked.connect(self.browseFiles) self.listWidgetUnlockButton.clicked.connect( self.listWidgetSelectedEvent) # connect with the thread self.signal.connect(self.fileUnlockedEvent)
def __init__(self, parent=None): super(LockerDialog, self).__init__(parent) if _ISPRODUCTION_: if not admin.isUserAdmin(): admin.runAsAdmin() sys.exit(0) self.setupUi(self) self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.setFixedSize(self.width(), self.height()) self.lockButton.setEnabled(False) # lock the exe button still password is set self.pickFileButton.clicked.connect(self.showFileDialog) self.passwordLineEdit.textChanged.connect(self.checkPasswordMatch) self.passwordAgainLineEdit.textChanged.connect(self.checkPasswordMatch) self.lockButton.clicked.connect(self._lockFile) # Connect to threadDone event self.signal.connect(self.fileLockedEvent)
def __init__(self, parent=None): super(LockerDialog, self).__init__(parent) if _ISPRODUCTION_: if not admin.isUserAdmin(): admin.runAsAdmin() sys.exit(0) self.setupUi(self) self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.setFixedSize(self.width(), self.height()) self.lockButton.setEnabled( False) # lock the exe button still password is set self.pickFileButton.clicked.connect(self.showFileDialog) self.passwordLineEdit.textChanged.connect(self.checkPasswordMatch) self.passwordAgainLineEdit.textChanged.connect(self.checkPasswordMatch) self.lockButton.clicked.connect(self._lockFile) # Connect to threadDone event self.signal.connect(self.fileLockedEvent)
def Install_VLC(VLC_PATH): if not admin.isUserAdmin(): admin.runAsAdmin() print 'VLC 설치 시작' try: os.chdir(os.path.join(os.getcwd(), os.path.dirname((sys.argv[0])))) app = application.Application() app.Start(VLC_PATH) app.WaitCPUUsageLower() except application.AppStartError as er: print str(er) try : language_window = app.Connect(title=u'Installer Language', class_name='#32770').Dialog print 'Choose Language' language_window[u'OK'].Click() except findwindows.WindowNotFoundError as er: InstallWindow = app.Connect(title=u'VLC media player \uc124\uce58', class_name='#32770').Dialog InstallWindow[u'\ucde8\uc18cButton'].Click() time.sleep(0.5) InstallWindow[u'\uc608(&Y)Button'].Click() print 'Already Installed' exit(1) print 'Choose Install or Not' language_window[u'\ub2e4\uc74c >'].Click() print 'Confirm License' language_window[u'\ub2e4\uc74c >'].Click() print 'Check Component' language_window[u'\ub2e4\uc74c >'].Click() print 'Choose Install Location' language_window[u'\uc124\uce58'].Click() app.WaitCPUUsageLower() print 'Install End Dialog' language_window[u'\ub9c8\uce68'].Click() print 'Compelete Install'
def test(): rc = 0 if not admin.isUserAdmin(): print(f'You\'re not an admin. {os.getpid()}, params: {sys.argv}') #rc = runAsAdmin(["c:\\Windows\\notepad.exe"]) rc = admin.runAsAdmin() else: print(f'You are an admin! {os.getpid()} params: {sys.argv}') rc = 0 x = input('Press Enter to exit.') return rc
def setAssoc(self): if platform.system() == "Linux": os.system( "xdg-mime default kmtorrent.desktop x-scheme-handler/magnet") return if not admin.isUserAdmin() and platform.system == "Windows": msgBox = QtWidgets.QMessageBox() msgBox.setIcon(QtWidgets.QMessageBox.Question) msgBox.setText("Set Association") msgBox.setInformativeText( "This feature requires elevated privilieges\nrun this feature in admin mode?" ) msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) msgBox.setDefaultButton(QtWidgets.QMessageBox.No) reply = msgBox.exec_() if reply == QtWidgets.QMessageBox.Yes: admin.runAsAdmin(cmdLine=[sys.argv[0]] + ["ADMIN"]) elif reply == QtWidgets.QMessageBox.No: return elif platform.system == "Windows": change_regedit()
def csharp_symlinks(args): dirname = os.path.dirname(args.project_file) engine_path = get_engine_path() symlinks = [] SymlinkFileName = os.path.join(dirname, 'Code', 'CryManaged', 'CESharp') TargetFileName = os.path.join(engine_path, 'Code', 'CryManaged', 'CESharp') symlinks.append((SymlinkFileName, TargetFileName)) SymlinkFileName = os.path.join(dirname, 'bin', args.platform, 'CryEngine.Common.dll') TargetFileName = os.path.join(engine_path, 'bin', args.platform, 'CryEngine.Common.dll') symlinks.append((SymlinkFileName, TargetFileName)) create_symlinks = [] for (SymlinkFileName, TargetFileName) in symlinks: if os.path.islink(SymlinkFileName): if os.path.samefile(SymlinkFileName, TargetFileName): continue elif os.path.exists(SymlinkFileName): error_unable_to_replace_file(SymlinkFileName) create_symlinks.append((SymlinkFileName, TargetFileName)) if create_symlinks and not admin.isUserAdmin(): cmdline = getattr(sys, 'frozen', False) and sys.argv or None rc = admin.runAsAdmin(cmdline) sys.exit(rc) for (SymlinkFileName, TargetFileName) in create_symlinks: if os.path.islink(SymlinkFileName): os.remove(SymlinkFileName) sym_dirname = os.path.dirname(SymlinkFileName) if not os.path.isdir(sym_dirname): os.makedirs(sym_dirname) SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1 dwFlags = os.path.isdir( TargetFileName) and SYMBOLIC_LINK_FLAG_DIRECTORY or 0x0 win32file.CreateSymbolicLink(SymlinkFileName, TargetFileName, dwFlags)
def unreg(): if not admin.isUserAdmin(): admin.runAsAdmin() win32com.server.register.UnregisterServer(BasicServer._reg_clsid_, BasicServer._reg_progid_)
def isAdmin(): if not admin.isUserAdmin(): admin.runAsAdmin()
f.close() except: f = open("admin.txt", "w") f.write("failed to run either") f.close() # if not admin.isUserAdmin(): # admin.runAsAdmin(getData()) rc = 0 if not admin.isUserAdmin(): print "You're not an admin.", os.getpid(), "params: ", sys.argv # rc = runAsAdmin(["c:\\Windows\\notepad.exe"]) rc = admin.runAsAdmin() else: print "You are an admin!", os.getpid(), "params: ", sys.argv rc = 0 getData() """ import admin import os import subprocess if not admin.isUserAdmin(): try: admin.runAsAdmin()
# Install the vector dll try: if os.name == 'nt': try: vxDLL = WinDLL( "c:\\Users\\Public\\Documents\\Vector XL Driver Library\\bin\\vxlapi.dll" ) except WindowsError: vxDLL = WinDLL( "c:\\Documents and Settings\\All Users\\Documents\\Vector XL Driver Library\\bin\\vxlapi.dll" ) except WindowsError: if not admin.isUserAdmin(): path = os.path.join(LIB_PATH, 'xl_lib83.exe') admin.runAsAdmin(cmdLine=[path]) raw_input('Press return to continue . . .') else: install_exe('xl_lib83.exe') # Install numpy try: import numpy except ImportError: try: install_exe('numpy-1.8.1-win32-superpack-python2.7.exe') except WindowsError: if not admin.isUserAdmin(): path = os.path.join(LIB_PATH, 'numpy-1.8.1-win32-superpack-python2.7.exe') admin.runAsAdmin(cmdLine=[path])
def elevate(): import admin if not admin.isUserAdmin(): # sys.exit() admin.runAsAdmin()
from time import localtime #dependencies #pywin32 #numpy #scipy #python-twitter #matplotlib #six #python-dateutil #pyparsing #soundcloud #PyEphem if not admin.isUserAdmin(): admin.runAsAdmin() callpath = 'C:\\temp\\calls' imgpath = 'C:\\temp\\imgs' dirpath = 'C:\\' existing = os.listdir(callpath) running = False checkTime = None def parse_file_name(file): sp = file.split("_") lt = localtime() tz = ''
import os import admin print("Are you root? ", end="") # Check if root or not if not admin.isUserAdmin(): print("No") print("Getting root...") admin.runAsAdmin("python example.py") # Run command as root else: print("Now you are root!") input("")
''' Auto update for Windows 10 Insider Useful for update native boot vhd/vhdx By @raspiduino on github Date created 19/11/2020 ''' # Many thanks whatever127 (uupdump.net), Leonard Richardson (beautifulsoup) and other libs. import requests from bs4 import BeautifulSoup import os import admin # https://github.com/raspiduino/pythonadmin if not admin.isUserAdmin(): admin.runAsAdmin("python updateinsider.py") exit(1) # Settings arch = "" # Change this to fit your arch (x86, amd64, arm64) # Change this to fit your ring: rings = ''' retail : Normal release rp : Release preview wis : Slow rings wif : Fast rings (Default) ''' ring = "" lang = "" # Pick a language edition = "" # Choose an edition (core, coren, professional, professionaln)
def checkAdmin(): if not admin.isUserAdmin(): admin.runAsAdmin() sys.exit()
import os, sys, base64, time, socket, hashlib, admin import _winreg as wreg from string import ascii_lowercase, digits, ascii_uppercase from Crypto import Random from Crypto.Cipher import AES from sys import platform as _platform from termcolor import colored if not admin.isUserAdmin(): admin.runAsAdmin() if _platform == 'win32': import colorama colorama.init() def yellow(text): return colored(text, 'yellow', attrs=['bold']) def green(text): return colored(text, 'green', attrs=['bold']) def red(text): return colored(text, 'red', attrs=['bold']) def cyan(text): return colored(text, 'cyan', attrs=['bold']) os.system('cls')
def process_similarities(directory, language, age_min, age_max, test=False): """ Retrieve raw data from the CHILDES database, pre-process it and compute the linguistic similarities measures. :param directory: The name of the directory in which all the intermediate and results data files will be stored :type directory: str :param language: The language from which CHILDES transcripts will be selected :type directory: str :param age_min: The minimum target childs age at which utterances will be retrieved (included) :type age_min: int :param age_max: The maximum target childs age at which utterances will be retrieved (included) :type age_max: int :param test: If True, only a small amount of utterances will be selected for each age, in order to accelerate processing. It is a development oriented parameter :type test: bool :returns: Nothing, but results like linguistic similarities are saved in several CSV files in the specified directory, one CSV for each target child age :rtype: None .. seealso:: Run.ipynb notebook .. warning:: language parameter values should either be: "English", "French", "Spanish", "German", "Chinese" or "Japanese. """ # create a specific directory for tests, to avoid erasing previously generated data if test: directory += "_test" if not os.path.isdir("../Databases/" + directory): print("Beginning the creation of a new database \n") else: print("Expanding the already existing " + directory + " database \n") # this is necessary as a parameter need to be modified on windows # for processing of japanese and chinese characters if language == "Japanese" or language == "Chinese": admin.runAsAdmin() print("\nInitializing settings") settings.init() print("\nCreating the initial directories architecture") create_architecture(directory) print("\nRetrieving raw data from CHILDES") retrieve_childes_data(directory, language, age_min, age_max, test) print("\nCharging the stop-words") fw = settings.dic_SW[language] if not os.path.isdir("../Databases/" + directory + "/vocabulary"): print("\nCreating the vocabulary") create_vocabulary(directory, [1, 3, 10, 20, 50]) print("\nCharging the vocabulary") vocabulary = get_vocab(directory) print("\nCharging the spacy model ") nlp = spacy.load(settings.dic_spacy[language]) print( "\nExpanding each transcripts objects by processing embeddings of each utterances" ) for age in range(age_min, age_max + 1): expand_data(age, nlp, fw, directory, vocabulary) print("\nDone, all data is accessible in '../Databases/" + directory + "/results.csv'")
import os import admin # https://github.com/raspiduino/pythonadmin import webbrowser import time import subprocess import stat import json from datetime import date, timedelta from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg if not admin.isUserAdmin(): # Not run as root yet if os.name == "nt": admin.runAsAdmin("python comadd.py") else: admin.runAsAdmin("python3 comadd.py") exit(1) #ttk.Style().theme_use("winnative") # Read setting # Setting file layout: # 1. Session time # 2. Break session time # 3. Apps to block list # 4. Sites to block list # 5. Other settings settingfile = open("setting.txt", "a+") settingfile.seek(0) # Read at the top of the file
def runGoodByeDpiThreadFunc(): admin.runAsAdmin(["lib_\\goodbyedpi\\goodbyedpi.exe "])
print('before copying Original to "filter.txt" to Documents folder') shutil.copy(srcPathFile, destPathFile) input('filter.txt should be there now.') print('openng FIlter.txt') print('opening', destPathFile) f = open(destPathFile, "a") input("it's open") line = '104.19.222.11 ' + url2bypass f.write(line) f.close() input("Appended a line. Now it's closed") #try: srcPathFile = r'C:\Windows\System32\drivers\etc\hostsBaam' #if not admin.isUserAdmin(): try: admin.runAsAdmin([shutil.copy(destPathFile, srcPathFile)]) except AttributeError: pass except PermissionError: print('Please run this script or open Command Prompt as Administrator.') #except PermissionError: # print("How do we get permission?") # print("Perhaps run this very pthon program as Administrator?") # #%%
import winreg import admin import os #print(0) if not admin.isUserAdmin(): admin.runAsAdmin(wait=False) exit() #print(0.5) REG_PATH = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0001" def set_reg(name, value): #try: winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, REG_PATH) registry_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, REG_PATH, 0, winreg.KEY_WRITE) winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value) winreg.CloseKey(registry_key) return True #except WindowsError: # return False def get_reg(name): try: registry_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, REG_PATH, 0, winreg.KEY_READ) value, regtype = winreg.QueryValueEx(registry_key, name)
'a', encoding="utf-8") #################### # main #################### if __name__ == "__main__": ###################### if configuration.RUN_AS_ADMIN: # TODO: check/improve tool behavior when Admin. # When running as Admin we get a console # very strange behavior...we start a complete new instance of the App # we cannot debug when running as Admin. ######################### if not admin.isUserAdmin(): sys.exit(admin.runAsAdmin(cmdLine=None, wait=False)) app = QApplication(sys.argv) font = QFont() font.setPointSize(configuration.FONT_SIZE) app.setFont(font) ui = MainWindow() ui.show() sys.exit(app.exec_()) #################### app = QApplication(sys.argv) font = QFont() font.setPointSize(configuration.FONT_SIZE) app.setFont(font) ui = MainWindow() ui.show() sys.exit(app.exec_())