Category Archives: Uncategorized

How to use yum to install RPMs required, for offline use?

Here is an example using “ffmpeg” as the package to download. I have tested the process on both Red Hat and CentOS 6.?

Install all the required package for the download process.

# yum install yum-plugin-downloadonly yum-utils createrepo
# mkdir /var/tmp/ffmpeg
# mkdir /var/tmp/ffmpeg-installroot

Note: The installroot is for the metada that will allow the full download of all dependencies.
# yum install --downloadonly --installroot=/var/tmp/ffmpeg-installroot --releasever=6 --downloaddir=/var/tmp/ffmpeg ffmpeg
Now, Generate the metadata needed to turn our new pile of RPMs into a YUM repo.

# createrepo --database /var/tmp/ffmpeg
# rm -rf /var/tmp/ffmpeg-installroot Configure the repo:
# vi /etc/yum.repos.d/offline-ffmpeg.repo
[offline-ffmpeg]
name=CentOS-$releasever - ffmpeg
baseurl=file:///var/tmp/ffmpeg
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

To check the missing dependencies:
# repoclosure --repoid=offline-ffmpeg

Then Offline: 

# yum --disablerepo=\* --enablerepo=offline-ffmpeg install ffmpeg

Good luck!!
 

Linux Interview! what to know

Common administrative commands in Red Hat Enterprise Linux 5, 6, and 7

System basics

Task RHEL5 RHEL6 RHEL7
View subscription information /etc/sysconfig/rhn/systemid /etc/sysconfig/rhn/systemid
subscription-manager identity
subscription-manager identity
Configure subscription rhn_register
subscription-manager 1
rhn_register
rhnreg_ks
subscription-manager
subscription-manager2
rhn_register 3
View RHEL version information /etc/redhat-release
View system profile sosreport
dmidecode
hwbrowser
sosreport
dmidecode
lstopo
lscpu

Basic configuration

Task RHEL5 RHEL6 RHEL7
Graphical configuration tools system-config-* gnome-control-center
Text-based configuration tools system-config-*-tui
Configure printer system-config-printer
Configure network system-config-network nmcli
nmtui
nm-connection-editor
Configure system language system-config-language localectl
Configure time and date system-config-date
date
timedatectl
date
Synchronize time and date ntpdate
/etc/ntp.conf
timedatectl
/etc/chrony.conf
ntpdate
Configure keyboard system-config-keyboard localectl
Configure SSH /etc/ssh/ssh_config
/etc/ssh/sshd_config
~/.ssh/config ssh-keygen

Jobs and services

Task RHEL5 RHEL6 RHEL7
List all services chkconfig –list
ls /etc/init.d/
systemctl -at service
ls /etc/systemd/system/*.service
ls /usr/lib/systemd/system/*.service
List running services service –status-all systemctl -t service –state=active
Start/stop service service name start
service name stop
systemctl start name.service
systemctl stop name.service
Enable/disable service chkconfig name on
chkconfig name off
systemctl enable name.service
systemctl disable name.service
View service status service name status systemctl status name.service
Check if service is enabled chkconfig name –list systemctl is-enabled name
Create new service file or modify configuration chkconfig –add systemctl daemon-reload
/etc/systemd/system/*.service
View run level/target runlevel
who -r
systemctl get-default
who -r
Change run level/target /etc/inittab
init run_level
systemctl isolate name.target
systemctl set-default
Configure logging /etc/syslog.conf /etc/rsyslog.conf /etc/rsyslog.conf
/etc/rsyslog.d/*.conf
/var/log/journal
systemd-journald.service
View logs /var/log /var/log
journalctl
Configure system audit add audit=1 to kernel cmdline
auditctl
/etc/audit/auditd.conf
/etc/audit/audit.rules
authconfig
/etc/pam.d/system-auth
pam_tty_audit kernel module
View audit output aureport /var/log/faillog
Schedule/batch tasks cron
at
batch
Find file by name locate
Find file by characteristic find
Create archive tar
cpio
zip

Kernel, boot, and hardware

Task RHEL5 RHEL6 RHEL7
Single user/rescue mode append 1 or s or init=/bin/bash to kernel cmdline append rd.break or init=/bin/bash to kernel cmdline
Shut down system shutdown
Power off system poweroff poweroff
systemctl poweroff
Halt system halt halt
systemctl halt
Reboot system reboot reboot
systemctl reboot
Configure default run level/target /etc/inittab systemctl set-default
Configure GRUB bootloader /boot/grub/grub.conf /etc/default/grub
grub2-mkconfig
grub-set-default
Configure kernel module modprobe
View hardware configured hwbrowser lshw (in EPEL)
Configure hardware device udev
View kernel parameters sysctl -a
cat /proc/cmdline
Load kernel module modprobe
Remove kernel module modprobe -r
View kernel version rpm -q kernel
uname -r

Software management

Task RHEL5 RHEL6 RHEL7
Install software yum install
yum groupinstall
yum install
yum group install
View software info yum info
yum groupinfo
yum info
yum group info
Update software yum update
Upgrade software yum upgrade
Configure software repository subscription-manager repos
/etc/yum.repos.d/*.repo
Find package owning file rpm -qf filename
yum provides filename-glob
View software version rpm -q packagename
View installed software rpm -qa
yum list installed

User management

Task RHEL5 RHEL6 RHEL7
Graphical user management system-config-users
Create user account useradd
Delete user account userdel
View/change user account details usermod
/etc/passwd
vipw
id
Create user group groupadd
Delete user group groupdel
Change group details groupmod
/etc/group
Change user password passwd
Change user permissions usermod
visudo
Change group permissions groupmod
visudo
Change password policy chage
View user sessions w

File systems, volumes, and disks

Task RHEL5 RHEL6 RHEL7
Default file system ext3 ext4 xfs
Create/modify disk partitions fdisk
parted
fdisk
gdisk
parted
ssm create
Format disk partition mkfs.filesystem_type (ext4, xfs)
mkswap
mkfs.filesystem_type (ext4, xfs)
mkswap
ssm create
Defragment disk space copy data to new file system
fsck (look for ‘non-contiguous inodes’)
copy data to new file system
fsck (look for ‘non-contiguous inodes’)
xfs_fsr
Mount storage mount
/etc/fstab
mount
/etc/fstab
ssm mount
Mount and activate swap /etc/fstab
swapon -a
Configure static mounts /etc/fstab
View free disk space df
View logical volume info lvdisplay
lvs
vgdisplay
vgs
pvdisplay
pvs
Create physical volume pvcreate pvcreate
ssm create (if backend is lvm)
Create volume group vgcreate vgcreate
ssm create (if backend is lvm)
Create logical volume lvcreate lvcreate
ssm create (if backend is lvm)
Enlarge volumes formatted with default file system vgextend
lvextend
resize2fs
vgextend
lvextend
xfs_growfs
ssm resize
Shrink volumes formatted with default file system resize2fs
lvreduce
vgreduce
XFS cannot currently be shrunk; copy desired data to a smaller file system.
Check/repair file system fsck fsck
ssm check
View NFS share showmount -e
mount
Configure NFS share /etc/exports
service nfs reload
/etc/exports
systemctl reload nfs.service
Configure on-demand auto-mounts /etc/auto.master.d/*.autofs
/etc/auto.*
Change file permissions chmod
chown
chgrp
umask (future file creation)
Change file attributes chattr
Change access control list setfacl

Networking

Task RHEL5 RHEL6 RHEL7
Configure name resolution /etc/hosts
/etc/resolv.conf
/etc/hosts
/etc/resolv.conf
nmcli con mod
Configure hostname /etc/sysconfig/network hostnamectl
/etc/hostname
nmtui
View network interface info ip addr
ifconfig
brctl
ip addr
nmcli dev show
teamdctl
brctl
bridge
Configure network interface /etc/sysconfig/network-scripts/ifcfg-* /etc/sysconfig/network-scripts/ifcfg-*
nmcli con [add|mod|edit]
nmtui
nm-connection-editor
View routes ip route
Configure routes ip route add
system-config-network
/etc/sysconfig/route-iface
ip route add
nmcli
nmtui
nm-connection-editor
/etc/sysconfig/route-iface
Configure firewall iptables and ip6tables
/etc/sysconfig/ip*tables
iptables and ip6tables
/etc/sysconfig/ip*tables
system-config-firewall
firewall-cmd
firewall-config
View ports/sockets ss
lsof
netstat
ss
lsof

Security and identity

Task RHEL5 RHEL6 RHEL7
Configure system security /etc/selinux/config
chcon
restorecon
semanage
setsebool
system-config-selinux
Report on system security sealert
LDAP, SSSD, Kerberos authconfig
authconfig-tui
authconfig-gtk
Network users getent

Resource management

Task RHEL5 RHEL6 RHEL7
Trace system calls strace
Trace library calls ltrace
Change process priority nice
renice
Change process run location taskset
Kill a process kill
pkill
killall
View system usage top
ps
sar
iostat
netstat
vmstat
mpstat
numastat
top
ps
sar
iostat
netstat
ss
vmstat
mpstat
numastat
tuna
top
ps
sar
iostat
ss
vmstat
mpstat
numastat
tuna
View disk usage df df
iostat

 

Simple questions

What is LD_LIBRARY_PATH?

  • LD_LIBRARY_PATH is an environment variable. It is used for debugging a new library or a non-standard library. It is also used to identify what directories need to be searched. Path to search for directories needs to give.
  • The variable can be set using setenv—LD_LIBRARY_PATH–$PATH.
  • It is used to search for the shared objects / dynamic libraries by the operating system for extendable functionality at runtime.

 

How to check Memory stats and CPU stats as a Linux admin?

Using ‘free’ & ‘vmstat’ command, we can display the physical and virtual memory statistics, respectively. With the help of ‘sar’ command, we can see the CPU utilization & other stats.

 

What are the different modes of Network bonding in Linux?

Below is a list of modes used in Network Bonding :
  • balance-rr or 0 – round-robin mode for fault tolerance and load balancing.
  • active-backup or 1 – Sets active-backup mode for fault tolerance.
  • balance-xor or 2 – Sets an XOR (exclusive-or) mode for fault tolerance and load balancing.
  • broadcast or 3 – Sets a broadcast mode for fault tolerance. All transmissions are sent on all slave interfaces.
  • 802.3ad or 4 – Sets an IEEE 802.3ad dynamic link aggregation mode. Creates aggregation groups that share the same speed & duplex settings.
  • balance-tlb or 5 – Sets a Transmit Load Balancing (TLB) mode for fault tolerance & load balancing.
  • balance-alb or 6 – Sets an Active Load Balancing (ALB) mode for fault tolerance & load balancing.

How to check and verify the status of the bond interface?

Using the command ‘cat /proc/net/bonding/bond0,’ we can check what mode is enabled and what LAN cards are used in this bond. In this example, we have one one bond interface. However, we can have multiple bond interfaces like bond1, bond2 and so on.

 

What is Puppet Server?

In computing, Puppet is an open-source software configuration management tool. It runs on many Unix-like systems as well as on Microsoft Windows, and includes its own declarative language to describe system configuration. 

 

What is the name and path of the main system log?

By default, the main system log is ‘/var/log/messages’. This file contains all the messages and the script written by the user. By default, all scripts are saved in this file. This is the standard system log file, which contains messages from all system software, non-kernel boot issues, and messages that go to ‘dmesg’. dmesg is a system file that is written upon system boot.

 

What is YUM?

yum is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories. yum is used in Red Hat Enterprise Linux versions 5 and later. Versions of Red Hat Enterprise Linux 4 and earlier used up2date.

 

What is the difference between ext2 and ext3 file systems?

  • The ext3 file system is an enhanced version of the ext2 file system.
  • The most important difference between Ext2 and Ext3 is that Ext3 supports journaling.
  • After an unexpected power failure or system crash (also called an unclean system shutdown), each mounted ext2 file system on the machine must be checked for consistency by the e2fsck program. This is a time-consuming process and during this time, any data on the volumes is unreachable.
  • The journaling provided by the ext3 file system means that this sort of file system check is no longer necessary after an unclean system shutdown. The only time a consistency check occurs using ext3 is in certain rare hardware failure cases, such as hard drive failures. The time to recover an ext3 file system after an unclean system shutdown does not depend on the size of the file system or the number of files. Rather, it depends on the size of the journal used to maintain consistency. The default journal size takes almost a second to recover, depending on the speed of the hardware.

 

Explain /proc filesystem?

/proc is a virtual file system that provides detailed information about Linux kernel, hardware and running processes. Files under /proc directory named as Virtual files.
Since /proc contains virtual files, it is called virtual file system. These virtual files have unique qualities. Most of them are listed as zero bytes in size.
Virtual files such as /proc/interrupts, /proc/meminfo, /proc/mounts, and /proc/partitions provide an up-to-the-moment glimpse of the system’s hardware. Others: /proc/filesystems file and the /proc/sys/ directory provide system configuration information and interfaces.

 

 

Beginner Linux Users: Don’t Be Scared of the Terminal

The Terminal Is Optional

Whether you want to install software, configure your network, or tweak other system settings, you can do it from the terminal – but you can also do it from the graphical interface. Most settings you would want to change are easily accessible in the standard graphical control panels.

If you have never tried using Linux, you may have an expectation that you will have to learn terminal commands to get around, but this has become less and less true with each passing year. Give Ubuntu a try and you may be surprised at how little you’ll need to use the terminal. Many users shouldn’t need to touch the terminal at all.

(It is possible that, if your hardware isn’t well-supported, you may have to use terminal commands. With properly supported hardware, you should not have to mess around with the terminal to make things work.)

 

Find and remove older file in Linux

With this, you will be able with the Linux find command to find all files older than 30 days and then execute rm command on them.

The find utility on Linux allows you to pass in arguments, including one to execute another command on each file. We’ll use this in order to figure out what files are older than a certain number of days, and then

use the ls command to list them. To be on the safe side and the

rm command to remove them.

List:

find  /path/to/files* –mtime +30 -exec ls –tl {} \;

Note that there are spaces between ls, {}, and \;

Remove:

find  /path/to/files* –mtime +30 -exec rm {} \;

  1. The first argument is the path to the files. This can be a path, a directory, or a wildcard as in the example above. I would recommend using the full path, and make sure that you run the command without the exec rm to make sure you are getting the right results.
  2. The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +30, it will find files older than 30 days
  3. The third argument, -exec, allows you to pass in a command such as ls -tl. The {} \; at the end is required to end the command.

Customize a Golden Image or RHEL ISO with kickstart file? Rhel4/5/6//7

Issue

 

  • How can we create a customized RHEL6 ISO with kickstart file included in the ISO?
  • How to include a kickstart file in ISO image and create customized ISO?

Resolution

1. Download the RHEL installation dvd iso or minimal boot media boot.iso

2. Mount the ISO

    # mount /path/to/rhel-dvd.iso /mnt/ -o loop


3. Copy the entire contents of the disk to another location.

    # mkdir /rhel
    # shopt -s dotglob
    # cp -ai /mnt/* /rhel

4. Create a kickstart file.
This is an example: 

5. Copy the kickstart file to the /rhel directory

      # cp /path/to/ks.cfg /rhel

6. Change the file '/rhel/isolinux/isolinux.cfg',  change the following lines :
     label linux
      menu label ^Install or upgrade an existing system
      menu default
      kernel vmlinuz
      append initrd=initrd.img
to
     label linux
      menu label ^Install or upgrade an existing system
      menu default
      kernel vmlinuz
      append initrd=initrd.img  ks=cdrom:/ks.cfg
NOTE: For Red Hat Enterprise Linux 7, use the following append line:
append initrd=initrd.img inst.stage2=hd:LABEL=***Volume_ID*** quiet ks=cdrom:/ks.cfg
Replace Volume_ID by the same value as one specified in -V option of the following mkisofs command.

7. Rebuild the DVD iso image

    # cd /rhel
    # mkisofs -o /tmp/new.iso -b isolinux/isolinux.bin -c isolinux/boot.cat --no-emul-boot --boot-load-size 4 --boot-info-table -J -R -V disks .
NOTE: In Red Hat Enterprise Linux 7, please make sure that you specify the volume id with -V option, and it's same as Volume_ID in step 6.

8. Boot the machine from this ISO

The best AWK one-liners

The best AWK one-liners

I love perl and I use it for most scripts but nothing beats awk on the commandline.
Print selected fields

Split up the lines of the file file.txt with “:” (colon) separated fields and print the second field ($2) of each line:
awk -F”:” ‘{print $2}’ file.txt
Same as above but print only output if the second field ($2) exists and is not empty:
awk -F”:” ‘{if ($2)print $2}’ file.txt
Print selected fields from each line separated by a dash:
awk -F: ‘{ print $1 “-” $4 “-” $6 }’ file.txt
Print the last field in each line:
awk -F: ‘{ print $NF }’ file.txt
Print every line and delete the second field:
awk ‘{ $2 = “”; print }’

Good to know:
The commandline option -F sets the field separator. The default is space.
$0 the entire line without the newline at the end
$1 to $9, $10 to …, the fields
NF number of fields
NR currant line number (counting across all files for multiple files)
FR line number (just for that file)
Print matching lines

Print field number two ($2) only on lines matching “some regexp”:
awk -F”:” ‘/some regexp/{print $2}’ file.txt
Print field number two ($2) only on lines matching “some regexp” otherwise print field number three ($3):
awk -F”:” ‘/some regexp/{print $2;next}{print $3}’ file.txt
The “next” command causes awk to continue with the next line and execute “{print $3}” only for non matching lines. This is like
/regexp/{…if..regexp..matches…;next}{…else…}

Print the next two (i=2) lines after the line matching regexp:
awk ‘/regexp/{i=2;next;}{if(i){i–; print;}}’ file.txt
Print the line and the next two (i=2) lines after the line matching regexp:
awk ‘/regexp/{i=2+1;}{if(i){i–; print;}}’ file.txt
Print the lines from a file starting at the line matching “start” until the line matching “stop”:
awk ‘/start/,/stop/’ file.txt
Regexp syntax:
c matches the non-metacharacter c.
\c matches the literal character c.
. matches any character including newline.
^ matches the beginning of a string (example: ^1 , only lines starting with a one)
$ matches the end of a string (example: end$ , only lines ending in “end”)
[abc…] character list, matches any of the characters abc….
[0-9a-zA-Z] range of characters 0-9 and a-z,A-Z
[^abc…] negated character list, matches any character except abc….
r1|r2 alternation: matches either r1 or r2.
r1r2 concatenation: matches r1, and then r2.
r+ matches one or more r’s.
r* matches zero or more r’s.
r? matches zero or one r’s.
(r) grouping: matches r.
Replacement for some common unix commands (useful in a non unix environment)

Count lines (wc -l):
awk ‘END{print NR}’
Search for matching lines (egrep regexp):
awk ‘/regexp/’
Print non matching lines (egrep -v regexp):
awk ‘!/regexp/’
Print matching lines and ignore case (egrep -i regexp):
awk ‘BEGIN {IGNORECASE=1};/regexp/’
Number lines (cat -n):
awk ‘{print FNR “\t” $0}’
Remove duplicate consecutive lines (uniq):
awk ‘a !~ $0{print}; {a=$0}’
Print first 5 lines of file (head -5):
awk ‘NR < 6’
Number non empty lines

This prints all lines and adds a line number to non empty lines:
awk ‘/^..*$/{ print NR “:” $0 ;next}{print}’ file.txt
Substitute foo for bar on lines matching regexp

awk ‘/regexp/{gsub(/foo/, “bar”)};{print}’ file.txt
Delete trailing white space (spaces, tabs)

awk ‘{sub(/[ \t]*$/, “”);print}’ file.txt
Delete leading white space

awk ‘{sub(/^[ \t]+/, “”); print}’ file.txt
Add some characters at the beginning of matching lines

Add ++++ at lines matching regexp.
awk ‘/regexp/{sub(/^/, “++++”); print;next;}{print}’ file.txt
Color gcc warnings in red

gcc -Wall main.c |& awk ‘/: warning:/{print “\x1B[01;31m” $0 “\x1B[m”;next;}{print}’
The “\x1B” means the ascii character with hex number 1B (ESC).
Print only lines of less than 80 characters

awk ‘length < 80’ file.txt

Print every line that is longer than 80 characters:
awk ‘length($0) > 80’ data
The sole rule has a relational expression as its pattern and has no action—so it uses the default action, printing the record.

Print the length of the longest input line:
awk ‘{ if (length($0) > max) max = length($0) }
END { print max }’ data
The code associated with END executes after all input has been read; it’s the other side of the coin to BEGIN.

Print the length of the longest line in data:
expand data | awk ‘{ if (x < length($0)) x = length($0) }
END { print “maximum line length is ” x }’
This example differs slightly from the previous one: the input is processed by the expand utility to change TABs into spaces, so the widths compared are actually the right-margin columns, as opposed to the number of input characters on each line.

Print every line that has at least one field:
awk ‘NF > 0’ data
This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been removed).

Print seven random numbers from 0 to 100, inclusive:
awk ‘BEGIN { for (i = 1; i <= 7; i++)
print int(101 * rand()) }’
Print the total number of bytes used by files:
ls -l files | awk ‘{ x += $5 }
END { print “total bytes: ” x }’
Print the total number of kilobytes used by files:
ls -l files | awk ‘{ x += $5 }
END { print “total K-bytes:”, x / 1024 }’
Print a sorted list of the login names of all users:
awk -F: ‘{ print $1 }’ /etc/passwd | sort
Count the lines in a file:
awk ‘END { print NR }’ data
Print the even-numbered lines in the data file:
awk ‘NR % 2 == 0’ data
If you used the expression ‘NR % 2 == 1’ instead, the program would print the odd-numbered lines.

RHEL mount hangs: nfs: server […] not responding, still trying

Environment

  • Red Hat Enterprise Linux 7
  • Red Hat Enterprise Linux 6
  • Red Hat Enterprise Linux 5
  • NFS Client (nfs-utils package)

    Issue

    • NFS shares hang with the following error(s) in /var/log/messages:
      kernel: nfs: server <NFSservername> not responding, still trying
      kernel: nfs: server <servername> not responding, timed out
    • Resolution

    • The fix on our system was to lazy unmount, stop any processes that might be using the mount point, and remount.umount -l (mountpoint)
      service yum-updatesd stop
      mount (flags) (mountpoint)

      
      

conflict between 64 bit and 32 bit package architectures

yum update or yum install fails with package conflict between 64 bit and 32 bit package architectures ?

Environment

  • Red Hat Enterprise Linux 5
  • Red Hat Enterprise Linux 6
  • 64 bit architecture
  • 32 bit packages installed sharing some files with the 64 bit ones

Problems

  • Files are conflicting between 64 and 32 bit packages, how to fix it ?
  • yum update or yum install fails with package conflict between 64 bit and 32 bit package architectures.
  • 32 bit package showing conflict problem with 64 bit package.
Transaction Check Error:
file /usr/share/man/man1/ca.1ssl.gz from install of openssl-0.9.8e-27.el5_10.3.x86_64 conflicts with file from package openssl-0.9.8e-27.el5_10.1.i686
file /usr/share/man/man1/req.1ssl.gz from install of openssl-0.9.8e-27.el5_10.3.x86_64 conflicts with file from package openssl-0.9.8e-27.el5_10.1.i686
file /usr/share/man/man1/x509.1ssl.gz from install of openssl-0.9.8e-27.el5_10.3.x86_64 conflicts with file from package openssl-0.9.8e-27.el5_10.1.i686

Resolution

You can configure the yum client to update only a package of the exact architecture installed on the system.

Perform the following steps to remove duplicate packages(i.e. 32-bit and 64-bit packages installed on server which is causing the dependency issues).

  1. Install the yum-utils package:
    # yum install yum-utils
  2. The package-cleanup --dupes lists all duplicate packages:
    # package-cleanup --dupes
  3. The package-cleanup --cleandupes removes the duplicates (it asks for a confirmation to remove all duplicates unless the -y switch is given):
    # package-cleanup --cleandupes   
  4. Edit /etc/yum.confset the following line:
    exactarch=1

    caveats to this: add multilib policy update in the configuration file

multilib_policy=all

  1. Run yum command:
    # yum clean all
    # yum update
    
    
    
    
    
    
    
    

    Root Cause

    When encountering library specific rpm dependencies, architecture of the packages must be considered. As the error here was from a 32bit rpm failing, logically it would follow the the package to resolve that dependency must also be 32bit. A 64bit library version can’t be utilized by a 32bit tool