Archive for the ‘Linux’ Category

Howto Verify an SSL certificate and it private key do match

Monday, March 17th, 2025

Howto Verify an SSL certificate and it's private key do match ?

ssl-verify-pem-and-key-certificate-howto

 

In this article I'll show you how can you verify SSL generated certificate match with its private key. This is mostly useful as sometimes installing signed SSL certfificates might mismatch the key and the result is an SSL mismatch that prevents the supposed encryption of the service from end user to the service to work as expected.
 
I assume you already have properly issued and signed SSL certificate and the private key you used to issue the certificate as well as the entire certificate chain CA and root CA, as well as the certificate.

Requirements

You must have the following item :

  • the signed SSL certificate
  • the certificate's private key
  • the entire certification chain (intermediate CA and root CA)

1. Procedure to verify certificate .crt and .key file match

The following procedures can be used to ensure the given certificate/private key are valid.

Private key verification

  • compute the private key modulus

 

$ openssl rsa -in  certificate.key -modulus -noout | openssl md5

(stdin)= e5220727Acc5396139823018773d55db

 

  • compute the certificate modulus

 

$ openssl x509 – in   certificate.crt -modulus -noout | openssl md5 (stdin)= e5220727Acc5396139823018773d55db

 

  • the private key and certificate modulus md5 must match


How to verify Private key verification (one liner command)

The following command should return 'OK'

 

$ [[  "$(openssl rsa -in your_company_private_key.key -modulus -noout | openssl md5)"   ==  "$(openssl x509 -in and_your_company_private_key.crt -modulus -noout | openssl md5)"   ]] && echo OK || echo NOK

 

2. CA (Certificate Authority)  chain verification

Execute the following command, The certificate.ca should contains the entire CA chain (intermediate CA + root CA)

 

$ openssl verify -CAfile certificate_file.ca certificate.crt: OK

 

3. Expiry date verification of SSL certificate

 

$ openssl x509 – in   certificate_file.crt -noout -startdate -enddate

 

4. Verify the expiry date of a running web service online or in private net

 

$ openssl s_client -connect your-remote-service.com:443 2> /dev/null  | openssl x509 -noout -startdate -enddate

notBefore=Oct 5 00:15:00 2024 GMT
notAfter=Oct 18 23:59:59 2026 GMT

 

If the service provide several certificate with SNI you should use this command to get back the good certificate. You have to set the subject certificate you want to get back

 

$ openssl s_client -connect www.your-remote-service.com:443 -servername srv.your-remote-service.com 2> /dev/null

| openssl x509 -noout -startdate -enddate

notBefore=Oct 5 00:15:00 2024 GMT
notAfter=Oct 18 23:59:59 2026 GMT

 

Sum up what learned ?

In this short article we learned how to verify .crt and and .key file does match, how to do a chain verification of SSL cert, how to check the expire date of a certificate, as well as how to use the openssl command to verify whether installed certificate on a web service is set and working.

How to Deploy a Docker Container with Apache on Debian Linux and assign container static IP address

Friday, February 14th, 2025

deploy-docker-container-with-static-ip-on-debian-linux-howto-logo

Deploying a Docker container with Apache on Debian Linux is an efficient way to manage web servers in isolated environments. Docker provides a convenient way to package and run applications, and when combined with Apache, it can be used for hosting websites or web applications. In this guide, we’ll walk through the necessary steps to set up and run an Apache web server inside a Docker container on a Debian Linux machine.

Prerequisites

Before starting, ensure that you have the following prerequisites in place:

  • A Debian-based Linux system (e.g., Debian 10, Debian 11).
  • Docker installed on your system. If you don’t have Docker installed, follow the installation steps below.
  • Basic knowledge of Linux commands and Docker concepts.

Step 1: Install Docker on Debian

First, you need to install Docker if it is not already installed on your Debian machine. Here’s how to install Docker on Debian:

  1. Update the package database:
     

    # apt update

  2. Install the required dependencies:

    apt install apt-transport-https ca-certificates curl gnupg lsb-release

  3. Add Docker’s official GPG key:

    # curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

  4. Set up the stable Docker repository:
     

    # echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] \
    https://download.docker.com/linux/debian $(lsb_release -cs) stable" \
    | tee /etc/apt/sources.list.d/docker.list > /dev/null 
    

     

  5. Install Docker Engine:
     

    # apt update sudo apt install docker-ce docker-ce-cli containerd.io

     

  6. Start Docker and enable it to run on boot:
     

    systemctl start docker
    # systemctl enable docker

  7. Verify Docker installation:
     

    # docker --version

    This should display the installed Docker version, confirming that Docker is installed successfully.
     

Step 2: Pull Apache Docker Image or whatever docker image you want to have installed

Now that Docker is set up, you need to pull the official Apache image from Docker Hub. The Apache image is maintained by the Docker team and comes pre-configured for running Apache in a container.
 

  1. Pull the Apache HTTP Server image:

    # docker pull httpd

    This will download the official Apache HTTP server image ( httpd ) from Docker Hub.

Step 3: Run Apache Container

Once the Apache image is pulled, you can start a Docker container running Apache.

  1. Run the Docker container:

    # docker run -d --name apache-container -p 80:80 httpd

    Here’s what the options mean:

    • -d : Runs the container in detached mode (in the background).
    • --name apache-container : Names the container apache-container .
    • -p 80:80 : Maps port 80 on the host to port 80 in the container (so you can access the Apache web server through port 80).
    • httpd : The name of the image you want to run (the Apache HTTP server).
  2. Verify the container is running:

    # docker ps

    This will show a list of running containers. You should see the apache-container running.

  3. Test the Apache server:

    Open a web browser and go to http://<your-server-ip> . You should see the default Apache welcome page, indicating that Apache is running successfully in the Docker container.

Step 4: Customize Apache Configuration (Optional)

You may want to customize the Apache configuration or serve your own website inside the container. Here’s how to do it:

 

. Run the Apache Docker Container with a Specific IP Address

To bind the container to a specific IP address, use the --add-host or --publish flag while running the container.

  • If you want to bind Apache to a specific IP address on the host (for example, 192.168.1.100 ), use the --publish option:

# docker run -d --name apache-container -p 192.168.1.100:80:80 apache-container


This command tells Docker to bind port 80 in the container to port 80 on the host's IP address 192.168.1.100 . Replace 192.168.1.100 with the desired IP address of your system.

  1. Create a directory for your custom website:

    # mkdir -p /home/user/my-website

  2. Add an index.html file or whatever PHP / Perl whatever files will be served:

    Create a simple HTML file in the directory:
     

    # echo '<html><body><h1>Hello, Apache on Docker!</h1></body></html>' > /home/user/my-website/index.html

  3. Stop the running Apache container:

    # docker stop apache-container

  4. Remove the stopped container:

    # docker rm apache-container

  5. Run a new container with your custom website:

    Now, you can mount your custom directory into the container as a volume:

    # docker run -d --name apache-container -p 80:80 -v /home/user/my-website:/usr/local/apache2/htdocs/ httpd

    The -v option mounts the local directory /home/user/my-website to the Apache server’s default document root directory ( /usr/local/apache2/htdocs/ ).

  6. Verify the custom website:

    Reload the web page in your browser. Now, you should see the "Hello, Apache on Docker!" message, confirming that your custom website is being served from the Docker container.

Step 5: Manage Docker Containers

You can manage the running Apache container with the following commands:

  • Stop the container:

    # docker stop apache-container

  • Start the container:

    # docker start apache-container

  • Remove the container (if needed):

    # docker rm apache-container

  • View logs for troubleshooting:

    # docker logs apache-container

Step 6: Automating Docker Container Deployment (Optional step)

If you want the Apache container to restart automatically after a system reboot, you can add the --restart flag to the docker run command.

For example, to make the container restart automatically unless it is manually stopped, use:
 

# docker run -d --name apache-container -p 80:80 --restart unless-stopped \
-v /home/user/my-website:/usr/local/apache2/htdocs/ httpd 

Conclusion

By following these steps, you can easily deploy Apache inside a Docker container on a Debian Linux machine. Docker allows you to run your Apache web server or whatever docker app you need to have in a lightweight and isolated environment, which is useful development, testing, and production environments. You can further customize this setup by adding additional configurations, integrating with databases, or automating deployments with Docker Compose or Kubernetes.

Enjoy your new Dockerized Apache setup!

How to prevent /etc/resolv.conf to overwrite on every Linux boot. Make /etc/resolv.conf DNS records permanent forever

Tuesday, February 4th, 2025

how-to-make-prevent-etc-resolv.conf-to-ovewrite-on-every-linux-boot-make-etc-resolv-conf-permanent-forever

Have you recently been seriously bothered, after one of the updates from older to newer Debian / Ubuntu / CentOS or other Linux distributions by the fact /etc/resolv.conf has become a dynamic file that pretty much in the spirit of cloud technologies is being regenerated and ovewritten on each and every system (server) OS update /  reboot and due to that you start getting some wrong inappropriate DNS records /etc/resolv.conf causing you harm to the server infrastructure?

During my set of server infra i have faced that odditty for some years now and i guess every system administrator out there has suffered at a point by having to migrate an older Linux release to a newer one, where something gets messed up with DNS resolving due to that Linux OS new feature of /etc/resolv.conf not being really static any more.

The Dynamic resolv.conf file for glibc resolver is often generated used to be regenerated by resolvconf command and consequentially can be tampered by dhcpd resolved systemd service as well perhaps other mechanism depending on how the different Linux distribution architects make it to behave …

There are more than one ways to stop the annoying /etc/resolv.conf ovewritten behavior

1. Using dhcpd to stop /etc/resolv.conf being overwritten

Using dhcpd either a small null up script can be used or a separate hook script.

The null script would look like this

root@pcfreak:/root# vim /etc/dhcp/dhclient-enter-hooks.d/nodnsupdate

#!/bin/sh
make_resolv_conf() {
    :
}

root@pcfreak:/root# chmod +x /etc/dhcp/dhclient-enter-hooks.d/nodnsupdate

 

This script overrides an internal function called make_resolv_conf() that would normally overwrite resolv.conf and instead does nothing.

On old Ubuntu s and Debian versions this should work.


Alternative method is to use a small hook dhcp script like this:

root@pcfreak:/root# echo 'make_resolv_conf() { :; }' > /etc/dhcp/dhclient-enter-hooks.d/leave_my_resolv_conf_alone
chmod 755 /etc/dhcp/dhclient-enter-hooks.d/leave_my_resolv_conf_alone


Next boot when dhclient runs onreboot or when you manually run sudo ifdown -a ; sudo ifup -a , 
it loads this script nodnsupdate or the hook script and hopefully your manually configured values of /etc/resolv.conf would not mess up your file anymore.

2. Use a chattr and set immutable flag attribute to /etc/resolv.conf to prevent re-boot to ovewrite it

Anyways the universal and simple way "hack" to prevent /etc/resolv.conf many prefer to use instead of dhcp (especially as not everyone is running a dhcp on a server) , to overwrite is to delete the file and make it immutable with chattr (assuming chattr is supported by the filesystem i.e. EXT3 / EXT4 / XFS , you use on the Linux.).

You might need to check the filesystem type, before using chattr.

root@pcfreak:/root# blkid  | awk '{print $1 ,$3, $4}'
/dev/xvda1: TYPE="xfs"
/dev/xvda2: TYPE="LVM2_member"
/dev/mapper/centos-root: TYPE="xfs"
/dev/mapper/centos-swap: TYPE="swap"
/dev/loop0:
/dev/loop1:
/dev/loop2:

 

Normally EXT fs and XFS support it, note that this is not going to be the case with a network filesystem like NFS.

If you have some weird Filesystem type and you try to chattr you will get error like:

chattr: Inappropriate ioctl for device while reading flags on /etc/resolv.conf

To make /etc/resolv.conf file unchangeable on next boot by dhcpd or systemd-resolved

 a systemd service that provides network name resolution to local applications via a D-Bus interface, the resolve NSS service (nss-resolve)
 

root@pcfreak:/root# rm -f /etc/resolv.conf  
{ echo "nameserver 1.1.1.1";
echo "nameserver 1.0.0.1;
echo "search mydomain.com"; } >  /etc/resolv.conf
chattr +i  /etc/resolv.conf
reboot  


Also it is a good think if you don't plan after some update to have unexpected results caused by systemd-resolved doing something strange is to rename to /etc/systemd/resolved.conf.dpkg-bak or completely remove file

/etc/systemd/resolved.conf

To prevent dhcpd to overwrite the server /etc/resolv.conf from something automatically taken from preconfigured central DNS inside the network configurations made from /etc/network/interfaces configurations such as:

        dns-nameservers 127.0.0.1 8.8.8.8 8.8.4.4 207.67.222.222 208.67.220.220


You need to change the DHCP configuration file named dhclient.conf and use the supersede option. 
To so Edit /etc/dhcp/dhclient.conf.

Look for lines like these:

#supersede domain-name "fugue.com home.vix.com";
#prepend domain-name-servers 127.0.0.1;

Remove the preceding “#” comment and use the domain-name and/or domain-name-servers which you want (your DNS FQDN). Save and hopefully the DNS related ovewrite to /etc/resolv.conf would be stopped, e.g. changes inside /etc/resolv.conf mnually done should stay permanent.

Also it is a good practice to disable ddns-update-style direcive inside /etc/dhcp/dhcpd.conf

root@pcfreak:/root# vim /etc/dhcp/dhcpd.conf
##ddns-update-style none;

However on many newer Debian Linux as of 2025 and its .deb based derivative distros, you have to consider the /etc/resolv.conf is a symlink to another file /etc/resolvconf/run/resolv.conf

If that is the case with you then you'll have to set the immutable chattr attribute flag like so

root@pcfreak:~# chattr -V +i /etc/resolvconf/run/resolv.conf
chattr 1.47.0 (5-Feb-2023)
Flags of /etc/resolvconf/run/resolv.conf set as —-i—————–

root@pcfreak:/root# lsattr /etc/resolvconf/run/resolv.conf
—-i—————– /etc/resolvconf/run/resolv.conf

3.  Make /etc/resolv.conf permanent with simple custom a rc.local boot triggered resolv.conf ovewrite from a resolv.conf_actual template file

Consider that due to the increasing complexity of how Linux based OS-es behaves and the fact the Linux is more and more written to fit integration into the Cloud and be as easy as possible to containerize or orchestrate (with lets say docker or some cloud PODs) and other multitude of OS virtualiozation stuff modernities  /etc/resolv.conf might still continue to ovewrite ! 🙂

Thus I've come up with my very own unique and KISS (Keep it Simple Stupid) method to make sure /etc/resolv.conf is kept permanent and ovewritten on every boot for that "hack" trick you only need to have the good old /etc/rc.local enabled – i have written a short article how it can be enabled on newer debian / ubuntu / fedora / centos Linux here.

Prepare your permanent and static /etc/resolv.conf file containing your preferred server DNSes under a file /etc/resolv.conf_actual

Here is an example of one of my /etc/resolv.conf template files that gets ovweritten on each boot.

root@pcfreak:/root# cat /etc/resolv.conf_actual
domain pc-freak.net
search pc-freak.net
#nameserver 192.168.0.1

nameserver 127.0.0.1
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 212.39.90.42
nameserver 212.39.90.43
nameserver 208.67.222.222
nameserver 208.67.220.220
options timeout:2 rotate


And in /etc/rc.local place before the exit directive inside the file simple copy over the original /etc/resolv.conf file real location.

Before proceeding to add it to execute /etc/rc.local assure yourself file is being venerated by OS.
 

root@pcfreak:/etc/dhcp# systemctl status rc-local
● rc-local.service – /etc/rc.local Compatibility
     Loaded: loaded (/etc/systemd/system/rc-local.service; enabled; preset: enabled)
    Drop-In: /usr/lib/systemd/system/rc-local.service.d
             └─debian.conf
     Active: active (exited) since Sun 2024-12-08 21:59:01 EET; 1 month 27 days ago
       Docs: man:systemd-rc-local-generator(8)
    Process: 1417 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)
        CPU: 302ms

Notice: journal has been rotated since unit was started, output may be incomplete.

root@pcfreak:/root# vim /etc/rc.local

 

cp -rpf /etc/resolv.conf_actual /etc/resolvconf/run/resolv.conf


NB ! Make sure those line is placed before any exit 0 command in /etc/rc.local otherwise that won''t work

That's it folks 🙂 
Using this simple trick you should be no longer bothered by a mysterious /etc/resolv.conf overwritten on next server reboot or system update (via a puppet / ansible or some other centralized update automation stuff) causing you a service or infrastructure outage.

Enjoy !

How to log multiple haproxy server instance processes on single server in seperate files with rsyslog filters

Monday, February 3rd, 2025

haproxy-log-frontend-backend-and-transferred-connections-in-separate-log-files-on-linux-server-logo

Lets say you want to have 2 separates instances of haproxy and log the output to separate files, how this can be achived?

In this article, i'll tell in few easy steps how to enable multiple haproxy server instances created on the same Linux server / VPS or docker container to run and log its served content in separate log files without using separate file logging handlers "local"s.
The task might be helpful for people who are involved with DevOps and has to route separate proxy traffic on same linux machine.
 

Lets say you have the following haproxy process instances running with separate haproxy configs:
 

1. haproxy
2. haproxy_worker2
3. haproxy_worker3

 

List of processes on the Linux host would looks like that.

[root@linux-server rsyslog.d]# ps -ef|grep -i hap
root     1151275 1147138  0 11:58 pts/2    00:00:00 grep –color=auto -i hap
root     1835200       1  0 Jan30 ?        00:00:00 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
haproxy  1835203 1835200  0 Jan30 ?        00:10:41 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
root     1835216       1  0 Jan30 ?        00:00:00 /usr/sbin/haproxy_worker2 -Ws -f /etc/haproxy/haproxy_worker2.cfg -p /run/haproxy_worker2.pid
haproxy  1835219 1835216  0 Jan30 ?        00:02:46 /usr/sbin/haproxy_worker2 -Ws -f /etc/haproxy/haproxy_worker2.cfg -p /run/haproxy_worker2.pid
root     1835216       1  0 Jan30 ?        00:00:00 /usr/sbin/haproxy_worker3 -Ws -f /etc/haproxy/haproxy_worker3.cfg -p /run/haproxy_worker3.pid
haproxy  1835219 1835216  0 Jan30 ?        00:02:46 /usr/sbin/haproxy_worker3 -Ws -f /etc/haproxy/haproxy_worker3.cfg -p /run/haproxy_worker3.pid

Question is how to log the 3 haproxies passed through configured connection IP and frontend / backend outputs to separate files

 /var/log/haproxy.log , /var/log/haproxy_worker2.log and /var/log/haproxy_worker3.log


To achieve the task, you will need to set-up 3 rsyslog config files name it according to your preferences and make sure no other rsyslog
file with haproxy related configuration does not mess up with the configs (e.g. is not having a config start number NUMBER_file.conf prior to the below created files.

Then create lets say 49_haproxy.conf and 50_haproxy_worker2.conf and 51_haproxy_worker3.conf

[root@linux-server rsyslog.d]# cat 48_haproxy.conf
#$ModLoad imudp
$UDPServerAddress 127.0.0.1
$UDPServerRun 514
#2022/02/02: HAProxy logs to local6, save the messages
# Template to include only the timestamp in HAProxy logs
template(name="HaproxyTimestampOnly" type="string" string="%timegenerated% %msg:::drop-last-lf%\n")
local6.*                /var/log/haproxy.log;HaproxyTimestampOnly
# Apply the template to HAProxy prod port mapping logs
#if $programname startswith 'haproxy[' then /var/log/haproxy.log;HaproxyTimestampOnly
& stop

[root@linux-server rsyslog.d]# cat 50_haproxy_worker2.conf
$ModLoad imudp
$UDPServerAddress 127.0.0.1
$UDPServerRun 514
# Template to include only the timestamp in HAProxy logs
template(name="HaproxyTimestampOnly" type="string" string="%timegenerated% %msg:::drop-last-lf%\n")

# Apply the template to HAProxy prod port mapping logs
if $programname startswith 'haproxy_worker2' then /var/log/haproxy_worker2.log;HaproxyTimestampOnly

 

[root@linux-server rsyslog.d]# cat 51_haproxy_worker3.conf
$ModLoad imudp
$UDPServerAddress 127.0.0.1
$UDPServerRun 514
# Template to include only the timestamp in HAProxy logs
template(name="HaproxyTimestampOnly" type="string" string="%timegenerated% %msg:::drop-last-lf%\n")

# Apply the template to HAProxy prod port mapping logs
if $programname startswith 'haproxy_worker3' then /var/log/haproxy_worker3.log;HaproxyTimestampOnly

Those rsyslog configs permissions has to be as follows:

[root@linux-server home]# ls -al /etc/rsyslog.d/48_haproxy.conf
-rw-r–r– 1 root root 488 Jan 30 12:44 /etc/rsyslog.d/48_haproxy.conf
[root@linux-server home]# ls -al /etc/rsyslog.d/50_haproxy_worker2.conf
-rw-r–r– 1 root root 379 Jan 30 12:45 /etc/rsyslog.d/50_haproxy_worker2.conf
[root@linux-server home]# ls -al /etc/rsyslog.d/51_haproxy_worker2.conf
-rw-r–r– 1 root root 379 Jan 30 12:45 /etc/rsyslog.d/51_haproxy_worker2.conf

 

The permissions for files to log the haproxy has to be as so:

[root@linux-server home]# ls -al /var/log/haproxy.log
-rw-r—– 1 haproxy haproxy 5014349 Feb  3 12:11 /var/log/haproxy.log
[root@linux-server home]# ls -al /var/log/haproxy_worker2.log
-rw-r—– 1 root root 728139 Feb  3 12:11 /var/log/haproxy_worker2.log
[root@linux-server home]# ls -al /var/log/haproxy_worker3.log
-rw-r—– 1 root root 728139 Feb  3 12:11 /var/log/haproxy_worker3.log

To make the changes take affect restart consequentially rsyslog first and then the 3 haproxy instances:

[root@linux-server home]# systemctl restart rsyslog
[root@linux-server home]# systemctl restart haproxy
[root@linux-server home]# systemctl restart haproxy2
[root@linux-server home]# systemctl restart haproxy3

Go on and check the logs that everything comes in from the haproxys running the same server into the separate files:

[root@linux-server home]# tail -f /var/log/haproxy.log /var/log/haproxy_worker2.log /var/log/haproxy_worker3.log

Hope this has helped someone out there looking to solve on how to log multiple haproxy instances on the same servers into separate files.

That's all folks. Enjoy!

Enable automatic updates on CentOS 8 , CentOS 9 Stream Linux with dnf-automatic and Cockpit Web GUI package management tool

Wednesday, January 15th, 2025

centos-8-and-centos-9-linux-enable-automatic-rpm-yum-updates-with-dnf-automatic-logo

Security for any OS is critical nowadays, thus as a CentOS legacy system admin at work or using CentOS Stream releases 8 and 9 that are to be around for the coming years

CentOS 8 and CentOS 9 Stream Lifecycle


CentOS Stream follows the same lifecycle as Red Hat Enterprise Linux. From version 8 onward this means every version is supported for 10 years, split into 5 years of Full Support and 5 years of maintenance support. Users also have the option to purchase an additional 3 years of Extended Life Cycle Support (ELS) as an add-on.

Version    General Availability    Full Support Ends    Maintenance Support Ends    Extended Life Cycle Support (ELS) Ends
8    May 7, 2019    May 31, 2024    May 31, 2029    May 31, 2032
9    May 18, 2022    May 31, 2027    May 31, 2032    May 31, 2035


In this article, you are going to learn how to enable automatic software updates on CentOS 8 and CentOS 9 ( Stream ) Linux OS-es. I'll show how to set up your system to download and apply  security and other updates without user intervention.

It is really useful to use the CentOS automatic updates OS capability, turning on updates and instead typing all the time yum update && yum upgrade (and wasting time to observe the process) as it takes usually some 5 to 10 minutes to make the OS automatically install updates in the background and notify you once all is done so you can periodically check what the dnf-automatic automatic update tool has done that in most cases of success would save you at least few minutes per host. Automatic updates is critical especially if you have to maintain an infrastructure of CentOS virtual servers at version 8 or 9.

Those who use heavily used CentOS might have already enabled and used dnf-automatic, but I guess just like me until recently, most people using CentOS 8 don’t know how to enable and apply CentOS Linux updates automatically and those article might be helpful.
 

1. Enable Automatic CentOS 8 / 9 Updates Using DNF Automatic RPM Package


Install the DNF-automatic RPM package, it will provide a DNF component that enables start automatically the update process. 
To install it on both CentOS 8 / 9.

[root@centos ~]# yum install dnf-automatic
CentOS Stream 9 – BaseOS                                                                                                                                   78 kB/s |  14 kB     00:00
CentOS Stream 9 – AppStream                                                                                                                                28 kB/s |  15 kB     00:00
CentOS Stream 9 – Extras packages                                                                                                                          81 kB/s |  18 kB     00:00
Dependencies resolved.
======================================================
 Package                                         Architecture                             Version                                          Repository                                Size
======================================================
Installing:
 dnf-automatic                                   noarch                                   4.14.0-23.el9                                    baseos                                    33 k
Upgrading:
 dnf                                             noarch                                   4.14.0-23.el9                                    baseos                                   478 k
 dnf-data                                        noarch                                   4.14.0-23.el9                                    baseos                                    37 k
 python3-dnf                                     noarch                                   4.14.0-23.el9                                    baseos                                   461 k
 yum                                             noarch                                   4.14.0-23.el9                                    baseos                                    88 k

Transaction Summary
=======================================================
Install  1 Package
Upgrade  4 Packages

Total download size: 1.1 M
Is this ok [y/N]: y
Downloading Packages:
(1/5): dnf-data-4.14.0-23.el9.noarch.rpm                                                                                                                  556 kB/s |  37 kB     00:00
(2/5): dnf-automatic-4.14.0-23.el9.noarch.rpm                                                                                                             406 kB/s |  33 kB     00:00
(3/5): yum-4.14.0-23.el9.noarch.rpm                                                                                                                       1.4 MB/s |  88 kB     00:00
(4/5): python3-dnf-4.14.0-23.el9.noarch.rpm                                                                                                               4.9 MB/s | 461 kB     00:00
(5/5): dnf-4.14.0-23.el9.noarch.rpm                                                                                                                       2.6 MB/s | 478 kB     00:00
——————————————————————————————————
Total                                                                                                                                                     1.1 MB/s | 1.1 MB     00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                                                  1/1
  Upgrading        : dnf-data-4.14.0-23.el9.noarch                                                                                                                                    1/9
  Upgrading        : python3-dnf-4.14.0-23.el9.noarch                                                                                                                                 2/9
  Upgrading        : dnf-4.14.0-23.el9.noarch                                                                                                                                         3/9
  Running scriptlet: dnf-4.14.0-23.el9.noarch                                                                                                                                         3/9
  Installing       : dnf-automatic-4.14.0-23.el9.noarch                                                                                                                               4/9
  Running scriptlet: dnf-automatic-4.14.0-23.el9.noarch                                                                                                                               4/9
  Upgrading        : yum-4.14.0-23.el9.noarch                                                                                                                                         5/9
  Cleanup          : yum-4.14.0-9.el9.noarch                                                                                                                                          6/9
  Running scriptlet: dnf-4.14.0-9.el9.noarch                                                                                                                                          7/9
  Cleanup          : dnf-4.14.0-9.el9.noarch                                                                                                                                          7/9
  Running scriptlet: dnf-4.14.0-9.el9.noarch                                                                                                                                          7/9
  Cleanup          : python3-dnf-4.14.0-9.el9.noarch                                                                                                                                  8/9
  Cleanup          : dnf-data-4.14.0-9.el9.noarch                                                                                                                                     9/9
  Running scriptlet: dnf-data-4.14.0-9.el9.noarch                                                                                                                                     9/9
  Verifying        : dnf-automatic-4.14.0-23.el9.noarch                                                                                                                               1/9
  Verifying        : dnf-4.14.0-23.el9.noarch                                                                                                                                         2/9
  Verifying        : dnf-4.14.0-9.el9.noarch                                                                                                                                          3/9
  Verifying        : dnf-data-4.14.0-23.el9.noarch                                                                                                                                    4/9
  Verifying        : dnf-data-4.14.0-9.el9.noarch                                                                                                                                     5/9
  Verifying        : python3-dnf-4.14.0-23.el9.noarch                                                                                                                                 6/9
  Verifying        : python3-dnf-4.14.0-9.el9.noarch                                                                                                                                  7/9
  Verifying        : yum-4.14.0-23.el9.noarch                                                                                                                                         8/9
  Verifying        : yum-4.14.0-9.el9.noarch                                                                                                                                          9/9

Upgraded:
  dnf-4.14.0-23.el9.noarch                   dnf-data-4.14.0-23.el9.noarch                   python3-dnf-4.14.0-23.el9.noarch                   yum-4.14.0-23.el9.noarch
Installed:
  dnf-automatic-4.14.0-23.el9.noarch

Complete!
[root@centos ~]#

Here is info on what dnf-automatic package will do: 

[root@centos ~]# rpm -qi dnf-automatic
Name        : dnf-automatic
Version     : 4.14.0
Release     : 23.el9
Architecture: noarch
Install Date: Wed 15 Jan 2025 08:00:47 AM -03
Group       : Unspecified
Size        : 57937
License     : GPLv2+
Signature   : RSA/SHA256, Thu 02 Jan 2025 01:19:43 PM -03, Key ID 05b555b38483c65d
Source RPM  : dnf-4.14.0-23.el9.src.rpm
Build Date  : Thu 12 Dec 2024 07:30:24 AM -03
Build Host  : s390-08.stream.rdu2.redhat.com
Packager    : builder@centos.org
Vendor      : CentOS
URL         : https://github.com/rpm-software-management/dnf
Summary     : Package manager – automated upgrades
Description :
Systemd units that can periodically download package upgrades and apply them.


Next up is configuring the dnf-automatic updates. The configuration file is located at /etc/dnf/automatic.conf. Once you have opened the file, you can to set the required values to fit your software requirements.
The values you might want to modify are as so:

 

[root@centos ~]# grep -v \# /etc/dnf/automatic.conf|sed '/^$/d'
[commands]
upgrade_type = default
random_sleep = 0
network_online_timeout = 60
download_updates = yes
apply_updates = no
reboot = never
reboot_command = "shutdown -r +5 'Rebooting after applying package updates'"
[emitters]
emit_via = stdio
[email]
email_from = root@example.com
email_to = root
email_host = localhost
[command]
[command_email]
email_from = root@example.com
email_to = root
[base]
debuglevel = 1
[root@centos ~]#

 

The most important things you need to tune in automatic.conf are:

[root@centos ~]# vim /etc/dnf/automatic.conf

apply_updates = no


should be changed to yes 

apply_updates = yes

for automatic updates to start by dnf-automatic service

It is nice to set the email server to use configuration values, as well as email from, email to and the way for
email to be set emit_via = stdio is default (check out the other options if to be used inside the commented lines)

Finally, you can now run dnf-automatic, execute the following command to schedule DNF automatic updates for your CentOS 8 machine.

[root@centos ~]# systemctl enable –now dnf-automatic.timer


The command above enables and starts the system timer. To check the status of the dnf-automatic service, run the following.

[root@centos ~]#  systemctl list-timers *dnf-*
NEXT                        LEFT       LAST                        PASSED      UNIT                ACTIVATES
Wed 2025-01-15 09:31:52 -03 13min left –                           –           dnf-makecache.timer dnf-makecache.service
Thu 2025-01-16 06:21:20 -03 21h left   Wed 2025-01-15 08:09:20 -03 1h 8min ago dnf-automatic.timer dnf-automatic.service

2 timers listed.
Pass –all to see loaded but inactive timers, too.

[root@centos ~]#

 

Enable and Manage Automatic updates with Cockpit GUI web interface


Sooner or later even hard core sysadmins has to enter the 21 century and start using a Web interfaces for server or Desktop Linux management to offload your head for more important stuff.
Cockpit is a great tool to help you automatically manage and update your servers with no need to use the Linux console most of the time.

Cockpit is a very powerful tool you can use to manage remotely updates through a web interface, it is very handy tool for system admins as it gives you overview over updates and supports automatic updates and set RPM package management tasks through web-based console. 
Cockpit allows updates over multiple servers and it makes it a kind of server orchestration tool that allows yo to update many same versioned operating system software.


If you haven't it already pre-installed in CentOS 8 / 9 depending on the type ofinstall you have done, you might need to install Cockpit.

To install cockpit

[root@centos ~]# yum install cockpit -y

To make the web service accessible in a browser you'll have to start it with cmds:

[root@centos ~]# systemctl start cockpit
[root@centos ~]# systemctl status cockpit

To access cockpit you'll either have to access it on https://localhost:9090 in case you need to access it locally via https://SERVER_IP:9090/.
Note that of course you will have to have firewalld enabling traffic to SERVER_IP PORT 9090.

 

centos-steam-cockpit-web-gui-autoupdate-tool-linux-screenshot1

By default cockpit will run with self signed certificate, if you need you can set up a certbot certificate or regenerate the self signed one for better managed security risk. For a first time if you haven't changed the certificate simply use the browser exclusion menu and login to Cockpit.

Once logged in you can check the available updates.

 

centos-steam-cockpit-web-gui-autoupdate-tool-linux-screenshot0

By default you will have to login with non-root account, preferably that should be an account who is authorized to become root via sudo.
To elevate to administrative privileges while in cockpit clock on 'Administrative access' and grant cockpit your superuser privileges.

centos-steam-cockpit-web-gui-autoupdate-tool-linux-screenshot2

Once authorized you can run the upgrade and enojy a coffee or beer in the mean time 🙂

centos-steam-cockpit-web-gui-autoupdate-tool-linux-screenshot-update-ongoing

Among the useful cockpit options, is also the Terminal through which you can run commands like over a normal Web SSH service.

The 'Logs' section is also very useful as it shows you clearly synthesized information on failed services and modules, since last OS system boot.

 

https://pc-freak.net/images/centos-steam-cockpit-web-gui-autoupdate-tool-linux-screenshot3

To add and manage updates for multiple hosts use the 'Add new host' menu that is a expansion of the main machine on which cockpit runs.


centos-steam-cockpit-web-gui-autoupdate-tool-linux-automatic-updates-settings

In the next window, turn automatic updates ON. You can now select the type of updates you want (Apply All Updates or Apply Security Updates), the day and time you want the updates applied, and the server rebooted.

CentOS 9's cockpit even have support for the innovative Kernel live patching, so the machine kernel can be updated even Live and you can save the reboot after complete patching of OS including the kernel.

centos-steam-cockpit-web-gui-autoupdate-tool-linux-kernel-live-patching-menu

Note that you cannot set up automatic updates without rebooting the system. Therefore, make sure your server can be rebooted at the time you’ve selected for the updates.

Sum it up


In this post, we learned have learned how to set up automatic updates for your CentOS 8 / 9 Linux. There are two main stream ways you can do it.
1. By using DNF automatic updates tool.
By enabling DNF automatic updates on CentOS 8 Linux the machine updated is faster, seemless and frequent as compared to manual updates.

This protects the OS more about crackers cyber-attacks. Secondly for the more lazy admins or for better structuring of updates (if it has to be executed on multiple hosts), the Cockpit web console is available.

With Cockpit, it’s much easy to enable automatic updates as the GUI is self-explanatory graphical user interface (GUI) as opposed to the DNF automatic updates, which would waste you more time on CLI ( shell ).
 

Enable Debian Linux automatic updates to keep latest OS Patches / Security Up to Date

Monday, January 13th, 2025

Enable Debian Linux automatic updates to keep latest OS Patches / Security Up to Date

Debian: Entenda a Importância Para o Mundo GNU/LINUX

I'm not a big fan of automatism on GNU / Linux as often using automatic updates could totally mess things especially with a complex and a bit chatic OS-es like is Linux nowadays. 
Nevertheless as Security is becoming more and more of a problem especially the browser security, having a scheduled way to apply updates like every normal modern Windows and MAC OS as an option is becoming essential to have a fully manageble Operating system.

As I use Debian GNU / Linux for desktop for my own personal computer and I have already a lot of Debian servers, whose OS minor level and package version maintenance takes up too big chunk of my time (a time I could dedicated to more useful activities). Thus I found it worthy at some cases to trigger Debian's way to keep the OS and security at a present level, the so called Debian "unattended upgrades".

In this article, I'll explain how to install and Enable Automatic (" Unattended " ) Updates on Debian, with the hope that other Debian users might start benefiting from it.
 

Pros of  enabling automatic updates, are:

  • Debian OS Stay secure without constant monitoring.
  • You Save much time by letting your system handle updates.
  • Presumably Enjoying more peace of mind, knowing your system is more protected.

Cons of enabling automatic updates:

  • Some exotic and bad maintained packages (might break after the update)
  • Customizations made on the OS /etc/sysctl.conf or any other very custom server configs might disappear or not work after the update
  • At worst scenario (a very rare but possible case) OS might fail to boot after update 🙂

Regular security updates patch vulnerabilities that could otherwise be exploited by attackers, which is especially important for servers and systems exposed to the internet, where threats evolve constantly.

1. Update Debian System to latest

Before applying automatic updates making any changes, run apt to update package lists and upgrade any outdated packages,to have automatic updates for a smooth configuration process.

# apt update && apt upgrade -y

2. Install the Unattended-Upgrades deb Package 

# apt install unattended-upgrades -y

Reading package lists… Done
Building dependency tree… Done
Reading state information… Done
The following additional packages will be installed:
  distro-info-data gir1.2-glib-2.0 iso-codes libgirepository-1.0-1 lsb-release python-apt-common python3-apt python3-dbus python3-distro-info python3-gi
Suggested packages:
  isoquery python-apt-doc python-dbus-doc needrestart powermgmt-base
The following NEW packages will be installed:
  distro-info-data gir1.2-glib-2.0 iso-codes libgirepository-1.0-1 lsb-release python-apt-common python3-apt python3-dbus python3-distro-info python3-gi unattended-upgrades
0 upgraded, 11 newly installed, 0 to remove and 0 not upgraded.
Need to get 3,786 kB of archives.
After this operation, 24.4 MB of additional disk space will be used.
Do you want to continue? [Y/n]

 

 

# apt install apt-listchanges
Reading package lists… Done
Building dependency tree… Done
Reading state information… Done
The following package was automatically installed and is no longer required:
  linux-image-5.10.0-30-amd64
Use 'apt autoremove' to remove it.
The following additional packages will be installed:
  python3-debconf
The following NEW packages will be installed:
  apt-listchanges python3-debconf
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 137 kB of archives.
After this operation, 452 kB of additional disk space will be used.
Do you want to continue? [Y/n]
Get:1 http://deb.debian.org/debian bookworm/main amd64 python3-debconf all 1.5.82 [3,980 B]
Get:2 http://deb.debian.org/debian bookworm/main amd64 apt-listchanges all 3.24 [133 kB]
Fetched 137 kB in 0s (292 kB/s)
Preconfiguring packages …
Deferring configuration of apt-listchanges until /usr/bin/python3
and python's debconf module are available
Selecting previously unselected package python3-debconf.
(Reading database … 84582 files and directories currently installed.)
Preparing to unpack …/python3-debconf_1.5.82_all.deb …
Unpacking python3-debconf (1.5.82) …
Selecting previously unselected package apt-listchanges.
Preparing to unpack …/apt-listchanges_3.24_all.deb …
Unpacking apt-listchanges (3.24) …
Setting up python3-debconf (1.5.82) …
Setting up apt-listchanges (3.24) …

Creating config file /etc/apt/listchanges.conf with new version

 

Example config for apt-listchanges would be like:

# vim /etc/apt/listchanges.conf
[apt]
frontend=pager
email_address=root
confirm=0
save_seen=/var/lib/apt/listchanges.db
which=both

3. Enable Automatic unattended upgrades

Once installed, enable automatic updates with the following command, which will prompt asking if you want to enable automatic updates. Select Yes and press Enter, which will confirm that the unattended-upgrades service is active and ready to manage updates for you.

# dpkg-reconfigure unattended-upgrades

Configure-Unattended-Upgrades-on-Debian_Linux-dpkg-reconfigure-screenshot

Or non-interactively by running command:

# echo unattended-upgrades unattended-upgrades/enable_auto_updates boolean true | debconf-set-selections
dpkg-reconfigure -f noninteractive unattended-upgrades


4. Set the Schedule for Automatic Updates on Debian

By default, unattended-upgrades runs daily, to verify or modify the schedule, check the systemd timer:

# sudo systemctl status apt-daily.timer
# sudo systemctl status apt-daily-upgrade.timer
# systemctl edit apt-daily-upgrade.timer

Current apt-daily.timer config as of Debian 12 (bookworm) is as follows

root@haproxy2:/etc/apt/apt.conf.d# cat  /lib/systemd/system/apt-daily.timer
[Unit]
Description=Daily apt download activities

[Timer]
OnCalendar=*-*-* 6,18:00
RandomizedDelaySec=12h
Persistent=true

[Install]
WantedBy=timers.target
root@haproxy2:/etc/apt/apt.conf.d#


 

# systemctl edit apt-daily-upgrade.timer

[Timer]
OnCalendar=
OnCalendar=03:00
RandomizedDelaySec=0

 

At Line  num 2 above is needed to reset (empty) the default value shown below in line  num 5.
Line 4 is needed to prevent any random delays coming from the defaults.


Now both timers should be active, if not, activate them with:

# systemctl enable –now apt-daily.timer
# systemctl enable –now apt-daily-upgrade.timer


These timers ensure that updates are checked and applied regularly, without manual intervention.

5.Test one time Automatic Updates on Debian works

To ensure everything is working, simulate an unattended upgrade with a dry run:

# unattended-upgrade –dry-run

 

You can monitor automatic updates by checking the logs.

# less /var/log/unattended-upgrades/unattended-upgrades.log

Log shows details of installed updates and any issues that occurred. Reviewing logs periodically can help you ensure that updates are being applied correctly and troubleshoot any problems.

6. Advanced Configuration Options

If you’re a power user or managing multiple systems, you might want to explore these additional settings in the configuration file:

# vim /etc/apt/apt.conf.d/50unattended-upgrades


Configure unattended-upgrades to send you an email whenever updates are installed.

Unattended-Upgrade::Mail "your-email-address@email-address.com";


Enable automatic reboots after kernel updates
by adding the line:

Unattended-Upgrade::Automatic-Reboot "true";

To schedule reboots after package upgrade is applied  at a specific time:

Unattended-Upgrade::Automatic-Reboot-Time "02:00";

Specify packages you don’t want to be updated by editing the Unattended-Upgrade::Package-Blacklist section in the configuration file.

 

Here is alternative way to configure the unattended upgrade, by using apt configuration options:

# vim /etc/apt/apt.conf.d/02periodic

// Control parameters for cron jobs by /etc/cron.daily/apt-compat //


// Enable the update/upgrade script (0=disable)
APT::Periodic::Enable "1";


// Do "apt-get update" automatically every n-days (0=disable)
APT::Periodic::Update-Package-Lists "1";


// Do "apt-get upgrade –download-only" every n-days (0=disable)
APT::Periodic::Download-Upgradeable-Packages "1";


// Run the "unattended-upgrade" security upgrade script
// every n-days (0=disabled)
// Requires the package "unattended-upgrades" and will write
// a log in /var/log/unattended-upgrades
APT::Periodic::Unattended-Upgrade "1";


// Do "apt-get autoclean" every n-days (0=disable)
APT::Periodic::AutocleanInterval "21";


// Send report mail to root
//     0:  no report             (or null string)
//     1:  progress report       (actually any string)
//     2:  + command outputs     (remove -qq, remove 2>/dev/null, add -d)
//     3:  + trace on
APT::Periodic::Verbose "2";

If you have to simultaneously update multiple machines and you're on a limited connection line, configure download limits if you’re on a metered connection by setting options in /etc/apt/apt.conf.d/20auto-upgrades.

7. Stop Automatic Unattended Upgrade

Under some circumstances if it happens the unattended upgrades are no longer required and you want to revert back to manual package updates, to disable the updates you have to disable the unattended-upgrades service

# systemctl stop unattended-upgrades


8.  Stop an ongoing apt deb package set of updates applied on Debian server

Perhaps not often, but it might be you have run an automated upgrade and this has broke a server system or a service and for that reason you would like to stop the upcoming upgrade (some of whose might have started on other servers) immediately, to do so, the easiest way (not always safe thogh) is to kill the unattended-upgrades daemon.
 

# pkill –signal SIGKILL unattended-upgrades


Note that this a very brutal way to kill it and that might lead to some broken package update, that you might have to later fix manually.

If you have the unattended-upgrade process running on the OS in the process list backgrounded and you want to stop the being on the fly upgrade on the system more safely for the system, you can stop and cancel the ongoing apt upgrade  it by running the ncurses prompt interface, through dpkg-reconfigure

# dpkg-reconfigure unattended-upgrades


Then just select No, press Enter. In my case, this has promptly stopped the ongoing unattended upgrade that seemed blocked (at least as promptly as the hardware seemed to allow 🙂 ).

If you want to disable it for future, so it doesn't automatically gets enabled on next manual update, by some update script disable service as well.
 

# systemctl disable unattended-upgrades

 

Close up

That’s all ! Now, your Debian system will automatically handle security updates, keeping your system secure without you having to do a thing.
The same guide should be good for most Deb based distributions such as Ubuntu / Mint and there rest of other Debian derivative OS-es.
You’ve now set up a reliable way to ensure your system stays protected from vulnerabilities, but anyways it is a good practice to always login and check what the update has done to the system, otherwise expect the unexpected. 

Flush DNS on Mac OS X ,Windows and Linux from command line

Wednesday, January 8th, 2025

MAC OSX DNS Configuration | DNSFLEX

 

MAC OS X flush DNS cache


Open macOS /Mac OS X terminal application and type the following command under OS X version 10.5 and above:

# dscacheutil -flushcache

Mac OS X Tiger (v10.4) user, enter:

# lookupd -flushcache

macOS 11 Big Sur or 12 Monterey user, try:

# sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

 

macOS 10.11 El Capitan, 10.12 Sierra, 10.13 High Sierra, 10.14 Mojave, or 10.15 Catalina user try:

# sudo killall -HUP mDNSResponder

 

On Mac OS X version 10.6 and onwards to dump DNS cached records
 

$ dscacheutil -cachedump -entries

Display your DNS cached records on Windows
 
Implement Windows Server DNS - Training | Microsoft Learn

  DNS cached records are stored to offload the DNS from querying it all the time in order to resolve the questionable site domain IP.

To view most recent cached DNS records on Windows use cmd:
 

c:\Windows\> ipconfig /displaydns

 

Windows IP Configuration

    array805.prod.do.dsp.mp.microsoft.com
    —————————————-
    Record Name . . . . . : array805.prod.do.dsp.mp.microsoft.com
    Record Type . . . . . : 1
    Time To Live  . . . . : 1894
    Data Length . . . . . : 4
    Section . . . . . . . : Answer
    A (Host) Record . . . : 52.143.124.236


    telemetry-incoming.r53-2.services.mozilla.com
    —————————————-
    Record Name . . . . . : telemetry-incoming.r53-2.services.mozilla.com
    Record Type . . . . . : 1
    Time To Live  . . . . : 444
    Data Length . . . . . : 4
    Section . . . . . . . : Answer
    A (Host) Record . . . : 34.120.208.123


    tunnel.googlezip.net
    —————————————-
    Record Name . . . . . : tunnel.googlezip.net
    Record Type . . . . . : 1
    Time To Live  . . . . : 36756
    Data Length . . . . . : 4

Use up/down scroll array to see the cached record you need to view in the DNS cache.
 

Flush DNS Cache on Windows OS

 


Open the terminal (Start > Run > type cmd and press the [Enter] key) and type the following command to flush DNS on Win XP/2000/7/10 etc:

# ipconfig /flushdns

 

How to Flush DNS local cache queries on Linux

How to Flush DNS Cache on Linux | Linux How to Flush DNS Guide

 

If you’re using a Linux distro such as Ubuntu, here’s how to flush the DNS cache:

Open the terminal by pressing Ctrl + Alt + T or searching for “Terminal” in the Activities menu.
Run the following command:
If you are running Ubuntu 20.04 LTS Linux or older Linux distro using systemd-resolve, use: sudo systemd-resolve –flush-caches.
If you are running Ubuntu 22.04 LTS or newer, use: sudo resolvectl flush-caches.
Enter your administrator password when prompted, and the DNS cache will be flushed.

To check the change in the DNS record is real, you can check the DNS cache statistics:

# resolvectl statistics

On older Linux distributions where /etc/resolv.conf nameserver directives are used to set the DNS for the server, to flush the cache
only options is to either flush the server used cache or change the nameserver inside the file.

 

Check the DNS cache records on older Linux distros (requires NSCD daemon)

Assuming the nscd daemon is UP and running (if not you have to install it) to check the cached local DNS records on Linux do

# service nscd status 


Reviewing Your DNS Cache on modern Linux distros

The systemd-resolved daemon reacts to USR1 by writing its cache to the system logs. We can then use the journalctl command to filter out the DNS entries.

We'll use the killall command with USR1 To send the signal to the systemd-resolved daemon. Note that although we're using the killall command, the systemd-resolved daemon continues to run. This isn't a termination signal that we're sending.

$ sudo killall -USR1 systemd-resolved

Now we'll use the journalctl command with the -u (filter by systemd unit) option to extract the log entries that have been generated by systemd-resolved . We'll redirect that output into a text files called "dns.txt."

$ sudo journalctl -u systemd-resolved > dns.txt

Then check the DNS records

$ less dns.txt

 

Then find the cached mappings between domain names and IP addresses in.

How to Flush the dnsmasq Cache on Linux

The dnsmasq application provides a DNS cache and a DHCP server.

dnsmasq is popular among with users who want to run their own DNS server, especially on non-systemd installations.

Flushing the dnsmasq DNS cache is easy. We need to send the SIGHUP signal, which tells the dnsmasq daemon to effectively reinitialize. Doing so clears its DNS cache. To send the signal we use the killall command with the -HUP flag, and the name of the application.

$ sudo killall -HUP dnsmasq

How to install and use WSL 2 Windows native Linux emulation Debian and Ubuntu Linux on Windows 10 / Windows 11

Thursday, October 31st, 2024

start-with-wsl-windows-emulation-linux-install-and-use-easily-linux-and-windows-together-with-no-external-software-tux-penguin-logo

WSL (Windows Subsystem for Linux) is perhaps relatively rarely known to the old school sys admins rats who usually use stuff like QEMU / KVM for Windows or Virtualbox / VMWare for Host machine.
However most people most lileky heard but never used or heard about the native (container like) virtualization WSL which was introduced in Windows 10 and Windows 11  as an attempt from Microsoft to improve the interoperability between Windows and Linux.
WSL version 1 and ver 2 allows Microsoft Windows for using a Linux environment without the need for a separate virtual machine.

In Windows 10, it is existing in Windows 10 Professional version can be installed either by joining the Windows Insider program or manually via Microsoft Store or Winget.
Hence perhaps you don't know that WSL virtualization can be used by those who want to mix Linux and Windows or for example get an advantages against dual-boot (installing Linux and Windows on the same computer).
Even better most significant WSL pros is you can literally running both systems at the same time without the need to run or stop every software that’s running and reboot to another system.

Procedure to set up a WSL is simple and similar to setting up a real Linux OS, therefore this guide can also be used as a reference to Linux setup.The specifications of WSL setup procedure are mainly in Install WSL and then setup any packages you would like to use for example if you want to be able to access remotely the WSL emulated Debian / Ubuntu or other of the installable distros via OpenSSH server.

1. Requirements to install and use WSL Linux emulation

To have the wsl subsystem used on Windows 10 or Windows 11 requirements:

You must be running Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11 to use the commands below. If you are on earlier versions please see the manual install page.

2. List available installable Linux distributions
 

WSL subsystem has ported only a certain set of Linux distributions, so if you need a very specific and unique Linux distribution, you would perhaps need to use Hyper-V virtualization or Virtualbox / VMWare.
However for people like me who are mainly using Debian GNU / Linux on daily basis as well as some OracleLinux admins / SUSE it is a perfect solution.

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –list –online
The following is a list of valid distributions that can be installed.
Install using 'wsl.exe –install <Distro>'.

NAME                            FRIENDLY NAME
Ubuntu                          Ubuntu
Debian                          Debian GNU/Linux
kali-linux                      Kali Linux Rolling
Ubuntu-18.04                    Ubuntu 18.04 LTS
Ubuntu-20.04                    Ubuntu 20.04 LTS
Ubuntu-22.04                    Ubuntu 22.04 LTS
Ubuntu-24.04                    Ubuntu 24.04 LTS
OracleLinux_7_9                 Oracle Linux 7.9
OracleLinux_8_7                 Oracle Linux 8.7
OracleLinux_9_1                 Oracle Linux 9.1
openSUSE-Leap-15.6              openSUSE Leap 15.6
SUSE-Linux-Enterprise-15-SP5    SUSE Linux Enterprise 15 SP5
SUSE-Linux-Enterprise-15-SP6    SUSE Linux Enterprise 15 SP6
openSUSE-Tumbleweed             openSUSE Tumbleweed


 

3. Install Linux distribution for a first time

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –install

wsl2-windows-virtualization-install-virtual-machine-debian1

The default Linux distribution that will get installed inside WLS Virtlualization is Ubuntu.

4. Install Debian GNU / Linux distribution as a second distro

 

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –install Debian

windows-wsl-linux-emulation/wsl2-windows-virtualization-install-virtual-machine-debian3

That second installed distro would make Debian now the default one to boot by WSL.

To run the fresh installed Debian GNU / Linux distribution, run only wsl command with no arguments.

# wsl

 

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –set-version Debian 2
For information on key differences with WSL 2 please visit https://aka.ms/wsl2
Conversion in progress, this may take a few minutes.
The distribution is already the requested version.
Error code: Wsl/Service/WSL_E_VM_MODE_INVALID_STATE
PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –set-version 2
There is no distribution with the supplied name.
Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND
PS C:\Windows\System32\WindowsPowerShell\v1.0>

Simply pressting CTRL + D from the actively running WSL emulated Linux (that is pretty much like a native Windows docker container if we have to compare to Linux) would stop the VM.
 

5. List runnable / installed VM Linux distributions
 

To list the available runnable Linux VMs on your Windows  status on Windows Subsystem for Linux:

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –list –verbose
  NAME      STATE           VERSION
* Debian    Stopped         2
  Ubuntu    Stopped         2

PS C:\Windows\System32\WindowsPowerShell\v1.0>


6. Run and check recent installed Linux distribution version

wsl2-windows-virtualization-install-virtual-machine-debian4

To run the newly install Debian Virtualized Linux (which as you can see is the default set distribution to run by WSL virtualization) simply type 

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl

hipo@PC2LP3:/mnt/c/Windows/System32/WindowsPowerShell/v1.0$hipo@WL-2SLPWL3:/mnt/c/Windows/System32/WindowsPowerShell/v1.0$ cd ~
hipo@PC2LP3:~$

 

hipo@PC2LP3:~$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
NAME="Debian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
hipo@WL-2SLPWL3:~$

 

7. Update the Debian distribuion packages to latest available

hipo@PC2LP3:~$ sudo su – root
hipo@PC2LP3:~# apt update –fix-missing


8. Install openssh server to be able to connect to the WSL hosted Virtual Machine

hipo@PC2LP3:/home/hipo# apt install openssh-server –yes


windows-wsl-linux-emulation

 

root@PC2LP3:/home/hipo# systemctl start openssh-server telnet
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
root@WL-2SLPWL3:/home/hipo# /etc/init.d/ssh start
Starting OpenBSD Secure Shell server: sshd.
root@WL-2SLPWL3:/home/hipo# ps -ef|grep -i ssh
root        30     9  0 18:19 ?        00:00:00 sshd: /usr/sbin/sshd [listener] 0 of 10-100 startups
root        32    15  0 18:20 pts/1    00:00:00 grep -i ssh

 

windows-wsl-linux-emulation

By default a fresh new installed VM would have a process list like below:

root@PC2LP3:/home/hipo# ps axuwef


wsl2-windows-virtualization-install-virtual-machine-debian7

To be able to have ifconfig and a number of other network tools it is useful to install net-tools package

root@PC2LP3:/home/hipo# apt install net-tools –yes

root@PC2LP3:/home/hipo# /sbin/ifconfig

Once the WSL VM and OpenSSHD is run you can try to telnet or ssh to the VM locally or remotely.

root@PC2LP3:/home/hipo# telnet localhost 22
Trying 127.0.0.1…
Connected to localhost.
Escape character is '^]'.
SSH-2.0-OpenSSH_9.2p1 Debian-2+deb12u3

9. Run commands directly from Windows command line or Powershell
 

You can also use the powershell to run commands via the virtualized Linux environment using simple syntax

# wsl [cmd-to-run]

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl ls /
bin   dev  home  lib    lost+found  mnt  proc  run   srv  tmp  var
boot  etc  init  lib64  media       opt  root  sbin  sys  usr
PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 18:07 hvc0     00:00:00 /init
root         5     1  0 18:07 hvc0     00:00:00 plan9 –control-socket 5 –log-level 4 –server-fd 6 –pipe-fd 8 –log-t
root         8     1  0 18:07 ?        00:00:00 /init
root         9     8  0 18:07 ?        00:00:00 /init
hipo        10     9  0 18:07 pts/0    00:00:00 ps -ef

PS C:\Windows\System32\WindowsPowerShell\v1.0>

10. Enable systemd on Linux distribution in WSL 2

Once you boot into the WSL installed distro shell edit /etc/wsl.conf:

$ vim /etc/wsl.conf

[boot]
systemd=true

11. Setting extra useful variables to boot the WSL emulated Linux VM 
 

root@debian-wsl:/home/hipo# cat /etc/wsl.conf
[boot]
systemd=true

# Automatically mount Windows drive when the distribution is launched
[automount]

# Set to true will automount fixed drives (C:/ or D:/) with DrvFs under the root directory set above. Set to false means drives won't be mounted automatically, but need to be mounted manually or with fstab.
enabled = true

# Sets the directory where fixed drives will be automatically mounted. This example changes the mount location, so your C-drive would be /c, rather than the default /mnt/c.
root = /

# DrvFs-specific options can be specified.
options = "metadata,uid=1003,gid=1003,umask=077,fmask=11,case=off"

# Sets the `/etc/fstab` file to be processed when a WSL distribution is launched.
mountFsTab = true

# Network host settings that enable the DNS server used by WSL 2. This example changes the hostname, sets generateHosts to false, preventing WSL from the default behavior of auto-generating /etc/hosts, and sets generateResolvConf to false, preventing WSL from auto-generating /etc/resolv.conf, so that you can create your own (ie. nameserver 1.1.1.1).
[network]
hostname = debian-wsl
generateHosts = true
generateResolvConf = true

# Set whether WSL supports interop processes like launching Windows apps and adding path variables. Setting these to false will block the launch of Windows processes and block adding $PATH environment variables.
[interop]
enabled = false
appendWindowsPath = false

# Set the user when launching a distribution with WSL.
[user]
default = hipo

# Set a command to run when a new WSL instance launches. This example starts the Docker container service.
#[boot]
#command = service docker start

root@debian-wsl:/home/hipo#

To learn about on Advanced settings configuration in WSL check out official Microsoft documentation here

12. Shutting down a running emulated Linux VM

If you have run a WSL VM and you want to shut it down do:

# wsl shutdown


If you at a point want to delete / uninstall the installed distribution you can do

# wsl –terminate Distro_Name
# wsl –uninstall Distro_Name


Or you if you want to do a cleanup of the stored files inside the installed distribution (if you have stored files), do:

# wsl –unregister Distro_Name


For more in depth details check out the manual
 

PS C:\Windows\System32\WindowsPowerShell\v1.0> wsl –help
Copyright (c) Microsoft Corporation. All rights reserved.
For privacy information about this product please visit https://aka.ms/privacy.

Usage: wsl.exe [Argument] [Options…] [CommandLine]

Arguments for running Linux binaries:

    If no command line is provided, wsl.exe launches the default shell.

    –exec, -e <CommandLine>
        Execute the specified command without using the default Linux shell.

    –shell-type <standard|login|none>
        Execute the specified command with the provided shell type.

    —
        Pass the remaining command line as-is.

Options:
    –cd <Directory>
        Sets the specified directory as the current working directory.
        If ~ is used the Linux user's home path will be used. If the path begins
        with a / character, it will be interpreted as an absolute Linux path.
        Otherwise, the value must be an absolute Windows path.

    –distribution, -d <Distro>
        Run the specified distribution.

    –user, -u <UserName>
        Run as the specified user.

    –system
        Launches a shell for the system distribution.

Arguments for managing Windows Subsystem for Linux:

    –help
        Display usage information.

    –debug-shell
        Open a WSL2 debug shell for diagnostics purposes.

    –install [Distro] [Options…]
        Install a Windows Subsystem for Linux distribution.
        For a list of valid distributions, use 'wsl.exe –list –online'.

        Options:
            –no-launch, -n
                Do not launch the distribution after install.

            –web-download
                Download the distribution from the internet instead of the Microsoft Store.

            –no-distribution
                Only install the required optional components, does not install a distribution.

            –enable-wsl1
                Enable WSL1 support.

    –manage <Distro> <Options…>
        Changes distro specific options.

        Options:
            –move <Location>
                Move the distribution to a new location.

            –set-sparse, -s <true|false>
                Set the vhdx of distro to be sparse, allowing disk space to be automatically reclaimed.

    –mount <Disk>
        Attaches and mounts a physical or virtual disk in all WSL 2 distributions.

        Options:
            –vhd
                Specifies that <Disk> refers to a virtual hard disk.

            –bare
                Attach the disk to WSL2, but don't mount it.

            –name <Name>
                Mount the disk using a custom name for the mountpoint.

            –type <Type>
                Filesystem to use when mounting a disk, if not specified defaults to ext4.

            –options <Options>
                Additional mount options.

            –partition <Index>
                Index of the partition to mount, if not specified defaults to the whole disk.

    –set-default-version <Version>
        Changes the default install version for new distributions.

    –shutdown
        Immediately terminates all running distributions and the WSL 2
        lightweight utility virtual machine.

    –status
        Show the status of Windows Subsystem for Linux.

    –unmount [Disk]
        Unmounts and detaches a disk from all WSL2 distributions.
        Unmounts and detaches all disks if called without argument.

    –uninstall
        Uninstalls the Windows Subsystem for Linux package from this machine.

    –update
        Update the Windows Subsystem for Linux package.

        Options:
            –pre-release
                Download a pre-release version if available.

    –version, -v
        Display version information.

Arguments for managing distributions in Windows Subsystem for Linux:

    –export <Distro> <FileName> [Options]
        Exports the distribution to a tar file.
        The filename can be – for stdout.

        Options:
            –vhd
                Specifies that the distribution should be exported as a .vhdx file.

    –import <Distro> <InstallLocation> <FileName> [Options]
        Imports the specified tar file as a new distribution.
        The filename can be – for stdin.

        Options:
            –version <Version>
                Specifies the version to use for the new distribution.

            –vhd
                Specifies that the provided file is a .vhdx file, not a tar file.
                This operation makes a copy of the .vhdx file at the specified install location.

    –import-in-place <Distro> <FileName>
        Imports the specified .vhdx file as a new distribution.
        This virtual hard disk must be formatted with the ext4 filesystem type.

    –list, -l [Options]
        Lists distributions.

        Options:
            –all
                List all distributions, including distributions that are
                currently being installed or uninstalled.

            –running
                List only distributions that are currently running.

            –quiet, -q
                Only show distribution names.

            –verbose, -v
                Show detailed information about all distributions.

            –online, -o
                Displays a list of available distributions for install with 'wsl.exe –install'.

    –set-default, -s <Distro>
        Sets the distribution as the default.

    –set-version <Distro> <Version>
        Changes the version of the specified distribution.

    –terminate, -t <Distro>
        Terminates the specified distribution.

    –unregister <Distro>
        Unregisters the distribution and deletes the root filesystem.
PS C:\Windows\System32\WindowsPowerShell\v1.0>

Once wsl is installed you can run it directly from Windows start menu, by searching for the name of the distribution you would like to run for example to run my Debian WSL running emulator::

Sum it up

What was shown up is how to run in parallel virtualized Linux distribution on Windows 10 and Windows 11 and how to install update to latest and run opensshd server to be able to ssh into the WSL Linux virtual machine remotely.
.Also i've shown you, How to test ssh is reachable and how to stop / start or destroy and cleanup any stored files for  VM if necessery, as well as how to apply some extra advanced configurations to boot VM for.

Using WSL is not the best virtualization ever but anyways it is an alternative for people employed in Domain attached Windows PCs part of Big Corporations, where VirtualBox use is blocked / prohibited and you still need to experiment or develop Shell scripts or software on Python / Perl / Ruby on Linux before you  do stuff on the PreProd or Production Linux host.

That's all folks, Enjoy ! 🙂
 

Recover lost / forgotten root password for CentOS 7 Linux / Boot CentOS 6 into Single User mode to reset admin pass

Friday, September 27th, 2024

centos-community-enterprise-operating-system-logo.

If you have some old CentOS 7 Virtual machine hanging for a long time and you don't remember the root password or you don't remember where you have stored it, but you have something important as data left over, you might need to recover root password for your CentOS 7 Virtual Machine.

I recently had to resolve that issue and here is the few easy steps to take to recover the lost root password.

Assuming you have tried to boot the VM and the VM boots fine and your few attempts to input manually some default passwords of yours failed, next 

1. Reboot the Virtual Machine to the GRUB boot menu

 

grub.png

The GRUB boot screen should appear and be there for few secs

2. Edit the boot loader kernel options ( add add rd.break enforcing=0 )

 

How to reset root password on CentOS Linux - Clouvider

Press 'e' to Edit the boot loader and modify the boot commands options passed to the linux kernel.

In GRUB edit mode:

add rd.break enforcing=0


to the end of the line starting with linux at the end of passed parameters list as shown in the picture.

When done editing, press Ctrl-x (Control button x key simultaneously) to boot with changed parameters.

ALTERNATIVE WAY TO BOOT THE SYSTEM INTO ROOT WITHOUT PASSWORD PROMPT:

Alternative options to use instead of add rd.break.enforcing=0 are to substitute the rhgb quiet kernel option with init=/bin/bash

Edit CentOS Grub Boot Menu Entries rhgb quiet options shot

Modify kernel parameters pass init=/bin/bash to kernel to boot emergency mode centos linux

 

As you might wonder for the meaning of the passed 2 parameters:

rd.break breaks the boot process at initramfs while
enforcing=0 disables the SELinux (which often enabled by default on CentOS).

Another way is to 

3. Boot in CentOS emergency mode and Reset the root password
 

When done editing, press Ctrl-x to boot with changed parameters.

As you might wonder for the meaning of the passed parameters:

rd.break breaks the boot process at initramfs while
enforcing=0 disables the SELinux (which often enabled by default on CentOS).

Whence system boots up with the modified kernel options cmd, the switch_root prompt will appear.
As the emerency mode boots the filesystem into read-only mode under /sysroot default directory, in order to be able to
modify the MD5 root password stored hash inside RO mounted /sysroot/etc/shadow you need to remount the Filesystme
in read-write mode.

To Remount the read-only file system /sysroot in write mode:

# mount -o remount,rw /sysroot

As the /sysroot is not the root directory to be able to use a standard passwd command you need to make /sysroot
as the default root folder for the booted linux by chrooting into it.
 

  • Generate MD5 password manually (for Hardcore masochistic admins 🙂 )

If you're a hard core linux sysadmin of course, generate your own new md5 password and directly modify /etc/shadow copy pasting the md5 string.

If you want to manually generate the md5 string, you can do it depending on the required encryption algorithm with:

For (md5, sha256, sha512) encrypted pass

# openssl passwd -6 -salt xyz  yourpass

For   (md5, sha256, sha512) encrypted pwd

# mkpasswd –method=SHA-512 –stdin

For (des, md5, sha256, sha512) encrypted pw

# perl -e 'print crypt("YourPasswd", "salt", "sha512"),"\n"'


Once the string is generated;

# vim  /etc/shadow


and exchange the old with new string for MD5

  • Change password with chroot (the easy common way)

remount read write the filesystem in emergency single user mode CentOS LINUX

# chroot /sysroot

That should drop you into another shell bash-4.x

 

Reset root user password in CentOS 7

# passwd
Changing password for user root.
New password:
Retype new password:

We need have to sync the entire filesystem we have to use the sync command, for novice sys admins who never heard about this command, below
short description:

The Linux sync command synchronizes cached data to permanent storage.
This data includes modified superblocks, modified inodes, delayed reads and writes, and others. sync uses several system calls:

sync()
syncfs()
fsync()
fdatasync()


For example, the sync command utilizes the sync() system call to write all buffered modifications to file data and metadata to an underlying storage device.

As a Linux systems administrator or developer, understanding the sync command can be crucial for efficient file synchronization. Additionally, sync can be helpful after crashes or when the file system becomes corrupted.

In this tutorial, we’ll explore the various aspects of the sync command. Also, we’ll see how we can use sync in different scenarios.

# sync

# exec /sbin/init

Try out the root password after booting normally into CentOS and the new set administrator pass should work.


Resetting forgotten (lost) root password on CentOS 6

The process is absolutely the same except on the Step 1 (in the modification of GRUB boot menu by pressing e key), add to

rhgb quiet

at the end one 'S'

This S character means 'boot CentOS into Single user mode'

rhgb quiet S

 

Go to single user mode on CentOS 6 Linux in boot loader S kernel setting

Then, press ENTER key and press b key to boot CentOS 6 into to single user mode.