билайн, автоматическая маршрутизация tp.internet.beeline.ru

Ответить
ya
^-^
Сообщения: 2673
Зарегистрирован: 16 дек 2021, 19:56

билайн, автоматическая маршрутизация tp.internet.beeline.ru

Сообщение ya »

билайн, автоматическая маршрутизация tp.internet.beeline.ru

Код: Выделить всё

#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <sstream>
#include <cstdlib> // для system()
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

const std::string configFilePath = "/etc/xl2tpd/xl2tpd.conf";
const std::string lnsKey = "lns";

std::string getIpForHostname(const std::string& hostname) {
    struct addrinfo hints{}, *res;
    hints.ai_family = AF_INET; // IPv4
    int err = getaddrinfo(hostname.c_str(), nullptr, &hints, &res);
    if (err != 0) {
        std::cerr << "Error resolving hostname: " << gai_strerror(err) << std::endl;
        return "";
    }
    char ipStr[INET_ADDRSTRLEN];
    struct sockaddr_in* ipv4 = (struct sockaddr_in*)res->ai_addr;
    inet_ntop(AF_INET, &(ipv4->sin_addr), ipStr, INET_ADDRSTRLEN);
    freeaddrinfo(res);
    return std::string(ipStr);
}

bool readConfigFile(const std::string& path, std::string& content) {
    std::ifstream inFile(path);
    if (!inFile) {
        std::cerr << "Failed to open config file for reading: " << path << std::endl;
        return false;
    }
    content.assign((std::istreambuf_iterator<char>(inFile)),
                    (std::istreambuf_iterator<char>()));
    return true;
}

bool writeConfigFile(const std::string& path, const std::string& content) {
    std::ofstream outFile(path);
    if (!outFile) {
        std::cerr << "Failed to open config file for writing: " << path << std::endl;
        return false;
    }
    outFile << content;
    return true;
}

bool checkRouteExists(const std::string& route) {
    // Проверка наличия маршрута
    std::string cmd = "ip route show " + route + " | grep -w \"" + route + "\"";
    int ret = system(cmd.c_str());
    return (ret == 0);
}

void addRoute() {
    // Добавление маршрута
    std::string cmd = "route add -net 172.18.48.0 netmask 255.255.255.0 gw 10.116.51.1 dev ens10";
    int ret = system(cmd.c_str());
    if (ret != 0) {
        std::cerr << "Ошибка при добавлении маршрута." << std::endl;
    } else {
        std::cout << "Маршрут успешно добавлен." << std::endl;
    }
}

int main() {
    const std::string hostname = "tp.internet.beeline.ru";

    // Получить IP-адрес для hostname
    std::string hostIp = getIpForHostname(hostname);
    if (hostIp.empty()) {
        std::cerr << "Не удалось определить IP-адрес для " << hostname << std::endl;
        return 1;
    }
    std::cout << "IP-адрес для " << hostname << ": " << hostIp << std::endl;

    // Проверка наличия маршрута и добавление при необходимости
    std::string routeToCheck = "172.18.48.0/24";
    if (!checkRouteExists(routeToCheck)) {
        std::cout << "Маршрут " << routeToCheck << " отсутствует. Добавляю..." << std::endl;
        addRoute();
    } else {
        std::cout << "Маршрут " << routeToCheck << " уже существует." << std::endl;
    }

    // Чтение конфигурационного файла
    std::string configContent;
    if (!readConfigFile(configFilePath, configContent)) {
        return 1;
    }

    // Поиск текущего значения lns
    std::regex lnsRegex(R"(^\s*lns\s*=\s*([^\s#]+))", std::regex::icase | std::regex::multiline);
    std::smatch match;
    bool found = false;
    std::string currentLnsValue;

    if (std::regex_search(configContent, match, lnsRegex)) {
        found = true;
        currentLnsValue = match[1];
        std::cout << "Текущее значение lns: " << currentLnsValue << std::endl;
    } else {
        std::cout << "Ключ lns не найден в конфигурационном файле." << std::endl;
    }

    // Проверка совпадения IP
    if (found && currentLnsValue == hostIp) {
        std::cout << "Значение lns уже соответствует IP-адресу." << std::endl;
    } else {
        // Замена или добавление lns
        if (found) {
            // Заменить существующую строку
            std::string newConfig;
            std::istringstream iss(configContent);
            std::string line;
            while (std::getline(iss, line)) {
                if (std::regex_match(line, match, lnsRegex)) {
                    newConfig += "lns = " + hostIp + "\n";
                } else {
                    newConfig += line + "\n";
                }
            }
            configContent = newConfig;
        } else {
            // Добавить новую строку
            if (!configContent.empty() && configContent.back() != '\n') {
                configContent += "\n";
            }
            configContent += "lns = " + hostIp + "\n";
        }

        // Записать файл
        if (!writeConfigFile(configFilePath, configContent)) {
            return 1;
        }
        std::cout << "Обновлено значение lns на: " << hostIp << std::endl;

        // Перезагрузить сервис
        std::cout << "Перезагрузка сервиса xl2tpd..." << std::endl;
        int ret = system("systemctl force-reload xl2tpd");
        if (ret != 0) {
            std::cerr << "Ошибка при выполнении systemctl force-reload xl2tpd" << std::endl;
            return 1;
        }
        std::cout << "Сервис xl2tpd успешно перезагружен." << std::endl;
    }

    return 0;
}

Код: Выделить всё

route add -net 172.18.48.0 netmask 255.255.255.0 gw 10.116.51.1 dev ens10
/etc/resolv.beeline.conf

Код: Выделить всё

domain beeline
search beeline
nameserver 172.18.49.10
nameserver 172.18.49.14
ya
^-^
Сообщения: 2673
Зарегистрирован: 16 дек 2021, 19:56

Re: билайн, автоматическая маршрутизация tp.internet.beeline.ru

Сообщение ya »

Для сборки создать файл CMakeLists.txt и установить пакеты cmake make g++

alpine

Код: Выделить всё

sudo apk add cmake make g++
devuan

Код: Выделить всё

sudo apt install cmake make g++
CMakeLists.txt

Код: Выделить всё

cmake_minimum_required(VERSION 3.10)

# Название проекта
project(xl2tpd_configurator)

# Установка стандарта C++
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Добавляем исполняемый файл
add_executable(xl2tpd_configurator main.cpp)
собрать командами:

Код: Выделить всё

make clean
cmake .
make -j$(nproc) 
Ответить