Bash script ssh failed login attempts

In Centos or RHEL, ssh failed login attempts are recorded in /var/log/secure file. Bash script the essential for DevOps Roles. You can ref to Bash script tutorial.

[huupv@localhost ~]$ sudo egrep "Failed password" /var/log/secure

To display a list of IP address ssh failed login attempts

[huupv@localhost ~]$ sudo egrep "Failed password" /var/log/secure | awk '{print $9 ": " $11}' | cut -d ';' -f1 | sed '/^\s*$/d' | uniq -c | sort -nr

I share bash script ssh failed login attempts on Linux. Checking log real time when user login into your system. In my bash script, I written three function : f_check_folder , f_get_log and f_failed_ssh. Running bash script with user root or user privilege.

Bash script ssh failed login attempts

#!/bin/bash
FILE1=/var/log/secure
FOLDER=/tmp/failed_ssh
TEMP_LOG=$FOLDER/tmp_secure.log
NUMBER=/tmp/failed_ssh/number.txt

####################
echo "HOSTNAME: `hostname`"

###################

f_check_folder () {
if [[ -d $FOLDER ]]; then
if [[ ! -s $NUMBER ]]; then
  touch $NUMBER
  echo 0 > $NUMBER
fi
else
  mkdir -p $FOLDER
  touch $NUMBER
  echo 0 > $NUMBER
fi
}

f_get_log () {
NUM=`cat $NUMBER`
SUM=`expr "$NUM" + 1`
tail -n +"$SUM" $FILE1 > $TEMP_LOG
echo `wc -l < $FILE1` > $NUMBER
}

f_failed_ssh () {

sudo egrep "Failed password" $TEMP_LOG | awk '{print $9 ": " $11}' | cut -d ';' -f1 | sed '/^\s*$/d' | uniq -c | sort -nr

}
f_check_folder
f_get_log
f_failed_ssh

The screen output terminal:

Conclusion

Thought the article, you can use Bash script ssh failed login attempts. I hope will this your helpful.

How to use Bash read file line by line

Introduction

In this tutorial, we will explore a simple and effective method to achieve this using Bash scripting. I use while..do..done use bash read file line by line on a Linux system. you can refer to the Bash script tutorial.

Bash, the default shell for most Unix-based operating systems, is a powerful tool for automating tasks and managing files and directories. One common task is reading a file line by line, which can be handy for various purposes, such as data processing, log analysis, and more.

Prerequisites

  • A Unix-like operating system (Linux or macOS) with Bash installed.
  • A text file that you want to read line by line. You can use any plain text file for this tutorial.

To read a file line by line using Bash, you can use a combination of the while loop and the read command. Here’s an example:

Bash read file line by line

For Example 1:

Using bash to read file.txt file.

[huupv@huupv devopsroles]$ cat file.txt 
Huu 30
Phan 28
foo 00

The content bash_read_file.sh file

#!/bin/bash
#To take a filename as an argument
filename="$1"
while read -r name age
do
  _NAME="$name"
  _AGE="$age"
  echo "Name read from file - ${_NAME}"
  echo "${_NAME}: Age is - ${_AGE}"
done < "$filename"

Explain it:

  • filename=$1 This line assigns the value of the first command-line argument to the filename variable. 
  • The -r option prevents backslash characters from being interpreted as escape characters.
  • done < $filename This line marks the end of the loop. The < symbol is used to redirect the contents of the file specified  "$filename" as the input for the while loop. Each line will be read and processed until the end of the file is reached.

To change mode execute and run the bash script

[huupv@huupv devopsroles]$ chmod +x bash_read_file.sh
[huupv@huupv devopsroles]$ ./bash_read_file.sh file.txt

The screen terminal:

Name read from file - Huu
Huu: Age is - 30
Name read from file - Phan
Phan: Age is - 28
Name read from file - foo
foo: Age is - 00

For example 2

Bash script read /etc/passwd file with fields: filed1 filed2 filed3 filed4 filed5 filed6 filed7

The content bash_read_file.sh file

#!/bin/bash
#Another thing is to take a filename as an argument.
filename="$1"
IFSOLD=$IFS
IFS=:
while read -r field1 field2 field3 field4 field5 field6 field7
do
  #display fields in /etc/passwd file
  printf 'Username: %s \t Shell: %s \t Home Dir: %s\n' "$field1" "$field7" "$field6"

done < "$filename"
IFS=$IFSOLD

The while loop reads each line from the file using the read command. The IFS= read -r field command ensures that leading and trailing whitespaces are preserved in each line.

The screen output terminal:

Conclusion

Through the article, you can use Bash read file line by line. By following these steps, you can effectively read a file line by line in Bash. 

Reading a file line by line in Bash is a fundamental skill that comes in handy for various scripting and automation tasks. With the while loop and the read command, you can efficiently process the contents of a file one line at a time, making it easier to work with large datasets, log files, and more. I hope will this your helpful.

How to install Git 2.18 on CentOS

Git is an open-source distributed version control system. In this tutorial, I will install Git 2.18 client on Centos.

CentOS’s default package repositories might not always have the latest version of Git available.

Here’s how you can install Git 2.18 on CentOS:

Jenkins release the source error code as below:

/remotes/origin/*" returned status code 128: error: The requested URL returned error: 401 while accessing https://github.com/xxx/xxx/info/refs
fatal: HTTP request failed

Solve problem Required Git >= 1.7.10

Step 1: Install the required packages

Before installing git makes sure you have installed in the package your system.

yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
yum install gcc perl-ExtUtils-MakeMaker

Step 2: Install git on Centos

Downloading Git source code from kernel git

cd /usr/src
wget https://www.kernel.org/pub/software/scm/git/git-2.18.0.tar.gz
tar xvzf git-2.18.0.tar.gz

After extracting the git source code and compiling the source code as below:

cd git-2.18.0
make prefix=/usr/local/git all
make prefix=/usr/local/git install

Step 3: Setup Environment

After the installation completes, you might need to update your system’s PATH environment variable to include the Git binary directory. Add the following line to your shell configuration file (e.g., .bashrc, .bash_profile, or .profile):

Set the PATH variable and reload the change in the current environment

echo "export PATH=/usr/local/git/bin:$PATH" >> /etc/bashrc

To apply the updated PATH configuration, either restart your shell session or run the following command:

After completing the steps. Verify that Git has been installed correctly by running:

git --version

Conclusion

Through the article, you should be able to manually build and install Git version 2.18.0 on CentOS. However, it’s worth noting that using the package manager or a more recent pre-built version from official repositories is generally recommended for easier maintenance and updates. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Oracle create schema: A Step-by-Step Guide

Introduction

A schema is defined as a user that owns data such as tables, indexes, and so forth. In this tutorial, How to use Oracle create schema.

Dive into the world of Oracle with this practical guide on creating schemas. This tutorial walks you through the essential steps to establish a schema in Oracle Database, starting with creating a tablespace, defining a new user, and culminating in setting up a test table. Ideal for database administrators and developers who want to streamline their database structure and enhance data management.

Oracle create schema

Access the Oracle database with permission privileges for creating a tablespace, creating a user, and creating a table on the Oracle Database.

[oracle@DBOracle ~]$ sqlplus / as sysdba

Step 1: Create tablespace on Oracle Database

Before creating a schema you need to create a file ( one or more files) for the schema to place its data into. This file schema writes data is called a tablespace. One tablespace has one or more datafile.

SQL> create tablespace datafile_test datafile '/U02/datafile_test_01.dbf' size 1000M extent management local autoallocate segment space management auto;

Step 2: Oracle Create a new user

The explain use command creates a user in Oracle

User: HuuPV
Password: pwd4HuuPV
Default Tablespace: datafile_test
Temporary Tablespace: TEMP

SQL> CREATE USER HuuPV IDENTIFIED BY pwd4HuuPV DEFAULT TABLESPACE datafile_test TEMPORARY TABLESPACE TEMP;

Oracle Privileges Granted to the APPDEV Role

SQL> GRANT CONNECT TO HuuPV;
SQL> GRANT UNLIMITED TABLESPACE TO HuuPV;
SQL> GRANT CREATE TABLE TO HuuPV;
SQL> GRANT CREATE PROCEDURE TO HuuPV;
SQL> GRANT CREATE VIEW TO HuuPV;
SQL> GRANT CREATE TRIGGER TO HuuPV;
SQL> GRANT CREATE SEQUENCE TO HuuPV;
SQL> GRANT CREATE SYNONYM TO HuuPV;

Step 3: Oracle creates a table for the test

SQL> create table test (NAME varchar2(32), AGE number);
SQL> insert into test (NAME, AGE) values ('HuuPV', 29);
SQL> insert into test (NAME, AGE) values ('Huu', 30);
SQL> commit;

Examine the content of the table test created above

SQL> select * from test;

The result created a table for the test

Oracle create schema another method uses the script oracle_create_user.sql  file

The content oracle_create_user.sql file

CREATE USER HuuPV IDENTIFIED BY pwd4HuuPV DEFAULT TABLESPACE datafile_test TEMPORARY TABLESPACE TEMP;
GRANT CONNECT TO HuuPV;
GRANT UNLIMITED TABLESPACE TO HuuPV;
GRANT CREATE TABLE TO HuuPV;
GRANT CREATE PROCEDURE TO HuuPV;
GRANT CREATE VIEW TO HuuPV;
GRANT CREATE TRIGGER TO HuuPV;
GRANT CREATE SEQUENCE TO HuuPV;
GRANT CREATE SYNONYM TO HuuPV;

Running script oracle_create_user.sql file

SQL>@/home/oracle/scripts/oracle_create_user.sql

Conclusion

By following the steps outlined in this guide, you’ve learned how to create an Oracle schema effectively. This foundation is crucial for managing and organizing data in Oracle databases efficiently, providing you with the skills to maintain a robust database environment.

My topic is “Install Oracle Database 12c on Centos 7“. I hope you find this helpful.

Install Oracle Database 12c on Centos 7

Oracle Database is a relational database management system (RDBMS) from the Oracle Corporation. I will guide Install Oracle Database 12c on centos 7 for Dev Environment step by step.

Step 1: Intro

My system is as below:

[root@DBOracle ~]# hostnamectl
Static hostname: DBOracle.DevopsRoles.local
Icon name: computer-vm
Chassis: vm
Machine ID: 248dbd1f6d5b4bbb85e743d11d4e994e
Boot ID: 7eded015f6a242e9a9e8c982d754cc26
Virtualization: kvm
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7
Kernel: Linux 3.10.0-862.6.3.el7.x86_64
Architecture: x86-64

Prerequisites

  • The firewall allows port Oracle Database
  • SELinux allows Oracle Database

In this guide, I will stop the firewall and SELinux disable mode 🙂 for a test install Oracle Database.

Step 2: Prepare to install Oracle database 12c step-by-step

Install required packages

[root@DBOracle ~]# yum install -y binutils.x86_64 compat-libcap1.x86_64 gcc.x86_64 gcc-c++.x86_64 glibc.i686 glibc.x86_64 \
glibc-devel.x86_64 ksh compat-libstdc++-33 libaio.i686 libaio.x86_64 libaio-devel.i686 libaio-devel.x86_64 \
libgcc.x86_64 libstdc++.i686 libstdc++.x86_64 libstdc++-devel.i686 libstdc++-devel.x86_64 libXi.i686 libXi.x86_64 \
libXtst.x86_64 make.x86_64 sysstat.x86_64 zip unzip smartmontools net-tools

Create user and group for Oracle Database

[root@DBOracle ~]# groupadd oinstall
[root@DBOracle ~]# groupadd dba
[root@DBOracle ~]# useradd -g oinstall -G dba oracle
[root@DBOracle ~]# passwd oracle

Add the parameters to the /etc/sysctl.conf as below

fs.aio-max-nr = 1048576
fs.file-max = 6815744
kernel.shmall = 2097152
kernel.shmmax = 1987162112
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default = 262144
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 1048586

Check and apply the new value-add parameters atop

sysctl -p
sysctl -a

the limit for Oracle users in /etc/security/limits.conf file

oracle soft nproc 2047
oracle hard nproc 16384
oracle soft nofile 1024
oracle hard nofile 65536
#Oracle recommended value for stack is set to 10240 for user oracle
oracle soft stack 10240

Oracle installation requires GUI access. I will install an X Window System on the Server Oracle Database

[root@DBOracle ~]# yum groupinstall -y "X Window System"

The use command below, to access to install Oracle databases in Step 3

ssh -X oracle@192.168.1.114

Download Oracle Databases

If you do not have an Oracle account yet, then register one to download it!

[root@DBOracle ~]# cd ~oracle/
[root@DBOracle ~]# unzip linuxx64_12201_database.zip -d /stage
[root@DBOracle ~]# chown -R oracle:oinstall /stage/database

Create folder U01 for Oracle installation files and folder U02 for the Oracle database files.

[root@DBOracle ~]# mkdir -p /U01 /U02

Change the owner and group of the new folder and set permissions to ‘755’

[root@DBOracle ~]# chown -R oracle:oinstall /U01 /U02
[root@DBOracle ~]# chmod -R 775 /U01 /U02
[root@DBOracle ~]# chmod g+s /U01 /U02

Yeah! let’s go install Oracle Database 12c. Are you ready

Step 3: Install Oracle Database 12c

From the client open a new terminal and connect to the server Oracle database.

ssh -X oracle@192.168.1.114

Install Oracle Database 12c as below:

[root@DBOracle ~]# cd /stage/database
[root@DBOracle ~]# ./runInstaller

The display terminal is as below:

Starting Oracle Universal Installer...

Checking Temp space: must be greater than 500 MB. Actual 26587 MB Passed
Checking swap space: must be greater than 150 MB. Actual 9535 MB Passed
Checking monitor: must be configured to display at least 256 colors. Actual 16777216 Passed
Preparing to launch Oracle Universal Installer from /tmp/OraInstall2018-07-05_10-20-03PM. Please wait ...

The installation GUI Oracle Database 12c as the picture below:

Select Installation Option

The choice “Create and configure a database” –> Next

Configure Security Updates

For Dev Environment

  • Email: None
  • Uncheck: I wish to receive security updates via My Oracle Support

For Production Environment

  • Email: Input your email
  • Check: I wish to receive security updates via My Oracle Support
  • My Oracle Support Password: Input your password

Select System Class

For Dev Environment

  • The choice ” Desktop class” –> Next

For production Environment

  • The choice “Server class” –> Next

Typical Install Configuration

  • Oracle base: /U01/home/oracle/app/oracle
  • Software location: /U01/home/oracle/app/oracle/product/12.2.0/dbhome_1
  • Database file location: /U02
  • Global database name: DevopsRoles
  • Password: DevopsRoles123
  • Uncheck: Create a Container database

Create Inventory

Summary

Install Product

During installation display pop-up as below

Open a new terminal and Login the root account into the server Oracle Database run two commands in the pop-up as below:

# bash /U01/home/oracle/app/oraInventory/orainstRoot.sh
# bash /U01/home/oracle/app/oracle/product/12.2.0/dbhome_1/root.sh

The picture runs commands as below:

Finish

Install Oracle Database 12c on Centos 7

Step 4: Testing login Oracle databases 12c

The Oracle installation is finished.

ssh root@192.168.1.114
su - oracle

To execute the command below to set the Oracle environment

export ORACLE_SID=DevopsRoles
export ORACLE_HOME=/U01/home/oracle/app/oracle/product/12.2.0/dbhome_1
export PATH=$PATH:$ORACLE_HOME/bin

Another method set the Oracle environment without losing it after the server Oracle reboot

[root@DBOracle ~]# su - oracle
[oracle@DBOracle ~]$ vi ~/.bash_profile

Add lines set Oracle end of the line in the bash_profile file

#Oracle environment
export ORACLE_SID=DevopsRoles
export ORACLE_HOME=/U01/home/oracle/app/oracle/product/12.2.0/dbhome_1
export PATH=$PATH:$ORACLE_HOME/bin

To apply the changeset Oracle environment

[oracle@DBOracle ~]$ source ~/.bash_profile

Access the Oracles database with permission privileges

sqlplus / as sysdba

Oracle uses default users. To change the default username ‘sys’

alter user sys identified by yourpassword;

Now, access the Oracle database web-based. Open your web browser https://192.168.1.114:5500/em/

Login Oracle database

User: system
Password: you have set up in step 3

Conclusion

Through the article, you have Install Oracle Database 12c on Centos 7. I hope will this your helpful. Thank you for reading the DevopsRoles page!

How to install Jenkins on centos 7

Jenkins is an open source Continuous Integration. In this article, I will guide you install jenkins on centos 7. The best way to increase my DevOps skill.

You must have to install Jenkins as below:

  • OS: Centos/Redhat or Ubuntu
  • Login into your Virtual Machine as a non-root user
  • To update packages your system ( option )
  • Checking Java JDK your system
  • Firewall open 8080 port

Install Jenkins on centos 7

Update your system

sudo yum install epel-release
sudo yum update

To install Java

sudo yum install java-1.8.0-openjdk.x86_64

After installing Java, you can confirm it.

java -version

Tell you about Java runtime environment

[huupv@localhost ~]$ java -version
openjdk version "1.8.0_171"
OpenJDK Runtime Environment (build 1.8.0_171-b10)
OpenJDK 64-Bit Server VM (build 25.171-b10, mixed mode)

you need to set “JAVA_HOME” and “JRE_HOME”.

sudo cp /etc/profile /etc/profile_backup
echo 'export JAVA_HOME=/usr/lib/jvm/jre-1.8.0-openjdk' | sudo tee -a /etc/profile
echo 'export JRE_HOME=/usr/lib/jvm/jre' | sudo tee -a /etc/profile
source /etc/profile

To check “JAVA_HOME” and “JRE_HOME”

[huupv@localhost ~]$ echo $JAVA_HOME
/usr/lib/jvm/jre-1.8.0-openjdk
[huupv@localhost ~]$ echo $JRE_HOME
/usr/lib/jvm/jre

To install Jenkins

Installing Jenkins a stable version

sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat-stable/jenkins.repo
sudo rpm --import https://jenkins-ci.org/redhat/jenkins-ci.org.key
sudo yum install jenkins

Start Jenkins server and set it to run at boot time:

sudo systemctl start jenkins.service
sudo systemctl enable jenkins.service

Firewall open 8080 port

Allow access to Jenkins via 8080 port

sudo firewall-cmd --zone=public --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

Access Jenkins from your web browser

http://<your-server-IP>:8080

How to “Unlock Jenkins”?

To use grep password as below:

[huupv@localhost ~]$ sudo cat /var/log/jenkins/jenkins.log | grep password -A 3

The output below:

Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:

f86044f712924b29b9420213c7a66133

jenkins default password centos: f86044f712924b29b9420213c7a66133

You are complete installed Jenkins on centos 7 as the picture below:

Conclusion

You have to install Jenkins on centos 7. I hope will this your helpful. Thank you for reading the DevopsRoles page!

How to Concatenate and Split Strings in Python

Introduction

Python is a versatile and powerful programming language widely used for various applications, from web development to data analysis. One of the fundamental skills in Python is string manipulation, particularly concatenating and splitting strings. This article will guide you through the basics and more advanced techniques for concatenate and Split Strings in Python, complete with practical examples and frequently asked questions.

What is String Concatenation?

String concatenation is the process of joining two or more strings end-to-end to form a single string. This operation is common in programming when constructing messages, creating paths, or merging data.

Basic String Concatenation in Python

In Python, there are several ways to concatenate strings. Let’s start with the most basic methods:

Using the + Operator

The + operator is the simplest way to concatenate strings in Python.

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World

Using the join() Method

The join() method is useful when you need to concatenate multiple strings from a list or tuple.

words = ["Hello", "World"]
result = " ".join(words)
print(result) # Output: Hello World

Using Formatted String Literals (f-strings)

Introduced in Python 3.6, f-strings provide a readable and concise way to concatenate strings.

name = "Alice"
greeting = f"Hello, {name}!"
print(greeting) # Output: Hello, Alice!

Advanced String Concatenation Techniques

Using the % Operator

The % operator, also known as the string formatting operator, is an older method for concatenating strings.

name = "Bob"
age = 25
result = "My name is %s and I am %d years old." % (name, age)
print(result) # Output: My name is Bob and I am 25 years old.

Using the format() Method

The format() method allows for more complex string formatting and concatenation.

name = "Carol"
age = 30
result = "My name is {} and I am {} years old.".format(name, age)
print(result) # Output: My name is Carol and I am 30 years old.

What is String Splitting?

String splitting is the process of breaking down a string into a list of substrings based on a delimiter. This is particularly useful when parsing data from files, user input, or network responses.

Basic String Splitting in Python

Using the split() Method

The split() method is the most common way to split strings in Python.

sentence = "Hello World"
words = sentence.split()
print(words) # Output: ['Hello', 'World']

Splitting with a Specific Delimiter

You can specify a delimiter to split the string by passing it as an argument to the split() method.

data = "apple,banana,cherry"
fruits = data.split(',')
print(fruits) # Output: ['apple', 'banana', 'cherry']

Advanced String Splitting Techniques

Using Regular Expressions

For more complex splitting patterns, you can use the re module.

import re

text = "one1two2three3"
result = re.split(r'\d', text)
print(result) # Output: ['one', 'two', 'three', '']

Limiting Splits

You can limit the number of splits by passing a second argument to the split() method.

data = "apple,banana,cherry,dates"
fruits = data.split(',', 2)
print(fruits) # Output: ['apple', 'banana', 'cherry,dates']

Practical Example

In this tutorial, we will demonstrate how to split and concatenate a string in Python using a practical example.

Example

Given an initial string Dev,Ops,R,o,l.e.s.com, we will split it and then concatenate the parts to form a new string "DevOpsRolescom".

string = "Dev,Ops,R,o,l.e.s.com"
print("Initial Strings: {}".format(string))

cleanstring = ''
for i in range(len(string)):
if string[i].isalpha():
cleanstring += string[i]

newcleanstring = str(cleanstring)
print("New Strings: {}".format(newcleanstring))

Output:

Initial Strings: Dev,Ops,R,o,l.e.s.com
New Strings: DevOpsRolescom

This example shows how to filter out only the alphabetic characters from the initial string and concatenate them to form a clean string.

The result is the picture below:

Common Issues and Solutions

Issue: Leading and Trailing Spaces

When concatenating strings, you may encounter unwanted spaces. Use the strip() method to remove them.

str1 = " Hello "
str2 = " World "
result = (str1 + str2).strip()
print(result) # Output: Hello World

Issue: Handling None Values

When concatenating strings that might include None values, use conditional expressions or the or operator.

str1 = "Hello"
str2 = None
result = str1 + (str2 or "")
print(result) # Output: Hello

Frequently Asked Questions

How do you concatenate multiple strings efficiently?

For concatenating a large number of strings, use the join() method with a list of strings for better performance.

Can you concatenate strings with different data types?

Yes, but you need to convert non-string data types to strings using the str() function.

num = 100
result = "The number is " + str(num)
print(result) # Output: The number is 100

How do you split a string into characters?

Use the list() function to split a string into a list of characters.

word = "hello"
characters = list(word)
print(characters) # Output: ['h', 'e', 'l', 'l', 'o']

Conclusion

Concatenating and splitting strings are fundamental skills in Python programming. This guide has covered both basic and advanced techniques to help you manipulate strings efficiently. Whether you are building a simple script or a complex application, mastering these techniques will enhance your coding capabilities.

By understanding and utilizing the methods and examples provided, you’ll be able to handle various string manipulation tasks in Python with confidence. Keep practicing, and soon these techniques will become second nature.

Thank you for reading the DevopsRoles page!

How to install Ansible on Centos/ Ubuntu/Fedora

Introduction

In this tutorial, I guide how to install Ansible on Centos 7/ Ubuntu 14.04 / Fedora. Ansible is an Automation tool for IT Management. It’s useful for System Admin, and DevOps to build Automation Configure Management. Ansible the essential for DevOps Roles.

To install Ansible on CentOS, Ubuntu, or Fedora, you can follow the instructions below for each respective operating system:

Requirements

  • Control Machine: Run Ansible.
  • Remote server: Deploy and Configure such as Tomcat,  Nginx, Apache, and so forth from Control Machine.

Control Machine and remote server communication through SSH key Authentication.

How to install Ansible on Control Machine

For Centos 7 and RHEL 7

Open a terminal on your CentOS machine.

 # rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
 # yum install ansible

For Ubuntu 14.04 / 15.04

 $ sudo apt-get install software-properties-common
 $ sudo apt-add-repository ppa:ansible/ansible
 $ sudo apt-get update
 $ sudo apt-get install ansible

Checking Ansible version

 $ ansible --version

For example, The output Ansible version

ansible 2.5.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

That’s it! Ansible should now be installed on your CentOS, Ubuntu, or Fedora machine. You can start using Ansible to automate your IT infrastructure tasks.

Conclusion

Thought this article, How to install Ansible on Centos/Ubuntu and Fedora. In the next post, I installed and configured Nginx automation from Control Machine for the Remote server. Thank you for reading the DevopsRoles page!

How to install erlang on ubuntu 16.04

Introduction

Erlang is a programming language used to build massively scalable soft real-time systems with requirements on high availability. In this tutorial, i will help you “how to install erlang on ubuntu 16.04 operating system.

Adding repository for erlang

$ cd /opt/
$ wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb
$ sudo dpkg -i erlang-solutions_1.0_all.deb

Update repository

$ sudo apt-get update

Install erlang on ubuntu

$ sudo apt-get install erlang

Alternatively, you can to install erlang on ubuntu with specify version

To search for erlang package version on ubuntu with apt-cache command as below:

$ sudo apt-cache show erlang

installing erlang package version

$ sudo apt-get install erlang=version-number

Conclusion

Thought the article, you have installed erlang on ubuntu server. Thank you for reading the DevopsRoles page!

Ref to link https://www.erlang.org/course.

Docker SSH into Container: A Complete Guide for Beginners and Advanced Users

Introduction

Docker containers have revolutionized the way developers build, ship, and manage applications. However, one common question arises: How do you Docker SSH into Container? While Docker doesn’t support traditional SSH access like physical servers, it provides a powerful alternative with the docker exec command. In this guide, we’ll explore step-by-step instructions on how to “SSH” into Docker containers from basic operations to more advanced use cases.

What is Docker SSH into Container?

Before diving into the practical steps, it’s important to clarify that Docker doesn’t actually use SSH for container access. Instead, Docker uses the docker exec command, which allows you to run commands or get an interactive shell inside running containers. This method is more efficient, secure, and tailored for containers than traditional SSH.

Why You Shouldn’t Use SSH for Docker Containers

  • Containers are lightweight: Adding an SSH server increases container size.
  • Docker has built-in tools: Using docker exec provides direct and simple access to containers without the overhead of SSH configuration.
  • Security: Running an SSH service in every container increases the attack surface. Docker’s approach with docker exec is more secure.

How to SSH into a Docker Container: Basic Method

Let’s start with the basics – getting into the shell of a running Docker container.

Step 1: List Running Containers

To view the currently running containers, you can use the following command:

docker ps

This command will display:

  • CONTAINER ID: Unique ID for each running container
  • IMAGE: The Docker image used to create the container
  • COMMAND: The main process running in the container
  • STATUS: Whether the container is running, paused, or stopped
  • NAMES: Friendly names assigned to containers for easy identification

Step 2: Access the Shell of a Running Container

Once you have the container ID or name, you can use the docker exec command to access the container’s bash shell. For example:

docker exec -it <container_ID_or_name> /bin/bash
  • -i: Keep STDIN open even if not attached.
  • -t: Allocate a pseudo-TTY, allowing you to interact with the container.

If your container uses a different shell, such as sh, replace /bin/bash with the appropriate shell path.

Advanced Docker Exec Usage

Once you’ve mastered the basics, you can use the docker exec command for more advanced tasks. Let’s look at some examples.

Running Commands in a Docker Container

You don’t always need to access a full shell; sometimes you just need to run a single command. You can do this using the docker exec command, followed by the command you want to execute. For example, to check the /etc/hosts file inside a container:

docker exec -it <container_ID_or_name> cat /etc/hosts

Inspect Container Configuration

To view detailed information about a container, such as its environment variables, network settings, and mounted volumes, use:

docker inspect <container_ID_or_name>

This is helpful when you need to troubleshoot or validate container configurations.

How to SSH into Stopped or Exited Containers

You can only run the docker exec command on running containers. If your container has stopped or exited, you need to start it before you can access it. Here’s how:

  1. List all containers (including stopped ones):
docker ps -a
  1. Start a stopped container:
docker start <container_ID_or_name>
  1. SSH into the container using the previously mentioned docker exec command.

Automating Docker SSH Access

For users who frequently need to access containers, creating a function in your .bashrc or .zshrc file can streamline the process:

function docker_ssh() {
    docker exec -it $1 /bin/bash
}

This allows you to use a simpler command like docker_ssh <container_ID_or_name>.

Frequently Asked Questions (FAQs)

1. Can I install SSH in a Docker container?

Yes, you can install SSH in a Docker container, but it’s generally discouraged. Adding SSH increases the container’s size and complexity. Using docker exec is the recommended way to access containers.

2. How do I copy files between my host machine and Docker containers?

You can use the docker cp command to copy files from your host to the container or vice versa. For example:

docker cp <source_path> <container_ID_or_name>:<destination_path>

3. How can I access Docker containers with graphical applications?

Docker containers can run graphical applications using X11 forwarding, but this setup requires additional configuration beyond simple terminal access.

4. What happens if I stop a container after SSHing into it?

If you stop a container while you’re connected using docker exec, your session will end immediately. You must restart the container to regain access.

Advanced Topics: Managing Multiple Containers

In environments with many running containers, it’s essential to efficiently manage them. Here are a few strategies:

Using Docker Compose for Multi-Container Applications

If you are running multiple containers, Docker Compose is a valuable tool. It allows you to define and manage multi-container applications with a simple YAML configuration file. To install and use Docker Compose:

sudo apt-get install docker-compose
docker-compose up

With Docker Compose, you can specify the configuration for all containers in one place, making it easier to scale, start, and stop services together.

Handling Docker Networks

Managing container networks is crucial, especially for multi-container applications. Docker provides default networking, but you can create custom networks for better isolation and performance.

  • List networks: docker network ls
  • Create a new network: docker network create my_network
  • Run a container on a network: docker run --network my_network <image>

Conclusion

Accessing a Docker container’s shell or executing commands inside it is made simple with the docker exec command. This guide covered everything from basic shell access to running advanced commands and managing multiple containers. Docker’s flexibility allows you to streamline container management without the need for traditional SSH. Thank you for reading the DevopsRoles page!

Devops Tutorial

Exit mobile version