Basics of Linux System (2)

PHP中文网
Release: 2017-06-20 11:19:38
Original
2403 people have browsed it
Linux Disk Management
I/O Ports: I/O device address;
Everything is a file:
open(), read(), write(), close()
Block device: block, access unit "block", disk
Character device: char, access unit "character", keyboard
Device file: associated to a device driver to communicate with the corresponding hardware device;
Device number:
Major device number: major number, identifies the device type
Minor device number: minor number, identifies different devices of the same type
Hard disk interface type:
Parallel:
IDE: 133MB/ s
SCSI: 640MB/s
Serial port:
SATA: 6Gbps
SAS: 6Gbps
USB: 480MB/s
##rpm: rotations per minute
##/dev/DEV_FILE
Device file naming for disk devices:
IDE: /dev/hd
##SCSI, SATA, SAS, USB: /dev/sd
Different devices: a-z
/dev/sda, /dev/sdb, ...
Different partitions on the same device: 1,2, ...
##/dev/sda1, /dev/sda5
Mechanical hard drive:
track: track
cylinder: cylinder
secotr: sectors
512bytes
##How to partition:
By cylinder
0 Track 0 Sector: 512bytes
MBR: Master Boot Record
446bytes: boot loader
64bytes: partition table
16bytes: identify a partition
2bytes: 55AA
4 primary partitions;
3 primary partitions + 1 extension (N logical partitions)
Logical partition
##Partition management tools: fdisk, parted, sfdisk
fdisk: For a hard disk, it can only manage up to 15 partitions;
# fdisk -l [-u] [device...]
fdisk device
Subcommand: Management function
p: print, display existing partition;
n: new, create
d: delete, delete
w: write, write to disk and exit
q: quit, abandon update and exit
m: Get help
l: List the partition id
t: Adjust the partition id
Check whether the kernel has recognized the new partition:
# cat /proc/partations
Notify the kernel to re-read the hard disk partition table:
partx -a /dev/DEVICE
-n M:N
kpartx -a /dev/DEVICE
-f: force
CentOS 5: Using partprobe
partprobe [/dev/DEVICE]
Linux file system management:
Linux file system: ext2, ext3, ext4, xfs, btrfs, reiserfs, jfs, swap
swap: swap partition
CD: iso9660
Windows: fat32, ntfs
Unix : FFS, UFS, JFS2
##Network file system: NFS, CIFS
Cluster file system: GFS2, OCFS2
Distributed file system: ceph,
moosefs, mogilefs, GlusterFS, Lustre
Depending on whether it supports the "journal" function:
Journal file system: ext3, ext4, xfs, ...
Non-journal file system File system: ext2, vfat
Components of the file system:
Modules in the kernel: ext4, xfs , vfat
User space management tools: mkfs.ext4, mkfs.xfs, mkfs.vfat
Linux Virtual file system: VFS
Create file system:
mkfs command:
(1) # mkfs.FS_TYPE /dev/DEVICE
##ext4
xfs
btrfs
vfat
(2) # mkfs -t FS_TYPE /dev/DEVICE
-L 'LABEL': Set volume label
##mke2fs: Special management tool for ext series file systems
-t {ext2|ext3|ext4}
##-b {1024|2048|4096}
-L 'LABEL'
-j: equivalent to -t ext3
mkfs.ext3 = mkfs -t ext3 = mke2fs -j = mke2fs -t ext3
-i #: Create an inode for every number of bytes in the data space; this size should not be less than the block size;
-N #: How many inodes are created for the data space;
-m #: The percentage of space reserved for managers;
-O FEATURE[,...]: Enable the specified feature
-O ^FEATURE: Turn off the specified feature
mkswap: Create swap partition
mkswap [options] device
-L 'LABEL'
Prerequisite: Adjust the ID of the partition to 82;
Others Commonly used tools:
blkid: View block device attribute information
blkid [OPTION]... [DEVICE]
-U UUID: Find the corresponding device based on the specified UUID
-L LABEL: Find the corresponding device based on the specified LABEL
e2label: LABEL for managing ext series file systems
# e2label DEVICE [LABEL]
tune2fs: Reset the value of the adjustable parameters of the ext series file system
-l: View the super block information of the specified file system; super block
-L 'LABEL': Modify the volume label
-m #: Modify the percentage of space reserved for administrators
-j: Upgrade ext2 to ext3
-O: Enable or disable file system properties
-o: Adjust the default mount options of the file system
-U UUID: Modify the UUID number;
dumpe2fs:
-h: View super block information
File system detection:
fsck: File System CheCk
fsck.FS_TYPE
fsck -t FS_TYPE
-a: Automatically fix errors
-r: Interactively fix errors
Note: FS_TYPE must be the same type as the existing files on the partition;
e2fsck: A dedicated detection and repair tool for ext series files
-y: The automatic answer is yes;
-f: Forced repair;
File system management:
The act of establishing an association between an additional file system and an existing directory in the root file system, so that this directory serves as an access entry for other files, is called mounting;
The process of releasing this association is called uninstallation;
Associate the device with the mount point: Mount Point
mount
When uninstalling: You can use the device or the mount point
umount
Note: The original files under the mount point will be temporarily hidden after the mount is completed;
Mounting method: mount DEVICE MOUNT_POINT
mount: Display all devices mounted on the current system by viewing the /etc/mtab file
mount [-fnrsvw] [-t vfstype] [-o options] device dir
device: Specify the device to be mounted;
(1) Device file: for example/dev/sda5
(2) Volume label: -L 'LABEL', for example -L 'MYDATA'
(3) UUID, -U 'UUID': For example -U '0c50523c-43f1-45e7-85c0-a126711d406e'
( 4) Pseudo file system name: proc, sysfs, devtmpfs, configfs
dir: The mount point
already exists; it is recommended to use an empty directory ;
The device being used by the process cannot be uninstalled;
Common command options:
-t vsftype: Specify the file system type on the device to be mounted;
-r: readonly, read-only mount;
-w: read and write, read-write mount;
-n: do not update /etc/mtab;
-a: Automatically mount all devices that support automatic mounting; (defined in the /etc/fstab file, and there is an "auto-mount" function in the mounting options)
-L 'LABEL': Specify the device to be mounted with the volume label;
-U 'UUID': Specify the device to be mounted with the UUID;
-B, --bind: Bind the directory to another directory;
Note: Check the mounted files tracked by the kernel All devices: cat /proc/mounts
-o options: (Options for mounting the file system)
async: asynchronous mode;
sync: synchronous mode;
atime/noatime: including directories and files;
diratime/nodiratime: Access timestamp of the directory
auto/noauto: Whether to support automatic mounting
exec/ noexec: Whether to support running applications on the file system as a process
dev/nodev: Whether to support the use of device files on this file system;
suid/nosuid:
remount: Remount
ro:
rw :
user/nouser: Whether ordinary users are allowed to mount this device
acl: Enable the acl function on this file system
Note: The above options can be used multiple times at the same time, separated by commas;
Default mount options: defaults
rw, suid, dev, exec, auto, nouser, and async
Uninstall command:
# umount DEVICE
# umount MOUNT_POINT
View the processes that are accessing the specified file system:
fuser -v MOUNT_POINT
Terminate all processes that are accessing the specified file system:
# fuser -km MOUNT_POINT
Mount swap partition:
Enable: swapon
##swapon [OPTION]... [DEVICE]
-a: Activate all swap partitions;
-p PRIORITY: Specify priority;
Disable: swapoff [OPTION]... [DEVICE]
Memory space usage status:
free [OPTION]
-m: in MB
-g: in GB
Tool for viewing information such as file system space usage:
df:
-h: human- readable
-i:inodes instead of blocks
-P: Output in Posix-compatible format;
View the overall space usage status of a directory:
du:
du [OPTION].. . DIR
-h: human-readable
-s: summary
Commands described: mount, umount, free, df, du, swapon, swapoff, fuser
Configuration file for file mounting: /etc/fstab
Each line defines a file system to be mounted;
The device or pseudo device to be mounted File systemMount pointFile system type Mount optionsDump frequency Self-test sequence
The device or pseudo file system to be mounted:
Device file, LABEL(LABEL=""), UUID( UUID=""), pseudo file system name (proc, sysfs)
Mount options:
defaults
Dump frequency:
0: No backup
1: Daily dump
2: Every other day dump
Self-test sequence:
0: No self-check
1: Self-check first; generally only rootfs uses 1;
...
Other concepts on the file system:
Inode: Index Node, index node
Address pointer:
Direct pointer:
Indirect pointer:
Third-level pointer:
inode bitmap: status information that identifies whether each inode is idle;
Linked file:
Hard link:
Cannot be linked directory;
cannot be performed across partitions;
points to multiple different paths to the same inode; creating a hard link to the file is The inode creates a new reference path, thus increasing its reference count;
Symbolic link:
can be performed on the directory;
can be performed across partitions;
points to the path of another file; its size is the length of the path string pointed to; does not increase or decrease the reference count of the target file inode;
ln [-sv] SRC DEST
-s: symbolic link
-v: verbose
The impact of file management operations on files:
File deletion:
File Copy:
File move:

1. Create a 20G file system with a block size of 2048 and a file The system is ext4, and the volume label is TEST. This partition is required to be automatically mounted to the /testing directory after booting, and has the acl mounting option by default;
(1) Create a 20G partition;
(2) Format:
mke2fs -t ext4 -b 2048 -L 'TEST' /dev/DEVICE
(3) Edit the /etc/fstab file
LABEL='TEST' /testing ext4 defaults,acl 0 0
3. Write a script to complete the following functions:
(1) List all disk devices recognized by the current system;
(2) If the number of disks is 1, display its space usage information;
Otherwise, the space usage information on the last disk is displayed;
if [ $disks -eq 1 ]; then
fdisk -l /dev/[hs]da
else
fdisk -l $(fdisk -l /dev /[sh]d[a-z] | grep -o "^Disk /dev/[sh]d[a-]" | tail -1 | cut -d' ' -f2)
fi
User interaction for bash script programming:
read [option]... [name. ..]
-p 'PROMPT'
-t TIMEOUT
bash -n /path/to/some_script
Detect syntax errors in scripts
bash - x /path/to/some_script
##Debug execution
##Example:
#!/bin/bash
Version: 0.0.1
# Author: MaEdu
# Description: read testing
read -p "Enter a disk special file: " diskfile
[ -z "$diskfile" ] && echo "Fool" && exit 1
##if fdisk -l | grep "^Disk $diskfile" &> /dev/null; then
fdisk -l $diskfile
##else
echo " Wrong disk special file."
exit 2
fi
##RAID:
Redundant Arrays of Inexpensive Disks
                                                                  Independent
Berkeley: A case for Redundent Arrays of Inexpensive Disks RAID
Improve IO capabilities:
Disk parallel reading and writing;
Improve durability;
Disk redundancy to achieve
Level: multiple blocks Disks work differently when organized together;
RAID implementation method:
External disk array: providing adaptation capabilities through expansion cards
Internal RAID: Motherboard integrated RAID controller
Software RAID:
Level: level
RAID-0: 0, striped volume, strip;
RAID-1: 1, mirrored volume, mirror;
RAID-2
..
RAID-5:
RAID-6
RAID10
RAID01
RAID-0 :
Improved reading and writing performance;
Available space: N*min(S1,S2,...)
No fault tolerance
Minimum number of disks: 2, 2+
RAID -1:
The reading performance is improved and the writing performance is slightly reduced;
Available space: 1*min(S1,S2,.. .)
With redundancy capability
Minimum number of disks: 2, 2+
RAID-4:
##1101, 0110, 1011
RAID-5:
Read and write performance improvement
Available space: (N-1)*min(S1,S2,...)
Fault tolerance: 1 disk
Minimum number of disks: 3, 3+
RAID-6:
Read and write performance improvement
Available space: (N-2)*min(S1, S2,...)
Fault tolerance: 2 disks
Minimum number of disks: 4, 4+
##Mixed type
RAID-10:
Read and write performance improvement
Available space: N*min(S1,S2,...)/2
Fault tolerance: each set of mirrors can only have one bad disk at most;
Minimum number of disks: 4, 4+
RAID-01:
RAID-50, RAID7
JBOD: Just a Bunch Of Disks
Function: Combine the space of multiple disks into one large continuous space;
Available space: sum(S1,S2,... )
Common levels: RAID-0, RAID-1, RAID-5, RAID-10, RAID-50, JBOD
Implementation method:
Hardware implementation method
Software implementation method
Implementation of software RAID on CentOS 6:
Combined with md (multi devices) in the kernel
mdadm: modal tool
Command syntax format: mdadm [mode] [options]
Supported RAID levels: LINEAR, RAID0, RAID1, RAID4, RAID5, RAID6, RAID10;
Mode :
Create: -C
Assembly: -A
Monitor: -F
Management: -f, -r, -a
##: /dev/md
#: Any block device
##-C: Creation mode
-n #: Use # block devices to create this RAID;
-l #: Specify the level of RAID to be created;
-a {yes|no}: Automatically create the device file of the target RAID device;
-c CHUNK_SIZE: Specify the block size;
-x #: Specify the number of free disks;
For example: create a RAID5 with 10G available space;
-D: Display detailed information about the raid;
mdadm -D /dev/md
#Management mode:
-f: Mark the specified disk as damaged;
-a : Add disk
-r: Remove disk
##Observe the status of md:
cat /proc/mdstat
Stop md device:
mdadm -S /dev /md
#watch command:
-n #: Refresh interval, unit is seconds;
watch -n# 'COMMAND'
##LVM2:
LVM: Logical Volume Manager, Version: 2
dm: device mapper, convert one or more underlying block devices Modules organized into a logical device;
/dev/dm-
/dev/mapper/VG_NAME -LV_NAME
/dev/mapper/vol0-root
##/dev/VG_NAME/LV_NAME
/dev/vol0/root
pv management tool:
pvs: brief pv information display
pvdisplay: Display detailed information of pv
##pvcreate /dev/DEVICE: Create pv
vg management tool:
vgs
vgdisplay
vgcreate [-s #[kKmMgGtTpPeE]] VolumeGroupName PhysicalDevicePath [PhysicalDevicePath...]
vgextend VolumeGroupName PhysicalDevicePath [PhysicalDevicePath...]
vgreduce VolumeGroupName PhysicalDevicePath [PhysicalDevicePath...]
Do pvmove first
vgremove
##lv management tool:
##lvs
##lvdisplay
lvcreate -L #[mMgGtT] -n NAME VolumeGroup
##lvremove /dev /VG_NAME/LV_NAME
Extend logical volume:
lvextend -L [+]#[mMgGtT] / dev/VG_NAME/LV_NAME
resize2fs /dev/VG_NAME/LV_NAME
Resize logical volume:
# umount /dev/VG_NAME/LV_NAME
e2fsck -f /dev/VG_NAME/LV_NAME
# resize2fs /dev/VG_NAME/LV_NAME #[mMgGtT]
# lvreduce -L [-]#[mMgGtT] /dev/VG_NAME/LV_NAME
# mount
Snapshot: snapshot
##lvcreate -L #[mMgGtT] -p r -s -n snapshot_lv_name original_lv_name
File system mounting usage:
Mounting optical disk device:
CD device file:
IDE: /dev/hdc
SATA: /dev/sr0
Symbolic link file:
/dev/cdrom
/dev/cdrw
/dev/dvd
/dev/dvdrw
##mount -r /dev/cdrom /media/cdrom
##umount /dev/cdrom
dd command: convert and copy a file
Usage:
dd if=/PATH/FROM /SRC of=/PATH/TO/DEST
bs=#: block size, copy unit size;
count=#: copy How many bs;
Disk copy:
##dd if=/dev/sda of=/dev/sdb
Backup MBR
dd if=/dev/sda of=/tmp/mbr.bak bs=512 count=1
Destroy the bootloader in the MBR:
dd if=/dev/zero of=/dev /sda bs=256 count=1
Two special devices:
/dev/null: Data black hole ;
/dev/zero:zero machine;
##btrfs file system:
Technical Preview
##Btrfs (B-tree, Butter FS, Better FS ), GPL, Oracle, 2007, CoW;
ext3/ext4, xfs
Core features:
Multiple physical volume support: btrfs can be composed of multiple underlying physical volumes; supports RAID, with online "add", "remove", and "modify";
Copy-on-write update mechanism (CoW): copy, update and replace pointers instead of "in-place" updates;
Data and metadata check code: checksum
Subvolume: sub_volume
Snapshot: Snapshot that supports snapshot;
Transparent compression:
File system creation:
mkfs.btrfs
-L 'LABEL'
-d : raid0, raid1, raid5, raid6, raid10, single
-m
-O
-O list-all : List all supported features;
Property view:
btrfs filesystem show
Mount file system:
mount -t btrfs /dev/sdb MOUNT_POINT
##Transparent compression mechanism:
mount -o compress={lzo|zlib} DEVICE MOUNT_POINT
Subcommands: filesystem, device, balance, subvolume
Compression, decompression and archiving tools
compress/uncompress: .Z
gzip/gunzip: .gz
bzip2/bunzip2: .bz2
xz/unxz: .xz
zip/unzip
tar, cpio
1.gzip/gunzip
##gzip [OPTION]... FILE ...
-d: Decompress, equivalent to gunzip
-c: Output the result to standard output;
-#: 1-9, specify the compression ratio;
zcat: View the text file content without explicit expansion;
2、bzip2/bunzip2/bzcat
##bzip2 [OPTION]... FILE ...
-k: keep, keep the original file;
-d: decompress
-#: 1-9, compression ratio, default is 6;
bzcat: Without explicit expansion View the content of the text file;
##3、xz/unxz/xzcat
##bzip2 [ OPTION]... FILE ...
-k: keep, keep the original file;
-d: decompress
-#: 1-9, compression ratio, default is 6;
xzcat: Without explicit expansion View the content of the text file;
4、tar
tar [OPTION].. .
(1) Create archive
tar -c -f /PATH/TO/SOMEFILE.tar FILE ...
##tar -cf /PATH/TO/SOMEFILE.tar FILE...
(2) View the file list in the archive
tar -t -f /PATH/TO/SOMEFILE.tar
(3) Expand the archive
tar -x -f /PATH/TO/SOMEFILE.tar
tar -x -f /PATH/TO/SOMEFILE.tar -C /PATH/TO/DIR
Combined with compression tools to achieve: archiving And compress
##-j: bzip2, -z: gzip, -J: xz
bash scripting:
##if statement, bash -n, bash -x
CONDITION:
bash command:
Use the execution status result of the command;
Success : true
Failure: flase
The meaning of success or failure: depends on the command used;
Single branch:
if CONDITION; then
if-true
fi
Double branch:
if CONDITION; then
if-true
else
if-false
fi
Multiple branches:
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
...
esle
all-false
fi
Make judgments condition by condition, No. When a "true" condition is encountered, its branch is executed and then ends;
Example: The user enters the file path and the script determines the file type;
#!/bin/bash
read -p "Enter a file path: " filename
if [ -z "$filename" ]; then
## echo "Usage: Enter a file path."
exit 2
fi
if [ ! -e $filename ]; then
echo "No such file."
## exit 3
fi
if [ -f $filename ]; then
echo "A common file."
elif [ -d $filename ]; then
echo "A directory."
elif [ -L $filename ]; then
echo "A symbolic file."
else
echo "Other type."
fi
## Note: if statements can be nested;
Loop: for, while, until
Loop body: to be executed Code; may be executed n times;
Entry condition:
Exit condition:
for loop:
##for variable name in list; do
Loop body
done
Execution mechanism:
Assign the elements in the list to the "variable name" in sequence "; The loop body is executed once after each assignment; until the elements in the list are exhausted, the loop ends;
Example: Add 10 users, user1- user10; password is the same as username;
#!/bin/bash
if [ ! $UID -eq 0 ]; then
echo "Only root."
exit 1
fi
##for i in {1..10}; do
if id user$i &> /dev/null; then
echo "user$i exists."
else
useradd user$i
if [ $? -eq 0 ]; then
echo "user$i" | passwd --stdin user$i &> /dev/null
## echo "Add user$i finished ."
##                                                                                                                                                                 
List generation method:
(1) Directly give the list;
(2) Integer list :
(a) {start..end}
(b) $(seq [start [step]] end)
(3) Command to return the list;
$(COMMAND)
(4) glob
(b) Variable reference;
$@, $*
##Example: Determine the types of all files under a certain path
#!/bin/bash
#for file in $(ls /var); do
if [ -f /var/$file ]; then
echo "Common file."
elif [ -L /var/$file ]; then
echo "Symbolic file."
elif [ -d /var/$file ]; then
##echo "Directory."
else
echo "Other type."
fi
done
##Example:
#!/bin/bash
declare -i estab=0
declare -i listen=0
declare -i other=0
for state in $( netstat -tan | grep "^tcp\>" | awk '{print $NF}'); do
if [ "$state" == ' ESTABLISHED' ]; then
let estab++
elif [ "$state" == 'LISTEN' ]; then
let listen++
## else
##let other++
fi
done
echo "ESTABLISHED: $estab"
echo "LISTEN: $listen"
echo "Unkown: $other"
/ There are multiple files starting with K and S in the etc/rc.d/rc3.d directory;
Read each file separately, and output the file starting with K Add stop to the file. The output of the file starting with S is the file name plus start;
"K34filename stop"
"S66filename start"
##Linux Package Management:
API:Application Programming Interface
POSIX:Portable OS
Program source code --> Preprocessing --> Compile --> Assembly --> Link
Static compilation:
Shared compilation: .so
ABI: Application Binary Interface
Incompatible between Windows and Linux
Library Level of virtualization:
Linux: WINE
Windows: Cywin
System-level development
C
C++
Application-level development
java
Python
php
perl
ruby
Components of a binary application:
Binary files , library files, configuration files, help files
Package manager:
debian: deb, dpt
redhat: rpm, rpm
rpm: Redhat Package Manager
RPM is Package Manager
Gentoo
##Archlinux
##Source code: name-VERSION.tar.gz
VERSION: major.minor.release
rpm package naming method:
name-VERSION-release.arch.rpm
VERSION: major.minor.release
release.arch:
release:release.OS
zlib- 1.2.7-13.el7.i686.rpm
Common arch:
x86: i386, i486 , i586, i686
##x86_64: x64, x86_64, amd64
powerpc: ppc
Platform independent: noarch
testapp: Unpacking
testapp-VERSION-ARCH.rpm: Main package
testapp-devel -VERSION-ARCH.rpm: Branch package
testapp-testing-VERSION-ARHC.rpm
package Between: There are dependencies
X, Y, Z
##yum: the front-end tool of the rpm package manager;
apt-get: deb package manager front-end tool;
zypper: rpm front-end management tool on suse;
dnf: Fedora 22+ rpm package manager front-end management tool;
View the library files that binary programs depend on:
ldd /PATH/TO/BINARY_FILE
Manage and view library files loaded on this machine:
ldconfig
/sbin/ldconfig -p: Displays all available library file names and file path mappings that have been cached on this machine;
The configuration files are: /etc/ld.so.conf, /etc/ld.so.conf.d/*.conf
## Cache file: /etc/ld.so.cache
Package management:
Function: Compile Each component file of the application program is packaged into one or several package files, so as to conveniently and quickly implement management operations such as installation, uninstallation, query, upgrade and verification of the program package;
1. List of program components (unique to each package)
File list
When installing or uninstalling Running script
2, database (public)
Package name and version
Dependencies;
Function description;
The file path and verification code information of each file generated by the installation;
How to manage packages:
Use package manager: rpm
Use front-end Tools: yum, dnf
Ways to obtain the program package:
(1) System release CD or Official server;
CentOS mirror:
##(2) Project official website
(3) Third-party organization:
Fedora-EPEL
Search engine:
##(4) Make your own
Suggestions : Check its legality
Source legitimacy;
Integrity of the package;
rpm command management package on CentOS system:
Installation, uninstallation, upgrade, query, verification, database maintenance
Installation:
##rpm {-i|--install} [install-options] PACKAGE_FILE ...
-v: verbose
-vv:
-h: Display the package management execution progress with #; each # represents 2% progress
##rpm -ivh PACKAGE_FILE ...
##[install- options]
--test: test the installation, but do not actually execute the installation process; dry run mode;
--nodeps: ignore dependencies Relationship;
--replacepkgs: Reinstall;
--nosignature: Do not check the source legitimacy;
--nodigest: Do not check package integrity;
##--noscipts: Do not execute package script fragments;
%pre: Pre-installation script; --nopre
%post: Post-installation script; --nopost
%preun: pre-uninstall script; --nopreun
%postun: post-uninstall script; --nopostun
Upgrade:
rpm {-U|--upgrade} [install-options] PACKAGE_FILE ...
rpm { -F|--freshen} [install-options] PACKAGE_FILE ...
upgrage: "Upgrade" if an older version of the package is installed; if it does not exist If the old version package is installed, then "install";
freeshen: If the old version package is installed, then "upgrade"; if the old version package does not exist, the upgrade operation will not be performed;
rpm -Uvh PACKAGE_FILE ...
rpm -Fvh PACKAGE_FILE ...
--oldpackage: downgrade;
--force: forced upgrade;
Note: (1) Do not upgrade the kernel; Linux supports the coexistence of multiple kernel versions, therefore, install the new version of the kernel directly;
(2) If the original package The configuration file has been modified after installation. When the level is long, the same configuration file provided by the new version will not directly overwrite the old version of the configuration file, but the new version of the file will be renamed (FILENAME.rpmnew) and retained;
Query:
rpm {-q|--query} [select-options] [query-options]
[select-options]
-a: All packages
-f: View which package the specified file was generated by
-p /PATH/TO/PACKAGE_FILE: Query for package files that have not yet been installed Operation;
--whatprovides CAPABILITY: Query which package the specified CAPABILITY is provided by;
--whatrequires CAPABILITY: Query which package the specified CAPABILITY depends on;
[query-options]
--changelog : Query the changelog of the rpm package
-c: Query the configuration file of the program
-d: Query the documentation of the program
-i: information
-l: View all files generated after the specified package is installed;
--scripts: script fragments that come with the package
-R: Query the CAPABILITY that the specified package depends on;
-- provides: Lists the CAPABILITY provided by the specified package;
Usage:
-qi PACKAGE, -qf FILE, -qc PACKAGE, -ql PACKAGE, -qd PACKAGE
-qpi PACKAGE_FILE, -qpl PACKAGE_FILE, ...
-qa
Uninstall:
rpm {-e|--erase} [--allmatches] [--nodeps ] [--noscripts]
[--notriggers] [--test] PACKAGE_NAME ...
## Verification:
rpm {-V|--verify} [select-options] [verify-options]
## S file Size differs
M Mode differs (includes permissions and file type)
5 digest (formerly MD5 sum) differs
D Device major/minor number mismatch
L readLink(2) path mismatch
U User ownership differs
G Group ownership differs
T mTime differs
P caPabilities differ
Package source legality verification Authenticity and integrity verification:
Integrity verification: SHA256
Source legality verification: RSA
Public key encryption:
Symmetric encryption: Use the same key for encryption and decryption;
Asymmetric encryption: the key is in pairs,
public key: public key, open to everyone
secret key: private key, cannot be made public
Import the required public key:
rpm --import /PATH/FROM/GPG-PUBKEY-FILE
The key file provided by the CentOS 7 distribution disc: RPM-GPG-KEY -CentOS-7
Database rebuild:
##rpm {--initdb|--rebuilddb}
initdb: Initialization
If the database does not exist beforehand, create a new one; otherwise, do not perform any operation;
rebuilddb: Rebuild
Re-create the database directly regardless of whether it currently exists or not;
Review: Linux Implementation of package management, rpm package manager
rpm command to implement program management:
Installation:-ivh , --nodeps, --replacepkgs
Uninstall: -e, --nodeps
Upgrade: -Uvh, -Fvh, -- nodeps, --oldpackage
Query: -q, -qa, -qf, -qi, -qd, -qc, -q --scripts, -q --changlog, - q --provides, -q --requires
Verification: -V
Import GPG key: --import, -K, --nodigest, --nosignature
Database reconstruction: --initdb, --rebuilddb
Linux program Package management (2)
CentOS: yum, dnf
##URL: ftp: //172.16.0.1/pub/
##YUM: yellow dog, Yellowdog Update Modifier
yum repository: yum repo
stores many rpm packages and related metadata files of the packages (placed in a specific directory: repodata);
File server:
ftp://
http: //
nfs://
file:///
yum client:
Configuration file:
/etc/yum.conf: Provides public configuration for all warehouses
/etc/yum.repos.d/*.repo: Provide configuration for the warehouse pointing
Definition of the warehouse pointing :
[repositoryID]
name=Some name for this repository
baseurl=url ://path/to/repository/
##enabled={1|0}
gpgcheck={1|0}
gpgkey=URL
enablegroups={1|0}
##failovermethod={roundrobin|priority}
The default is: roundrobin, which means random selection;
cost=
The default is: 1000
yum source in the classroom: http://172.16.0.1/cobbler/ks_mirror/CentOS-6.6-x86_64/
CentOS 6.6 X84_64 epel: http://172.16.0.1/fedora-epel/6/x86_64/
Usage of yum command:
yum [options] [command] [package ...]
       command is one of:
        * install package1 [package2] [...]
        * update [package1] [package2] [...]
        * update-to [package1] [package2] [...]
        * check-update
        * upgrade [package1] [package2] [...]
        * upgrade-to [package1] [package2] [...]
        * distribution-synchronization [package1] [package2] [...]
        * remove | erase package1 [package2] [...]
        * list [...]
        * info [...]
        * provides | whatprovides feature1 [feature2] [...]
        * clean [ packages | metadata | expire-cache | rpmdb | plugins | all ]
        * makecache
        * groupinstall group1 [group2] [...]
        * groupupdate group1 [group2] [...]
        * grouplist [hidden] [groupwildcard] [...]
        * groupremove group1 [group2] [...]
        * groupinfo group1 [...]
        * search string1 [string2] [...]
        * shell [filename]
        * resolvedep dep1 [dep2] [...]
        * localinstall rpmfile1 [rpmfile2] [...]
           (maintained for legacy reasons only - use install)
        * localupdate rpmfile1 [rpmfile2] [...]
           (maintained for legacy reasons only - use update)
        * reinstall package1 [package2] [...]
        * downgrade package1 [package2] [...]
        * deplist package1 [package2] [...]
        * repolist [all|enabled|disabled]
        * version [ all | installed | available | group-* | nogroups* | grouplist | groupinfo ]
        * history [info|list|packages-list|packages-info|summary|addon-info|redo|undo|rollback|new|sync|stats]
        * check
        * help [command]
    显示仓库列表:
    repolist [all|enabled|disabled]
    显示程序包:
    list
    # yum list [all | glob_exp1] [glob_exp2] [...]
    # yum list {available|installed|updates} [glob_exp1] [...]
    安装程序包:
    install package1 [package2] [...]
    reinstall package1 [package2] [...]  (重新安装)
    升级程序包:
    update [package1] [package2] [...]
    downgrade package1 [package2] [...] (降级)
    检查可用升级:
    check-update
    卸载程序包:
    remove | erase package1 [package2] [...]
    查看程序包information:
    info [...]
    查看指定的特性(可以是某文件)是由哪个程序包所提供:
    provides | whatprovides feature1 [feature2] [...]
    清理本地缓存:
    clean [ packages | metadata | expire-cache | rpmdb | plugins | all ]
    构建缓存:
    makecache
    搜索:
    search string1 [string2] [...]
    以指定的关键字搜索程序包名及summary信息;
View the capabilities that the specified package depends on:
deplist package1 [package2] [...]
View yum transaction history:
history [info|list|packages-list|packages-info|summary|addon-info|redo|undo|rollback|new|sync|stats]
Install and upgrade local packages:
* localinstall rpmfile1 [rpmfile2] [...]
(maintained for legacy reasons only - use install)
* localupdate rpmfile1 [rpmfile2] [...]
(maintained for legacy reasons only - use update)
Package group management Related commands:
* groupinstall group1 [group2] [...]
* groupupdate group1 [group2] [...]
* grouplist [hidden] [ groupwildcard] [...]
* groupremove group1 [group2] [...]
* groupinfo group1 [...]
How to use the CD as a local yum repository:
(1) Mount the CD to a directory, such as /media/cdrom
# mount -r -t iso9660 /dev/cdrom /media/cdrom
(2) Create configuration file
[CentOS7]
name=
baseurl=
gpgcheck=
enabled=
## yum command line options:
--nogpgcheck: disable gpg check;
-y: The automatic answer is "yes";
-q: Silent mode;
--disablerepo=repoidglob: temporary Disable the repo specified here;
--enablerepo=repoidglob: Temporarily enable the repo specified here;
--noplugins: Disable All plug-ins;
Variables available in yum's repo configuration file:
$releasever: The major version number of the current OS release;
$arch: Platform;
$basearch: Basic platform;
$YUM0- $YUM9
$releasever/$basearch/os
Create yum warehouse:
createrepo [options]
Package compilation and installation:
testapp-VERSION-release.src. rpm --> After installation, use the rpmbuild command to create an rpm package in binary format, and then install it;
Source code --> Preprocessing- -> Compile (gcc) --> Assemble --> Link --> Execute
Source code organization format:
Multiple files: There may be cross-file dependencies between the codes in the file;
C, C++: make (configure --> Makefile.in --> makefile)
java: maven
##C code compilation and installation three steps:
./configure:
(1) Pass parameters through options, specify enabled features, installation Path, etc.; when executing, the makefile will be generated with reference to the user's specification and the Makefile.in file;
(2) Check the external environment it depends on;
make:
Build the application based on the makefile;
make install
Development tools:
autoconf: Generate configure script
automake: Generate Makefile.in
Recommendation: Check INSTALL and README before installation
Obtain the source code of the open source program:
Official self-built site:
apache.org (ASF)
mariadb.org
...
Code hosting:
SourceForge
Github.com
code.google.com
c/c++: gcc (GNU C Complier)
Compile C source code:
Premise: Provide development tools and development environment
Development tools: make, gcc, etc.
Development environment: development library , header file
glibc: Standard library
Provide development components through "package group"
CentOS 6: "Development Tools", "Server Platform Development",
Step one: configure script
Options: Specify the installation location, specify the enabled features
--help: Get the supported options
Option classification:
Installation path setting:
--prefix=/PATH/TO/SOMEWHERE: Specify the default installation location; the default is /usr/local/
--sysconfdir=/PATH/TO/SOMEWHERE: Configuration file installation location;
System types:
Optional Features: Optional Features
--disable -FEATURE
--enable-FEATURE[=ARG]
Optional Packages: Optional package
--with-PACKAGE[=ARG]
--without-PACKAGE
Step two: make
Step three: make install
Configuration after installation:
(1) Export the binary program directory to the PATH environment variable;
Edit the file /etc/profile.d /NAME.sh
export PATH=/PATH/TO/BIN:$PATH
(2) Export Library file path
Edit /etc/ld.so.conf.d/NAME.conf
Add the directory where the new library file is located to this point file;
Let the system regenerate the cache:
ldconfig [-v]
(3) Export header file
Implemented based on link:
ln - sv
(4) Export help manual
Edit/etc/man.config file
Add a MANPATH
Linux network attribute management
LAN: Ethernet, token Ring Network
Ethernet: CSMA/CD
Conflict Domain
Broadcast Domain
MAC:Media Access Control
48bits:
24bits:
24bits:
##IP: Internet Protocol
Routing protocol
Routed protocol
OSI, TCP/IP
tcp/ip layering:
application layer
transport layer
internet layer
datalink layer
pysical layer
Transport layer protocol :
tcp, udp, sctp
##Network layer protocol:
ip
##ip protocol:
IPv4 address classification:
Dotted decimal: 0-255
0000 0000 - 1111 1111
## 0.0.0.0-255.255.255.255
Class A:
0 000 0000 - 0 111 1111: 1- 127
Number of networks: 126, 127
Number of hosts in each network: 2^24-2
Default subnet mask: 255.0.0.0
Private address: 10.0.0.0/8
##Category B:
10 00 0000 - 10 11 1111: 128-191
Number of networks: 2^14
Number of hosts in each network: 2^16-2
Default subnet mask: 255.255.0.0
Private network address: 172.16.0.0/16-172.31.0.0/16
Category C:
110 0 0000 - 110 1 1111: 192-223
Number of networks: 2^21
In each network Number of hosts: 2^8-2
Default subnet mask: 255.255.255.0
Private network address: 192.168.0.0/24 -192.168.255.0/24
Class D: Multicast
1110 0000 - 1110 1111: 224-239
Class E:
240-255
Subnet mask:
172.16.100.100/255.255.0.0, 172.17.1.1
Cross-network communication: routing
Host routing
Network routing
Default routing
Connect the Linux host to the network:
IP/mask
Routing: Default Gateway
DNS Server
Primary DNS Server
Secondary DNS Server
Third DNS server
Configuration method:
Static specification :
ifcfg: ifconfig, route, netstat
ip: object {link, addr, route}, ss, tc
Configuration file
system-config-network-tui (setup)
CentOS 7:
nmcli, nmtui
Dynamic allocation:
DHCP: Dynamic Host Configuration Protocol
Configure network interface:
Interface naming method:
CentOS 6:
Ethernet: eth[0,1,2,...]
ppp: ppp[0,1,2,...]
ifconfig command
ifconfig [interface]
# ifconfig -a
# ifconfig IFACE [up|down]
ifconfig interface [aftype] options | address ...
# ifconfig IFACE IP/mask [up]
# ifconfig IFACE IP netmask MASK
Note: Effective immediately;
Enable promiscuous mode: [-]promisc
##route command
Route management command
View: route -n
Add: route add
route add [-net|-host] target [netmask Nm] [gw Gw] [[dev] If]
Target: 192.168.1.3 Gateway: 172.16.0.1
~]# route add -host 192.168.1.3 gw 172.16.0.1 dev eth0
Destination: 192.168.0.0 Gateway: 172.16.0.1
~]# route add -net 192.168.0.0 netmask 255.255.255.0 gw 172.16.0.1 dev eth0
~]# route add -net 192.168.0.0/24 gw 172.16.0.1 dev eth0
Default route, Gateway: 172.16.0.1
~]# route add -net 0.0.0.0 netmask 0.0.0.0 gw 172.16.0.1
~]# route add default gw 172.16.0.1
Delete: route del
route del [-net|-host] target [gw Gw] [netmask Nm] [[dev] If]
Target: 192.168.1.3 Gateway: 172.16.0.1
~]# route del -host 192.168.1.3
Target: 192.168.0.0 Gateway: 172.16.0.1
~]# route del -net 192.168.0.0 netmask 255.255.255.0
DNS server specification
/etc/resolv.conf
         
nameserver DNS_SERVER_IP1
                                             
Correct solution: FQDN-->IP
# dig -t A FQDN
# host -t A FQDN
Reverse solution: IP-->FQDN
# dig -x IP
# host -t PTR IP
##FQDN: www.madu.com.
netstat command:
netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
   
Display network connections:
     
netstat [--tcp|-t] [--udp|-u] [--raw|-w] [--listening|-l] [--all|-a] [--numeric|-n] [- -extend|-e[--extend|-e]] [--program|-p]
-t: tcp protocol related
-u: UDP protocol related
-w: Raw socket related
-l: In listening state
-a: All status
-n: Display IP and port in numbers;
-e: Extended format
-p: Display related processes and PID
Common combinations:
-tan, -uan, -tnl, -unl
Display routing table:
netstat { --route|-r} [--numeric|-n]
-r: Display the kernel routing table
-n: Number Format
##Display interface statistics:
netstat {--interfaces|-I|-i} [iface ] [--all|-a] [--extend|-e] [--program|-p] [--numeric|-n]
# netstat -i
# netstat -I IFACE
Summary: ifcfg family command configuration
ifconfig/route/netstat
ifup/ifdown
Linux network configuration (2)
Configure Linux network properties: ip command
ip command:
ip - show / manipulate routing, devices, policy routing and tunnels
##ip [ OPTIONS ] OBJECT { COMMAND | help }
OBJECT := { link | addr | route }
##link OBJECT:
ip link - network device configuration
set
dev IFACE
Setable attributes:
up and down: Activate or disable the specified interface;
show
[dev IFACE]: Specify the interface
[up]: Only display the active interface
ip address - protocol address management
##ip addr { add | del } IFADDR dev STRING
[label LABEL]: Specify the network card alias when adding an address
[scope {global|link|host}]: Specify the role Domain
global: available globally;
link: only link available;
host: Available on this machine;
[broadcast ADDRESS]: Specify the broadcast address
##ip address show - look at protocol addresses
[dev DEVICE]
##[label PATTERN]
[primary and secondary]
ip address flush - flush protocol addresses
Use the same format as show
ip route - routing table management
ip route add
Add route: ip route add TARGET via GW dev IFACE src SOURCE_IP
##TARGET:
Host routing: IP
Network routing: NETWORK/ MASK
Add gateway: ip route add defalt via GW dev IFACE
ip route delete
Delete route: ip route del TARGET
##ip route show
ip route flush
[dev IFACE]
[via PREFIX]
ss command:
Format: ss [OPTION]... [FILTER]
Options:
-t: tcp protocol related
-u: udp protocol related
-w: bare sleeve Connector related
-x: Unix sock related
-l: Listen state connection
-a: All
-n: Number format
-p: Related programs and PID
-e: Extended information
-m: Memory usage
-o: Timer information
FILTER := [ state TCP-STATE ] [ EXPRESSION ]
##Common states of TCP:
tcp finite state machine:
LISTEN: Listening
ESTABLISHED: Established connection
FIN_WAIT_1
FIN_WAIT_2
SYN_SENT
SYN_RECV
CLOSED
##EXPRESSION:
dport =
sport =
Example: '( dport = :ssh or sport = :ssh )'
Commonly used combinations:
##-tan, -tanl, -tanlp, -uan
# #Linux network attribute configuration (3): Modify the configuration file
IP, MASK, GW, DNS related configuration files: /etc/sysconfig/network-scripts/ ifcfg-IFACE
Routing-related configuration files: /etc/sysconfig/network-scripts/route-IFACE
/etc/sysconfig/network-scripts/ifcfg-IFACE:
DEVICE: The device to which this configuration file applies;
HWADDR: The MAC address of the corresponding device;
BOOTPROTO: The address configuration protocol used when activating this device, commonly used dhcp, static, none, bootp;
NM_CONTROLLED: NM is the abbreviation of NetworkManager; whether this network card accepts NM control; CentOS6 recommends "no";
ONBOOT: whether to activate this device when the system boots;
TYPE: interface type; common Ethernet, Bridge;
UUID: unique identifier of the device;
IPADDR: Specify the IP address;
NETMASK: subnet mask;
GATEWAY: default gateway;
DNS1: the first one DNS server pointing;
DNS2: The second DNS server pointing;
USERCTL: Whether ordinary users can control it This device;
PEERDNS: If the value of BOOTPROTO is "dhcp", whether to allow the dns server pointing information assigned by the dhcp server to be directly overwritten into the /etc/resolv.conf file;
/etc/sysconfig/network-scripts/route-IFACE
Two styles:
(1) TARGET via GW
(2) Define a route every three lines
ADDRESS#=TARGET
##NETMASK#=mask
##GATEWAY#=GW
Configure multiple addresses for the network card:
ifconfig:
##ifconfig IFACE_ALIAS
ip
ip addr add
Configuration file:
##ifcfg-IFACE_ALIAS
DEVICE=IFACE_ALIAS
Note: Gateway alias cannot be booted using dhcp protocol;
Linux network attribute configuration tui (text user interface):
system-config-network-tui
You can also use setup to find it;
Note: Remember to restart the network service to take effect;
Configure the host name of the current host:
hostname [HOSTNAME]
/etc/sysconfig/network
HOSTNAME=
The network interface identifies and names the associated udev configuration file:
/etc/udev/rules.d/70-persistent-net.rules
##Uninstall the network card driver:
modprobe -r e1000
Load the network card driver:
modprobe e1000
##CentOS 7 network property configuration
Traditional naming : Ethernet eth[0,1,2,...], wlan[0,1,2,...]
Predictable function
udev supports several different naming schemes:
Firmware, Topology
(1) Network card naming mechanism
systemd naming method for network devices:
(a ) If the index information provided by Firmware or BIOS for the device integrated on the motherboard is available and predictable, the name is based on this index, such as eno1;
(b) If Firmware or BIOS is The index information provided by the PCI-E expansion slot is available and predictable, so it is named according to this index, such as ens1;
(c) If the physical location information of the hardware interface is available, Then name it based on this information, such as enp2s0;
(d) If the user explicitly starts it, you can also name it based on the MAC address, enx2387a1dc56;
(e) When none of the above are available, the traditional naming mechanism will be used;
Some of the above naming mechanisms require the participation of the biosdevname program;
(2) Name composition format
en: ethernet
##wl : wlan
##ww: ​​wwan
## Name type:
o: The device index number of the integrated device;
s: Index number of the expansion slot;
x: Naming based on MAC address;
ps: enp2s1
The naming process of the network card device:
Step one:
##udev, auxiliary tool program/lib/udev/rename_device, /usr/lib/udev/rules.d/60-net.rules
Step 2:
biosdevname will be based on /usr/lib/udev/rules.d/71-biosdevname.rules
The third step:
By detecting the network interface device, according to /usr/lib/udev/rules.d/ 75-net-description
ID_NET_NAME_ONBOARD, ID_NET_NAME_SLOT, ID_NET_NAME_PATH
##Return to the traditional naming method:
(1) Edit the /etc/default/grub configuration file
GRUB_CMDLINE_LINUX="net.ifnames=0 rhgb quiet"
(2) Generate its configuration file for grub2
grub2-mkconfig -o /etc/grub2.cfg
(3) Restart the system
Address configuration tool: nmcli
nmcli [ OPTIONS ] OBJECT { COMMAND | help }
##device - show and manage network interfaces
connection - start, stop, and manage network connections
How to modify properties such as IP address:
#nmcli connection modify IFACE [+|-]setting.property value
setting.property:
ipv4. addresses
ipv4.gateway
ipv4.dns1
ipv4.method
manual
Network interface configuration tui tool: nmtui
Host name configuration tool: hostnamectl
status
set-hostname
Reference:
Network client tools:
##lftp, ftp, lftpget, wget
# lftp [ -p port] [-u user[,password]] SERVER
Subcommand:
get
mget
ls
help
# lftpget URL
# ftp
# wget
wget [option]... [URL]...
-q: Silent mode
-c: Continued Transmission
-O: Save location
--limit-rates=: Specify transmission rate
Review: ip command, ss command; configuration file; CentOS 7
ifcfg, ip, netstat , ss
Configuration file:
/etc/sysconfig/network-scripts/
ifcfg-IFNAME
route-IFNAME
CentOS 7: nmcli, nmtui
Linux process And job management
Kernel functions: process management, file system, network functions, memory management, drivers, security functions
Process: A copy of the running program;
Existence life cycle
Linux kernel’s fixed format for storing process information: task struct
Linked list of task struct components for multiple tasks: task list
Process creation:
init
Father-child relationship
Process: They are all created by their parent process
fork(), clone()
Process priority:
0-139:
1-99: real-time priority;
100-139: static Priority;
The smaller the number, the higher the priority;
Nice value:
-20,19
##Big O
O(1), O( logn), O(n), O(n^2), O(2^n)
Process memory:
Page Frame: Page frame, used to store page data
Storage Page
MMU: Memory Management Unit
IPC: Inter Process Communication
On the same host:
signal
shm: shared memory
semerphor
On different hosts:
rpc: remote procecure call
socket:
Linux kernel: preemptive multitasking
Process type:
Daemon process: During the system boot process A process started in , a process that has nothing to do with the terminal;
Foreground process: a process that is related to the terminal and started through the terminal
Note: Also The process started in the foreground can be sent to the background to run in daemon mode;
Process status:
Running State: running
Ready state: ready
Sleep state:
Interruptible: interruptable
Uninterruptable: uninterruptable
Stopped state: suspended in memory, but will not be scheduled unless manually started; stopped
Zombie state: zombie
Process classification:
CPU- Bound
IO-Bound
##"Linux Kernel Design and Implementation", "In-depth Understanding of the Linux Kernel"
Tools for viewing and managing Linux processes: pstree, ps, pidof, pgrep, top, htop, glance, pmap, vmstat, dstat, kill, pkill, job, bg, fg, nohup
pstree command:
pstree - display a tree of processes
ps: process state
ps - report a snapshot of the current processes
The relevant information of each process in the Linux system is stored in each file in the /proc/PID directory;
ps [OPTION]...
Options: Support two styles
Common combination: aux
u: User-centered organization of process status information display
a: Terminal-related processes;
x: Process independent of terminal;
~]# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
VSZ: Virtual memory SiZe, virtual memory set
RSS: ReSident Size, resident memory set
STAT:Process status
R:running
S: interruptable sleeping
D: uninterruptable sleeping
##T: stopped
Z: zombie
+: Foreground process
l: Multi-threaded process
N: Low priority process
<: High priority process
s: session leader
Common combinations:- ef
-e: Display all processes
-f: Display full format program information
Commonly used combinations: -eFH
-F: Display process information in complete format
-H: Process Hierarchical format displays process-related information
Commonly used combinations: -eo, axo
-eo pid,tid,class ,rtprio,ni,pri,psr,pcpu,stat,comm
##axo stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,pcpu,comm
ni: nice value
pri: priority, priority
psr: processor, CPU
rtprio: real-time priority
pgrep, pkill:
pgrep [options] pattern
pkill [options] pattern
##-u uid: effective user
-U uid: real user
-t terminal: Process related to the specified terminal
-l: Display the process name
-a: Display the process name in full format
-P pid: Display its parent The process is the process list of the process specified here
pidof:
Get its PID according to the process name;
top:
There are many built-in commands:
Sort:
   
P: The occupied CPU percentage;
 
M: The occupied memory percentage;  
   
T: Cumulative CPU time occupied;
Header information display:
uptime information: l command
tasks and cpu information: t command
cpu respectively displays: 1 (number)
memory information: m command
Exit command: q
Modify refresh interval: s
Terminate the specified process: k
Options:
-d #: Specify the refresh time interval, the default is 3 seconds;
-b: In batch mode;
-n #: How many batches to display;
htop command:
Options:
-d #: Specify the delay time;
-u UserName: Only display the processes of the specified user;
-s COLOMN: Sort by specified field;
Command:
s: Track selection System call for a specified process;
l: Displays the list of files opened by the selected process;
a: Bind the selected process to a specified CPU core;
t: Display the process tree
Note: Fedora-EPEL Source
Review:
Linux Basics:
CPU: timeslice
Memory: Linear address space
I/O:
Time-sharing multiplexing
Process viewing tools: pstree, ps, pgrep, pidof, top, htop
Linux process viewing and management (2)
Linux process viewing and management tools: pstree, ps, pidof, pgrep , top, htop, glances, pmap, vmstat, dstat, kill, pkill, job, bg, fg, nohup
vmstat command:
vmstat [options] [delay [count]]
##procs:
r : The number of processes waiting to run;
b: The number of processes in uninterruptible sleep state; (length of the blocked queue);
memory:
swpd: The total amount of swap memory used;
free: The total amount of free physical memory;
buffer: The total amount of memory used for buffer;
cache: The total amount of memory used for cache;
swap:
si: The data rate of data entering the swap (kb/s)
so: The data rate of the data leaving the swap Data rate (kb/s)
io:
bi: The rate at which data is read from the block device to the system; (kb/s )
bo: The rate at which data is saved to the block device;
#system:
in : interrupts, interrupt rate;
cs: context switch, process switching rate;
cpu:
us
sy
id
wa
st
Options:
-s: Display memory statistics
pmap command:
pmap - report memory map of a process
pmap [options] pid [...]
-x: Display information in detailed format;
Another implementation:
# cat /proc/PID/maps
glances命令:
glances [-bdehmnrsvyz1] [-B bind] [-c server] [-C conffile] [-p port] [-P password] [--password] [-t refresh] [-f file] [-o output]
内建命令:
 a  Sort processes automatically     l  Show/hide logs
 c  Sort processes by CPU%           b  Bytes or bits for network I/O
 m  Sort processes by MEM%           w  Delete warning logs
 p  Sort processes by name           x  Delete warning and critical logs
 i  Sort processes by I/O rate       1  Global CPU or per-CPU stats
 d  Show/hide disk I/O stats         h  Show/hide this help screen
 f  Show/hide file system stats      t  View network I/O as combination
 n  Show/hide network stats          u  View cumulative network I/O
 s  Show/hide sensors stats          q  Quit (Esc and Ctrl-C also work)
 y  Show/hide hddtemp stats
常用选项:
-b: 以Byte为单位显示网卡数据速率;
-d: 关闭磁盘I/O模块;
-f /path/to/somefile: 设定输入文件位置;
-o {HTML|CSV}:输出格式;
-m: 禁用mount模块
-n: 禁用网络模块
-t #: 延迟时间间隔
-1:每个CPU的相关数据单独显示;
C/S模式下运行glances命令:
服务模式:
glances -s -B IPADDR
IPADDR: 指明监听于本机哪个地址
客户端模式:
glances -c IPADDR
IPADDR:要连入的服务器端地址
dstat命令:
dstat [-afv] [options..] [delay [count]]
-c: 显示cpu相关信息;
-C #,#,...,total
-d: 显示disk相关信息;
-D total,sda,sdb,...
-g:显示page相关统计数据;
-m: 显示memory相关统计数据;
-n: 显示network相关统计数据;
-p: 显示process相关统计数据;
-r: 显示io请求相关的统计数据;
-s: 显示swapped相关的统计数据;
--tcp
--udp
--unix
--raw
--socket 
--ipc
--top-cpu:显示最占用CPU的进程;
--top-io: 显示最占用io的进程;
--top-mem: 显示最占用内存的进程;
--top-lantency: 显示延迟最大的进程;
kill命令:
Send control signals to the process to achieve process management
Display available signals in the current system:
# kill -l
man 7 signal
##Commonly used signals:
1) SIGHUP: Let it reread the configuration file without closing the process;
2) SIGINT: Abort the running process; equivalent to Ctrl+c ;
9) SIGKILL: Kill the running process;
15) SIGTERM: Terminate the running process;
18) SIGCONT:
19) SIGSTOP:
##Method to specify the signal :
(1) Numeric identification of the signal; 1, 2, 9
(2) Complete name of the signal; SIGHUP
(3) The abbreviated name of the signal; HUP
##Send a signal to the process:
kill [-SIGNAL] PID...
Kill all processes under "name":
killall [-SIGNAL] Program
##Linux job control
##Foreground job: Started through the terminal, and will always occupy the terminal after startup;
Background job: can be started through the terminal, but it will run in the background after startup (release the terminal);
How to make the job run in the background?
(1) Running job
Ctrl+z
(2) Not yet Started job
# COMMAND &
##Although this type of job is sent to the background to run, it is still related to Terminal related; if you want to send it to the background, peel off the relationship with the terminal:
# nohup COMMAND &
View all jobs:
# jobs
##Job Control:
# fg [[%]JOB_NUM]: Bring the specified background job back to the foreground;
# bg [[%]JOB_NUM]: Let the job sent to the background continue to run in the background ;
# kill [%JOB_NUM]: Terminate the specified job;
Process priority adjustment:
Static priority: 100-139
The nice value when the process is started by default is 0 and the priority is 120;
nice command:
nice [OPTION] [COMMAND [ARG]...]
renice command:
renice [-n] priority pid...
View:
ps axo pid,comm,ni
Not covered Command: sar, tsar, iostat, iftop
##Linux task planning, periodic task execution
Execute a task at a certain time in the future: at, batch
Run a task periodically: cron
Email service:
smtp: simple mail transmission protocol, used to transmit emails;
pop3: Post Office Protocol
imap4: Internet Mail Access Protocol
##mailx - send and receive Internet mail
MUA:Mail User Agent
##mailx [-s 'SUBJECT'] username[@hostname]
Generation of email body:
(1) Give it directly, Ctrl+d;
(2) Input redirection;
(3) Through pipe;
echo -e " How are you?\nHow old are you?" | mail
mailx
at command:
at [option] TIME
TIME:
HH:MM [YYYY-mm-dd]
noon, midnight, teatime
tomorrow
now+#{minutes, hours, days, OR weeks}
##Common options:
-q QUEUE:
-l: Lists jobs waiting to be run in the specified queue; equivalent to atq
- d: Delete the specified job; equivalent to atrm
-c: View specific job tasks;
-f /path/from/somefile : Read the task from the specified file;
Note: The execution result of the job will be notified to the relevant users by email;
batch command:
Let the system choose its own free time to perform the tasks specified here;
Periodic task schedule: cron
Related packages:
cronie: main package, provides crond Daemon processes and related auxiliary tools;
cronie-anacron: a supplementary program for cronie; used to monitor the execution status of cronie tasks; if the tasks in cronie failed to run at the time point in the past If it runs normally, anacron will subsequently start this task;
crontabs: contains system maintenance tasks provided by CentOS;
Make sure the crond daemon is running:
CentOS 7:
##systemctl status crond
...running...
CentOS 6:
service crond status
Tasks scheduled to be executed periodically are submitted to crond, which implements point-to-point execution.
System cron task: system maintenance job
/etc/crontab
User cron task :
crontab command
system cron task
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
| | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | | |
* * * * * user-name command to be executed
For example: Run the echo command at 9:10 pm;
10 21 * * * gentoo /bin/echo "Howdy!"
Time representation:
(1) Specific value;
Values ​​within the valid value range at a given time point;
(2) *
All values ​​within the valid value range at a given time point;
means "every...";
(3 ) Discrete values:,
#,#,
#(4) Continuous values:-
#-#
(5) In the specified time range, define the step size:
/#: # is the step size
For example: echo command every 3 hours;
0 */3 * * * gentoo /bin/echo "howdy!"
User cron:
crontab command definition, each user has a dedicated cron task file: /var/spool/cron /USERNAME
crontab command:
##crontab [-u user] [-l | -r | -e ] [-i]
-l: List all tasks;
-e: Edit tasks;
-r: Remove all tasks;
-i: Used with -r to allow users to selectively remove specified tasks in interactive mode;
-u user: Only root can run, and manages cron tasks for the specified user;
# #Note: The running results will be notified to relevant users by email;
(1) COMMAND > /dev/null
(2) COMMAND &> /dev/null
##For cron tasks, % has a special purpose; if you want to use % in a command, you need to escape it; however, If you place % in single quotes, you don’t need to escape it;
Thinking:
(1) How to run a task in seconds?
* * * * * for min in 0 1 2; do echo "hi"; sleep 20; done
(2) How To run a task every 7 minutes?
sleep command:
sleep NUMBER[SUFFIX]...
SUFFIX:
s: seconds, default
m: Minutes
h: hour
d: day
Startup process of CentOS 5 and 6
Linux: kernel+rootfs
kernel: process management, memory management, network management, driver, file system, security functions
rootfs:
glibc
Library: function collection, function, calling interface
Process call: procedure
Function call: function
##Program
Kernel design school:
Single-kernel design: Linux
Integrate all functions into the same program;
Microkernel design: Windows, Solaris
Each function is implemented using a separate subsystem;
Linux kernel features:
Support modularization: .ko
Supports dynamic loading and unloading of modules ;
Components:
Core file:/boot/vmlinuz-VERSION-release
ramdisk:
CentOS 5: /boot/initrd-VERSION-release.img
CentOS 6: / boot/initramfs-VERSION-release.img
Module file:/lib/modules/VERSION-release
CentOS system startup process:
POST: power-on self-test;
ROM: CMOS
BIOS:Basic Input and Output System
##ROM+RAM
BOOT Sequence:
Search each boot device in order. The first device with a boot program is the device used for this startup;
bootloader: boot loader, program
windows: ntloader
Linux:
LILO :LInux LOader
GRUB: GRand Uniform Bootloader
GRUB 0.X: GRUB Legacy
GRUB 1.x: GRUB2
#Function: Provide a menu that allows the user to choose to start the system or a different kernel version; load the user-selected kernel Go to a specific space in the memory, decompress, expand, and transfer system control to the kernel;
MBR:
446: bootloader
64: fat
2: 55AA
GRUB:
bootloader: 1st stage
disk: 2nd stage
kernel:
Self-initialization:
Detect all identifiable hardware devices;
Load the hardware driver; (you may use ramdisk to load the driver)
Mount the root file system in read-only mode;
Run the first application in user space: /sbin/init
##Type of init program:
SysV: init, CentOS 5
Configuration file: /etc/inittab
Upstart: init , CentOS 6
Configuration files: /etc/inittab, /etc/init/*.conf
Systemd : systemd, CentOS 7
Configuration file: /usr/lib/systemd/system, /etc/systemd/system
ramdisk:
One of the features in the kernel: using buffering and caching to access files on the disk;
ramdisk --> ramfs
##CentOS 5: initrd, tool program: mkinitrd
CentOS 6: initramfs, tool program: mkinitrd, dracut
System initialization:
POST --> BootSequence (BIOS) --> Bootloader(MBR) --> kernel(ramdisk) --> rootfs(read-only) --> init
/sbin/init
##CentOS 5:
Run level: Set for application purposes such as system operation or maintenance;
0-6: 7 levels
0: Shutdown
1: Single user mode (root, no login required), single, maintenance mode;
2: Multi-user mode, the network function will be started, but NFS will not be started; maintenance mode;
3: Multi-user mode, normal mode; Text interface;
4: Reserved level; can be the same as level 3;
5: Multi-user mode, normal mode; graphical interface;
6: Restart
Default level:
3, 5
Switch level:
init
#View level:
runlevel
who -r
Configuration file:/etc/inittab
Each line defines an action and its corresponding process
id:runlevel:action:process
action:
wait: Switch to this level and run once;
respawn: If this process terminates, restart it;
initdefault: Set the default run level; process is omitted;
sysinit: Set the system initialization method. Generally, /etc/rc.d/rc.sysinit is specified here;
...
id:3:initdefault:
si::sysinit:/etc/rc.d/rc.sysinit
l0:0:wait:/etc/rc.d/rc 0
##l1:1:wait:/ etc/rc.d/rc 1
...
l6:6:wait:/etc/rc.d/rc 6
Explanation: rc 0 --> means reading /etc/rc.d/rc0.d/
K*: K##*: ##Running order; the smaller the number, the earlier it runs; the smaller the number, the service usually depends on other services;
S*: S##*: ##Running order; the smaller the number, the earlier it runs; the service with the smaller number is usually the service that is relied on;
for srv in /etc/rc.d/rc0.d/K*; do
$srv stop
done
for srv in /etc/rc.d/rc0.d/S*; do
$srv start
done
chkconfig command
View services at all levels Startup or shutdown settings:
chkconfig [--list] [name]
Add:
The SysV service script is placed in /etc/rc.d/init.d (/etc/init.d)
chkconfig --add name
#!/bin/bash
## chkconfig: LLLL nn nn
Delete:
chkconfig --del name
Modify the specified link type
chkconfig [--level levels] name
--level LLLL: Specify the level to be set; when omitted, it means 2345;
Note: Normal level, the last service S99local started is not linked to a service script in /etc/rc.d/init.d, but points to the /etc/rc.d/rc.local script; therefore, it is inconvenient or unnecessary to write it as a service The script is placed in the /etc/rc.d/init.d/ directory, and the command that you want to run automatically when the computer is turned on can be placed directly in the /etc/rc.d/rc.local file;
tty1:2345:respawn:/usr/sbin/mingetty tty1
tty2:2345:respawn:/usr/sbin/mingetty tty2
...
##tty6:2345:respawn:/usr/sbin/mingetty tty6
minggetty will call the login program
/etc/rc.d/rc.sysinit: system initialization script
(1) Set the host name;
(2) Set the welcome message;
(3) Activate udev and selinux;
(4) Mount the file system defined in the /etc/fstab file;
(5) Detect the root file system, And remount the root file system in read-write mode;
(6) Set the system clock;
(7) Activate the swap device;
(8) Set kernel parameters according to the /etc/sysctl.conf file;
(9) Activate lvm and software raid devices;
(10) Load additional device drivers;
(11) Cleanup operation;
Summary: /sbin/init --> (/etc/inittab) --> Set the default run level --> Run the system initial script and complete system initialization --> Close Corresponding to the services that need to be closed, you need to start the service to start it --> Set up the login terminal
##CentOS 6:
The init program is: upstart, and its configuration file:
##/etc/inittab, /etc/init/*.conf
Note: The /etc/init/*.conf file syntax follows the upstart configuration file syntax format;
CentOS 6 startup process:
POST --> Boot Sequence(BIOS) -- > Boot Loader (MBR) --> Kernel(ramdisk) --> rootfs --> switchroot --> /sbin/init -->(/etc/inittab, /etc/init/*. conf) --> Set the default run level --> System initialization script --> Close or start services at the corresponding level --> Start terminal
##GRUB( Boot Loader):
grub: GRand Unified Bootloader
##grub 0.x: grub legacy
grub 1.x: grub2
##grub legacy:
stage1: mbr
stage1_5: The sector after mbr allows the bootloader in stage1 to identify the file system on the partition where stage2 is located;
stage2: Disk partition (/boot/grub/)
Configuration file: /boot/grub/grub.conf <-- /etc/grub.conf
stage2 and kernel are usually placed in a basic disk partition;
Function:
(1) Provide menus and interactive interfaces
e: Edit mode, used to edit menus;
c : Command mode, interactive interface;
(2) Load the kernel or operating system selected by the user
Allow parameters to be passed to the kernel
This menu can be hidden
(3) Provides a protection mechanism for the menu
is the edit menu Authenticate
Authenticate for an enabled kernel or operating system
How to identify a device:
(hd#,#)
hd#: Disk number, represented by numbers; numbering starts from 0
#: Partition number, represented by numbers; numbering starts from 0
(hd0,0)
##grub’s command line interface
help: Get help list
help KEYWORD: Detailed help information
find (hd#,#)/PATH/TO/SOMEFILE:
root (hd#,#)
kernel /PATH/TO/KERNEL_FILE: Set the kernel file used for this startup; in addition, you can add many cmdline parameters supported by the kernel;
For example: init=/ path/to/init, selinux=0
initrd /PATH/TO/INITRAMFS_FILE: Set the ramdisk that provides additional files for the selected kernel;
boot: Boot the selected kernel;
Manually start the system through the grub command line interface:
grub> root (hd#,#)
grub> kernel /vmlinuz-VERSION-RELEASE ro root=/dev/DEVICE
grub> initrd /initramfs-VERSION-RELEASE.img
grub> boot
##Configuration file:/boot /grub/grub.conf
Configuration items:
default=#: Set the default startup menu item; single item (title) Numbering starts from 0;
timeout=#: Specify how long the menu item waits for option selection;
splashima=(hd#,#)/PATH/TO/XPM_PIC_FILE: Specify Menu background image file path;
hiddenmenu: hidden menu;
##password [--md5] STRING: menu editing authentication;
title TITLE: Define the menu item "title", which can appear multiple times;
root (hd#,#): grub searches for stage2 and kernel files The device partition where it is located; is the "root" of grub;
kernel /PATH/TO/VMLINUZ_FILE [PARAMETERS]: started kernel
initrd /PATH/TO/INITRAMFS_FILE: Kernel matching ramfs file;
password [--md5] STRING: Authentication when booting the selected kernel or operating system;
grub-md5-crypt command
Enter single-user mode:
(1) Edit the grub menu (select the title to be edited, and then use the e command);
(2) In the selected kernel It can be appended with
1, s, S or single;
(3) In the line where the kernel is located, type the "b" command;
Install grub:
(1) grub-install
grub-install --root-directory=ROOT /dev/DISK
##(2) grub
grub> root (hd#,#)
##grub> setup (hd#)
Linux Kernel:
Single-kernel system design, but fully draws on the advantages of the microkernel design system and introduces a modular mechanism to the kernel.
Kernel components:
kernel: Kernel core, usually bzIma, usually in the /boot directory, named vmlinuz-VERSION- RELEASE;
kernel object: Kernel object, generally placed in /lib/modules/VERSION-RELEASE/
[ ]: N
[M]: M
[*]: Y
Auxiliary file: ramdisk
initrd
initramfs
Running Kernel:
uname command:
##uname - print system information
uname [OPTION]...
-n: Display node name;
-r: Display VERSION-RELEASE;
Module:
lsmod command:
Display what has been done by the core The loaded kernel module
The displayed content comes from: /proc/modules file
modinfo command:
Display detailed description information of the module
##modinfo [ -k kernel ] [ modulename|filename ... ]
-n: Only display the module file path
-p: Display the module parameters
-a: author
-d: description
-l: license
modprobe command:
Load or unload the kernel module
modprobe [ -C config-file ] [ modulename ] [ module parame-ters... ]
Configuration file: /etc/modprobe.conf, /etc/modprobe.d/*.conf
modprobe [ -r ] modulename...
depmod command:
Tool for generating kernel module dependency files and system information mapping files;
Loading or unloading kernel modules:
insmod command:
insmod [ filename ] [ module options... ]
##rmmod
rmmod [ modulename ]
/proc directory:
Kernel Its own internal status information and statistical information, as well as configurable parameters are output through the proc pseudo file system;
Parameters:
Read-only: Output information
Writable: User-specified "new value" can be accepted to configure a certain function or feature of the kernel
/proc/sys
(1) The sysctl command is used to view or set many parameters in this directory;
sysctl -w path.to.parameter=VALUE
~]# sysctl -w kernel.hostname=mail.madu.com
(2) The echo command can also modify the values ​​of most parameters through redirection;
echo "VALUE" > ; /proc/sys/path/to/parameter
~]# echo "www.madu.com" > /proc/sys/kernel/hostname
sysctl command:
Default configuration file:/etc/sysctl.conf
(1) Set a certain parameter
sysctl -w parameter=VALUE
(2) Set by reading the configuration file Parameters
sysctl -p [/path/to/conf_file]
Route forwarding in the kernel:
/proc/sys/net/ipv4/ip_forward
Commonly used parameters:
net.ipv4.ip_forward
vm.drop_caches
kernel.hostname
/sys directory:
sysfs: Outputs the relevant attribute information of each hardware device recognized by the kernel, as well as the kernel’s setting information for hardware characteristics; Some parameters can be modified to adjust the hardware operating characteristics.
udev dynamically creates the required device files for each device through the information output under this path; udev is a user space program that runs; special tools: udevadmin, hotplug;
When udev creates a device file for a device, it will read its pre-defined rule files, usually in /etc/udev/rules.d and /usr /lib/udev/rules.d directory;
Production of ramdisk file:
(1) mkinitrd Command
Recreate the ramdisk file for the currently used kernel
~] # mkinitrd /boot/initramfs-$(uname -r) .img $(uname -r)
(2) dracut command
Restart the kernel for the currently used Make ramdisk file
~] # dracut /boot/initramfs-$(uname -r).img $(uname -r)
Compile kernel:
Prerequisite:
(1) Prepare the development environment;
( 2) Obtain relevant information about the hardware devices on the target host;
(3) Obtain relevant information about the target host system functions, such as the file system to be enabled;
(4) Obtain the kernel source code package;
www.kernel.org
Prepare the development environment:
Package Group (CentOS 6):
Server Platform Development
Development Tools
Target host hardware device related information:
CPU:
~]# cat /proc/cpuinfo
~]# x86info -a
~]# lscpu
##PCI device :
~]# lspci
-v
-vv
~]# lsusb
-v
-vv
~]# lsblk
Understand all hardware device information
~]# hal-device
##Simple production process based on the template file:
~]# tar xf linux-3.10.67.tar.xz -C /usr/src
~]# cd /usr/src
~] # ln -sv linux-3.10.67 linux
~]# cd linux
~]# cp /boot/config-$( uname -r) ./.config
##~]# make menuconfig
~]# screen
~]# make -j
#~]# make modules_install
~]# make install
Restart the system and test using the new kernel;
Linux kernel compilation (2 )
Steps to compile the kernel:
(1) Configure kernel options
Support "update" mode for configuration:
(a) make config: Configure each configurable option in the kernel in a traversal manner based on the command line;
(b) make menuconfig: a text window interface based on curses;
(c) make gconfig: a window interface based on GTK development environment;
(d) make xconfig: window interface based on Qt development environment;
## Supports "new configuration" mode for configuration:
(a) make defconfig: Configure based on the "default" configuration provided by the kernel for the target platform;
(b) make allnoconfig: Answer all options For "no";
(2) Compile
make [-j #]
How to compile only part of the functions in the kernel:
(a) Compile only the relevant code in a certain subdirectory:
# cd /usr/src/linux
# make dir/
(b) Only compile a specific module:
# cd /usr/src/linux
# make dir/file.ko
For example: Compile the driver only for e1000:
# make drivers/net/ethernet/intel/e1000/ e1000.ko
How to cross-compile the kernel:
The target platform for compilation is different from the current platform;
# make ARCH=arch_name
To obtain help for a specific target platform
make ARCH =arch_name help
How to recompile the kernel source tree that has been compiled:
Clean up beforehand Operation:
# make clean: clean most files generated by compilation, but will retain config files, etc.;
# make mrproper: clean All compiled files, config and some backup files;
# make distclean: mrproper, patches and editor backup files;
screen command:
Open a new screen:
screen
Exit and close screen:
# exit
Strip current screen:
Ctrl +a,d
Display all open screens:
screen -ls
Restore A certain screen
##screen -r [SESSION]
CentOS system installation
bootloader-->kernel(initramfs)-->rootfs-->/sbin/init
##anaconda: Installer
tui: text window based on curses;
gui: graphics window;
CentOS installation program startup process:
MBR: boot.cat
stage2: isolinux/isolinux.bin
Configuration file: isolinux/isolinux.cfg
##Each corresponding menu option:
Load the kernel: isolinuz/vmlinuz
Pass parameters to the kernel: append initrd=initrd.img ...
Mount the root file system and start anaconda
Start the GUI interface by default
If explicitly specified, use TUI Interface:
Just pass the "text" parameter to the kernel;
boot: linux text
Note: The above content should generally be located in the boot device; there are several ways to use subsequent anaconda and its installation packages:
Local CD
Local hard disk
ftp server: yum repository
http server: yum repostory
nfs server
If you want to manually specify the installation source:
boot: linux method
Working process of anaconda application:
Pre-installation configuration phase
Language used during the installation process
Keyboard type
Installation target storage device
Basic Storage: local disk
Special device: iSCSI
Set host name
Configure network interface
Time zone
Administrator password
Set partition mode and MBR installation location
Create a normal user
Select the program to be installed Package
Installation Phase
Create partitions on the target disk, perform formatting operations, etc.
Install the selected package to the target location
Install bootloader
First startup
iptables
selinux
core dump
anaconda configuration method:
(1) Interactive Configuration method;
(2) Automatically complete the configuration by reading the configuration file given in advance;
Configuration given according to specific syntax Options;
kickstart file;
##Installation boot options:
boot:
text: Text installation method
method: Manually specify the installation method to use
Network related boot options:
ip=IPADDR
##netmask=MASK
gateway=GW
dns=DNS_SERVER_IP
ifname=NAME:MAC_ADDR
with remote Access function-related boot options:
vnc
vncpassword='PASSWORD'
specify The location of the kickstart file
ks=
##DVD drive: ks=cdrom:/PATH/TO/KICKSTART_FILE
Hard drive: ks=hd:/device/drectory/KICKSTART_FILE
HTTP server: ks=http://host:port/path/to/KICKSTART_FILE
FTP server: ks=ftp://host:port/path/to/KICKSTART_FILE
HTTPS server: ks=https://host :port/path/to/KICKSTART_FILE
Start emergency rescue mode:
rescue
Official Document: "Installation Guide"
kickstart file format:
Command segment : Indicate various pre-installation configurations, such as keyboard type, etc.;
Package segment: Indicate the package group or package to be installed, the package not to be installed, etc.;
%packages
@group_name
package
-package
##%end
Script section:
%pre: Pre-installation script
Running environment: a mini-Linux environment running on the installation media
##%post: Post-installation script
Running environment: the installed system;
Commands in the command section:
Required command
authconfig: Authentication method configuration
authconfig --useshadow --passalgo=sha512
bootloader: bootloader installation location and related configuration
##bootloader --location=mbr --driveorder=sda --append="crashkernel =auto crashkernel=auto rhgb rhgb quiet quiet"
keyboard: Set keyboard type
lang: Language type
part: Create a partition
rootpw: Specify the root password
timezone: Time zone
Optional commands
install OR upgrade
text: Text installation interface
network
firewall
selinux
halt
poweroff
reboot
repo
##user: Create a new user for the system after the installation is complete
url: Specify the installation source
How to create the kickstart file:
(1) Direct manual editing;
Modify according to a template;
(2) You can use the creation tool: system-config-kickstart ( CentOS 6)
Modify and generate new configuration based on a template;
http://172.16.0.1/ centos6.x86_64.cfg
Check the ks file for syntax errors: ksvalidator
# ksvalidator /PATH/TO/ KICKSTART_FILE
Create a bootable disc:
# mkisofs -R -J -T -v --no-emul -boot --boot-load-size 4 --boot-info-table -V "CentOS 6.6 x86_64 boot" -b isolinux/isolinux.bin -c isolinux/boot.cat -o /root/boot.iso myiso/
Review: CentOS system installation
kickstart file:
command Section
Required: authconfig, bootloader, ...
Optional: firewall, selinux, reboot, ...
Package segment
%packages
##@group_name
package
-package
##%end
Script section
%pre
...
%end
%post
...
%end
Creation tool: system-config-kickstart
Syntax check: ksvalidator
How to install the process Get the kickstart file:
DVD: ks=cdrom:/PATH/TO/KS_FILE
HTTP: ks=http://HOST: PORT/PATH/TO/KS_FILE
SELinux:
##SELinux: Secure Enhanced Linux , working in the Linux kernel
DAC: Discretionary Access Control;
MAC: Mandatory Access Control;
SELinux has two working levels:
strict: Each process is controlled by selinux;
targeted: Only a limited number of processes are controlled by selinux;
Only monitor processes that are easily invaded;
sandbox:
subject operation object
subject: process
object: process, file,
File: open, read, write, close, chown, chmod
subject: domain
object: type
SELinux for each Security labels are provided for files and processes;
user:role:type
user: SELinux user;
role: role;
type: type;
## SELinux rule base:
Rules: Which domain can access which type or types of files;
## Configure SELinux:
Whether SELinux is enabled;
Relabel the file;
Set certain cloth characteristics ;
SELinux status:
enforcing: Enforcing, every restricted process must be restricted;
permissive: Enable, each restricted process violation operation will not be prohibited, but will be recorded in the audit log;
disabled : Close;
Related commands:
getenforce: Get the current status of selinux;
setenforce 0|1
0: Set to permissive
1: Set to enforcing
This setting: Invalid after restarting the system;
Configuration file: /etc/sysconfig/selinux, /etc /selinux/config
SELINUX={disabled|enforcing|permissive}
##Re-mark the file:
chcon
chcon [OPTION]... CONTEXT FILE...
chcon [ OPTION]... [-u USER] [-r ROLE] [-t TYPE] FILE...
chcon [OPTION]... --reference=RFILE FILE. ..
-R: Recursive marking;
Default label for restore files:
restorecon [-R] /path/to/somewhere
##Boolean Rules:
getsebool
##setsebool
##getsebool Command:
getsebool [-a] [boolean]
##setsebool command:
setsebool [ -P] boolean value | bool1=val1 bool2=val2 ...
bash script programming:
Programming language:
Data structure
Sequential execution
Select execution
Conditional test
Run command or [[ EXPRESSION ]]
Execution status return value;
if
##case
Loop Execute
to run a certain code segment multiple times;
How many times to run it repeatedly?
The number of cycles is known in advance:
The number of cycles is unknown in advance;
Must have entry conditions and exit conditions:
for, while, until
Function: structured programming and code reuse;
function
##for loop syntax:
for NAME in LIST; do
Loop body
done
List generation method:
(1) Integer list
{start..end}
$(seq start [[step]end])
(2) glob
/ etc/rc.d/rc3.d/K*
(3) Command
Detect through ping command Online status of all hosts within the range of 172.16.250.1-254;
#!/bin/bash
#
net='172.16.250'
uphosts=0
downhosts=0
for i in {1..20}; do
ping -c 1 -w 1 ${net}.$ {i} &> /dev/null
## if [ $? -eq 0 ]; then
echo "${net}. ${i} is up."
let uphosts++
## else
echo "$ {net}.${i} is down."
let downhosts++
fi
done
echo "Up hosts: $uphosts."
echo "Down hosts: $downhosts."
while loop:
while CONDITION; do
Loop body
done
##CONDITION: Loop control condition; Before entering the loop, make a judgment first; make a judgment again after each loop;
If the condition is "true", then execute a loop; until the condition test status is "false", terminate Loop;
Therefore: CONDTION should generally have a loop control variable; and the value of this variable will be continuously modified in the loop body;
Example: Find the sum of all positive integers within 100;
#!/bin/bash
#declare -i sum=0
declare -i i=1
while [ $i -le 100 ]; do
let sum+=$i
## let i++
done
echo "$i"
echo "Summary: $sum."
Add 10 users
user1-user10
#!/bin/bash
declare -i i=1
declare -i users=0
while [ $i -le 10 ]; do
if ! id user$i &> /dev/null; then
useradd user$i
echo "Add user: user$i."## let users++
fi
## let i++
done
echo "Add $users users."
Use the ping command to detect the online status of all hosts within the range of 172.16.250.1-254; (use while loop)
#!/bin/bash
#declare -i i=1
##declare - i uphosts=0
declare -i downhosts=0
net='172.16.250'
while [ $i -le 20 ]; do
if ping -c 1 -w 1 $net.$i &> /dev/null ; then
echo "$net.$i is up."
let uphosts++
else
echo "$net.$i is down."
let downhosts++
## fi
let i++
done
##echo "Up hosts: $uphosts. "
echo "Down hosts: $downhosts."
Print the multiplication table; (use for respectively and while loop implementation)
#!/bin/bash
for j in {1..9}; do
for i in $(seq 1 $j); do
echo -e -n "${i}X${j}=$[$i*$j]\t"
done
echo
done
##!/bin/bash
declare -i i=1
declare -i j=1
while [ $j -le 9 ]; do
while [ $i -le $j ]; do
echo -e -n "${i}X${j}=$[$i*$j]\t"
let i++
done
echo
## let i=1
let j++
done
## Use RANDOM to generate 10 random numbers and output This 10 number, and displays the largest and smallest among them;
#!/bin/bash
declare -i max=0
declare -i min=0
declare -i i=1
##while [ $i -le 9 ]; do
## rand=$RANDOM
echo $rand
## if [ $i -eq 1 ]; then
max=$rand
##min=$rand
fi
if [ $rand -gt $max ]; then
max=$rand
fi
if [ $rand -lt $min ]; then
min=$rand
fi
let i++
done
##echo "MAX : $max."
echo "MIN: $min."
##Review: selinux, while
selinux: Kernel, security enhancement;
Enable:
/etc/sysconfig/selinux, /etc/selinux/config
# setenforce
getenforce
Marking:
chcon [-t TYPE]
##-R
Boolean type:
getsebool [-a]
##setsebool [-P]
while loop:
while CONDITION; do
Loop body
done
sed:Editor
sed: Stream EDitor, line editor;
##Usage:
sed [option]... 'script' inputfile...
script:
'Address command'
Common options:
-n: Do not output the content in the mode to the screen;
-e: Multi-point editing;
-f /PATH/TO/SCRIPT_FILE: Read the editing script from the specified file;
-r: Supports the use of extended regular expressions;
-i: Edit in place;
Address delimitation:
(1) No address: process the full text;
(2) Single address:
#: The specified line;
/pattern/: Each line that can be matched by this pattern;
(3) Address range:
#,
##,+
#/pat1/,/pat2/
#,/pat1/
(4) ~:Step
1~2
2~2
Edit command:
d: Delete
p: Display the content in the pattern space
a \text : Append text after the line; support using \n to implement multi-line appending;
i \text: Insert text before the line; support using \n to implement multi-line insertion;
c \text: The replacement line is single or multi-line text;
w /path/to/somefile: Save the lines matched by the pattern space to the specified In the file;
r /path/from/somefile: Read the text stream of the specified file to the line after the matched line in the pattern space;
=: Print the line number for the line in the pattern space;
!: Negate the condition;
s/// : Support the use of other delimiters, s@@@, s;
replacement tag:
g: Inline global replacement;
p: Display the successfully replaced lines;
w /PATH/TO/SOMEFILE: Save the successful replacement results to the specified file ;
1: Delete the blank characters at the beginning of all lines starting with a blank in the /boot/grub/grub.conf file;
~]# sed 's@^[[:space:]]\+@@' /etc/grub2.cfg
2: Delete the # and blank characters at the beginning of all lines in the /etc/fstab file that begin with # and are followed by at least one blank character;
~]# sed 's@ ^#[[:space:]]\+@@' /etc/fstab
3: echo an absolute path to the sed command and extract its base name ;Get the directory name;
~]# echo "/etc/sysconfig/" | sed 's@[^/]\+/\?$@@'
Advanced editing commands:
h: Overwrite the content in the pattern space into the holding space;
H: Append the content in the pattern space to the holding space;
g: Take the data from the holding space and overwrite it into the pattern space;
G: Take out the content from the holding space and append it to the pattern space;
x: Exchange the content in the pattern space with the content in the holding space;
n: Read the next line of the matched line to the pattern space;
N: Append the next line of the matched line to the pattern space Space;
d: Delete lines in the pattern space;
D: Delete all lines in the multi-line pattern space;
sed -n 'n;p' FILE: Display even lines
sed '1!G;h;$!d' FILE: Display in reverse File content
sed '$!N;$!D' FILE: Take out the last two lines of the file;
sed '$!d' FILE: Take out the last line of the file;
sed 'G' FILE:
sed '/^$/d;G' FILE:
sed 'n;d' FILE: Display odd lines;
sed -n '1!G;h;$p' FILE: Display each line in the file in reverse;
bash script programming
##while CONDITION; do
Loop body
done
##Entry condition: CONDITION is true;
Exit condition: false
until CONDITION; do
Loop body
done
Entry condition: false
Exit condition: true
Example: Find the sum of all positive integers within 100;
#!/bin/bash
declare -i i=1
declare -i sum=0
until [ $i -gt 100 ]; do
let sum+=$i
let i++
done
##echo "Sum: $sum"
Example: Print the multiplication table
#!/bin/bash
#declare -i j=1
declare -i i=1
until [ $j -gt 9 ]; do
until [ $i -gt $j ]; do
echo -n -e "${i}X${j}=$[$i*$j]\t"
let i++
done
## echo
let i=1
let j++
done
Loop control statement (used in the loop body):
continue [N]: End the current cycle of layer N in advance and directly enter the next round of judgment;
while CONDTIITON1; do
CMD1
...
##if CONDITION2; then
continue
fi
CMDn
##...
done
break [N]: End the loop early;
while CONDTIITON1; do
CMD1
...
if CONDITION2; then
break
fi
CMDn
...
done
#Example 1: Find the sum of all even numbers within 100; it is required to loop through all positive integers within 100 ;
#!/bin/bash
declare -i i=0
declare -i sum=0
##until [ $i -gt 100 ]; do
let i++
## if [ $[$i%2] -eq 1 ]; then
continue
fi
let sum+=$i
done
echo "Even sum: $sum"
Create an infinite loop:
while true; do
Loop body
done
##until false; do
Loop body
done
Example 2 : Get information about logged-in users from the system every 3 seconds; if docker is logged in, it will be recorded in the log and exit;
#!/bin/bash
read -p "Enter a user name: " username
while true; do
if who | grep "^$username" &> /dev/null; then
##break
fi
sleep 3
done
echo "$username logged on." >> /tmp/user.log
Two implementations:
#!/bin/bash
read -p "Enter a user name: " username
##until who | grep "^$username" &> /dev/null; do
sleep 3
done
##echo "$username logged on." >> /tmp/user.log
Special usage of while loop (traverse each line of the file):
while read line; do
Loop body
##done < /PATH/FROM/SOMEFILE
Read each line in the /PATH/FROM/SOMEFILE file in turn, and assign the line value to the variable line:
Example: Find all users whose ID numbers are even numbers and display their user names and ID numbers;
#!/bin/bash
while read line;do
if [ $[`echo $line | cut -d: -f3` % 2] -eq 0 ];then
## echo -e -n "username: `echo $line | cut -d: -f1`\t"
## echo "uid: `echo $line | cut -d: -f3 `"
fi
##done < /etc/passwd
Special format of for loop: for ((Control variable initialization; conditional judgment Expression; modified expression of control variable)); do
Loop body
done
Control variable initialization: only executed once when running into the loop code segment;
Corrected expression of the control variable: Control will be performed first at the end of each cycle Variable correction operation, and then make conditional judgment;
Example: Find the sum of all positive integers within 100;
#!/bin/bash
declare -i sum=0
for ((i =1;i<=100;i++)); do
let sum+=$i
done
echo "Sum: $sum."
##Example 2: Print the multiplication table;
#!/bin/bash
for((j= 1;j<=9;j++));do
for((i=1;i<=j;i++))do
            echo -e -n "${i}X${j}=$[$i*$j]\t"
          done
echo
done
(1) Display a menu as follows:
cpu) show cpu information;
mem) show memory information;
disk) show disk information;
quit) quit
(2) Prompt the user to select options;
(3) Display the user Selected content;
#!/bin/bash
#cat << EOF
##cpu) show cpu information;
mem) show memory information;
disk) show disk information;
quit) quit
========== ==================
##EOF
read -p "Enter a option: " option
while [ "$option" != 'cpu' -a "$option" != 'mem' -a "$option" ! = 'disk' -a "$option" != 'quit' ]; do
read -p "Wrong option, Enter again: " option
done
if [ "$option" == 'cpu' ]; then
## lscpu
elif [ "$option" == 'mem' ]; then
cat /proc/meminfo
elif [ "$option" == 'disk' ]; then
fdisk -l
else
echo "Quit"
exit 0
fi
Further:
The user selects and does not exit the script after the display is completed; instead, it prompts the user to continue to select and display other content; it does not exit until quit is used;
Conditional judgment: case statement
case variable reference in
PAT1)
Branch 1
##;;
PAT2)
Branch 2
##;;
...
*)
Default branch
;;
esac
Example:
#!/bin/bash
#cat << EOF
cpu) show cpu information;
mem) show memory information;
disk) show disk information;
quit) quit
==============================
EOF
read -p "Enter a option: " option
while [ "$option" != ' cpu' -a "$option" != 'mem' -a "$option" != 'disk' -a "$option" != 'quit' ]; do
read -p "Wrong option, Enter again: " option
done
##case "$option" in
cpu)
lscpu
;;
mem)
cat /proc/meminfo
##;;
disk)
fdisk -l
;;
*)
echo "Quit..."
exit 0
;;
esac
##(1) The script accepts parameters: start, stop, restart, status;
(2) If the parameter is not one of the four, prompt to use the format and then exit with an error;
(3) If it is start: create /var/lock/subsys/SCRIPT_NAME, and displays "Start successfully";
Consider: What should be done if it has been started once before?
(4) If it is stop: delete /var/lock/subsys/SCRIPT_NAME, and display "stop completed";
Consider : What should I do if it has been stopped beforehand?
(5) If it is a restart, stop first, then start;
Consider: What to do if there is no start?
(6) If it is status, then
If the /var/lock/subsys/SCRIPT_NAME file exists, "SCRIPT_NAME is running" will be displayed. ...";
If the /var/lock/subsys/SCRIPT_NAME file does not exist, "SCRIPT_NAME is stopped..." will be displayed;
Where: SCRIPT_NAME is the current script name;
##Summary: until, while, for, case
bash script programming:
case statement:
case Variable reference in
PAT1)
Branch 1
;;
PAT2)
Branch 2
;;
##. ..
##*)
branchn
;;
esac
case supports glob-style wildcards:
*: any character of any length ;
##?: Any single character;
[]: Any single character within the specified range;
a|b: a or b
function: function
Procedural programming: code reuse
Modular programming
Structured programming
Grammar 1:
function f_name {
...function body...
}
Syntax 2:
f_name() {
...Function body...
}
Call: The function will only be executed when it is called;
Call: Given a function name
Where the function name appears, it will be automatically replaced by the function code;
Life cycle of the function: Created when called, terminated when returned;
return command returns a custom status result;
0: Success
1-255: Failed
!/bin/bash
#function adduser {
if id $username &> /dev/null; then
echo "$username exists."
return 1
else
useradd $username
## [ $? -eq 0 ] && echo "Add $username finished." && return 0
## fi
}
##for i in {1..10}; do
username=myuser$i
adduser
done
Example: Service Script
#!/bin/bash
# chkconfig : - 88 12
# description: test service script
prog=$ (basename $0)
lockfile=/var/lock/subsys/$prog
##start() {
if [ -e $lockfile ]; then
echo "$prog is aleady running."
return 0
else
##touch $lockfile
##[ $? -eq 0 ] && echo "Starting $prog finished."
fi
}
stop() {
if [ -e $lockfile ]; then
##rm -f $lockfile && echo " Stop $prog ok."
else
echo "$prog is stopped yet."
fi
}
##status() {
if [ -e $lockfile ]; then
##echo "$prog is running."
else
echo "$prog is stopped."
fi
}
usage() {
echo "Usage: $prog {start|stop|restart|status}"
}
if [ $# -lt 1 ]; then
usage
exit 1
fi
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
##status
;;
*)
usage
esac
##Function return value:
The execution result of the function is returned Value:
(1) Use the echo or print command for output;
(2) The execution result of the command called in the function body;
The exit status code of the function:
(1) The default depends on the exit status code of the last command executed in the function body;
(2) Custom exit status code:
return
The function can accept parameters:
Pass parameters to the function: When calling the function, just separate the given parameter list with a blank after the function name; for example, "testfunc arg1 arg2..."
In the function body, you can use $1, $2, ... to call these parameters; you can also use special variables such as $@, $*, $# ;
Example: Add 10 users
#!/bin/bash
function adduser {
if [ $# -lt 1 ]; then
return 2
# 2: no arguments
fi
if id $1 &> /dev/null; then
echo "$1 exists."
return 1
else
##useradd $1
[ $? -eq 0 ] && echo "Add $1 finished." && return 0
fi
##}
for i in {1..10}; do
adduser myuser$i
done
Print the NN multiplication table, using functions;
Variable scope:
Local variables: current shell process; in order to execute the script, a dedicated shell process will be started; therefore, the scope of local variables is the current shell script program file;
Local variables: the life cycle of the function; the variables are automatically destroyed when the function ends;
If there are local variables in the function, their names are the same as local variables;
How to define local variables in a function:
local NAME=VALUE
Function recursion:
The function calls itself directly or indirectly;
N!= N(n-1)(n-2)...1
n(n-1)! = n(n-1)(n-2)!
!/bin/bash
#fact() {
if [ $1 -eq 0 -o $1 -eq 1 ]; then
echo 1
else
echo $[$1*$(fact $[$1-1])]
fi
}
fact 5
Find the n-order Fibonacci sequence;
#!/bin/bash
#fab() {
if [ $1 -eq 1 ]; then
echo 1
## elif [ $1 -eq 2 ]; then
echo 1
else
##echo $[$(fab $[$1-1])+$(fab $[$1-2])]
fi
}
##fab 7
Systemd:
##POST --> Boot Sequence --> Bootloader --> kernel + initramfs(initrd) --> rootfs --> /sbin/init
##init:
CentOS 5: SysV init
CentOS 6: Upstart
CentOS 7: Systemd
New features of Systemd:
Parallel startup of services during system boot;
Activation on demand Process;
System status snapshot;
Defining service control logic based on dependencies;
Core concept: unit
configuration file for identification and configuration; the file mainly contains system services, listening sockets, saved system snapshots and other init-related Information;
Save to:
/usr/lib/systemd/system
/ run/systemd/system
/etc/systemd/system
Unit type:
Service unit: The file extension is .service, used to define system services;
Target unit: The file extension is .target, used to simulate the implementation of " Runlevel";
Device unit: .device, used to define the device recognized by the kernel;
Mount unit: .mount, definition file System mount point;
Socket unit: .socket, used to identify the socket file used for inter-process communication;
Snapshot unit: . snapshot, management system snapshot;
Swap unit: .swap, used to identify swap devices;
Automount unit: .automount, file system Automatic mount point;
Path unit: .path, used to define a file or directory in the file system;
Key features:
Socket-based activation mechanism: socket and service program are separated;
Bus-based activation mechanism:
Device-based activation mechanism:
Path-based activation mechanism:
System snapshot: Save the current status information of each unit in a persistent storage device;
Backwards compatible with sysv init script;
Incompatible:
The systemctl command is fixed
systemctl cannot communicate with services that are not started by systemd
Management system service:
CentOS 7: service unit
Note: Compatible with earlier versions Service script
Command: systemctl COMMAND name.service
Start: service name start ==> systemctl start name.service
##Stop: service name stop ==> systemctl stop name.service
Restart: service name restart ==> systemctl restart name.service
Status: service name status ==> systemctl status name. service
Conditional restart: service name condrestart ==> systemctl try-restart name.service
Reload or restart the service: systemctl reload-or-restart name.service
Reload or conditionally restart the service: systemctl reload-or-try-restart name.service
Disable setting to auto-start at boot: systemctl mask name.service
Cancel prohibiting setting to auto-start at boot: systemctl unmask name.service
View the current activation status of a service: systemctl is-active name.service
View all activated services:
systemctl list-units --type service
View all services:
systemctl list -units --type service --all
The corresponding relationship of the chkconfig command:
Set a service to start Self-start: chkconfig name on ==> systemctl enable name.service
Disable: chkconfig name off ==> systemctl disable name.service
View the startup status of all services:
##chkconfig --list ==> systemctl list-unit-files --type service
Check whether the service starts automatically at boot: systemctl is-enabled name.service
##Other commands:
View service dependencies: systemctl list-dependencies name.service
##target units:
unit configuration file: .target
Run level:
0 ==> runlevel0.target , poweroff.target
1 ==> runlevel1.target, rescue.target
2 ==> runlevel2.target, multi -user.target
##3 ==> runlevel3.target, multi-user.target
4 ==> runlevel4.target , multi-user.target
5 ==> runlevel5.target, graphical.target
6 ==> runlevel6.target , reboot.target
Level switching:
init N ==> systemctl isolate name.target
View level:
runlevel ==> systemctl list-units --type target
Get the default run level:
/etc/inittab ==> systemctl get-default
Modify the default level:
/etc/inittab ==> systemctl set-default name.target
Switch to emergency rescue mode:
systemctl rescue
Switch to emergency mode :
systemctl emergency
Other commonly used commands:
Shutdown : systemctl halt, systemctl poweroff
Restart: systemctl reboot
Suspend: systemctl suspend
Snapshot: systemctl hibernate
Snapshot and suspend: systemctl hybrid-sleep
##Review: bash scripting, systemd
Function: Modular programming
function f_name {
...Function body...
}
f_name() {
...Function Body...
}
return command;
Parameters:
Calling parameters in the function body: $1, $2, ...
$*, $@, $
#Pass parameters to the function:
Function name parameter list
systemd: System and Service
unit:
Type: service, target
.service, . target
systemctl
bash script programming:
##Array:
Variable: a memory space that stores a single element;
Array: a continuous memory space that stores multiple elements;
Array name
Index: The number starts from 0 and is a numerical index;
Note: Index is also supported Use custom formats, not just numerical formats;
bash arrays support sparse formats;
Reference elements in an array: ${ARRAY_NAME[INDEX]}
Declare an array:
declare -a ARRAY_NAME
declare -A ARRAY_NAME: Associative array;
Assignment of array elements:
(1) Only assign one element at a time;
ARRAY_NAME[INDEX]=VALUE
weekdays[0]=" Sunday"
weekdays[4]="Thursday"
(2) Assign all elements at once:
ARRAY_NAME=("VAL1" "VAL2" "VAL3" ...)
(3) Assign only specific elements:
ARRAY_NAME=([0]="VAL1" [3]="VAL2" ...)
(4) read -a ARRAY
Reference array element: ${ARRAY_NAME[INDEX]}
Note: Omitting [INDEX] means referencing the element with subscript 0;
The length of the array (the number of elements in the array): ${#ARRAY_NAME[*]}, ${#ARRAY_NAME[@]}
Example: Generate 10 random numbers and save them in an array, and find their maximum and minimum values;
#!/ bin/bash
declare -a rand
declare -i max=0
for i in {0..9}; do
rand[$i]=$RANDOM
echo ${rand[$i]}
## [ ${rand[$i]} -gt $max ] && max=$ {rand[$i]}
done
##echo "Max: $max"
Define an array. The elements in the array are all files ending with .log in the /var/log directory; statistics are required The sum of the number of lines in the file whose subscript is an even number;
#!/bin/bash
#declare -a files
files=(/var/log/*.log)
declare -i lines=0
for i in $(seq 0 $[${#files[*]}-1]); do
if [ $[$i%2] -eq 0 ];then
let lines+=$(wc -l ${files[$i ]} | cut -d' ' -f1)
fi
done
echo "Lines: $lines."
##Reference elements in the array:
All elements: ${ARRAY[@]}, ${ARRAY[*]}
Array slice: ${ARRAY[@] :offset:number}
offset: The number of elements to be skipped
number: The number of elements to be taken out, take the offset All elements after the amount: ${ARRAY[@]:offset};
Append elements to the array:
ARRAY[${#ARRAY[*]}]
Delete an element in the array:
unset ARRAY[INDEX]
Associative array:
declare -A ARRAY_NAME
ARRAY_NAME=([index_name1]='val1' [index_name2]='val2' ...)
##bash’s string processing tools:
String slicing:
${var: offset:number}
Get the rightmost characters of the string: ${var: -lengh}
Note: after the colon There must be a blank character;
Get the substring based on the pattern:
${var#*word}: where word can be any specified character; function: from left to right, find the first occurrence of word in the string stored in the var variable, and delete all characters between the beginning of the string and the first occurrence of the word character;
${var##*word}: Same as above, but all content between the beginning of the string and the last character specified by word is deleted;
file="/var/log/messages"
${file##*/}: messages
${var%word*}: word can be any specified character; function: from right to left, find the first occurrence of word in the string stored in the var variable, and delete the string All characters between the last character to the left and the first word character;
file="/var/log/messages"
${file%/*}: /var/log
${var%%word*}: Same as above, except that the rightmost part of the string is deleted All characters between the characters on the side to the left and the last occurrence of word characters;
Example: url=:80
${url##*:}
${url%%:*}
Find Replacement:
${var/pattern/substi}: Find the first string matched by pattern in the string represented by var, and replace it with substi;
${var//pattern/substi}: Find all strings that can be matched by pattern in the string represented by var, and replace them with substi;
${var/#pattern/substi}: Find the string matched by pattern at the beginning of the line in the string represented by var, and replace it with substi;
${var/%pattern/substi}: Find the string matched by pattern at the end of the line in the string represented by var, and replace it with substi;
Find and delete:
${var/pattern}: Find the string represented by var and delete the first time The string matched by pattern
${var//pattern}:
${var/#pattern}:
${var/%pattern}:
##Character case conversion:
${var^^}: Convert all lowercase letters in var to uppercase;
${var,,}: Convert all uppercase letters in var to lowercase;
Variable assignment:
${var:-value}: If var is empty or not set, then return value; otherwise, return the value of var;
${var:=value}: If var is empty or not set, then return value and assign value to var; otherwise, return the value of var;
${var:+value}: If var is not empty, return value;
${var:?error_info}: If var is empty or not set, then return error_info; otherwise, return the value of var;
Use the configuration file for the script program:
(1) Define a text file and define "name=value" for each line
(2) Source this file in the script
Command:
mktemp Command:
mktemp [OPTION]... [TEMPLATE]
TEMPLATE: filename.XXX
XXX must appear at least three times;
OPTION:
-d: Create a temporary directory;
--tmpdir=/PATH/TO/SOMEDIR: Specify the location of the temporary file directory;
install command:
install [OPTION]... [-T] SOURCE DEST
install [ OPTION]... SOURCE... DIRECTORY
## install [OPTION]... -t DIRECTORY SOURCE...
install [ OPTION]... -d DIRECTORY...
Option:
- m MODE
##-o OWNER
-g GROUP
GNU awk:
Three tools for text processing: grep, sed, awk
grep, egrep, fgrep: text filtering tool; pattern
sed: line editor
Pattern space, hold space
awk: report generator, formatted text output;
AWK: Aho , Weinberger, Kernighan --> New AWK, NAWK
##GNU awk, gawk
gawk - pattern scanning and processing language
Basic usage: gawk [options] 'program' FILE ...
program: PATTERN{ACTION STATEMENTS}
Separate statements with semicolons
print, printf
Options:
-F: Specify the field separator used when inputting;
-v var=value: custom variable;
1, print
print item1, item2, ...
Key points:
(1) Comma Delimiter;
(2) Each output item can be a string or a numerical value; the field, variable or awk expression of the current record;
(3) If item is omitted, it is equivalent to print $0;
##2, variable
2.1 Built-in variables
FS: input field seperator, the default is blank characters;
OFS: output field seperator, the default is blank characters;
RS: input record seperator, newline character during input;
ORS: output record seperator, newline character during output;
NF: number of field, number of fields
{print NF}, {print $NF}
NR: number of record, number of lines;
FNR: Count each file separately; number of lines;
FILENAME: Current file name;
ARGC: Number of command line parameters;
ARGV : Array, which stores the parameters given by the command line;
2.2 Custom variables
( 1) -v var=value
Variable names are case-sensitive;
(2) Directly define
in the program. 3. Printf command
formatting Output: printf FORMAT, item1, item2, ...
(1) FORMAT must be given;
(2) There will be no automatic line wrapping, and the line wrapping control character needs to be explicitly given, \n
(3) In FORMAT, a formatting symbol needs to be specified for each subsequent item;
Format character:
%c: Display the ASCII code of the character;
%d, %i: Display decimal integer;
%e, %E: Display numerical value in scientific notation;
%f: Display as floating point number;
%g, %G: Display value in scientific notation or floating point form;
##% s: display string;
%u: unsigned integer;
##%%: display % itself;
Modifier:
#[.#]: The first number controls the width of the display; the second # represents the decimal point Precision;
%3.1f
-: Left-aligned
+: Display the sign of the value
4. Operators
##Arithmetic operators:
x+y, x-y, x*y, x/y, x^y, x%y
-x
+x: Convert to numeric value;
String operator: unsigned operator, string concatenation
Assignment operators:
=, +=, -=, *=, /=, %=, ^=
++, --
##Comparison operators:
>, > =, <, <=, !=, ==
Pattern matching characters:
~: Whether it matches
!~: Whether it does not match
## Logical operator:
&&
||
!
## Function call:
function_name(argu1, argu2, ...)
Conditional expression:
selector?if-true-expression:if-false-expression
awk -F: '{$3> =1000?usertype="Common User":usertype="Sysadmin or SysUser";printf "%15s:%-s\n",$1,usertype}' /etc/passwd
5, PATTERN
(1) empty: empty pattern, matches each line;
(2) /regular expression/: Only process lines that can be matched by the pattern here;
(3) relational expression: relational expression; the result can be "true" or "false"; it will be processed only if the result is "true";
True: the result is a non-zero value, a non-empty string;
(4) line ranges: line range,
startline,endline :/pat1/,/pat2/
Note: The format of directly giving numbers is not supported
~] # awk -F: '(NR>=2&&NR<=10){print $1}' /etc/passwd
(5) BEGIN/END mode
BEGIN{}: Executed only once before starting to process the text in the file;
END{}: Executed only once after the text processing is completed;
6. Commonly used actions
(1) Expressions
(2) Control statements: if, while, etc.;
(3) Compound statements: combination statements;
(4) input statements
(5) output statements
##7, control statements
if(condition) {statments}
if(condition) {statments} else {statements}
while(conditon) {statments}
##do {statements} while(condition)
for(expr1;expr2;expr3) {statements }
break
continue
##delete array[index]
delete array
exit
{ statements }
7.1 if-else
Syntax: if(condition) statement [else statement]
~]# awk -F: '{if($3>=1000) {printf "Common user: %s\n",$1} else {printf "root or Sysuser: %s\n", $1}}' /etc/passwd
~]# awk -F: '{if($NF=="/bin/bash") print $1 }' /etc/passwd
##~]# awk '{if(NF>5) print $0}' /etc/fstab
##~]# df -h | awk -F[%] '/^\/dev/{print $1}' | awk '{if($NF>=20) print $1}'
Usage scenario: Make conditional judgment on the entire row or a certain field obtained by awk;
7.2 while loop
Syntax: while(condition) statement
Condition "true", enter the loop; condition " False", exit the loop;
Usage scenarios: Used when processing multiple fields in a row one by one; used when processing each element in an array one by one ;
##~]# awk '/^[[:space:]]*linux16/{i=1;while(i<=NF) {print $i,length($i); i++}}' /etc/grub2.cfg
##~]# awk '/^[[:space:] ]*linux16/{i=1;while(i<=NF) {if(length($i)>=7) {print $i,length($i)}; i++}}' /etc/grub2. cfg
7.3 do-while loop
Syntax: do statement while(condition)
Meaning: Execute the loop body at least once
7.4 for loop
Syntax: for( expr1;expr2;expr3) statement
for(variable assignment;condition;iteration process) {for-body}
~]# awk '/^[[:space:]]*linux16/{for(i=1;i<=NF;i++) {print $i,length($i)} }' /etc/grub2.cfg
Special usage:
Can traverse the elements in the array;
Syntax: for(var in array) {for-body}
7.5 switch statement
Syntax: switch(expression) {case VALUE1 or /REGEXP/: statement; case VALUE2 or /REGEXP2/: statement; . ..; default: statement}
7.6 break and continue
break [n]
continue
7.7 next
End the transaction early processing and go directly to the next line;
##~]# awk -F: '{if($3%2!=0) next; print $1,$3 }' /etc/passwd
8, array
Associative array: array[ index-expression]
index-expression:
(1) Any string can be used; the string must be Use double quotes;
(2) If an array element does not exist in advance, awk will automatically create this element when referencing it, and initialize its value to "empty string";
To determine whether an element exists in the array, use the "index in array" format;
##weekdays[mon]="Monday"
To iterate through each element in the array, use a for loop;
for(var in array) {for-body}
##~]# awk 'BEGIN{weekdays["mon"] ="Monday";weekdays["tue"]="Tuesday";for(i in weekdays) {print weekdays[i]}}'
Note : var will traverse each index of the array;
state["LISTEN"]++
state["ESTABLISHED"]++
~]# netstat -tan | awk '/^tcp\>/{state[$NF]++}END{for(i in state ) { print i,state[i]}}'
##~]# awk '{ip[$1]++}END{for(i in ip ) {print i,ip[i]}}' /var/log/httpd/access_log
1: Statistics of each file in the /etc/fstab file The number of times the system type appears;
~]# awk '/^UUID/{fs[$3]++}END{for(i in fs) {print i,fs[i ]}}' /etc/fstab
2: Count the number of occurrences of each word in the specified file;
~]# awk '{for(i=1;i<=NF;i++){count[$i]++}}END{for(i in count) {print i,count[i]}}' / etc/fstab
9, function
9.1 Built-in function
Numerical processing:
rand(): Returns a random number between 0 and 1;
String processing:
length([s]): Returns the length of the specified string;
sub(r, s,[t]): Use the pattern represented by r to find the matching content in the character represented by t, and replace its first occurrence with the content represented by s;
gsub(r,s,[t]): Use the pattern represented by r to find matching content in the character represented by t, and replace all occurrences of it with the content represented by s;
split(s,a[,r]): Use r as the separator to cut the character s, and save the cut result to the array represented by a;
~]# netstat -tan | awk '/^tcp\>/{split($5,ip,":");count[ip[1] ]++}END{for (i in count) {print i,count[i]}}'
9.2 Custom function
《sed and awk》
#
   
DNF新一代的RPM软件包管理器。他首先出现在 Fedora 18 这个发行版中。而最近,他取代了YUM,正式成为 Fedora 22 的包管理器。
DNF包管理器克服了YUM包管理器的一些瓶颈,提升了包括用户体验,内存占用,依赖分析,运行速度等多方面的内容。
DNF使用 RPM, libsolv 和 hawkey 库进行包管理操作。尽管它没有预装在 CentOS 和 RHEL 7 中,但你可以在使用 YUM 的同时使用 DNF 。
DNF 的最新稳定发行版版本号是 1.0,发行日期是2015年5月11日。 这一版本的额 DNF 包管理器(包括在他之前的所有版本) 都大部分采用 Python 编写,发行许可为GPL v2.
Dependency resolution of YUM is a nightmare and was resolved in DNF with SUSE library ‘libsolv’ and Python wrapper along with C Hawkey.
YUM don’t have a documented API.
Building new features are difficult.
No support for extensions other than Python.
Lower memory reduction and less automatic synchronization of metadata – a time taking process.

The above is the detailed content of Basics of Linux System (2). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template