Website mit ISPConfig REST API hinzufügen

Strontium

Member
Beispielcode ISPConfig Remote API für PHP, Python, Perl, Rust

Perl:
#!/usr/bin/env perl

use strict;
use warnings;
use LWP::UserAgent;
use JSON;
use HTTP::Request::Common;
use IO::Socket::SSL;

# SSL-Zertifikatsüberprüfung deaktivieren
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
IO::Socket::SSL::set_defaults(SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE);

# Zuerst ISPConfig Remote-User mit "Sites Domain functions" anlegen!

# Konfiguration
my $base_url = 'https://192.168.0.14:8080/remote/json.php';
my $username = 'ispconfigremoteuser';
my $password = 'secretpassword';
my $client_id = 1;
my $server_id = 1;

# Parameter für die Website-Erstellung
my $params = {
    server_id            => $server_id,          # (int) ID des Servers, auf dem die Domain hinzugefügt werden soll
    ip_address           => '*',                 # (varchar) IP-Adresse der Domain, Standard '*'
    domain               => 'apitestdomain.com', # (varchar) Domainname
    type                 => 'vhost',             # (varchar) Typ der Domain: 'vhost', 'alias', 'vhostalias', 'subdomain', 'vhostsubdomain'
    parent_domain_id     => 0,                   # (int) ID der übergeordneten Domain, falls es sich um eine Subdomain handelt
    vhost_type           => 'name',              # (varchar) Typ des vhost: 'name'
    hd_quota             => 100000,              # (bigint) Festplattenkontingent in MB, -1 für unbegrenzt
    traffic_quota        => -1,                  # (bigint) Verkehrskontingent in MB, -1 für unbegrenzt
    cgi                  => 'y',                 # (enum) CGI-Unterstützung: 'y' (Standard), 'n'
    ssi                  => 'y',                 # (enum) SSI-Unterstützung: 'y' (Standard), 'n'
    suexec               => 'y',                 # (enum) SuExec-Unterstützung: 'y' (Standard), 'n'
    errordocs            => 1,                   # (tinyint) Eigene Fehlermeldungsseiten: 1 (aktiviert), 0 (Standard)
    is_subdomainwww      => 1,                   # (tinyint) 'www' als Subdomain, 1 (aktiviert), 0 (deaktiviert)
    subdomain            => 'none',              # (enum) 'none' (Standard), 'www', '*'
    php                  => 'php-fpm',           # (enum) PHP-Unterstützung: 'no', 'fast-cgi', 'php-fpm' (Standard)
    ruby                 => 'n',                 # (enum) Ruby-Unterstützung: 'y', 'n' (Standard)
    redirect_type        => '',                  # (varchar) Typ der Weiterleitung, z.B. 'no', 'R', 'L', 'redirect'
    redirect_path        => '',                  # (varchar) Ziel der Weiterleitung, falls 'redirect_type' gesetzt ist
    ssl                  => 'n',                 # (enum) SSL-Unterstützung: 'y', 'n' (Standard)
    ssl_letsencrypt      => 'n',                 # (enum) Let's Encrypt SSL-Zertifikat: 'y', 'n' (Standard)
    ssl_state            => '',                  # (varchar) SSL-Zertifikatsdetails, z.B. Bundesland
    ssl_locality         => '',                  # (varchar) SSL-Zertifikatsdetails, z.B. Stadt
    ssl_organisation     => '',                  # (varchar) SSL-Zertifikatsdetails, z.B. Organisation
    ssl_organisation_unit=> '',                  # (varchar) SSL-Zertifikatsdetails, z.B. Abteilung
    ssl_country          => '',                  # (varchar) SSL-Zertifikatsdetails, z.B. Land (2 Buchstaben)
    ssl_domain           => '',                  # (varchar) Domainname des SSL-Zertifikats
    ssl_request          => '',                  # (mediumtext) SSL-Zertifikatsanforderung
    ssl_key              => '',                  # (mediumtext) SSL-Zertifikatschlüssel
    ssl_cert             => '',                  # (mediumtext) SSL-Zertifikat
    ssl_bundle           => '',                  # (mediumtext) SSL-Zertifikats-Bundle
    ssl_action           => '',                  # (varchar) SSL-Aktion: 'show', 'save', 'create', 'delete'
    stats_password       => '',                  # (varchar) Passwort für Statistiken
    stats_type           => '',                  # (varchar) Typ der Statistiken: '' (Standard), 'goaccess'
    storage_time_log_files => 7,                 # (int) Aufbewahrungszeit für Protokolldateien in Tagen
    allow_override       => 'All',               # (varchar) 'AllowOverride'-Richtlinien für Apache, z.B. 'None', 'All'
    apache_directives    => '',                  # (mediumtext) Zusätzliche Apache-Direktiven
    php_open_basedir     => '/',                 # (mediumtext) PHP open_basedir-Einstellung
    custom_php_ini       => '',                  # (mediumtext) Benutzerdefinierte PHP.ini-Einstellungen
    pm                   => 'ondemand',          # (enum) PHP-FPM Prozessmanager: 'static', 'dynamic', 'ondemand' (Standard)
    pm_max_children      => 500,                 # (int) Max. Anzahl der PHP-FPM-Kinderprozesse, Standard 500
    pm_max_requests      => 0,                   # (int) Max. Anzahl der Anfragen pro PHP-FPM-Kinderprozess, 0 für unbegrenzt
    pm_process_idle_timeout => 5,                # (int) Leerlaufzeit in Sekunden, Standard 5
    custom_php_ini       => '',                  # (mediumtext) Benutzerdefinierte PHP.ini-Einstellungen
    backup_interval      => 'daily',             # (varchar) Intervall für Backups, z.B. 'daily', 'weekly'
    backup_copies        => 7,                   # (int) Anzahl der aufzubewahrenden Backups
    active               => 'y',                 # (enum) Aktivierung der Domain: 'y' (Standard), 'n'
    traffic_quota_lock   => 'n',                 # (enum) Sperre bei Erreichen des Verkehrskontingents: 'y', 'n' (Standard)
    http_port            => '80',                # (int) HTTP-Port, Standard 80
    https_port           => '443',               # (int) HTTPS-Port, Standard 443
    tideways_sample_rate => 25,                  # (int) Tideways-Probenahmerate in Prozent
};

# UserAgent initialisieren
my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 } );

# Login zur ISPConfig API
my $login_url = "$base_url?login";
my $login_payload = {
    username => $username,
    password => $password
};

my $response = $ua->post(
    $login_url,
    Content_Type => 'application/json',
    Content      => encode_json($login_payload)
);

if ($response->is_success) {
    my $response_data = decode_json($response->decoded_content);
    my $session_id = $response_data->{response};

    print "Login erfolgreich: Session-ID: $session_id\n";

    my $web_domain_payload = {
        session_id => $session_id,
        client_id  => $client_id,
        params     => $params,
    };

    my $add_web_domain_url = "$base_url?sites_web_domain_add";
    $response = $ua->post(
        $add_web_domain_url,
        Content_Type => 'application/json',
        Content      => encode_json($web_domain_payload)
    );

    if ($response->is_success) {
        $response_data = decode_json($response->decoded_content);

        if ($response_data->{response}) {
            print "Website-Domain erfolgreich hinzugefügt. ID: $response_data->{response}\n";
        } else {
            print "Fehler beim Hinzufügen der Website-Domain: "
                . ($response_data->{message} // 'Unbekannter Fehler')
                . "\nAntwort: " . encode_json($response_data) . "\n";
        }
    } else {
        print "HTTP-Fehler beim Hinzufügen der Website-Domain: "
            . $response->status_line . "\n"
            . "Antwort: " . $response->decoded_content . "\n";
    }

    my $logout_url = "$base_url?logout";
    my $logout_payload = { session_id => $session_id };

    $response = $ua->post(
        $logout_url,
        Content_Type => 'application/json',
        Content      => encode_json($logout_payload)
    );

    if ($response->is_success) {
        print "Logout erfolgreich.\n";
    } else {
        print "Fehler beim Logout: " . $response->status_line . "\n";
    }
} else {
    print "Login fehlgeschlagen: " . $response->status_line . "\n"
        . "Antwort: " . $response->decoded_content . "\n";
}
 
Zuletzt bearbeitet:

Strontium

Member
Python:
import requests
import json

# Disable SSL certificate verification
requests.packages.urllib3.disable_warnings()

# First create an ISPConfig remote user with ‘Sites Domain functions’!

# Configuration
base_url = 'https://192.168.0.14:8080/remote/json.php'
username = 'ispconfigremoteuser'
password = 'secretpassword'
client_id = 1
server_id = 1

# Parameters for creating the website
params = {
    'server_id': server_id,                # (int) ID of the server where the domain should be added
    'ip_address': '*',                     # (string) IP address for the domain, default '*'
    'domain': 'apitestdomain.com',         # (string) Domain name
    'type': 'vhost',                       # (string) Type of the domain: 'vhost', 'alias', 'vhostalias', 'subdomain', 'vhostsubdomain'
    'parent_domain_id': 0,                 # (int) ID of the parent domain if this is a subdomain
    'vhost_type': 'name',                  # (string) Type of the vhost: 'name'
    'hd_quota': 100000,                    # (int) Disk quota in MB, -1 for unlimited
    'traffic_quota': -1,                   # (int) Traffic quota in MB, -1 for unlimited
    'cgi': 'y',                            # (enum) CGI support: 'y' (default), 'n'
    'ssi': 'y',                            # (enum) SSI support: 'y' (default), 'n'
    'suexec': 'y',                         # (enum) SuExec support: 'y' (default), 'n'
    'errordocs': 1,                        # (int) Custom error documents: 1 (enabled), 0 (default)
    'is_subdomainwww': 1,                  # (int) 'www' as subdomain: 1 (enabled), 0 (disabled)
    'subdomain': 'none',                   # (enum) 'none' (default), 'www', '*'
    'php': 'php-fpm',                      # (enum) PHP support: 'no', 'fast-cgi', 'php-fpm' (default)
    'ruby': 'n',                           # (enum) Ruby support: 'y', 'n' (default)
    'redirect_type': '',                   # (string) Type of redirect, e.g., 'no', 'R', 'L', 'redirect'
    'redirect_path': '',                   # (string) Destination of redirect, if 'redirect_type' is set
    'ssl': 'n',                            # (enum) SSL support: 'y', 'n' (default)
    'ssl_letsencrypt': 'n',                # (enum) Let's Encrypt SSL certificate: 'y', 'n' (default)
    'ssl_state': '',                       # (string) SSL certificate details, e.g., state
    'ssl_locality': '',                    # (string) SSL certificate details, e.g., city
    'ssl_organisation': '',                # (string) SSL certificate details, e.g., organization
    'ssl_organisation_unit': '',           # (string) SSL certificate details, e.g., department
    'ssl_country': '',                     # (string) SSL certificate details, e.g., country (2-letter code)
    'ssl_domain': '',                      # (string) Domain name of the SSL certificate
    'ssl_request': '',                     # (string) SSL certificate request
    'ssl_key': '',                         # (string) SSL certificate key
    'ssl_cert': '',                        # (string) SSL certificate
    'ssl_bundle': '',                      # (string) SSL certificate bundle
    'ssl_action': '',                      # (string) SSL action: 'show', 'save', 'create', 'delete'
    'stats_password': '',                  # (string) Password for statistics
    'stats_type': '',                      # (string) Type of statistics: '' (default), 'goaccess'
    'storage_time_log_files': 7,           # (int) Retention time for log files in days
    'allow_override': 'All',               # (string) 'AllowOverride' directives for Apache, e.g., 'None', 'All'
    'apache_directives': '',               # (string) Additional Apache directives
    'php_open_basedir': '/',               # (string) PHP open_basedir setting
    'custom_php_ini': '',                  # (string) Custom PHP.ini settings
    'pm': 'ondemand',                      # (enum) PHP-FPM process manager: 'static', 'dynamic', 'ondemand' (default)
    'pm_max_children': 500,                # (int) Max number of PHP-FPM child processes, default 500
    'pm_max_requests': 0,                  # (int) Max number of requests per PHP-FPM child process, 0 for unlimited
    'pm_process_idle_timeout': 5,          # (int) Idle timeout in seconds, default 5
    'backup_interval': 'daily',            # (string) Backup interval, e.g., 'daily', 'weekly'
    'backup_copies': 7,                    # (int) Number of backup copies to retain
    'active': 'y',                         # (enum) Activation of the domain: 'y' (default), 'n'
    'traffic_quota_lock': 'n',             # (enum) Lock when traffic quota is reached: 'y', 'n' (default)
    'http_port': '80',                     # (int) HTTP port, default 80
    'https_port': '443',                   # (int) HTTPS port, default 443
    'tideways_sample_rate': 25,            # (int) Tideways sampling rate in percent
}

# Initialize the session
session = requests.Session()

# Login to ISPConfig API
login_url = f"{base_url}?login"
login_payload = {
    'username': username,
    'password': password
}

response = session.post(login_url, json=login_payload, verify=False)

if response.status_code == 200:
    response_data = response.json()
    session_id = response_data.get('response')

    if session_id:
        print(f"Login successful: Session ID: {session_id}")

        # Add the web domain
        web_domain_payload = {
            'session_id': session_id,
            'client_id': client_id,
            'params': params
        }

        add_web_domain_url = f"{base_url}?sites_web_domain_add"
        response = session.post(add_web_domain_url, json=web_domain_payload, verify=False)

        if response.status_code == 200:
            response_data = response.json()

            if response_data.get('response'):
                print(f"Website domain successfully added. ID: {response_data['response']}")
            else:
                print(f"Error adding website domain: {response_data.get('message', 'Unknown error')}")
                print(f"Response: {json.dumps(response_data)}")
        else:
            print(f"HTTP error adding website domain: {response.status_code}")
            print(f"Response: {response.text}")

        # Logout from ISPConfig API
        logout_url = f"{base_url}?logout"
        logout_payload = {'session_id': session_id}
        response = session.post(logout_url, json=logout_payload, verify=False)

        if response.status_code == 200:
            print("Logout successful.")
        else:
            print(f"Error logging out: {response.status_code}")
    else:
        print(f"Login failed: {response_data.get('message', 'Unknown error')}")
else:
    print(f"Login request failed: {response.status_code}")
    print(f"Response: {response.text}")
 

Strontium

Member
PHP:
<?php

// Disable SSL certificate verification
$context = stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
]);

// First create an ISPConfig remote user with ‘Sites Domain functions’!

// Configuration
$base_url = 'https://192.168.0.14:8080/remote/json.php';
$username = 'ispconfigremoteuser';
$password = 'secretpassword';
$client_id = 1;
$server_id = 1;

// Parameters for creating the website
$params = [
    'server_id'            => $server_id,               // (int) ID of the server where the domain will be hosted.
    'ip_address'           => '*',                      // (string) The IP address to bind the domain to. '*' means any IP.
    'domain'               => 'apitestdomain.com',      // (string) The domain name to be added.
    'type'                 => 'vhost',                  // (string) Type of domain: 'vhost' | 'alias' | 'vhostalias' | 'subdomain' | 'vhostsubdomain'.
    'parent_domain_id'     => 0,                        // (int) ID of the parent domain, applicable for subdomains or aliases.
    'vhost_type'           => 'name',                   // (string) Type of virtual host: 'name' or 'ip'.
    'hd_quota'             => 100000,                   // (int) Disk quota in MB. '-1' means unlimited.
    'traffic_quota'        => -1,                       // (int) Traffic quota in MB. '-1' means unlimited.
    'cgi'                  => 'y',                      // (enum) Enable CGI: 'y' (yes) | 'n' (no). Default is 'y'.
    'ssi'                  => 'y',                      // (enum) Enable SSI: 'y' (yes) | 'n' (no). Default is 'y'.
    'suexec'               => 'y',                      // (enum) Enable suEXEC: 'y' (yes) | 'n' (no). Default is 'y'.
    'errordocs'            => 1,                        // (int) Enable custom error documents. Default is '0'.
    'is_subdomainwww'      => 1,                        // (int) Add 'www.' as a subdomain automatically. Default is '1'.
    'subdomain'            => 'none',                   // (enum) Subdomain type: 'none' | 'www'. Default is 'none'.
    'php'                  => 'php-fpm',                // (string) PHP mode: 'no' | 'fast-cgi' | 'php-fpm'. Default is 'php-fpm'.
    'stats_type'           => 'webalizer',              // (string) Statistics tool: 'webalizer' or others. Default is 'webalizer'.
    'allow_override'       => 'All',                    // (string) AllowOverride directive in Apache. Default is 'All'.
    'pm'                   => 'ondemand',               // (string) PHP-FPM process manager: 'static' | 'dynamic' | 'ondemand'. Default is 'ondemand'.
    'pm_max_requests'      => 0,                        // (int) Max requests before a child process is restarted. Default is '0'.
    'pm_process_idle_timeout' => 10,                    // (int) Timeout in seconds before idle processes are terminated. Default is '10'.
    'active'               => 'y',                      // (enum) Domain active: 'y' (yes) | 'n' (no). Default is 'y'.
    'traffic_quota_lock'   => 'n',                      // (enum) Lock account if traffic quota is exceeded: 'y' (yes) | 'n' (no). Default is 'n'.
    'pm_max_children'      => 10,                       // (int) Maximum number of child processes in PHP-FPM. Default is '500'.
    'pm_start_servers'     => 2,                        // (int) Number of child processes created on startup. Default is '2'.
    'pm_min_spare_servers' => 1,                        // (int) Minimum number of spare child processes. Default is '1'.
    'pm_max_spare_servers' => 5,                        // (int) Maximum number of spare child processes. Default is '5'.
    'php_fpm_use_socket'   => 'y',                      // (enum) Use socket for PHP-FPM: 'y' (yes) | 'n' (no). Default is 'y'.
    'http_port'            => '80',                     // (int) HTTP port number. Default is '80'.
    'https_port'           => '443',                    // (int) HTTPS port number. Default is '443'.
];

// Initialize HTTP client
$options = [
    'http' => [
        'header'  => "Content-Type: application/json\r\n",
        'method'  => 'POST',
        'ignore_errors' => true,  // To capture error responses
        'content' => '',
        'timeout' => 30,
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
];

// Login to ISPConfig API
$login_payload = json_encode([
    'username' => $username,
    'password' => $password
]);

$options['http']['content'] = $login_payload;
$context = stream_context_create($options);
$response = file_get_contents("$base_url?login", false, $context);

if ($response === FALSE) {
    die("Login failed.\n");
}

$response_data = json_decode($response, true);
$session_id = $response_data['response'];

if ($session_id) {
    echo "Login successful: Session ID: $session_id\n";

    // Prepare the payload for adding the web domain
    $web_domain_payload = json_encode([
        'session_id' => $session_id,
        'client_id'  => $client_id,
        'params'     => $params,
    ]);

    // Set the payload for the domain add request
    $options['http']['content'] = $web_domain_payload;
    $context = stream_context_create($options);

    // Send the request to add the web domain
    $response = file_get_contents("$base_url?sites_web_domain_add", false, $context);
    $response_data = json_decode($response, true);

    if ($response_data['response']) {
        echo "Website domain successfully added. ID: " . $response_data['response'] . "\n";
    } else {
        echo "Error adding website domain: "
            . ($response_data['message'] ?? 'Unknown error')
            . "\nResponse: " . json_encode($response_data) . "\n";
    }

    // Logout from ISPConfig API
    $logout_payload = json_encode(['session_id' => $session_id]);
    $options['http']['content'] = $logout_payload;
    $context = stream_context_create($options);
    $response = file_get_contents("$base_url?logout", false, $context);

    if ($response !== FALSE) {
        echo "Logout successful.\n";
    } else {
        echo "Logout failed.\n";
    }
} else {
    echo "Login failed: " . ($response_data['message'] ?? 'Unknown error') . "\n";
}

?>
 
Zuletzt bearbeitet:

Strontium

Member
Rust

C-ähnlich:
# Cargo.toml

[package]
name = "sites_web_domain_add"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = { version = "0.12.5", features = ["json", "native-tls"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

C-ähnlich:
// src/main.rs

#![recursion_limit = "256"]

// sudo apt-get install libssl-dev
// First, create an ISPConfig remote user with ‘Sites Domain functions’!

use reqwest::Client;
use serde_json::json;
use std::collections::HashMap;
use std::error::Error;
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {

    // Configuration
    let base_url = "https://192.168.0.14:8080/remote/json.php";
    let username = "ispconfigremoteuser";
    let password = "secretpassword";
    let client_id = 1;
    let server_id = 1;
    let domain_name = "apitestdomain.com";  // Set the domain name here

    // Parameters for the website creation
    let params = json!({
        "server_id": server_id,               // (int) Server ID where the domain will be added
        "ip_address": "*",                    // (string) IP address of the domain, default '*'
        "domain": domain_name,                // (string) Domain name
        "type": "vhost",                      // (string) Type of domain: 'vhost', 'alias', 'vhostalias', 'subdomain', 'vhostsubdomain'
        "parent_domain_id": 0,                // (int) ID of the parent domain if it's a subdomain
        "vhost_type": "name",                 // (string) Vhost type: 'name'
        "hd_quota": 100000,                   // (bigint) Disk quota in MB, -1 for unlimited
        "traffic_quota": -1,                  // (bigint) Traffic quota in MB, -1 for unlimited
        "cgi": "y",                           // (enum) CGI support: 'y' (default), 'n'
        "ssi": "y",                           // (enum) SSI support: 'y' (default), 'n'
        "suexec": "y",                        // (enum) SuExec support: 'y' (default), 'n'
        "errordocs": 1,                       // (int) Custom error documents: 1 (enabled), 0 (default)
        "is_subdomainwww": 1,                 // (int) 'www' as subdomain, 1 (enabled), 0 (disabled)
        "subdomain": "none",                  // (enum) 'none' (default), 'www', '*'
        "php": "php-fpm",                     // (enum) PHP support: 'no', 'fast-cgi', 'php-fpm' (default)
        "ruby": "n",                          // (enum) Ruby support: 'y', 'n' (default)
        "redirect_type": "",                  // (string) Type of redirection, e.g., 'no', 'R', 'L', 'redirect'
        "redirect_path": "",                  // (string) Target of the redirection if 'redirect_type' is set
        "ssl": "n",                           // (enum) SSL support: 'y', 'n' (default)
        "ssl_letsencrypt": "n",               // (enum) Let's Encrypt SSL certificate: 'y', 'n' (default)
        "ssl_state": "",                      // (string) SSL certificate details, e.g., state
        "ssl_locality": "",                   // (string) SSL certificate details, e.g., locality
        "ssl_organisation": "",               // (string) SSL certificate details, e.g., organization
        "ssl_organisation_unit": "",          // (string) SSL certificate details, e.g., organizational unit
        "ssl_country": "",                    // (string) SSL certificate details, e.g., country (2 letters)
        "ssl_domain": "",                     // (string) SSL certificate domain name
        "ssl_request": "",                    // (text) SSL certificate request
        "ssl_key": "",                        // (text) SSL certificate key
        "ssl_cert": "",                       // (text) SSL certificate
        "ssl_bundle": "",                     // (text) SSL certificate bundle
        "ssl_action": "",                     // (string) SSL action: 'show', 'save', 'create', 'delete'
        "stats_password": "",                 // (string) Password for statistics
        "stats_type": "",                     // (string) Type of statistics: '' (default), 'goaccess'
        "storage_time_log_files": 7,          // (int) Log file retention time in days
        "allow_override": "All",              // (string) 'AllowOverride' directives for Apache, e.g., 'None', 'All'
        "apache_directives": "",              // (text) Additional Apache directives
        "php_open_basedir": "/",              // (text) PHP open_basedir setting
        "custom_php_ini": "",                 // (text) Custom PHP.ini settings
        "pm": "ondemand",                     // (enum) PHP-FPM process manager: 'static', 'dynamic', 'ondemand' (default)
        "pm_max_children": 500,               // (int) Max number of PHP-FPM child processes, default 500
        "pm_max_requests": 0,                 // (int) Max requests per PHP-FPM child process, 0 for unlimited
        "pm_process_idle_timeout": 5,         // (int) Idle process timeout in seconds, default 5
        "backup_interval": "daily",           // (string) Backup interval, e.g., 'daily', 'weekly'
        "backup_copies": 7,                   // (int) Number of backups to keep
        "active": "y",                        // (enum) Activate the domain: 'y' (default), 'n'
        "traffic_quota_lock": "n",            // (enum) Lock when traffic quota is reached: 'y', 'n' (default)
        "http_port": "80",                    // (int) HTTP port, default 80
        "https_port": "443",                  // (int) HTTPS port, default 443
        "tideways_sample_rate": 25            // (int) Tideways sampling rate in percent
    });

    // Client with disabled SSL verification (for development)
    let client = Client::builder()
        .danger_accept_invalid_certs(true)
        .build()?;

    // Login to ISPConfig API
    let login_response = client
        .post(format!("{base_url}?login"))
        .json(&json!({ "username": username, "password": password }))
        .send()
        .await?;

    if login_response.status().is_success() {
        let login_json: HashMap<String, serde_json::Value> = login_response.json().await?;
        let session_id = login_json["response"].as_str().unwrap_or_default();

        println!("Login successful: Session ID: {}", session_id);

        let add_web_domain_url = format!("{base_url}?sites_web_domain_add");

        let web_domain_payload = json!({
            "session_id": session_id,
            "client_id": client_id,
            "params": params
        });

        let domain_response = client
            .post(&add_web_domain_url)
            .json(&web_domain_payload)
            .send()
            .await?;

        if domain_response.status().is_success() {
            let response_json: HashMap<String, serde_json::Value> = domain_response.json().await?;
            if let Some(false) = response_json["response"].as_bool() {
                let error_message = response_json.get("message").unwrap_or(&serde_json::Value::String("Unknown error".to_string())).to_string();
                eprintln!("Failed to add website domain: {}", error_message);
                std::process::exit(1);
            } else {
                println!("Website domain successfully added: {}", domain_name);
            }
        } else {
            println!(
                "HTTP error when adding website domain: {}",
                domain_response.status()
            );
        }

        // Logout
        let logout_response = client
            .post(format!("{base_url}?logout"))
            .json(&json!({ "session_id": session_id }))
            .send()
            .await?;

        if logout_response.status().is_success() {
            println!("Logout successful.");
        } else {
            println!(
                "Error during logout: {}",
                logout_response.status()
            );
        }
    } else {
        println!(
            "Login failed: {}",
            login_response.status()
        );
    }

    Ok(())
}
 

Werbung

Top