All Documents
Current Document

Content is empty

If you don't find the content you expect, please try another search term

Documentation

Common Linux commands

Last updated:2021-08-03 18:56:33

syslog

This command serves as the default logging daemon of the Linux system. It receives system information of different severity levels from various functions.

The /etc/syslog.conf file instructs syslogd to report messages based on the device and severity level of information. You can use the logger command for logging by syslogd.

Record log messages in the /var/log/messages file.

logger this is a test log line
Output:
tail -n 1 messagesJan 5 10:07:03 localhost root: this is a test log line

Record a specific tag.

logger -t TAG this is a test log line
Output:
tail -n 1 messagesJan 5 10:37:14 localhost TAG: this is a test log line

systemctl

This command instructs the system service manager and combines the service command with the chkconfig command.

Task Old command New command
Enable a service to start automatically. chkconfig --level 3 httpd on systemctl enable httpd.service
Enable a service not to start automatically. chkconfig --level 3 httpd off systemctl disable httpd.service
Check the service status. service httpd status systemctl status httpd.service (detailed service information)
systemctl is-active httpd.service (whether the service is active)
Display all started services. chkconfig --list systemctl list-units --type=service
Start a service. service httpd start systemctl start httpd.service
Stop a service. service httpd stop systemctl stop httpd.service
Restart a service. service httpd restart systemctl restart httpd.service

Examples

  1. Start the nfs service.
systemctl start nfs-server.service
  1. Enable the service to start automatically at system startup.
systemctl enable nfs-server.service
  1. Disable the service from starting automatically at system startup.
systemctl disable nfs-server.service
  1. Check the current status of the service.
systemctl status nfs-server.service
  1. Restart the service.
systemctl restart nfs-server.service
  1. Check all started services.
systemctl list -units --type=service
  1. Open port 22 on iptables.
iptables -I INPUT -p tcp --dport 22 -j accept
  1. Close SElinux.

    Set SELINUX=” disabled” in the /etc/selinux/config file, and then restart the system.

  2. Completely disable the firewall.
sudo systemctl status firewalld.servicesudo systemctl stop firewalld.servicesudo systemctl disable firewalld.service

crontab

Use this command to submit and manage user tasks that need to be executed periodically. When the operating system is installed, this command is installed by default and the crond process is started automatically. The crond process checks tasks every minute for automatic execution.

Syntax

crontab (option) (parameter)

Options

-e: Edit the user’s timer setting.
-l: List the user’s timer setting.
-r: Remove the user’s timer setting.
-u<username>: Specify the user name to set the timer.

Parameters

crontab file: Specify the crontab file containing the tasks to be executed.

mount

Use this command to mount a file system to the specified mount point. This command is typically used for manually mounting a CD-ROM for data access, because Linux does not mount the CD-ROM automatically for an inserted disk.

Syntax

mount (option) (parameter)

Options

-V: Display the program version. 
-l: List all mounted file systems.
-h: Display the help information and exit.
-v: Enable verbose mode to output details of instruction execution.
-n: Mount a file system that is not contained in the /etc/mtab file. 
-r: Mount a file system in read-only mode.
-a: Mount all file systems described in the /etc/fstab file.

Parameters

Device file name: Specify the name of the device for the file system to be mounted. Mount point: Specify the mount point directory.

Examples

mount -t auto /dev/cdrom /mnt/cdrom
mount: mount point /mnt/cdrom does not exist         #The /mnt/cdrom directory does not exist.
cd /mnt
-bash: cd: /mnt: No such file or directory
mkdir -p /mnt/cdrom     #Create the /mnt/cdrom directory.
ls
bin   dev  home    lib         media  mnt  proc  sbin     srv  tmp  
var
boot  etc  initrd  lost+found  misc   opt  root  selinux  sys  usr
mount -t auto /dev/cdrom /mnt/cdrom    #Mount a CD-ROM. 
mount: block device /dev/cdrom is write-protected, mounting read-only     #The CD-ROM is successfully mounted.
ll /mnt/cdrom    # View the CD-ROM information.
total 859
dr-xr-xr-x  4 root root   2048 Sep  4  2005 CentOS
-r--r--r--  2 root root   8859 Mar 19  2005 centosdocs-man.css
-r--r--r--  9 root root  18009 Mar  1  2005 GPL
dr-xr-xr-x  2 root root 241664 May  7 02:32 headers
dr-xr-xr-x  4 root root   2048 May  7 02:23 images
dr-xr-xr-x  2 root root   4096 May  7 02:23 isolinux
dr-xr-xr-x  2 root root  18432 May  2 18:50 NOTES
-r--r--r--  2 root root   5443 May  7 01:49 RELEASE-NOTES-en.html
dr-xr-xr-x  2 root root   2048 May  7 02:34 repodata
-r--r--r--  9 root root   1795 Mar  1  2005 rpm-GPG-KEY
-r--r--r--  2 root root   1795 Mar  1  2005 RPM-GPG-KEY-centos4
-r--r--r--  1 root root 571730 May  7 01:39 yumgroups.xml

fsck

Use this command to check and try to fix file system errors.

Syntax

fsck (option) (parameter)

Options

-a: Fix the file system automatically without displaying any interactive prompt messages.
-A: Check all file systems contained in the /etc/fstab file.
-N: Display actions that will be executed, instead of actually executing them.
-P: Use this option together with -A to check all file systems simultaneously.
-r: Enter the interactive mode, in which the user needs to confirm each operation and decide the processing method to fix file system errors.
-R: Use this option together with -A to skip checking file systems located in the specified directory.
-s: Check tasks in sequence instead of simultaneously.
-t< file system type>: Specify the type of the file systems to examine.
-T: Execute fsck command without displaying the title information.
-V: Display the process of command execution.

Parameters

File system: Specify the file system to examine.

Examples

A file system error might lead to an abnormal shutdown of Linux. If you are informed of the faulty hard disk partition, such as /dev/hda2, use the following command to fix the error:

fsck -y /dev/hda2

When the fix process is complete, use the reboot command to restart the system
If the problem is not located, use the following command:

fsck

Enter y in the following confirmation dialog boxes. Then, use the reboot command to restart the system.

ulimit

Use this command to control access to shell resources for system users. It is a simple and effective method for resource restriction. For temporary restriction, use ulimit to control shell sessions that are logged in through CLI, and the restriction becomes invalid at termination of the sessions. For regular and fixed restriction, add the ulimit command statement to files read by login shells to restrict specific users.

Syntax

ulimit (option)

Options

-a: Display current resource restriction settings.
-c <core file upper limit>: Set the maximum size of the core file, in blocks.
-d <data segment size>: Set the maximum size of the program’s data segment, in KB.
-f <file size>: Set the maximum size of files that can be created by shell, in blocks.
-H: Set the rigid restrictions of the resource, that is, the limitation set by the administrator.
-m <memory size>: Specify the upper limit of accessible memory, in KB.
-n <number of files>: Specify the maximum number of files that can be opened simultaneously.
-p <buffer size>: Specify the size of the pipe buffer, in 512 bytes.
-s <stack size>: Specify the upper limit of stacking, in KB.
-S: Set the elastic restrictions of resources.
-t <CPU time>: Specify the upper limit of time on CPU usage, in seconds.
-u <number of programs>: Specify the maximum number of programs that a user can launch.
-v <size of virtual memory>: Specify the upper limit of accessible virtual memory, in KB.

Examples

[root@localhost ~]# ulimit -a
core file size       (blocks, -c) 0            #The maximum size for the core file is 100 blocks. 
data seg size        (kbytes, -d) unlimited    #The data segment of the process is not limited. 
scheduling priority          (-e) 0
file size            (blocks, -f) unlimited    #The file size is not limited.
pending signals              (-i) 98304        #The maximum number of signals to be processed is 98,304.
max locked memory   (kbytes, -l) 32            #The maximum size of physical memory locked by each task is 32KB.
max memory size     (kbytes, -m) unlimited     #The size of resident physical memory for each task is not limited.
open files                    (-n) 1024        #A task can open up to 1024 files simultaneously.
pipe size         (512 bytes, -p) 8            #The maximum size of a pipe is 4,096 bytes.
POSIX message queues (bytes, -q) 819200        #The maximum size of the POSIX message queue is 819,200 bytes.
real-time priority            (-r) 0
stack size           (kbytes, -s) 10240        #The maximum stack size for processes is 10,240 bytes.
cpu time            (seconds, -t) unlimited    #The CPU time used by processes is not limited.
max user processes             (-u) 98304  #The maximum number of processes (including threads) launched simultaneously by the current user is 98,304.
virtual memory      (kbytes, -v) unlimited     #The address space for processes is not limited.
file locks                   (-x) unlimited    #The number of locked files is not limited. 

sysctl

Use this command to dynamically modify the kernel's operating parameters while the kernel is running. The kernel parameters are stored at directory /proc/sys, which include TCP/IP stack and advanced options for the virtual memory system. The total number of system variables configurable with this command exceeds 500.

Syntax

sysctl (option) (parameter)

Options

-n: Print values excluding keywords.
-e: Ignore unknown keyword error.
-N: Print names only.
-w: Use this option to change the sysctl setting.
-p: Load the kernel parameter settings from the /etc/sysctl.conf file.
-a: Print all current available kernel variables and values.
-A: Print all current available kernel variables and values in a form.

Parameters

variable = value: Set the value of a kernel variable.

Examples

sysctl -a 

Print the setting of the variable named kern.maxproc.

sysctl kern.maxproc 
kern.maxproc: 1044

Set the value of the variable kern.maxfiles to 5000.

sysctl kern.maxfiles=5000
kern.maxfiles: 2088 -> 5000

You can change the system variables by using the sysctl command or editing the sysctl.conf file. In the file, set the value in the form of “variable=value”. The sysctl settings are typically character strings, numbers, or of Boolean type (1 for yes and 0 for no).

sysctl -w kernel.sysrq=0
sysctl -w kernel.core_uses_pid=1
sysctl -w net.ipv4.conf.default.accept_redirects=0
sysctl -w net.ipv4.conf.default.accept_source_route=0
sysctl -w net.ipv4.conf.default.rp_filter=1
sysctl -w net.ipv4.tcp_syncookies=1
sysctl -w net.ipv4.tcp_max_syn_backlog=2048
sysctl -w net.ipv4.tcp_fin_timeout=30
sysctl -w net.ipv4.tcp_synack_retries=2
sysctl -w net.ipv4.tcp_keepalive_time=3600
sysctl -w net.ipv4.tcp_window_scaling=1
sysctl -w net.ipv4.tcp_sack=1

Configure sysctl

Edit the file /etc/sysctl.conf. Modify the contents as needed or enter the following contents if the file is empty:

# Controls source route verification
# Default should work for all interfaces
net.ipv4.conf.default.rp_filter = 1
# net.ipv4.conf.all.rp_filter = 1
# net.ipv4.conf.lo.rp_filter = 1
# net.ipv4.conf.eth0.rp_filter = 1
# Disables IP source routing
# Default should work for all interfaces
net.ipv4.conf.default.accept_source_route = 0
# net.ipv4.conf.all.accept_source_route = 0
# net.ipv4.conf.lo.accept_source_route = 0
# net.ipv4.conf.eth0.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
# Increase maximum amount of memory allocated to shm
# Only uncomment if needed!
# kernel.shmmax = 67108864
# Disable ICMP Redirect Acceptance
# Default should work for all interfaces
net.ipv4.conf.default.accept_redirects = 0
# net.ipv4.conf.all.accept_redirects = 0
# net.ipv4.conf.lo.accept_redirects = 0
# net.ipv4.conf.eth0.accept_redirects = 0
# enable Log Spoofed Packets, Source Routed Packets, Redirect Packets
# Default should work for all interfaces
net.ipv4.conf.default.log_martians = 1
# net.ipv4.conf.all.log_martians = 1
# net.ipv4.conf.lo.log_martians = 1
# net.ipv4.conf.eth0.log_martians = 1
# Decrease the time default value for tcp_fin_timeout connection
net.ipv4.tcp_fin_timeout = 25
# Decrease the time default value for tcp_keepalive_time connection
net.ipv4.tcp_keepalive_time = 1200
# Turn on the tcp_window_scaling
net.ipv4.tcp_window_scaling = 1
# Turn on the tcp_sack
net.ipv4.tcp_sack = 1
# tcp_fack should be on because of sack
net.ipv4.tcp_fack = 1
# Turn on the tcp_timestamps
net.ipv4.tcp_timestamps = 1
# Enable TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1
# Enable ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1
# make more local ports available
# net.ipv4.ip_local_port_range = 1024 65000
# set TCP Re-Ordering value in kernel to ‘5′
net.ipv4.tcp_reordering = 5
# Lower syn retry rates
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 3
# Set Max SYN Backlog to ‘2048′
net.ipv4.tcp_max_syn_backlog = 2048
# Various Settings
net.core.netdev_max_backlog = 1024
# Increase the maximum number of skb-heads to be cached
net.core.hot_list_length = 256
# Increase the tcp-time-wait buckets pool size
net.ipv4.tcp_max_tw_buckets = 360000
# This will increase the amount of memory available for socket input/output queues
net.core.rmem_default = 65535
net.core.rmem_max = 8388608
net.ipv4.tcp_rmem = 4096 87380 8388608
net.core.wmem_default = 65535
net.core.wmem_max = 8388608
net.ipv4.tcp_wmem = 4096 65535 8388608
net.ipv4.tcp_mem = 8388608 8388608 8388608
net.core.optmem_max = 40960

fstab

This file describes the file systems in Linux. It includes static information about the file systems and defines the integration method of the storage devices and partitions to the whole system. Use the mount command to read this file and confirm the mounting options of devices and partitions.

File format

<file system> <dir> <type> <options> <dump> <pass>

Separated by space or Tab.

  • <file systems>: Partition or storage device to mount.
  • <dir>: Mount point for <file systems>.

  • <type>: File system type for mounting the partition or device. Various file systems are supported.

  • <options>: Parameters for mounting. Note that some mounting parameters only exist in specific file systems.

    Common parameters include:

- auto – Perform automatic mounting at system startup or by executing the mount -a command.
- noauto – Perform mounting manually when the user command is executed.
- exec – Allow to execute binary files in the partition.
- noexec – Prohibit binary files to be executed on this file system. 
- ro – Mount the file system in read-only mode.
- rw – Mount the file system in read/write mode.
- user – Allow any user to mount this file system. If no definition is displayed, the noexec, nosuid, and nodev parameters are enabled by default.
- users – Allow all users in the users group to mount the file system.
- nouser – Allow mounting to be performed only by the root user .
- owner – Allow mounting to be performed by the device owner.
- sync – Perform I/O simultaneously.
- async – Perform I/O asynchronously.
- dev – Parse the special block devices of the file system. 
- nodev – Leave the special block devices of the file system unparsed. 
- suid – Allow the SUID operation and SGID bit setting. 
- nosuid – Prohibit the SUID operation and SGID bit setting.
- noatime – Turn off update of the inode access record in the file system to improve system performance (see the atime parameter). 
- nodiratime – Turn off update of the directory inode access record in the file system to improve system performance (see the atime parameter). 
- relatime – Update the inode access record in real time. The access time will be updated only when the earlier access time exists. 
- flush – It is a vfat option to update data more frequently. The copy dialog box or process bar disappears only when all data has been written to the system.
- defaults – Use the default mounting settings of the file system. For example, the default parameter settings of ext4 are rw, suid, dev, exec, auto, nouser, and async. 
  • <dump>: Use the dump tool to decide the time for backup. The tool checks the contents and decides whether or not to back up the file system. Supported values are 0 and 1. 0 indicates ignore and 1 indicates backup.

  • <pass>: fsck reads the value of <pass> to decide the checking order of file systems. Supported values are 0, 1, and 2. The root directory gains the highest priority of 1; other devices that need to be checked are set to 2. 0 indicates that fsck does not check the device.

Examples

Identify the disk by using the kernel name.

/etc/fstab
# <file system> <dir> <type> <options> <dump> <pass>
tmpfs /tmp tmpfs nodev,nosuid 0 0
/dev/sda1 / ext4 defaults,noatime 0 1
/dev/sda2 none swap defaults 0 0
/dev/sda3 /home ext4 defaults,noatime 0 2

Forbid frequent log printing by the idle kernel

echo 1>/sys/module/rcupdate/parameters/rcu_cpu_stall_suppress

This parameter is in the rc.local file. Use it to prevent slow server response caused by the frequent log printing on the idle KEC instance. Without setting this parameter, kernel logs will be printed every few seconds.

Close the NetworkManager service

After installation of x-window on CentOS 6.6, the NetworkManager service is automatically started and it disables the KEC instance from obtaining an IP address and DNS address at the system restart. To solve the problem, close this service.

Connect to the KEC instance through VNC on the console.

Temporarily close the service.

service  NetworkManager stop

Permanently close the service.

chkconfig NetworkManager off

Tips

Auto mounting

If the /home partition is large in size, first start the services that do not depend on the partition, and then add the following parameters to the /home project in the /etc/fstab file.

noauto,x-systemd.automount

This method ensures that the /home partition is mounted only when it is accessed. The kernel will cache all file operations until preparation of the /home partition is complete. The file system of /home is identified as autofs and will be ignored during mlocate queries.

You can mount a remote file system in the same way. In addition, you can set the timeout period by using the x-systemd.device-timeout parameter to save time in the case that an Internet resource cannot be accessed. To use a secret key for the encrypted file system, add the noauto parameter to the /etc/crypttab file.

/etc/crypttabdata /dev/md0 /root/key noauto

Swap partition UUID

If the swap partition has no UUID, you can manually assign a UUID. Check the swap partition by using the Isblk –f command. The target swap partition does not have the UUID listed. To assign a UUID to the swap partition:

# swapon -s  //Check swap usage summary by device.
# swapoff /dev/sda7  //Disable swapping on the specified devices and files.
# mkswap -U random /dev/sda7  //Create a swap partition by a new UUID.
# swapon /dev/sda7  //Activate the swap partition.

Spaces in pathnames

To represent a space in the mounting path, use the escape character “040”, which is a 3-digital octal value.

/etc/fstab
UUID=47FA-4071 /home/username/Camera040Pictures vfat defaults,noatime 0 2
/dev/sda7 /media/100040GB040(Storage) ext4 defaults,noatime,user 0 0

Peripheral device

Use the nofail command to ignore absence of peripheral devices that were previously inserted and mounted to the system. If this command is not used, the system will generate errors for absence of peripheral devices at startup.

/etc/fstab /dev/sdg1 /media/backup jfs defaults,nofail 0 2

Read and write permissions for common users

To obtain the write permission to FAT32 partitions, you must modify the /etc/fstab file first.

/etc/fstab/dev/sdxY /mnt/some_folder vfat user,rw,umask=000 0 0

For example, to mount a FAT32 partition located at /dev/sda9 to /mnt/fat32, use the following command:

/etc/fstab/dev/sda9 /mnt/fat32 vfat user,rw,umask=111,dmask=000 0 0
On this page
Pure ModeNormal Mode

Pure Mode

Click to preview the document content in full screen
Feedback