How to Run Shell Scripts with Sudo Command in Linux

sudo is a powerful command line tool that enables a “permitted user” to run a command as another user (the superuser by default), as defined by a security policy. On most if not all Linux systems, the security policy is driven by the /etc/sudoers file.

Read Also10 Useful Sudoers Configurations for Setting ‘sudo’ in Linux

Therefore, to run a shell script or program as root, you need to use sudo command. However, sudo only recognizes and runs commands that exist in directories specified in the secure_path in the /etc/sudoers, unless a command is present in the secure_path, you’ll counter an error such as the one below.

This will happen even if the script exists in a directory in the PATH environmental variable, because when a user invokes sudoPATH is replaced with secure_path.

$ echo  $PATH
$ ls  -l
$ sudo proconport.sh 80

Sudo Error While Running Script

Sudo Error While Running Script

In the above scenario, the directory /home/aaronkilik/bin is in the PATH environment variable and we are trying to run the script /home/aaronkilik/bin/proconport.sh (finds process listening on a port) with root privileges.

Then we encountered the error “sudo: proconport.sh: command not found”, since /home/aaronkilik/bin is not in the sudo secure_path as shown in next screenshot.

Check Sudo Secure Path

Check Sudo Secure Path

To fix this, we need to add the directory containing our scripts in the sudo secure_path by using the visudo command by editing /etc/sudoers file as follows.

$ sudo visudo

Attention: This method has serious security implications especially on servers running on the Internet. This way, we risk exposing our systems to various attacks, because an attacker who manages to gain access to an unsecure (without superuser privileges) directory that has been added to secure_path, can run a malicious script/program with sudo command.

For security reason, do check out the following article from the sudo website explains a vulnerability relating to secure_path: https://www.sudo.ws/sudo/alerts/secure_path.html

Preferably, we can provide the absolute path to a script while running it with sudo:

$ sudo ./proconport.sh 80

Run Script Using Sudo Command

Run Script Using Sudo Command

That’s It! You may follow list of articles about sudo command:

  1. How to Run ‘sudo’ Command Without Entering a Password in Linux
  2. How to Keep ‘sudo’ Password Timeout Session Longer in Linux
  3. How to Fix “Username is not in the sudoers file. This incident will be reported” in Ubuntu
  4. Let Sudo Insult You When You Enter Incorrect Password

Source

How to Check Remote Ports are Reachable Using ‘nc’ Command

port is a logical entity which acts as a endpoint of communication associated with an application or process on an Linux operating system. It is useful to know which ports are open and running services on a target machine before using them.

We can easily list open ports in Linux on a local machine using the netstat or several other Linux commands such NMAP.

In this guide, we will show you how to determine if ports on a remote host are reachable/open using simple netcat (in short nc) command.

netcat (or nc in short) is a powerful and easy-to-use utility that can be employed for just about anything in Linux in relation to TCP, UDP, or UNIX-domain sockets.

# yum install nc                  [On CentOS/RHEL]
# dnf install nc                  [On Fedora 22+]
$ sudo apt-get install netcat     [On Debian/Ubuntu]

We can use it to: open TCP connections, listen on arbitrary TCP and UDP ports, send UDP packets, do port scanning under both IPv4 and IPv6 and beyond.

Using netcat, you can check if a single or multiple or a range of open ports as follows. The command below will help us see if the port 22 is open on the host 192.168.56.10:

$ nc -zv 192.168.1.15 22

In the command above, the flag:

  1. -z – sets nc to simply scan for listening daemons, without actually sending any data to them.
  2. -v – enables verbose mode.

The next command will check if ports 8022 and 21 are open on the remote host 192.168.5.10 (we can use the hostname as well):
nc -zv 192.168.56.10 80 22 21

It is also possible to specify a range of ports to be scanned:’

$ nc -zv 192.168.56.10 20-80

For more examples and usage of netcat command, read through our articles as follows.

  1. Transfer Files Between Linux Servers Using netcat Command
  2. Linux Network Configuration and Troubleshooting Commands

That’s all. In this article, we explained how to check if ports on a remote host are reachable/open using simple netcat commands.

Source

4 Ways to Find Server Public IP Address in Linux Terminal

In computer networking, an IP (Internet Protocol) address is a numerical identifier assigned permanently or temporarily to every device connected to a network that uses the Internet Protocol for communication. Its two major functions are to identify a network or host on a network and also serve for location addressing.

Read AlsoHow to Set Static IP Address and Configure Network in Linux

There are currently two versions of IP addresses: IPv4 and IPv6, which can either be private (viewable within an internal network) or public (can be seen by other machines on the Internet).

Additionally, a host can be assigned a static or dynamic IP address depending on the network configurations. In this article, we will show you 4 ways to find your Linux machine or server public IP address from the terminal in Linux.

1. Using dig Utility

dig (domain information groper) is a simple command line utility for probing DNS name servers. To find your public IP addresses, use the opendns.com resolver as in the command below:

$ dig +short myip.opendns.com @resolver1.opendns.com

120.88.41.175

2. Using host Utility

host command is an easy-to-use command line utility for carrying out DNS lookups. The command below will help to display your systems public IP address.

$ host myip.opendns.com resolver1.opendns.com | grep "myip.opendns.com has" | awk '{print $4}'

120.88.41.175

Important: The next two methods employ third party websites to display your IP address on the command line as described below.

3. Using wget Command Line Downloader

wget is a powerful command line downloader that supports various protocols like HTTP, HTTPS, FTP and many more. You can use it with third party websites to view your public IP address as follows:

$ wget -qO- http://ipecho.net/plain | xargs echo
$ wget -qO - icanhazip.com

120.88.41.175

4. Using cURL Command Line Downloader

curl is a popular command line tool for uploading or downloading files from a server using any of the supported protocols (HTTP, HTTPS, FILE, FTP, FTPS and others). The following commands displays your public IP address.

$ curl ifconfig.co
$ curl ifconfig.me
$ curl icanhazip.com

120.88.41.175

That’s It! You may find these following articles useful to read.

  1. 5 Linux Command Line Based Tools for Downloading Files and Browsing Websites
  2. 11 Ways to Find User Account Info and Login Details in Linux
  3. 7 Ways to Determine the File System Type in Linux (Ext2, Ext3 or Ext4)

That’s all! If you have any questions or other methods to share in relation to this topic, use the feedback form below to write back to us.

Source

A – Z LINUX COMMANDS (136) – OVERVIEW WITH EXAMPLES

Linux Commands Cheat Sheet

adduser/addgroup agetty alias anacron
apropos apt apt-get aptitude
arch arp at atq
atrm awk batch basename
bc bg bzip cal
cat chgrp chmod chown
cksum clear cmp comm
cp date dd df
diff dir dmidecode du
echo eject env exit
expr factor find free
grep groups gzip gunzip
head history hostname hostnamectl
hwclock hwinfo id ifconfig
ionice iostat ip iptables
iw iwlist kill killall
kmod last ln locate
login ls lshw lscpu
lsof lsusb man mdsum
mkdir more mv nano
nc/netcat netstat nice nmap
nproc openssl passwd pidof
ping ps pstree pwd
rdiff-backup reboot rename rm
rmdir scp shutdown sleep
sort split ssh stat
su sudo sum tac
tail talk tar tee
time top touch tr
uname uniq uptime users
vim/vi w wall watch
wc wget whatis which
who whereis xargs yes
youtube-dl zcmp/zdiff zip zz

There are a countless number of commands in Linux. We are bound to use a number of them on a daily routine or numerous times to perform common tasks than others. It is important to note that certain commands are “distro-based” – they can only be found in specific distros. While others are generic Unix/Linux commands that you’ll find in all if not most mainstream distros.

In this article, we will introduce you a list of most frequently used Linux commands with their examples for easy learning. You can find the actual description of each Linux command in their manual page which you can access like this:

$ man command-name

adduser/addgroup Command

The adduser and addgroup commands are used to add a user and group to the system respectively according to the default configuration specified in /etc/adduser.conf file.

$ sudo adduser tecmint

For more adduser and addgroup commands: 15 Practical Examples on adduser Command in Linux

agetty Command

agetty is a program which manages physical or virtual terminals and is invoked by init. Once it detects a connection, it opens a tty port, asks for a user’s login name and calls up the /bin/login command. Agetty is a substitute of Linux getty:

$ agetty -L 9600 ttyS1 vt100

alias Command

alias is a useful shell built-in command for creating aliases (shortcut) to a Linux command on a system. It is helpful for creating new/custom commands from existing Shell/Linux commands (including options):

$ alias home='cd /home/tecmint/public_html'

The above command will create an alias called home for /home/tecmint/public_html directory, so whenever you type home in the terminal prompt, it will put you in the /home/tecmint/public_html directory.

anacron Command

anacron is a Linux facility used to run commands periodically with a frequency defined in days, weeks and months.

Unlike its sister cron; it assumes that a system will not run continuously, therefore if a scheduled job is due when the system is off, it’s run once the machine is powered on.

For more information about anacron and cron read: Cron Vs Anacron: How to Schedule Jobs Using Anacron on Linux

apropos Command

apropos command is used to search and display a short man page description of a command/program as follows.

$ apropos adduser

apt Command

apt tool is a relatively new higher-level package manager for Debian/Ubuntu systems:

$ sudo apt update

For more apt usage read: 15 Useful Examples on APT Command

apt-get Command

apt-get is a powerful and free front-end package manager for Debian/Ubuntu systems. It is used to install new software packages, remove available software packages, upgrade existing software packages as well as upgrade entire operating system.

$ sudo apt-get update

For more apt-get usage, read: 25 Useful Commands of APT-GET for Package Management

aptitude Command

aptitude is a powerful text-based interface to the Debian GNU/Linux package management system. Like apt-get and apt; it can be used to install, remove or upgrade software packages on a system.

$ sudo aptitude update

For more usage on aptitude, read: Learn Debian Package Management with Aptitude Command

arch Command

arch is a simple command for displaying machine architecture or hardware name (similar to uname -m):

$ arch 

arp Command

ARP (Address Resolution Protocol) is a protocol that maps IP network addresses of a network neighbor with the hardware (MAC) addresses in an IPv4 network.

You can use it as below to find all alive hosts on a network:

$ sudo arp-scan --interface=enp2s0 --localnet  

at Command

at command is used to schedule tasks to run in a future time. It’s an alternative to cron and anacron, however, it runs a task once at a given future time without editing any config files:

For example, to shutdown the system at 23:55 today, run:

$ sudo echo "shutdown -h now" | at -m 23:55

atq Command

atq command is used to view jobs in at command queue:

$ atq

atrm Command

atrm command is used to remove/deletes jobs (identified by their job number) from at command queue:

$ atrm 2

For more usage about at command, read: How to Use ‘at’ Command to Schedule a Task in Linux

awk Command

Awk is a powerful programming language created for text processing and generally used as a data extraction and reporting tool.

$ awk '//{print}'/etc/hosts

For more Awk concepts (basic and advance) with simple and easy-to-understand, we’ve created a book that contains 13 chapters with a total of 41 pages, which covers all Awk basic and advance usage with practical examples: Awk Getting Started Guide for Beginners

batch Command

batch is also used to schedule tasks to run a future time, similar to the at command.

basename Command

basename command helps to print the name of a file stripping of directories in the absolute path:

$ basename bin/findhosts.sh

bc Command

bc is a simple yet powerful and arbitrary precision CLI calculator language which can be used like this:

$ echo 20.05 + 15.00 | bc

bg Command

bg is a command used to send a process to the background.

$ tar -czf home.tar.gz .
$ bg 
$ jobs

To learn more about bg command, read: Start Linux Command in Background and Detach Process in Terminal

bzip2 Command

bzip2 command is used to compress or decompress file(s).

$ bzip2 -z filename      #Compress
$ bzip2 -d filename.bz2  #Decompress

To learn more examples on bzip2, read: How to Compress and Decompress a .bz2 File in Linux

cal Command

The cal command print a calendar on the standard output.

$ cal

cat Command

cat command is used to view contents of a file or concatenate files, or data provided on standard input, and display it on the standard output.

$ cat file.txt

To learn more about cat command, read: 13 Useful Cat Command Examples on Linux

chgrp Command

chgrp command is used to change the group ownership of a file. Provide the new group name as its first argument and the name of file as the second argument like this:

$ chgrp tecmint users.txt

chmod Command

chmod command is used to change/update file access permissions like this.

$ chmod +x sysinfo.sh

chown Command

chown command changes/updates the user and group ownership of a file/directory like this.

$ chmod -R www-data:www-data /var/www/html

To learn more about chgrp, chmod and chwon commands, read: Managing Users & Groups, File Permissions & Attributes in Linux

cksum Command

cksum command is used to display the CRC checksum and byte count of an input file.

$ cksum README.txt

clear Command

clear command lets you clear the terminal screen, simply type.

$ clear

cmp Command

cmp performs a byte-by-byte comparison of two files like this.

$ cmp file1 file2

comm Command

comm command is used to compare two sorted files line-by-line as shown below.

$ comm file1 file2

cp Command

cp command is used for copying files and directories from one location to another.

$ cp /home/tecmint/file1 /home/tecmint/Personal/

For more information on how to copy files in Linux, read:

  1. How to Copy a File to Multiple Directories in Linux
  2. Advanced Copy Command – Shows Progress Bar While Copying Large Files/Folders in Linux
  3. Progress – A Tiny Tool to Monitor Progress for (cp, mv, dd, tar, etc.) Commands in Linux

date Command

date command displays/sets the system date and time like this.

$ date
$ date --set="8 JUN 2017 13:00:00"

To learn more about how to set date in Linux, read: How to Set System Date in Linux

dd Command

dd command is used for copying files, converting and formatting according to flags provided on the command line. It can strip headers, extracting parts of binary files and so on.

The example below shows creating a boot-able USB device:

$ dd if=/home/tecmint/kali-linux-1.0.4-i386.iso of=/dev/sdc1 bs=512M; sync

df Command

df command is used to show file system disk space usage as follows.

$ df -h

For more usage on df command, read: 12 Useful ‘df’ Command Examples to Check Disk Space

diff Command

diff command is used to compare two files line by line. It can also be used to find the difference between two directories in Linux like this:

$ diff file1 file2

Some useful diff tools for Linux: 8 Best File Comparison and Difference (Diff) Tools for Linux

dir Command

dir command works like Linux ls command, it lists the contents of a directory.

$ dir

dmidecode Command

dmidecode command is a tool for retrieving hardware information of any Linux system. It dumps a computer’s DMI (a.k.a SMBIOS) table contents in a human-readable format for easy retrieval.

To view your system hardware info, you can type:

$ sudo dmidecode --type system

Some useful tools to find out Linux system hardware info: 10 Useful Commands to Get Linux Hardware Information

du Command

du command is used to show disk space usage of files present in a directory as well as its sub-directories as follows.

$ du /home/aaronkilik

echo Command

echo command prints a text of line provided to it.

$ echo “This is TecMint - Linux How Tos”

eject Command

eject command is used to eject removable media such as DVD/CD ROM or floppy disk from the system.

$ eject /dev/cdrom
$ eject /mnt/cdrom/
$ eject /dev/sda

env Command

env command lists all the current environment variables and used to set them as well.

$ env

Learn more on How to Set and Unset Environment Variables in Linux

exit Command

exit command is used to exit a shell like so.

$ exit

expr Command

expr command is used to calculate an expression as shown below.

$ expr 20 + 30

factor Command

factor command is used to show the prime factors of a number.

$ factor 10

find Command

find command lets you search for files in a directory as well as its sub-directories. It searches for files by attributes such as permissions, users, groups, file type, date, size and other possible criteria.

$ find /home/tecmint/ -name tecmint.txt

Learn more on how to find files in Linux:

  1. How to Use ‘find’ Command to Search for Multiple Filenames (Extensions)
  2. How to Find Number of Files in a Directory and Subdirectories
  3. How to Find Today’s Modified Files in Linux
  4. How to Find and Sort Files Based on Modified Date and Time
  5. How to Find Top Directories and Files (Disk Space) in Linux

free Command

free command shows the system memory usage (free, used, swapped, cached, etc.) in the system including swap space. Use the -h option to display output in human friendly format.

$ free -h 

Learn more on how to find memory usage in Linux.

  1. Find Top Running Processes by Highest Memory and CPU Usage in Linux
  2. Smem – Reports Memory Consumption Per-Process and Per-User Basis in Linux
  3. How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

grep Command

grep command searches for a specified pattern in a file (or files) and displays in output lines containing that pattern as follows.

$ grep ‘tecmint’ domain-list.txt

Learn more about grep command usage in Linux.

  1. What’s Difference Between Grep, Egrep and Fgrep in Linux?
  2. 12 Basic Linux ‘Grep’ Command Examples in Linux
  3. 11 Advanced Linux ‘Grep’ Commands in Linux

groups Command

groups command displays all the names of groups a user is a part of like this.

$ groups
$ groups tecmint

gzip Command

Gzip helps to compress a file, replaces it with one having a .gz extension as shown below:

$ gzip passwds.txt
$ cat file1 file2 | gzip > foo.gz

gunzip Command

gunzip expands or restores files compressed with gzip command like this.

$ gunzip foo.gz

head Command

head command is used to show first lines (10 lines by default) of the specified file or stdin to the screen:

# ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head 

history Command

history command is used to show previously used commands or to get info about command executed by a user.

$ history

Learn more about Linux history command.

  1. The Power of Linux “History Command” in Bash Shell
  2. Set Date and Time for Each Command You Execute in Bash History
  3. How to Use ‘Yum History’ to Find Out Installed/Removed Packages Info

hostname Command

hostname command is used to print or set system hostname in Linux.

$ hostname
$ hostname NEW_HOSTNAME

hostnamectl Command

hostnamectl command controls the system hostname under systemd. It is used to print or modify the system hostname and any related settings:

$ hostnamectl
$ sudo hostnamectl set-hostname NEW_HOSTNAME

hwclock

hwclock is a tool for managing the system hardware clock; read or set the hardware clock (RTC).

$ sudo hwclock
$ sudo hwclock --set --date 8/06/2017

hwinfo Command

hwinfo is used to probe for the hardware present in a Linux system like this.

$ hwinfo

Learn more about how to get Linux hardware info.

  1. I-Nex – An Advanced Tool to Collect System/Hardware Information in Linux
  2. 9 Useful Tools to Get System Information in Linux

id Command

id command shows user and group information for the current user or specified username as shown below.

$ id tecmint

ifconfig Command

ifconfig command is used to configure a Linux systems network interfaces. It is used to configure, view and control network interfaces.

$ ifconfig
$ sudo ifconfig eth0 up
$ sudo ifconfig eth0 down
$ sudo ifconfig eth0 172.16.25.125

ionice Command

ionice command is used to set or view process I/O scheduling class and priority of the specified process.

If invoked without any options, it will query the current I/O scheduling class and priority for that process:

$ ionice -c 3 rm /var/logs/syslog

To understand how it works, read this article: How to Delete HUGE (100-200GB) Files in Linux

iostat Command

iostat is used to show CPU and input/output statistics for devices and partitions. It produces useful reports for updating system configurations to help balance the input/output load between physical disks.

$ iostat 

ip Command

ip command is used to display or manage routing, devices, policy routing and tunnels. It also works as a replacement for well known ifconfig command.

This command will assign an IP address to a specific interface (eth1 in this case).

$ sudo ip addr add 192.168.56.10 dev eth1

iptables Command

iptables is a terminal based firewall for managing incoming and outgoing traffic via a set of configurable table rules.

The command below is used to check existing rules on a system (using it may require root privileges).

$ sudo iptables -L -n -v

Learn more about iptables firewall in Linux.

  1. How to Start/Stop and Enable/Disable FirewallD and Iptables in Linux
  2. Basic Guide on IPTables (Linux Firewall) Tips / Commands
  3. Nishita Agarwal Shares Her Interview Experience on Linux ‘iptables’ Firewall

iw Command

iw command is used to manage wireless devices and their configuration.

$ iw list 

iwlist Command

iwlist command displays detailed wireless information from a wireless interface. The command below enables you to get detailed information about the wlp1s0interface.

$ iwlist wlp1s0 scanning

kill Command

kill command is used to kill a process using its PID by sending a signal to it (default signal for kill is TERM).

$ kill -p 2300
$ kill -SIGTERM -p 2300

killall Command

killall command is used to kill a process by its name.

$ killall firefox

Learn more about kill and killall command in Linux.

  1. How to Find and Kill Running Processes in Linux
  2. A Guide to Kill, Pkill and Killall Commands to Terminate a Process
  3. How to Kill Processes/Unresponsive Applications Using ‘xkill’ Command

kmod Command

kmod command is used to manage Linux kernel modules. To list all currently loaded modules, type.

$ kmod list

last Command

last command display a listing of last logged in users.

$ last 

ln Command

ln command is used to create a soft link between files using the -s flag like this.

$ ln -s /usr/bin/lscpu cpuinfo

locate Command

locate command is used to find a file by name. The locate utility works better and faster than it’s find counterpart.

The command below will search for a file by its exact name (not *name*):

$ locate -b '\domain-list.txt'

login Command

login command is used to create a new session with the system. You’ll be asked to provide a username and a password to login as below.

$ sudo login

ls Command

ls command is used to list contents of a directory. It works more or less like dir command.

The -l option enables long listing format like this.

$ ls -l file1

To know more about ls command, read our guides.

  1. 15 Basic ‘ls’ Command Examples in Linux
  2. 7 Quirky ‘ls’ Command Tricks Every Linux User Should Know
  3. How to Sort Output of ‘ls’ Command By Last Modified Date and Time
  4. 15 Interview Questions on Linux “ls” Command – Part 1
  5. 10 Useful ‘ls’ Command Interview Questions – Part 2

lshw Command

lshw command is a minimal tool to get detailed information on the hardware configuration of the machine, invoke it with superuser privileges to get a comprehensive information.

$ sudo lshw  

lscpu Command

lscpu command displays system’s CPU architecture information (such as number of CPUs, threads, cores, sockets, and more).

$ lscpu

lsof Command

lsof command displays information related to files opened by processes. Files can be of any type, including regular files, directories, block special files, character special files, executing text reference, libraries, and stream/network files.

To view files opened by a specific user’s processes, type the command below.

$ lsof -u tecmint

lsusb Command

lsusb command shows information about USB buses in the system and the devices connected to them like this.

$ lsusb 

man Command

man command is used to view the on-line reference manual pages for commands/programs like so.

$ man du
$ man df

md5sum Command

md5sum command is used to compute and print the MD5 message digest of a file. If run without arguments, debsums checks every file on your system against the stock md5sum files:

$ sudo debsums

mkdir Command

mkdir command is used to create single or more directories, if they do not already exist (this can be overridden with the -p option).

$ mkdir tecmint-files
OR 
$ mkdir -p tecmint-files

more Command

more command enables you to view through relatively lengthy text files one screenful at a time.

$ more file.txt

Check difference between more and less command and Learn Why ‘less’ is Faster Than ‘more’ Command

mv Command

mv command is used to rename files or directories. It also moves a file or directory to another location in the directory structure.

$ mv test.sh sysinfo.sh 

nano Command

nano is a popular small, free and friendly text editor for Linux; a clone of Pico, the default editor included in the non-free Pine package.

To open a file using nano, type:

$ nano file.txt

nc/netcat Command

nc (or netcat) is used for performing any operation relating to TCP, UDP, or UNIX-domain sockets. It can handle both IPv4 and IPv6 for opening TCP connections, sending UDP packets, listening on arbitrary TCP and UDP ports, performing port scanning.

The command below will help us see if the port 22 is open on the host 192.168.56.5.

$ nc -zv 192.168.1.5 22

Learn more examples and usage on nc command.

  1. How to Check Remote Ports are Reachable Using ‘nc’ Command
  2. How to Transfer Files Between Computers Using ‘nc’ Command

netstat Command

netstat command displays useful information concerning the Linux networking subsystem (network connections, routing tables, interface statistics, masquerade connections, and multicast memberships).

This command will display all open ports on the local system:

$ netstat -a | more

nice Command

nice command is used to show or change the nice value of a running program. It runs specified command with an adjusted niceness. When run without any command specified, it prints the current niceness.

The following command starts the process “tar command” setting the “nice” value to 12.

$ nice -12 tar -czf backup.tar.bz2 /home/*

nmap Command

nmap is a popular and powerful open source tool for network scanning and security auditing. It was intended to quickly scan large networks, but it also works fine against single hosts.

The command below will probe open ports on all live hosts on the specified network.

$ nmap -sV 192.168.56.0/24

nproc Command

nproc command shows the number of processing units present to the current process. It’s output may be less than the number of online processors on a system.

$ nproc  

openssl Command

The openssl is a command line tool for using the different cryptography operations of OpenSSL’s crypto library from the shell. The command below will create an archive of all files in the current directory and encrypt the contents of the archive file:

$ tar -czf - * | openssl enc -e -aes256 -out backup.tar.gz

passwd Command

passwd command is used to create/update passwords for user accounts, it can also change the account or associated password validity period. Note that normal system users may only change the password of their own account, while root may modify the password for any account.

$ passwd tecmint

pidof Command

pidof displays the process ID of a running program/command.

$ pidof init
$ pidof cinnamon

ping Command

ping command is used to determine connectivity between hosts on a network (or the Internet):

$ ping google.com

ps Command

ps shows useful information about active processes running on a system. The example below shows the top running processes by highest memory and CPU usage.

# ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head

pstree Command

pstree displays running processes as a tree which is rooted at either PID or init if PID is omitted.

$ pstree

pwd Command

pwd command displays the name of current/working directory as below.

$ pwd

rdiff-backup Command

rdiff-backup is a powerful local/remote incremental backup script written in Python. It works on any POSIX operating system such as Linux, Mac OS X.

Note that for remote backups, you must install the same version of rdiff-backup on both the local and remote machines. Below is an example of a local backup command:

$ sudo rdiff-backup /etc /media/tecmint/Backup/server_etc.backup

reboot Command

reboot command may be used to halt, power-off or reboot a system as follows.

$ reboot

rename Command

rename command is used to rename many files at once. If you’ve a collection of files with “.html” extension and you want to rename all of them with “.php” extension, you can type the command below.

$ rename 's/\.html$/\.php/' *.html

rm command

rm command is used to remove files or directories as shown below.

$ rm file1
$ rm -rf my-files

rmdir Command

rmdir command helps to delete/remove empty directories as follows.

$ rmdir /backup/all

scp Command

scp command enables you to securely copy files between hosts on a network, for example.

$ scp ~/names.txt root@192.168.56.10:/root/names.txt

shutdown Command

shutdown command schedules a time for the system to be powered down. It may be used to halt, power-off or reboot the machine like this.

$ shutdown --poweroff

Learn how to show a Custom Message to Users Before Linux Server Shutdown.

sleep Command

sleep command is used to delay or pause (specifically execution of a command) for a specified amount of time.

$ check.sh; sleep 5; sudo apt update

sort Command

sort command is used to sort lines of text in the specified file(s) or from stdin as shown below

$ cat words.txt

Learn more examples of sort command in Linux.

  1. 7 Interesting Linux ‘sort’ Command Examples
  2. How to Sort Output of ‘ls’ Command By Last Modified Date and Time
  3. How to Find and Sort Files Based on Modification Date and Time

split Command

split as the name suggests, is used to split a large file into small parts.

$ tar -cvjf backup.tar.bz2 /home/tecmint/Documents/* 

ssh Command

ssh (SSH client) is an application for remotely accessing and running commands on a remote machine. It is designed to offer a secure encrypted communications between two untrusted hosts over an insecure network such as the Internet.

$ ssh tecmint@192.168.56.10

Learn more about ssh command and how to use it on Linux.

  1. 5 Best Practices to Secure and Protect SSH Server
  2. Configure “No Password SSH Keys Authentication” with PuTTY on Linux
  3. SSH Passwordless Login Using SSH Keygen in 5 Easy Steps
  4. Restrict SSH User Access to Certain Directory Using Chrooted Jail

stat Command

stat is used to show a file or file system status like this (-f is used to specify a filesystem).

$ stat file1

su Command

su command is used to switch to another user ID or become root during a login session. Note that when su is invoked without a username, it defaults to becoming root.

$ su 
$ su tecmint

sudo Command

sudo command allows a permitted system user to run a command as root or another user, as defined by the security policy such as sudoers.

In this case, the real (not effective) user ID of the user running sudo is used to determine the user name with which to query the security policy.

$ sudo apt update
$ sudo useradd tecmint
$ sudo passwd tecmint

Learn more about sudo command and how to use it on Linux.

  1. 10 Useful Sudoers Configurations for Setting ‘sudo’ in Linux
  2. How to Run ‘sudo’ Command Without Entering a Password in Linux
  3. How to Keep ‘sudo’ Password Timeout Session Longer in Linux

sum Command

sum command is used to show the checksum and block counts for each each specified file on the command line.

$ sum output file.txt 

tac Command

tac command concatenates and displays files in reverse. It simply prints each file to standard output, showing last line first.

$tac file.txt

tail Command

tail command is used to display the last lines (10 lines by default) of each file to standard output.

If there more than one file, precede each with a header giving the file name. Use it as follow (specify more lines to display using -n option).

$ tail long-file
OR
$ tail -n 15 long-file

talk Command

talk command is used to talk to another system/network user. To talk to a user on the same machine, use their login name, however, to talk to a user on another machine use ‘user@host’.

$ talk person [ttyname]
OR
$ talk‘user@host’ [ttyname]

tar Command

tar command is a most powerful utility for archiving files in Linux.

$ tar -czf home.tar.gz .

Learn more about tar command and its usage on Linux.

  1. 18 Tar Command Examples in Linux
  2. How to Split Large ‘tar’ Archive into Multiple Files of Certain Size
  3. How to Extract Tar Files to Specific or Different Directory in Linux

tee Command

tee command is used to read from standard input and prints to standard output and files as shown below.

$ echo "Testing how tee command works" | tee file1 

time Command

time command runs programs and summarizes system resource usage.

$ time wc /etc/hosts

top Command

top program displays all processes on a Linux system in regards to memory and CPU usage and provides a dynamic real-time view of a running system.

$ top

touch Command

touch command changes file timestamps, it can also be used to create a file as follows.

$ touch file.txt

tr Command

tr command is a useful utility used to translate (change) or delete characters from stdin, and write the result to stdout or send to a file as follows.

$ cat domain-list.txt | tr [:lower:] [:upper:]

uname Command

uname command displays system information such as operating system, network node hostname kernel name, version and release etc.

Use the -a option to show all the system information:

$ uname 

uniq Command

uniq command displays or omits repeated lines from input (or standard input). To indicate the number of occurrences of a line, use the -c option.

$ cat domain-list.txt

uptime Command

uptime command shows how long the system has been running, number of logged on users and the system load averages as follows.

$ uptime

users Command

users command shows the user names of users currently logged in to the current host like this.

$ users

vim/vi Command

vim (Vi Improved) popular text editor on Unix-like operating systems. It can be used to edit all kinds of plain text and program files.

$ vim file

Learn how to use vi/vim editor in Linux along with some tips and tricks.

  1. 10 Reasons Why You Should Use Vi/Vim Editor in Linux
  2. How to Install and Use Vi/Vim Editor in Linux
  3. How to Save a File in Vim Editor in Linux
  4. How to Exit a File in Vim Editor in Linux
  5. Learn Useful ‘Vi/Vim’ Editor Tips and Tricks to Enhance Your Skills
  6. 8 Interesting ‘Vi/Vim’ Editor Tips and Tricks for Every Linux Administrator

w Command

w command displays system uptime, load averages and information about the users currently on the machine, and what they are doing (their processes) like this.

$ w

wall Command

wall command is used to send/display a message to all users on the system as follows.

$ wall “This is TecMint – Linux How Tos”

watch Command

watch command runs a program repeatedly while displaying its output on fullscreen. It can also be used to watch changes to a file/directory. The example below shows how to watch the contents of a directory change.

$ watch -d ls -l

wc Command

wc command is used to display newline, word, and byte counts for each file specified, and a total for many files.

$ wc filename

wget Command

wget command is a simple utility used to download files from the Web in a non-interactive (can work in the background) way.

$ wget -c http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz

whatis Command

whatis command searches and shows a short or one-line manual page descriptions of the provided command name(s) as follows.

$ whatis wget

which Command

which command displays the absolute path (pathnames) of the files (or possibly links) which would be executed in the current environment.

$ which who

who Command

who command shows information about users who are currently logged in like this.

$ who

whereis Command

whereis command helps us locate the binary, source and manual files for commands.

$ whereis cat

xargs Command

xargs command is a useful utility for reading items from the standard input, delimited by blanks (protected with double or single quotes or a backslash) or newlines, and executes the entered command.

The example below show xargs being used to copy a file to multiple directories in Linux.

$ echo /home/aaronkilik/test/ /home/aaronkilik/tmp | xargs -n 1 cp -v /home/aaronkilik/bin/sys_info.sh

yes Command

yes command is used to display a string repeatedly until when terminated or killed using [Ctrl + C] as follows.

$ yes "This is TecMint - Linux HowTos"

youtube-dl Command

youtube-dl is a lightweight command-line program to download videos and also extract MP3 tracks from YouTube.com and a few more sites.

The command below will list available formats for the video in the provided link.

$ youtube-dl --list-formats https://www.youtube.com/watch?v=iR

zcmp/zdiff Command

zcmp and zdiff minimal utilities used to compare compressed files as shown in the examples below.

$ zcmp domain-list.txt.zip basic_passwords.txt.zip
$ zdiff domain-list.txt.zip basic_passwords.txt.zip 

zip Command

zip is a simple and easy-to-use utility used to package and compress (archive) files.

$ tar cf - . | zip | dd of=/dev/nrst0 obs=16k
$ zip inarchive.zip foo.c bar.c --out outarchive.zip
$ tar cf - .| zip backup -

zz Command

zz command is an alias of the fasd commandline tool that offers quick access to files and directories in Linux. It is used to quickly and interactively cd into a previously accessed directory by selecting the directory number from the first field as follows.

$ zz

That’s it for now! As we mentioned before, there are a countless number of commands in Linux. The list is possibly longer than we can offer.

Source

14 Useful Examples of Linux ‘sort’ Command

Sort is a Linux program used for printing lines of input text files and concatenation of all files in sorted order. Sort command takes blank space as field separator and entire Input file as sort key. It is important to notice that sort command don’t actually sort the files but only print the sorted output, until your redirect the output.

This article aims at deep insight of Linux ‘sort‘ command with 14 useful practical examples that will show you how to use sort command in Linux.

1. First we will be creating a text file (tecmint.txt) to execute ‘sort‘ command examples. Our working directory is ‘/home/$USER/Desktop/tecmint.

The option ‘-e‘ in the below command enables interpretion of backslash and /n tells echo to write each string to a new line.

$ echo -e "computer\nmouse\nLAPTOP\ndata\nRedHat\nlaptop\ndebian\nlaptop" > tecmint.txt

Split String by Lines in Linux

2. Before we start with ‘sort‘ lets have a look at the contents of the file and the way it look.

$ cat tecmint.txt

Check Content of File

3. Now sort the content of the file using following command.

$ sort tecmint.txt

Sort Content of File linux

Note: The above command don’t actually sort the contents of text file but only show the sorted output on terminal.

4. Sort the contents of the file ‘tecmint.txt‘ and write it to a file called (sorted.txt) and verify the content by using cat command.

$ sort tecmint.txt > sorted.txt
$ cat sorted.txt

Sort File Content in Linux

5. Now sort the contents of text file ‘tecmint.txt‘ in reverse order by using ‘-r‘ switch and redirect output to a file ‘reversesorted.txt‘. Also check the content listing of the newly created file.

$ sort -r tecmint.txt > reversesorted.txt
$ cat reversesorted.txt

Sort Content By Reverse

6. We are going a create a new file (lsl.txt) at the same location for detailed examples and populate it using the output of ‘ls -l‘ for your home directory.

$ ls -l /home/$USER > /home/$USER/Desktop/tecmint/lsl.txt
$ cat lsl.txt

Populate Output of Home Directory

Now will see examples to sort the contents on the basis of other field and not the default initial characters.

7. Sort the contents of file ‘lsl.txt‘ on the basis of 2nd column (which represents number of symbolic links).

$ sort -nk2 lsl.txt

Note: The ‘-n‘ option in the above example sort the contents numerically. Option ‘-n‘ must be used when we wanted to sort a file on the basis of a column which contains numerical values.

Sort Content by Column

8. Sort the contents of file ‘lsl.txt‘ on the basis of 9th column (which is the name of the files and folders and is non-numeric).

$ sort -k9 lsl.txt

Sort Content Based on Column

9. It is not always essential to run sort command on a file. We can pipeline it directly on the terminal with actual command.

$ ls -l /home/$USER | sort -nk5

Sort Content Using Pipe Option

10. Sort and remove duplicates from the text file tecmint.txt. Check if the duplicate has been removed or not.

$ cat tecmint.txt
$ sort -u tecmint.txt

Sort and Remove Duplicates

Rules so far (what we have observed):

  1. Lines starting with numbers are preferred in the list and lies at the top until otherwise specified (-r).
  2. Lines starting with lowercase letters are preferred in the list and lies at the top until otherwise specified (-r).
  3. Contents are listed on the basis of occurrence of alphabets in dictionary until otherwise specified (-r).
  4. Sort command by default treat each line as string and then sort it depending upon dictionary occurrence of alphabets (Numeric preferred; see rule – 1) until otherwise specified.

11. Create a third file ‘lsla.txt‘ at the current location and populate it with the output of ‘ls -lA‘ command.

$ ls -lA /home/$USER > /home/$USER/Desktop/tecmint/lsla.txt
$ cat lsla.txt

Populate Output With Hidden Files

Those having understanding of ‘ls‘ command knows that ‘ls -lA’=’ls -l‘ + Hidden files. So most of the contents on these two files would be same.

12. Sort the contents of two files on standard output in one go.

$ sort lsl.txt lsla.txt

Sort Contents of Two Files

Notice the repetition of files and folders.

13. Now we can see how to sort, merge and remove duplicates from these two files.

$ sort -u lsl.txt lsla.txt

 Sort, Merge and Remove Duplicates from File

Notice that duplicates has been omitted from the output. Also, you can write the output to a new file by redirecting the output to a file.

14.
 We may also sort the contents of a file or the output based upon more than one column. Sort the output of ‘ls -l‘ command on the basis of field 2,5 (Numeric) and 9 (Non-Numeric).

$ ls -l /home/$USER | sort -t "," -nk2,5 -k9

Sort Content By Field Column

That’s all for now. In the next article we will cover a few more examples of ‘sort‘ command in detail for you. Till then stay tuned and connected to Tecmint. Keep sharing. Keep commenting. Like and share us and help us get spread.

Source

CPUTool – Limit and Control CPU Utilization of Any Process in Linux

One of the critical areas under Linux performance monitoring has to be CPU usage and system load. There are several Linux performance monitoring tools to keep an eye on how things are unfolding on a system.

A number of these tools simply output the system state/statistics while a few others provide you means of managing system performance. One such tool called CPUTool.

CPUTool is a simple yet powerful command-line tool for limiting and controlling CPU utilization of any process to a given limit and allows the interruption of process execution if the system load overreach a defined threshold.

How Does CPUTool Work?

In order to limit CPU usage, cputool sends the SIGSTOP and SIGCONT signals to processes and this is determined by the system load. It relies on the /proc pseudo-filesystem to read PIDs and their CPU usage measures.

It may be used to limit the CPU usage or system load influenced by a single process or a group of processes to a given limit and/or suspend processes if the system load goes beyond a threshold.

Suggested Read: Understand Linux Load Averages and Monitor Performance of Linux

Install CPUTool to Limit CPU Usage and Load Average

CPUTool is only available to install on Debian/Ubuntu and its derivatives from the default system repositories using package management tool.

$ sudo apt install cputool

Limiting Process CPU Usage With CUPTool

Now lets look at how cputool really works. To demonstrate it all, we will run a dd command which should result into a high CPU percentage, in the background and display its PID.

# dd if=/dev/zero of=/dev/null &

To monitor CPU usage we can use the top or glances tools that allow us to view a real-time regularly updated state of a running Linux system processes:

# top
Monitor dd Command CPU Usage

Monitor dd Command CPU Usage

From the output above, we can see that dd command is having the highest percentage of CPU time 99.7%)Now we can limit this using cputool as shown below.

The --cpu-limit or -c flag is used to set a usage percentage for a process or group of processes and -p to specify a PID. The following command will limit the dd command (PID 8275) to 50% use of one CPU core:

# cputool --cpu-limit 50 -p 8275 

After running cputool, we can check the new CPU usage for the process (PID 8275) once more. Now the CPU usage for dd process should range from (49.0%-52.0%).

# top
Limit Process CPU to 50% Usage

Limit Process CPU to 50% Usage

To further limit dd’s CPU usage to 20%, we can run cputool for a second time:

# cputool --cpu-limit 20 -p 8275 

Then immediately check using tools such as top or glances like this (the CPU usage for dd should now range from 19.0%-22.0% or slightly beyond this):

# top
Limit Process CPU Usage to 20%

Limit Process CPU Usage to 20%

Note that the shell doesn’t expect any user input while cputool is running; therefore becomes unresponsive. To kill it (this will terminate the CPU usage limitation operation), press Ctrl + C.

Importantly, to specify a process group (one program with several running instances each with a distinct PID) for instance HTTP web server:

# pidof apache2
9592 3643 3642 3641 3640 3638 3637 1780

Use the -P flag like this:

# cputool --cpu-limit 20 -P 1780

Limiting System Load with CUPTool

The -l option is used to specify the maximum load the system may go though for the process or process group to continue running. We may use a fractional value (e.g. 2.5).

The example below means run rsync for a local backup only when the system load does not exceed 3.5:

# cputool --load-limit 3.5 --rsync -av /home/tecmint /backup/`date +%Y-%m-%d`/

For more information and usage, view the CPUTool man page:

# man cputool

Do check out following useful guides for finding CPU info and CPU performance monitoring:

  1. 9 Useful Commands to Get CPU Information on Linux
  2. Cpustat – Monitors CPU Utilization by Running Processes in Linux
  3. CoreFreq – A Powerful CPU Monitoring Tool for Linux Systems
  4. Find Top Running Processes by Highest Memory and CPU Usage in Linux

In conclusion, CPUTool really comes in handy for Linux performance management.

 
Source

20 Advanced Commands for Linux Experts

Thanks for all the likes, good words and support you gave us in the first two part of this article. In the first article we discussed commands for those users who have just switched to Linux and needed the necessary knowledge to start with.

  1. 20 Useful Commands for Linux Newbies

In the second article we discussed the commands which a middle level user requires to manage his own system.

  1. 20 Advanced Commands for Middle Level Linux Users

What Next? In this article I will be explaining those commands required for administrating the Linux Server.

Linux System Admin Commands

Linux Expert Commands

41. Command: ifconfig

ifconfig is used to configure the kernel-resident network interfaces. It is used at boot time to set up interfaces as necessary. After that, it is usually only needed when debugging or when system tuning is needed.

Check Active Network Interfaces
[avishek@tecmint ~]$ ifconfig 

eth0      Link encap:Ethernet  HWaddr 40:2C:F4:EA:CF:0E  
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0 
          inet6 addr: fe80::422c:f4ff:feea:cf0e/64 Scope:Link 
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1 
          RX packets:163843 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:124990 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:1000 
          RX bytes:154389832 (147.2 MiB)  TX bytes:65085817 (62.0 MiB) 
          Interrupt:20 Memory:f7100000-f7120000 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0 
          inet6 addr: ::1/128 Scope:Host 
          UP LOOPBACK RUNNING  MTU:16436  Metric:1 
          RX packets:78 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:78 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:0 
          RX bytes:4186 (4.0 KiB)  TX bytes:4186 (4.0 KiB)
Check All Network Interfaces

Display details of All interfaces including disabled interfaces using “-a” argument.

[avishek@tecmint ~]$ ifconfig -a

eth0      Link encap:Ethernet  HWaddr 40:2C:F4:EA:CF:0E  
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0 
          inet6 addr: fe80::422c:f4ff:feea:cf0e/64 Scope:Link 
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1 
          RX packets:163843 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:124990 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:1000 
          RX bytes:154389832 (147.2 MiB)  TX bytes:65085817 (62.0 MiB) 
          Interrupt:20 Memory:f7100000-f7120000 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0 
          inet6 addr: ::1/128 Scope:Host 
          UP LOOPBACK RUNNING  MTU:16436  Metric:1 
          RX packets:78 errors:0 dropped:0 overruns:0 frame:0 
          TX packets:78 errors:0 dropped:0 overruns:0 carrier:0 
          collisions:0 txqueuelen:0 
          RX bytes:4186 (4.0 KiB)  TX bytes:4186 (4.0 KiB) 

virbr0    Link encap:Ethernet  HWaddr 0e:30:a3:3a:bf:03  
          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
Disable an Interface
[avishek@tecmint ~]$ ifconfig eth0 down
Enable an Interface
[avishek@tecmint ~]$ ifconfig eth0 up
Assign IP Address to an Interface

Assign “192.168.1.12” as the IP address for the interface eth0.

[avishek@tecmint ~]$ ifconfig eth0 192.168.1.12
Change Subnet Mask of Interface eth0
[avishek@tecmint ~]$ ifconfig eth0 netmask 255.255.255.
Change Broadcast Address of Interface eth0
[avishek@tecmint ~]$ ifconfig eth0 broadcast 192.168.1.255
Assign IP Address, Netmask and Broadcast to Interface eth0
[avishek@tecmint ~]$ ifconfig eth0 192.168.1.12 netmask 255.255.255.0 broadcast 192.168.1.255

Note: If using a wireless network you need to use command “iwconfig“. For more “ifconfig” command examples and usage, read 15 Useful “ifconfig” Commands.

42. Command: netstat

netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc..,

List All Network Ports
[avishek@tecmint ~]$ netstat -a

Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     741379   /run/user/user1/keyring-I5cn1c/gpg
unix  2      [ ACC ]     STREAM     LISTENING     8965     /var/run/acpid.socket
unix  2      [ ACC ]     STREAM     LISTENING     18584    /tmp/.X11-unix/X0
unix  2      [ ACC ]     STREAM     LISTENING     741385   /run/user/user1/keyring-I5cn1c/ssh
unix  2      [ ACC ]     STREAM     LISTENING     741387   /run/user/user1/keyring-I5cn1c/pkcs11
unix  2      [ ACC ]     STREAM     LISTENING     20242    @/tmp/dbus-ghtTjuPN46
unix  2      [ ACC ]     STREAM     LISTENING     13332    /var/run/samba/winbindd_privileged/pipe
unix  2      [ ACC ]     STREAM     LISTENING     13331    /tmp/.winbindd/pipe
unix  2      [ ACC ]     STREAM     LISTENING     11030    /var/run/mysqld/mysqld.sock
unix  2      [ ACC ]     STREAM     LISTENING     19308    /tmp/ssh-qnZadSgJAbqd/agent.3221
unix  2      [ ACC ]     STREAM     LISTENING     436781   /tmp/HotShots
unix  2      [ ACC ]     STREAM     LISTENING     46110    /run/user/ravisaive/pulse/native
unix  2      [ ACC ]     STREAM     LISTENING     19310    /tmp/gpg-zfE9YT/S.gpg-agent
....
List All TCP Ports
[avishek@tecmint ~]$ netstat -at

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 localhost:mysql         *:*                     LISTEN     
tcp        0      0 *:5901                  *:*                     LISTEN     
tcp        0      0 *:5902                  *:*                     LISTEN     
tcp        0      0 *:x11-1                 *:*                     LISTEN     
tcp        0      0 *:x11-2                 *:*                     LISTEN     
tcp        0      0 *:5938                  *:*                     LISTEN     
tcp        0      0 localhost:5940          *:*                     LISTEN     
tcp        0      0 ravisaive-OptiPl:domain *:*                     LISTEN     
tcp        0      0 ravisaive-OptiPl:domain *:*                     LISTEN     
tcp        0      0 localhost:ipp           *:*                     LISTEN     
tcp        0      0 ravisaive-OptiPle:48270 ec2-23-21-236-70.c:http ESTABLISHED
tcp        0      0 ravisaive-OptiPle:48272 ec2-23-21-236-70.c:http TIME_WAIT  
tcp        0      0 ravisaive-OptiPle:48421 bom03s01-in-f22.1:https ESTABLISHED
tcp        0      0 ravisaive-OptiPle:48269 ec2-23-21-236-70.c:http ESTABLISHED
tcp        0      0 ravisaive-OptiPle:39084 channel-ecmp-06-f:https ESTABLISHED
...
Show Statistics for All Ports
[avishek@tecmint ~]$ netstat -s

Ip:
    4994239 total packets received
    0 forwarded
    0 incoming packets discarded
    4165741 incoming packets delivered
    3248924 requests sent out
    8 outgoing packets dropped
Icmp:
    29460 ICMP messages received
    566 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 98
        redirects: 29362
    2918 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 2918
IcmpMsg:
        InType3: 98
        InType5: 29362
        OutType3: 2918
Tcp:
    94533 active connections openings
    23 passive connection openings
    5870 failed connection attempts
    7194 connection resets received
....

OK! For some reason if you want not to resolve host, port and user name as a output of netstat.

[avishek@tecmint ~]$ netstat -an

Fine, you may need to get the output of netstat continuously till interrupt instruction is passed (ctrl+c).

[avishek@tecmint ~]$ netstat -c

For more “netstat” command examples and usage, see the article 20 Netstat Command Examples.

43. Command: nslookup

A network utility program used to obtain information about Internet servers. As its name suggests, the utility finds name server information for domains by querying DNS.

[avishek@tecmint ~]$ nslookup tecmint.com 

Server:		192.168.1.1 
Address:	192.168.1.1#53 

Non-authoritative answer: 
Name:	tecmint.com 
Address: 50.16.67.239
Query Mail Exchanger Record
[avishek@tecmint ~]$ nslookup -query=mx tecmint.com 

Server:		192.168.1.1 
Address:	192.168.1.1#53 

Non-authoritative answer: 
tecmint.com	mail exchanger = 0 smtp.secureserver.net. 
tecmint.com	mail exchanger = 10 mailstore1.secureserver.net. 

Authoritative answers can be found from:
Query Name Server
[avishek@tecmint ~]$ nslookup -type=ns tecmint.com 

Server:		192.168.1.1 
Address:	192.168.1.1#53 

Non-authoritative answer: 
tecmint.com	nameserver = ns3404.com. 
tecmint.com	nameserver = ns3403.com. 

Authoritative answers can be found from:
Query DNS Record
[avishek@tecmint ~]$ nslookup -type=any tecmint.com 

Server:		192.168.1.1 
Address:	192.168.1.1#53 

Non-authoritative answer: 
tecmint.com	mail exchanger = 10 mailstore1.secureserver.net. 
tecmint.com	mail exchanger = 0 smtp.secureserver.net. 
tecmint.com	nameserver = ns06.domaincontrol.com. 
tecmint.com	nameserver = ns3404.com. 
tecmint.com	nameserver = ns3403.com. 
tecmint.com	nameserver = ns05.domaincontrol.com. 

Authoritative answers can be found from:
Query Start of Authority
[avishek@tecmint ~]$ nslookup -type=soa tecmint.com 

Server:		192.168.1.1 
Address:	192.168.1.1#53 

Non-authoritative answer: 
tecmint.com 
	origin = ns3403.hostgator.com 
	mail addr = dnsadmin.gator1702.hostgator.com 
	serial = 2012081102 
	refresh = 86400 
	retry = 7200 
	expire = 3600000 
	minimum = 86400 

Authoritative answers can be found from:
Query Port Number

Change the port number using which you want to connect

[avishek@tecmint ~]$ nslookup -port 56 tecmint.com

Server:		tecmint.com
Address:	50.16.76.239#53

Name:	56
Address: 14.13.253.12

Read Also : 8 Nslookup Commands

44. Command: dig

dig is a tool for querying DNS nameservers for information about host addresses, mail exchanges, nameservers, and related information. This tool can be used from any Linux (Unix) or Macintosh OS X operating system. The most typical use of dig is to simply query a single host.

[avishek@tecmint ~]$ dig tecmint.com

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> tecmint.com 
;; global options: +cmd 
;; Got answer: 
;; ->>HEADER<
Turn Off Comment Lines
[avishek@tecmint ~]$ dig tecmint.com +nocomments 

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> tecmint.com +nocomments 
;; global options: +cmd 
;tecmint.com.			IN	A 
tecmint.com.		14400	IN	A	40.216.66.239 
;; Query time: 418 msec 
;; SERVER: 192.168.1.1#53(192.168.1.1) 
;; WHEN: Sat Jun 29 13:53:22 2013 
;; MSG SIZE  rcvd: 45
Turn Off Authority Section
[avishek@tecmint ~]$ dig tecmint.com +noauthority 

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> tecmint.com +noauthority 
;; global options: +cmd 
;; Got answer: 
;; ->>HEADER<
Turn Off Additional Section
[avishek@tecmint ~]$ dig  tecmint.com +noadditional 

; <<>> DiG 9.9.2-P1 <<>> tecmint.com +noadditional
;; global options: +cmd
;; Got answer:
;; ->>HEADER<
Turn Off Stats Section
[avishek@tecmint ~]$ dig tecmint.com +nostats 

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> tecmint.com +nostats 
;; global options: +cmd 
;; Got answer: 
;; ->>HEADER<
Turn Off Answer Section
[avishek@tecmint ~]$ dig tecmint.com +noanswer 

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> tecmint.com +noanswer 
;; global options: +cmd 
;; Got answer: 
;; ->>HEADER<
Disable All Section at Once
[avishek@tecmint ~]$ dig tecmint.com +noall 

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> tecmint.com +noall 
;; global options: +cmd

Read Also : 10 Linux Dig Command Examples

45. Command: uptime

You have just connected to your Linux Server Machine and founds Something unusual or malicious, what you will do? Guessing…. NO, definitely not you could run uptime to verify what happened actually when the server was unattended.

[avishek@tecmint ~]$ uptime

14:37:10 up  4:21,  2 users,  load average: 0.00, 0.00, 0.04

46. Command: wall

one of the most important command for administrator, wall sends a message to everybody logged in with their mesg permission set to “yes“. The message can be given as an argument to wall, or it can be sent to wall’s standard input.

[avishek@tecmint ~]$ wall "we will be going down for maintenance for one hour sharply at 03:30 pm"

Broadcast message from root@localhost.localdomain (pts/0) (Sat Jun 29 14:44:02 2013): 

we will be going down for maintenance for one hour sharply at 03:30 pm

47. command: mesg

Lets you control if people can use the “write” command, to send text to you over the screen.

mesg [n|y]
n - prevents the message from others popping up on the screen.
y – Allows messages to appear on your screen.

48. Command: write

Let you send text directly to the screen of another Linux machine if ‘mesg’ is ‘y’.

[avishek@tecmint ~]$ write ravisaive

49. Command: talk

An enhancement to write command, talk command lets you talk to the logged in users.

[avishek@tecmint ~]$ talk ravisaive

Note: If talk command is not installed, you can always apt or yum the required packages.

[avishek@tecmint ~]$ yum install talk
OR
[avishek@tecmint ~]$ apt-get install talk

50. Command: w

what command ‘w’ seems you funny? But actually it is not. t’s a command, even if it’s just one letter long! The command “w” is a combination of uptime and who commands given one immediately after the other, in that order.

[avishek@tecmint ~]$ w

15:05:42 up  4:49,  3 users,  load average: 0.02, 0.01, 0.00 
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT 
server   tty7     :0               14:06    4:43m  1:42   0.08s pam: gdm-passwo 
server   pts/0    :0.0             14:18    0.00s  0.23s  1.65s gnome-terminal 
server   pts/1    :0.0             14:47    4:43   0.01s  0.01s bash

51. Command: rename

As the name suggests, this command rename files. rename will rename the specified files by replacing the first occurrence from the file name.

Give the file names a1, a2, a3, a4.....1213

Just type the command.

 rename a1 a0 a?
 rename a1 a0 a??

52. Command: top

Displays the processes of CPU. This command refresh automatically, by default and continues to show CPUprocesses unless interrupt-instruction is given.

[avishek@tecmint ~]$ top

top - 14:06:45 up 10 days, 20:57,  2 users,  load average: 0.10, 0.16, 0.21
Tasks: 240 total,   1 running, 235 sleeping,   0 stopped,   4 zombie
%Cpu(s):  2.0 us,  0.5 sy,  0.0 ni, 97.5 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem:   2028240 total,  1777848 used,   250392 free,    81804 buffers
KiB Swap:  3905532 total,   156748 used,  3748784 free,   381456 cached

  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+ COMMAND                                                                                                            
23768 ravisaiv  20   0 1428m 571m  41m S   2.3 28.9  14:27.52 firefox                                                                                                            
24182 ravisaiv  20   0  511m 132m  25m S   1.7  6.7   2:45.94 plugin-containe                                                                                                    
26929 ravisaiv  20   0  5344 1432  972 R   0.7  0.1   0:00.07 top                                                                                                                
24875 ravisaiv  20   0  263m  14m  10m S   0.3  0.7   0:02.76 lxterminal                                                                                                         
    1 root      20   0  3896 1928 1228 S   0.0  0.1   0:01.62 init                                                                                                               
    2 root      20   0     0    0    0 S   0.0  0.0   0:00.06 kthreadd                                                                                                           
    3 root      20   0     0    0    0 S   0.0  0.0   0:17.28 ksoftirqd/0                                                                                                        
    5 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 kworker/0:0H                                                                                                       
    7 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 kworker/u:0H                                                                                                       
    8 root      rt   0     0    0    0 S   0.0  0.0   0:00.12 migration/0                                                                                                        
    9 root      20   0     0    0    0 S   0.0  0.0   0:00.00 rcu_bh                                                                                                             
   10 root      20   0     0    0    0 S   0.0  0.0   0:26.94 rcu_sched                                                                                                          
   11 root      rt   0     0    0    0 S   0.0  0.0   0:01.95 watchdog/0                                                                                                         
   12 root      rt   0     0    0    0 S   0.0  0.0   0:02.00 watchdog/1                                                                                                         
   13 root      20   0     0    0    0 S   0.0  0.0   0:17.80 ksoftirqd/1                                                                                                        
   14 root      rt   0     0    0    0 S   0.0  0.0   0:00.12 migration/1                                                                                                        
   16 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 kworker/1:0H                                                                                                       
   17 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 cpuset                                                                                                             
   18 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 khelper                                                                                                            
   19 root      20   0     0    0    0 S   0.0  0.0   0:00.00 kdevtmpfs                                                                                                          
   20 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 netns                                                                                                              
   21 root      20   0     0    0    0 S   0.0  0.0   0:00.04 bdi-default                                                                                                        
   22 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 kintegrityd                                                                                                        
   23 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 kblockd                                                                                                            
   24 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 ata_sff

Read Also : 12 TOP Command Examples

53. Command: mkfs.ext4

This command create a new ext4 file system on the specified device, if wrong device is followed after this command, the whole block will be wiped and formatted, hence it is suggested not to run this command unless and until you understand what you are doing.

Mkfs.ext4 /dev/sda1 (sda1 block will be formatted)
mkfs.ext4 /dev/sdb1 (sdb1 block will be formatted)

Read MoreWhat is Ext4 and How to Create and Convert

54. Command: vi/emacs/nano

vi (visual), emacsnano are some of the most commonly used editors in Linux. They are used oftenly to edit text, configuration,… files. A quick guide to work around vi and nano is, emacs is a.

vi-editor
[avishek@tecmint ~]$ touch a.txt (creates a text file a.txt) 
[avishek@tecmint ~]$ vi a.txt (open a.txt with vi editor)

[press ‘i’ to enter insert mode, or you won’t be able to type-in anything]

echo "Hello"  (your text here for the file)
  1. alt+x (exit insert mode, remember to keep some space between the last letter.
  2. ctrl+x command or your last word will be deleted).
  3. :wq! (saves the file, with the current text, remember ‘!’ is to override).
nano editor
[avishek@tecmint ~]$ nano a.txt (open a.txt file to be edited with nano)
edit, with the content, required

ctrl +x (to close the editor). It will show output as:

Save modified buffer (ANSWERING "No" WILL DESTROY CHANGES) ?                    
 Y Yes 
 N No           ^C Cancel

Click ‘y’ to yes and enter file name, and you are done.

55. Command: rsync

Rsync copies files and has a -P switch for a progress bar. So if you have rsync installed, you could use a simple alias.

alias cp='rsync -aP'

Now try to copy a large file in terminal and see the output with remaining items, similar to a progress bar.

Moreover, Keeping and Maintaining backup is one of the most important and boring work a system administrator, needs to perform. Rsync is a very nice tool (there exists, several other) to create and maintain backup, in terminal.

[avishek@tecmint ~]$ rsync -zvr IMG_5267\ copy\=33\ copy\=ok.jpg ~/Desktop/ 

sending incremental file list 
IMG_5267 copy=33 copy=ok.jpg 

sent 2883830 bytes  received 31 bytes  5767722.00 bytes/sec 
total size is 2882771  speedup is 1.00

Note-z for compression, -v for verbose and -r for recursive.

56. Command: free

Keeping track of memory and resources is as much important, as any other task performed by an administrator, and ‘free‘ command comes to rescue here.

Current Usage Status of Memory
[avishek@tecmint ~]$ free

             total       used       free     shared    buffers     cached
Mem:       2028240    1788272     239968          0      69468     363716
-/+ buffers/cache:    1355088     673152
Swap:      3905532     157076    3748456
Tuned Output in KB, or MB, or GB
[avishek@tecmint ~]$ free -b

             total       used       free     shared    buffers     cached
Mem:    2076917760 1838272512  238645248          0   71348224  372670464
-/+ buffers/cache: 1394253824  682663936
Swap:   3999264768  160845824 3838418944
[avishek@tecmint ~]$ free -k

             total       used       free     shared    buffers     cached
Mem:       2028240    1801484     226756          0      69948     363704
-/+ buffers/cache:    1367832     660408
Swap:      3905532     157076    3748456
[avishek@tecmint ~]$ free -m

             total       used       free     shared    buffers     cached
Mem:          1980       1762        218          0         68        355
-/+ buffers/cache:       1338        641
Swap:         3813        153       3660
[avishek@tecmint ~]$ free -g

             total       used       free     shared    buffers     cached
Mem:             1          1          0          0          0          0
-/+ buffers/cache:          1          0
Swap:            3          0          3
Check Current Usage in Human Readable Format
[avishek@tecmint ~]$ free -h

             total       used       free     shared    buffers     cached
Mem:          1.9G       1.7G       208M         0B        68M       355M
-/+ buffers/cache:       1.3G       632M
Swap:         3.7G       153M       3.6G
Check Status Contineously After Regular Interval
[avishek@tecmint ~]$ free -s 3

             total       used       free     shared    buffers     cached
Mem:       2028240    1824096     204144          0      70708     364180
-/+ buffers/cache:    1389208     639032
Swap:      3905532     157076    3748456

             total       used       free     shared    buffers     cached
Mem:       2028240    1824192     204048          0      70716     364212
-/+ buffers/cache:    1389264     638976
Swap:      3905532     157076    3748456

Read Also : 10 Examples of Free Command

57. Command: mysqldump

Ok till now you would have understood what this command actually stands for, from the name of this command.mysqldump commands dumps (backups) all or a particular database data into a given a file.For example,

[avishek@tecmint ~]$ mysqldump -u root -p --all-databases > /home/server/Desktop/backupfile.sql

Notemysqldump requires mysql to be running and correct password for authorisation. We have covered some useful “mysqldump” commands at Database Backup with mysqldump Command

58. Command: mkpasswd

Make a hard-to-guess, random password of the length as specified.

[avishek@tecmint ~]$ mkpasswd -l 10

zI4+Ybqfx9
[avishek@tecmint ~]$ mkpasswd -l 20 

w0Pr7aqKk&hmbmqdrlmk

Note-l 10 generates a random password of 10 characters while -l 20 generates a password of character 20, it could be set to anything to get desired result. This command is very useful and implemented in scripting language oftenly to generate random passwords. You might need to yum or apt the ‘expect’ package to use this command.

[root@tecmint ~]# yum install expect 
OR
[root@tecmint ~]# apt-get install expect

59. Command: paste

Merge two or more text files on lines using. Example. If the content of file1 was:

1 
2 
3 

and file2 was: 

a 
b 
c 
d 
the resulting file3 would be: 

1    a 
2    b 
3    c 
     d

60.Command: lsof

lsof stands for “list open files” and displays all the files that your system has currently opened. It’s very useful to figure out which processes uses a certain file, or to display all the files for a single process. Some useful 10 lsof Command examples, you might be interested in reading.

[avishek@tecmint ~]$ lsof 

COMMAND     PID   TID            USER   FD      TYPE     DEVICE SIZE/OFF       NODE NAME
init          1                  root  cwd       DIR        8,1     4096          2 /
init          1                  root  rtd       DIR        8,1     4096          2 /
init          1                  root  txt       REG        8,1   227432     395571 /sbin/init
init          1                  root  mem       REG        8,1    47080     263023 /lib/i386-linux-gnu/libnss_files-2.17.so
init          1                  root  mem       REG        8,1    42672     270178 /lib/i386-linux-gnu/libnss_nis-2.17.so
init          1                  root  mem       REG        8,1    87940     270187 /lib/i386-linux-gnu/libnsl-2.17.so
init          1                  root  mem       REG        8,1    30560     263021 /lib/i386-linux-gnu/libnss_compat-2.17.so
init          1                  root  mem       REG        8,1   124637     270176 /lib/i386-linux-gnu/libpthread-2.17.so
init          1                  root  mem       REG        8,1  1770984     266166 /lib/i386-linux-gnu/libc-2.17.so
init          1                  root  mem       REG        8,1    30696     262824 /lib/i386-linux-gnu/librt-2.17.so
init          1                  root  mem       REG        8,1    34392     262867 /lib/i386-linux-gnu/libjson.so.0.1.0
init          1                  root  mem       REG        8,1   296792     262889 /lib/i386-linux-gnu/libdbus-1.so.3.7.2
init          1                  root  mem       REG        8,1    34168     262840 /lib/i386-linux-gnu/libnih-dbus.so.1.0.0
init          1                  root  mem       REG        8,1    95616     262848 /lib/i386-linux-gnu/libnih.so.1.0.0
init          1                  root  mem       REG        8,1   134376     270186 /lib/i386-linux-gnu/ld-2.17.so
init          1                  root    0u      CHR        1,3      0t0       1035 /dev/null
init          1                  root    1u      CHR        1,3      0t0       1035 /dev/null
init          1                  root    2u      CHR        1,3      0t0       1035 /dev/null
init          1                  root    3r     FIFO        0,8      0t0       1714 pipe
init          1                  root    4w     FIFO        0,8      0t0       1714 pipe
init          1                  root    5r     0000        0,9        0       6245 anon_inode
init          1                  root    6r     0000        0,9        0       6245 anon_inode
init          1                  root    7u     unix 0xf5e91f80      0t0       8192 @/com/ubuntu/upstart
init          1                  root    8w      REG        8,1     3916        394 /var/log/upstart/teamviewerd.log.1 (deleted)

This is not the end, a System Administrator does a lot of stuff, to provide you such a nice interface, upon which you work. System Administration is actually an art of learning and implementing in a very much perfect way. We will try to get you with all other necessary stuff which a linux professional must learn, linux in its basic actually itself, is a process of learning and learning.

Source

How to Download Files to Specific Directory Using Wget

Wget is a popular, non-interactive and widely used network downloader which supports protocols such as HTTP, HTTPS, and FTP, and retrieval via HTTP proxies. By default, wget downloads files in the current working directory where it is run.

Read AlsoHow to Rename File While Downloading with Wget in Linux

In this article, we will show how to download files to a specific directory without moving into that directory. This guide is useful, if, for example, you are using wget in a script, and want to automate downloads which should be stored in different directories.

In addition, wget being non-interactive (can work in the background) by design makes it easy to use for automating downloads via shell scripts. You can actually initiate a download and disconnect from the system, letting wget complete the job.

Wget’s -P or --directory-prefix option is used to set the directory prefix where all retrieved files and subdirectories will be saved to.

In this example, we will demonstrate how to download the glances config template and store it under /etc/glances/ directory.

$ sudo mkdir /etc/glances
$ ls /etc/glances/
$ sudo wget https://raw.githubusercontent.com/nicolargo/glances/develop/conf/glances.conf -P /etc/glances/
$ ls /etc/glances/

Wget Download Files to Specific Directory

Wget Download Files to Specific Directory

If you are downloading a heavy file, you may want to add the -c or --continue flag, which means continue getting a partially-downloaded file. With it, you don’t have to start the download afresh.

This option helps you to resume downloading a file started by a previous instance of wget, or by another program or one that you had paused. It is also useful in case of any network failure. For example,

$ wget -c https://tenet.dl.sourceforge.net/project/parrotsecurity/iso/4.1/Parrot-security-4.1_amd64.iso

For more information, see the wget man page.

$ man wget 

You might also like to read these following related articles.

  1. How to Download and Extract Tar Files with One Command
  2. 5 Linux Command Line Based Tools for Downloading Files and Browsing Websites
  3. 15 Tips On How to Use ‘Curl’ Command in Linux

That’s all! In this short article, we have explained how to download files to a specific directory without moving into that directory, using wget. You can share your thoughts with us in the comments.

Source

How to Get Hardware Information with Dmidecode Command on Linux

In this article we’ll see how we can use Dmidecode command to retrieve hardware information of any Linux system. Suppose if we want to upgrade a system we need to gather information like MemoryBIOS and CPUetc. With help of Dmidecode command we will come to know the details without opening system chasis. Dmidecode command works for RHEL/CentOS/Fedora/Ubuntu Linux.

How to Get Hardware Information in Linux

How to Get Hardware Information in Linux

Dmidecode tool read DMI (some say SMBIOS) table to fetch data and displays useful system informations like hardware detailsserial numbers and BIOS version, Processor etc. in human readable format. You may require root priviledge to execute dmidecode command.

1. Basic Output of Demidecode

Below is the Demidecode command sample output.

# dmidecode 2.11
SMBIOS version fixup (2.31 -> 2.3).
SMBIOS 2.3 present.
45 structures occupying 1642 bytes.
Table at 0x000E0010.

Handle 0x0000, DMI type 0, 20 bytes
BIOS Information
        Vendor: Phoenix Technologies LTD
        Version: 6.00
        Release Date: 12/06/2006
        Address: 0xE78A0
        Runtime Size: 100192 bytes
        ROM Size: 64 kB
        Characteristics:
                ISA is supported
                PCI is supported
                PC Card (PCMCIA) is supported
                PNP is supported
                APM is supported
                BIOS is upgradeable
                BIOS shadowing is allowed
                ESCD support is available
               USB legacy is supported
                Smart battery is supported
                BIOS boot specification is supported

2. How to Get DMI Types

DMI Id give us particular hardware information of system. Dmidecode with options ‘-t ‘or ‘–type‘ and ‘Id‘ will provide us the exact infromation. Id 6 will give us Memory Module information.

[root@tecmint ~]# dmidecode -t 6
# dmidecode 2.11
SMBIOS version fixup (2.31 -> 2.3).
SMBIOS 2.3 present.

Handle 0x0009, DMI type 6, 12 bytes
Memory Module Information
        Socket Designation: RAM socket #0
        Bank Connections: 0 1
        Current Speed: Unknown
        Type: EDO DIMM
        Installed Size: 1024 MB (Single-bank Connection)
        Enabled Size: 1024 MB (Single-bank Connection)
        Error Status: OK

Handle 0x000A, DMI type 6, 12 bytes
Memory Module Information
        Socket Designation: RAM socket #1
        Bank Connections: 2 3
        Current Speed: Unknown
        Type: EDO DIMM
        Installed Size: Not Installed
        Enabled Size: Not Installed
        Error Status: OK

Handle 0x000B, DMI type 6, 12 bytes
Memory Module Information
        Socket Designation: RAM socket #2
        Bank Connections: 4 5
        Current Speed: Unknown
        Type: EDO DIMM
        Installed Size: Not Installed
        Enabled Size: Not Installed
        Error Status: OK

Handle 0x000C, DMI type 6, 12 bytes
Memory Module Information
        Socket Designation: RAM socket #3
        Bank Connections: 6 7
        Current Speed: Unknown
        Type: EDO DIMM
        Installed Size: Not Installed
        Enabled Size: Not Installed
        Error Status: OK

Following are the DMI types details.

		Type   Information
		----------------------------------------
          0		BIOS
          1		System
          2		Base Board
          3		Chassis
          4		Processor
          5		Memory Controller
          6		Memory Module
          7		Cache
          8		Port Connector
          9		System Slots
         10		On Board Devices
         11		OEM Strings
         12		System Configuration Options
         13		BIOS Language
         14		Group Associations
         15		System Event Log
         16		Physical Memory Array
         17		Memory Device
         18		32-bit Memory Error
         19		Memory Array Mapped Address
         20		Memory Device Mapped Address
         21		Built-in Pointing Device
         22		Portable Battery
         23		System Reset
         24		Hardware Security
         25		System Power Controls
         26		Voltage Probe
         27		Cooling Device
         28		Temperature Probe
         29		Electrical Current Probe
         30		Out-of-band Remote Access
         31		Boot Integrity Services
         32		System Boot
         33		64-bit Memory Error
         34		Management Device
         35		Management Device Component
         36		Management Device Threshold Data
         37		Memory Channel
         38		IPMI Device
         39		Power Supply

Instead of going with ‘type_id‘ you can also use keyword with ‘-t‘ argument to the dmidecode command. Following are the list of available keywords.

	Keyword     Types
       ------------------------------
       bios        0, 13
       system      1, 12, 15, 23, 32
       baseboard   2, 10
       chassis     3
       processor   4
       memory      5, 6, 16, 17
       cache       7
       connector   8
       slot        9

For example, to get the Cache information on system, you can execute below command instead of Id 7.

[root@tecmint ~]# dmidecode -t cache
# dmidecode 2.11
SMBIOS version fixup (2.31 -> 2.3).
SMBIOS 2.3 present.

Handle 0x000D, DMI type 7, 19 bytes
Cache Information
        Socket Designation: L1 Cache
        Configuration: Enabled, Socketed, Level 1
        Operational Mode: Write Back
        Location: Internal
        Installed Size: 16 kB
        Maximum Size: 16 kB
        Supported SRAM Types:
                Burst
                Pipeline Burst
                Asynchronous
        Installed SRAM Type: Asynchronous
        Speed: Unknown
        Error Correction Type: Unknown
        System Type: Unknown
        Associativity: Unknown

Handle 0x000E, DMI type 7, 19 bytes
Cache Information
        Socket Designation: L2 Cache
        Configuration: Enabled, Socketed, Level 2
        Operational Mode: Write Back
        Location: External
        Installed Size: 0 kB
        Maximum Size: 512 kB
        Supported SRAM Types:
                Burst
                Pipeline Burst
                Asynchronous
        Installed SRAM Type: None
        Speed: Unknown
        Error Correction Type: Unknown
        System Type: Unknown
        Associativity: Unknown

3. How to Get Memory Information

How do i get Memory information on system and how much memory is supported by system? The following command shows that the system can support maximum 4GB of RAM.

[root@tecmint ~]# dmidecode -t 16
# dmidecode 2.11
SMBIOS version fixup (2.31 -> 2.3).
SMBIOS 2.3 present.

Handle 0x001D, DMI type 16, 15 bytes
Physical Memory Array
        Location: System Board Or Motherboard
        Use: System Memory
        Error Correction Type: None
        Maximum Capacity: 4 GB
        Error Information Handle: Not Provided
        Number Of Devices: 4

Note: From the keyword list the memory related information IDs are 5616 and 17.

4. How Do I Get BIOS information?

To get the BIOS information of the system, run the following command with ‘-t’ option.

[root@tecmint ~]# dmidecode -t bios
# dmidecode 2.11
SMBIOS version fixup (2.31 -> 2.3).
SMBIOS 2.3 present.

Handle 0x0000, DMI type 0, 20 bytes
BIOS Information
        Vendor: Phoenix Technologies LTD
        Version: 6.00
        Release Date: 12/06/2006
        Address: 0xE78A0
        Runtime Size: 100192 bytes
        ROM Size: 64 kB
        Characteristics:
                ISA is supported
                PCI is supported
                PC Card (PCMCIA) is supported
                PNP is supported
                APM is supported
                BIOS is upgradeable
                BIOS shadowing is allowed
                ESCD support is available
                USB legacy is supported
                Smart battery is supported
                BIOS boot specification is supported

5. How Do I Get the Manufacturer, Model and Serial Number?

To get the information about ManufacturerModel and Serial Number of system, use the following command as shown below.

[root@tecmint ~]# dmidecode -t system
# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0001, DMI type 1, 27 bytes
System Information
        Manufacturer: LENOVO
        Product Name: 9637C76
        Version: ThinkCentre M55e
        Serial Number: L9BT188
        UUID: 8015D37A-2F82-DC11-A3FB-8C6E4EBAD5CE
        Wake-up Type: AC Power Restored
        SKU Number: Not Specified
        Family: Not Specified

Handle 0x000F, DMI type 12, 5 bytes
System Configuration Options
        Option 1: Jumper settings can be described here.

Handle 0x0010, DMI type 15, 29 bytes
System Event Log
        Area Length: 432 bytes
        Header Start Offset: 0x0000
        Header Length: 16 bytes
        Data Start Offset: 0x0010
        Access Method: General-purpose non-volatile data functions
        Access Address: 0x0000
        Status: Valid, Not Full
        Change Token: 0x0000001A
        Header Format: Type 1
        Supported Log Type Descriptors: 3
        Descriptor 1: POST error
        Data Format 1: POST results bitmap
        Descriptor 2: Single-bit ECC memory error
        Data Format 2: Multiple-event
        Descriptor 3: Multi-bit ECC memory error
        Data Format 3: Multiple-event

Handle 0x0017, DMI type 23, 13 bytes
System Reset
        Status: Enabled
        Watchdog Timer: Present
        Boot Option: Do Not Reboot
        Boot Option On Limit: Do Not Reboot
        Reset Count: Unknown
        Reset Limit: Unknown
        Timer Interval: Unknown
        Timeout: Unknown

Handle 0x001F, DMI type 32, 20 bytes
System Boot Information
        Status:

Please run ‘man dmidecode‘ from terminal or command prompt to know more about dmidecode.

Read Also10 Command Line Tools to Get Linux Hardware Information

Source

10 Useful “IP” Commands to Configure Network Interfaces

In this post, we are going to review how we can assign Static IP AddressStatic RouteDefault Gateway etc.  Assigning IP Address on demand using IP command. IFCONFIG command is deprecated and replaced by IPcommand in Linux. However, IFCONFIG command is still works and available for most of the Linux distributions.

Don’t Miss: ifconfig vs ip: What’s Difference and Comparing Commands

IP Command Examples

10 IP Command Examples

Note: Please take configuration file backup before doing any changes.

How do i Configure Static IP Address Internet Protocol (IPv4)

To configure static IP Address, you need to update or edit network configuration file to assign an Static IP Address to a system. You must be superuser with su (switch user) command from terminal or command prompt.

For RHEL/CentOS/Fedora

Open and edit network configuration file for (eth0 or eth1) using your favorite editor. For example, to assigning IP Address to eth0 interface as follows.

[root@tecmint ~]# vi /etc/sysconfig/network-scripts/ifcfg-eth0
Simple output:
DEVICE="eth0"
BOOTPROTO=static
ONBOOT=yes
TYPE="Ethernet"
IPADDR=192.168.50.2
NAME="System eth0"
HWADDR=00:0C:29:28:FD:4C
GATEWAY=192.168.50.1

For Ubuntu/Debian/Linux Mint

Assign Static IP Address to eth0 interface editing configuration file /etc/network/interfaces to make permanent changes as shown below.

auto eth0
iface eth0 inet static
address 192.168.50.2
netmask 255.255.255.0
gateway 192.168.50.1

Next, restart network services after entering all the details using the following command.

# /etc/init.d/networking restart
$ sudo /etc/init.d/networking restart

1. How to Assign a IP Address to Specific Interface

The following command used to assign IP Address to a specific interface (eth1) on the fly.

# ip addr add 192.168.50.5 dev eth1
$ sudo ip addr add 192.168.50.5 dev eth1

Note: Unfortunately all these settings will be lost after a system restart.

2. How to Check an IP Address

To get the depth information of your network interfaces like IP Address, MAC Address information, use the following command as shown below.

# ip addr show
$ sudo ip addr show
Sample Output
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
    link/ether 00:0c:29:28:fd:4c brd ff:ff:ff:ff:ff:ff
    inet 192.168.50.2/24 brd 192.168.50.255 scope global eth0
    inet6 fe80::20c:29ff:fe28:fd4c/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
    link/ether 00:0c:29:28:fd:56 brd ff:ff:ff:ff:ff:ff
    inet 192.168.50.5/24 scope global eth1
    inet6 fe80::20c:29ff:fe28:fd56/64 scope link
       valid_lft forever preferred_lft forever

3. How to Remove an IP Address

The following command will remove an assigned IP address from the given interface (eth1).

# ip addr del 192.168.50.5/24 dev eth1
$ sudo ip addr del 192.168.50.5/24 dev eth1

4. How to Enable Network Interface

The “up” flag with interface name (eth1) enables a network interface. For example, the following command will activates the eth1 network interface.

# ip link set eth1 up
$ sudo ip link set eth1 up

5. How to Disable Network Interface

The “down” flag with interface name (eth1) disables a network interface. For example, the following command will De-activates the eth1 network interface.

# ip link set eth1 down
$ sudo ip link set eth1 down

6. How do I Check Route Table?

Type the following command to check the routing table information of system.

# ip route show
$ sudo ip route show
Sample Output
10.10.20.0/24 via 192.168.50.100 dev eth0
192.168.160.0/24 dev eth1  proto kernel  scope link  src 192.168.160.130  metric 1
192.168.50.0/24 dev eth0  proto kernel  scope link  src 192.168.50.2
169.254.0.0/16 dev eth0  scope link  metric 1002
default via 192.168.50.1 dev eth0  proto static

7. How do I Add Static Route

Why you need to add Static routes or Manual routes, because that the traffic must not pass through the default gateway. We need to add Static routes to pass traffic from best way to reach the destination.

# ip route add 10.10.20.0/24 via 192.168.50.100 dev eth0
$ sudo ip route add 10.10.20.0/24 via 192.168.50.100 dev eth0

8. How to Remove Static Route

To remove assigned static route, simply type the following command.

# ip route del 10.10.20.0/24
$ sudo ip route del 10.10.20.0/24

9. How do I Add Persistence Static Routes

All the above route will be lost after a system restart. To add permanent Static route, edit file /etc/sysconfig/network-scripts/route-eth0 (We are storing static route for (eth0) and add the following lines and save and exist. By default route-eth0 file will not be there, need to be created.

For RHEL/CentOS/Fedora

# vi /etc/sysconfig/network-scripts/route-eth0
10.10.20.0/24 via 192.168.50.100 dev eth0

For Ubuntu/Debian/Linux Mint

Open the file /etc/network/interfaces and at the end add the persistence Static routes. IP Addresses may differ in your environment.

$ sudo vi /etc/network/interfaces
auto eth0
iface eth0 inet static
address 192.168.50.2
netmask 255.255.255.0
gateway 192.168.50.100
#########{Static Route}###########
up ip route add 10.10.20.0/24 via 192.168.50.100 dev eth0

Next, restart network services after entering all the details using the following command.

# /etc/init.d/network restart
$ sudo /etc/init.d/network restart

10. How do I Add Default Gateway

Default gateway can be specified globally or for in interface-specific config file. Advantage of default gateway is If we have more than one NIC is present in the system. You can add default gateway on the fly as shown below command.

# ip route add default via 192.168.50.100
$ sudo ip route add default via 192.168.50.100

Kindly correct me if i missed out. Please refer manual page doing man ip from terminal/command prompt to know more about IP Command.

Source

WP2Social Auto Publish Powered By : XYZScripts.com