Saturday 24 November 2018

Configuring chrony time server in Centos 7

In this quick article we'll demonstrate how to configure the chrony time service in Linux. Configuring chrony is an exam objective for the RedHat as well as Linux Foundation exams.
Chrony is touted as an alternative for the popular ntpd daemon that has been used in UNIX/Linux systems for years now. Chrony has become more popular in desktop environments since time synchronization using chrony is very quick making it ideal for systems that get restarted frequently.

To install chrony, type the following command:

[root@cent7~]# yum install chrony
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                                                                                          | 7.7 kB  00:00:00
 * base: centos.mirror.myduniahost.com
 * epel: mirrors.aliyun.com
 * extras: mirror.0x.sg
 * updates: mirror.0x.sg
base                                                                                                                                          | 3.6 kB  00:00:00
epel                                                                                                                                          | 3.2 kB  00:00:00
extras                                                                                                                                        | 3.4 kB  00:00:00
updates                                                                                                                                       | 3.4 kB  00:00:00
(1/2): epel/x86_64/updateinfo                                                                                                                 | 932 kB  00:00:01
(2/2): epel/x86_64/primary                                                                                                                    | 3.6 MB  00:00:14
epel                                                                                                                                                     12716/12716
Package chrony-3.2-2.el7.x86_64 already installed and latest version
Nothing to do

Apparently it's already installed on my system.

Let's take a look at the available time servers in the chrony configuration file /etc/chrony.conf.

[root@cent7~]# grep -E '^server' /etc/chrony.conf
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
[root@cent7~]#

Now we'll enable and start the service.

[root@cent7 ~]# systemctl enable chronyd
Created symlink from /etc/systemd/system/multi-user.target.wants/chronyd.service to /usr/lib/systemd/system/chronyd.service.
[root@cent7 ~]# systemctl start chronyd

Let's check the status of the service now:

[root@cent7 ~]# systemctl status chronyd
● chronyd.service - NTP client/server
   Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2018-11-24 11:53:55 IST; 5s ago
     Docs: man:chronyd(8)
           man:chrony.conf(5)
  Process: 1796 ExecStartPost=/usr/libexec/chrony-helper update-daemon (code=exited, status=0/SUCCESS)
  Process: 1792 ExecStart=/usr/sbin/chronyd $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 1794 (chronyd)
   CGroup: /system.slice/chronyd.service
           └─1794 /usr/sbin/chronyd

Nov 24 11:53:55 cent7 systemd[1]: Starting NTP client/server...
Nov 24 11:53:55 cent7 chronyd[1794]: chronyd version 3.2 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCFILTER +SECHASH +SIGND +ASYNCDNS +IPV6 +DEBUG)
Nov 24 11:53:55 cent7 systemd[1]: Started NTP client/server.

To obtain information about the time server we are currently syncing our time from, type the following command:

[root@cent7 ~]# chronyc tracking
Reference ID    : 768CB862 (sr-97-184-140-128-on-nets.com)
Stratum         : 3
Ref time (UTC)  : Sat Nov 24 06:24:05 2018
System time     : 0.000006578 seconds slow of NTP time
Last offset     : +0.007599837 seconds
RMS offset      : 0.007599837 seconds
Frequency       : 0.000 ppm slow
Residual freq   : +3831.410 ppm
Skew            : 1000000.000 ppm
Root delay      : 0.178650528 seconds
Root dispersion : 39.540195465 seconds
Update interval : 1.6 seconds
Leap status     : Normal

From the above output we can determine that we are currently syncing time from the server sr-97-184-140-128-on-nets.com.

To view the list of time servers available to us to sync from type the following command:

[root@cent7~]# chronyc sources
210 Number of sources = 4
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^- ntp.fra.de.as206479.net       2   6    37    53    +36ms[  +36ms] +/-  252ms
^* hkg1.m-d.net                  2   6    37    54  -1579us[  -17ms] +/-  117ms
^? 30-213-226-103-static.ch>     1   6     1    54  +1364us[  -14ms] +/-   93ms
^+ sr-97-184-140-128-on-net>     2   6    37    54  +1105us[+1105us] +/-  122ms

The * symbol indicates the time server we are currently syncing from.

I hope that you found this quick and easy setup of chrony to be useful.

Tuesday 13 November 2018

host command as an alternative to nslookup

The nslookup command is the go to command for performing hostname/IP address lookups. It's a standard command found in Linux, UNIX and Windows distributions alike. While writing scripts we may come across requirements wherein we need the hostname and IP address information to be extracted from the output of the command.

If we use nslookup for this purpose then we would need to employ some interesting awk or grep commands to get the desired result. Given below is an example:

[root@lpic ~]# nslookup google.com
Server:         192.168.178.1
Address:        192.168.178.1#53

Non-authoritative answer:
Name:   google.com
Address: 172.217.24.238

[root@lpic ~]# nslookup google.com | awk '/Address/ && !/#/ {print $2}'
172.217.160.206
[root@lpic ~]#

On the contrary now let's talk about the host command. host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. But I found it's output easier to read and extract desired fields from it. Here's an example:

[root@lpic ~]# host google.com
google.com has address 172.217.24.238
google.com has IPv6 address 2404:6800:4002:803::200e
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
[root@lpic ~]#
[root@lpic ~]# host google.com | awk '/has address/ {print $4}'
172.217.24.238
[root@lpic ~]#

I hope this quick tip has been helpful for you.

Tuesday 3 April 2018

Using Perl DBI module to interact with an oracle database



In this article, I'll demonstrate how we can use the famous Perl DBI module to connect to an Oracle database. To connect to a database, DBI uses database driver modules (DBD) which handles the entire interaction between the queries typed within the Perl script and the actual database connectivity engine or in simple terms the database client. DBI comes available with the database driver for MySQL database by default as MySQL is the more popular database among folks engaged in web development.

The setup:
I'll be working with a Centos 6 system for the purpose of this demonstration and have installed the Oracle 11g database XE edition since it's quite easy to set up. I've also given the oracle user full superuser privileges temporarily.

So, let's get started.

Installing the DBD for Oracle:
Before downloading the package we need to make sure that we are logged in as the oracle user and the oracle user environment is set. To set the environment for Oracle XE edition, run the following script:

. /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh 

This sets up environment variables like ORACLE_HOME etc.

Now let's download the DBD:Oracle package from CPAN via wget.

-bash-4.1$ wget http://search.cpan.org/CPAN/authors/id/P/PY/PYTHIAN/DBD-Oracle-1.64.tar.gz
--2018-03-27 19:05:41--  http://search.cpan.org/CPAN/authors/id/P/PY/PYTHIAN/DBD-Oracle-1.64.tar.gz
Resolving search.cpan.org... 199.15.176.188
Connecting to search.cpan.org|199.15.176.188|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://www.cpan.org/authors/id/P/PY/PYTHIAN/DBD-Oracle-1.64.tar.gz [following]
--2018-03-27 19:05:46--  http://www.cpan.org/authors/id/P/PY/PYTHIAN/DBD-Oracle-1.64.tar.gz
Resolving www.cpan.org... 151.101.2.49, 151.101.66.49, 151.101.130.49, ...
Connecting to www.cpan.org|151.101.2.49|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 444613 (434K) [application/x-gzip]
Saving to: “DBD-Oracle-1.64.tar.gz”

100%[=================================================================================================================================================>] 444,613      287K/s   in 1.5s

2018-03-27 19:05:50 (287 KB/s) - “DBD-Oracle-1.64.tar.gz” saved [444613/444613]


Now let's extract the package and take a look at what's inside.

-bash-4.1$ tar xzf DBD-Oracle-1.64.tar.gz
-bash-4.1$
-bash-4.1$ cd DBD-Oracle-1.64
-bash-4.1$ ls
Changes       dbdimp.c  dbivport.h  hints    lib      Makefile.PL  META.json  mkta.pl  oci.def     Oracle.h   README           README.mkdn  Todo
CONTRIBUTORS  dbdimp.h  examples    INSTALL  LICENSE  MANIFEST     META.yml   oci8.c   ocitrace.h  Oracle.xs  README.help.txt  t            typemap
-bash-4.1$

Before starting with the installation make sure that you have gcc installed as we'll need a C compiler to build the binaries from the source. Also, we need to export the following variables:

export ORACLE_USERID=hr/demo123
export ORACLE_DSN='dbi:Oracle:XE'

export LD_LIBRARY_PATH=/u01/app/oracle/product/11.2.0/xe/lib

The ORACLE_USERID is the user id and password for the user that we will use to connect to the database and ORACLE_DSN is the data source name which is the Oracle DBD name dbi:Oracle and the name of the database instance which is XE in this case. The LD_LIBRARY_PATH variable denotes the location where the installer should look for any library files it may require.


Now, execute the following commands to install the Oracle DBD package:

perl Makefile.PL

make

make test

sudo make install


Once the commands mentioned above complete successfully, check the installed versions of the DBI module and the database driver to ensure that the installation was successful.

-bash-4.1$ perl -e 'use DBI; print $DBI::VERSION,"\n";'
1.609
-bash-4.1$ perl -e 'use DBD::Oracle; print $DBD::Oracle::VERSION,"\n";'
1.64
-bash-4.1


The working script:
Given below is a simple Perl script that uses the DBI module to connect to the XE instance and query some records from the table named employees. I executed the script successfully while logged in as the oracle user. I'm not certain if it'll work if executed as a different user.

#!/usr/bin/perl

use DBI;        #connect to database

$dbh=DBI->connect("dbi:Oracle:XE",'hr','demo123') or die "Error $! \n";

##connect function calls bliss function and creates the object $dbh#

$sth=$dbh->prepare("select EMPLOYEE_ID, FIRST_NAME from EMPLOYEES WHERE JOB_ID='SH_CLERK'") or die "Errors $! \n";

##prepare compiles the SQL query#

$res=$sth->execute();

eval {

$res=$sth->execute();
};

if($@) { print $@,"\n"; next; }
else { print "query executed successfully \n"; }

if($res) {

        print "EMPLOYEE_ID\tFIRST_NAME\n";
        while(@row=$sth->fetchrow_array) {
                print "$row[0]\t\t$row[1]\n";
                }

#$sth is also an object and fetchrow_array is a function that works on this object#
#fetchrow_array function fetches each record as a separate array element#
         }

$dbh->disconnect;


Conclusion:
In this article, we demonstrated how to install the database driver for Oracle and use it with the Perl DBI module to interact with an Oracle database.


Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...