def init_console(self): """Sets up connection to console.""" try: win32console.AttachConsole(-1) # pythonw.exe from console atexit.register(lambda: ConsoleWriter.realwrite("\n")) except Exception: pass # Okay if fails: can be python.exe from console try: handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) handle.WriteConsole("\n") ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.WriteConsole except Exception: # Fails if GUI program: make new console try: win32console.FreeConsole() except Exception: pass try: win32console.AllocConsole() handle = open("CONOUT$", "w") argv = [util.longpath(sys.argv[0])] + sys.argv[1:] handle.write(" ".join(argv) + "\n\n") handle.flush() ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.write sys.stdin = open("CONIN$", "r") atexit.register(self.on_exe_exit) except Exception: try: win32console.FreeConsole() except Exception: pass ConsoleWriter.realwrite = self.stream.write ConsoleWriter.is_loaded = True
def start(self): self.log('Launching nio process') win32console.AllocConsole() self.process = subprocess.Popen( [self.niod_path], cwd=self.project_path, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
def free_console(self): """Only free console if one was created successfully.""" free_console = True try: win32console.AllocConsole() except: free_console = False return free_console
def write(self, text): """ Prints text to console window. GUI application will need to attach to the calling console, or launch a new console if not available. """ global window if not window and win32console: if not ConsoleWriter.is_loaded and not ConsoleWriter.handle: try: win32console.AttachConsole(-1) # pythonw.exe from console atexit.register(lambda: ConsoleWriter.realwrite("\n")) except Exception: pass # Okay if fails: can be python.exe from console try: handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) handle.WriteConsole("\n" + text) ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.WriteConsole except Exception: # Fails if GUI program: make new console try: win32console.FreeConsole() except Exception: pass try: win32console.AllocConsole() handle = open("CONOUT$", "w") argv = [util.longpath(sys.argv[0])] + sys.argv[1:] handle.write(" ".join(argv) + "\n\n" + text) handle.flush() ConsoleWriter.handle = handle ConsoleWriter.realwrite = handle.write sys.stdin = open("CONIN$", "r") exitfunc = lambda s: (handle.write(s), handle.flush(), raw_input()) atexit.register(exitfunc, "\nPress ENTER to exit.") except Exception: try: win32console.FreeConsole() except Exception: pass ConsoleWriter.realwrite = self.stream.write ConsoleWriter.is_loaded = True else: try: self.realwrite(text) self.flush() except Exception: self.stream.write(text) else: self.stream.write(text)
def __init__(self, parent_pid, lst_cmd_line): try: _ConsoleProcessBase.__init__(self, parent_pid) self.parent_pid = parent_pid self._start_parent_monitor() self.cmd_line = ' '.join(lst_cmd_line) self.echo = eval(os.environ.get('pyconsole_echo', 'True')) self.child_handle = None self.child_pid = None self.paused = False self.x_max = 0 self.y_max = 0 self.y_buffer_max = 0 self.y_last = 0 self.y_adjust = 0 self.y_current = 0 self.last_event_time = 0 self._initialize() self._initialize_events() win32console.FreeConsole() # alloc 2000 lines ? win32console.AllocConsole() self.con_stdout = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE) self.con_stdin = win32console.GetStdHandle( win32console.STD_INPUT_HANDLE) win32console.SetConsoleTitle('console process pid:%s ppid:%s' % ( os.getpid(), parent_pid, )) # size = win32console.PyCOORDType (X=1000, Y=30) # self.con_stdout.SetConsoleScreenBufferSize (size) dct_info = self.con_stdout.GetConsoleScreenBufferInfo() self.y_buffer_max = dct_info['Size'].Y - 1 self.con_window = win32console.GetConsoleWindow().handle self.set_console_event_hook() self._start_paused_monitor() self._child_create() self._start_remote_input() self.message_pump() except: logging.exception('fatal error')
def RunAs(self): #username = "******" #domain = "." #password ="******" cmd = "uninstall.exe" free_console = True try: win32console.AllocConsole() except win32console.error as exc: if exc.winerror != 5: raise ## only free console if one was created successfully free_console = False stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) #p = subprocess.Popen(["runas",r"/user:{}\{}".format(domain,username),cmd],stdout=subprocess.PIPE) subprocess.Popen("runas /savecred /user:Administrator %s" % cmd, shell=True) '''
import win32console, win32con import traceback, time virtual_keys={} for k,v in list(win32con.__dict__.items()): if k.startswith('VK_'): virtual_keys[v]=k free_console=True try: win32console.AllocConsole() except win32console.error as exc: if exc.winerror!=5: raise ## only free console if one was created successfully free_console=False stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdin=win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) newbuffer=win32console.CreateConsoleScreenBuffer() newbuffer.SetConsoleActiveScreenBuffer() newbuffer.SetConsoleTextAttribute(win32console.FOREGROUND_RED|win32console.FOREGROUND_INTENSITY |win32console.BACKGROUND_GREEN|win32console.BACKGROUND_INTENSITY) newbuffer.WriteConsole('This is a new screen buffer\n') ## test setting screen buffer and window size ## screen buffer size cannot be smaller than window size window_size=newbuffer.GetConsoleScreenBufferInfo()['Window'] coord=win32console.PyCOORDType(X=window_size.Right+20, Y=window_size.Bottom+20) newbuffer.SetConsoleScreenBufferSize(coord)
def main(): """ Entry point for GNS3 GUI. """ parser = argparse.ArgumentParser() parser.add_argument('--version', help="show the version", action='version', version=__version__) parser.parse_args() exception_file_path = "exception.log" def exceptionHook(exception, value, tb): if exception == KeyboardInterrupt: sys.exit(0) lines = traceback.format_exception(exception, value, tb) print("****** Exception detected, traceback information saved in {} ******".format(exception_file_path)) print("\nPLEASE REPORT ON http://forum.gns3.net/development-f14.html OR http://github.com/GNS3/gns3-gui/issues\n") print("".join(lines)) try: curdate = time.strftime("%d %b %Y %H:%M:%S") logfile = open(exception_file_path, "a") logfile.write("=== GNS3 {} traceback on {} ===\n".format(__version__, curdate)) logfile.write("".join(lines)) logfile.close() except OSError as e: print("Could not save traceback to {}: {}".format(exception_file_path, e)) if not sys.stdout.isatty(): # if stdout is not a tty (redirected to the console view), # then print the exception on stderr too. print("".join(lines), file=sys.stderr) # catch exceptions to write them in a file sys.excepthook = exceptionHook current_year = datetime.date.today().year print("GNS3 GUI version {}".format(__version__)) print("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year)) # we only support Python 2 version >= 2.7 and Python 3 version >= 3.3 if sys.version_info < (2, 7): raise RuntimeError("Python 2.7 or higher is required") elif sys.version_info[0] == 3 and sys.version_info < (3, 3): raise RuntimeError("Python 3.3 or higher is required") version = lambda version_string: [int(i) for i in version_string.split('.')] if version(QtCore.QT_VERSION_STR) < version("4.6"): raise RuntimeError("Requirement is Qt version 4.6 or higher, got version {}".format(QtCore.QT_VERSION_STR)) # 4.8.3 because of QSettings (http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html) if DEFAULT_BINDING == "PyQt" and version(QtCore.BINDING_VERSION_STR) < version("4.8.3"): raise RuntimeError("Requirement is PyQt version 4.8.3 or higher, got version {}".format(QtCore.BINDING_VERSION_STR)) if DEFAULT_BINDING == "PySide" and version(QtCore.BINDING_VERSION_STR) < version("1.0"): raise RuntimeError("Requirement is PySide version 1.0 or higher, got version {}".format(QtCore.BINDING_VERSION_STR)) try: # if tornado is present then enable pretty logging. import tornado.log tornado.log.enable_pretty_logging() except ImportError: pass # check for the correct locale # (UNIX/Linux only) locale_check() try: os.getcwd() except FileNotFoundError: log.critical("the current working directory doesn't exist") return # always use the INI format on Windows and OSX (because we don't like the registry and plist files) if sys.platform.startswith('win') or sys.platform.startswith('darwin'): QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat) if sys.platform.startswith('win'): try: import win32console import win32con import win32gui except ImportError: raise RuntimeError("Python for Windows extensions must be installed.") try: win32console.AllocConsole() #FIXME: do not hide the console for alpha releases to help with debugging #console_window = win32console.GetConsoleWindow() #win32gui.ShowWindow(console_window, win32con.SW_HIDE) except win32console.error as e: print("warning: could not allocate console: {}".format(e)) exit_code = MainWindow.exit_code_reboot while exit_code == MainWindow.exit_code_reboot: exit_code = 0 app = QtGui.QApplication(sys.argv) # this info is necessary for QSettings app.setOrganizationName("GNS3") app.setOrganizationDomain("gns3.net") app.setApplicationName("GNS3") app.setApplicationVersion(__version__) # save client logging info to a file logfile = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), "GNS3_client.log") try: logger = logging.getLogger("gns3") try: os.makedirs(os.path.dirname(QtCore.QSettings().fileName())) except FileExistsError: pass handler = logging.FileHandler(logfile, "w") handler.setLevel(logging.INFO) formatter = logging.Formatter("[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s", datefmt="%y%m%d %H:%M:%S") handler.setFormatter(formatter) logger.addHandler(handler) except OSError as e: log.warn("could not log to {}: {}".format(logfile, e)) # update the exception file path to have it in the same directory as the settings file. exception_file_path = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), exception_file_path) mainwindow = MainWindow.instance() mainwindow.show() exit_code = app.exec_() delattr(MainWindow, "_instance") app.deleteLater() sys.exit(exit_code)
def allocate(cls): win32console.AllocConsole()
def session_thread(self): # Prepare regex to parse the main hashcat process output regex_list = [ ("hash_type", re.compile("^Hash\.Type\.+: +(.*)\s*$")), ("speed", re.compile("^Speed\.#1\.+: +(.*)\s*$")), ] if self.crack_type == "dictionary": regex_list.append(("progress", re.compile("^Progress\.+: +\d+/\d+ \((\S+)%\)\s*$"))) regex_list.append(("time_estimated", re.compile("^Time\.Estimated\.+: +(.*)\s*$"))) elif self.crack_type == "mask": regex_list.append(("progress", re.compile("^Input\.Mode\.+: +Mask\s+\(\S+\)\s+\[\d+\]\s+\((\S+)%\)\s*$"))) self.time_started = str(datetime.now()) if not self.session_status in ["Aborted"]: # Command lines used to crack the passwords if self.crack_type == "dictionary": if self.rule_file != None: cmd_line = [Hashcat.binary, '--session', self.name, '--status', '-a', '0', '-m', str(self.hash_mode_id), self.hash_file, self.wordlist_file, '-r', self.rule_file] else: cmd_line = [Hashcat.binary, '--session', self.name, '--status', '-a', '0', '-m', str(self.hash_mode_id), self.hash_file, self.wordlist_file] if self.crack_type == "mask": cmd_line = [Hashcat.binary, '--session', self.name, '--status', '-a', '3', '-m', str(self.hash_mode_id), self.hash_file, self.mask_file] if self.username_included: cmd_line += ["--username"] if self.device_type: cmd_line += ["-D", str(self.device_type)] # workload profile cmd_line += ["--workload-profile", Hashcat.workload_profile] # set pot file cmd_line += ["--potfile-path", self.pot_file] else: # resume previous session cmd_line = [Hashcat.binary, '--session', self.name, '--restore'] print("Session:%s, startup command:%s" % (self.name, " ".join(cmd_line))) logging.debug("Session:%s, startup command:%s" % (self.name, " ".join(cmd_line))) with open(self.hashcat_output_file, "a") as f: f.write("Command: %s\n" % " ".join(cmd_line)) self.session_status = "Running" self.time_started = datetime.utcnow() self.save() if os.name == 'nt': # To controlhashcat on Windows, very different implementation than on linux # Look at: # https://github.com/hashcat/hashcat/blob/9dffc69089d6c52e6f3f1a26440dbef140338191/src/terminal.c#L477 free_console=True try: win32console.AllocConsole() except win32console.error as exc: if exc.winerror!=5: raise ## only free console if one was created successfully free_console=False self.win_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) # cwd needs to be added for Windows version of hashcat if os.name == 'nt': self.session_process = subprocess.Popen(cmd_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(Hashcat.binary)) else: self.session_process = subprocess.Popen(cmd_line, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(Hashcat.binary)) self.update_session() for line in self.session_process.stdout: with open(self.hashcat_output_file, "ab") as f: f.write(line) line = line.decode() line = line.rstrip() if line == "Resumed": self.session_status = "Running" self.save() if line == "Paused": self.session_status = "Paused" self.save() for var_regex in regex_list: var = var_regex[0] regex = var_regex[1] m = regex.match(line) if m: setattr(self, var, m.group(1)) # check timestamp if self.end_timestamp: current_timestamp = int(datetime.utcnow().timestamp()) if current_timestamp > self.end_timestamp: self.quit() break return_code = self.session_process.wait() # The cracking ended, set the parameters accordingly if return_code in [255,254]: self.session_status = "Error" if return_code == 254: self.reason = "GPU-watchdog alarm" else: ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') error_msg = self.session_process.stderr.read().decode() error_msg = ansi_escape.sub('', error_msg).strip() self.reason = error_msg elif return_code in [2,3,4]: self.session_status = "Aborted" self.reason = "" else: self.session_status = "Done" self.reason = "" self.time_estimated = "N/A" self.speed = "N/A" self.save()
def __cmdHandler(cls, msg): if cls.__cmdBuffer == None: win32console.AllocConsole() cls.__cmdBuffer = win32console.CreateConsoleScreenBuffer() cls.__cmdBuffer.SetConsoleActiveScreenBuffer() cls.__cmdBuffer.WriteConsole(msg)