Exemple #1
0
def kill_internet(ppid: int, print_output: bool = True) -> int:
    """ Отключение от интернета """

    # print_output "Печать вывода"
    # ppid "Номер процесса"

    if print_output is True:
        status_user = _input_while.input_y_n("Обнаружено соединение с ",
                                             "использованием wpa_supplicant,"
                                             " прервать? (y, n)",
                                             color="yellow")
        if status_user == 1:
            subprocess.check_output(["systemctl", "stop",
                                    "wpa_supplicant_python.service"])

            # Пробуем остановить службу (если её нет, то ничего не произойдет)
            _writes.kill(ppid)
            print_arr("Соединение было разорвано!", color="red")
            return 1

        if status_user == 0:
            if print_output is True:
                print_arr("Учтите, т.к wpa_supplicant запущен,",
                          "могут возникнуть проблемы", color="red")
            return 0

    if print_output is False:
        subprocess.check_call(["systemctl", "stop",
                              "wpa_supplicant_python.service"])
        _writes.kill(ppid)
        return 1
Exemple #2
0
 def wrap2(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except (KeyboardInterrupt, EOFError):
         print()
         print_arr("Остановлено!", color="red")
         raise SystemExit(1)
def input_list(text_quest: str,
               text: List[str],
               color: str,
               print_output: bool = True) -> int:
    """ Менюшка с вариантами ответов """

    # text_quest "Вопрос"
    # text "Варианты ответов"

    assert isinstance(text, list)

    print_arr(text_quest, color=color)

    if print_output is True:
        print_arr("-" * 25, color="green")
        for ind, value in enumerate(text, 1):
            print_arr(f"[{ind}] ", value, color="red", arrow=False)
        print_arr("-" * 25, color="green")

    if print_output is False:
        ind = len(text)

    while True:
        try:
            user_choice = input("> ").lower()

            if (len(user_choice) > 3 or int(user_choice) <= 0
                    or int(user_choice) > ind):
                raise ValueError

            return text[int(user_choice) - 1]

        except ValueError:
            print_arr(f"{user_choice} не существует!", color="red")
Exemple #4
0
def connect(device: str, path: str, print_output: bool = True) -> int:
    """ Используется для подключение к интернету """

    # device "Модуль вафли"
    # path "Путь до конфига"
    # print_output "Печатать вывод"

    _writes.extra_kill()
    # Финальный шаг
    try:
        subprocess.check_call(
            ["wpa_supplicant", "-B", "-i", device, "-c", path],
            stdout=devnull, stderr=devnull)
    except subprocess.CalledProcessError:
        pass

    if check_connect() == 1:
        if print_output is True:
            print_arr("Подключено!", color="green")
        return 1

    else:
        if print_output is True:
            print_arr("Не получилось подключится ): ", color="red")
        return 0
def check_root():
    """ Проверка рута """

    user = getpass.getuser()  # Узнаем пользователя

    if user != "root":
        print_arr("Привет, ", user, color="green")
        print_arr("Для работоспособности программы "
                  "Вам требуется root",
                  color="red")
        raise SystemExit(1)
Exemple #6
0
        def wrap2(*args, **kwargs):
            try:
                return_status = func(*args, **kwargs)
            except Exception as e:
                print_arr("Произошла ошибка!", color="red")
                print_arr(e, color="red")

                return 0
            else:
                if return_status is None:
                    return 1
                if return_status is not None:
                    return return_status
def input_y_n(*text: str, color: str):
    """ Спрашивает пользователя, давая вводить y или n """
    # text "`text` будет появлятся при вопросе"

    print_arr(*text, color=color)
    while True:
        user_choice = input("> ").lower()

        if user_choice == "y":
            return 1
        if user_choice == "n":
            return 0
        print_arr("Не понимаю о чем Вы, повторите еще раз...", color="red")
Exemple #8
0
def auto_wpa(print_output: bool = True) -> int:
    """ Добавляем наш демон в автозагрузку """

    # print_output "Вывод"

    try:
        if print_output:
            print_arr("Добавляю в автозагрузку...", color="green")

        subprocess.check_call(
            ["systemctl", "enable", "wpa_supplicant_python.service"],
            stdout=devnull,
            stderr=devnull)
        return 1
    except subprocess.CalledProcessError as error:
        print_arr(error, color="red")
        return 0
def kill(id_proccess: int) -> int:
    """ Завершение процесса """

    try:
        process = psutil.Process(id_proccess)
        process.kill()

        if check_connect(timeout=1.5, print_output=False) == 1:
            status_kill = extra_kill()

            if status_kill == 0:
                print_arr("Не получилось отключится, прерывание!", color="red")
                raise SystemExit(1)

        return 1
    except Exception as e:
        return 0
Exemple #10
0
def check_connect(timeout: int = 10, print_output: bool = True) -> int:
    """ Проверка соединения с интернетом """

    # timeout - "Задержка (wpa_supplicant не сразу включается)"
    # print_output - "Печатать вывод"

    if print_output is True:
        print_arr("Проверка соединения...", color="yellow")

    time.sleep(timeout)

    s = socket.gethostbyname(socket.getfqdn())

    if s.startswith("192."):
        return 1

    return 0
Exemple #11
0
def write_daemon(device: str, path: str) -> int:
    """ Создаём демона """

    # device "Модуль вайли"
    # path "Путь до конфига"

    daemon = f"""
[Unit]
Description = network connection
After = network.target
[Service]
ExecStart = /usr/bin/wpa_supplicant -B -i {device} -c {path}
RemainAfterExit=true
[Install]
WantedBy = multi-user.target
"""
    if os.path.exists(path_daemon):
        with open(path_daemon) as file:
            if file.read() == daemon:
                raise SystemExit(0)

        user_choice = _input_while.input_y_n("Обнаружен существующий демон.",
                                             " Перезаписать? (y, n)",
                                             color="yellow")

        if user_choice == 1:
            os.remove(path_daemon)
            with open(path_daemon, "w") as file:
                file.write(daemon)

            return 1
    else:
        user_choice = _input_while.input_y_n(
            "Желаете добавить в автозагрузку"
            "? (y, n)", color="yellow")

        if user_choice == 1:
            with open(path_daemon, "w") as file:
                file.write(daemon)

            if auto_wpa(print_output=False) != 1:
                print_arr("Не удалось добавить в автозагрузку!", color="red")
                raise SystemExit(0)
def password_user(ssid: str) -> Union[str, None]:
    """ Функция для ввода пароля """

    print_arr(f"Введите пароль от {ssid}\n[ENTER] - если пароль ненужен",
              color="green")

    while True:
        user_choice = input("> ")

        if user_choice == "":
            return None

        if len(user_choice) < 8 or len(user_choice) > 64:
            print_arr(
                "Пароль должен состоять от 8 символов и до 64, "
                "повторите попытку!",
                color="red")
        else:
            return user_choice
def password_and_ssid() -> Tuple[str]:
    """ Функция для ввода SSID & Пароля """

    # Ввод ssid
    print_arr("Введите SSID (название точки доступа)", color="green")
    ssid = input("> ")
    # Ввод пароля

    path = correct_Profile(ssid)
    if ssid in profiles_mkdir():
        user_Choice = input_y_n("Профиль существует, перезаписать? (y, n) ",
                                color="yellow")
        if user_Choice == 0:
            password = view_password(path)
            return ssid, password

        if user_Choice == 1:
            os.remove(path)

    password = password_user(ssid)
    return ssid, password
def take_device(print_output: bool = True) -> Tuple[str]:
    """ Определение вафли """
    global device

    devices = [line for line in psutil.net_if_stats()]
    device_list = [
        line for line in devices if line != 'lo' and "enp" not in line
    ]

    if len(device_list) == 1:
        device = device_list[0]
        return device

    elif len(device_list) == 0:
        print_arr("Ошибка: Не обнаружено ни одного молуля!", color="red")
        raise SystemExit(1)

    else:
        device_arg = __init__.args.device
        if device_arg is not False:  # Если был введен аргумент --device
            if device_arg not in device_list:  # если пользователь ошибся
                print_arr(f"Модуль {device_arg} не найден!", color="yellow")
                device = input_list(
                    "Обнаружено несколько модулей"
                    " WI-FI, выберите нужный!",
                    device_list,  # Список с модулями
                    color="yellow")
            else:  # Если все норм
                device = device_arg

        elif device_arg is False:  # Если аргумента непоследовало
            if print_output is True:
                device = input_list(
                    "Обнаружено несколько модулей"
                    " WI-FI, выберите нужный!",
                    device_list,  # Список с модулями
                    color="yellow")

        return device
Exemple #15
0
def watch_ssid() -> Union[int, List[str]]:
    """
    Функция для просмотра SSID
    """

    try:
        out = os.popen("wpa_cli scan").read().split("\n")
        if "OK" in out[1]:
            print_arr("Идет поиск WI-FI сетей...", color="yellow")

            time.sleep(2)

            wifi_list = os.popen("wpa_cli scan_results").read()
            wifi_list = wifi_list.split("\n")
            wifi_list_dirty = wifi_list[2:]
            wifi_list_dirty = [[line.replace('\t', " ")]
                               for line in wifi_list_dirty]

            wifi_list_clean = []
            for line in wifi_list_dirty:
                wifi_list_clean.append([element.split(" ")
                                       for element in line])

            del wifi_list_clean[-1]

            print(print_arr("MAC", color="pink",
                            return_color=True).rjust(26), end="")

            print(print_arr("SIGNAL", color="pink",
                            return_color=True).rjust(22), end="")

            print(print_arr("SECURITY", color="pink",
                            return_color=True).center(23), end="")

            print(print_arr("SSID", color="pink",
                            return_color=True).center(34), end="")
            print()

            unpack = lambda *x: x
            counter = 0
            ssids_wifi = []
            for line in wifi_list_clean:
                for line2 in line:
                    if len(line2) != 5:
                        for number, string in enumerate(line2, 0):
                            if string.rfind("[ESS]") == -1: continue
                            else:
                                break

                        ssid_full = ""
                        for last_word in line2[number + 1:]:
                            ssid_full += last_word

                        del line2[number + 1:]
                        line2.append(ssid_full)

                    for mac, none, signal, security, ssid in unpack(line2):
                        counter += 1

                        ssids_wifi.append(ssid)
                        counter_text = f"[{counter}]"

                        signal = int(signal[1:])
                        #######################################################
                        # MAC Адресс
                        text = print_arr(mac, color="yellow", arrow=False,
                                         return_color=True
                                         ).ljust(len(mac) + 10, "|")
                        text = "{0}{2}\033[39m|\033[39m{1}"
                        "".format(counter_text.center(6), text, "")
                        print(text, end="")
                        #######################################################

                        # Уровень сигнала

                        ##########
                        # Покраска текста
                        if signal < 65:
                            color = "green"
                        elif signal < 75:
                            color = "yellow"
                        elif signal < 85:
                            color = "red"
                        else:
                            color = "red"
                        ##########

                        text = print_arr(
                                        signal,
                                        color=color,
                                        return_color=True
                                        ).ljust(12)

                        print(f"  {text} |", end="")
                        #######################################################

                        # Безопасность

                        if security == "[ESS]":
                            text = "None".center(8)
                        elif ("[WPA-PSK-CCMP+TKIP]" in security
                              or "[WPA2-PSK-CCMP+TKIP]" in security):
                            text = "WPA/WPA2"

                        elif ("[WPA-PSK-CCMP]" in security
                              or "[WPA2-PSK-CCMP]" in security):
                            text = "WPA/WPA2"

                        text = print_arr(text,
                                         color="red",
                                         return_color=True).ljust(12)
                        print(f" {text} ".ljust(20, "|"), end="")
                        #######################################################

                        # SSID сетей
                        text = print_arr(ssid,
                                         color="blue",
                                         return_color=True).center(35)
                        if ssid == "":
                            text = print_arr("<SSID не обнаружен!>",
                                             color="red",
                                             return_color=True).center(35)

                        print(f"{text}".ljust(len(text) + 1, "|"))
            print()
            return ssids_wifi

        else:
            print(out)
            print_arr(out[1], color="red")
            print_arr("Не удалось просканировать сети!", color="red")

    except Exception:
        return 0
Exemple #16
0
from _config import devnull


try:
    russian_locale()
    check_root()
    device_user = take_device()
    # -----------------------

    module_profile()
    write_dhcp()

    #########################
    # Добавление в автозагрузку
    print_arr(
            "Запускаю/добавляю в автозагрузку systemd-networkd...",
            color="pink")

    subprocess.check_call(["systemctl", "enable", "--now",
                          "systemd-networkd.service"],
                          stdout=devnull,
                          stderr=devnull)

    # Создание ссылки
    subprocess.check_call(["ln", "-snf", "/run/systemd/resolve/resolv.conf",
                          "/etc/resolv.conf"],
                          stdout=devnull,
                          stderr=devnull)

    # Запуск systemd-resolved / автозагрузка
    subprocess.check_call(["systemctl", "enable", "--now",