예제 #1
0
def main():
    engine_dir = sys.argv[1]
    ferr = sys.argv[2]

    engine_setup = str(Path(engine_dir, 'setup.py'))
    install_command = [sys.executable, engine_setup, 'install']

    p = subprocess.run(install_command,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       cwd=engine_dir)

    if p.returncode != 0:
        if (b"error: could not create 'build'" in p.stderr
                or b"error: You do not have write permission" in p.stderr):
            # Access denied, try to install as Administrator/root
            elevate.elevate(show_console=False, graphical=True)

        try:
            stderr_text = p.stderr.decode()
        except UnicodeDecodeError:
            enc = chardet.detect(p.stderr)['encoding']
            if enc:
                stderr_text = p.stderr.decode(enc)
            else:
                # cannot decode bytes, return as it is
                stderr_text = str(p.stderr)

        with open(ferr, 'w', encoding='utf-8') as fp:
            fp.write(stderr_text)

    return p.returncode
예제 #2
0
def main():
    '''
    Runs authentication server.
    '''
    # elevate this to root for modifying iptables
    elevate(graphical=False)
    Server().run()
예제 #3
0
    def check_wsc(self):
        """The high-level method to check wpa_supplicant.conf file's validation. If the file is not valid, method creates new valid file.
        """

        if os.path.isfile(self.wpa_supp_conf_file):
            elevate(show_console=False, graphical=False)

            wpa_supp_file = open(self.wpa_supp_conf_file, "r")
            correct_header_count = 0
            for line in wpa_supp_file:
                if self.conf_headers[0] in line:
                    correct_header_count += 1
                if self.conf_headers[1] in line:
                    correct_header_count += 1
                if self.conf_headers[2] in line:
                    correct_header_count += 1

            wpa_supp_file.close()

            if correct_header_count != 3:
                print("wpa_supplicant.conf is not valid. Creating new one.")
                self.create_wsc()

        else:
            self.create_wsc()
예제 #4
0
def client():
    parser = ArgumentParser()
    parser.add_argument('iface', metavar='interface', type=str)
    parser.add_argument('-p', '--port', metavar='PORT', type=int, default=8888, dest='port')
    parser.add_argument('--host', metavar='PORT', type=str, dest='host')
    args = parser.parse_args()

    elevate(graphical=False)

    while True:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.connect((args.host, args.port))
            print('⭘ Connected to {}:{}'.format(args.host, args.port))
            mac = sock.recv(17).decode('ascii')
            time_left = int(sock.recv(10).decode('ascii'))
            print('⭘ Received pass for MAC', mac)

            set_interface_mac(args.iface, mac)

        with Halo(spinner='clock') as s:
            for i in reversed(range(time_left)):
                s.text = 'Waiting {}m {}s until next pass... [q]uit | [r]efresh'.format(int(i / 60), i % 60)
                rlist, _, _ = select([sys.stdin], [], [], 0)
                if rlist:
                    key = sys.stdin.readline()[0]
                    if key == 'q':
                        return
                    elif key == 'r':
                        break
                    else:
                        s.text = 'Command not recognized: {}'.format(key)

                time.sleep(1)
예제 #5
0
def main():
    elevate.elevate()
    app = wx.App()
    locale_setup.setup_locale()
    mc = main_controller.MainController()
    mc.show_window()
    app.MainLoop()
예제 #6
0
def prepare(args):
    """The function that prepares the working environment for storing data during running.

    Args:
        args:       Command-line arguments.
    """

    if args["interface"] == "official_stand" or args[
            "interface"] == "remote_ui":
        elevate(show_console=False, graphical=False)

    if not os.path.exists(dot_t_system_dir):
        os.mkdir(dot_t_system_dir)

    global administrator
    global update_manager

    administrator = Administrator()
    update_manager = UpdateManager()

    if args["sub_jobs"]:
        start_sub(args)
        sys.exit(1)

    if args["access_point"]:
        elevate(show_console=False, graphical=False)

        access_point = AccessPoint(args)
        access_point.start()

    if not args["AI"] or args["non_moving_target"]:
        if args["learn"]:
            raise Exception(
                'All AI learning tools deprecated. Don\'t use the learn mode without AI.'
            )
예제 #7
0
def main():
    print(HTML('<b><skyblue>systemd unit file generator</skyblue></b>'))

    unit_install = False

    argparser = argparse.ArgumentParser()
    argparser.add_argument(
        '--install',
        help=
        'Install the generated systemd file. You need root rights or sudo to use this option.'
    )
    args = argparser.parse_args()
    if args.install:
        elevate()
        unit_install = True

    svcname = prompt('Service name: ', validator=RequiredValidator())
    executable = prompt('Service command: ', validator=RequiredValidator())
    cwddir = prompt('Working directory: ')
    usraccount = prompt('Service account name: ',
                        validator=RequiredValidator())
    usrgroup = prompt('Service group name: ')
    restart = prompt(
        'Restart Behavior (1 = never, 2 = always 3 = on-success 4 = on-failure 5 = on-abnormal 6 = on-abort 7 = on-watchdog): ',
        validator=RestartNumberValidator())
    desc = prompt('Description: ')

    file = generate_unit(svcname, executable, cwddir, usraccount, usrgroup,
                         restart, desc)

    if unit_install:
        install_unit(file)
예제 #8
0
def main():
    try:
        hide_console()

        if not Debug and not is_admin():
            try:
                from elevate import elevate
                elevate(graphical=False, show_console=True)
                return
            except Exception:
                result = message_box(
                    "Some features may not be available or may not work properly.\nPlease, run as administrator!",
                    "Warning")
                if result == 4:
                    restart()
                    return
                if result == 5:
                    pass
                else:
                    exit(1)
                    return

        logger.init()
        config.init()

        browser = Thread(target=lambda: start_browser(shutdown))

        browser.start()

        shutdown()

    except KeyboardInterrupt:
        shutdown()
예제 #9
0
def main():
    parser = ArgumentParser()
    parser.add_argument('iface', metavar='interface', type=str)
    parser.add_argument('--once', dest='once', action='store_true')
    args = parser.parse_args()

    elevate(graphical=False)
    while True:
        change_activate(args.iface)

        if args.once:
            break
        else:
            with Halo(spinner='clock') as s:
                for i in reversed(range(60 * 59)):
                    s.text = 'Waiting {}m {}s until next pass... [q]uit | [r]efresh'.format(int(i / 60), i % 60)
                    rlist, _, _ = select([sys.stdin], [], [], 0)
                    if rlist:
                        key = sys.stdin.readline()[0]
                        if key == 'q':
                            return
                        elif key == 'r':
                            break
                        else:
                            s.text = 'Command not recognized: {}'.format(key)

                    time.sleep(1)
예제 #10
0
def driver():
    if get_os() == 2:
        if ctypes.windll.shell32.IsUserAnAdmin() == 0:
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable,
                                                __file__, None, 1)
    else:
        if os.getuid() == 0:
            elevate(graphical=False)

    print("Running script with Root/Admin privileges. AWESOME!!")

    os_number = get_os()

    if os_number == 2:
        print("OS: Windows")
        website_blocker = Blocker(r"C:\Windows\System32\drivers\etc\hosts",
                                  os_number)
        website_blocker.blocker_menu()
    elif os_number == 1:
        print("OS: OS X")
        website_blocker = Blocker("/etc/hosts", os_number)
        website_blocker.blocker_menu()
    elif os_number == 0:
        print("OS: Linux")
        website_blocker = Blocker("/etc/hosts", os_number)
        website_blocker.blocker_menu()
예제 #11
0
def processInitialization():

    # Register handler for CTRL+C quitting
    signal.signal(signal.SIGINT, signalHandler)

    # Elevate to root permission
    elevate(graphical=False)
예제 #12
0
    def add(self, command: str):
        elevate.elevate(graphical=False)

        buffer: str = (f"start on filesystem\n" f"exec {command}")

        with open(f"/etc/init/{self._filename(command)}", "w") as script:
            script.write(buffer)
예제 #13
0
def checkupdates(versionu):
    print(versionu)
    try:    
        is_adminp = ctypes.windll.shell32.IsUserAnAdmin()
    except:
        pass
        is_adminp = 1
    if is_adminp == 1:
        is_admin = True
    else:
        is_admin = False
    verrequest = requests.get(url="https://raw.githubusercontent.com/InventorXtreme/ChatNoise/master/version")
    if versionu == verrequest.text:
        pass
    else:
        versionmenu = messagebox.askquestion(title="Electic Boogaloo Update", message="Update found!\n"
                                                                                "Your Version :" + versionu + "\n"
                                                                                "New Version: " + verrequest.text + "\n"
                                                                                "Update to new version?")
        if versionmenu == "yes":
            download_folder = os.path.expanduser("~") + "/Downloads/"
            snip = verrequest.text[2:]
            url = "https://github.com/InventorXtreme/ChatNoise/releases/download/" + snip + "/setup.exe"
            print(url)
            # messagebox.showinfo("Downloading Update...","Downloading Update...")
            if is_admin == False:
                root.destroy()
                elevate()
            else:
                #urllib.request.urlretrieve(url, r"C:\temp\setup.exe")
                setupfile = requests.get(url)
                with open(r'C:\temp\setup.exe') as helpme:
                    helpme.write(setupfile.content)
                exit()
예제 #14
0
def main():
    if platform.system() != "Windows":
        elevate(graphical=True)  # root permission for linux

    player_addr = ('127.0.0.1', int(sys.argv[1]))
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    wait_for_player(soc, player_addr)

    send = lambda byte: soc.sendto(byte, player_addr)
    death = threading.Event()
    try:  # bind the hotkeys
        i = 0
        for _, hotkey, src in read_hk():
            print(hotkey, "-->", src)
            if src == QUIT:
                kb.add_hotkey(hotkey, end_of_the_fun, args=(send, death, i))
            else:
                kb.add_hotkey(hotkey, hk_pressed, args=(send, hotkey, i))
            i += 1
    except Exception as e:
        log(f"binding the hotkeys -> {str(e)}")
        sys.exit(1)

    print('LISTENER READY')
    death.wait()
    print('LISTENER DIED')
예제 #15
0
 def __init__(self, clock):
     elevate()
     self.clock = clock
     self.snake = None
     self.pixels = neopixel.NeoPixel(RPI_PIN,
                                     NUMBER_OF_LEDS,
                                     auto_write=False)
     self.is_updating = False
     self.playing_snake = False
예제 #16
0
def step_2():
    """Install NodeJS"""
    print("Entering Step 2; Install NodeJS")
    logging.debug("Entering Step 2; Install NodeJS")
    if windows:
        if os.path.exists(
                os.path.realpath(f"{os.environ['ProgramFiles']}\\nodejs")):
            logging.debug(
                "NPM and nodeJS already installed, skipping installation")
        else:
            exc_path = _download(
                "node",
                "https://nodejs.org/dist/v12.19.0/node-v12.19.0-x64.msi",
                ".msi")
            # Can't use _install() because need to use msi tools
            subprocess.Popen(
                f'msiexec.exe /i {exc_path} ADDLOCAL=\"DocumentationShortcuts,EnvironmentPathNode,EnvironmentPathNpmModules,npm,NodeRuntime,EnvironmentPath\" /passive',
                universal_newlines=True,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE).communicate()

            from tkinter import Tk, Label
            from tkinter import messagebox

            root = Tk()
            root.geometry("500x500")

            details = Label(
                root,
                text=
                'Please close this window and re-run install.exe to finalize installation',
                font="50")
            details.pack()
            root.mainloop()

            os.remove(exc_path)
            sys.exit()
    elif linux:
        ...
    elif mac:
        if os.path.exists("/usr/local/bin/npm"):
            logging.debug(
                "NPM and nodeJS already installed, skipping installation")
        else:
            elevate(show_console=False
                    )  # Displays a popup window to give script sudo access
            logger = logging.getLogger(__name__)  # Reinstantiate logger
            exc_path = _download(
                "node", "https://nodejs.org/dist/v12.19.0/node-v12.19.0.pkg",
                ".pkg")
            out, err = subprocess.Popen(f'installer -pkg {exc_path} -target /',
                                        universal_newlines=True,
                                        shell=True,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE).communicate()
            print(out, err)
예제 #17
0
def try_UAC_bypass(my_socket):
    if is_admin():
        # Code of your program here
        print("[+] It is already in admin mode")

    else:
        # Re-run the program with admin rights
        print("[-] Trying to escalate to ADMIN")
        elevate(show_console=False)
예제 #18
0
def main():
    parsed = parser.parse_args()
    colors = [Color(color) for color in parsed.colors.split(",")]
    colors = _expand_colors_to(colors, 7)
    pattern = Pattern(parsed.pattern)

    if not os.geteuid() == 0 and not parsed.root:
        elevate()

    KeyboardControler().send_args(colors, pattern, parsed.intensity,
                                  parsed.speed)
예제 #19
0
def main():
    if (platform.system() == "Windows"):
        # elevate(show_console=False)
        pass
    else:
        elevate(graphical=False)
        # pass
    root = tk.Tk()
    # root.iconbitmap('TC_Logo.ico')
    app = Settings(root)
    root.mainloop()
예제 #20
0
def main():
    # doom_binary = PureWindowsPath(home + "/.emacs.d/bin/doom.cmd")
    # run in admin mode so we can install emacs and symlinks to binaries
    elevate()
    install_emacs()
    install_site_start()
    download_and_install_dependencies()
    clone_doom_emacs_github_repo()
    install_custom_doom_cmd()
    symlink_binaries_to_appdata()
    run_doom_env()
    run_doom_install()
    install_config_files()
    run_doom_sync()
    install_fonts()
예제 #21
0
def handle_stop():
    # We will need sudo privileges to stop the driver because it was started as sudo
    if os.getuid != 0:
        elevate(graphical=False)

    for process in psutil.process_iter():
        cmdline = process.cmdline()
        if len(cmdline) < 3:
            continue

        if cmdline[2] == DRIVER_SCRIPT:
            print('Process found. Terminating it.')
            process.terminate()
            break
    else:
        print('Process not found: It is already dead')
예제 #22
0
def main(argv=None):
    actions = {
        'set': set_env_var,
        'prepend': prepend_env_var,
        'append': append_env_var,
    }

    envs = [winenv.ENV_USER, winenv.ENV_SYSTEM]

    p = argparse.ArgumentParser()
    p.add_argument('action',
                   choices=['set', 'prepend', 'append'],
                   metavar='action')
    p.add_argument('-m', '--system', action='store_true', dest='system')
    p.add_argument('-f', '--force', action='store_true', dest='overwrite')
    p.add_argument('vars', nargs='+', metavar='name=[value]')

    args = p.parse_args(argv)

    if not args.system or elevate.elevate():
        for var in args.vars:
            if '=' not in var:
                print('Skipping invalid var {}'.format(var), file=sys.stderr)
                continue

            name, value = var.split('=', 1)
            actions[args.action](name, value, envs[int(args.system)],
                                 args.overwrite)
예제 #23
0
def main():
    from elevate import elevate

    if not os.geteuid() == 0:
        elevate()

    control = ControlCenter(vendor_id=0x048d, product_id=0xce00)

    parser = argparse.ArgumentParser(
        description="Supply at least one of the options [-c|-H|-V|-s|-d]. "
        "Colors available: "
        "[red|green|blue|teal|pink|purple|white|yellow|orange]")
    parser.add_argument('-c', '--color', help='Single color')
    parser.add_argument('-b', '--brightness', help='1, 2, 3 or 4')
    parser.add_argument('-H',
                        '--h-alt',
                        nargs=2,
                        help='Horizontal alternating colors')
    parser.add_argument('-V',
                        '--v-alt',
                        nargs=2,
                        help='Vertical alternating colors')
    parser.add_argument(
        '-s',
        '--style',
        help='one of (rainbow, reactive, raindrop, marquee, aurora)')
    parser.add_argument('-d',
                        '--disable',
                        action='store_true',
                        help='turn keyboard backlight off'),

    parsed = parser.parse_args()
    if parsed.disable:
        control.disable_keyboard()
    if parsed.brightness:
        control.adjust_brightness(int(parsed.brightness))
    if parsed.color:
        control.mono_color_setup(parsed.color)
    elif parsed.h_alt:
        control.h_alt_color_setup(*parsed.h_alt)
    elif parsed.v_alt:
        control.v_alt_color_setup(*parsed.v_alt)
    elif parsed.style:
        control.keyboard_style(parsed.style)
    else:
        print("Invalid or absent command")
예제 #24
0
    def add(self, command: str):
        import configparser

        config: configparser.ConfigParser = configparser.ConfigParser()
        config.optionxform = str  # required because it preserves the cases

        elevate.elevate(graphical=False)

        config["Unit"] = {
            "Description": f"{os.path.dirname(command)}: Created by StartupPy"
        }
        config["Service"] = {"Type": "simple", "ExecStart": command}
        config["Install"] = {"WantedBy": "multi-user.target"}

        with open(f"/etc/systemd/system/{self._filename(command)}",
                  "w") as service:
            config.write(service)
예제 #25
0
    def __init__(self):
        useless_process_killer.check_and_kill()

        if psutil.MACOS:
            elevate()

        data_provider = PortDataProvider()

        app = QApplication(sys.argv)

        window = MainWindow(data_provider)

        window.resize(500, 600)
        window.setWindowTitle('Port Poirot')

        window.show()

        app.exec_()
예제 #26
0
def main():
    from elevate import elevate

    if not os.geteuid() == 0:
        elevate()

    control = ControlCenter(vendor_id=0x048d, product_id=0xce00)

    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''
            Supply at least one of the options [-c|-H|-V|-s|-d].
                
            Colors available:
            [red|green|blue|teal|pink|purple|white|yellow|orange|olive|maroon|brown|gray|skyblue|navy|crimson|darkgreen|lightgreen|gold|violet] '''),
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument(
        '-c', '--color', help='Select a single color for all keys.')
    parser.add_argument(
        '-b', '--brightness', help='Set brightness, 1 is minimum, 4 is maximum.', type=int, choices=range(1, 5))
    parser.add_argument('-H', '--h-alt', nargs=2,
                        help='Horizontal alternating colors')
    parser.add_argument('-V', '--v-alt', nargs=2,
                        help='Vertical alternating colors')
    parser.add_argument('-s', '--style',
                        help='One of (rainbow, marquee, wave, raindrop, aurora, random, reactive, breathing, ripple, reactiveripple, reactiveaurora, fireworks). Additional single colors are available for the following styles: raindrop, aurora, random, reactive, breathing, ripple, reactiveripple, reactiveaurora and fireworks. These colors are: Red (r), Orange (o), Yellow (y), Green (g), Blue (b), Teal (t), Purple (p). Append those styles with the start letter of the color you would like (e.g. rippler = Ripple Red')
    parser.add_argument('-d', '--disable', action='store_true',
                        help='Turn keyboard backlight off'),

    parsed = parser.parse_args()
    if parsed.disable:
        control.disable_keyboard()
    if parsed.brightness:
        control.adjust_brightness(int(parsed.brightness))
    if parsed.color:
        control.mono_color_setup(parsed.color)
    elif parsed.h_alt:
        control.h_alt_color_setup(*parsed.h_alt)
    elif parsed.v_alt:
        control.v_alt_color_setup(*parsed.v_alt)
    elif parsed.style:
        control.keyboard_style(parsed.style)
    else:
        print("Invalid or absent command")
예제 #27
0
def handle_evdev_test(event_path):
    # We will need sudo privileges to access the event files
    if os.getuid != 0:
        elevate(graphical=False)

    try:
        dev = evdev.InputDevice(event_path)
        if not dev:
            raise Exception(
                "could not find device. The device may already be open")

        for event in dev.read_loop():
            if event.type == evdev.ecodes.EV_KEY:
                print(evdev.categorize(event))
    except Exception as e:
        print(e, file=sys.stderr)
    except KeyboardInterrupt:
        print('Exiting')
        exit()
예제 #28
0
def compat_check():
    print("Checking for compatibility...")
    cprint(f"Release: v1.0 {platform}", "grey", "on_yellow")
    # If linux, warn the user
    # If macOS, elevate permissions if not present
    if (platform == "linux"):
        print("(Unsupported OS): Anything beyond this point might go crazy...")
    elif (platform == "darwin"):
        from elevate import elevate
        if getuid() != 0:
            print("Not adminstrator: It's needed to emulate keyboard on macOS")
            elevate(graphical=False)
        if getuid() == 0:
            cprint("Success: ", "green", end="")
            print("Got permission!")
        else:
            print("Couldn't get administrator priveledges :(")
            input("rip. press [Enter] to close this app.")
            exit(0)
예제 #29
0
def main():
    target_spec = parse_args()

    # Stealth scan, OS scan, and MAC resolution require superuser priveleges
    elevate(graphical=False, show_console=False)

    # Enable p0f passive scan while nmap is scanning
    with P0f_client("p0f.socket") as p0f_client:
        nm = PortScanner()

        # If no target spec specified, detect subnet automatically
        if target_spec is None:
            target_spec = get_network_parameters()
            print("Using automatic target_spec: ", target_spec)

        # Invoke nmap scanner
        print("Starting scan")

        try:
            nm.scan(target_spec,
                    arguments="-sS -sU -p 22 -sV -O -T4 --script=banner")
        except KeyboardInterrupt as e:
            print("nmap scan interrupted.")

        # Process hosts
        hosts = dict()

        for host in nm.all_hosts():
            try:
                hosts[host] = Host(host, nm, p0f_client)
            except Exception as e:
                print("Error parsing host ", host, " ", e)
                raise e  # TODO - REMOVE

        print(len(hosts), " hosts scanned with target spec: ", target_spec)

        # Create XML output
        xml = XML(hosts)

        with open("host_report.xml", "w") as out_file:
            out_file.write(xml.get_xml())
예제 #30
0
    def install(self):
        """Method to install the dependencies after git updation. It creates the sha-256 hash of the changed install scripts.
        Then compares them with the scripts those has hash when the Installer instance generates. If there is a difference between old and new install scripts, starts reinstallation.
        otherwise, terminates.
        """

        if self.editable:
            current_hash = self.__get_hash_of(self.install_dev_sh)
            if current_hash == self.last_hash:
                return

            install_sh = self.install_dev_sh
        else:
            current_hash = self.__get_hash_of(self.install_sh)
            if current_hash == self.last_hash:
                return

            install_sh = self.install_sh

        elevate(show_console=False, graphical=False)
        subprocess.call(install_sh, shell=True)