Category Archives: Linux

Discover DevOps roles and learn Linux from basics to advanced at DevOpsRoles.com. Detailed guides and in-depth articles to master Linux for DevOps careers.

Install Gradle on CentOS

In this tutorial, How to install Gradle on CentOS. Gradle is a free and Open Source that helps your build, automate and deliver better software, faster.

Prerequisites

  • Server instance : CentOS 7
  • A sudo user.

Your System update

Login into the sudo user and run the following commands to update your system.

$ sudo yum -y install epel-release
$ sudo yum -y update
$ sudo reboot

Install JDK

Gradle requires Java Development Kit (JDK) 7 or higher in order to work. Link here

Download Gradle

In this guide, I use the “binary-only” archive. Link the Gradle release page to the latest version of Gradle. Using wget command to download Gradle.

$ cd /opt/
$ wget https://downloads.gradle-dn.com/distributions/gradle-5.6.2-bin.zip

Install Gradle on CentOS

Your run the command following.

$ sudo mkdir /opt/gradle
$ sudo unzip -d /opt/gradle gradle-5.6.2-bin.zip

Set the PATH environment for Gradle executable.

$ export PATH=$PATH:/opt/gradle/gradle-5.6.2/bin

To check if the Gradle install was successful.

$ gradle -v

Your system is now built the program with Gradle. Thank you for reading the DevopsRoles page!

Redis Install and Configure: Your Database and Cache System

Introduction

This tutorial is a Step-by-Step Guide to Redis Install and Configure. Now, let’s go Redis Install and Configure.

Dive into the efficient world of Redis with this detailed guide on installation and configuration on Linux systems. Whether you’re setting up Redis for the first time or optimizing an existing installation, this tutorial offers clear, step-by-step instructions to get Redis up and running smoothly on your server.

Redis

  • It is an Open Source.
  • In-memory data structure store.
  • Used as Database.
  • Cache and message broker.
  • Redis is a key-value pair cache and store

Redis is perfect for storing sessions. All operations are performed in memory, so reading and writing will be fast

Redis Install and Configure

Download Redis

Link latest Redis home here

$ cd /opt
$ wget http://download.redis.io/releases/redis-5.0.5.tar.gz
$ sudo tar zxvf redis-5.0.5.tar.gz
$ cd redis-5.0.5

Install Redis

$ sudo make test
$ sudo make
$ sudo make install

If the following error is in make test command as below.

You need tcl 8.5 or newer in order to run the Redis test
make[1]: *** [test] Error 1
make[1]: Leaving directory `/opt/redis-5.0.5/src'
make: *** [test] Error 2

You need to install tcl

$ sudo yum install -y tcl

Again install Redis

$ sudo make test

Error

Executing test client: couldn’t execute “src/redis-benchmark”: no such file or directory.

Then perform the following steps

$ sudo make distclean
$ sudo make
$ sudo make install

Configure Redis

$ sudo mkdir /etc/redis
$ sudo cp redis.conf /etc/redis/6379.conf
$ sudo vi /etc/redis/6379.conf

The information content 6379.conf file

$ cat /etc/redis/6379.conf | grep -v "#" | sed /^$/d
 bind 127.0.0.1
 protected-mode yes
 port 6379
 tcp-backlog 511
 timeout 0
 tcp-keepalive 300
 daemonize yes
 supervised no
 pidfile /var/run/redis_6379.pid
 loglevel notice
 logfile "/var/log/redis_6379.log"
 databases 16
 always-show-logo yes
 save 900 1
 save 300 10
 save 60 10000
 stop-writes-on-bgsave-error yes
 rdbcompression yes
 rdbchecksum yes
 dbfilename dump.rdb
 dir /etc/redis/
 replica-serve-stale-data yes
 replica-read-only yes
 repl-diskless-sync no
 repl-diskless-sync-delay 5
 repl-disable-tcp-nodelay no
 replica-priority 100
 maxmemory 10240000
 lazyfree-lazy-eviction no
 lazyfree-lazy-expire no
 lazyfree-lazy-server-del no
 replica-lazy-flush no
 appendonly no
 appendfilename "appendonly.aof"
 appendfsync everysec
 no-appendfsync-on-rewrite no
 auto-aof-rewrite-percentage 100
 auto-aof-rewrite-min-size 64mb
 aof-load-truncated yes
 aof-use-rdb-preamble yes
 lua-time-limit 5000
 slowlog-log-slower-than 10000
 slowlog-max-len 128
 latency-monitor-threshold 0
 notify-keyspace-events ""
 hash-max-ziplist-entries 512
 hash-max-ziplist-value 64
 list-max-ziplist-size -2
 list-compress-depth 0
 set-max-intset-entries 512
 zset-max-ziplist-entries 128
 zset-max-ziplist-value 64
 hll-sparse-max-bytes 3000
 stream-node-max-bytes 4096
 stream-node-max-entries 100
 activerehashing yes
 client-output-buffer-limit normal 0 0 0
 client-output-buffer-limit replica 256mb 64mb 60
 client-output-buffer-limit pubsub 32mb 8mb 60
 hz 10
 dynamic-hz yes
 aof-rewrite-incremental-fsync yes
 rdb-save-incremental-fsync yes

Create Deamon for Redis

$ sudo cp utils/redis_init_script /etc/init.d/redis
$ sudo chkconfig --add redis
$ sudo chkconfig redis on
$ sudo /etc/init.d/redis start

The Redis server has been installed on your system.

$ sudo netstat -nplt | grep 6379                                            
 tcp        0      0 127.0.0.1:6379              0.0.0.0:*                   LISTEN      11567/redis-server

For more advanced details the “redis.conf” file configuration item is described as follows:

When the client is idle for a long time, close the connection

timeout 300

Specify the logging level. Redis supports four levels: debug, verbose, notice, and warning. The default is verbose.

loglevel verbose

Set the number of databases, the default database is 0, you can use the “select DBID from v$database;” command to specify the database ID on the connection

databases 16

Set the IP address and port of the master service when the machine is slav service. When Redis starts, it will automatically synchronize data from the master.

slaveof <masterip> <masterport>

When the master service is password protected, the slav service connects to the master password.

masterauth <master-password>

Set the Redis connection password. If the connection password is configured, the client needs to provide the password through the AUTH command when connecting to Redis. The default is off.

requirepass abc

Set the maximum number of client connections at the same time. The default is unlimited.

maxclients 128

Specify the maximum memory limit of Redis. Redis will load the data into the memory at startup. After the maximum memory is reached, Redis will first try to clear the expired or expired Key. When this method is processed, the maximum memory setting is still reached. The write operation will no longer be possible, but the read operation will still be possible. Redis’ new VM mechanism will store the Key in memory and the value will be stored in the swap area.

maxmemory <bytes>

You can use the same configuration file between multiple Redis instances on the same host, and each instance has its own specific configuration file.

include /path/to/local.conf

Conclusion

Successfully installing and configuring Redis enhances your application’s performance by providing rapid data access. This guide aims to equip you with the knowledge to seamlessly integrate Redis into your system, ensuring optimal setup for a robust data management solution. Thank you for reading the DevopsRoles page!

sed command in Linux with Examples

The sed command is a stream editor for filtering and transforming text. In this tutorial, How to sed command in Linux with Examples.

The sed command-Line in Linux, which stands for “stream editor,” is a powerful text processing tool used for performing various text manipulations and transformations. It reads input line by line, applies specified operations, and outputs the result. Here are a few examples of how to use the sed command line:

Syntax

sed [OPTION]... {script-only-if-no-other-script} [input-file]...

On the man page, the describes it

  • sed – modifies lines from the specified File parameter according to an edit script and writes them to standard output.
  • man sed – More details information about the sed command.

The sed command in Linux with Examples

For example, the file sed_test.txt as below

[huupv@DevopsRoles vagrant]$ cat sed_test.txt                                                                                                                                  
# /etc/ntp.conf, configuration for ntpd; see ntp.conf(5) for help

driftfile /var/lib/ntp/ntp.drift

# Enable this if you want statistics to be logged.
#statsdir /var/log/ntpstats/

statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

# Specify one or more NTP servers.

# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
# on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for
# more information.
pool 0.ubuntu.pool.ntp.org iburst
pool 1.ubuntu.pool.ntp.org iburst
pool 2.ubuntu.pool.ntp.org iburst
pool 3.ubuntu.pool.ntp.org iburst

Append line

$ sed '/^pool 3/ a server ntp.devopsroes.com' sed_test.txt

Insert line

It will be added lines before the matching line.

$ sed '/^pool 3/i server ntp.devopsroles.com' sed_test.txt

Delete line

used d to delete matching lines. \s is escaped for regular expressions.

$ sed ' /^pool\s[0-9]\.ubuntu/d' sed_test.txt

How to write multi-line

There are two ways, use {} or other files.

Use {}

$ sed ' {
 /^pool 0/i server ntp.devopsroles.com
 /^pool\s[0-9]/d
 } ' ./sed_test.txt

create a ntp.sed file and read with the -f option.

The content ntp.sed file.

/^$/d
/^\s*#/d
/^pool 0/ i server ntp.devopsroles.com prefer
/^pool\s[0-9]\.ubuntu/d

Explain the above line.

/^$/d - Delete blank lines.
/^\s*#/d - Delete the line following # after any space including 0 (Delete comment line of #)

As a result

$ sed -f ntp.sed sed_test.txt

The backup file before changing the original file has been modified.

$ sed -i.bak -f ntp.sed ntp.conf

Print specific lines from a file

sed -n '2,5p' input_file

Delete lines matching a pattern

sed '/pattern/d' input_file

Append text after a specific line

sed '/pattern/a\new_line' input_file

Conclusion

sed Linux is a simple command in Linux. It uses the number of lines of files. These are just a few examples of how to use the sed command in Linux.

The sed command offers a wide range of text manipulation capabilities, including search and replace, insertions, deletions, and more. Thank you for reading the DevopsRoles page!

Minikube Build local Kubernetes environment

Introduction

In today’s DevOps-driven world, Kubernetes has become an essential tool for managing containerized applications at scale. However, setting up a full Kubernetes cluster can be complex and resource-intensive. How to Minikube Build local Kubernetes.

Minikube is a lightweight Kubernetes implementation that creates a local, single-node Kubernetes cluster for development and testing. In this guide, we’ll walk you through everything you need to know to build a local Kubernetes environment using Minikube, from basic setup to advanced configurations. In this tutorial, How to use Minikube Build local Kubernetes environment.

Why Use Minikube?

  • Ease of Use: Minikube simplifies the process of setting up a Kubernetes cluster.
  • Local Development: Ideal for local development and testing.
  • Resource Efficient: Requires fewer resources compared to a full-scale Kubernetes cluster.
  • Feature-Rich: Supports most Kubernetes features and add-ons.

Prerequisites

Before you start, ensure you have the following:

  • A computer with at least 2GB of RAM and 20GB of free disk space.
  • A hypervisor like VirtualBox, VMware, Hyper-V, or KVM.
  • kubectl, the Kubernetes command-line tool, was installed.
  • Minikube installed.

My Virtual Machine has installed Docker. Reference: Link here

Minikube Build local Kubernetes

Install Minikube and kubectl

Minikube

$ curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/

kubectl

$ curl -Lo kubectl https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && chmod +x kubectl && sudo mv kubectl /usr/local/bin/

Set of environment variables.

$ sudo vi /etc/profile

#Add end line in file
export MINIKUBE_WANTUPDATENOTIFICATION=false
export MINIKUBE_WANTREPORTERRORPROMPT=false
export MINIKUBE_HOME=/root
export CHANGE_MINIKUBE_NONE_USER=true
export KUBECONFIG=/root/.kube/config

$ sudo mkdir -p /root/.kube || true
$ sudo touch /root/.kube/config

Launch Minikube

You can use used "--vm-driver=none" option to build Kubernetes on the host running Minikube

$ sudo /usr/local/bin/minikube start --vm-driver=none

File /root/.kube/config have been created. verify the content

$ sudo kubectl config view

Check service minikube status

$ sudo minikube status

Allow port 8443 on the firewall

$ sudo firewall-cmd --add-port=8443/tcp --zone=public --permanent
$ sudo firewall-cmd --reload
$ sudo firewall-cmd --list-all

Create and start container dashboard

using image “k8s.gcr.io/echoserver:1.4” to create the dashboard

$ sudo docker images | grep 'k8s.gcr.io/echoserver'

Minikube created a pod

$ sudo kubectl run hello-minikube --image=k8s.gcr.io/echoserver:1.4 --port=808

To verify node and pod

$ sudo kubectl get nodes
$ sudo kubectl get pods

Instances run on nodes as Docker containers. Displays a list of deployments.

$ sudo kubectl get deployments

Creating service

You use "--type=NodePort" option. Open the service on the IP of each node to the static port (NordPort). A ClusterIP Service routed by the NodePort Service is automatically created. You can access the NordPort Service from outside the cluster by requesting :

$ sudo kubectl expose deployment hello-minikube --type=NodePort
$ sudo kubectl get services

Access dashboard

Get the dashboard URL. The port automatically changes one time.

$ sudo minikube dashboard --url
$ curl http://127.0.0.1:36439/api/v1/namespaces/kube-system/services/http:kubernetes-dashboard:/proxy/

When accessing via Kubernetes proxy

kubectl acts as a reverse proxy to the API endpoint.

$ sudo minikube dashboard --url
$ sudo kubectl proxy
$ curl http://localhost:8001

Accessible dashboard from outside

Minikube started with the "--vm-driver=none" option, it can only be accessed from the host OS using the proxy. Therefore, change the proxy settings so that they can be accessed from outside the host OS (browser).

$ sudo minikube dashboard --url
$ sudo kubectl proxy --address=0.0.0.0 --accept-hosts='.*'

Link URL: http://{YOUR_HOST_NAME}:8001/api/v1/namespaces/kube-system/services/http:kubernetes-dashboard:/proxy/#!/overview?namespace=default

The verify log

$ sudo kubectl logs hello-minikube-78c9fc5f89-9whkn
$ minikube logs -f 

Using kubectl command to delete service, deployment

$ sudo kubectl delete services hello-minikube
$ sudo kubectl delete deployment hello-minikube

Get status to have delete service, deployment

$ sudo kubectl get nodes
$ sudo kubectl get pods
$ sudo kubectl get services
$ sudo kubectl get deployments

Stop minikube and delete the cluster

$ sudo minikube stop
$ minikube delete

Conclusion

Minikube is an excellent tool for developers who want to learn and experiment with Kubernetes without the complexity of setting up a full-scale cluster. By following this guide, you can easily set up a local Kubernetes environment using Minikube, deploy applications, and explore advanced features. Whether you’re a beginner or an experienced developer, Minikube provides a convenient and efficient way to work with Kubernetes on your local machine.

How to set $PATH in Linux

In this tutorial, How to set $PATH in Linux. You may set the $PATH permanently in 2 ways:

  • Set PATH for Particular user.
  • or set a common path for ALL system users.

You need to make “.bash_profile” in-home directory in the user for set PATH Particular user as command below

[huupv@DevopsRoles vagrant]$ echo "export PATH=$PATH:/path/to/dir" >> /home/huupv/.bash_profile
[huupv@DevopsRoles vagrant]$ source /home/huupv/.bash_profile

Or set a common path for ALL system users, you need to set path as below

[root@DevopsRoles vagrant]# echo "export PATH=$PATH:/path/to/dir" >> /etc/profile
[root@DevopsRoles vagrant]# source /etc/profile

An example set a common path for ALL system users as the picture below

Conclusion

Thought the article, You can set PATH 2 way in Linux as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Install Minikube kubernetes on Centos

In this tutorial, How to install Minikube kubernetes to configure a single Node Cluster within a VM. How do I Configure Kubernetes which is a Docker Container system?

A Hypervisor supported by Minikube. In this example, Install KVM Hypervisor. You can use other Hypervisors such as VirtualBox, VMware Fusion v.v.

Install Minikube kubernetes

KVM Hypervisor installing

[root@DevopsRoles ~]# yum -y install qemu-kvm libvirt libvirt-python libguestfs-tools virt-install libvirt-daemon-kvm
[root@DevopsRoles ~]# systemctl start libvirtd
[root@DevopsRoles ~]# systemctl enable libvirtd

Add repository for configure Kubernetes and Install Minikube

Configure Kubernetes repository

[root@DevopsRoles ~]# cat <<'EOF' > /etc/yum.repos.d/kubernetes.repo

[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-$basearch
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF

Install Minikube

[root@DevopsRoles ~]# yum -y install kubectl
[root@DevopsRoles ~]# wget https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 -O minikube
[root@DevopsRoles ~]# wget https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-kvm2
[root@DevopsRoles ~]# chmod 755 minikube docker-machine-driver-kvm2
[root@DevopsRoles ~]# mv minikube docker-machine-driver-kvm2 /usr/local/bin/

Check version minikube

[root@DevopsRoles ~]# /usr/local/bin/minikube version
[root@DevopsRoles ~]# kubectl version -o json 

Start Minikube

[root@DevopsRoles ~]# minikube start --vm-driver kvm2 

Minikube the command line

#show status
[root@DevopsRoles ~]# minikube status
[root@DevopsRoles ~]# minikube service list 
[root@DevopsRoles ~]# minikube docker-env 
[root@DevopsRoles ~]# kubectl cluster-info 
[root@DevopsRoles ~]# kubectl get nodes 
[root@DevopsRoles ~]# virsh list
[root@DevopsRoles ~]# minikube ssh # possible to access with SSH to the VM
[root@DevopsRoles ~]# minikube stop # to stop minikube, do like follows
[root@DevopsRoles ~]# minikube delete  # to remove minikube, do like follows
[root@DevopsRoles ~]# virsh list --all 

Conclusion

Thought the article, How to install Minikube Kubernetes on Centos as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

How to Install PHP 7.3 on Centos 7

Introduction

In this tutorial, we’ll guide you through the straightforward process of install PHP 7.3 on CentOS 7. By default, CentOS 7 comes with PHP 5.4, but if you require PHP 7.3, it’s easily achievable using RPM packages. The initial step involves installing Remi’s Repository on CentOS. This repository serves as a valuable resource for obtaining the desired PHP version.

Follow the steps diligently to seamlessly upgrade and enhance your CentOS 7 server with PHP 7.3, unlocking improved features and performance. Stay tuned for a hassle-free installation that aligns with your development needs on CentOS 7.

Install PHP 7.3 on Centos 7

[vagrant@DevopsRoles ~]# yum --enablerepo=remi-safe -y install php73 php73-php-pear php73-php-mbstring

Check version PHP

[vagrant@DevopsRoles ~]# php73 -v 
[vagrant@DevopsRoles ~]# which php73
[vagrant@DevopsRoles ~]# ll /bin/php73

Load environment variables with the SCL tool

[vagrant@DevopsRoles ~]# scl enable php73 bash 
[vagrant@DevopsRoles ~]# php -v 

Start and enable php7.3

[vagrant@DevopsRoles ~]# systemctl start php73-php-fpm
[vagrant@DevopsRoles ~]# systemctl enable php73-php-fpm
[vagrant@DevopsRoles ~]# systemctl restart httpd 

create phpinfo to verify php

[vagrant@DevopsRoles ~]# echo '<?php phpinfo(); ?>' > /var/www/html/info.php 
[vagrant@DevopsRoles ~]# curl http://localhost/info.php | grep 'PHP Version' | tail -1 | sed -e 's/<[^>]*>//g' 

Consider this option if you want to utilize PHP 7.3 for both Apache and Nginx.

[vagrant@DevopsRoles ~]# yum --enablerepo=remi-safe -y install php73-php-fpm php73-php

Conclusion

Congratulations, you’ve successfully installed PHP 7.3 on CentOS/RHEL! ? Thank you for being a part of the DevopsRoles page!

Add Repositories on Linux

Introduction

In this tutorial, How to add Repositories on Linux. How to add some useful external repositories for RHEL/Centos or Ubuntu/Debian.

Repositories are essential in Linux systems for accessing and installing software packages. By adding repositories, you gain access to a broader range of applications and updates, ensuring your system stays secure and up-to-date. In this guide, we’ll walk you through the process of adding repositories on Linux, covering various package managers like APT, YUM, and Zypper. Whether you’re a beginner or an advanced user, this tutorial will help you effectively manage repositories and optimize your Linux experience.

The procedure to enable repository as follows

  • Open a shell prompt
  • Install repositories
  • Refresh repository

Add Repositories on Linux

Add Repositories for Centos

1. Install a plugin to add priorities

[vagrant@DevopsRoles ~]# yum -y install yum-plugin-priorities
[vagrant@DevopsRoles ~]# sed -i -e "s/\]$/\]\npriority=1/g" /etc/yum.repos.d/CentOS-Base.repo

2. Add Repositories

EPEL Repository

[vagrant@DevopsRoles ~]# yum -y install epel-release
[vagrant@DevopsRoles ~]# sed -i -e "s/\]$/\]\npriority=5/g" /etc/yum.repos.d/epel.repo

Another add Remi’s RPM Repository

[vagrant@DevopsRoles ~]# yum -y install http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
# set [priority=10]
[vagrant@DevopsRoles ~]# sed -i -e "s/\]$/\]\npriority=10/g" /etc/yum.repos.d/remi-safe.repo

Note: if [enabled=0], To use the repository use command below

[vagrant@DevopsRoles ~]# yum --enablerepo=epel install [Package]

Refresh Repositories

[vagrant@DevopsRoles ~]# yum repolist

Add Repositories for Ubuntu & Debian

Using add-apt-repository command

The syntax

add-apt-repository ppa:<ppa_name>

Example,

[vagrant@DevopsRoles ~]$ sudo add-apt-repository ppa:libreoffice/ppa

Fix add-apt-repository: command not found error

[vagrant@DevopsRoles ~]$ sudo apt-get install software-properties-common
[vagrant@DevopsRoles ~]$ sudo apt-get update

Conclusion

Thought the article, How to Add Repositories on Linux as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

How to Install and configure ssh server on Centos 7

Introduction

In this tutorial, we will install and configure the SSH server on CentOS 7. SSH, also known as Secure Socket Shell, is a network protocol that allows for secure remote login from one computer to another. It provides system administrators a secure way to access a server remotely.

Prerequisites

Before we start, ensure you have:

  • A CentOS 7 server with a non-root user having sudo privileges.
  • Internet access to download the necessary packages.

Install and configure SSH server on Centos 7

Installing SSH Server

Step 1: Update Your System

First, update your system to ensure all existing packages are up-to-date:

sudo yum update -y

Step 2: Install OpenSSH Server

Install OpenSSH, the most popular SSH server package:

sudo yum install -y openssh openssh-server openssh-clients openssl-libs

Starting and Enabling SSH Service

Once the installation is complete, start the SSH service and enable it to start on boot.

Step 3: Start SSH Service

Start the SSH service using the command:

sudo systemctl start sshd

Step 4: Enable SSH Service

Enable the SSH service to start automatically on system boot:

sudo systemctl enable sshd

Step 5: Check SSH Service Status

Verify the SSH service status with:

sudo systemctl status sshd

Configuring SSH Server

Basic Configuration

The SSH server configuration file is located at /etc/ssh/sshd_config. You can edit this file to customize the SSH server settings.

Step 6: Open SSH Configuration File

Open the SSH configuration file with a text editor:

sudo vi /etc/ssh/sshd_config

Step 7: Disable Root Login

For security reasons, it is recommended to disable root login. Find and change the following line:

PermitRootLogin no

Step 8: Save and Exit

Save the changes and exit the editor. In vi, you can do this by pressing Esc, typing :wq, and hitting Enter.

Step 9: Restart SSH Service

After making the changes, restart the SSH service:

sudo systemctl restart sshd

Step 10: Allow SSH Through the Firewall

If Firewalld is running, allow SSH port 22/tcp:

sudo firewall-cmd --add-service=ssh --permanent
sudo firewall-cmd --reload

Advanced Configuration

For advanced users, additional configuration options can further secure your SSH server.

Step 11: Configure Public Key Authentication

Public key authentication is more secure than password authentication. Ensure the following lines are set in the configuration file:

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

Step 12: Configure Two-Factor Authentication

Two-factor authentication adds an extra layer of security. You can set it up by installing and configuring google-authenticator.

sudo yum install google-authenticator -y google-authenticator

Follow the prompts to set up two-factor authentication.

Step 13: Restrict SSH Access by IP Address

You can limit SSH access to specific IP addresses by adding the following lines:

AllowUsers yourusername@192.168.1.100
DenyUsers baduser@192.168.1.*

Configuring SSH Client

Step 14: Install SSH Client

To connect to the SSH server, install the SSH client:

sudo yum -y install openssh-clients

Step 15: Connect to SSH Server

Use a common user to connect to the SSH server:

ssh yourusername@your_server_ip

Replace yourusername with your actual username and your_server_ip with the server’s IP address.

Transferring Files Using SSH

Using SCP (Secure Copy)

SCP allows for secure file transfer between the local machine and the remote server.

Step 16: Copy the File to the Remote Server

scp ./localfile.txt yourusername@your_server_ip:/remote/directory/

Step 17: Copy the File from the Remote Server

scp yourusername@your_server_ip:/remote/directory/remotefile.txt ./localdirectory/

Using SFTP (SSH File Transfer Protocol)

SFTP is another method for secure file transfer. It is typically enabled by default.

Step 18: Connect to SFTP

sftp yourusername@your_server_ip

Step 19: Common SFTP Commands

  • Show the current directory on the remote server: pwd
  • Show the current directory on the local server: !pwd
  • List files in the current directory on the remote server: ls -l
  • List files in the current directory on the local server: !ls -l
  • Change the directory on the remote server: cd /remote/directory/
  • Upload a file to the remote server: put localfile.txt remotefile.txt
  • Download a file from the remote server: get remotefile.txt localfile.txt
  • Delete a directory on the remote server: rmdir directoryname
  • Delete a file on the remote server: rm filename
  • Execute commands on the local server: !command
  • Exit SFTP: quit

SSH Key-Pair Authentication

Step 20: Create SSH Key Pair

Generate a new SSH key pair on the client machine:

ssh-keygen -t rsa

Step 21: Move the Public Key to the Authorized Keys

Move the generated public key to the server’s authorized keys file:

mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys

Step 22: Secure the .ssh Directory

mkdir ~/.ssh
chmod 700 ~/.ssh

Step 23: Transfer the Secret Key to the Client

Copy the secret key from the server to the client’s SSH directory:

scp yourusername@your_server_ip:/home/yourusername/.ssh/id_rsa ~/.ssh/

Step 24: Connect Using SSH Key

ssh -i ~/.ssh/id_rsa yourusername@your_server_ip

Step 25: Disable Password Authentication

Disable password authentication for enhanced security. Edit the SSH configuration file:

PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM yes

Restart the SSH service:

sudo systemctl restart sshd

Common Issues and Troubleshooting

Issue 1: Connection Refused

If you encounter a “Connection refused” error, check if the SSH service is running and the firewall settings allow SSH traffic:

sudo systemctl status sshd
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload

Issue 2: Permission Denied

If you see a “Permission denied” error, ensure your user has the correct permissions and the SSH keys are correctly configured.

Issue 3: SSH Service Not Starting

If the SSH service fails to start, check the configuration file for syntax errors using:

sudo sshd -t

FAQs

Q: How do I restart the SSH service?

A: You can restart the SSH service using:

sudo systemctl restart sshd

Q: How do I check the SSH server version?

A: Check the SSH server version with:

ssh -V

Q: Can I use SSH keys for authentication?

A: Yes, SSH keys provide a secure way of authentication. Follow the steps in the advanced configuration section to set it up.

Conclusion

Setting up and configuring an SSH server on CentOS 7 is a crucial skill for system administrators. This guide covered everything from basic installation to advanced configuration, ensuring your SSH server is secure and efficient. By following these steps, you can enhance your server’s security and manage it remotely with ease. Thank you for reading the DevopsRoles page!

Install Chrony and Configure NTP server

In this tutorial, How to Install Chrony and Configure NTP server in Linux. Chrony is used to sync the system clock from different NTP servers.

Chrony with two programs: chronyc is the command-line interface for chrony and chronyd is the daemon that can be started at boot time.

Install chrony

# yum -y install chrony    # CentOS/RHEL
# apt install chrony       # Debian/Ubuntu
# dnf -y install chrony    # Fedora 22+

Configure chrony

[vagrant@DevopsRoles ~]$ sudo vi /etc/chrony.conf

Example add lines as below

# change servers for synchronization
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
server 0.asia.pool.ntp.org
server 1.asia.pool.ntp.org
server 2.asia.pool.ntp.org
server 3.asia.pool.ntp.org
# Allow NTP client access from local network.
allow 10.0.2.0/24

Start and enable daemon upon boot

[vagrant@DevopsRoles ~]$ sudo systemctl start chronyd 
[vagrant@DevopsRoles ~]$ sudo systemctl enable chronyd

If Firewalld is running, allow port 123/UDP.

[vagrant@DevopsRoles ~]$ sudo firewall-cmd --add-service=ntp --permanent 
[vagrant@DevopsRoles ~]$ sudo firewall-cmd --reload

Check Chrony Synchronization

[vagrant@DevopsRoles ~]$ chronyc sources
[vagrant@DevopsRoles ~]$ chronyc tracking

Conclusion

You have installed Chrony and Configured the NTP server. I hope will this your helpful. Thank you for reading the DevopsRoles page!