{"id":506821,"date":"2025-08-08T05:45:45","date_gmt":"2025-08-08T05:45:45","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=506821"},"modified":"2025-08-08T05:45:45","modified_gmt":"2025-08-08T05:45:45","slug":"sincronizzare-lora-in-linux-usando-uno-script-shell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/sincronizzare-lora-in-linux-usando-uno-script-shell\/","title":{"rendered":"Sincronizzare l&#8217;ora in Linux usando uno script Shell"},"content":{"rendered":"<p>La sincronizzazione dell&#8217;ora \u00e8 un pilastro della moderna infrastruttura IT. Dal logging accurato alle comunicazioni sicure, passando per il coordinamento dei sistemi distribuiti, \u00e8 essenziale che l&#8217;ora del sistema sia coerente tra i server e gli <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/cose-un-dispositivo-endpoint-panoramica-per-professionisti\/\">endpoint<\/a>. Per i professionisti IT e i Managed Service Provider (MSP), disporre di un metodo affidabile e automatizzato per sincronizzare l&#8217;ora in Linux \u00e8 fondamentale. In questo post presentiamo uno script shell progettato per sincronizzare l&#8217;ora utilizzando <code>chronyd<\/code> o <code>systemd-timesyncd<\/code>, due servizi di network time protocol (NTP) ampiamente supportati in Linux.<\/p>\n<h2>Contesto<\/h2>\n<p>Molti ambienti IT, soprattutto quelli che si affidano a piattaforme di gestione e automazione centralizzate come NinjaOne, richiedono una rigorosa sincronizzazione dell&#8217;orario. Le correlazioni dei log, il versioning dei file, i token di autenticazione e le tracce di audit dipendono tutti da orologi di sistema precisi. Anche se i servizi NTP come <code>chronyd<\/code> e <code>systemd-timesyncd<\/code> spesso gestiscono questa attivit\u00e0 in background, una configurazione errata, un&#8217;interruzione del servizio o un&#8217;incoerenza dell&#8217;immagine del sistema possono impedire la sincronizzazione.<\/p>\n<p>Questo script shell affronta questi problemi rilevando automaticamente i servizi di sincronizzazione dell&#8217;ora disponibili, assicurandosi che siano configurati correttamente, avviandoli temporaneamente se necessario, sincronizzando l&#8217;ora e fornendo una diagnostica dettagliata. Gestisce inoltre i servizi in modo aggraziato, riportando i sistemi allo stato precedente se i servizi di sincronizzazione dell&#8217;orario sono stati inizialmente disabilitati.<\/p>\n<h2>Lo script per sincronizzare l&#8217;ora in Linux:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\">#!\/usr\/bin\/env bash\r\n#\r\n# Description: Synchronize the time on Linux using the system's network time server. Expects chrony or systemd-timesyncd to be installed and running.\r\n# By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https:\/\/www.ninjaone.com\/terms-of-use.\r\n# Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. \r\n# Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. \r\n# Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. \r\n# Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. \r\n# Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. \r\n# Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. \r\n# EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#\r\n# Minimum OS Architecture Supported: Debian 11 (Bullseye)+, Red Hat Enterprise Linux (RHEL) 8+\r\n#\r\n# Release Notes: Initial Release\r\n#\r\n\r\n# When run directly without testing, the \"__()\" function does nothing.\r\ntest || __() { :; }\r\n\r\ndie() {\r\n    local _ret=\"${2:-1}\"\r\n    echo \"$1\" &gt;&amp;2\r\n    exit \"${_ret}\"\r\n}\r\n\r\nfunction GetChronyConfigFile() {\r\n    local _configFile\r\n    # Check if there is a chrony config folder\r\n    if [[ -d \"\/etc\/chrony\" ]]; then\r\n        # Check if the config file exists\r\n        if [[ -f \"\/etc\/chrony\/chrony.conf\" ]]; then\r\n            _configFile=\"\/etc\/chrony\/chrony.conf\"\r\n        fi\r\n    fi\r\n    # Check if primary default config file exists, this takes precedence over the chrony folder\r\n    if [[ -f \"\/etc\/chrony.conf\" ]]; then\r\n        _configFile=\"\/etc\/chrony.conf\"\r\n    fi\r\n    # Get the system's default config file for chronyd\r\n    _chronySystemDefaultConfigFile=$(\r\n        # Get man page for chronyd\r\n        # Looking for a line containing this \"The compiled-in default value is \/etc\/chrony\/chrony.conf.\"\r\n        man chronyd |\r\n            # Get the default config file location\r\n            grep \/chrony.conf | grep default |\r\n            # Get the last item in the line\r\n            awk '{print $NF}' |\r\n            # Remove the trailing period\r\n            sed 's\/\\.$\/\/'\r\n    )\r\n    # Check if the config file exists\r\n    if [[ -f \"$_chronySystemDefaultConfigFile\" ]]; then\r\n        _configFile=\"$_chronySystemDefaultConfigFile\"\r\n    fi\r\n\r\n    # Validate that the config file exists\r\n    if [[ -n \"${_configFile}\" &amp;&amp; -f \"$_configFile\" ]]; then\r\n        echo \"$_configFile\"\r\n    else\r\n        echo \"[Error] No chrony config file found\"\r\n        exit 1\r\n    fi\r\n}\r\n\r\nfunction GetNtpPoolServers() {\r\n    local -a _configFiles\r\n    local -a _pools\r\n    local -a _servers\r\n    local -a _timedatectlConfigFiles\r\n    _timedatectlConfigFiles=(\r\n        # Last take precedence over previous ones\r\n        \"\/usr\/lib\/systemd\/timesyncd.conf.d\"\r\n        \"\/usr\/local\/lib\/systemd\/timesyncd.conf.d\"\r\n        \"\/run\/systemd\/timesyncd.conf.d\"\r\n        \"\/etc\/systemd\/timesyncd.conf.d\"\r\n        \"\/usr\/lib\/systemd\/timesyncd.conf\"\r\n        \"\/usr\/local\/lib\/systemd\/timesyncd.conf\"\r\n        \"\/run\/systemd\/timesyncd.conf\"\r\n        \"\/etc\/systemd\/timesyncd.conf\"\r\n    )\r\n    # Get the NTP pool servers for the specified region\r\n\r\n    echo \"[Info] Getting NTP pools and servers\"\r\n    if command -v chronyc &amp;&gt;\/dev\/null; then\r\n        # Get the NTP pool servers for chrony\r\n        if [[ -f \"${_chronyConfigFile}\" ]]; then\r\n            _pools+=$(grep -E \"^pool\" \"${_chronyConfigFile}\" | awk '{print $2}' | sort -u)\r\n            _servers+=$(grep -E \"^server\" \"${_chronyConfigFile}\" | awk '{print $2}' | sort -u)\r\n        fi\r\n    elif command -v timedatectl &amp;&gt;\/dev\/null; then\r\n        # Get the NTP pool servers for systemd-timesyncd\r\n        for configFile in \"${_timedatectlConfigFiles[@]}\"; do\r\n            if [[ -d \"$configFile\" ]]; then\r\n                # If the config file is a directory, check for .conf files inside it\r\n                for confFile in \"$configFile\"\/*.conf; do\r\n                    if [[ -f \"$confFile\" ]]; then\r\n                        # Append the contents of the .conf file to the list of config files\r\n                        _pools+=$(grep -E \"^NTP=\" \"$configFile\" | awk -F '=' '{print $2}' | sort -u)\r\n                        _pools+=$(grep -E \"^FallbackNTP=\" \"$configFile\" | awk -F '=' '{print $2}' | sort -u)\r\n                    fi\r\n                done\r\n            elif [[ -f \"$configFile\" ]]; then\r\n                _pools+=$(grep -E \"^NTP=\" \"$configFile\" | awk -F '=' '{print $2}' | sort -u)\r\n                _pools+=$(grep -E \"^FallbackNTP=\" \"$configFile\" | awk -F '=' '{print $2}' | sort -u)\r\n            fi\r\n        done\r\n    else\r\n        echo \"[Error] chronyc or timedatectl not found\"\r\n        exit 1\r\n    fi\r\n\r\n    # Return the list of NTP pools and servers\r\n    if [[ -n \"${_pools}\" ]]; then\r\n        echo \"[Info] NTP pools:\"\r\n        echo \"$_pools\"\r\n    fi\r\n    if [[ -n \"${_servers}\" ]]; then\r\n        echo \"[Info] NTP servers:\"\r\n        echo \"$_servers\"\r\n    fi\r\n    if [[ -z \"${_pools}\" &amp;&amp; -z \"${_servers}\" ]]; then\r\n        # If no pools or servers were found\r\n        echo \"[Info] Distribution's default NTP servers are being used.\"\r\n    fi\r\n}\r\n\r\nfunction GetNtpConfiguration() {\r\n\r\n    # Get the NTP configuration for the specified region\r\n\r\n    if command -v chronyc &amp;&gt;\/dev\/null; then\r\n        echo \"[Info] NTP configuration:\"\r\n        if ! [[ -f \"$_chronyConfigFile\" ]]; then\r\n            _chronyConfigFile=\"$(GetChronyConfigFile)\"\r\n        fi\r\n\r\n        # Get the NTP configuration for chrony\r\n        grep -E \"^server|^pool\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null\r\n        if [[ -f \"${_chronyConfigFile}\" ]]; then\r\n            grep -E \"^sourcedir\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null | awk '{print $2}' | while read -r _dir; do\r\n                if [[ -d \"$_dir\" ]]; then\r\n                    for confFile in \"$_dir\"\/*.conf; do\r\n                        # Check if the file exists before grepping\r\n                        if [[ -f \"$confFile\" ]]; then\r\n                            grep -E \"^server|^pool\" &lt;\"$confFile\" 2&gt;\/dev\/null\r\n                        fi\r\n                    done\r\n                fi\r\n            done\r\n            grep -E \"^confdir\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null | awk '{print $2}' | while read -r _dir; do\r\n                if [[ -d \"$_dir\" ]]; then\r\n                    for confFile in \"$_dir\"\/*.conf; do\r\n                        # Check if the file exists before grepping\r\n                        if [[ -f \"$confFile\" ]]; then\r\n                            grep -E \"^server|^pool\" &lt;\"$confFile\" 2&gt;\/dev\/null\r\n                        fi\r\n                    done\r\n                fi\r\n            done\r\n        fi\r\n    elif command -v timedatectl &amp;&gt;\/dev\/null; then\r\n        # Get the NTP configuration for systemd-timesyncd\r\n        if ((\"$(timedatectl --version | grep systemd | awk '{print $2}')\" &gt;= 239)); then # Try to get the NTP configuration\r\n            echo \"[Info] NTP configuration:\"\r\n            timedatectl show-timesync 2&gt;\/dev\/null\r\n        else\r\n            # If it fails then we are running and older version of systemd, then get the status\r\n            echo \"[Warn] systemd version is older than 239, show-timesync is not available.\"\r\n        fi\r\n    else\r\n        echo \"[Error] No NTP configuration found.\"\r\n        exit 1\r\n    fi\r\n}\r\n\r\nfunction IsChronySecurityConfigured() {\r\n    # Check if the keyfile is set in chrony.conf\r\n    if grep -q \"^keyfile\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null; then\r\n        # Check if commandkey is set in chrony.conf\r\n        if grep -q \"^commandkey\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null; then\r\n            echo \"[Info] Keyfile and commandkey are set in ${_chronyConfigFile}\"\r\n            _id=$(grep \"^keyfile\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null | awk '{print $2}')\r\n            _keyfile=$(grep \"^commandkey\" \"${_chronyConfigFile}\" 2&gt;\/dev\/null | awk '{print $2}')\r\n            # Check if the keyfile exists\r\n            if [[ -f \"$_keyfile\" ]]; then\r\n                # Check if commandkey exists in keyfile\r\n                if grep -q \"^$_id\" \"$_keyfile\"; then\r\n                    # Keyfile exists and commandkey is set\r\n                    return 0\r\n                else\r\n                    # Keyfile exists but commandkey is not set\r\n                    echo \"[Error] Keyfile $_keyfile exists but commandkey $_id is not set in it\"\r\n                    return 1\r\n                fi\r\n            else\r\n                # Keyfile does not exist\r\n                echo \"[Error] Keyfile $_keyfile does not exist\"\r\n                return 1\r\n            fi\r\n        else\r\n            # Keyfile is set but commandkey is not set\r\n            return 1\r\n        fi\r\n    else\r\n        # Keyfile is not set\r\n        return 1\r\n    fi\r\n}\r\n\r\n__ begin __\r\n\r\n# Check if the script is being run as root. If not, exit with an error message.\r\nif [[ $(id -u) -ne 0 ]]; then\r\n    die \"[Error] This script must be run with root permissions. Try running it with sudo or as the system\/root user.\" 1\r\nfi\r\n\r\n_is_enabled=0\r\n_is_active=0\r\n\r\n# Check if time synchronization services are installed\r\nif systemctl list-unit-files | grep -q -E \"(systemd-timesyncd|chronyd).service\"; then\r\n    echo \"[Info] Time synchronization service(s) found:\"\r\n    # Check if systemd-timesyncd or chronyd is running\r\n    while read -r service; do                                          # Read each service name\r\n        if systemctl is-enabled --quiet \"${service}\" 2&gt;\/dev\/null; then # Check if the service is enabled\r\n            echo \"[Info] ${service} is enabled\"\r\n            _is_enabled=1\r\n        else\r\n            echo \"[Info] ${service} is not enabled\"\r\n        fi\r\n        if systemctl is-active --quiet \"${service}\" 2&gt;\/dev\/null; then # Check if the service is active\/running\r\n            echo \"[Info] ${service} is running\"\r\n            _is_active=1\r\n        else\r\n            echo \"[Info] ${service} is not running\"\r\n        fi\r\n    done &lt; &lt;(\r\n        systemctl list-unit-files |                         # List all unit files\r\n            grep -E \"(systemd-timesyncd|chronyd).service\" | # Filter for systemd-timesyncd or chronyd\r\n            awk '{print $1}'                                # Get the first column (service name)\r\n    )\r\n    _service_name=$(systemctl list-unit-files | grep -E \"(systemd-timesyncd|chronyd).service\" | awk '{print $1}')\r\n    if [[ -z \"${_service_name}\" ]] &amp;&amp; [[ $_is_enabled -eq 0 ]] &amp;&amp; [[ \"${_is_active}\" -eq 0 ]]; then\r\n        die \"[Error] No time synchronization service found. Please install systemd-timesyncd, or chrony.\" 1\r\n    fi\r\n    if [[ \"${_is_active}\" -eq 0 ]]; then\r\n        echo \"[Info] Time synchronization service is not running. Will start it now, sync it, and stop it after.\"\r\n        # Start the service\r\n        if [[ \"${_service_name}\" == *\"chronyd\"* ]]; then\r\n            # If chronyd is available, start it as it takes precedence over systemd-timesyncd\r\n            # Start chronyd\r\n            echo \"[Info] Starting time synchronization service: chronyd\"\r\n            systemctl start chronyd.service 2&gt;\/dev\/null || die \"[Error] Failed to start chronyd service\" 1\r\n            sleep 2\r\n        elif [[ \"${_service_name}\" == *\"systemd-timesyncd\"* ]]; then\r\n            # chronyd is not available, so we will use systemd-timesyncd\r\n            # Start systemd-timesyncd\r\n            echo \"[Info] Starting time synchronization service: systemd-timesyncd\"\r\n            systemctl start systemd-timesyncd.service 2&gt;\/dev\/null || die \"[Error] Failed to start systemd-timesyncd service\" 1\r\n            sleep 2\r\n        else\r\n            # If neither chronyd nor systemd-timesyncd is available, exit with an error\r\n            die \"[Error] No time synchronization service found. Please install systemd-timesyncd, or chrony.\" 1\r\n        fi\r\n    fi\r\nelse\r\n    die \"[Error] No time synchronization service found. Please install systemd-timesyncd, or chrony.\" 1\r\nfi\r\n\r\n_shouldError=0\r\n\r\n# Sync time now\r\necho \"[Info] Syncing time now\"\r\nif command -v chronyc &amp;&gt;\/dev\/null; then\r\n    # Check if keyfile is set in chrony.conf\r\n    if IsChronySecurityConfigured; then\r\n        # Use chronyc to sync time\r\n        echo \"[Info] Syncing time using chronyc with keyfile in ${_chronyConfigFile}\"\r\n        if [[ \"$(chronyc -a makestep 2&gt;\/dev\/null)\" == *\"OK\"* ]]; then\r\n            echo \"[Info] Time syncing\"\r\n        else\r\n            echo \"[Error] Failed to sync time using chronyc\"\r\n            _shouldError=1\r\n        fi\r\n    else\r\n        # Sync time using chronyc\r\n        echo \"[Info] Syncing time using chronyc\"\r\n        if [[ \"$(chronyc makestep 2&gt;\/dev\/null)\" == *\"OK\"* ]]; then\r\n            echo \"[Info] Time syncing\"\r\n        else\r\n            echo \"[Error] Failed to sync time using chronyc\"\r\n            _shouldError=1\r\n        fi\r\n    fi\r\n\r\n    # Verify that time is synced if we had no errors\r\n    if ((_shouldError == 0)); then\r\n        # Sleep for 5 seconds to allow some time to sync after restarting chronyd\r\n        sleep 5\r\n\r\n        # Check if time is synced with chronyc tracking\r\n        case $(chronyc tracking 2&gt;\/dev\/null | grep \"Leap status\") in\r\n        *\"Leap Second\"* | *\"Normal\"*)\r\n            # If the leap status is \"Leap Second\" or \"Normal\", then time is synced\r\n            echo \"[Info] Time synced successfully\"\r\n            ;;\r\n        *\"Insert second\"*)\r\n            # If the leap status is \"Insert second\", then time is being synced\r\n            echo \"[Info] Chrony is in the process of inserting a second and will be synced over time to prevent time jumps.\"\r\n            ;;\r\n        *\"Delete second\"*)\r\n            # If the leap status is \"Delete second\", then time is being synced\r\n            echo \"[Info] Chrony is in the process of deleting a second and will be synced over time to prevent time jumps.\"\r\n            ;;\r\n        *\"Not synchronized\"*)\r\n            # If the leap status is \"Not synchronized\", then time is not synced\r\n            echo \"[Error] Chrony is not synchronized.\"\r\n            _shouldError=1\r\n            ;;\r\n        *\"Unknown\"*)\r\n            # If the leap status is \"Unknown\", then time is not synced\r\n            echo \"[Error] Unknown status from chronyc tracking.\"\r\n            _shouldError=1\r\n            ;;\r\n        *)\r\n            # If the leap status is not recognized, then time is not synced\r\n            echo \"[Error] Failed to get sync status from chronyc\"\r\n            _shouldError=1\r\n            ;;\r\n        esac\r\n\r\n        # Stop chronyd if it was not running before\r\n        if ((_is_active == 0)); then\r\n            sleep 5\r\n            # Get the service name\r\n            _service_name=$(systemctl list-unit-files | grep -E \"chronyd.service\" | awk '{print $1}')\r\n            echo \"[Info] Stopping time synchronization service: ${_service_name}\"\r\n            # Stop the service\r\n            systemctl stop \"$_service_name\" 2&gt;\/dev\/null\r\n        fi\r\n    fi\r\nelif command -v timedatectl &amp;&gt;\/dev\/null; then\r\n    # Sync time using timedatectl\r\n    echo \"[Info] Syncing time using timedatectl\"\r\n    # Restart systemd-timesyncd to force a sync\r\n    if systemctl restart systemd-timesyncd.service 2&gt;\/dev\/null; then\r\n        if timedatectl status 2&gt;\/dev\/null | grep \"synchronized\" | grep -q \"yes\"; then\r\n            echo \"[Info] Time synced successfully\"\r\n        else\r\n            echo \"[Error] Failed to sync time using timedatectl\"\r\n            _shouldError=1\r\n        fi\r\n    else\r\n        echo \"[Error] Failed to sync time using timedatectl\"\r\n        _shouldError=1\r\n    fi\r\n\r\n    # Stop systemd-timesyncd if it was not running before\r\n    if ((_is_active == 0)); then\r\n        sleep 5\r\n        # Get the service name\r\n        _service_name=$(systemctl list-unit-files | grep -E \"systemd-timesyncd.service\" | awk '{print $1}')\r\n        echo \"[Info] Stopping time synchronization service: ${_service_name}\"\r\n        # Stop the service\r\n        systemctl stop \"$_service_name\" 2&gt;\/dev\/null\r\n    fi\r\nelse\r\n    echo \"[Error] No time synchronization service found. Please install systemd-timesyncd, or chrony.\"\r\n    exit 1\r\nfi\r\n\r\necho \"\"\r\n\r\nGetNtpConfiguration\r\nGetNtpPoolServers\r\n\r\nif ((_shouldError == 1)); then\r\n    exit 1\r\nfi\r\n<\/pre>\n<p>&nbsp;<\/p>\n\n<h2>Analisi dettagliata dello script per sincronizzare l&#8217;ora in Linux<\/h2>\n<p>Questo script per sincronizzare l&#8217;ora in Linux \u00e8 strutturato in pi\u00f9 funzioni e sezioni per garantire il controllo modulare e la chiarezza. Ecco una panoramica dei suoi componenti principali:<\/p>\n<h3>1. Controlli precedenti all&#8217;azione vera e propria<\/h3>\n<ul>\n<li><strong>Controllo dei permessi di root<\/strong><strong><br \/>\n<\/strong>Assicurati che lo script per sincronizzare l&#8217;ora in Linux venga eseguito come <code>root<\/code>, poich\u00e9 il controllo dell&#8217;ora e dei servizi richiede privilegi elevati.<\/li>\n<li><strong>Rilevamento del servizio<\/strong><strong><br \/>\n<\/strong>Cerca <code>chronyd<\/code> o <code>systemd-timesyncd<\/code>. Se nessuno dei due \u00e8 installato, lo script per sincronizzare l&#8217;ora in Linux terminer\u00e0 con un chiaro messaggio di errore.<\/li>\n<\/ul>\n<h3>2. Controllo e sincronizzazione del servizio<\/h3>\n<ul>\n<li><strong>Valutazione dello stato del servizio<\/strong><strong><br \/>\n<\/strong>Determina se ogni servizio \u00e8 abilitato e\/o in esecuzione. Se un servizio non \u00e8 in esecuzione, lo script per sincronizzare l&#8217;ora in Linux avvier\u00e0 temporaneamente quello appropriato.<\/li>\n<li><strong>Sincronizzazione dell&#8217;ora<\/strong>\n<ul>\n<li>Se si utilizza <code>cronyc<\/code>: Emette il comando <code>makestep<\/code> per sincronizzare immediatamente l&#8217;ora.<\/li>\n<li>Se si usa <code>timedatectl<\/code>: Riavvia <code>systemd-timesyncd<\/code> e controlla lo stato di sincronizzazione.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Ripristino del servizio<\/strong><strong><br \/>\n<\/strong>Se un servizio era inizialmente inattivo, lo script per sincronizzare l&#8217;ora in Linux lo arresta nuovamente dopo la sincronizzazione.<\/li>\n<\/ul>\n<h3>3. Ispezione della configurazione<\/h3>\n<ul>\n<li><strong><code>GetChronyConfigFile()<\/code><\/strong>: Individua il file di configurazione chrony in base alle convenzioni di sistema o alle impostazioni predefinite delle pagine man.<\/li>\n<li><strong><code>GetNtpPoolServers()<\/code><\/strong>: Raccoglie i pool NTP e le configurazioni dei server dai file di configurazione <code>chronyd<\/code> o <code>timesyncd<\/code>.<\/li>\n<li><strong><code>GetNtpConfiguration()<\/code><\/strong>: Mostra tutte le configurazioni di server, pool ed eventualmente sorgenti per aiutare a convalidare le impostazioni NTP.<\/li>\n<li><strong><code>IsChronySecurityConfigured()<\/code><\/strong>: Verifica che <code>chronyd<\/code> abbia parametri di sicurezza come <code>keyfile<\/code> e <code>commandkey<\/code> impostati correttamente.<\/li>\n<\/ul>\n<h2>Casi d&#8217;uso potenziali<\/h2>\n<h3>Caso di studio: Patch management da remoto<\/h3>\n<p>Un MSP gestisce sistemi Linux in diversi fusi orari. Una recente patch distribuita tramite NinjaOne riporta timestamp di installazione incoerenti. L&#8217;amministratore esegue questo script come fase di pre-controllo in un criterio NinjaOne. Lo script per sincronizzare l&#8217;ora in Linux assicura che tutti i sistemi si sincronizzino con lo stesso pool NTP prima dell&#8217;inizio del processo di patching. Di conseguenza, i log si allineeranno correttamente e i report che ne risultano saranno accurati.<\/p>\n<h2>Confronti<\/h2>\n<table>\n<tbody>\n<tr>\n<td><strong>Metodo<\/strong><\/td>\n<td><strong>Vantaggi<\/strong><\/td>\n<td><strong>Limitazioni<\/strong><\/td>\n<\/tr>\n<tr>\n<td><code>ntpdate<\/code> (legacy)<\/td>\n<td>Veloce, autonomo<\/td>\n<td>Deprecato, inaffidabile<\/td>\n<\/tr>\n<tr>\n<td><code>chronyd\/systemd-timesyncd<\/code><\/td>\n<td>Moderno, sicuro, persistente<\/td>\n<td>Richiede una configurazione adeguata<\/td>\n<\/tr>\n<tr>\n<td><strong>Questo script<\/strong><\/td>\n<td>Rilevamento, convalida e controlli di sicurezza automatizzati<\/td>\n<td>\u00c8 necessario un accesso root iniziale<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>A differenza dei comandi ad hoc o degli strumenti tradizionali, questo script per sincronizzare l&#8217;ora in Linux fornisce un metodo strutturato, consapevole degli errori e indipendente dai servizi, adatto alla distribuzione automatizzata.<\/p>\n<h2>Domande frequenti<\/h2>\n<p><strong>D: Cosa succede se n\u00e9 <\/strong><strong><code>chronyd<\/code><\/strong><strong> n\u00e9 <\/strong><strong><code>systemd-timesyncd<\/code><\/strong><strong> sono installati?<\/strong><strong><br \/>\n<\/strong>R: Lo script per sincronizzare l&#8217;ora in Linux si arresta e consiglia all&#8217;utente di installare uno dei due servizi.<\/p>\n<p><strong>D: Questo script pu\u00f2 essere programmato tramite cron o NinjaOne?<\/strong><strong><br \/>\n<\/strong>R: S\u00ec, \u00e8 pienamente compatibile con le piattaforme di automazione e i cron job.<\/p>\n<p><strong>D: Lo script interferir\u00e0 con la mia configurazione di sincronizzazione dell&#8217;ora esistente?<\/strong><strong><br \/>\n<\/strong>R: No. Se un servizio di sincronizzazione dell&#8217;orario era inattivo prima dell&#8217;esecuzione dello script per sincronizzare l&#8217;ora in Linux, verr\u00e0 nuovamente arrestato dopo la sincronizzazione.<\/p>\n<p><strong>D: \u00c8 sicuro eseguire lo script per sincronizzare l&#8217;ora in Linux sui server di produzione?<\/strong><strong><br \/>\n<\/strong>R: S\u00ec, a patto che il riavvio del servizio non influisca sulle applicazioni dipendenti. Ti consigliamo di eseguire i test in diverse fasi di distribuzione, e prima di tutto in ambiente di test.<\/p>\n<h2>Implicazioni<\/h2>\n<p>Una sincronizzazione dell&#8217;orario non eseguita alla perfezione pu\u00f2 causare una serie di problemi: login falliti a causa della mancata corrispondenza dei token, <a href=\"https:\/\/www.ninjaone.com\/it-hub\/endpoint-security\/what-is-data-corruption\/\">log corrotti<\/a> e repliche interrotte. Convalidando i file di configurazione, controllando la sicurezza dei servizi e permettendo di avere log facili da controllare in fase di audit, questo script migliora l&#8217;affidabilit\u00e0 e la sicurezza dell&#8217;infrastruttura. \u00c8 particolarmente importante per i sistemi che si occupano di gestione delle identit\u00e0, di comunicazioni sicure e di ambienti che richiedono conformit\u00e0.<\/p>\n<h2>Raccomandazioni<\/h2>\n<ul>\n<li><strong>Testa prima della distribuzione<\/strong>: Esegui sempre lo script per sincronizzare l&#8217;ora in Linux in un ambiente di test.<\/li>\n<li><strong>Utilizza lo script insieme a uno strumento di monitoraggio<\/strong>: Utilizza NinjaOne o strumenti simili per monitorare lo stato del servizio dopo la distribuzione.<\/li>\n<li><strong>Includi lo script nell&#8217;immagine di sistema di base<\/strong>: Aggiungi questo script per sincronizzare l&#8217;ora in Linux come parte della configurazione post-installazione per evitare problemi futuri.<\/li>\n<li><strong>Registra l&#8217;output<\/strong>: Reindirizza l&#8217;output dello script per sincronizzare l&#8217;ora in Linux a un file di log per poterlo verificare (<code>.\/sync-time.sh &gt;&gt; \/var\/log\/time-sync.log<\/code>).<\/li>\n<\/ul>\n<h2>Considerazioni finali<\/h2>\n<p>La sincronizzazione dell&#8217;ora \u00e8 fondamentale per l&#8217;integrit\u00e0 operativa a tutti i livelli dell&#8217;IT. Questo script offre un modo resiliente, portatile e conforme agli standard per sincronizzare l&#8217;ora su Linux utilizzando lo scripting shell. Integrato con piattaforme come NinjaOne, questo script consente ai professionisti IT e agli MSP di mantenere l&#8217;uniformit\u00e0 all&#8217;interno del proprio parco macchine senza alcuno sforzo, migliorando la capacit\u00e0 di essere pronti per eventuali audit, l&#8217;accuratezza dei dati e l&#8217;affidabilit\u00e0 del sistema.<\/p>\n<p>Per coloro che vogliono sincronizzare l&#8217;ora in Linux utilizzando lo scripting shell, questo strumento \u00e8 affidabile e facile da automatizzare. Integrandolo nei processi del ciclo di vita, puoi garantire l&#8217;impostazione di un&#8217;orario coerente e sicura in tutta l&#8217;infrastruttura.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4211],"use_cases":[4269],"class_list":["post-506821","script_hub","type-script_hub","status-publish","hentry","script_hub_category-linux"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/506821","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=506821"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=506821"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=506821"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=506821"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}