How to Use Udev for Device Detection and Management in Linux

Udev (userspace /dev) is a Linux sub-system for dynamic device detection and management, since kernel version 2.6. It’s a replacement of devfs and hotplug.

It dynamically creates or removes device nodes (an interface to a device driver that appears in a file system as if it were an ordinary file, stored under the /dev directory) at boot time or if you add a device to or remove a device from the system. It then propagates information about a device or changes to its state to user space.

It’s function is to 1) supply the system applications with device events, 2) manage permissions of device nodes, and 3) may create useful symlinks in the /dev directory for accessing devices, or even renames network interfaces.

One of the pros of udev is that it can use persistent device names to guarantee consistent naming of devices across reboots, despite their order of discovery. This feature is useful because the kernel simply assigns unpredictable device names based on the order of discovery.

In this article, we will learn how to use Udev for device detection and management on Linux systems. Note that most if not all mainstream modern Linux distributions come with Udev as part of the default installation.

Learn Basics of Udev in Linux

The udev daemon, systemd-udevd (or systemd-udevd.service) communicates with the kernel and receives device uevents directly from it each time you add or remove a device from the system, or a device changes its state.

Udev is based on rules – it’s rules are flexible and very powerful. Every received device event is matched against the set of rules read from files located in /lib/udev/rules.d and /run/udev/rules.d.

You can write custom rules files in the /etc/udev/rules.d/ directory (files should end with the .rulesextension) to process a device. Note that rules files in this directory have the highest priority.

To create a device node file, udev needs to identify a device using certain attributes such as the labelserial number, its major and minor number used, bus device number and so much more. This information is exported by the sysfs file system.

Whenever you connect a device to the system, the kernel detects and initializes it, and a directory with the device name is created under /sys/ directory which stores the device attributes.

The main configuration file for udev is /etc/udev/udev.conf, and to control the runtime behavior the udev daemon, you can use the udevadm utility.

To display received kernel events (uevents) and udev events (which udev sends out after rule processing), run udevadm with the monitor command. Then connect a device to your system and watch, from the terminal, how the device event is handled.

The following screenshot shows an excerpt of an ADD event after connecting a USB flash disk to the test system:

$ udevadm monitor 

Monitor Device Events in Linux

Monitor Device Events in Linux

To find the name assigned to your USB disk, use the lsblk utility which reads the sysfs filesystem and udev db to gather information about processed devices.

 
$ lsblk

List Block Devices in Linux

List Block Devices in Linux

From the output of the previous command, the USB disk is named sdb1 (absolute path should be /dev/sdb1). To query the device attributes from the udev database, use the info command.

$ udevadm info /dev/sdb1

Query Device Attributes from Udev DB in Linux

Query Device Attributes from Udev DB in Linux

How to Work with Udev Rules in Linux

In this section, we will briefly discuss how to write udev rules. A rule comprises of a comma-separated list of one or more key-value pairs. Rules allow you to rename a device node from the default name, modify permissions and ownership of a device node, trigger execution of a program or script when a device node is created or deleted, among others.

We will write a simple rule to launch a script when a USB device is added and when it is removed from the running system.

Let’s start by creating the two scripts:

$ sudo vim /bin/device_added.sh

Add the following lines in the device_added.sh script.

#!/bin/bash
echo "USB device added at $(date)" >>/tmp/scripts.log

Open the second script.

$ sudo vim /bin/device_removed.sh

Then add the following lines to device_removed.sh script.

#!/bin/bash
echo "USB device removed  at $(date)" >>/tmp/scripts.log

Save the files, close and make both scripts executable.

$ sudo chmod +x /bin/device_added.sh
$ sudo chmod +x /bin/device_removed.sh

Next, let’s create a rule to trigger execution of the above scripts, called /etc/udev/rules.d/80-test.rules.

$ vim /etc/udev/rules.d/80-test.rules

Add these two following rules in it.

SUBSYSTEM=="usb", ACTION=="add", ENV{DEVTYPE}=="usb_device",  RUN+="/bin/device_added.sh"
SUBSYSTEM=="usb", ACTION=="remove", ENV{DEVTYPE}=="usb_device", RUN+="/bin/device_removed.sh"

where:

  • "==": is an operator to compare for equality.
  • "+=": is an operator to add the value to a key that holds a list of entries.
  • SUBSYSTEM: matches the subsystem of the event device.
  • ACTION: matches the name of the event action.
  • ENV{DEVTYPE}: matches against a device property value, device type in this case.
  • RUN: specifies a program or script to execute as part of the event handling.

Save the file and close it. Then as root, tell systemd-udevd to reload the rules files (this also reloads other databases such as the kernel module index), by running.

$ sudo udevadm control --reload

Now connect a USB drive into your machine and check if the device_added.sh script was executed. First of all the file scripts.log should be created under /tmp.

$ ls -l /tmp/scripts.log

Check Scripts Log After Adding USB

Check Scripts Log After Adding USB

Then the file should have an entry such as “USB device removed at date_time”, as shown in the screenshot.

$ cat /tmp/scripts.log

Check Scripts Log After Removing USB

Check Scripts Log After Removing USB

For more information on how to write udev rules and manage udev, consult the udev and udevadm manual entries respectively, by running:

$ man udev
$ man udevadm
Summary

Udev is a remarkable device manager that provides a dynamic way of setting up device nodes in the /devdirectory. It ensures that devices are configured as soon as they are plugged in and discovered. It propagates information about a processed device or changes to its state, to user space.

Source

Create Multiple IP Addresses to One Single Network Interface

The concept of creating or configuring multiple IP addresses on a single network interface is called IP aliasing. IP aliasing is very useful for setting up multiple virtual sites on Apache using one single network interface with different IP addresses on a single subnet network.

The main advantage of using this IP aliasing is, you don’t need to have a physical adapter attached to each IP, but instead you can create multiple or many virtual interfaces (aliases) to a single physical card.

Linux IP Aliasing

Create Multiple IP Addresses in One NiC

The instructions given here are applies to all major Linux distributions like Red HatFedora, and CentOS. Creating multiple interfaces and assign IP address to it manually is a daunting task. Here we’ll see how we can assign IP address to it defining a set of IP range. Also understand how we are going to create a virtual interface and assign different range of IP Address to an interface in one go. In this article we used LAN IPs, so replace those with ones you will be using.

Creating Virtual Interface and Assign Multiple IP Addresses

Here I have an interface called “ifcfg-eth0“, the default interface for the Ethernet device. If you’ve attached second Ethernet device, then there would be an “ifcfg-eth1” device and so on for each device you’ve attached. These device network files are located in “/etc/sysconfig/network-scripts/” directory. Navigate to the directory and do “ls -l” to list all devices.

# cd /etc/sysconfig/network-scripts/
# ls -l
Sample Output
ifcfg-eth0   ifdown-isdn    ifup-aliases  ifup-plusb     init.ipv6-global
ifcfg-lo     ifdown-post    ifup-bnep     ifup-post      net.hotplug
ifdown       ifdown-ppp     ifup-eth      ifup-ppp       network-functions
ifdown-bnep  ifdown-routes  ifup-ippp     ifup-routes    network-functions-ipv6
ifdown-eth   ifdown-sit     ifup-ipv6     ifup-sit
ifdown-ippp  ifdown-tunnel  ifup-isdn     ifup-tunnel
ifdown-ipv6  ifup           ifup-plip     ifup-wireless

Let’s assume that we want to create three additional virtual interfaces to bind three IP addresses (172.16.16.126172.16.16.127, and 172.16.16.128) to the NIC. So, we need to create three additional alias files, while “ifcfg-eth0” keeps the same primary IP address. This is how we moving forward to setup three aliases to bind the following IP addresses.

Adapter            IP Address                Type
-------------------------------------------------
eth0              172.16.16.125            Primary
eth0:0            172.16.16.126            Alias 1
eth0:1            172.16.16.127            Alias 2
eth0:2            172.16.16.128            Alias 3

Where “:X” is the device (interface) number to create the aliases for interface eth0. For each alias you must assign a number sequentially. For example, we copying existing parameters of interface “ifcfg-eth0” in virtual interfaces called ifcfg-eth0:0ifcfg-eth0:1 and ifcfg-eth0:2. Go into the network directory and create the files as shown below.

# cd /etc/sysconfig/network-scripts/
# cp ifcfg-eth0 ifcfg-eth0:0
# cp ifcfg-eth0 ifcfg-eth0:1
# cp ifcfg-eth0 ifcfg-eth0:2

Open a file “ifcfg-eth0” and view the contents.

[root@tecmint network-scripts]# vi ifcfg-eth0

DEVICE="eth0"
BOOTPROTO=static
ONBOOT=yes
TYPE="Ethernet"
IPADDR=172.16.16.125
NETMASK=255.255.255.224
GATEWAY=172.16.16.100
HWADDR=00:0C:29:28:FD:4C

Here we only need two parameters (DEVICE and IPADDR). So, open each file with VI editor and rename the DEVICE name to its corresponding alias and change the IPADDR address. For example, open files “ifcfg-eth0:0“, “ifcfg-eth0:1” and “ifcfg-eth0:2” using VI editor and change both the parameters. Finally it will look similar to below.

ifcfg-eth0:0
DEVICE="eth0:0"
BOOTPROTO=static
ONBOOT=yes
TYPE="Ethernet"
IPADDR=172.16.16.126
NETMASK=255.255.255.224
GATEWAY=172.16.16.100
HWADDR=00:0C:29:28:FD:4C
ifcfg-eth0:1
DEVICE="eth0:1"
BOOTPROTO=static
ONBOOT=yes
TYPE="Ethernet"
IPADDR=172.16.16.127
NETMASK=255.255.255.224
GATEWAY=172.16.16.100
HWADDR=00:0C:29:28:FD:4C
ifcfg-eth0:2
DEVICE="eth0:2"
BOOTPROTO=static
ONBOOT=yes
TYPE="Ethernet"
IPADDR=172.16.16.128
NETMASK=255.255.255.224
GATEWAY=172.16.16.100
HWADDR=00:0C:29:28:FD:4C

Once, you’ve made all changes, save all your changes and restart/start the network service for the changes to reflect.

[root@tecmint network-scripts]# /etc/init.d/network restart

To verify all the aliases (virtual interface) are up and running, you can use “ifconfig” or “ip” command.

[root@tecmint network-scripts]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.125  Bcast:172.16.16.100  Mask:255.255.255.224
          inet6 addr: fe80::20c:29ff:fe28:fd4c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:237 errors:0 dropped:0 overruns:0 frame:0
          TX packets:198 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:25429 (24.8 KiB)  TX bytes:26910 (26.2 KiB)
          Interrupt:18 Base address:0x2000

eth0:0    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.126  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

eth0:1    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.127  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

eth0:2    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.128  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

Ping each of them from different machine. If everything setup correctly, you will get a ping response from each of them.

ping 172.16.16.126
ping 172.16.16.127
ping 172.16.16.128
Sample Output
[root@tecmint ~]# ping 172.16.16.126
PING 172.16.16.126 (172.16.16.126) 56(84) bytes of data.
64 bytes from 172.16.16.126: icmp_seq=1 ttl=64 time=1.33 ms
64 bytes from 172.16.16.126: icmp_seq=2 ttl=64 time=0.165 ms
64 bytes from 172.16.16.126: icmp_seq=3 ttl=64 time=0.159 ms

--- 172.16.16.126 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.159/0.552/1.332/0.551 ms

[root@tecmint ~]# ping 172.16.16.127
PING 172.16.16.127 (172.16.16.127) 56(84) bytes of data.
64 bytes from 172.16.16.127: icmp_seq=1 ttl=64 time=1.33 ms
64 bytes from 172.16.16.127: icmp_seq=2 ttl=64 time=0.165 ms
64 bytes from 172.16.16.127: icmp_seq=3 ttl=64 time=0.159 ms

--- 172.16.16.127 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.159/0.552/1.332/0.551 ms

[root@tecmint ~]# ping 172.16.16.128
PING 172.16.16.128 (172.16.16.128) 56(84) bytes of data.
64 bytes from 172.16.16.128: icmp_seq=1 ttl=64 time=1.33 ms
64 bytes from 172.16.16.128: icmp_seq=2 ttl=64 time=0.165 ms
64 bytes from 172.16.16.128: icmp_seq=3 ttl=64 time=0.159 ms

--- 172.16.16.128 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.159/0.552/1.332/0.551 ms

Seems everything working smoothly, With these new IPs’ you can setup virtual sites in ApacheFTP accounts and many other things.

Assign Multiple IP Address Range

If you would like to create a range of Multiple IP Addresses to a particular interface called “ifcfg-eth0“, we use “ifcfg-eth0-range0” and copy the contains of ifcfg-eth0 on it as shown below.

[root@tecmint network-scripts]# cd /etc/sysconfig/network-scripts/
[root@tecmint network-scripts]# cp -p ifcfg-eth0 ifcfg-eth0-range0

Now open “ifcfg-eth0-range0” file and add “IPADDR_START” and “IPADDR_END” IP address range as shown below.

[root@tecmint network-scripts]# vi ifcfg-eth0-range0

#DEVICE="eth0"
#BOOTPROTO=none
#NM_CONTROLLED="yes"
#ONBOOT=yes
TYPE="Ethernet"
IPADDR_START=172.16.16.126
IPADDR_END=172.16.16.130
IPV6INIT=no
#GATEWAY=172.16.16.100

Save it and restart/start network service

[root@tecmint network-scripts]# /etc/init.d/network restart

Verify that virtual interfaces are created with IP Address.

[root@tecmint network-scripts]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.125  Bcast:172.16.16.100  Mask:255.255.255.224
          inet6 addr: fe80::20c:29ff:fe28:fd4c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1385 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1249 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:127317 (124.3 KiB)  TX bytes:200787 (196.0 KiB)
          Interrupt:18 Base address:0x2000

eth0:0     Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.126  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

eth0:1    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.127  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

eth0:2    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.128  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

eth0:3    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.129  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

eth0:4    Link encap:Ethernet  HWaddr 00:0C:29:28:FD:4C
          inet addr:172.16.16.130  Bcast:172.16.16.100  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:18 Base address:0x2000

If you having any trouble in setting up, please do post your queries in the comment section.

Source

procinfo – Shows System Statistics from /proc Filesystem

The proc file system is a virtual file system that contains files that store information about processes and other system information. It is mapped to the /proc directory and mounted at boot time. A number of programs retrieve information from /proc file system, process it and provide it readily usable for various purposes.

Procinfo is a simple command line utility for viewing system information collected from /proc directory and prints it beautifully formatted on the standard output device. In this article, we will explain a number of procinfocommand examples in Linux.

In most Linux distributions, the procinfo command should come pre-installed, if you don’t have it, install it using following command.

$ sudo apt install procinfo		#Debian/Ubuntu
$ sudo yum install procinfo		#CentOS/RHEL
$ sudo dnf install procinfo		#Fedora 22+

The simplest example is to run procinfo without any arguments as shown.

$ procinfo

Memory:        Total        Used        Free     Buffers                       
RAM:         8069036     7693288      375748      301356                       
Swap:        3906556           0     3906556                                   

Bootup: Mon Jun  4 11:09:45 2018   Load average: 0.35 0.84 1.01 1/1021 15406   

user  :   01:09:12.02  13.4%  page in :          2434469                       
nice  :   00:02:12.37   0.4%  page out:          2162544                       
system:   00:15:17.34   3.0%  page act:          2395528                       
IOwait:   00:39:04.09   7.6%  page dea:             3424                       
hw irq:   00:00:00.00   0.0%  page flt:         20783328                       
sw irq:   00:00:29.07   0.1%  swap in :                0                       
idle  :   06:30:26.88  75.6%  swap out:                0                       
uptime:   02:10:11.66         context :         51698643                       

irq   0:         21  2-edge timer        irq  42:          0  466944-edge PCIe 
irq   1:       3823  1-edge i8042        irq  43:     193892  327680-edge xhci_
irq   8:          1  8-edge rtc0         irq  44:     191759  512000-edge 0000:
irq   9:       2175  9-fasteoi acpi      irq  45:    1021515  524288-edge enp1s
irq  12:       6865  12-edge i8042       irq  46:     541926  32768-edge i915  
irq  19:          0  19-fasteoi rtl_pc   irq  47:         14  360448-edge mei_m
irq  23:         33  23-fasteoi ehci_h   irq  48:        344  442368-edge snd_h
irq  40:          0  458752-edge PCIe    irq  49:        749  49152-edge snd_hd
irq  41:          0  464896-edge PCIe                                          

loop0              90r               0   loop4              14r               0
loop1             159r               0   loop5            7945r               0
loop2             214r               0   loop6             309r               0
loop3              79r               0   sda           112544r           70687w

enp1s0      TX 58.30MiB      RX 883.00MiB     vmnet8      TX 0.00B         RX 0.00B        
lo          TX 853.65KiB     RX 853.65KiB     wlp2s0      TX 0.00B         RX 0.00B        
vmnet1      TX 0.00B         RX 0.00B                                          

To print memory stats in human readable format (KiB, MiB, GiB), instead of the default Kbytes, use the -H flag.

$ procinfo -H

Memory:        Total        Used        Free     Buffers                       
RAM:         7.70GiB     7.36GiB   344.27MiB   294.38MiB                       
Swap:        3.73GiB       0.00B     3.73GiB                                   

Bootup: Mon Jun  4 11:09:45 2018   Load average: 0.61 0.84 1.00 2/1017 15439   

user  :   01:09:21.25  13.3%  page in :          2434613                       
nice  :   00:02:12.43   0.4%  page out:          2223808                       
system:   00:15:19.82   2.9%  page act:          2416184                       
IOwait:   00:39:08.21   7.5%  page dea:             3424                       
hw irq:   00:00:00.00   0.0%  page flt:         20891258                       
sw irq:   00:00:29.08   0.1%  swap in :                0                       
idle  :   06:33:48.38  75.7%  swap out:                0                       
uptime:   02:11:06.85         context :         51916194                       

irq   0:         21  2-edge timer        irq  42:          0  466944-edge PCIe 
irq   1:       3985  1-edge i8042        irq  43:     196957  327680-edge xhci_
irq   8:          1  8-edge rtc0         irq  44:     192411  512000-edge 0000:
irq   9:       2196  9-fasteoi acpi      irq  45:    1021900  524288-edge enp1s
irq  12:       6865  12-edge i8042       irq  46:     543742  32768-edge i915  
irq  19:          0  19-fasteoi rtl_pc   irq  47:         14  360448-edge mei_m
irq  23:         33  23-fasteoi ehci_h   irq  48:        344  442368-edge snd_h
irq  40:          0  458752-edge PCIe    irq  49:        749  49152-edge snd_hd
irq  41:          0  464896-edge PCIe                                          

loop0              90r               0   loop4              14r               0
loop1             159r               0   loop5            7945r               0
loop2             214r               0   loop6             309r               0
loop3              79r               0   sda           112568r           71267w

enp1s0      TX 58.33MiB      RX 883.21MiB     vmnet8      TX 0.00B         RX 0.00B        
lo          TX 854.18KiB     RX 854.18KiB     wlp2s0      TX 0.00B         RX 0.00B        
vmnet1      TX 0.00B         RX 0.00B                                        

The -d flag allows for displaying statistics on a per-seconds basis rather than as total values.

$ procinfo -d 

To display statistics as totals, use the -D flag as follows.

$ procinfo -D

You can get continues updates on the screen and pause updates for N number of second (for instance 5seconds in this command) using the -n flag and press q to quit in this mode.

$ procinfo -n5 -H

To report “real” free memory similar to that showed by the free utility, use the -r option.

$ procinfo -r 

To show numbers of bytes instead of number of I/O requests, employ the -b option.

$ procinfo -b

Procinfo works interactively too, when run fullscreen, this allows you to use the dDr and b keys whose functions correspond to their same-named command line flags explained above.

For more information, see the procinfo man page.

$ man procinfo 

In this article, we have explained a number of procinfo command examples.

Source

20 Practical Examples of RPM Commands in Linux

RPM (Red Hat Package Manager) is an default open source and most popular package management utility for Red Hat based systems like (RHELCentOS and Fedora). The tool allows system administrators and users to installupdateuninstallqueryverify and manage system software packages in Unix/Linux operating systems. The RPM formerly known as .rpm file, that includes compiled software programs and libraries needed by the packages. This utility only works with packages that built on .rpm format.

RPM Command Examples

20 Most Useful RPM Command Examples

This article provides some useful 20 RPM command examples that might be helpful to you. With the help of these rpm command you can managed to install, update, remove packages in your Linux systems.

Some Facts about RPM (RedHat Package Manager)

  1. RPM is free and released under GPL (General Public License).
  2. RPM keeps the information of all the installed packages under /var/lib/rpm database.
  3. RPM is the only way to install packages under Linux systems, if you’ve installed packages using source code, then rpm won’t manage it.
  4. RPM deals with .rpm files, which contains the actual information about the packages such as: what it isfrom where it comesdependencies infoversion info etc.

There are five basic modes for RPM command

  1. Install : It is used to install any RPM package.
  2. Remove : It is used to erase, remove or un-install any RPM package.
  3. Upgrade : It is used to update the existing RPM package.
  4. Verify : It is used to verify an RPM packages.
  5. Query : It is used query any RPM package.

Where to find RPM packages

Below is the list of rpm sites, where you can find and download all RPM packages.

  1. http://rpmfind.net
  2. http://www.redhat.com
  3. http://freshrpms.net/
  4. http://rpm.pbone.net/

Read Also :

  1. 20 YUM Command Examples in Linux
  2. 10 Wget Command Examples in Linux
  3. 30 Most Useful Linux Commands for System Administrators

Please remember you must be root user when installing packages in Linux, with the root privileges you can manage rpm commands with their appropriate options.

1. How to Check an RPM Signature Package

Always check the PGP signature of packages before installing them on your Linux systems and make sure its integrity and origin is OK. Use the following command with –checksig (check signature) option to check the signature of a package called pidgin.

[root@tecmint]# rpm --checksig pidgin-2.7.9-5.el6.2.i686.rpm

pidgin-2.7.9-5.el6.2.i686.rpm: rsa sha1 (md5) pgp md5 OK

2. How to Install an RPM Package

For installing an rpm software package, use the following command with -i option. For example, to install an rpm package called pidgin-2.7.9-5.el6.2.i686.rpm.

[root@tecmint]# rpm -ivh pidgin-2.7.9-5.el6.2.i686.rpm

Preparing...                ########################################### [100%]
   1:pidgin                 ########################################### [100%]
RPM command and options
  1. -i : install a package
  2. -v : verbose for a nicer display
  3. -h: print hash marks as the package archive is unpacked.

3. How to check dependencies of RPM Package before Installing

Let’s say you would like to do a dependency check before installing or upgrading a package. For example, use the following command to check the dependencies of BitTorrent-5.2.2-1-Python2.4.noarch.rpm package. It will display the list of dependencies of package.

[root@tecmint]# rpm -qpR BitTorrent-5.2.2-1-Python2.4.noarch.rpm

/usr/bin/python2.4
python >= 2.3
python(abi) = 2.4
python-crypto >= 2.0
python-psyco
python-twisted >= 2.0
python-zopeinterface
rpmlib(CompressedFileNames) = 2.6
RPM command and options
  1. -q : Query a package
  2. -p : List capabilities this package provides.
  3. -R: List capabilities on which this package depends..

4. How to Install a RPM Package Without Dependencies

If you know that all needed packages are already installed and RPM is just being stupid, you can ignore those dependencies by using the option –nodeps (no dependencies check) before installing the package.

[root@tecmint]# rpm -ivh --nodeps BitTorrent-5.2.2-1-Python2.4.noarch.rpm

Preparing...                ########################################### [100%]
   1:BitTorrent             ########################################### [100%]

The above command forcefully install rpm package by ignoring dependencies errors, but if those dependency files are missing, then the program will not work at all, until you install them.

5. How to check an Installed RPM Package

Using -q option with package name, will show whether an rpm installed or not.

[root@tecmint]# rpm -q BitTorrent

BitTorrent-5.2.2-1.noarch

6. How to List all files of an installed RPM package

To view all the files of an installed rpm packages, use the -ql (query list) with rpm command.

[root@tecmint]# rpm -ql BitTorrent

/usr/bin/bittorrent
/usr/bin/bittorrent-console
/usr/bin/bittorrent-curses
/usr/bin/bittorrent-tracker
/usr/bin/changetracker-console
/usr/bin/launchmany-console
/usr/bin/launchmany-curses
/usr/bin/maketorrent
/usr/bin/maketorrent-console
/usr/bin/torrentinfo-console

7. How to List Recently Installed RPM Packages

Use the following rpm command with -qa (query all) option, will list all the recently installed rpm packages.

[root@tecmint]# rpm -qa --last

BitTorrent-5.2.2-1.noarch                     Tue 04 Dec 2012 05:14:06 PM BDT
pidgin-2.7.9-5.el6.2.i686                     Tue 04 Dec 2012 05:13:51 PM BDT
cyrus-sasl-devel-2.1.23-13.el6_3.1.i686       Tue 04 Dec 2012 04:43:06 PM BDT
cyrus-sasl-2.1.23-13.el6_3.1.i686             Tue 04 Dec 2012 04:43:05 PM BDT
cyrus-sasl-md5-2.1.23-13.el6_3.1.i686         Tue 04 Dec 2012 04:43:04 PM BDT
cyrus-sasl-plain-2.1.23-13.el6_3.1.i686       Tue 04 Dec 2012 04:43:03 PM BDT

8. How to List All Installed RPM Packages

Type the following command to print the all the names of installed packages on your Linux system.

[root@tecmint]# rpm -qa

initscripts-9.03.31-2.el6.centos.i686
polkit-desktop-policy-0.96-2.el6_0.1.noarch
thunderbird-17.0-1.el6.remi.i686

9. How to Upgrade a RPM Package

If we want to upgrade any RPM package “–U” (upgrade) option will be used. One of the major advantages of using this option is that it will not only upgrade the latest version of any package, but it will also maintain the backup of the older package so that in case if the newer upgraded package does not run the previously installed package can be used again.

[root@tecmint]# rpm -Uvh nx-3.5.0-2.el6.centos.i686.rpm
Preparing...                ########################################### [100%]
   1:nx                     ########################################### [100%]

10. How to Remove a RPM Package

To un-install an RPM package, for example we use the package name nx, not the original package name nx-3.5.0-2.el6.centos.i686.rpm. The -e (erase) option is used to remove package.

[root@tecmint]# rpm -evv nx

11. How to Remove an RPM Package Without Dependencies

The –nodeps (Do not check dependencies) option forcefully remove the rpm package from the system. But keep in mind removing particular package may break other working applications.

[root@tecmint]# rpm -ev --nodeps vsftpd

12. How to Query a file that belongs which RPM Package

Let’s say, you have list of files and you would like to find out which package belongs to these files. For example, the following command with -qf (query file) option will show you a file /usr/bin/htpasswd is own by package httpd-tools-2.2.15-15.el6.centos.1.i686.

[root@tecmint]# rpm -qf /usr/bin/htpasswd

httpd-tools-2.2.15-15.el6.centos.1.i686

13. How to Query a Information of Installed RPM Package

Let’s say you have installed an rpm package and want to know the information about the package. The following -qi (query info) option will print the available information of the installed package.

[root@tecmint]# rpm -qi vsftpd

Name        : vsftpd				   Relocations: (not relocatable)
Version     : 2.2.2				   Vendor: CentOS
Release     : 11.el6				   Build Date: Fri 22 Jun 2012 01:54:24 PM BDT
Install Date: Mon 17 Sep 2012 07:55:28 PM BDT      Build Host: c6b8.bsys.dev.centos.org
Group       : System Environment/Daemons           Source RPM: vsftpd-2.2.2-11.el6.src.rpm
Size        : 351932                               License: GPLv2 with exceptions
Signature   : RSA/SHA1, Mon 25 Jun 2012 04:07:34 AM BDT, Key ID 0946fca2c105b9de
Packager    : CentOS BuildSystem <http://bugs.centos.org>
URL         : http://vsftpd.beasts.org/
Summary     : Very Secure Ftp Daemon
Description :
vsftpd is a Very Secure FTP daemon. It was written completely from
scratch.

14. Get the Information of RPM Package Before Installing

You have download a package from the internet and want to know the information of a package before installing. For example, the following option -qip (query info package) will print the information of a package sqlbuddy.

[root@tecmint]# rpm -qip sqlbuddy-1.3.3-1.noarch.rpm

Name        : sqlbuddy                     Relocations: (not relocatable)
Version     : 1.3.3                        Vendor: (none)
Release     : 1                            Build Date: Wed 02 Nov 2011 11:01:21 PM BDT
Install Date: (not installed)              Build Host: rpm.bar.baz
Group       : Applications/Internet        Source RPM: sqlbuddy-1.3.3-1.src.rpm
Size        : 1155804                      License: MIT
Signature   : (none)
Packager    : Erik M Jacobs
URL         : http://www.sqlbuddy.com/
Summary     : SQL Buddy â Web based MySQL administration
Description :
SQLBuddy is a PHP script that allows for web-based MySQL administration.

15. How to Query documentation of Installed RPM Package

To get the list of available documentation of an installed package, use the following command with option -qdf(query document file) will display the manual pages related to vmstat package.

[root@tecmint]# rpm -qdf /usr/bin/vmstat

/usr/share/doc/procps-3.2.8/BUGS
/usr/share/doc/procps-3.2.8/COPYING
/usr/share/doc/procps-3.2.8/COPYING.LIB
/usr/share/doc/procps-3.2.8/FAQ
/usr/share/doc/procps-3.2.8/NEWS
/usr/share/doc/procps-3.2.8/TODO

16. How to Verify a RPM Package

Verifying a package compares information of installed files of the package against the rpm database. The -Vp(verify package) is used to verify a package.

[root@tecmint downloads]# rpm -Vp sqlbuddy-1.3.3-1.noarch.rpm

S.5....T.  c /etc/httpd/conf.d/sqlbuddy.conf

17. How to Verify all RPM Packages

Type the following command to verify all the installed rpm packages.

[root@tecmint]# rpm -Va

S.5....T.  c /etc/rc.d/rc.local
.......T.  c /etc/dnsmasq.conf
.......T.    /etc/ld.so.conf.d/kernel-2.6.32-279.5.2.el6.i686.conf
S.5....T.  c /etc/yum.conf
S.5....T.  c /etc/yum.repos.d/epel.repo

18. How to Import an RPM GPG key

To verify RHEL/CentOS/Fedora packages, you must import the GPG key. To do so, execute the following command. It will import CentOS 6 GPG key.

[root@tecmint]# rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

19. How to List all Imported RPM GPG keys

To print all the imported GPG keys in your system, use the following command.

[root@tecmint]# rpm -qa gpg-pubkey*

gpg-pubkey-0608b895-4bd22942
gpg-pubkey-7fac5991-4615767f
gpg-pubkey-0f2672c8-4cd950ee
gpg-pubkey-c105b9de-4e0fd3a3
gpg-pubkey-00f97f56-467e318a
gpg-pubkey-6b8d79e6-3f49313d
gpg-pubkey-849c449f-4cb9df30

20. How To rebuild Corrupted RPM Database

Sometimes rpm database gets corrupted and stops all the functionality of rpm and other applications on the system. So, at the time we need to rebuild the rpm database and restore it with the help of following command.

[root@tecmint]# cd /var/lib
[root@tecmint]# rm __db*
[root@tecmint]# rpm --rebuilddb
[root@tecmint]# rpmdb_verify Packages

Source

3 of the Best System Monitor Tools for Ubuntu

As the number of devices, servers, and services you have in your business or organization grows, so does the need to monitor your systems. System monitoring, whether on premise or in the cloud, covers the capacity, activity, and health of the hosts and apps. The process is designed to cover all computing resources to root out and tackle problems in real-time before they occur.

If you’re using Ubuntu, system monitoring tools will help you spot any service failures or errors before they impact users.

The most basic tool at your disposal is the System Monitor, a built-in utility for Linux that acts like Windows’ Task Manager and offers basic activity monitoring information from running processes to what consumes the most resources.

However, you can get sophisticated system monitoring tools that show you more resource utilization information for memory, CPU, disk, and network connections.

Here are three you can use with Ubuntu.

1. Nagios

best-system-monitoring-tools-ubuntu-nagios-logo

This system monitoring tool for Ubuntu offers complete monitoring of servers and workstations – including service and process state, operating system metrics, and file system usage, plus more.

It is powerful, scalable, reliable, and customizable software, despite being complex to configure. As an enduring standard in system and network monitoring, Nagios offers immense benefits such as fast detection of protocol failures and network outages, plus increased availability of services, server, and applications.

Two solutions are available for system monitoring: Nagios Core and Nagios XI.

Nagios Core

best-system-monitoring-tools-ubuntu-nagioscore

This is the open-source free version that monitors servers, applications, and services, with features such as a basic user interface with network map, reporting by SMS and email, and basic reports.

Nagios Core monitors your critical IT infrastructure components from system metrics, servers, applications, services, and network protocols. It then sends you alerts via SMS, email, or custom script when critical components fail and recover, so your admins are always notified of important events.

Reports are available providing a historical record of events, outages, notifications and alert responses for your review later plus advanced graphs to plan for upgrades before outdated systems catch you offguard.

It is a powerful open-source option for Ubuntu system monitoring with great features like a web interface, multi-tenant capabilities, and extendable architecture through integration with in-house or third-party apps, and other community-developed add-ons.

While it may have a learning curve to begin with, an active community is available if you need assistance.

Nagios XI

best-system-monitoring-tools-ubuntu-nagiosxi

This is the commercial variant of the tool that has a richer range of features and automated configuration assistance.

Among its powerful features (over and above what Core offers) include the powerful Nagios Core 4 monitoring engine that gives you the highest degree of server performance monitoring.

Also included are configuration wizards to guide users through monitoring of devices, services and applications, and a configuration snapshot to save recent configurations and revert to them when you want.

You can customize your design, layout, and preferences on a per-user basis using the updated GUI, so your customers and teams get the flexibility they want. It also offers custom role assignment that ensures a secure environment.

What we like about Nagios

  • Easy to use
  • Offers free and premium (with 60-day trial) options
  • Comprehensive IT infrastructure monitoring as all mission-critical infrastructure components are monitored.
  • Allows multiple users to access the web interface and view the relevant infrastructure status
  • Fast configuration in a few simple clicks
  • Easy to set up and manage user accounts
  • Extendable architecture using add-ons

2. Glances

best-system-monitoring-tools-ubuntu-glances-2

This is a cross-platform, data-center monitoring tool that runs on GNU/Linux, macOS, Windows, and BSD operating systems. It is written in Python language using the psutil library from where it draws information from the system, giving you as much as you need at a glance.

You can use Glance to monitor load average, CPU, memory, disk I/O, network interfaces, mounted devices, file system space utilization, plus all active and top processes.

One of its main features is the ability to set thresholds in a configuration file with four options displayed in different colors that indicate the logjam in the system: OK (green), careful (blue), warning (violet), and critical (red).

The threshold levels are set at 50, 70, and 90 for careful, warning, and critical levels respectively. You can customize these using the “glances.conf” file found in the “/etc/glances/” directory.

best-system-monitoring-tools-ubuntu-glances

View critical information such as the average CPU load, disk I/O read/write speeds, current disk usage for mounted devices, and top processes together with their CPU/memory usage.

The downside with having all this information is that Glances tends to use a significant amount of CPU resources.

If you need help with Glances, there are wikis available on their website. You can also contact other developers and users on Twitter, Chat for developers, and user groups.

What we like about Glances

  • Easy to install as it is available on Ubuntu’s repository
  • Displays more information compared to other monitoring tools
  • Web-based GUI makes monitoring flexible
  • Can monitor remote systems

3. htop

best-system-monitoring-tools-ubuntu-htop

htop is an interactive process reviewer and text-mode application that performs system monitoring in real-time. It offers a complete view of processes that are running and their usage. This way you can free your system from any malfunctions as it serves its purpose.

The tool is based on “ncurses” and offers support for mouse operation. Like other tools, htop uses color to give visual indications of the memory, processor, and swap usage.

A flexible, clean, and easy-to-configure summary section displayed in two columns lets you view information about your system. However, some information like CPU percentages by idle, user, or system time, may not be available.

Function keys are available to configure the summary section and add data display lists to either column. There’s also a process section that sorts factors such as memory/CPU usage, PID, or user.

Note: htop is now cross-platform since version 2.0, supporting Linux, BSD, and macOS.

What we like about htop

  • Clean and easy-to-read summary section
  • Each user has a configuration file
  • Automatic save for any changes stored in configuration files

Source

How to Find Out Top Directories and Files (Disk Space) in Linux

As a Linux administrator, you must periodically check which files and folders are consuming more disk space. It is very necessary to find the unnecessary junks and free up them from your hard disk.

This brief tutorial describes how to find the largest files and folders in the Linux file system using du and findcommand. If you want to learn more about these two commands, then head over to the following articles.

  1. Learn 10 Useful ‘du’ (Disk Usage) Commands in Linux
  2. Master the ‘Find’ Command with this 35 Practical Examples

How to Find Biggest Files and Directories in Linux

Run the following command to find out top biggest directories under /home partition.

# du -a /home | sort -n -r | head -n 5

Find Largest Directories in Linux

Find Largest Directories in Linux

The above command displays the biggest 5 directories of my /home partition.

Find Largest Directories in Linux

If you want to display the biggest directories in the current working directory, run:

# du -a | sort -n -r | head -n 5

Find Biggest Directories Only

Find Biggest Directories Only

Let us break down the command and see what says each parameter.

  1. du command: Estimate file space usage.
  2. a : Displays all files and folders.
  3. sort command : Sort lines of text files.
  4. -n : Compare according to string numerical value.
  5. -r : Reverse the result of comparisons.
  6. head : Output the first part of files.
  7. -n : Print the first ‘n’ lines. (In our case, We displayed first 5 lines).

Some of you would like to display the above result in human readable format. i.e you might want to display the largest files in KBMB, or GB.

# du -hs * | sort -rh | head -5

Find Top Directories Sizes in Linux

Find Top Directories Sizes in Linux

The above command will show the top directories, which are eating up more disk space. If you feel that some directories are not important, you can simply delete few sub-directories or delete the entire folder to free up some space.

To display the largest folders/files including the sub-directories, run:

# du -Sh | sort -rh | head -5

Find Largest Folder and Sub directories

Find Largest Folder and Sub directories

Find out the meaning of each options using in above command:

  1. du command: Estimate file space usage.
  2. -h : Print sizes in human readable format (e.g., 10MB).
  3. -S : Do not include size of subdirectories.
  4. -s : Display only a total for each argument.
  5. sort command : sort lines of text files.
  6. -r : Reverse the result of comparisons.
  7. -h : Compare human readable numbers (e.g., 2K, 1G).
  8. head : Output the first part of files.

Find Out Top File Sizes Only

If you want to display the biggest file sizes only, then run the following command:

# find -type f -exec du -Sh {} + | sort -rh | head -n 5

Find Top File Sizes in Linux

Find Top File Sizes in Linux

To find the largest files in a particular location, just include the path besides the find command:

# find /home/tecmint/Downloads/ -type f -exec du -Sh {} + | sort -rh | head -n 5
OR
# find /home/tecmint/Downloads/ -type f -printf "%s %p\n" | sort -rn | head -n 5

Find Top File Size in Specific Location

Find Top File Size in Specific Location

The above command will display the largest file from /home/tecmint/Downloads directory.

That’s all for now. Finding biggest files and folders is no big deal. Even a novice administrator can easily find them. If you find this tutorial useful, please share on your social networks and support TecMint.

Source

10 Useful ‘locate’ Command Practical Examples for Linux Newbies

One of most obnoxious experiences that most new users of the Linux platform usually face is the inability to find the simplest and yet more effective means of looking up files on their system.

Linux, like almost any other operating system, utilizes several mechanisms to answer search queries for users. Two of the most popular file searching utilities accessible to users are called find and locate.

Now, it is important to note that both search processes work extremely well but nonetheless, the center of this article will be more on the locate utility, which is the more convenient of the two as it uses more efficient ways to quickly process queries inputted by the users.

The locate utility works better and faster than it’s find counterpart because instead of searching the file system when a file search is initiated – Something find does – locate would look through a database. This database contains bits and parts of files and their corresponding paths on your system.

Here are ten simple locate commands to set you up in becoming more productive with your Linux machine.

1. Using locate Command

Firing locate command to look for a file is pretty easy and straightforward. All you need to do is type:

$ locate LAMP-Setup.odt

/home/tecmint/LAMP-Setup.odt
/home/tecmint/TecMint.com/LAMP-Setup.odt

2. Limit Search Queries to a Specific Number

You can limit your search returns to a required number to avoid redundancy with your search results using the -n command.

For example, if you want just 20 results from your queries, you can type the following command:

$ locate "*.html" -n 20

/home/tecmint/.config/google-chrome/Default/Extensions/aapocclcgogkmnckokdopfmhonfmgoek/0.9_0/main.html
/home/tecmint/.config/google-chrome/Default/Extensions/aohghmighlieiainnegkcijnfilokake/0.9_0/main.html
/home/tecmint/.config/google-chrome/Default/Extensions/felcaaldnbdncclmgdcncolpebgiejap/1.1_0/main.html
/home/tecmint/.config/google-chrome/Default/Extensions/kbfnbcaeplbcioakkpcpgfkobkghlhen/14.752.848_0/forge.html
/home/tecmint/.config/google-chrome/Default/Extensions/kbfnbcaeplbcioakkpcpgfkobkghlhen/14.752.848_0/src/popup.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/additional-feature.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/background.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/edit.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/help.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/options.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/popup.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/purchase.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/upload.html
/home/tecmint/.config/google-chrome/Default/Extensions/nlipoenfbbikpbjkfpfillcgkoblgpmj/3.9.16_0/oauth2/oauth2.html
/home/tecmint/.config/google-chrome/Default/Extensions/nmmhkkegccagdldgiimedpiccmgmieda/1.0.0.2_0/html/craw_window.html
/home/tecmint/.config/google-chrome/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm/5516.1005.0.3_0/cast_route_details.html
/home/tecmint/.config/google-chrome/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm/5516.1005.0.3_0/feedback.html
/home/tecmint/.config/google-chrome/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm/5516.1005.0.3_0/cast_setup/devices.html
/home/tecmint/.config/google-chrome/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm/5516.1005.0.3_0/cast_setup/index.html
/home/tecmint/.config/google-chrome/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm/5516.1005.0.3_0/cast_setup/offers.html

The results will show the first 20 files that end with .html.

3. Display The Number of Matching Entries

If you want to display the count of all matching entries of file “tecmint“, use the locate -c command.

$ locate -c [tecmint]*

1550

4. Ignore Case Sensitive Locate Outputs

By default, locate is configured to process queries in a case sensitive manner meaning TEXT.TXT will point you to a different result than text.txt.

To have locate command ignore case sensitivity and show results for both uppercase and lowercase queries, input commands with the -i option.

$ locate -i *text.txt*

/home/tecmint/TEXT.txt
/home/tecmint/text.txt

5. Refresh mlocate Database

Since locate command relies on a database called mlocate. The said database needs to be updated regularly for the command utility to work
efficiently.

To update the mlocate database, you use a utility called updatedb. It should be noted that you will need superuser privileges for this to work properly, is it needs to be executed as root or sudo privileges.

$ sudo updatedb

6. Display Only Files Present in Your System

When you have an updated mlocate database**, locate command still produces results of files whose physical copies are deleted from your system.

To avoid seeing results of files not present in your machine at the time of punching in the command, you will need to use the locate-e command. The process searches your system to verify the existence of the file you’re looking for even if it is still present in your mlocate.db.

$ locate -i -e *text.txt*

/home/tecmint/text.txt

7. Separate Output Entries Without New Line

locate command’s default separator is the newline (\\n) character. But if you prefer to use a different separator like the ASCII NUL, you can do so using the -0 command line option.

$ locate -i -0 *text.txt*

/home/tecmint/TEXT.txt/home/tecmint/text.txt

8. Review Your Locate Database

If you’re in doubt as to the current status of your mlocate.db, you can easily view the locate database statistics by using the -S command.

$ locate -S

Database /var/lib/mlocate/mlocate.db:
	32,246 directories
	4,18,850 files
	2,92,36,692 bytes in file names
	1,13,64,319 bytes used to store database

9. Suppress Error Messages in Locate

Constantly trying to access your locate database does sometimes yield unnecessary error messages stating that you do not have the required privileges to have root access to the mlocate.db, because you’re only a normal user and not the required Superuser.

To completely do away with these message, use the -q command.

$ locate "\*.dat" -q*

10. Choose a Different mlocate Location

If you’re inputting queries looking for results not present in the default mlocate database and want answers from a different mlocate.db located somewhere else in your system, you can point the locate command to a different mlocate database at a different part of your system with the -d command.

$ locate -d <new db path> <filename>

locate command might seem like one of those utilities that does everything you asked it to do without much of a hustle but in truth, in order for the process to keep its efficiency, the mlocate.db needs to be fed with information every now and then. Failure to do so might render the program a bit useless.

Source

10 Interesting Linux Command Line Tricks and Tips Worth Knowing

I passionately enjoy working with commands as they offer more control over a Linux system than GUIs(Graphical User Interfaces) applications, therefore am always on the look out to discover or figure out interesting ways and ideas to make Linux so easy and fun to operate, primarily from the terminal.

It is always thrilling when we discover new tricks or tips while using Linux especially a command line geek like myself.

Suggested Read: 5 Interesting Command Line Tips and Tricks in Linux – Part 1

And the feeling of wanting to share newly learned practices or commands with millions of Linux users out there, particularly the newbies who are still getting their way around this exciting operating system normally sets in.

Suggested Read: 10 Useful Linux Command Line Tricks for Newbies – Part 2

In this article, we will review a number of useful command line tricks and tips that can significantly enhance your Linux usage skills.

1. Lock or Hide a File or Directory in Linux

The simplest way of locking a file or directory is by using Linux file permissions. In case your the owner of a file or directory, you can block (remove read, write and execute privileges) other users and groups from accessing it as follows:

$ chmod 700 tecmint.info
OR
$ chmod go-rwx tecmint.info

To know more about Linux file permissions, read this article Managing Users & Groups, File Permissions & Attributes in Linux.

To hide the file/directory from other system users, rename it with a (.) at the start of the file or directory:

$ mv filename .tecmint.info

2. Translate rwx Permissions into Octal Format in Linux

By default, when you run the ls command, it displays file permissions in rwx format, but to understand the equivalence of this format and the octal format, you can learn how to translate rwx permissions into Octal format in Linux.

3. How to Use ‘su’ When ‘sudo’ Fails

Although sudo command is used to execute commands with superuser privileges, there are moments when it fails to work as in the example below.

Here, I want to empty the contents of a large file named uptime.log but the operation has failed even when I used sudo.

$ cat /dev/null >/var/log/uptime.log 
$ sudo cat /dev/null >/var/log/uptime.log

Empty Large File Content in Linux

Empty Large File Content in Linux

In such as case, you need to switch to the root user account using su command to perform the operation like so:

$ su
$ sudo cat /dev/null >/var/log/uptime.log
$ cat /var/log/uptime.log

Switch to Super User

Switch to Super User

Try to understand the difference between su and sudo, in addition, read through their man pages for more guidelines:

$ man sudo
$ man su

4. Kill a Process in Linux

Sometimes when you want to terminate a process using kill or killall or pkill commands, it may fail to work, you realize that the process still continues to run on the system.

In order to destructively kill a process, send the -KILL siganl to it.

First determine its process ID and then kill it like so:

$ pidof vlc
$ sudo kill -KILL 10279

Find and Kill Process in Linux

Find and Kill Process in Linux

Check the kill command for additional usage options and information.

5. Delete File Permanently in Linux

Normally, we use the rm command to delete files from a Linux system, however, these files do not completely get deleted, they are simply stored and hidden on the hard disk and can still be recovered these files in Linuxand viewed by another person.

To prevent this, we can use the shred command which overwrites the file content and optionally deletes the file as well.

$ shred -zvu tecmint.pdf

The options used in the above command:

  1. -z – adds a final overwrite with zeros to hide shredding.
  2. -u – helps to truncate and remove file after overwriting.
  3. -v – shows progress.

Delete File Permanently in Linux

Delete File Permanently in Linux

Read through shred man page for additional usage instructions:

$ man shred

6. Rename Multiple Files in Linux

You can rename multiple files in Linux on the go by invoking the rename command.

It renames the filenames supplied according to a rule specified in the first argument.

The command below renames all .pdf files to .doc, here 's/\.pdf$/\.doc/' is the rule:

$ rename -v 's/\.pdf$/\.doc/' *.pdf

Rename Multiple Files in Linux

Rename Multiple Files in Linux

The next example renames all files matching "*.bak" to strip the extension, where 's/\e.bak$//' is the rule:

 

7. Check for Spelling of Words in Linux

The look command displays lines beginning with a given string, it can help you to check for the spelling of word from within the command line. Although it is not so effective and reliable, look is still a useful alternative to other powerful spelling-checkers:

$ look linu
$ look docum

Spell Checking in Linux

Spell Checking in Linux

8. Search for Description of Keyword in Manual Page

The man command is used to display manual entry pages of commands, when used with the -k switch, it searches the short descriptions and manual page names for the keyword printf (such as adjust, apache and php in the commands below) as regular expression.

$ man -k adjust
$ man -k apache
$ man -k php

Show Description of Keyword in Manual Pages

Show Description of Keyword in Manual Pages

9. Watch Logs in Real-Time in Linux

With watch command, you can run another Linux command periodically while displaying its output on fullscreen and alongside tail command which is used to view the last parts of a file, it is possible to watch the recording of log entries in a logfile.

In the example below, you will watch the system authentication logfile. Open two terminal windows, display the logfile for watching in real-time in the first window like so:

$ sudo watch tail /var/log/auth.log

You can also use tail command which shows the last parts of a file. Its -f flag enables watching changes in a file in real-time, therefore it is possible to watch the recording of log entries in a logfile.

$ sudo tail -f /var/log/auth.log

And run the commands below in the second terminal as you observe the logfile content from the first window:

$ sudo mkdir -p /etc/test
$ sudo rm -rf /etc/test

10. List All Shell builtin Commands

shell builtin is a command or a function, called from within and executed directly in the shell itself, instead of an external executable program which the shell would load from the hard disk and execute.

To list all shell builtins and their usage syntax, run:

$ help

As a concluding remark, command line tricks and tips always come in handy and make learning and using Linux easy and fun especially for newbies.

You can as well share with us other useful and interesting command line tricks or tips in Linux that you have come across via the comment form below.

Source

How to Find and Kill Running Processes in Linux

Process management is one of the important aspects of System Administration in Linux, and it includes killing of processes using the kill command.

Find and Kill Running Processes in Linux

Find and Kill Running Processes in Linux

In this how-to, we shall look at killing of less productive or unwanted processes on your Linux system.

What is a Process in Linux?

A process on a Linux system can be a running occurrence of an application or program. You can also refer to processes as tasks executing in the operating system.

When a process is running, it keeps on shifting from one state to another and a process can in one of the following states:

  1. Running: meaning the process is either executing or it is just set to be executed.
  2. Waiting: meaning that the process is waiting for an event or for a system resource to carry out a task.

There are two types of waiting process under Linux namely interruptible and uninterruptible.

A waiting process that can be interrupted by signals is called Interruptible, while a waiting process that is directly waiting on hardware conditions and cannot be interrupted under any conditions is called uninterruptible.

  1. Stopped: meaning that the process has been stopped, using a signal.
  2. Zombie: meaning the process has been stopped abruptly and is dead.

With this brief overview let us now look at ways of killing processes in a Linux system. We’ve already covered a few articles on ways to kill Linux running processes us using kill, pkill, killall and xkill, you can read them below.

  1. A Guide to Manage Linux Processes Using Kill, Pkill and Killall Commands
  2. How to Kill Unresponsive Linux Processes Using Xkill Command

When killing processes, the kill command is used to send a named signal to a named process or groups of processes. The default signal is the TERM signal.

Remember that the kill command can be a built-in function in many modern shells or external located at /bin/kill.

How to Find Process PID in Linux

In Linux every process on a system has a PID (Process Identification Number) which can be used to kill the process.

You can identify the PID of any process by using the pidof command as follows:

$ pidof firefox
$ pidof chrome
$ pidof gimp-2.8

Find Process PID in Linux

Find Process PID in Linux

How to Kill Processes in Linux

Once you find the process PID, let us now look at how to kill processes. In this first example, I am going to first get the PID of the process and then send a signal to it.

I want to kill gimp process, so I will do it as follows:

$ pidof gimp-2.8
$ kill 9378

To verify that the process has been killed, run the pidof command and you will not be able to view the PID.

$ pidof gimp-2.8

Kill Linux Process PID

Kill Linux Process PID

You can also send a named signal to the process by using the signal name or numbers as follows:

$ pidof vlc
$ kill -SIGTERM 9541
$ pidof vlc

Kill Linux Process PID by Signal

Kill Process PID by Signal

Using the signal number to kill a process:

$ pidof banshee
$ kill -9 9647
$ pidof banshee

Kill Linux Process PID by Number

Kill Process PID by Number

In the above example, the number 9 is the signal number for the SIGKILL signal.

How to Kill Multiple Process PID’s in Linux

To kill more than one process, pass the PID(s) to the kill command as follows:

$ pidof gimp-2.8
$ pidof vlc
$ pidof banshee
$ kill -9 9734 9747 9762

Kill Multiple Linux Process PID's

Kill Multiple Linux Process PID’s

Summary

There are many other ways of killing processes in Linux, these few examples just help to give you an overview of killing processes. Do let us know how you kill processes in Linux? and also tell other ways if any via comments.

Source

Ncdu a NCurses Based Disk Usage Analyzer and Tracker

ncdu (NCurses Disk Usage) is a command line version of the most popular “du command“. It is based on ncurses and provides a fastest way to analyse and track what files and directories are using your disk space in Linux. It provides an excellent ncurses based interface to display the information in more intuitive way like columns for how much disk space used in megabytesgigabytes and graphical bar usage, file/directory namesfile deletionrefresh, etc. ncdu aims to be simple, fast and easy to use program and runs on any minimal Linux/Unix based system with ncurses installed.

ncdu commands

Install NCDU Tool

This article explains you through the process of installing and using NCDU program on a Linux system.

Installing ncdu (NCurses Disk Usage)

The “ncdu” package is not available under RHELCentOSFedoraScientific Linux distributions, you must have epel repository enabled on your system to install it using yum command.

# yum install ncdu

The “ncdu” utility is available on UbuntuLinux Mint and Debian from the package manager system, use the following apt-get command to install it.

$ sudo apt-get install ncdu

How Do I Use ncdu

Source

WP2Social Auto Publish Powered By : XYZScripts.com