Linux Admin 简明教程
Linux Admin - CentOS Overview
在商业级 Linux 发行版中,CentOS 始终如一地忠于 Linux 成立之初的开源性质。第一个 Linux 内核是由赫尔辛基大学的一名大学生 (Linus Torvalds) 开发的,并结合了由理查德·斯托曼创立和推广的 GNU 实用程序。CentOS 拥有经过验证的开源许可,可以为当今的商业世界提供动力。
Unique among business class Linux distributions, CentOS stays true to the open-source nature that Linux was founded on. The first Linux kernel was developed by a college student at the University of Helsinki (Linus Torvalds) and combined with the GNU utilities founded and promoted by Richard Stallman. CentOS has a proven, open-source licensing that can power today’s business world.
CentOS 已迅速成为世界上最多的服务器平台之一。任何 Linux 管理员在求职时,一定会遇到以下话语:“CentOS Linux 体验优先”。从初创公司到财富 10 强科技巨头,CentOS 已跻身全球服务器操作系统的高端行列。
CentOS has quickly become one of the most prolific server platforms in the world. Any Linux Administrator, when seeking employment, is bound to come across the words: “CentOS Linux Experience Preferred”. From startups to Fortune 10 tech titans, CentOS has placed itself amongst the higher echelons of server operating systems worldwide.
使 CentOS 从其他 Linux 发行版中脱颖而出的原因是以下几个因素的出色组合 −
What makes CentOS stand out from other Linux distributions is a great combination of −
-
Open source licensing
-
Dedicated user-base of Linux professionals
-
Good hardware support
-
Rock-solid stability and reliability
-
Focus on security and updates
-
Strict adherence to software packaging standards needed in a corporate environment
.
在开始课程之前,我们假设读者具有 Linux 及管理员基本知识,例如:
Before starting the lessons, we assume that the readers have a basic knowledge of Linux and Administration fundamentals such as −
-
What is the root user?
-
The power of the root user
-
Basic concept of security groups and users
-
Experience using a Linux terminal emulator
-
Fundamental networking concepts
-
Fundamental understanding of interpreted programming languages (Perl, Python, Ruby)
-
Networking protocols such as HTTP, LDAP, FTP, IMAP, SMTP
-
Cores that compose a computer operating system: file system, drivers, and the kerne
Basic CentOS Linux Commands
在学习 CentOS Linux 管理员的工具之前,了解 Linux 管理命令行背后的理念非常重要。
Before learning the tools of a CentOS Linux Administrator, it is important to note the philosophy behind the Linux administration command line.
Linux 是根据“实现更大的任务时可将小型精确工具链接起来”的 Unix 理念而设计的。从根本上讲,Linux 很多时候并不会将大型单一用途应用程序与某个特定用途结合起来。相反,有数百个基本实用程序,在相结合时能够有效地为完成大型任务提供强大的功能。
Linux was designed based on the Unix philosophy of “small, precise tools chained together simplifying larger tasks”. Linux, at its root, does not have large single-purpose applications for one specific use a lot of the time. Instead, there are hundreds of basic utilities that when combined offer great power to accomplish big tasks with efficiency.
Examples of the Linux Philosophy
例如,如果管理员希望获取系统中所有当前用户的列表,可以使用以下连锁命令获取系统中所有用户的列表。在执行命令时,将按字母顺序列出系统中的用户。
For example, if an administrator wants a listing of all the current users on a system, the following chained commands can be used to get a list of all system users. On execution of the command, the users are on the system are listed in an alphabetical order.
[root@centosLocal centos]# cut /etc/passwd -d":" -f1 | sort
abrt
adm
avahi
bin
centos
chrony
colord
daemon
dbus
可以轻松地使用以下命令将此列表导出到文本文件中。
It is easy to export this list into a text file using the following command.
[root@localhost /]# cut /etc/passwd -d ":" -f1 > system_users.txt
[root@localhost /]# cat ./system_users.txt | sort | wc –l
40
[root@localhost /]#
还可以将用户列表与稍后导出的内容进行比较。
It is also possible to compare the user list with an export at a later date.
[root@centosLocal centos]# cut /etc/passwd -d ":" -f1 > system_users002.txt &&
cat system_users002.txt | sort | wc -l
41
[root@centosLocal centos]# diff ./system_users.txt ./system_users002.txt
evilBackdoor [root@centosLocal centos]#
通过这种将小工具连接起来以完成更大任务的方法,编写一个执行这些命令的脚本比在固定时间间隔自动发送结果电子邮件更加简单。
With this approach of small tools chained to accomplish bigger tasks, it is simpler to make a script performing these commands, than automatically email results at regular time intervals.
每个 Linux 管理员都应该精通的基本命令如下:
Basic Commands every Linux Administrator should be proficient in are −
在 Linux 世界中,管理员每天使用 filtering 命令来分析日志、筛选命令输出以及使用交互式 shell 脚本执行操作。如前所述,这些命令的力量在于它们能够通过称为 piping 的过程相互修改。
In the Linux world, Administrators use filtering commands every day to parse logs, filter command output, and perform actions with interactive shell scripts. As mentioned, the power of these commands come in their ability to modify one another through a process called piping.
以下命令显示了 CentOS 主用户词典中有多少个单词以字母 a 开头。
The following command shows how many words begin with the letter a from the CentOS main user dictionary.
[root@centosLocal ~]# egrep '^a.*$' /usr/share/dict/words | wc -l
25192
[root@centosLocal ~]#
Linux Admin - File / Folder Management
为了介绍 CentOS Linux 中对目录和文件应用的权限,我们看看下面的命令输出。
To introduce permissions as they apply to both directories and files in CentOS Linux, let’s look at the following command output.
[centos@centosLocal etc]$ ls -ld /etc/yum*
drwxr-xr-x. 6 root root 100 Dec 5 06:59 /etc/yum
-rw-r--r--. 1 root root 970 Nov 15 08:30 /etc/yum.conf
drwxr-xr-x. 2 root root 187 Nov 15 08:30 /etc/yum.repos.d
Note − 你将看到的三个主要对象类型是
Note − The three primary object types you will see are
-
"-" − a dash for plain file
-
"d" − for a directory
-
"l" − for a symbolic link
我们重点关注针对每个目录和文件的三个输出块 −
We will focus on the three blocks of output for each directory and file −
-
drwxr-xr-x : root : root
-
-rw-r—r-- : root : root
-
drwxr-xr-x : root : root
现在我们来分析一下,以便更好地理解这些行 −
Now let’s break this down, to better understand these lines −
d |
Means the object type is a directory |
rwx |
Indicates directory permissions applied to the owner |
r-x |
Indicates directory permissions applied to the group |
r-x |
Indicates directory permissions applied to the world |
root |
The first instance, indicates the owner of the directory |
root |
The second instance, indicates the group to which group permissions are applied |
理解所有者、组和 World(世界)之间的区别很重要。如果不理解这一点,对于向互联网托管服务的服务器来说可能会产生巨大影响。
Understanding the difference between owner, group and world is important. Not understanding this can have big consequences on servers that host services to the Internet.
在我们给出实际实例之前,让我们首先理解应用于目录和文件的权限。
Before we give a real-world example, let’s first understand the permissions as they apply to directories and files.
请查看下表,然后继续执行说明。
Please take a look at the following table, then continue with the instruction.
Octal |
Symbolic |
Perm. |
Directory |
1 |
x |
Execute |
Enter the directory and access files |
2 |
w |
Write |
Delete or modify the files in a directory |
4 |
r |
Read |
List the files within the directory |
Note − 当文件应可在目录中读取时,通常会应用读取和执行权限。否则,用户将难以处理这些文件。禁用写入权限将确保文件无法:重命名、删除、覆盖或修改权限。
Note − When files should be accessible for reading in a directory, it is common to apply read and execute permissions. Otherwise, the users will have difficulty working with the files. Leaving write disabled will assure files cannot be: renamed, deleted, copied over, or have permissions modified.
Applying Permissions to Directories and Files
在应用权限时,有两个概念需要理解 −
When applying permissions, there are two concepts to understand −
-
Symbolic Permissions
-
Octal Permissions
从本质上说,它们都是相同的,但引用和分配文件权限的方式不同。有关快速指南,请研究并参考下表 −
In essence, each are the same but a different way to referring to, and assigning file permissions. For a quick guide, please study and refer to the following table −
Read |
Write |
Execute |
|
Octal |
4 |
2 |
1 |
Symbolic |
r |
w |
x |
在使用 octal 方法分配权限时,请使用 3 字节数字,例如:760。数字 760 转化为:所有者:rwx;组:rw;其他(或世界)无权限。
When assigning permissions using the octal method, use a 3 byte number such as: 760. The number 760 translates into: Owner: rwx; Group: rw; Other (or world) no permissions.
另一种情况:733 将转化为:所有者:rwx;组:wx;其他:wx。
Another scenario: 733 would translate to: Owner: rwx; Group: wx; Other: wx.
使用八进制方法的权限有一个缺点。现有的权限集无法修改。只能重新分配对象的整个权限集。
There is one drawback to permissions using the Octal method. Existing permission sets cannot be modified. It is only possible to reassign the entire permission set of an object.
现在您可能会想,总是重新分配权限有什么问题?想象一下一个大型目录结构,例如生产 Web 服务器上的 /var/www/。我们希望对所有目录递归地取消 Other 的 w 或写入位。因此,强制仅在安全措施需要时主动添加它。如果我们重新分配整个权限集,我们将取消分配给每个子目录的所有其他自定义权限。
Now you might wonder, what is wrong with always re-assigning permissions? Imagine a large directory structure, for example /var/www/ on a production web-server. We want to recursively take away the w or write bit on all directories for Other. Thus, forcing it to be pro-actively added only when needed for security measures. If we re-assign the entire permission set, we take away all other custom permissions assigned to every sub-directory.
因此,它将给系统管理员和用户带来问题。在某些时候,某人(或某些人)需要重新分配所有由于重新分配每个目录和对象的整个权限集而被清除的自定义权限。
Hence, it will cause a problem for both the administrator and the user of the system. At some point, a person (or persons) would need to re-assign all the custom permissions that were wiped out by re-assigning the entire permission-set for every directory and object.
在这种情况下,我们希望使用符号方法来修改权限 −
In this case, we would want to use the Symbolic method to modify permissions −
chmod -R o-w /var/www/
以上命令不会“覆盖权限”,而是修改当前权限集。因此,习惯于使用最佳做法
The above command would not "overwrite permissions" but modify the current permission sets. So get accustomed to using the best practice
-
Octal only to assign permissions
-
Symbolic to modify permission sets
重要的是,CentOS 管理员必须熟练掌握八进制和符号权限,因为权限对于数据和整个操作系统的完整性非常重要。如果权限不正确,最终结果将是敏感数据和整个操作系统将受到威胁。
It is important that a CentOS Administrator be proficient with both Octal and Symbolic permissions as permissions are important for the integrity of data and the entire operating system. If permissions are incorrect, the end result will be both sensitive data and the entire operating system will be compromised.
在介绍完这些内容后,我们来看看一些用于修改权限和对象所有者/成员的命令 −
With that covered, let’s look at a few commands for modifying permissions and object owner/members −
-
chmod
-
chown
-
chgrp
-
umask
chmod : Change File Mode Permission Bits
Command |
Action |
-c |
Like verbose, but will only report the changes made |
-v |
Verbose, outputsthe diagnostics for every request made |
-R |
Recursively applies the operation on files and directories |
chmod 允许我们使用八进制或符号权限集更改目录和文件的权限。我们将使用它来修改分配和上传目录。
chmod will allow us to change permissions of directories and files using octal or symbolic permission sets. We will use this to modify our assignment and uploads directories.
chown : Change File Owner and Group
Command |
Action |
-c |
Like verbose, but will only report the changes made |
-v |
Verbose, outputsthe diagnostics for every request made |
-R |
Recursively applies the operation on files and directories |
chown 可以同时修改用户和对象组的所有权。但是,除非需要同时修改两者,否则通常使用 chgrp 来修改组。
chown can modify both owning the user and group of objects. However, unless needing to modify both at the same time, using chgrp is usually used for groups.
chgrp : Change Group Ownership of File or Directory
Command |
Action |
-c |
Like verbose, but will only report the changes |
-v |
Verbose, outputs the diagnostics for every request made |
-R |
Recursively, applies the operations on file and directories |
chgrp 将更改组所有者为提供的组。
chgrp will change the group owner to that supplied.
Real-world practice
让我们更改 /var/www/students/ 中所有子目录分配,以便所有组是学生组。然后将 students 根目录分配给教授组。之后,让 Terry Thomas 博士成为 students 目录的所有者,因为他负责学校的所有计算机科学学术工作。
Let’s change all the subdirectory assignments in /var/www/students/ so the owning group is the students group. Then assign the root of students to the professors group. Later, make Dr. Terry Thomas the owner of the students directory, since he is tasked as being in-charge of all Computer Science academia at the school.
正如我们所见,在创建时,目录保留相当原始。
As we can see, when created, the directory is left pretty raw.
[root@centosLocal ~]# ls -ld /var/www/students/
drwxr-xr-x. 4 root root 40 Jan 9 22:03 /var/www/students/
[root@centosLocal ~]# ls -l /var/www/students/
total 0
drwxr-xr-x. 2 root root 6 Jan 9 22:03 assignments
drwxr-xr-x. 2 root root 6 Jan 9 22:03 uploads
[root@centosLocal ~]#
作为管理员,我们永远不想将我们的根凭据交给任何人。但同时,我们需要允许用户执行他们的工作。因此,让我们允许 Terry Thomas 博士更多地控制文件结构并限制学生可以执行的操作。
As Administrators we never want to give our root credentials out to anyone. But at the same time, we need to allow users the ability to do their job. So let’s allow Dr. Terry Thomas to take more control of the file structure and limit what students can do.
[root@centosLocal ~]# chown -R drterryt:professors /var/www/students/
[root@centosLocal ~]# ls -ld /var/www/students/
drwxr-xr-x. 4 drterryt professors 40 Jan 9 22:03 /var/www/students/
[root@centosLocal ~]# ls -ls /var/www/students/
total 0
0 drwxr-xr-x. 2 drterryt professors 6 Jan 9 22:03 assignments
0 drwxr-xr-x. 2 drterryt professors 6 Jan 9 22:03 uploads
[root@centosLocal ~]#
现在,每个目录和子目录的所有者都是 drterryt,所有组是 professors。由于 assignments 目录供学生上交已分配作业,因此,让我们取消学生组列出和修改文件的权限。
Now, each directory and subdirectory has an owner of drterryt and the owning group is professors. Since the assignments directory is for students to turn assigned work in, let’s take away the ability to list and modify files from the students group.
[root@centosLocal ~]# chgrp students /var/www/students/assignments/ && chmod
736 /var/www/students/assignments/
[root@centosLocal assignments]# ls -ld /var/www/students/assignments/
drwx-wxrw-. 2 drterryt students 44 Jan 9 23:14 /var/www/students/assignments/
[root@centosLocal assignments]#
学生可以将作业复制到 assignments 目录。但他们无法列出目录内容、复制当前文件或修改 assignments 目录中的文件。因此,它只允许学生提交已完成的作业。CentOS 文件系统将提供上交作业的时间戳。
Students can copy assignments to the assignments directory. But they cannot list contents of the directory, copy over current files, or modify files in the assignments directory. Thus, it just allows the students to submit completed assignments. The CentOS filesystem will provide a date-stamp of when assignments turned in.
作为 assignments 目录所有者——
As the assignments directory owner −
[drterryt@centosLocal assignments]$ whoami
drterryt
[drterryt@centosLocal assignments]$ ls -ld /var/www/students/assignment
drwx-wxrw-. 2 drterryt students 44 Jan 9 23:14 /var/www/students/assignments/
[drterryt@centosLocal assignments]$ ls -l /var/www/students/assignments/
total 4
-rw-r--r--. 1 adama students 0 Jan 9 23:14 myassign.txt
-rw-r--r--. 1 tammyr students 16 Jan 9 23:18 terryt.txt
[drterryt@centosLocal assignments]$
我们可以看到,目录所有者可以列出文件以及修改和删除文件。
We can see, the directory owner can list files as well as modify and remove files.
umask Command: Supplies the Default Modes for File and Directory Permissions As They are Created
umask 是一条重要的命令,它在创建文件和目录权限时提供默认模式。
umask is an important command that supplies the default modes for File and Directory Permissions as they are created.
umask 权限使用一元否定逻辑。
umask permissions use unary, negated logic.
Permission |
Operation |
0 |
Read, write, execute |
1 |
Read and write |
2 |
Read and execute |
3 |
Read only |
4 |
Read and execute |
5 |
Write only |
6 |
Execute only |
7 |
No permissions |
[adama@centosLocal umask_tests]$ ls -l ./
-rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir
-rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt
[adama@centosLocal umask_tests]$ whoami
adama
[adama@centosLocal umask_tests]$ umask
0022
[adama@centosLocal umask_tests]$
现在,让我们更改当前用户的 umask,并创建一个新文件和新目录。
Now, let’s change the umask for our current user, and make a new file and directory.
[adama@centosLocal umask_tests]$ umask 077
[adama@centosLocal umask_tests]$ touch mynewfile.txt
[adama@centosLocal umask_tests]$ mkdir myNewDir
[adama@centosLocal umask_tests]$ ls -l
total 0
-rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir
-rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt
drwx------. 2 adama students 6 Jan 10 00:35 myNewDir
-rw-------. 1 adama students 0 Jan 10 00:35 mynewfile.txt
正如我们所见,新创建的文件比之前稍微严格一些。
As we can see, newly created files are a little more restrictive than before.
用户 umask 必须在以下位置进行更改:-
umask for users must should be changed in either −
-
/etc/profile
-
~/bashrc
[root@centosLocal centos]# su adama
[adama@centosLocal centos]$ umask
0022
[adama@centosLocal centos]$
通常,CentOS 中的默认 umask 是可以的。当我们遇到 0022 的默认值时通常会出现问题,这是因为属于不同组的不同部门需要在项目上进行协作时。
Generally, the default umask in CentOS will be okay. When we run into trouble with a default of 0022, is usually when different departments belonging to different groups need to collaborate on projects.
这正是系统管理员职责所在,以平衡 CentOS 操作系统的操作和设计。
This is where the role of a system administrator comes in, to balance the operations and design of the CentOS operating system.
Linux Admin - User Management
在讨论用户管理时,我们必须了解以下三个重要术语:
When discussing user management, we have three important terms to understand −
-
Users
-
Groups
-
Permissions
我们已经详尽讨论了对文件和文件夹应用的权限。在本章中,我们将讨论用户和组。
We have already discussed in-depth permissions as applied to files and folders. In this chapter, let’s discuss about users and groups.
CentOS Users
在 CentOS 中,有两种类型的帐号:
In CentOS, there are two types accounts −
-
System accounts − Used for a daemon or other piece of software.
-
Interactive accounts − Usually assigned to a user for accessing system resources.
这两种用户类型之间的主要区别在于:
The main difference between the two user types is −
-
System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login.
-
Interactive accounts are used by end-users to access computing resources from either a shell or physical console login.
基于此对用户的基本了解,现在让我们为会计部的 Bob Jones 创建一个新用户。使用 adduser 命令添加新用户。
With this basic understanding of users, let’s now create a new user for Bob Jones in the Accounting Department. A new user is added with the adduser command.
以下是 adduser 一些常见选项 −
Following are some adduser common switches −
Switch |
Action |
-c |
Adds comment to the user account |
-m |
Creates user home directory in default location, if nonexistent |
-g |
Default group to assign the user |
-n |
Does not create a private group for the user, usually a group with username |
-M |
Does not create a home directory |
-s |
Default shell other than /bin/bash |
-u |
Specifies UID (otherwise assigned by the system) |
-G |
Additional groups to assign the user to |
创建新用户时,使用 -c、-m、-g、-n 选项如下 −
When creating a new user, use the -c, -m, -g, -n switches as follows −
[root@localhost Downloads]# useradd -c "Bob Jones Accounting Dept Manager"
-m -g accounting -n bjones
现在让我们看看是否创建了新用户 −
Now let’s see if our new user has been created −
[root@localhost Downloads]# id bjones
(bjones) gid = 1001(accounting) groups = 1001(accounting)
[root@localhost Downloads]# grep bjones /etc/passwd
bjones:x:1001:1001:Bob Jones Accounting Dept Manager:/home/bjones:/bin/bash
[root@localhost Downloads]#
现在我们需使用 passwd 命令启用新帐户 −
Now we need to enable the new account using the passwd command −
[root@localhost Downloads]# passwd bjones
Changing password for user bjones.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
[root@localhost Downloads]#
未启用用户帐户,允许用户登录系统。
The user account is not enabled allowing the user to log into the system.
Disabling User Accounts
有几种方法可用于禁用系统上的帐户。这些方法包括手动编辑 /etc/passwd 文件。也可以使用 passwd 命令和 -l 选项。这两种方法都有一个重大缺陷:如果用户拥有 ssh 访问权限并使用 RSA 密钥进行身份验证,则他们仍然可以使用这种方法登录。
There are several methods to disable accounts on a system. These range from editing the /etc/passwd file by hand. Or even using the passwd command with the *-l*switch. Both of these methods have one big drawback: if the user has ssh access and uses an RSA key for authentication, they can still login using this method.
现在我们用 chage 命令,将密码过期日期更改为前面的日期。另外,最好在帐户上注明禁用原因。
Now let’s use the chage command, changing the password expiry date to a previous date. Also, it may be good to make a note on the account as to why we disabled it.
[root@localhost Downloads]# chage -E 2005-10-01 bjones
[root@localhost Downloads]# usermod -c "Disabled Account while Bob out of the country
for five months" bjones
[root@localhost Downloads]# grep bjones /etc/passwd
bjones:x:1001:1001:Disabled Account while Bob out of the country for four
months:/home/bjones:/bin/bash
[root@localhost Downloads]#
Manage Groups
在 Linux 中管理组,能让管理员方便地将用户合并到容器中,对所有组成员应用适用权限集。例如,会计中的所有用户可能需要访问相同的文件。因此,我们创建一个会计组,添加会计用户。
Managing groups in Linux makes it convenient for an administrator to combine the users within containers applying permission-sets applicable to all group members. For example, all users in Accounting may need access to the same files. Thus, we make an accounting group, adding Accounting users.
在大多数情况下,任何需要特殊权限的内容都应该在组中完成。此方法通常会比仅对一个用户应用特殊权限节省时间。例如,Sally 负责报告,并且只有 Sally 需要访问某些文件以进行报告。然而,如果 Sally 有天生病而 Bob 需做报告怎么办?或者对报告的需求增长怎么办?当建立一个组时,管理员只需执行一次。在需求更改或扩展时应用添加用户。
For the most part, anything requiring special permissions should be done in a group. This approach will usually save time over applying special permissions to just one user. Example, Sally is in-charge of reports and only Sally needs access to certain files for reporting. However, what if Sally is sick one day and Bob does reports? Or the need for reporting grows? When a group is made, an Administrator only needs to do it once. The add users is applied as needs change or expand.
以下是用于管理组的一些常见命令 −
Following are some common commands used for managing groups −
-
chgrp
-
groupadd
-
groups
-
usermod
chgrp − 更改文件或目录的组所有权。
chgrp − Changes the group ownership for a file or directory.
让我们为会计组人员创建一个目录来存储文件并为文件创建子目录。
Let’s make a directory for people in the accounting group to store files and create directories for files.
[root@localhost Downloads]# mkdir /home/accounting
[root@localhost Downloads]# ls -ld /home/accounting
drwxr-xr-x. 2 root root 6 Jan 13 10:18 /home/accounting
[root@localhost Downloads]#
接下来,让我们将组所有权赋予会计组。
Next, let’s give group ownership to the accounting group.
[root@localhost Downloads]# chgrp -v accounting /home/accounting/
changed group of ‘/home/accounting/’ from root to accounting
[root@localhost Downloads]# ls -ld /home/accounting/
drwxr-xr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/
[root@localhost Downloads]#
现在,会计组中的每个人都具有对 /home/accounting 的读取和执行权限。他们还需要写入权限。
Now, everyone in the accounting group has read and execute permissions to /home/accounting. They will need write permissions as well.
[root@localhost Downloads]# chmod g+w /home/accounting/
[root@localhost Downloads]# ls -ld /home/accounting/
drwxrwxr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/
[root@localhost Downloads]#
由于会计组可能会处理敏感文件,我们需要对其他或世界应用一些限制性权限。
Since the accounting group may deal with sensitive documents, we need to apply some restrictive permissions for other or world.
[root@localhost Downloads]# chmod o-rx /home/accounting/
[root@localhost Downloads]# ls -ld /home/accounting/
drwxrwx---. 2 root accounting 6 Jan 13 10:18 /home/accounting/
[root@localhost Downloads]#
groupadd − 用于创建新组。
groupadd − Used to make a new group.
Switch |
Action |
-g |
Specifies a GID for the group |
-K |
Overrides specs for GID in /etc/login.defs |
-o |
Allows overriding non-unique group id disallowance |
-p |
Group password, allowing the users to activate themselves |
让我们创建一个名为 secret 的新组。我们将为组添加一个密码,允许用户使用已知密码添加自己。
Let’s make a new group called secret. We will add a password to the group, allowing the users to add themselves with a known password.
[root@localhost]# groupadd secret
[root@localhost]# gpasswd secret
Changing the password for group secret
New Password:
Re-enter new password:
[root@localhost]# exit
exit
[centos@localhost ~]$ newgrp secret
Password:
[centos@localhost ~]$ groups
secret wheel rdc
[centos@localhost ~]$
在实际中,组密码并不常用。辅助组是足够的,并且在其他用户之间共享密码并不是一个很好的安全实践。
In practice, passwords for groups are not used often. Secondary groups are adequate and sharing passwords amongst other users is not a great security practice.
groups 命令用于显示用户属于哪个组。在对我们当前用户进行一些更改后,我们将使用它。
The groups command is used to show which group a user belongs to. We will use this, after making some changes to our current user.
usermod 用于更新帐户属性。
usermod is used to update account attributes.
以下是常见 usermod 开关。
Following are the common usermod switches.
Switch |
Action |
-a |
Appends, adds user to supplementary groups, only with the -G option |
-c |
Comment, updatesthe user comment value |
-d |
Home directory, updates the user’s home directory |
-G |
Groups, adds or removesthe secondary user groups |
-g |
Group, default primary group of the user |
[root@localhost]# groups centos
centos : accounting secret
[root@localhost]#
[root@localhost]# usermod -a -G wheel centos
[root@localhost]# groups centos
centos : accounting wheel secret
[root@localhost]#
Linux Admin - Quota Management
CentOS 磁盘配额既可以启用,既能够在超出磁盘容量前提醒系统管理员,又能够拒绝向用户提供进一步的磁盘存储访问。当磁盘已满时,取决于磁盘中的内容,整个系统可能会突然停止,直至恢复。
CentOS disk quotas can be enabled both; alerting the system administrator and denying further disk-storage-access to a user before disk capacity is exceeded. When a disk is full, depending on what resides on the disk, an entire system can come to a screeching halt until recovered.
在 CentOS Linux 中启用配额管理基本上是一个 4 步过程:
Enabling Quota Management in CentOS Linux is basically a 4 step process −
-
Step 1 − Enable quota management for groups and users in /etc/fstab.
-
Step 2 − Remount the filesystem.
-
Step 3 − Create Quota database and generate disk usage table.
-
Step 4 − Assign quota policies.
Enable Quota Management in /etc/fstab
首先,我们要备份 /etc/fstab 文件:
First, we want to backup our /etc/fstab filen −
[root@centosLocal centos]# cp -r /etc/fstab ./
我们现在在当前工作目录中有已知正常工作 /etc/fstab 的副本。
We now have a copy of our known working /etc/fstab in the current working directory.
#
# /etc/fstab
# Created by anaconda on Sat Dec 17 02:44:51 2016
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/cl-root / xfs defaults 0 0
UUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0
/dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0
/dev/mapper/cl-swap swap swap defaults 0 0
我们在 /etc/fstab 的选项部分中对要向其应用用户和组配额的卷或标签进行了以下更改。
We made the following changes in the options section of /etc/fstab for the volume or Label to where quotas are to be applied for users and groups.
-
usrquota
-
grpquota
如你所见,我们正在使用 xfs 文件系统。当使用 xfs 时,需要附加手动步骤。 /home 与 / 在同一磁盘上。进一步调查显示 / 设置了 noquota,这是内核级安装选项。我们必须重新配置内核启动选项。
As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps involved. /home is on the same disk as /. Further investigation shows / is set for noquota, which is a kernel level mounting option. We must re-configure our kernel boot options.
root@localhost rdc]# mount | grep ' / '
/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
[root@localhost rdc]#
Reconfiguring Kernel Boot Options for XFS File Systems
仅在以下两种情况下才需要此步骤:
This step is only necessary under two conditions −
-
When the disk/partition we are enabling quotas on, is using the xfs file system
-
When the kernel is passing noquota parameter to /etc/fstab at boot time
Step 1 − 备份 /etc/default/grub。
Step 1 − Make a backup of /etc/default/grub.
cp /etc/default/grub ~/
Step 2 − 修改 /etc/default/grub。
Step 2 − Modify /etc/default/grub.
以下是默认文件。
Here is the default file.
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet"
GRUB_DISABLE_RECOVERY="true"
我们要修改以下行:
We want to modify the following line −
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet"
更改为
to
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv
=cl/swap rhgb quiet rootflags=usrquota,grpquota"
Note − 正确无误地复制这些更改很重要。在我们重新配置 grub.cfg 后,如果配置中出现任何错误,系统将无法启动。请在非生产系统上尝试本教程的这一部分。
Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our system will fail to boot if any errors were made in the configuration. Please, try this part of the tutorial on a non-production system.
Step 3 − 备份你正在使用的 grub.cfg
Step 3 − Backup your working grub.cfg
cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak
制作一个新的 grub.cfg
Make a new grub.cfg
[root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd
Found initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img
done
[root@localhost rdc]#
重新启动
Reboot
[root@localhost rdc]#reboot
如果所有修改都精确无误,我们应该不会有向 xfs 文件系统添加配额的权限。
If all modifications were precise, we should not have the availability to add quotas to the xfs file system.
[rdc@localhost ~]$ mount | grep ' / '
/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota)
[rdc@localhost ~]$
我们通过 grub 传递了 usrquota 和 grpquota 参数。
We have passed the usrquota and grpquota parameters via grub.
现在,再次编辑 /etc/fstab 以包括 /home,因为 /home 与同一块物理磁盘有关。
Now, again edit /etc/fstab to include / since /homeon the same physical disk.
/dev/mapper/cl-root/xfs
defaults,usrquota,grpquota 0 0
现在,让我们启用配额数据库。
Now let’s enable the quota databases.
[root@localhost rdc]# quotacheck -acfvugM
确保启用配额。
Make sure Quotas are enabled.
[root@localhost rdc]# quotaon -ap
group quota on / (/dev/mapper/cl-root) is on
user quota on / (/dev/mapper/cl-root) is on
group quota on /home (/dev/mapper/cl-home) is on
user quota on /home (/dev/mapper/cl-home) is on
[root@localhost rdc]#
Remount the File System
如果分区或磁盘与正在启动的分区分离,我们可以重新装载而不必重新启动。如果某个磁盘/分区在根目录 / 中进行配置,我们需要重新启动操作系统。强制重新装载并应用更改,重新装载文件系统是必须的。
If the partition or disk is separate from the actively booted partition, we can remount without rebooting. If the quota was configured on a disk/partition booted in the root directory /, we may need to reboot the operating system. Forcing the remount and applying changes, the need to remount the filesystem may vary.
[rdc@localhost ~]$ df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/cl-root 22447404 4081860 18365544 19% /
devtmpfs 903448 0 903448 0% /dev
tmpfs 919308 100 919208 1% /dev/shm
tmpfs 919308 9180 910128 1% /run
tmpfs 919308 0 919308 0% /sys/fs/cgroup
/dev/sda2 1268736 176612 1092124 14% /boot
/dev/mapper/cl-var 4872192 158024 4714168 4% /var
/dev/mapper/cl-home 18475008 37284 18437724 1% /home
tmpfs 183864 8 183856 1% /run/user/1000
[rdc@localhost ~]$
就像我们看到的那样,LVM 卷正在使用。因此,简单地重新启动即可。这会重新装载 /home 并将 /etc/fstab 配置更改加载到活动配置中。
As we can see, LVM volumes are in use. So it’s simple to just reboot. This will remount /home and load the /etc/fstab configuration changes into active configuration.
Create Quota Database Files
CentOS 现在能够处理 /home 中的磁盘配额。要启用完全配额支持,我们必须运行 quotacheck 命令。
CentOS is now capable of working with disk quotas on /home. To enable full quota supprt, we must run the quotacheck command.
quotacheck 将创建两个文件 −
quotacheck will create two files −
-
aquota.user
-
aquota.group
这些文件用于存储已启用配额的磁盘/分区的配额信息。
These are used to store quota information for the quota enabled disks/partitions.
以下是常见的 quotacheck 开关。
Following are the common quotacheck switches.
Switch |
Action |
-u |
Checks for user quotas |
-g |
Checks for group quotas |
-c |
Quotas should be enabled for each file system with enables quotas |
-v |
Displays verbose output |
Add Quota Limits Per User
为此,我们将使用 edquota 命令,后跟用户名 −
For this, we will use the edquota command, followed by the username −
[root@localhost rdc]# edquota centos
Disk quotas for user centos (uid 1000):
Filesystem blocks soft hard inodes soft hard
/dev/mapper/cl-root 12 0 0 13 0 0
/dev/mapper/cl-home 4084 0 0 140 0 0
让我们看看每一列。
Let’s look at each column.
-
Filesystem − It is the filesystem quotas for the user applied to
-
blocks − How many blocks the user is currently using on each filesystem
-
soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period
-
hard − Set blocks for a hard limit. Hard limit is total allowable quota
-
inodes − How many inodes the user is currently using
-
soft − Soft inode limit
-
*hard * − Hard inode limit
以用户身份检查当前配额 −
To check our current quota as a user −
[centos@localhost ~]$ quota
Disk quotas for user centos (uid 1000):
Filesystem blocks quota limit grace files quota limit grace
/dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$
当超出硬配额限度时,系统会向用户发出以下错误。
Following is an error given to a user when the hard quota limit has exceeded.
[centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/
cp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE-
1611.iso.part’: Disk quota exceeded
[centos@localhost Downloads]$
正如我们所见,我们正在接近此用户的磁盘配额。我们设置一个软限制警告。这种方式,在配额限制到期之前,用户会提前收到通知。根据经验,当用户上班并需要花费 45 分钟来清除文件以便开始实际工作时,您会收到最终用户的投诉。
As we can see, we are closely within this user’s disk quota. Let’s set a soft limit warning. This way, the user will have advance notice before quota limits expire. From experience, you will get end-user complaints when they come into work and need to spend 45 minutes clearing files to actually get to work.
作为管理员,可以使用 repquota 命令来检查配额使用情况。
As an Administrator, we can check quota usage with the repquota command.
[root@localhost Downloads]# repquota /home
Block limits File limits
User used soft hard grace used soft hard grace
----------------------------------------------------------------------------------------
root -- 0 0 0 3 0 0
centos -+ 6189824 56123456 61234568 541 520 540 6days
[root@localhost Downloads]#
正如我们所见,用户 centos 已超出其硬块配额,并且无法在 /home 上使用任何更多磁盘空间。
As we can see, the user centos has exceeded their hard block quota and can no longer use any more disk space on /home.
-+ 表示已在文件系统上超过硬配额。
-+denotes a hard quota has been exceeded on the filesystem.
在规划配额时,有必要进行一些计算。管理员需要了解的是:系统上有多少用户?在用户/组之间分配多少可用空间?文件系统上的块由多少字节组成?
When planning quotas, it is necessary to do a little math. What an Administrator needs to know is:How many users are on the system? How much free space to allocate amongst users/groups? How many bytes make up a block on the file system?
根据自由磁盘与块相关的空间来定义配额。建议在文件系统上留出“安全”的可用空间缓冲区,以便在最坏的情况下仍然保留:同时超出所有配额。特别是在系统用于编写日志的分区上。
Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a "safe" buffer of free-space on the file system that will remain in worst case scenario: all quotas are simultaneously exceeded. This is especially on a partition that is used by the system for writing logs.
Systemd Services Start and Stop
systemd 是 Linux 中运行服务的新方法。systemd 已经取代 sysvinit。systemd 为 Linux 带来了更快的启动时间,并且现已成为管理 Linux 服务的标准方式。尽管稳定,systemd 仍在不断发展。
systemd is the new way of running services on Linux. systemd has a superceded sysvinit. systemd brings faster boot-times to Linux and is now, a standard way to manage Linux services. While stable, systemd is still evolving.
systemd 作为一个 init 系统,用于管理在 Linux 内核启动后需要更改状态的服务和守护进程。通过状态更改启动、停止、重新加载和调整服务的状态。
systemd as an init system, is used to manage both services and daemons that need status changes after the Linux kernel has been booted. By status change starting, stopping, reloading, and adjusting service state is applied.
首先,让我们检查一下服务器当前运行的 systemd 版本。
First, let’s check the version of systemd currently running on our server.
[centos@localhost ~]$ systemctl --version
systemd 219
+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP
+GCRYPT +GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN
[centos@localhost ~]$
在撰写本文时,CentOS 7 版本已完全更新,systemd 版本 219 是当前稳定版本。
As of CentOS version 7, fully updated at the time of this writing systemd version 219 is the current stable version.
我们还可以使用 systemd-analyze 分析服务器的最后一次启动时间
We can also analyze the last server boot time with systemd-analyze
[centos@localhost ~]$ systemd-analyze
Startup finished in 1.580s (kernel) + 908ms (initrd) + 53.225s (userspace) = 55.713s
[centos@localhost ~]$
当系统启动速度较慢时,可以使用 systemd-analyze blame 命令。
When the system boot times are slower, we can use the systemd-analyze blame command.
[centos@localhost ~]$ systemd-analyze blame
40.882s kdump.service
5.775s NetworkManager-wait-online.service
4.701s plymouth-quit-wait.service
3.586s postfix.service
3.121s systemd-udev-settle.service
2.649s tuned.service
1.848s libvirtd.service
1.437s network.service
875ms packagekit.service
855ms gdm.service
514ms firewalld.service
438ms rsyslog.service
436ms udisks2.service
398ms sshd.service
360ms boot.mount
336ms polkit.service
321ms accounts-daemon.service
在使用 systemd 时,了解单元的概念非常重要。 Units 是 systemd 了解如何解释的资源。单元被分为 12 类,如下所示 −
When working with systemd, it is important to understand the concept of units. Units are the resources systemd knows how to interpret. Units are categorized into 12 types as follows −
-
.service
-
.socket
-
.device
-
.mount
-
.automount
-
.swap
-
.target
-
.path
-
.timer
-
.snapshot
-
.slice
-
.scope
在大多数情况下,我们将把 .service 作为单元目标。建议对其他类型进行进一步的研究。因为只有 .service 单元适用于启动和停止 systemd 服务。
For the most part, we will be working with .service as unit targets. It is recommended to do further research on the other types. As only .service units will apply to starting and stopping systemd services.
每个单元都在位于以下位置的文件中定义 −
Each unit is defined in a file located in either −
-
/lib/systemd/system − base unit files
-
/etc/systemd/system − modified unit files started at run-time
Manage Services with systemctl
要使用 systemd,我们需要非常熟悉 systemctl 命令。以下是 systemctl 最常用的命令行开关。
To work with systemd, we will need to get very familiar with the systemctl command. Following are the most common command line switches for systemctl.
Switch |
Action |
-t |
Comma separated value of unit types such as service or socket |
-a |
Shows all loaded units |
--state |
Shows all units in a defined state, either: load, sub, active, inactive, etc.. |
-H |
Executes operation remotely. Specify Host name or host and user separated by @. |
Basic systemctl Usage
systemctl [operation]
example: systemctl --state [servicename.service]
快速查看在我们主机上运行的所有服务。
For a quick look at all the services running on our box.
[root@localhost rdc]# systemctl -t service
UNIT LOAD ACTIVE SUB DESCRIPTION
abrt-ccpp.service loaded active exited Install ABRT coredump hook
abrt-oops.service loaded active running ABRT kernel log watcher
abrt-xorg.service loaded active running ABRT Xorg log watcher
abrtd.service loaded active running ABRT Automated Bug Reporting Tool
accounts-daemon.service loaded active running Accounts Service
alsa-state.service loaded active running Manage Sound Card State (restore and store)
atd.service loaded active running Job spooling tools
auditd.service loaded active running Security Auditing Service
avahi-daemon.service loaded active running Avahi mDNS/DNS-SD Stack
blk-availability.service loaded active exited Availability of block devices
bluetooth.service loaded active running Bluetooth service
chronyd.service loaded active running NTP client/server
Stopping a Service
首先,停止蓝牙服务。
Let’s first, stop the bluetooth service.
[root@localhost]# systemctl stop bluetooth
[root@localhost]# systemctl --all -t service | grep bluetooth
bluetooth.service loaded inactive dead Bluetooth service
[root@localhost]#
如我们所见,蓝牙服务现在处于非激活状态。
As we can see, the bluetooth service is now inactive.
再次启动蓝牙服务。
To start the bluetooth service again.
[root@localhost]# systemctl start bluetooth
[root@localhost]# systemctl --all -t service | grep bluetooth
bluetooth.service loaded active running Bluetooth service
[root@localhost]#
Note − 我们没有指定 bluetooth.service,因为 .service 是隐含的。将处理服务追加到单元类型中是一种好习惯。因此,从这里开始,我们将使用 .service 扩展名来明确我们正在处理服务单元操作。
Note − We didn’t specify bluetooth.service, since the .service is implied. It is a good practice to think of the unit type appending the service we are dealing with. So, from here on, we will use the .service extension to clarify we are working on service unit operations.
可以在服务上执行的主要操作包括 −
The primary actions that can be performed on a service are −
Start |
Starts the service |
Stop |
Stops a service |
Reload |
Reloads the active configuration of a service w/o stopping it (like kill -HUP in system v init) |
Restart |
Starts, then stops a service |
Enable |
Starts a service at boot time |
Disable |
Stops a service from automatically starting at run time |
上述操作主要用于以下场景 −
The above actions are primarily used in the following scenarios −
Start |
To bring a service up that has been put in the stopped state. |
Stop |
To temporarily shut down a service (for example when a service must be stopped to access files locked by the service, as when upgrading the service) |
Reload |
When a configuration file has been edited and we want to apply the new changes while not stopping the service. |
Restart |
In the same scenario as reload, but the service does not support reload. |
Enable |
When we want a disabled service to run at boot time. |
Disable |
Used primarily when there is a need to stop a service, but it starts on boot. |
检查服务的当前状态 −
To check the status of a service −
[root@localhost]# systemctl status network.service
network.service - LSB: Bring up/down networking
Loaded: loaded (/etc/rc.d/init.d/network; bad; vendor preset: disabled)
Active: active (exited) since Sat 2017-01-14 04:43:48 EST; 1min 31s ago
Docs: man:systemd-sysv-generator(8)
Process: 923 ExecStart = /etc/rc.d/init.d/network start (code=exited, status = 0/SUCCESS)
localhost.localdomain systemd[1]: Starting LSB: Bring up/down networking...
localhost.localdomain network[923]: Bringing up loopback interface: [ OK ]
localhost.localdomain systemd[1]: Started LSB: Bring up/down networking.
[root@localhost]#
向我们展示网络服务的当前状态。如果我们想看到所有与网络相关的服务,我们可以使用 −
Show us the current status of the networking service. If we want to see all the services related to networking, we can use −
[root@localhost]# systemctl --all -t service | grep -i network
network.service loaded active exited LSB: Bring up/
NetworkManager-wait-online.service loaded active exited Network Manager
NetworkManager.service loaded active running Network Manager
ntpd.service loaded inactive dead Network Time
rhel-import-state.service loaded active exited Import network
[root@localhost]#
对于熟悉 sysinit 管理服务方法的人来说,向 systemd 过渡很重要。systemd 是在 Linux 中启动和停止守护进程服务的新方式。
For those familiar with the sysinit method of managing services, it is important to make the transition to systemd. systemd is the new way starting and stopping daemon services in Linux.
Linux Admin - Resource Mgmt with systemctl
systemctl 是用于控制 systemd 的实用程序。systemctl 为 CentOS 管理员提供了在 systemd 上执行多项操作的能力,包括:
systemctl is the utility used to control systemd. systemctl provides CentOS administrators with the ability to perform a multitude of operations on systemd including −
-
Configure systemd units
-
Get status of systemd untis
-
Start and stop services
-
Enable / disable systemd services for runtime, etc.
systemctl 的命令语法相当简单,但可能会混淆选项和开关。我们将介绍最基本的 systemd 功能,适用于 CentOS Linux 的管理。
The command syntax for systemctl is pretty basic, but can tangle with switches and options. We will present the most essential functions of systemctl needed for administering CentOS Linux.
Basic systemctl syntax:
systemctl [OPTIONS] COMMAND [NAME]
以下是 systemctl 常用的命令:
Following are the common commands used with systemctl −
-
start
-
stop
-
restart
-
reload
-
status
-
is-active
-
list-units
-
enable
-
disable
-
cat
-
show
以上我们已经通过 systemctl 讨论了 start、stop、reload、restart、enable 和 disable 命令,现在让我们进一步了解剩余的常用命令。
We have already discussed start, stop, reload, restart, enable and disable with systemctl. So let’s go over the remaining commonly used commands.
status
在最简单的形式中,status 命令可以用来查看整体系统状态,就像下例所示:
In its most simple form, the status command can be used to see the system status as a whole −
[root@localhost rdc]# systemctl status
● localhost.localdomain
State: running
Jobs: 0 queued
Failed: 0 units
Since: Thu 2017-01-19 19:14:37 EST; 4h 5min ago
CGroup: /
├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
├─user.slice
│ └─user-1002.slice
│ └─session-1.scope
│ ├─2869 gdm-session-worker [pam/gdm-password]
│ ├─2881 /usr/bin/gnome-keyring-daemon --daemonize --login
│ ├─2888 gnome-session --session gnome-classic
│ ├─2895 dbus-launch --sh-syntax --exit-with-session
上面的输出已经简化。在实际中,systemctl status 将输出大约 100 行树状进程状态。
The above output has been condensed. In the real-world systemctl status will output about 100 lines of treed process statuses.
假设我们要检查防火墙服务的 – 状态
Let’s say we want to check the status of our firewall service −
[root@localhost rdc]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2017-01-19 19:14:55 EST; 4h 12min ago
Docs: man:firewalld(1)
Main PID: 825 (firewalld)
CGroup: /system.slice/firewalld.service
└─825 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
如你所见,我们的防火墙服务目前处于活动状态,且已经运行超过 4 小时。
As you see, our firewall service is currently active and has been for over 4 hours.
list-units
list-units 命令允许我们列出所有特定类型单元。让我们检查 systemctl 管理的套接字:
The list-units command allows us to list all the units of a certain type. Let’s check for sockets managed by systemd −
[root@localhost]# systemctl list-units --type=socket
UNIT LOAD ACTIVE SUB DESCRIPTION
avahi-daemon.socket loaded active running Avahi mDNS/DNS-SD Stack Activation Socket
cups.socket loaded active running CUPS Printing Service Sockets
dbus.socket loaded active running D-Bus System Message Bus Socket
dm-event.socket loaded active listening Device-mapper event daemon FIFOs
iscsid.socket loaded active listening Open-iSCSI iscsid Socket
iscsiuio.socket loaded active listening Open-iSCSI iscsiuio Socket
lvm2-lvmetad.socket loaded active running LVM2 metadata daemon socket
lvm2-lvmpolld.socket loaded active listening LVM2 poll daemon socket
rpcbind.socket loaded active listening RPCbind Server Activation Socket
systemd-initctl.socket loaded active listening /dev/initctl Compatibility Named Pipe
systemd-journald.socket loaded active running Journal Socket
systemd-shutdownd.socket loaded active listening Delayed Shutdown Socket
systemd-udevd-control.socket loaded active running udev Control Socket
systemd-udevd-kernel.socket loaded active running udev Kernel Socket
virtlockd.socket loaded active listening Virtual machine lock manager socket
virtlogd.socket loaded active listening Virtual machine log manager socket
现在让我们检查当前运行中的服务:
Now let’s check the current running services −
[root@localhost rdc]# systemctl list-units --type=service
UNIT LOAD ACTIVE SUB DESCRIPTION
abrt-ccpp.service loaded active exited Install ABRT coredump hook
abrt-oops.service loaded active running ABRT kernel log watcher
abrt-xorg.service loaded active running ABRT Xorg log watcher
abrtd.service loaded active running ABRT Automated Bug Reporting Tool
accounts-daemon.service loaded active running Accounts Service
alsa-state.service loaded active running Manage Sound Card State (restore and store)
atd.service loaded active running Job spooling tools
auditd.service loaded active running Security Auditing Service
is-active
is-active 命令是 systemctl 命令的一个示例,它旨在返回某个单元的状态信息。
The is-active command is an example of systemctl commands designed to return the status information of a unit.
[root@localhost rdc]# systemctl is-active ksm.service
active
cat
cat 是一个很少使用的命令。与其在 shell 中使用 cat 并键入单元文件的路径,不如直接使用 systemctl cat。
cat is one of the seldomly used command. Instead of using cat at the shell and typing the path to a unit file, simply use systemctl cat.
[root@localhost]# systemctl cat firewalld
# /usr/lib/systemd/system/firewalld.service
[Unit]
Description=firewalld - dynamic firewall daemon
Before=network.target
Before=libvirtd.service
Before = NetworkManager.service
After=dbus.service
After=polkit.service
Conflicts=iptables.service ip6tables.service ebtables.service ipset.service
Documentation=man:firewalld(1)
[Service]
EnvironmentFile = -/etc/sysconfig/firewalld
ExecStart = /usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS
ExecReload = /bin/kill -HUP $MAINPID
# supress to log debug and error output also to /var/log/messages
StandardOutput = null
StandardError = null
Type = dbus
BusName = org.fedoraproject.FirewallD1
[Install]
WantedBy = basic.target
Alias = dbus-org.fedoraproject.FirewallD1.service
[root@localhost]#
现在我们已经更详细地了解了 systemctl 和 systemd,让我们使用它们来管理 cgroups 或控制组中的资源。
Now that we have explored both systemd and systemctl in more detail, let’s use them to manage the resources in cgroups or control groups.
Linux Admin - Resource Mgmt with crgoups
cgroups 或控制组是 Linux 内核的一项功能,它允许管理员为服务和群组分配或限制系统资源。
cgroups or Control Groups are a feature of the Linux kernel that allows an administrator to allocate or cap the system resources for services and also group.
要列出正在运行的活动控制组,可以使用以下 ps 命令 −
To list active control groups running, we can use the following ps command −
[root@localhost]# ps xawf -eo pid,user,cgroup,args
8362 root - \_ [kworker/1:2]
1 root - /usr/lib/systemd/systemd --switched-
root --system -- deserialize 21
507 root 7:cpuacct,cpu:/system.slice /usr/lib/systemd/systemd-journald
527 root 7:cpuacct,cpu:/system.slice /usr/sbin/lvmetad -f
540 root 7:cpuacct,cpu:/system.slice /usr/lib/systemd/systemd-udevd
715 root 7:cpuacct,cpu:/system.slice /sbin/auditd -n
731 root 7:cpuacct,cpu:/system.slice \_ /sbin/audispd
734 root 7:cpuacct,cpu:/system.slice \_ /usr/sbin/sedispatch
737 polkitd 7:cpuacct,cpu:/system.slice /usr/lib/polkit-1/polkitd --no-debug
738 rtkit 6:memory:/system.slice/rtki /usr/libexec/rtkit-daemon
740 dbus 7:cpuacct,cpu:/system.slice /bin/dbus-daemon --system --
address=systemd: --nofork --nopidfile --systemd-activation
在 CentOS 6.X 中,资源管理已通过 systemd init 实现重新定义。当考虑服务资源管理时,主要要注意的是 cgroups。 cgroups 已随着 systemd 在功能和简单性上得到提升。
Resource Management, as of CentOS 6.X, has been redefined with the systemd init implementation. When thinking Resource Management for services, the main thing to focus on are cgroups. cgroups have advanced with systemd in both functionality and simplicity.
资源管理中 cgroups 的目标是 - 不允许任何一项服务全部拖垮系统。或者,任何一项服务进程(也许是一个编写很糟糕的 PHP 脚本)都不会因为消耗过多资源而损害服务器功能。
The goal of cgroups in resource management is -no one service can take the system, as a whole, down. Or no single service process (perhaps a poorly written PHP script) will cripple the server functionality by consuming too many resources.
cgroup 允许对下列资源的单元进行资源控制 −
cgroups allow resource control of units for the following resources −
-
CPU − Limit cpu intensive tasks that are not critical as other, less intensive tasks
-
Memory − Limit how much memory a service can consume
-
Disks − Limit disk i/o
CPU 时间:
*CPU Time: *
需要较低 CPU 优先级的任务可以拥有自定义配置的 CPU 片段。
Tasks needing less CPU priority can have custom configured CPU Slices.
举例来说,我们来看看以下两个服务。
Let’s take a look at the following two services for example.
Polite CPU Service 1
[root@localhost]# systemctl cat polite.service
# /etc/systemd/system/polite.service
[Unit]
Description = Polite service limits CPU Slice and Memory
After=remote-fs.target nss-lookup.target
[Service]
MemoryLimit = 1M
ExecStart = /usr/bin/sha1sum /dev/zero
ExecStop = /bin/kill -WINCH ${MAINPID}
WantedBy=multi-user.target
# /etc/systemd/system/polite.service.d/50-CPUShares.conf
[Service]
CPUShares = 1024
[root@localhost]#
Evil CPU Service 2
[root@localhost]# systemctl cat evil.service
# /etc/systemd/system/evil.service
[Unit]
Description = I Eat You CPU
After=remote-fs.target nss-lookup.target
[Service]
ExecStart = /usr/bin/md5sum /dev/zero
ExecStop = /bin/kill -WINCH ${MAINPID}
WantedBy=multi-user.target
# /etc/systemd/system/evil.service.d/50-CPUShares.conf
[Service]
CPUShares = 1024
[root@localhost]#
让我们使用较低的 CPU 优先级来设置 Polite Service:
Let’s set Polite Service using a lesser CPU priority −
systemctl set-property polite.service CPUShares = 20
/system.slice/polite.service
1 70.5 124.0K - -
/system.slice/evil.service
1 99.5 304.0K - -
正如我们所看到的,在正常的系统空闲时间里,这两个恶意进程仍在使用 CPU 周期。然而,设置使用更少时间片段的那个正在消耗更少的 CPU 时间。带着这点考虑,我们可以看到,使用更少的时间片段将会允许关键任务更好的访问系统资源。
As we can see, over a period of normal system idle time, both rogue processes are still using CPU cycles. However, the one set to have less time-slices is using less CPU time. With this in mind, we can see how using a lesser time time-slice would allow essential tasks better access the system resources.
为了为每一种资源设置服务,set-property 方法定义了以下参数:
To set services for each resource, the set-property method defines the following parameters −
systemctl set-property name parameter=value
CPU Slices |
CPUShares |
Memory Limit |
MemoryLimit |
Soft Memory Limit |
MemorySoftLimit |
Block IO Weight |
BlockIOWeight |
Block Device Limit (specified in /volume/path) ) |
BlockIODeviceWeight |
Read IO |
BlockIOReadBandwidth |
Disk Write IO |
BlockIOReadBandwidth |
大多数情况下,服务将受到 CPU 使用情况、内存限制和读/写 I/O 的限制。
Most often services will be limited by CPU use, Memory limits and Read / Write IO.
在更改每个方法之后,都有必要重新加载 systemd,并重新启动服务:
After changing each, it is necessary to reload systemd and restart the service −
systemctl set-property foo.service CPUShares = 250
systemctl daemon-reload
systemctl restart foo.service
Configure CGroups in CentOS Linux
要在 CentOS Linux 中创建自定义 cgroup,我们首先需要安装服务并对其进行配置。
To make custom cgroups in CentOS Linux, we need to first install services and configure them.
Step 1 - 安装 libcgroup(如果尚未安装)。
Step 1 − Install libcgroup (if not already installed).
[root@localhost]# yum install libcgroup
Package libcgroup-0.41-11.el7.x86_64 already installed and latest version
Nothing to do
[root@localhost]#
如我们所见,CentOS 7 默认安装了 libcgroup,使用万能安装程序。使用最小安装程序将要求我们安装 libcgroup 实用程序以及任何依赖项。
As we can see, by default CentOS 7 has libcgroup installed with the everything installer. Using a minimal installer will require us to install the libcgroup utilities along with any dependencies.
Step 2 - 启动并启用 cgconfig 服务。
Step 2 − Start and enable the cgconfig service.
[root@localhost]# systemctl enable cgconfig
Created symlink from /etc/systemd/system/sysinit.target.wants/cgconfig.service to /usr/lib/systemd/system/cgconfig.service.
[root@localhost]# systemctl start cgconfig
[root@localhost]# systemctl status cgconfig
● cgconfig.service - Control Group configuration service
Loaded: loaded (/usr/lib/systemd/system/cgconfig.service; enabled; vendor preset: disabled)
Active: active (exited) since Mon 2017-01-23 02:51:42 EST; 1min 21s ago
Main PID: 4692 (code=exited, status = 0/SUCCESS)
Memory: 0B
CGroup: /system.slice/cgconfig.service
Jan 23 02:51:42 localhost.localdomain systemd[1]: Starting Control Group configuration service...
Jan 23 02:51:42 localhost.localdomain systemd[1]: Started Control Group configuration service.
[root@localhost]#
Linux Admin - Process Management
以下是与进程管理一起使用的常用命令:bg、fg、nohup、ps、pstree、top、kill、killall、free、uptime、nice。
Following are the common commands used with Process Management–bg, fg, nohup, ps, pstree, top, kill, killall, free, uptime, nice.
Work with Processes
Quick Note: Process PID in Linux
Quick Note: Process PID in Linux
在 Linux 中,每个正在运行的进程都被赋予一个 PID 或进程 ID 号码。这个 PID 就是 CentOS 识别特定进程的方式。正如我们所讨论的,systemd 是第一个启动的进程并在 CentOS 中被赋予 PID 1。
In Linux every running process is given a PID or Process ID Number. This PID is how CentOS identifies a particular process. As we have discussed, systemd is the first process started and given a PID of 1 in CentOS.
Pgrep 用于获取给定进程名称的 Linux PID。
Pgrep is used to get Linux PID for a given process name.
[root@CentOS]# pgrep systemd
1
[root@CentOS]#
如你所见,pgrep 命令返回了 systemd 的当前 PID。
As seen, the pgrep command returns the current PID of systemd.
Basic CentOS Process and Job Management in CentOS
在 Linux 中处理进程时,了解如何在命令行中执行基本的前台和后台进程非常重要。
When working with processes in Linux it is important to know how basic foregrounding and backgrounding processes is performed at the command line.
-
fg − Bringsthe process to the foreground
-
bg − Movesthe process to the background
-
jobs − List of the current processes attached to the shell
-
ctrl+z − Control + z key combination to sleep the current process
-
& − Startsthe process in the background
我们从使用 shell 命令 sleep 入手。 sleep 将仅仅按照它的命名,休眠一段时间:sleep。
Let’s start using the shell command sleep. sleep will simply do as it is named, sleep for a defined period of time: sleep.
[root@CentOS ~]$ jobs
[root@CentOS ~]$ sleep 10 &
[1] 12454
[root@CentOS ~]$ sleep 20 &
[2] 12479
[root@CentOS ~]$ jobs
[1]- Running sleep 10 &
[2]+ Running sleep 20 &
[cnetos@CentOS ~]$
现在,我们将第一个作业置于前台 −
Now, let’s bring the first job to the foreground −
[root@CentOS ~]$ fg 1
sleep 10
如果你有留意,你便会注意到前台作业卡在你的 shell 中了。现在,我们将进程设为休眠,然后在后台重新启用它。
If you are following along, you’ll notice the foreground job is stuck in your shell. Now, let’s put the process to sleep, then re-enable it in the background.
-
Hit control+z
-
Type: bg 1, sending the first job into the background and starting it.
[root@CentOS ~]$ fg 1
sleep 20
^Z
[1]+ Stopped sleep 20
[root@CentOS ~]$ bg 1
[1]+ sleep 20 &
[root@CentOS ~]$
nohup
在从 shell 或终端进行操作时,值得注意的是,默认情况下,当 shell 关闭或用户注销时,附加至 shell 的所有进程和作业都会终止。在使用 nohup 时,如果用户注销或关闭附加该进程的 shell,进程将继续运行。
When working from a shell or terminal, it is worth noting that by default all the processes and jobs attached to the shell will terminate when the shell is closed or the user logs out. When using nohup the process will continue to run if the user logs out or closes the shell to which the process is attached.
[root@CentOS]# nohup ping www.google.com &
[1] 27299
nohup: ignoring input and appending output to ‘nohup.out’
[root@CentOS]# pgrep ping
27299
[root@CentOS]# kill -KILL `pgrep ping`
[1]+ Killed nohup ping www.google.com
[root@CentOS rdc]# cat nohup.out
PING www.google.com (216.58.193.68) 56(84) bytes of data.
64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 1 ttl = 128
time = 51.6 ms
64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 2 ttl = 128
time = 54.2 ms
64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 3 ttl = 128
time = 52.7 ms
ps Command
ps 命令通常由管理员使用,以调查特定进程的快照。ps 通常与 grep 配合使用,以筛选出特定进程进行分析。
The ps command is commonly used by administrators to investigate snapshots of a specific process. ps is commonly used with grep to filter out a specific process to analyze.
[root@CentOS ~]$ ps axw | grep python
762 ? Ssl 0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork -nopid
1296 ? Ssl 0:00 /usr/bin/python -Es /usr/sbin/tuned -l -P
15550 pts/0 S+ 0:00 grep --color=auto python
在上方的命令中,我们看到了所有使用 Python 解释器的进程。结果中还包含我们的 grep 命令,它查找字符串 python。
In the above command, we see all the processes using the python interpreter. Also included with the results were our grep command, looking for the string python.
以下是与 ps 配合使用时最常见的命令行开关。
Following are the most common command line switches used with ps.
Switch |
Action |
a |
Excludes constraints of only the reporting processes for the current user |
x |
Shows processes not attached to a tty or shell |
w |
Formats wide output display of the output |
e |
Shows environment after the command |
-e |
Selects all processes |
-o |
User-defined formatted output |
-u |
Shows all processes by a specific user |
-C |
Shows all processes by name or process id |
--sort |
Sorts the processes by definition |
查看 nobody 用户正在使用的所有进程
To see all processes in use by the nobody user −
[root@CentOS ~]$ ps -u nobody
PID TTY TIME CMD
1853 ? 00:00:00 dnsmasq
[root@CentOS ~]$
查看 firewalld 进程的所有信息
To see all information about the firewalld process −
[root@CentOS ~]$ ps -wl -C firewalld
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 0 762 1 0 80 0 - 81786 poll_s ? 00:00:01 firewalld
[root@CentOS ~]$
让我们看看哪些进程消耗的内存最多
Let’s see which processes are consuming the most memory −
[root@CentOS ~]$ ps aux --sort=-pmem | head -10
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
cnetos 6130 0.7 5.7 1344512 108364 ? Sl 02:16 0:29 /usr/bin/gnome-shell
cnetos 6449 0.0 3.4 1375872 64440 ? Sl 02:16 0:00 /usr/libexec/evolution-calendar-factory
root 5404 0.6 2.1 190256 39920 tty1 Ssl+ 02:15 0:27 /usr/bin/Xorg :0 -background none -noreset -audit 4 -verbose -auth /run/gdm/auth-for-gdm-iDefCt/database -seat seat0 -nolisten tcp vt1
cnetos 6296 0.0 1.7 1081944 32136 ? Sl 02:16 0:00 /usr/libexec/evolution/3.12/evolution-alarm-notify
cnetos 6350 0.0 1.5 560728 29844 ? Sl 02:16 0:01 /usr/bin/prlsga
cnetos 6158 0.0 1.4 1026956 28004 ? Sl 02:16 0:00 /usr/libexec/gnome-shell-calendar-server
cnetos 6169 0.0 1.4 1120028 27576 ? Sl 02:16 0:00 /usr/libexec/evolution-source-registry
root 762 0.0 1.4 327144 26724 ? Ssl 02:09 0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
cnetos 6026 0.0 1.4 1090832 26376 ? Sl 02:16 0:00 /usr/libexec/gnome-settings-daemon
[root@CentOS ~]$
查看用户 centos 的所有进程,并格式化,显示自定义输出
See all the processes by user centos and format, displaying the custom output −
[cnetos@CentOS ~]$ ps -u cnetos -o pid,uname,comm
PID USER COMMAND
5802 centos gnome-keyring-d
5812 cnetos gnome-session
5819 cnetos dbus-launch
5820 cnetos dbus-daemon
5888 cnetos gvfsd
5893 cnetos gvfsd-fuse
5980 cnetos ssh-agent
5996 cnetos at-spi-bus-laun
pstree Command
pstree 与 ps 类似,但并不常用。它以更清晰的树状模式显示进程。
pstree is similar to ps but is not often used. It displays the processes in a neater tree fashion.
[centos@CentOS ~]$ pstree
systemd─┬─ModemManager───2*[{ModemManager}]
├─NetworkManager─┬─dhclient
│ └─2*[{NetworkManager}]
├─2*[abrt-watch-log]
├─abrtd
├─accounts-daemon───2*[{accounts-daemon}]
├─alsactl
├─at-spi-bus-laun─┬─dbus-daemon───{dbus-daemon}
│ └─3*[{at-spi-bus-laun}]
├─at-spi2-registr───2*[{at-spi2-registr}]
├─atd
├─auditd─┬─audispd─┬─sedispatch
│ │ └─{audispd}
│ └─{auditd}
├─avahi-daemon───avahi-daemon
├─caribou───2*[{caribou}]
├─cgrulesengd
├─chronyd
├─colord───2*[{colord}]
├─crond
├─cupsd
pstree 的总输出可能超过 100 行。通常,ps 将提供更有用的信息。
The total output from pstree can exceed 100 lines. Usually, ps will give more useful information.
top Command
在解决 Linux 性能问题时, top 是最常用的命令之一。它适用于 Linux 中的实时统计和进程监控。以下是从命令行中调出时 top 的默认输出。
top is one of the most often used commands when troubleshooting performance issues in Linux. It is useful for real-time stats and process monitoring in Linux. Following is the default output of top when brought up from the command line.
Tasks: 170 total, 1 running, 169 sleeping, 0 stopped, 0 zombie
%Cpu(s): 2.3 us, 2.0 sy, 0.0 ni, 95.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 1879668 total, 177020 free, 607544 used, 1095104 buff/cache
KiB Swap: 3145724 total, 3145428 free, 296 used. 1034648 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
5404 root 20 0 197832 48024 6744 S 1.3 2.6 1:13.22 Xorg
8013 centos 20 0 555316 23104 13140 S 1.0 1.2 0:14.89 gnome-terminal-
6339 centos 20 0 332336 6016 3248 S 0.3 0.3 0:23.71 prlcc
6351 centos 20 0 21044 1532 1292 S 0.3 0.1 0:02.66 prlshprof
在运行 top 时用到的常用热键(在 shell 中运行 top 时,按相应键即可访问热键)。
Common hot keys used while running top (hot keys are accessed by pressing the key as top is running in your shell).
Command |
Action |
b |
Enables / disables bold highlighting on top menu |
z |
Cycles the color scheme |
l |
Cycles the load average heading |
m |
Cycles the memory average heading |
t |
Task information heading |
h |
Help menu |
Shift+F |
Customizes sorting and display fields |
以下是 top 中的常用命令行开关。
Following are the common command line switches for top.
Command |
Action |
-o |
Sorts by column (can prepend with - or + to sort ascending or descending) |
-u |
Shows only processes from a specified user |
-d |
Updates the delay time of top |
-O |
Returns a list of columns which top can apply sorting |
top 中的排序选项屏幕,使用 Shift+F 呈现。此屏幕允许在 top 中对显示和排序选项进行自定义。
Sorting options screen in top, presented using Shift+F. This screen allows customization of top display and sort options.
Fields Management for window 1:Def, whose current sort field is %MEM
Navigate with Up/Dn, Right selects for move then <Enter> or Left commits,
'd' or <Space> toggles display, 's' sets sort. Use 'q' or <Esc> to end!
* PID = Process Id TGID = Thread Group Id
* USER = Effective User Name ENVIRON = Environment vars
* PR = Priority vMj = Major Faults delta
* NI = Nice Value vMn = Minor Faults delta
* VIRT = Virtual Image (KiB) USED = Res+Swap Size (KiB)
* RES = Resident Size (KiB) nsIPC = IPC namespace Inode
* SHR = Shared Memory (KiB) nsMNT = MNT namespace Inode
* S = Process Status nsNET = NET namespace Inode
* %CPU = CPU Usage nsPID = PID namespace Inode
* %MEM = Memory Usage (RES) nsUSER = USER namespace Inode
* TIME+ = CPU Time, hundredths nsUTS = UTS namespace Inode
* COMMAND = Command Name/Line
PPID = Parent Process pid
UID = Effective User Id
top,显示用户 rdc 的进程,并按内存使用量排序 −
top, showing the processes for user rdc and sorted by memory usage −
PID USER %MEM PR NI VIRT RES SHR S %CPU TIME+ COMMAND
6130 rdc 6.2 20 0 1349592 117160 33232 S 0.0 1:09.34 gnome-shell
6449 rdc 3.4 20 0 1375872 64428 21400 S 0.0 0:00.43 evolution-calen
6296 rdc 1.7 20 0 1081944 32140 22596 S 0.0 0:00.40 evolution-alarm
6350 rdc 1.6 20 0 560728 29844 4256 S 0.0 0:10.16 prlsga
6281 rdc 1.5 20 0 1027176 28808 17680 S 0.0 0:00.78 nautilus
6158 rdc 1.5 20 0 1026956 28004 19072 S 0.0 0:00.20 gnome-shell-cal
显示有效的 top 字段(概览) −
Showing valid top fields (condensed) −
[centos@CentOS ~]$ top -O
PID
PPID
UID
USER
RUID
RUSER
SUID
SUSER
GID
GROUP
PGRP
TTY
TPGID
kill Command
kill 命令用于通过其 PID 从命令 shell 终止进程。终止进程时,我们需要指定要发送的信号。信号让内核了解我们希望如何结束进程。最常用的信号是 −
The kill command is used to kill a process from the command shell via its PID. When killing a process, we need to specify a signal to send. The signal lets the kernel know how we want to end the process. The most commonly used signals are −
-
SIGTERM is implied as the kernel lets a process know it should stop soon as it is safe to do so. SIGTERM gives the process an opportunity to exit gracefully and perform safe exit operations.
-
SIGHUP most daemons will restart when sent SIGHUP. This is often used on the processes when changes have been made to a configuration file.
-
SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The kernel needs an option to end a process that will not comply with requests. When a process is hung, the SIGKILL option is used to shut the process down explicitly.
对于可以使用 kill 发送的所有信号列表,可以使用 -l 选项 −
For a list off all signals that can be sent with kill the -l option can be used −
[root@CentOS]# kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
[root@CentOS rdc]#
使用 SIGHUP 来重启系统。
Using SIGHUP to restart system.
[root@CentOS]# pgrep systemd
1
464
500
643
15071
[root@CentOS]# kill -HUP 1
[root@CentOS]# pgrep systemd
1
464
500
643
15196
15197
15198
[root@CentOS]#
pkill 允许管理员按进程名称发送 kill 信号。
pkill will allow the administrator to send a kill signal by the process name.
[root@CentOS]# pgrep ping
19450
[root@CentOS]# pkill -9 ping
[root@CentOS]# pgrep ping
[root@CentOS]#
killall 将终止所有进程。小心以 root 身份使用 killall,因为它会终止所有用户的进程。
killall will kill all the processes. Be careful using killall as root, as it will kill all the processes for all users.
[root@CentOS]# killall chrome
free Command
free 是一个非常简单的命令,通常用于快速查看系统的内存。它显示已使用的物理内存和交换内存的总量。
free is a pretty simple command often used to quickly check the memory of a system. It displays the total amount of used physical and swap memory.
[root@CentOS]# free
total used free shared buff/cache available
Mem: 1879668 526284 699796 10304 653588 1141412
Swap: 3145724 0 3145724
[root@CentOS]#
nice Command
nice 允许管理员根据 CPU 使用情况设置进程的调度优先级。基本上,niceness 是内核将如何为进程或作业调度 CPU 时间片的。默认情况下,假定进程对 CPU 资源的访问权相同。
nice will allow an administrator to set the scheduling priority of a process in terms of CPU usages. The niceness is basically how the kernel will schedule CPU time slices for a process or job. By default, it is assumed the process is given equal access to CPU resources.
首先,让我们使用 top 查看当前正在运行的进程的优先级。
First, let’s use top to check the niceness of the currently running processes.
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
28 root 39 19 0 0 0 S 0.0 0.0 0:00.17 khugepaged
690 root 39 19 16808 1396 1164 S 0.0 0.1 0:00.01 alsactl]
9598 rdc 39 19 980596 21904 10284 S 0.0 1.2 0:00.27 tracker-extract
9599 rdc 39 19 469876 9608 6980 S 0.0 0.5 0:00.04 tracker-miner-a
9609 rdc 39 19 636528 13172 8044 S 0.0 0.7 0:00.12 tracker-miner-f
9611 rdc 39 19 469620 8984 6496 S 0.0 0.5 0:00.02 tracker-miner-u
27 root 25 5 0 0 0 S 0.0 0.0 0:00.00 ksmd
637 rtkit 21 1 164648 1276 1068 S 0.0 0.1 0:00.11 rtkit-daemon
1 root 20 0 128096 6712 3964 S 0.3 0.4 0:03.57 systemd
2 root 20 0 0 0 0 S 0.0 0.0 0:00.01 kthreadd
3 root 20 0 0 0 0 S 0.0 0.0 0:00.50 ksoftirqd/0
7 root 20 0 0 0 0 S 0.0 0.0 0:00.00 migration/0
8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh
9 root 20 0 0 0 0 S 0.0 0.0 0:02.07 rcu_sched
我们希望关注 NI 所描绘的 NICE 列。niceness 范围可以在 -20 到正 19 之间。-20 表示给予的最高优先级。
We want to focus on the NICE column depicted by NI. The niceness range can be anywhere between -20 to positive 19. -20 represents the highest given priority.
nohup nice --20 ping www.google.com &
Linux Admin - Firewall Setup
firewalld 是 CentOS 上用于 iptables 的默认前端控制器。与原始 iptables 相比,firewalld 前端有两个主要优点 −
firewalld is the default front-end controller for iptables on CentOS. The firewalld front-end has two main advantages over raw iptables −
-
Uses easy-to-configure and implement zones abstracting chains and rules.
-
Rulesets are dynamic, meaning stateful connections are uninterrupted when the settings are changed and/or modified.
记住,firewalld 是 iptables 的包装器——而不是替代品。虽然可以将自定义 iptables 命令与 firewalld 一起使用,但建议使用 firewalld 以免破坏防火墙功能。
Remember, firewalld is the wrapper for iptables - not a replacement. While custom iptables commands can be used with firewalld, it is recommended to use firewalld as to not break the firewall functionality.
首先,让我们确保 firewalld 已启动并已启用。
First, let’s make sure firewalld is both started and enabled.
[root@CentOS rdc]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2017-01-26 21:42:05 MST; 3h 46min ago
Docs: man:firewalld(1)
Main PID: 712 (firewalld)
Memory: 34.7M
CGroup: /system.slice/firewalld.service
└─712 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
我们可以看到,firewalld 处于活动状态(开机自启动)且当前正在运行。如果处于非活动状态或未启动,我们可以使用 −
We can see, firewalld is both active (to start on boot) and currently running. If inactive or not started we can use −
systemctl start firewalld && systemctl enable firewalld
现在我们已经配置了 firewalld 服务,让我们确保它可操作。
Now that we have our firewalld service configured, let’s assure it is operational.
[root@CentOS]# firewall-cmd --state
running
[root@CentOS]#
我们可以看到,firewalld 服务已完全正常工作。
We can see, the firewalld service is fully functional.
Firewalld 基于区域这一概念工作。区域通过网络管理器应用到网络接口。我们将在配置网络时对此进行讨论。但目前,默认情况下,更改默认区域将更改留在“默认区域”默认状态中的任何网络适配器。
Firewalld works on the concept of zones. A zone is applied to network interfaces through the Network Manager. We will discuss this in configuring networking. But for now, by default, changing the default zone will change any network adapters left in the default state of "Default Zone".
让我们快速查看一下 firewalld 随附的每个区域。
Let’s take a quick look at each zone that comes out-of-the-box with firewalld.
Sr.No. |
Zone & Description |
1 |
drop Low trust level. All incoming connections and packetsare dropped and only outgoing connections are possible via statefullness |
2 |
block Incoming connections are replied with an icmp message letting the initiator know the request is prohibited |
3 |
public All networks are restricted. However, selected incoming connections can be explicitly allowed |
4 |
external Configures firewalld for NAT. Internal network remains private but reachable |
5 |
dmz Only certain incoming connections are allowed. Used for systems in DMZ isolation |
6 |
work By default, trust more computers on the network assuming the system is in a secured work environment |
7 |
hone By default, more services are unfiltered. Assuming a system is on a home network where services such as NFS, SAMBA and SSDP will be used |
8 |
trusted All machines on the network are trusted. Most incoming connections are allowed unfettered. This is not meant for interfaces exposed to the Internet |
最常用的区域为:public、drop、work 和 home。
The most common zones to use are:public, drop, work, and home.
以下是一些会使用每个常见区域的情景 −
Some scenarios where each common zone would be used are −
-
public − It is the most common zone used by an administrator. It will let you apply the custom settings and abide by RFC specifications for operations on a LAN.
-
drop − A good example of when to use drop is at a security conference, on public WiFi, or on an interface connected directly to the Internet. drop assumes all unsolicited requests are malicious including ICMP probes. So any request out of state will not receive a reply. The downside of drop is that it can break the functionality of applications in certain situations requiring strict RFC compliance.
-
work − You are on a semi-secure corporate LAN. Where all traffic can be assumed moderately safe. This means it is not WiFi and we possibly have IDS, IPS, and physical security or 802.1x in place. We also should be familiar with the people using the LAN.
-
home − You are on a home LAN. You are personally accountable for every system and the user on the LAN. You know every machine on the LAN and that none have been compromised. Often new services are brought up for media sharing amongst trusted individuals and you don’t need to take extra time for the sake of security.
区域和网络接口按照一对多的级别工作。一个网络接口 一次只能应用一个区域。而一个区域可以同时应用到多个接口。
Zones and network interfaces work on a one to many level. One network interface can only have a single zone applied to it at a time. While, a zone can be applied to many interfaces simultaneously.
让我们看看可以使用哪些区域,以及当前应用了哪些区域。
Let’s see what zones are available and what are the currently applied zone.
[root@CentOS]# firewall-cmd --get-zones
work drop internal external trusted home dmz public block
[root@CentOS]# firewall-cmd --get-default-zone
public
[root@CentOS]#
准备好向 firewalld 中添加一些自定义规则了吗?
Ready to add some customized rules in firewalld?
首先,让我们看看我们的盒子在外面对端口扫描仪是什么样子。
First, let’s see what our box looks like, to a portscanner from outside.
bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1
Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:36 MST
Nmap scan report for centos.shared (10.211.55.1)
Host is up (0.00046s latency).
Not shown: 1023 filtered ports
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 3.71 seconds
bash-3.2#
让我们允许端口 80 的传入请求。
Let’s allow the incoming requests to port 80.
首先,检查当前应用了什么区域。
First, check to see what zone is applied as default.
[root@CentOs]# firewall-cmd --get-default-zone
public
[root@CentOS]#
然后,将允许端口 80 的规则设为当前默认区域。
Then, set the rule allowing port 80 to the current default zone.
[root@CentOS]# firewall-cmd --zone=public --add-port = 80/tcp
success
[root@CentOS]#
现在,让我们在允许端口 80 连接后检查一下我们的盒子。
Now, let’s check our box after allowing port 80 connections.
bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1
Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:42 MST
Nmap scan report for centos.shared (10.211.55.1)
Host is up (0.00053s latency).
Not shown: 1022 filtered ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp closed http
Nmap done: 1 IP address (1 host up) scanned in 3.67 seconds
bash-3.2#
现在它允许非请求流量进入 80。
It now allows unsolicited traffic to 80.
让我们将默认区域设为 drop,看看对端口扫描会发生什么。
Let’s put the default zone to drop and see what happens to port scan.
[root@CentOS]# firewall-cmd --set-default-zone=drop
success
[root@CentOS]# firewall-cmd --get-default-zone
drop
[root@CentOs]#
现在我们使用位于更安全区域中的网络接口扫描该主机。
Now let’s scan the host with the network interface in a more secure zone.
bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1
Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:50 MST
Nmap scan report for centos.shared (10.211.55.1)
Host is up (0.00094s latency).
All 1024 scanned ports on centos.shared (10.211.55.1) are filtered
Nmap done: 1 IP address (1 host up) scanned in 12.61 seconds
bash-3.2#
现在,从外部过滤了一切。
Now, everything is filtered from outside.
如下所示,drop 时主机甚至不会响应 ICMP ping 请求。
As demonstrated below, the host will not even respond to ICMP ping requests when in drop.
bash-3.2# ping 10.211.55.1
PING 10.211.55.1 (10.211.55.1): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
让我们再次将默认区域设为 public。
Let’s set the default zone to public again.
[root@CentOs]# firewall-cmd --set-default-zone=public
success
[root@CentOS]# firewall-cmd --get-default-zone
public
[root@CentOS]#
现在让我们在 public 中检查我们当前的过滤规则集。
Now let’s check our current filtering ruleset in public.
[root@CentOS]# firewall-cmd --zone=public --list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: enp0s5
sources:
services: dhcpv6-client ssh
ports: 80/tcp
protocols:
masquerade: no
forward-ports:
sourceports:
icmp-blocks:
rich rules:
[root@CentOS rdc]#
在配置中,我们 80 端口的过滤规则仅在运行配置的上下文中。这意味着在系统重启或 firewalld 服务重启后,我们的规则将被舍弃。
As configured, our port 80 filter rule is only within the context of the running configuration. This means once the system is rebooted or the firewalld service is restarted, our rule will be discarded.
我们很快将配置一个 httpd 服务守护程序,所以让我们使我们的变更持久 -
We will be configuring an httpd daemon soon, so let’s make our changes persistent −
[root@CentOS]# firewall-cmd --zone=public --add-port=80/tcp --permanent
success
[root@CentOS]# systemctl restart firewalld
[root@CentOS]#
现在我们在公有区域中的 80 端口规则在重启和服务重启期间将持久。
Now our port 80 rule in the public zone is persistent across reboots and service restarts.
以下是通过 firewall-cmd 应用的常见的 firewalld 命令。
Following are the common firewalld commands applied with firewall-cmd.
Command |
Action |
firewall-cmd --get-zones |
Lists all zones that can be applied to an interface |
firewall-cmd —status |
Returns the currents status of the firewalld service |
firewall-cmd --get-default-zone |
Gets the current default zone |
firewall-cmd --set-default-zone=<zone> |
Sets the default zone into the current context |
firewall-cmd --get-active-zone |
Gets the current zones in context as applied to an interface |
firewall-cmd --zone=<zone> --list-all |
Lists the configuration of supplied zone |
firewall-cmd --zone=<zone> --addport=<port/transport protocol> |
Applies a port rule to the zone filter |
--permanent |
Makes changes to the zone persistent. Flag is used inline with modification commands |
这些是管理和配置 firewalld 的基本概念。
These are the basic concepts of administrating and configuring firewalld.
在 CentOS 中配置基于主机的防火墙服务在更复杂的网络场景中可能是一个复杂的任务。firewalld 和 iptables 在 CentOS 中的高级使用和配置可能需要一整套教程。然而,我们已经展示了应该足以完成大多数日常任务的基础知识。
Configuring host-based firewall services in CentOS can be a complex task in more sophisticated networking scenarios. Advanced usage and configuration of firewalld and iptables in CentOS can take an entire tutorial. However, we have presented the basics that should be enough to complete a majority of daily tasks.
Configure PHP in CentOS Linux
PHP 是当今使用最多的 Web 语言之一。在 CentOS 上安装一个 LAMP 堆栈是每个系统管理员都需要执行的事情,而且可能早于预期。
PHP is the one of the most prolific web languages in use today. Installing a LAMP Stack on CentOS is something every system administrator will need to perform, most likely sooner than later.
一个传统的 LAMP 堆栈包含 (L)inux (A)pache (M)ySQL (P)HP。
A traditional LAMP Stack consists of (L)inux (A)pache (M)ySQL (P)HP.
在 CentOS 中,一个 LAMP 堆栈有三个主要组件 -
There are three main components to a LAMP Stack on CentOS −
-
Web Server
-
Web Development Platform / Language
-
Database Server
Note - LAMP 堆栈这个术语也可能包含以下技术:PostgreSQL、MariaDB、Perl、Python、Ruby、NGINX Web 服务器。
Note − The term LAMP Stack can also include the following technologies: PostgreSQL, MariaDB, Perl, Python, Ruby, NGINX Webserver.
本教程中,我们坚持使用 CentOS GNU Linux 的传统 LAMP 堆栈: Apache Web 服务器,MySQL 数据库服务器和 PHP。
For this tutorial, we will stick with the traditional LAMP Stack of CentOS GNU Linux: Apache web server, MySQL Database Server, and PHP.
我们实际上将使用 MariaDB。MySQL 配置文件、数据库和表对 MariaDB 来说是透明的。由于 Oracle 已接管 MySQL 的开发,因此 MariaDB 现在包含在标准 CentOS 存储库中,而不是 MySQL。这是由于许可和开源合规性的限制。
We will actually be using MariaDB. MySQL configuration files, databases and tables are transparent to MariaDB. MariaDB is now included in the standard CentOS repository instead of MySQL. This is due to the limitations of licensing and open-source compliance, since Oracle has taken over the development of MySQL.
我们需要做的第一件事是安装 Apache。
The first thing we need to do is install Apache.
[root@CentOS]# yum install httpd
Loaded plugins: fastestmirror, langpacks
base
| 3.6 kB 00:00:00
extras
| 3.4 kB 00:00:00
updates
| 3.4 kB 00:00:00
extras/7/x86_64/primary_d
| 121 kB 00:00:00
Loading mirror speeds from cached hostfile
* base: mirror.sigmanet.com
* extras: linux.mirrors.es.net
* updates: mirror.eboundhost.com
Resolving Dependencies
--> Running transaction check
---> Package httpd.x86_64 0:2.4.6-45.el7.centos will be installed
--> Processing Dependency: httpd-tools = 2.4.6-45.el7.centos for package:
httpd-2.4.6-45.el7.centos.x86_64
--> Processing Dependency: /etc/mime.types for package: httpd-2.4.645.el7.centos.x86_64
--> Running transaction check
---> Package httpd-tools.x86_64 0:2.4.6-45.el7.centos will be installed
---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed
--> Finished Dependency Resolution
Installed:
httpd.x86_64 0:2.4.6-45.el7.centos
Dependency Installed:
httpd-tools.x86_64 0:2.4.6-45.el7.centos
mailcap.noarch 0:2.1.41-2.el7
Complete!
[root@CentOS]#
我们配置 httpd 服务。
Let’s configure httpd service.
[root@CentOS]# systemctl start httpd && systemctl enable httpd
现在,让我们确保防火墙可以访问 Web 服务器。
Now, let’s make sure the web-server is accessible through firewalld.
bash-3.2# nmap -sS -p 1-1024 -T 5 -sV 10.211.55.1
Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-28 02:00 MST
Nmap scan report for centos.shared (10.211.55.1)
Host is up (0.00054s latency).
Not shown: 1022 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1 (protocol 2.0)
80/tcp open http Apache httpd 2.4.6 ((CentOS))
Service detection performed. Please report any incorrect results at
https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 10.82 seconds bash-3.2#
正如 nmap 服务探测所示,Apache Web 服务器正在侦听并响应 CentOS 主机上的请求。
As you can see by the nmap service probe, Apache webserver is listening and responding to requests on the CentOS host.
Install MySQL Database Server
[root@CentOS rdc]# yum install mariadb-server.x86_64 && yum install mariadb-
devel.x86_64 && mariadb.x86_64 && mariadb-libs.x86_64
我们正在为 MariaDB 安装以下存储库包 −
We are installing the following repository packages for MariaDB −
mariadb-devel.x86_64
需要从具有 MySQL/MariaDB 兼容性的源代码编译的文件。
Files need to compile from the source with MySQL/MariaDB compatibility.
mariadb.x86_64
用于从命令行管理 MariaDB 服务器的 MariaDB 客户端实用程序。
MariaDB client utilities for administering MariaDB Server from the command line.
mariadb-libs.x86_64
可能需要用于与 MySQL/MariaDB 支持一起编译的其他应用程序的 MariaDB 公共库。
Common libraries for MariaDB that could be needed for other applications compiled with MySQL/MariaDB support.
现在,启动并启用 MariaDB 服务。
Now, let’s start and enable the MariaDB Service.
[root@CentOS]# systemctl start mariadb
[root@CentOS]# systemctl enable mariadb
Note − 与 Apache 不同,我们不会通过基于主机的防火墙 (firewalld) 启用到 MariaDB 的连接。在使用数据库服务器时,除非明确需要远程套接字访问,否则仅允许本地套接字连接被认为是最佳安全实践。
Note − Unlike Apache, we will not enable connections to MariaDB through our host-based firewall (firewalld). When using a database server, it’s considered best security practice to only allow local socket connections, unless the remote socket access is specifically needed.
确保 MariaDB 服务器已接受连接。
Let’s make sure the MariaDB Server is accepting connections.
[root@CentOS#] netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN
tcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN
[root@CentOS rdc]#
正如我们所看到的,MariaDB 在 3306 tcp 端口上侦听。我们将保留基于主机的防火墙 (firewalld) 阻止传入 3306 端口的连接。
As we can see, MariaDB is listening on port 3306 tcp. We will leave our host-based firewall (firewalld) blocking incoming connections to port 3306.
Install and Configure PHP
[root@CentOS#] yum install php.x86_64 && php-common.x86_64 && php-mysql.x86_64
&& php-mysqlnd.x86_64 && php-pdo.x86_64 && php-soap.x86_64 && php-xml.x86_64
我建议安装以下 php 包以实现通用兼容性 −
I’d recommend installing the following php packages for common compatibility −
-
php-common.x86_64
-
php-mysql.x86_64
-
php-mysqlnd.x86_64
-
php-pdo.x86_64
-
php-soap.x86_64
-
php-xml.x86_64
[root@CentOS]# yum install -y php-common.x86_64 php-mysql.x86_64 php-
mysqlnd.x86_64 php-pdo.x86_64 php-soap.x86_64 php-xml.x86_64
这是我们位于 /var/www/html/ 的 Apache Web 根目录中的简单 php 文件。
This is our simple php file located in the Apache webroot of /var/www/html/
[root@CentOS]# cat /var/www/html/index.php
<html>
<head>
<title>PHP Test Page</title>
</head>
<body>
PHP Install
<?php
echo "We are now running PHP on GNU Centos Linux!<br />"
?>
</body>
</html>
[root@CentOS]#
将我们的页面所有者组更改为我们的 http 守护程序运行的系统用户。
Let’s change the owning group of our page to the system user our http daemon is running under.
[root@CentOS]# chgrp httpd /var/www/html/index.php && chmod g+rx /var/www/html/index.php
---
通过 ncat 手动请求时。
When requested manually via ncat.
bash-3.2# ncat 10.211.55.1 80
GET / index.php
HTTP/1.1 200 OK
Date: Sat, 28 Jan 2017 12:06:02 GMT
Server: Apache/2.4.6 (CentOS) PHP/5.4.16
X-Powered-By: PHP/5.4.16
Content-Length: 137
Connection: close
Content-Type: text/html; charset=UTF-8
<html>
<head>
<title>PHP Test Page</title>
</head>
<body>
PHP Install
We are now running PHP on GNU Centos Linux!<br />
</body>
</html>
bash-3.2#
PHP 和 LAMP 是非常流行的网络编程技术。作为 CentOS 管理员,LAMP 的安装和配置必将成为你的需求之一。易于使用的 CentOS 软件包已经做了很多工作,可以根据源代码编译 Apache、MySQL 和 PHP。
PHP and LAMP are very popular web-programming technologies. LAMP installation and configuration is sure to come up on your list of needs as a CentOS Administrator. Easy to use CentOS packages have taken a lot of work from compiling Apache, MySQL, and PHP from the source code.
Set Up Python with CentOS Linux
Python 是一种广泛使用的解释型语言,为在 Linux(和其他操作系统上)编写脚本应用程序的世界带来了专业性。Perl 曾经是行业标准,但 Python 在很多方面都超越了 Perl。
Python is a widely used interpreted language that has brought professionalism to the world of coding scripted applications on Linux (and other operating systems). Where Perl was once the industry standard, Python has surpassed Perl in many respects.
Python 相对于 Perl 的一些优势包括:
Some strengths of Python versus Perl are −
-
Rapid progression in refinement
-
Libraries that are standard to the language
-
Readability of the code is thought out in language definition
-
Many professional frameworks for everything from GUI support to web-development
Python 可以执行 Perl 可以执行的所有操作,并且在很多情况下以更好的方式执行。虽然 Perl 仍然在 Linux 管理员的工具箱中占有一席之地,但学习 Python 是作为技能组合的一个极好选择。
Python can do anything Perl can do, and in a lot of cases in a better manner. Though Perl still has its place amongst the toolbox of a Linux admin, learning Python is a great choice as a skill set.
Python 最大的缺点有时与其优点有关。从历史上看,Python 最初是设计用于教授编程的。有时,其“易于阅读”和“以正确方式做事”的核心基础会在编写简单代码时导致不必要的复杂性。另外,其标准库在从版本 2.X 过渡到版本 3.X 时造成了问题。
The biggest drawbacks of Python are sometimes related to its strengths. In history, Python was originally designed to teach programming. At times, its core foundations of "easily readable" and "doing things the right way" can cause unnecessary complexities when writing a simple code. Also, its standard libraries have caused problems in transitioning from versions 2.X to 3.X.
实际上,Python 脚本用于 CentOS 的核心,对于操作系统的功能至关重要。因此,将我们的开发 Python 环境与 CentOS 的核心 Python 环境隔离开来非常重要。
Python scripts are actually used at the core of CentOS for functions vital to the functionality of the operating system. Because of this, it is important to isolate our development Python environment from CentOS' core Python environment.
对于初学者来说,当前有两个版本的 Python: Python 2.X 和 Python 3.X 。
For starters, there are currently two versions of Python: Python 2.X and Python 3.X.
这两个阶段仍然处于积极生产中,尽管版本 2.X 很快就要弃用(已经持续了几年)。两个活跃版本 Python 的原因基本上是修复了版本 2.X 的缺点。这要求版本 3.X 的一些核心功能被重新制作,以一种版本 2.X 脚本无法支持的方式。
Both stages are still in active production, though version 2.X is quickly closing in on depreciation (and has been for a few years). The reason for the two active versions of Python was basically fixing the shortcomings of version 2.X. This required some core functionality of version 3.X to be redone in ways it could not support some version 2.X scripts.
基本上,克服这种过渡的最好方法是:开发 3.X,并为传统脚本保持最新的 2.X 版本。目前,CentOS 7.X 依赖于版本 2.X 的半当前修订版。
Basically, the best way to overcome this transition is: Develop for 3.X and keep up with the latest 2.X version for legacy scripts. Currently, CentOS 7.X relies on a semi-current revision of version 2.X.
在撰写本文时,Python 的最新版本是: 3.4.6 和 2.7.13 。
As of this writing, the most current versions of Python are: 3.4.6 and 2.7.13.
不要让这一切混淆或得出任何关于 Python 的结论。设置 Python 环境实际上非常简单。有了 Python 框架和库,实现此任务实际上非常容易。
Don’t let this confuse or draw any conclusions of Python. Setting up a Python environment is really pretty simple. With Python frameworks and libraries, this task is actually really easy to accomplish.
在设置 Python 环境之前,我们需要一个合理的环境。首先,让我们确保 CentOS 安装已完全更新,并安装一些构建实用程序。
Before setting up our Python environments, we need a sane environment. To start, let’s make sure our CentOS install is fully updated and get some building utilities installed.
Step 1 - 更新 CentOS。
Step 1 − Update CentOS.
[root@CentOS]# yum -y update
Step 2 - 安装构建实用程序。
Step 2 − Install build utilities.
[root@CentOS]# yum -y groupinstall "development tools"
Step 3 - 安装一些需要的软件包。
Step 3 − Install some needed packages.
[root@CentOS]# yum install -y zlib-dev openssl-devel sqlite-devel bip2-devel
现在我们需要从源代码安装当前的 Python 2.X 和 3.X。
Now we need to install current Python 2.X and 3.X from source.
-
Download compressed archives
-
Extract files
-
Compile source code
让我们从为 /usr/src/ 中的每个 Python 安装创建一个构建目录开始。
Let’s start by creating a build directory for each Python install in /usr/src/
[root@CentOS]# mkdir -p /usr/src/pythonSource
现在让我们为每个 Python 安装,下载 源 tar 包。
Now let’s download the source tarballs for each −
[root@CentOS]# wget https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tar.xz
[root@CentOS]# wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
现在我们需要从归档中提取每个。
Now we need to extract each from the archive.
Step 1 − 安装 xz-libs 并提取 tar 包。
Step 1 − Install xz-libs and extract the tarballs.
[root@CentOS]# yum install xz-libs
[root@CentOS python3]# xz -d ./*.xz
[root@CentOS python3]# ls
Python-2.7.13.tar Python-3.6.0.tar
[root@CentOS python3]#
Step 2 − 从 tar 包中解包每个安装程序。
Step 2 − Untar each installer from its tarball.
[root@CentOS]# tar -xvf ./Python-2.7.13.tar
[root@CentOS]# tar -xvf ./Python-3.6.0.tar
Step 3 − 进入每个目录并运行 configure 脚本。
Step 3 − Enter each directory and run the configure script.
[root@CentOS]# ./configure --prefix=/usr/local
root@CentOS]# make altinstall
Note − 务必使用 altinstall ,而不是 install。这将使 CentOS 和 Python 的开发版本保持分离。否则,你可能会破坏 CentOS 的功能。
Note − Be sure to use altinstall and not install. This will keep CentOS and development versions of Python separated. Otherwise, you may break the functionality of CentOS.
现在,你将看到编译过程开始。泡杯咖啡,休息 15 分钟,直到编译完成。由于我们已安装了 Python 所需的所有依赖项,因此编译过程应该会顺利完成,而不会出错。
You will now see the compilation process begins. Grab a cup of coffee and take a 15minute break until completion. Since we installed all the needed dependencies for Python, the compilation process should complete without error.
让我们确保已安装了 2.X 的最新版本 Python。
Let’s make sure we have the latest 2.X version of Python installed.
[root@CentOS Python-2.7.13]# /usr/local/bin/python2.7 -V
Python 2.7.13
[root@CentOS Python-2.7.13]#
Note − 你将希望为指向 Python 2.X 开发环境的 shebang 行添加前缀。
Note − You will want to prefix the shebang line pointing to our development environment for Python 2.X.
[root@CentOS Python-2.7.13]# cat ver.py
#!/usr/local/bin/python2.7
import sys
print(sys.version)
[root@CentOS Python-2.7.13]# ./ver.py
2.7.13 (default, Jan 29 2017, 02:24:08)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
就这样,我们为 2.X 和 3.X 版本分别安装了 Python。从这里,我们可以使用 pip 和 virtualenv 等每个功能和实用程序来进一步减轻管理 Python 环境和软件包安装的负担。
Just like that, we have separate Python installs for versions 2.X and 3.X. From here, we can use each and utilities such as pip and virtualenv to further ease the burden of managing Python environments and package installation.
Configure Ruby on CentOS Linux
Ruby 既适用于 Web 开发,又适用于 Linux 管理。Ruby 提供了前面讨论过的所有语言(PHP、Python 和 Perl)中的许多好处。
Ruby is a great language for both web development and Linux Administration. Ruby provides many benefits found in all the previous languages discussed: PHP, Python, and Perl.
若要安装 Ruby,最好通过 rbenv 引导,这允许管理员轻松安装和管理 Ruby 环境。
To install Ruby, it is best to bootstrap through the rbenv which allows the administrators to easily install and manage Ruby Environments.
安装 Ruby 的另一种方法是使用 Ruby 的标准 CentOS 软件包。建议使用 rbenv 方法及其所有好处。对于不了解 Ruby 的人来说,CentOS 软件包会更容易。
The other method for installing Ruby is the standard CentOS packages for Ruby. It is advisable to use the rbenv method with all its benefits. CentOS packages will be easier for the non-Ruby savvy.
首先,让我们为 rbenv 安装程序获取一些必需的依赖项。
First, let’s get some needed dependencies for rbenv installer.
-
git-core
-
zlib
-
zlib-devel
-
gcc-c++
-
patch
-
readline
-
readline-devel
-
libyaml-devel
-
libffi-devel
-
openssl-devel
-
make
-
bzzip2
-
autoconf
-
automake
-
libtool
-
bison
-
curl
-
sqlite-devel
根据安装 CentOS 时选择的选项和角色,这些软件包中的大多数可能已经安装。最好安装我们不确定的所有内容,因为这可以减少在安装需要依赖项的软件包时遇到的麻烦。
Most of these packages may already be installed depending on the chosen options and roles when installing CentOS. It is good to install everything we are unsure about as this can lead to less headache when installing packages requiring dependencies.
[root@CentOS]# yum -y install git-core zlib zlib-devel gcc-c++ patch readline
readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf
automake libtool bison curl sqlite-devel
Method 1 : rbenv for Dynamic Ruby Development Environments
现在,作为将要使用 Ruby 的用户:
Now as the user who will be using Ruby −
[rdc@CentOS ~]$ git clone https://github.com/rbenv/rbenv.git
[rdc@CentOS ~]$ https://github.com/rbenv/ruby-build.git
ruby-build 将为 rbenv 提供安装功能:
ruby-build will provide installation features to rbenv −
Note − 我们需要在运行 install.sh 之前切换到 root 或管理用户。
Note − We need to switch to root or an administration user before running install.sh
[rdc@CentOS ruby-build]$ cd ~/ruby-build
[rdc@CentOS ruby-build]# ./install.sh
让我们为 rbenv 配置 Shell,并确保已安装正确的选项。
Let’s set our shell for rbenv and assure we have installedthe correct options.
[rdc@CentOS ~]$ source ~/rbenv/rbenv.d/exec/gem-rehash.bash
[rdc@CentOS ruby-build]$ ~/rbenv/bin/rbenv
rbenv 1.1.0-2-g4f8925a
Usage: rbenv <command> [<args>]
一些有用的 rbenv 命令为:
Some useful rbenv commands are −
Commands |
Action |
local |
Sets or shows the local application-specific Ruby version |
global |
Sets or shows the global Ruby version |
shell |
Sets or shows the shell-specific Ruby version |
install |
Installs a Ruby version using ruby-build |
uninstall |
Uninstalls a specific Ruby version |
rehash |
Rehashes rbenv shims (run this after installing executables) |
version |
Shows the current Ruby version and its origin |
versions |
Lists all Ruby versions available to rbenv |
which |
Displays the full path to an executable |
whence |
Lists all Ruby versions that contain the given executable |
现在,我们安装 Ruby
Let’s now install Ruby −
[rdc@CentOS bin]$ ~/rbenv/bin/rbenv install -v 2.2.1
编译完成后
After compilation completes −
[rdc@CentOS ~]$ ./ruby -v
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
[rdc@CentOS ~]$
现在,我们拥有一个工作 Ruby 环境,其 Ruby 2.X 分支为已更新且正常工作的版本。
We now have a working Ruby environment with an updated and working version of Ruby 2.X branch.
Method 2 : Install Ruby from CentOS Packages
这是最简单的方法。但是,它受 CentOS 中打包的版本和 gem 的限制。对于认真的开发工作,强烈建议使用 rbenv 方法来安装 Ruby。
This is the most simple method. However, it can be limited by the version and gems packaged from CentOS. For serious development work, it is highly recommended to use the rbenv method to install Ruby.
安装 Ruby、所需的开发包和一些常见的 gem。
Install Ruby, needed development packages, and some common gems.
[root@CentOS rdc]# yum install -y ruby.x86_64 ruby-devel.x86_64 ruby-
libs.x86_64 ruby-gem-json.x86_64 rubygem-rake.noarch
遗憾的是,我们使用的是过时的 Ruby 版本。
Unfortunately, we are left with somewhat outdated version of Ruby.
[root@CentOS rdc]# ruby -v
ruby 2.0.0p648 (2015-12-16) [x86_64-linux]
[root@CentOS rdc]#
Linux Admin - Set Up Perl for CentOS Linux
Perl 已经存在很长时间。它最初被设计为一种用于解析文本文件的报告语言。随着流行程度的提高,Perl 增加了对模块支持、CPAN、套接字、线程和其他功能的支持,这些功能是强大的脚本语言所需的。
Perl has been around for a long time. It was originally designed as a reporting language used for parsing text files. With increased popularity, Perl has added a module support or CPAN, sockets, threading, and other features needed in a powerful scripting language.
Perl 相对于 PHP、Python 或 Ruby 的最大优势是:它能以最少的麻烦完成任务。这种 Perl 的理念并不总是意味着它能正确地完成任务。然而,对于 Linux 上的管理任务,Perl 被认为是作为脚本语言的最佳选择。
The biggest advantage of Perl over PHP, Python, or Ruby is: it gets things done with minimal fuss. This philosophy of Perl does not always mean it gets things done the right way. However, for administration tasks on Linux, Perl is considered as the go-to choice for a scripting language.
Perl 相对于 Python 或 Ruby 的部分优势有:
Some advantages of Perl over Python or Ruby are −
-
Powerful text processing
-
Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)
-
Perl can do anything (almost)
Perl 的部分缺点有:
Some drawbacks of Perl are −
-
Syntax can be confusing
-
Coding style in Perl can be unique and bog down collaboration
-
Perl is not really Object Oriented
-
Typically, there isn’t a lot of thought put into standardization and best-practice when Perl is used.
当决定使用 Perl、Python 或 PHP 时,应询问以下问题:
When deciding whether to use Perl, Python or PHP; the following questions should be asked −
-
Will this application ever need versioning?
-
Will other people ever need to modify the code?
-
Will other people need to use this application?
-
Will this application ever be used on another machine or CPU architecture?
如果对上述所有问题的答案均为“不”,那么 Perl 是一个不错的选择,并且可能会在最终结果方面加快速度。
If the answers to all the above are "no", Perl is a good choice and may speed things up in terms of end-results.
在提及这一点之后,让我们配置 CentOS 服务器以使用最新版本的 Perl。
With this mentioned, let’s configure our CentOS server to use the most recent version of Perl.
在安装 Perl 之前,我们需要了解对 Perl 的支持。Perl 仅在最后两个稳定版本中得到官方支持。因此,我们希望确保我们开发环境与 CentOS 版本隔离。
Before installing Perl, we need to understand the support for Perl. Officially, Perl is only supported far back as the last two stable versions. So, we want to be sure to keep our development environment isolated from the CentOS version.
隔离的原因是:如果有人向 CentOS 社区发布使用 Perl 的工具,很有可能它会被修改为在与 CentOS 一起发布的 Perl 上工作。但是,我们也希望为开发目的安装最新版本。与 Python 一样,CentOS 内置 Perl 专注于稳定性,而不是前沿技术。
The reason for isolation is: if someone releases a tool in Perl to the CentOS community, more than likely it will be modified to work on Perl as shipped with CentOS. However, we also want to have the latest version installed for development purposes. Like Python, CentOS ships Perl focused on the reliability and not cutting edge.
让我们检查一下 CentOS 7 中的当前 Perl 版本。
Let’s check our current version of Perl on CentOS 7.
[root@CentOS]# perl -v
This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
我们当前运行的是 Perl 5.16.3。截至撰写本文时,最新版本为:perl-5.24.0
We are currently running Perl 5.16.3. The most current version as of this writing is: perl-5.24.0
我们肯定想要升级我们的版本,能够在我们的代码中使用最新的 Perl 模块。幸运的是,有一个很好的工具可以维护 Perl 环境,同时还能将我们的 CentOS Perl 版本保持隔离。它叫做 perlbrew 。
We definitely want to upgrade our version, being able to use up-to-date Perl modules in our code. Fortunately, there is a great tool for maintaining Perl environments and keeping our CentOS version of Perl isolated. It is called perlbrew.
我们来安装 Perl Brew。
Let’s install Perl Brew.
[root@CentOS]# curl -L https://install.perlbrew.pl | bash
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 170 100 170 0 0 396 0 --:--:-- --:--:-- --:--:-- 397
100 1247 100 1247 0 0 1929 0 --:--:-- --:--:-- --:--:-- 1929
现在我们已经安装了 Perl Brew,让我们来为 Perl 最新版本创建一个环境。
Now that we have Perl Brew installed, let’s make an environment for the latest version of Perl.
首先,我们需要当前安装的 Perl 版本来引导 perlbrew 安装。因此,让我们从 CentOS 存储库中获取一些需要的 Perl 模块。
First, we will need the currently installed version of Perl to bootstrap the perlbrew install. Thus, let’s get some needed Perl modules from the CentOS repository.
Note - 在可用时,我们总希望在 CentOS Perl 安装中使用 CentOS Perl 模块,而不是 CPAN。
Note − When available we always want to use CentOS Perl modules versus CPAN with our CentOS Perl installation.
Step 1 - 安装 CentOS Perl Make::Maker 模块。
Step 1 − Install CentOS Perl Make::Maker module.
[root@CentOS]# yum -y install perl-ExtUtils-MakeMaker.noarch
Step 2 - 安装最新版本的 perl。
Step 2 − Install the latest version of perl.
[root@CentOS build]# source ~/perl5/perlbrew/etc/bashrc
[root@CentOS build]# perlbrew install -n -j4 --threads perl-5.24.1
我们为 Perl 安装选择的选项是 -
The options we chose for our Perl install are −
-
n − No tests
-
j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)
-
threads − Enable threading support for Perl
在安装成功执行后,让我们切换到我们最新的 Perl 环境。
After our installation has been performed successfully, let’s switch to our newest Perl environment.
[root@CentOS]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1
A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.
[root@CentOS]# perl -v
This is perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linuxthread-multi
(with 1 registered patch, see perl -V for more detail)
Copyright 1987-2017, Larry Wall
Perl may be copied only under the terms of either the Artistic License or the GNU General
Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on this system
using "man perl" or "perldoc perl". If you have access to the Internet, point your
browser at http://www.perl.org/, the Perl Home Page.
[root@CentOS]#
简单的 Perl 脚本打印在 perlbrew 环境上下文中运行的 Perl 版本 -
Simple perl script printing perl version running within the context of our perlbrew environment −
[root@CentOS]# cat ./ver.pl
#!/usr/bin/perl
print $^V . "\n";
[root@CentOS]# perl ./ver.pl
v5.24.1
[root@CentOS]#
Perl 安装后,我们可以使用 perl brew 的 cpanm 加载 cpan 模块 -
Once perl is installed, we can load cpan modules with perl brew’s cpanm −
[root@CentOS]# perl-brew install-cpanm
现在,让我们使用 cpanm 安装程序在 perl brew 中用我们当前的 Perl 版本 5.24.1 来制作 LWP 模块。
Now let’s use the cpanm installer to make the LWP module with our current Perl version of 5.24.1 in perl brew.
Step 1 - 切换到我们当前 Perl 版本的上下文中。
Step 1 − Switch to the context of our current Perl version.
[root@CentOS ~]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1
一个子 shell 以 perl-5.24.1 作为激活的 perl 启动。运行“exit”来结束它。
A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.
[root@CentOS ~]#
Step 2 - 安装 LWP 用户代理 Perl 模块。
Step 2 − Install LWP User Agent Perl Module.
[root@CentOS ~]# ~/perl5/perlbrew/bin/cpanm -i LWP::UserAgent
Step 3 - 现在,让我们使用新的 CPAN 模块来测试我们的 Perl 环境。
Step 3 − Now let’s test our Perl environment with the new CPAN module.
[root@CentOS ~]# cat ./get_header.pl
#!/usr/bin/perl
use LWP;
my $browser = LWP::UserAgent->new();
my $response = $browser->get("http://www.slcc.edu/");
unless(!$response->is_success) {
print $response->header("Server");
}
[root@CentOS ~]# perl ./get_header.pl
Microsoft-IIS/8.5 [root@CentOS ~]#
就是这样!Perl Brew 使 perl 环境隔离变得小事一桩,并且可以被认为是 Perl 中的最佳实践。
There you have it! Perl Brew makes isolating perl environments a snap and can be considered as a best practice as things get with Perl.
Install and Configure Open LDAP
LDAP 是 Light Weight Directory Access Protocol 的别称,是一种协议,用于访问目录中的企业内 X.500 服务容器。那些熟悉 Windows Server 管理的人可以将 LDAP 视为在本质上非常类似于 Active Directory。在把 Windows 工作站编织到 OpenLDAP CentOS 企业中时,这甚至是一个被广泛使用的方法。在另一方面,CentOS Linux 工作站可以共享资源,并参与 Windows 域中的基本功能。
LDAP known as Light Weight Directory Access Protocol is a protocol used for accessing X.500 service containers within an enterprise known from a directory. Those who are familiar with Windows Server Administration can think of LDAP as being very similar in nature to Active Directory. It is even a widely used concept of intertwining Windows workstations into an OpenLDAP CentOS enterprise. On the other spectrum, a CentOS Linux workstation can share resources and participate with the basic functionality in a Windows Domain.
将 LDAP 部署在 CentOS 上,作为目录服务器代理、目录系统代理或 DSA(所有这些首字母缩写词都相同),类似于使用 NDS 采用目录树结构的较旧 Novell Netware 安装。
Deploying LDAP on CentOS as a Directory Server Agent, Directory System Agent, or DSA (these acronyms are all one and the same) is similar to older Novell Netware installations using the Directory Tree structure with NDS.
Brief History of LDAP
LDAP 基本上是访问具有企业资源的 X.500 目录的高效方式。X.500 和 LDAP 具有相同的特性,并且非常相似,以至于 LDAP 客户端可以在一些帮助器的帮助下访问 X.500 目录。LDAP 也有自己的目录服务器,称为 slapd 。LDAP 和 DAP 之间的主要区别在于,轻量级版本被设计为在 TCP 上运行。
LDAP was basically created as an efficient way to access X.500 directories with enterprise resources. Both X.500 and LDAP share the same characteristics and are so similar that LDAP clients can access X.500 directories with some helpers. While LDAP also has its own directory server called slapd. The main difference between LDAP and DAP is, the lightweight version is designed to operate over TCP.
DAP 则使用完整的 OSI 模型。由于 TCP/IP 和以太网在当今网络中占据主导地位,因此很少遇到在特定遗留计算模型之外使用 DAP 和本机 X.500 企业目录的目录服务实现。
While DAP uses the full OSI Model. With the advent of the Internet, TCP/IP and Ethernet prominence in networks of today, it is rare to come across a Directory Services implantation using both DAP and native X.500 enterprise directories outside specific legacy computing models.
CentOS Linux 的 openldap 使用的主要组件如下:
The main components used with openldap for CentOS Linux are −
openldap |
LDAP support libraries |
openldap-server |
LDAP server |
openldap-clients |
LDAP client utlities |
openldap-devel |
Development libraries for OpenLDAP |
compay-openldap |
OpenLDAP shared libraries |
slapd |
Directory server daemon of OpenLDAP |
slurpd |
Used for LDAP replication across an enterprise domain |
Note - 为企业命名时,最佳做法是使用 .local TLD。当分离在线和内部域基础设施时,使用 .net 或 .com 可能会带来困难。想象一下一家公司同时对外部和内部操作使用 acme.com,其内部工作量会增加多少。因此,明智的做法是让互联网资源称为 acme.com 或 acme.net。然后,本地网络企业资源被描绘成 acme.local。这需要配置 DNS 记录,但可以在简单、表达和安全性方面获得回报。
Note − When naming your enterprise, it is a best practice to use the .local TLD. Using a .net or .com can cause difficulties when segregating an online and internal domain infrastructure. Imagine the extra work for a company internally using acme.com for both external and internal operations. Hence, it can be wise to have Internet resources called acme.com or acme.net. Then, the local networking enterprise resources is depicted as acme.local. This will entail configuring DNS records, but will pay in simplicity, eloquence and security.
Install Open LDAP on CentOS
从 YUM 安装 openldap、openldap-servers、openldap-clients 和 migrationtools。
Install the openldap, openldap-servers, openldap-clients and migrationstools from YUM.
[root@localhost]# yum -y install openldap openldap-servers openldap-clients
migration tools
Loaded plugins: fastestmirror, langpacks
updates
| 3.4 kB 00:00:00
updates/7/x86_64/primary_db
| 2.2 MB 00:00:05
Determining fastest mirrors
(1/2): extras/7/x86_64/primary_db
| 121 kB 00:00:01
(2/2): base/7/x86_64/primary_db
| 5.6 MB 00:00:16
Package openldap-2.4.40-13.el7.x86_64 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package openldap-clients.x86_64 0:2.4.40-13.el7 will be installed
---> Package openldap-servers.x86_64 0:2.4.40-13.el7 will be installed
--> Finished Dependency Resolution
base/7/x86_64/group_gz
| 155 kB 00:00:00
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch
Version Repository Size
===============================================================================
===============================================================================
Installing:
openldap-clients x86_64
2.4.40-13.el7 base 188 k
openldap-servers x86_64
2.4.40-13.el7 base 2.1 M
Transaction Summary
===============================================================================
===============================================================================
Install 2 Packages
Total download size: 2.3 M
Installed size: 5.3 M
Downloading packages:
Installed:
openldap-clients.x86_64 0:2.4.40-13.el7
openldap-servers.x86_64 0:2.4.40-13.el7
Complete!
[root@localhost]#
现在,让我们启动并启用 slapd 服务 -
Now, let’s start and enable the slapd service −
[root@centos]# systemctl start slapd
[root@centos]# systemctl enable slapd
此时,让我们确保我们在 /etc/openldap 中拥有 openldap 结构。
At this point, let’s assure we have our openldap structure in /etc/openldap.
root@localhost]# ls /etc/openldap/
certs check_password.conf ldap.conf schema slapd.d
[root@localhost]#
然后确保我们的 slapd 服务正在运行。
Then make sure our slapd service is running.
root@centos]# netstat -antup | grep slapd
tcp 0 0 0.0.0.0:389 0.0.0.0:* LISTEN 1641/slapd
tcp6 0 0 :::389 :::* LISTEN 1641/slapd
[root@centos]#
接下来,让我们配置我们的 Open LDAP 安装。
Next, let’s configure our Open LDAP installation.
确保已创建我们的系统 ldap 用户。
Make sure our system ldap user has been created.
[root@localhost]# id ldap
uid=55(ldap) gid=55(ldap) groups=55(ldap)
[root@localhost]#
生成我们的 LDAP 凭据。
Generate our LDAP credentials.
[root@localhost]# slappasswd
New password:
Re-enter new password:
{SSHA}20RSyjVv6S6r43DFPeJgASDLlLoSU8g.a10
[root@localhost]#
我们需要保存 slappasswd 的输出。
We need to save the output from slappasswd.
Configure Open LDAP
Step 1 - 为域配置 LDAP 并添加管理员用户。
Step 1 − Configure LDAP for domain and add administrative user.
首先,我们要设置我们的 openLDAP 环境。以下是与 ldapmodify 命令一起使用的模板。
First, we want to set up our openLDAP environment. Following is a template to use with the ldapmodify command.
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: dc=vmnet,dc=local
dn: olcDatabase = {2}hdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=ldapadm,dc=vmnet,dc=local
dn: olcDatabase = {2}hdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: <output from slap
使用 ldapmodify 命令更改为:/etc/openldap/slapd.d/cn=config/olcDatabase = {1}monitor.ldif。
Make changes to: /etc/openldap/slapd.d/cn=config/olcDatabase = {1}monitor.ldif with the ldapmodify command.
[root@localhost]# ldapmodify -Y EXTERNAL -H ldapi:/// -f /home/rdc/Documents/db.ldif
SASL/EXTERNAL authentication started
SASL username: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "olcDatabase = {2}hdb,cn=config"
modifying entry "olcDatabase = {2}hdb,cn=config"
modifying entry "olcDatabase = {2}hdb,cn=config"
[root@localhost cn=config]#
让我们检查修改后的 LDAP 配置。
Let’s check the modified LDAP configuration.
root@linux1 ~]# vi /etc/openldap/slapd.d/cn=config/olcDatabase={2}hdb.ldif
[root@centos]# cat /etc/openldap/slapd.d/cn\=config/olcDatabase\=\{2\}hdb.ldif
# AUTO-GENERATED FILE - DO NOT EDIT!! Use ldapmodify.
# CRC32 a163f14c
dn: olcDatabase = {2}hdb
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {2}hdb
olcDbDirectory: /var/lib/ldap
olcDbIndex: objectClass eq,pres
olcDbIndex: ou,cn,mail,surname,givenname eq,pres,sub
structuralObjectClass: olcHdbConfig
entryUUID: 1bd9aa2a-8516-1036-934b-f7eac1189139
creatorsName: cn=config
createTimestamp: 20170212022422Z
olcSuffix: dc=vmnet,dc=local
olcRootDN: cn=ldapadm,dc=vmnet,dc=local
olcRootPW:: e1NTSEF1bUVyb1VzZTRjc2dkYVdGaDY0T0k =
entryCSN: 20170215204423.726622Z#000000#000#000000
modifiersName: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth
modifyTimestamp: 20170215204423Z
[root@centos]#
如你所见,我们的 LDAP 企业修改已成功。
As you can see, our LDAP enterprise modifications were successful.
接下来,我们要为 OpenLDAP 创建一个自签名 SSL 证书。这将保护企业服务器和客户端之间的通信。
Next, we want to create an self-signed ssl certificate for OpenLDAP. This will secure the communication between the enterprise server and clients.
Step 2 - 为 OpenLDAP 创建自签名证书。
Step 2 − Create a self-signed certificate for OpenLDAP.
我们将使用 openssl 创建自签名 SSL 证书。转到下一章 Create LDAP SSL Certificate with openssl ,了解如何保护与 OpenLDAP 的通信。然后,当 SSL 证书配置好后,我们将完成我们的 OpenLDAP 企业配置。
We will use openssl to create a self-signed ssl certificate. Go to the next chapter, Create LDAP SSL Certificate with openssl for instructions to secure communications with OpenLDAP. Then when ssl certificates are configured, we will have completed our OpenLDAP enterprise configuration.
Step 3 - 配置 OpenLDAP 以使用证书进行安全通信。
Step 3 − Configure OpenLDAP to use secure communications with certificate.
在 vim 中使用以下信息创建一个 certs.ldif 文件 -
Create a certs.ldif file in vim with the following information −
dn: cn=config
changetype: modify
replace: olcTLSCertificateFile
olcTLSCertificateFile: /etc/openldap/certs/yourGeneratedCertFile.pem
dn: cn=config
changetype: modify
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: /etc/openldap/certs/youGeneratedKeyFile.pem
接下来,再次使用 ldapmodify 命令将更改合并到 OpenLDAP 配置中。
Next, again, use the ldapmodify command to merge the changes into the OpenLDAP configuration.
[root@centos rdc]# ldapmodify -Y EXTERNAL -H ldapi:/// -f certs.ldif
SASL/EXTERNAL authentication started
SASL username: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "cn=config"
[root@centos]#
最后,让我们测试我们的 OpenLDAP 配置。
Finally, let’s test our OpenLADP configuration.
[root@centos]# slaptest -u
config file testing succeeded
[root@centos]#
Step 4 − 设置 slapd 数据库。
Step 4 − Set up slapd database.
cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG &&
chown ldap:ldap /var/lib/ldap/*
更新 OpenLDAP 架构。
Updates the OpenLDAP Schema.
添加 cosine 和 nis LDAP 架构。
Add the cosine and nis LDAP schemas.
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif
最后,创建企业架构并将其添加到当前 OpenLDAP 配置。
Finally, create the enterprise schema and add it to the current OpenLDAP configuration.
以下是针对一个名为 vmnet.local 的域,其中 LDAP 管理员被称作 ldapadm。
Following is for a domain called vmnet.local with an LDAP Admin called ldapadm.
dn: dc=vmnet,dc=local
dc: vmnet
objectClass: top
objectClass: domain
dn: cn=ldapadm ,dc=vmnet,dc=local
objectClass: organizationalRole
cn: ldapadm
description: LDAP Manager
dn: ou = People,dc=vmnet,dc=local
objectClass: organizationalUnit
ou: People
dn: ou = Group,dc=vmnet,dc=local
objectClass: organizationalUnit
ou: Group
最后,将其导入当前 OpenLDAP 架构。
Finally, import this into the current OpenLDAP schema.
[root@centos]# ldapadd -x -W -D "cn=ldapadm,dc=vmnet,dc=local" -f ./base.ldif
Enter LDAP Password:
adding new entry "dc=vmnet,dc=local"
adding new entry "cn=ldapadm ,dc=vmnet,dc=local"
adding new entry "ou=People,dc=vmnet,dc=local"
adding new entry "ou=Group,dc=vmnet,dc=local"
[root@centos]#
Step 5 − 设置 OpenLDAP 企业用户。
Step 5 − Set up an OpenLDAP Enterprise Users.
打开 vim 或你最喜欢的文本编辑器,然后复制以下格式。这是针对“vmnet.local”LDAP 域中一个名为“entacct”的用户进行设置。
Open vim or your favorite text editor and copy the following format. This is setup for a user named "entacct" on the "vmnet.local" LDAP domain.
dn: uid=entacct,ou=People,dc=vmnet,dc=local
objectClass: top
objectClass: account
objectClass: posixAccount
objectClass: shadowAccount
cn: entacct
uid: entacct
uidNumber: 9999
gidNumber: 100
homeDirectory: /home/enyacct
loginShell: /bin/bash
gecos: Enterprise User Account 001
userPassword: {crypt}x
shadowLastChange: 17058
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
现在,按照保存的方式将上述文件导入 OpenLDAP 架构。
Now import the above files, as saved, into the OpenLdap Schema.
[root@centos]# ldapadd -x -W -D "cn=ldapadm,dc=vmnet,dc=local" -f entuser.ldif
Enter LDAP Password:
adding new entry "uid=entacct,ou=People,dc=vmnet,dc=local"
[root@centos]#
在用户可以访问 LDAP 企业之前,我们需要分配密码,如下所述 -
Before the users can access the LDAP Enterprise, we need to assign a password as follows −
ldappasswd -s password123 -W -D "cn=ldapadm,dc=entacct,dc=local" -x "uid=entacct
,ou=People,dc=vmnet,dc=local"
-s 为用户指定密码
-s specifies the password for the user
-x 是应用密码更新的用户名
-x is the username to which password updated is applied
-D 是针对 LDAP 架构进行身份验证的“指定名称”。
-D is the *distinguished name" to authenticate against LDAP schema.
最后,在登录企业帐户之前,让我们检查我们的 OpenLDAP 条目。
Finally, before logging into the Enterprise account, let’s check our OpenLDAP entry.
[root@centos rdc]# ldapsearch -x cn=entacct -b dc=vmnet,dc=local
# extended LDIF
#
# LDAPv3
# base <dc=vmnet,dc=local> with scope subtree
# filter: cn=entacct
# requesting: ALL
#
# entacct, People, vmnet.local
dn: uid=entacct,ou=People,dc=vmnet,dc=local
objectClass: top
objectClass: account
objectClass: posixAccount
objectClass: shadowAccount
cn: entacct
uid: entacct
uidNumber: 9999
gidNumber: 100
homeDirectory: /home/enyacct
loginShell: /bin/bash
gecos: Enterprise User Account 001
userPassword:: e2NyeXB0fXg=
shadowLastChange: 17058
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
将 /etc/passwd 和 /etc/groups 这样的内容转换为 OpenLDAP 身份验证需要使用迁移工具。这些包含在 migrationtools 包中。然后安装在 /usr/share/migrationtools 中。
Converting things like /etc/passwd and /etc/groups to OpenLDAP authentication requires the use of migration tools. These are included in the migrationtools package. Then, installed into /usr/share/migrationtools.
[root@centos openldap-servers]# ls -l /usr/share/migrationtools/
total 128
-rwxr-xr-x. 1 root root 2652 Jun 9 2014 migrate_aliases.pl
-rwxr-xr-x. 1 root root 2950 Jun 9 2014 migrate_all_netinfo_offline.sh
-rwxr-xr-x. 1 root root 2946 Jun 9 2014 migrate_all_netinfo_online.sh
-rwxr-xr-x. 1 root root 3011 Jun 9 2014 migrate_all_nis_offline.sh
-rwxr-xr-x. 1 root root 3006 Jun 9 2014 migrate_all_nis_online.sh
-rwxr-xr-x. 1 root root 3164 Jun 9 2014 migrate_all_nisplus_offline.sh
-rwxr-xr-x. 1 root root 3146 Jun 9 2014 migrate_all_nisplus_online.sh
-rwxr-xr-x. 1 root root 5267 Jun 9 2014 migrate_all_offline.sh
-rwxr-xr-x. 1 root root 7468 Jun 9 2014 migrate_all_online.sh
-rwxr-xr-x. 1 root root 3278 Jun 9 2014 migrate_automount.pl
-rwxr-xr-x. 1 root root 2608 Jun 9 2014 migrate_base.pl
Step 6 − 最后,我们需要允许访问 slapd 服务,以便它可以提供服务请求。
Step 6 − Finally, we need to allow access to the slapd service so it can service requests.
firewall-cmd --permanent --add-service=ldap
firewall-cmd --reload
Configure LDAP Client Access
配置 LDAP 客户端访问要求客户端上装有以下包:openldap、open-ldap 客户端和 nss_ldap。
Configuring LDAP client access requires the following packages on the client: openldap, open-ldap clients, and nss_ldap.
为客户端系统配置 LDAP 身份验证会更容易。
Configuring LDAP authentication for client systems is a bit easier.
Step 1 − 安装依赖程序包 −
Step 1 − Install dependent packeges −
# yum install -y openldap-clients nss-pam-ldapd
Step 2 − 利用 authconfig 配置 LDAP 认证。
Step 2 − Configure LDAP authentication with authconfig.
authconfig --enableldap --enableldapauth --ldapserver=10.25.0.1 --
ldapbasedn="dc=vmnet,dc=local" --enablemkhomedir --update
Step 3 − 重新启动 nslcd 服务。
Step 3 − Restart nslcd service.
systemctl restart nslcd
Linux Admin - Create SSL Certificates
TLS and SSL Background
TLS 是套接字层安全性的新标准,它取代了 SSL。TLS 提供了更好的加密标准,以及其他安全性和协议包装特性来提升 SSL。常常会互换使用术语 TLS 和 SSL。但是,作为专业的 CentOS 管理员,区分每种技术之间的差异和历史非常重要。
TLS is the new standard for socket layer security, proceeding SSL. TLS offers better encryption standards with other security and protocol wrapper features advancing SSL. Often, the terms TLS and SSL are used interchangeably. However, as a professional CentOS Administrator, it is important to note the differences and history separating each.
SSL 最高版本为 3.0。SSL 由 Netscape 开发和推广为行业标准。在 Netscape 被 AOL(90 年代流行的 ISP,也被称为 America Online)收购后,AOL 从未真正推动 SSL 所需的安全改进。
SSL goes up to version 3.0. SSL was developed and promoted as an industry standard under Netscape. After Netscape was purchased by AOL (an ISP popular in the 90’s otherwise known as America Online) AOL never really promoted the change needed for security improvements to SSL.
在版本 3.1 中,SSL 技术迁移到了开放系统标准,并更改为 TLS。由于 SSL 的版权仍归 AOL 所有,因此创造了一个新术语 - TLS - Transport Layer Security 。所以必须承认 TLS 实际上不同于 SSL。特别是,因为旧的 SSL 技术已知的安全问题,而且一些技术现已过时。
At version 3.1, SSL technology moved into the open systems standards and was changed to TLS. Since copyrights on SSL were still owned by AOL a new term was coined − TLS - Transport Layer Security. So it is important to acknowledge that TLS is in fact different from SSL. Especially, as older SSL technologies have known security issues and some are considered obsolete today.
Note - 本教程在谈论 3.1 及更高版本的技术时将使用术语 TLS。当具体评论 SSL 技术 3.0 及更低版本时,将使用 SSL。
Note − This tutorial will use the term TLS when speaking of technologies 3.1 and higher. Then SSL when commenting specific to SSL technologies 3.0 and lower.
SSL vs TLS Versioning
下表展示了 TLS 和 SSL 版本如何相互关联。我听说过一些人在谈论 SSL 3.2 版本,但是他们的术语可能是从博客中读来的。作为一名专业管理员,我们始终希望使用标准术语。因此,在讨论 SSL 时应该指的是过去的技术。一些简单的事情可以让 CentOS 求职者看起来像经验丰富的 CS 专业人士。
The following table shows how TLS and SSL versioning would relate to one another. I have heard a few people speak in terms of SSL version 3.2. However, they probably got the terminology from reading a blog. As a professional administrator, we always want to use the standard terminology. Hence, while speaking SSL should be a reference to past technologies. Simple things can make a CentOS job seeker look like a seasoned CS Major.
TLS |
SSL |
- |
3.0 |
1.0 |
3.1 |
1.1 |
3.2 |
1.2 |
3.3 |
TLS 为当今互联网用户执行着两个主要功能:首先,它验证一方的身份,被称为 authentication 。其次,它在传输层为缺乏此原生功能的上层协议(ftp、http、电子邮件协议等)提供 end-to-end encryption 。
TLS performs two main functions important to the users of the Internet today: One, it verifies who a party is, known as authentication. Two, it offers end-to-end encryption at the transport layer for upper level protocols that lack this native feature (ftp, http, email protocols, and more).
首先,验证一方的身份对于端到端加密来说非常重要。如果消费者与一个未被授权收款的网站有着加密连接,那么财务数据仍然存在风险。所有网络钓鱼网站都会缺乏以下内容: a properly signed TLS certificate verifying website operators are who they claim to be from a trusted CA 。
The first, verifies who a party is and is important to security as end-to-end encryption. If a consumer has an encrypted connection to a website that is not authorized to take payment, financial data is still at risk. This is what every phishing site will fail to have: a properly signed TLS certificate verifying website operators are who they claim to be from a trusted CA.
只有两种方法可以解决没有正确签名证书的问题:引导用户允许信任已签名的证书的 Web 浏览器,或希望用户不懂技术,不知道受信任的证书颁发机构(CA)的重要作用。
There are only two methods to get around not having a properly signed certificate: trick the user into allowing trust of a web-browser for a self-signed certificate or hope the user is not tech savvy and will not know the importance of a trusted Certificate Authority (or a CA).
在本教程中,我们将使用自签名证书。这意味着,如果不明确授予该证书受信任状态来访问网站的每个 Web 浏览器,就会显示一个错误,阻止用户访问该网站。然后,它将强制用户在访问具有自签名证书的网站之前执行一些操作。请记住,为了安全这是件好事。
In this tutorial, we will be using what is known as a self-signed certificate. This means, without explicitly giving this certificate the status of trusted in every web browser visiting the web-site, an error will be displayed discouraging the users from visiting the site. Then, it will make the user jump though a few actions before accessing a site with a self-signed certificate. Remember for the sake of security this is a good thing.
Install and Configure openssl
openssl 是 TLS 开源实现的标准。openssl 用于 Linux、BSD 发行版、OS X 等系统,甚至支持 Windows。
openssl is the standard for open-source implementations of TLS. openssl is used on systems such as Linux, BSD distributions, OS X, and even supports Windows.
openssl 很重要,因为它提供传输层安全,并抽象出身份验证和端到端加密的详细编程,便于开发人员使用。这就是为什么几乎每个使用 TLS 的开源应用程序都会使用 openssl。它还默认安装在每个现代版本的 Linux 上。
openssl is important, as it provides transport layer security and abstracts the detailed programming of Authentication and end-to-end encryption for a developer. This is why openssl is used with almost every single open-source application using TLS. It is also installed by default on every modern version of Linux.
默认情况下,openssl 应该从至少版本 5 开始安装在 CentOS 上。要确保,我们尝试通过 YUM 安装 openssl。只需运行安装命令,因为 YUM 足够智能,它会让我们知道是否已安装某个软件包。如果出于兼容性原因,我们运行较老版本的 CentOS,则执行 yum -y install 确保 openssl 相对于近期 Heartbleed 漏洞已更新。
By default, openssl should be installed on CentOS from at least version 5 onwards. Just to assure, let’s try installing openssl via YUM. Just run install, as YUM is intelligent enough to let us know if a package is already installed. If we are running an older version of CentOS for compatibility reasons, doing a yum -y install will ensure openssl is updated against the semi-recent heart-bleed vulnerability.
在运行安装程序时,发现 openssl 实际上有一个更新。
When running the installer, it was found there was actually an update to openssl.
[root@centos]# yum -y install openssl
Resolving Dependencies
--> Running transaction check
---> Package openssl.x86_64 1:1.0.1e-60.el7 will be updated
---> Package openssl.x86_64 1:1.0.1e-60.el7_3.1 will be an update
--> Processing Dependency: openssl-libs(x86-64) = 1:1.0.1e-60.el7_3.1 for
package: 1:openssl-1.0.1e-60.el7_3.1.x86_64
--> Running transaction check
---> Package openssl-libs.x86_64 1:1.0.1e-60.el7 will be updated
---> Package openssl-libs.x86_64 1:1.0.1e-60.el7_3.1 will be an update
--> Finished Dependency Resolution
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch
Version Repository Size
===============================================================================
===============================================================================
Updating:
openssl x86_64
1:1.0.1e-60.el7_3.1 updates 713 k
Updating for dependencies:
Create Self-signed Certificate for OpenLDAP
这是为我们之前的 OpenLDAP 安装创建自签名证书的方法。
This is a method to create a self-signed for our previous OpenLDAP installation.
创建自签名 OpenLDAP 证书。
To create an self-signed OpenLDAP Certificate.
openssl req -new -x509 -nodes -out /etc/openldap/certs/myldaplocal.pem -keyout
/etc/openldap/certs/myldaplocal.pem -days 365
[root@centos]# openssl req -new -x509 -nodes -out /etc/openldap/certs/vmnet.pem
-keyout /etc/openldap/certs/vmnet.pem -days 365
Generating a 2048 bit RSA private key
.............................................+++
................................................+++
writing new private key to '/etc/openldap/certs/vmnet.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:US
State or Province Name (full name) []:Califonia
Locality Name (eg, city) [Default City]:LA
Organization Name (eg, company) [Default Company Ltd]:vmnet
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:centos
Email Address []:bob@bobber.net
[root@centos]#
我们的 OpenLDAP 证书现在应该放在 /etc/openldap/certs/ 中。
Now our OpenLDAP certificates should be placed in /etc/openldap/certs/
[root@centos]# ls /etc/openldap/certs/*.pem
/etc/openldap/certs/vmnetcert.pem /etc/openldap/certs/vmnetkey.pem
[root@centos]#
如您所见,我们已在 /etc/openldap/certs/ 目录中安装了证书和密钥。最后,我们需要更改每个证书和密钥的权限,因为它们当前归 root 用户所有。
As you can see, we have both the certificate and key installed in the /etc/openldap/certs/ directories. Finally, we need to change the permissions to each, since they are currently owned by the root user.
[root@centos]# chown -R ldap:ldap /etc/openldap/certs/*.pem
[root@centos]# ls -ld /etc/openldap/certs/*.pem
-rw-r--r--. 1 ldap ldap 1395 Feb 20 10:00 /etc/openldap/certs/vmnetcert.pem
-rw-r--r--. 1 ldap ldap 1704 Feb 20 10:00 /etc/openldap/certs/vmnetkey.pem
[root@centos]#
Create Self-signed Certificate for Apache Web Server
在本教程中,我们将假定 Apache 已安装。我们在另一个教程(配置 CentOS 防火墙)中安装了 Apache,并将为未来的教程介绍 Apache 高级安装。因此,如果您尚未安装 Apache,请继续操作。
In this tutorial, we will assume Apache is already installed. We did install Apache in another tutorial (configuring CentOS Firewall) and will go into advanced installation of Apache for a future tutorial. So, if you have not already installed Apache, please follow along.
一旦可以使用以下步骤安装 Apache HTTPd −
Once Apache HTTPd can be installed using the following steps −
Step 1 − 为 Apache httpd 服务器安装 mod_ssl。
Step 1 − Install mod_ssl for Apache httpd server.
首先,我们需要使用 mod_ssl 配置 Apache。使用 YUM 软件包管理器非常简单 −
First we need to configure Apache with mod_ssl. Using the YUM package manager this is pretty simple −
[root@centos]# yum -y install mod_ssl
然后重新载入您的 Apache 守护进程,以确保 Apache 使用新配置。
Then reload your Apache daemon to ensure Apache uses the new configuration.
[root@centos]# systemctl reload httpd
此时,Apache 已配置为在 local host 上支持 TLS 连接。
At this point, Apache is configured to support TLS connections on the local host.
Step 2 − 创建自签名 ssl 证书。
Step 2 − Create the self-signed ssl certificate.
首先,让我们配置我们的私有 TLS 密钥目录。
First, let’s configure our private TLS key directory.
[root@centos]# mkdir /etc/ssl/private
[root@centos]# chmod 700 /etc/ssl/private/
Note − 确保只有 root 具有对此目录的读/写访问权限。如果世界拥有读/写访问权限,您的私钥可用于解密嗅探的流量。
Note − Be sure only the root has read/write access to this directory. With world read/write access, your private key can be used to decrypt sniffed traffic.
生成证书和密钥文件。
Generating the certificate and key files.
[root@centos]# sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout
/etc/ssl/private/self-gen-apache.key -out /etc/ssl/certs/self-sign-apache.crt
Generating a 2048 bit RSA private key
..........+++
....+++
-----
Country Name (2 letter code) [XX]:US
State or Province Name (full name) []:xx
Locality Name (eg, city) [Default City]:xxxx
Organization Name (eg, company) [Default Company Ltd]:VMNET
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:centos.vmnet.local
Email Address []:
[root@centos]#
Note − 如果没有注册的域名,您可以使用服务器的公共 IP 地址。
Note − You can use public IP Address of the server if you don’t have a registered domain name.
让我们看看我们的证书 −
Let’s take a look at our certificate −
[root@centos]# openssl x509 -in self-sign-apache.crt -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 17620849408802622302 (0xf489d52d94550b5e)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=UT, L=xxxx, O=VMNET, CN=centos.vmnet.local
Validity
Not Before: Feb 24 07:07:55 2017 GMT
Not After : Feb 24 07:07:55 2018 GMT
Subject: C=US, ST=UT, L=xxxx, O=VMNET, CN=centos.vmnet.local
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:c1:74:3e:fc:03:ca:06:95:8d:3a:0b:7e:1a:56:
f3:8d:de:c4:7e:ee:f9:fa:79:82:bf:db:a9:6d:2a:
57:e5:4c:31:83:cf:92:c4:e7:16:57:59:02:9e:38:
47:00:cd:b8:31:b8:34:55:1c:a3:5d:cd:b4:8c:b0:
66:0c:0c:81:8b:7e:65:26:50:9d:b7:ab:78:95:a5:
31:5e:87:81:cd:43:fc:4d:00:47:5e:06:d0:cb:71:
9b:2a:ab:f0:90:ce:81:45:0d:ae:a8:84:80:c5:0e:
79:8a:c1:9b:f4:38:5d:9e:94:4e:3a:3f:bd:cc:89:
e5:96:4a:44:f5:3d:13:20:3d:6a:c6:4d:91:be:aa:
ef:2e:d5:81:ea:82:c6:09:4f:40:74:c1:b1:37:6c:
ff:50:08:dc:c8:f0:67:75:12:ab:cd:8d:3e:7b:59:
e0:83:64:5d:0c:ab:93:e2:1c:78:f0:f4:80:9e:42:
7d:49:57:71:a2:96:c6:b8:44:16:93:6c:62:87:0f:
5c:fe:df:29:89:03:6e:e5:6d:db:0a:65:b2:5e:1d:
c8:07:3d:8a:f0:6c:7f:f3:b9:32:b4:97:f6:71:81:
6b:97:e3:08:bd:d6:f8:19:40:f1:15:7e:f2:fd:a5:
12:24:08:39:fa:b6:cc:69:4e:53:1d:7e:9a:be:4b:
以下是我们使用 openssl 命令的每个选项的解释 −
Here is an explanation for each option we used with the openssl command −
Command |
Action |
req -X509 |
Use X.509 CSR management PKI standard for key management. |
-nodes |
Do not secure our certificate with a passphrase. Apache must be able to use the certificate without interruption of a passphrase. |
-days 2555 |
Tells the validity of the certificate to 7 years or 2555 days. Time period can be adjusted as needed. |
-newkey rsa:2048 |
Specified to generate both key and certificate using RSA at 2048 bits in length. |
接下来,我们要为与客户端协商 PFS 创建一个 Diffie-Heliman 组。
Next, we want to create a Diffie-Heliman group for negotiating PFS with clients.
[centos#] openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
这将需要 5 到 15 分钟的时间。
This will take from 5 to 15 minutes.
Perfect Forward Secrecy − 用于在私钥受损的情况下保护会话数据。这将在客户端和服务器之间生成一个密钥,该密钥对每个会话都是唯一的。
Perfect Forward Secrecy − Used to secure session data in case the private key has been compromised. This will generate a key used between the client and the server that is unique for each session.
现在,将完美前向保密配置添加到我们的证书。
Now, add the Perfect Forward Secrecy configuration to our certificate.
[root@centos]# cat /etc/ssl/certs/dhparam.pem | tee -a /etc/ssl/certs/self-sign-apache.crt
Configure Apache to Use Key and Certificate Files
我们将对 /etc/httpd/conf.d/ssl.conf − 进行更改
We will be making changes to /etc/httpd/conf.d/ssl.conf −
我们将对 ssl.conf 进行以下更改。不过,在进行更改之前,我们应该备份原始文件。在高级文本编辑器(如 vi 或 emcas)中对生产服务器进行更改时,在进行编辑之前始终备份配置文件是一种最佳实践。
We will make the following changes to ssl.conf. However, before we do that we should back the original file up. When making changes to a production server in an advanced text editor like vi or emcas, it is a best practice to always backup configuration files before making edits.
[root@centos]# cp /etc/httpd/conf.d/ssl.conf ~/
现在让我们继续编辑,方法是将 ssl.conf 的已知工作副本复制到我们主文件夹的根目录。
Now let’s continue our edits after copying a known-working copy of ssl.conf to the root of our home folder.
-
Locate
-
Edit both DocumentRoot and ServerName as follows.
\\# General setup for the virtual host, inherited from global configuration
DocumentRoot "/var/www/html"
ServerName centos.vmnet.local:443
DocumentRoot 这是您的默认 Apache 目录的路径。该文件夹中应有一个默认页面,该页面将显示一个 HTTP 请求,要求获取 Web 服务器或网站的默认页面。
DocumentRoot this is the path to your default apache directory. In this folder should be a default page that will display a HTTP request asking for the default page of your web server or site.
ServerName 是服务器名称,它可以是服务器的 IP 地址或主机名。对于 TLS,最佳做法是使用主机名创建证书。从我们的 OpenLdap 教程中,我们在本地企业域上创建了名为 centos 的主机名:vmnet.local
ServerName is the server name that can be either an ip address or the host name of the server. For TLS, it is a best practice to create a certificate with a host name. From our OpenLdap tutorial, we created a hostname of centos on the local enterprise domain: vmnet.local
现在我们要对以下行进行注释。
Now we want to comment the following lines out.
SSLProtocol
# SSL Protocol support:
# List the enable protocol levels with which clients will be able to
# connect. Disable SSLv2 access by default:
~~~~> #SSLProtocol all -SSLv2
# SSL Cipher Suite:
# List the ciphers that the client is permitted to negotiate.
# See the mod_ssl documentation for a complete list.
~~~~> #SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5:!SEED:!IDEA
然后让 Apache 知道在哪里找到我们的证书和私有/公钥对。
Then let Apache know where to find our certificate and private/public key pair.
Specify path to our self-signed certificate file
# Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate. If
# the certificate is encrypted, then you will be prompted for a
# pass phrase. Note that a kill -HUP will prompt again. A new
# certificate can be generated using the genkey(1) command.
~~~~> SSLCertificateFile /etc/ssl/certs/self-sign-apache.crt
specify path to our private key file
# Server Private Key:
# If the key is not combined with the certificate, use this
# directive to point at the key file. Keep in mind that if
# you've both a RSA and a DSA private key you can configure
# both in parallel (to also allow the use of DSA ciphers, etc.)
~~~~> SSLCertificateKeyFile /etc/ssl/private/self-gen-apache.key
最后,我们需要允许通过端口 443 的入站连接到 https。
Finally, we need to allow inbound connections to https over port 443.
Install Apache Web Server CentOS 7
在本章中,我们将讲述一些 Apache HTTP Server 如何诞生的背景,然后在 CentOS Linux 7 上安装最新稳定版本。
In this chapter, we will learn a little about the background of how Apache HTTP Server came into existence and then install the most current stable version on CentOS Linux 7.
Brief History on Apache WebServer
Apache 是一个由来已久的 Web 服务器。事实上,几乎与 http 本身一样长!
Apache is a web server that has been around for a long time. In fact, almost as long as the existence of http itself!
Apache 最初是美国国家超级计算应用中心(也称为 NCSA)的一个相当小的项目。在 90 年代中期,“httpd”(当时称为这个名字)是互联网上最流行的 Web 服务器平台,拥有约 90% 或以上的市场份额。
Apache started out as a rather small project at the National Center for Supercomputing Applications also known as NCSA. In the mid-90’s "httpd", as it was called, was by far the most popular web-server platform on the Internet, having about 90% or more of the market share.
当时,这是一个简单的项目。被称为网站管理员的熟练 IT 人员负责:维护 Web 服务器平台和 Web 服务器软件以及前端和后端网站开发。httpd 的核心是其使用称为插件或扩展的自定义模块的能力。网站管理员足够熟练,可以编写核心服务器软件的补丁。
At this time, it was a simple project. Skilled I.T. staff known as webmaster were responsible for: maintaining web server platforms and web server software as well as both front-end and back-end site development. At the core of httpd was its ability to use custom modules known as plugins or extensions. A webmaster was also skilled enough to write patches to core server software.
在 90 年代中后期,httpd 的高级开发人员和项目经理离开 NCSA 去做别的事情。这使得最流行的 Web 守护进程处于停滞状态。
Sometime in the late-mid-90’s, the senior developer and project manager for httpd left NCSA to do other things. This left the most popular web-daemon in a state of stagnation.
由于 httpd 的使用如此广泛,一群经验丰富的 httpd 网站管理员要求召开峰会,商讨 httpd 的未来。他们决定协调并应用最佳扩展和补丁到当前的稳定版本中。然后,httpd 领域的鼻祖诞生了,并被命名为 Apache HTTP Server。
Since the use of httpd was so widespread a group of seasoned httpd webmasters called for a summit reqarding the future of httpd. It was decided to coordinate and apply the best extensions and patches into a current stable release. Then, the current grand-daddy of http servers was born and christened Apache HTTP Server.
Little Known Historical Fact - Apache 的名字不是来自美洲原住民部落的勇士。实际上,它的名字是这样创造和命名的:由许多才华横溢的计算机科学家提供的许多修复(或补丁)组合而成,即 patchy 或 Apache 。
Little Known Historical Fact − Apache was not named after a Native American Tribe of warriors. It was in fact coined and named with a twist: being made from many fixes (or patches) from many talented Computer Scientists: a patchy or Apache.
Install Current Stable Version on CentOS Linux 7
Step 1 - 通过 yum 安装 httpd。
Step 1 − Install httpd via yum.
yum -y install httpd
此时,Apache HTTP Server 将通过 yum 安装。
At this point Apache HTTP Server will install via yum.
Step 2 - 编辑针对您的 httpd 需求的 httpd.conf 文件。
Step 2 − Edit httpd.conf file specific to your httpd needs.
在默认的 Apache 安装中,Apache 的配置文件名为 httpd.conf,位于 /etc/httpd/ 中。因此,让我们在 vim 中打开它。
With a default Apache install, the configuration file for Apache is named httpd.conf and is located in /etc/httpd/. So, let’s open it in vim.
在 vim 中打开的 httpd.conf 的前几行 -
The first few lines of httpd.conf opened in vim −
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
我们将针对 CentOS 安装进行以下更改,以便从 http 端口 80 处理 http 请求。
We will make the following changes to allow our CentOS install to serve http requests from http port 80.
Listening host and port
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
从这里,我们更改 Apache 以侦听特定端口或 IP 地址。例如,如果我们想在备用端口(如 8080)上运行 httpd 服务,或者如果我们的 Web 服务器配置了具有单独 IP 地址的多个接口。
From here, we change Apache to listen on a certain port or IP Address. For example, if we want to run httpd services on an alternative port such as 8080. Or if we have our web-server configured with multiple interfaces with separate IP addresses.
Listen
防止 Apache 附加到每个 IP 地址上的每个侦听守护进程。这有助于停止仅指定 IPv6 或 IPv4 流量。甚至绑定到多宿主主上的所有网络接口。
Keeps Apache from attaching to every listening daemon onto every IP Address. This is useful to stop specifying only IPv6 or IPv4 traffic. Or even binding to all network interfaces on a multi-homed host.
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
Listen 10.0.0.25:80
#Listen 80
DocumentRoot
“文档根”是 Apache 将查找索引文件以在访问服务器时提供请求的默认目录: http://www.yoursite.com/ 将从文档根检索和提供索引文件。
The "document root" is the default directory where Apache will look for an index file to serve for requests upon visiting your sever: http://www.yoursite.com/ will retrieve and serve the index file from your document root.
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html"
Step 3 - 启动并启用 httpd 服务。
Step 3 − Start and Enable the httpd Service.
[root@centos rdc]# systemctl start httpd && systemctl reload httpd
[root@centos rdc]#
Step 4 - 配置防火墙以允许访问端口 80 请求。
Step 4 − Configure firewall to allow access to port 80 requests.
[root@centos]# firewall-cmd --add-service=http --permanent
Linux Admin - MySQL Setup On CentOS 7
正如在将 CentOS 配置为与 Maria DB 配合使用时,CentOS 7 yum 存储库中没有本地 MySQL 包。考虑到这一点,我们需要添加一个 MySQL 托管存储库。
As touched upon briefly when configuring CentOS for use with Maria DB, there is no native MySQL package in the CentOS 7 yum repository. To account for this, we will need to add a MySQL hosted repository.
MariaDB vs MySQL On CentOS Linux
需要指出的一点是 MySQL 需要一组与 MariaDB 不同的基本依赖项。同时使用 MySQL 会打破 CentOS 的概念和哲学:专为实现最大可靠性而设计的生产包。
One thing to note is MySQL will require a different set of base dependencies from MariaDB. Also using MySQL will break the concept and philosophy of CentOS: production packages designed for maximum reliability.
因此,在决定是否使用 Maria 还是 MySQL 时应权衡这两个选项:我的当前数据库模式是否适用于 Maria?安装 MySQL 相比使用 Maria 有什么优势?
So when deciding whether to use Maria or MySQL one should weigh two options: Will my current DB Schema work with Maria? What advantage does installing MySQL over Maria give me?
Maria 组件对 MySQL 结构完全透明,具有更好的许可,并增加了一些效率。除非有令人信服的理由出现,否则建议将 CentOS 配置为使用 MariaDB。
Maria components are 100% transparent to MySQL structure, with some added efficiency with better licensing. Unless a compelling reason comes along, it is advised to configure CentOS to use MariaDB.
在 CentOS 上支持 Maria 的最大原因是:
The biggest reasons for favoring Maria on CentOS are −
-
Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria.
-
CentOS is designed to run with Maria. Hence, Maria will offer better stability.
-
Maria is officially supported for CentOS.
Download and Add the MySQL Repository
从以下链接下载并安装 MySQL 存储库:
We will want to download and install the MySQL repository from −
Step 1 − 下载存储库。
Step 1 − Download the Repository.
存储库经过方便地打包,使用 rpm 包可以轻松安装。可使用 wget 下载:
The repository comes conveniently packaged in an rpm package for easy installation. It can be downloaded with wget −
[root@centos]# wget http://repo.mysql.com/mysql-community-release-el75.noarch.rpm
--2017-02-26 03:18:36-- http://repo.mysql.com/mysql-community-release-el75.noarch.rpm
Resolving repo.mysql.com (repo.mysql.com)... 104.86.98.130
Step 2 −从 YUM 安装 MySQL。
Step 2 − Install MySQL From YUM.
我们现在可以使用 yum 包管理器来安装 MySQL:
We can now use the yum package manager to install MySQL −
[root@centos]# yum -y install mysql-server
Step 3 −启动并启用 MySQL 守护进程服务。
Step 3 − Start and Enable the MySQL Daemon Service.
[root@centos]# systemctl start mysql
[root@centos]# systemctl enable mysql
Step 4 −确保我们的 MySQL 服务正在运行中。
Step 4 − Make sure our MySQL service is up and running.
[root@centos]# netstat -antup | grep 3306
tcp6 0 0 :::3306 :::* LISTEN 6572/mysqld
[root@centos]#
注意:我们不会允许任何防火墙规则通过。通常将 MySQL 配置为使用 Unix Domain Sockets 。这确保只有 LAMP 堆栈的 Web 服务器在本地才能访问 MySQL 数据库,从而消除了数据库软件中的整个攻击向量维度。
Note − We will not allow any firewall rules through. It’s common to have MySQL configured to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally, can access the MySQL database, taking out a complete dimension in the attack vector at the database software.
Set Up Postfix MTA and IMAP/POP3
为了从我们的 CentOS 7 服务器发送电子邮件,我们需要进行设置来配置一个现代邮件传输代理 (MTA)。邮件传输代理是通过 SMTP 为系统用户或公司互联网域发送出站邮件的守护进程。
In order to send an email from our CentOS 7 server, we will need the setup to configure a modern Mail Transfer Agent (MTA). Mail Transfer Agent is the daemon responsible for sending outbound mail for system users or corporate Internet Domains via SMTP.
值得注意的是,本教程仅教授针对本地使用而设置守护进程的过程。我们不会详细介绍为业务运营设置 MTA 的高级配置。这是多种技能的组合,包括但不限于:DNS、获取未列入黑名单的静态可路由 IP 地址以及配置高级安全和服务设置。简而言之,本教程旨在让你熟悉基本配置。请不要将本教程用于面向互联网的主机的 MTA 配置。
It is worth noting, this tutorial only teaches the process of setting up the daemon for local use. We do not go into detail about advanced configuration for setting up an MTA for business operations. This is a combination of many skills including but not limited to: DNS, getting a static routable IP address that is not blacklisted, and configuring advanced security and service settings. In short, this tutorial is meant to familiarize you with the basic configuration. Do not use this tutorial for MTA configuration of an Internet facing host.
我们将 Postfix 作为本教程的 MTA,因为该 MTA 同时注重安全性和易于管理。CentOS 旧版本中安装的默认 MTA 为 Sendmail。 Sendmail 是一个优秀的 MTA。然而,据作者的浅见,Postfix 在针对 MTA 的以下注释中达到了最佳点。Postfix 已在 CentOS 的最新版本中替代 Sendmail 成为默认 MTA。
With its combined focus on both security and the ease of administration, we have chosen Postfix as the MTA for this tutorial. The default MTA installed in the older versions of CentOS is Sendmail. Sendmail is a great MTA. However, of the author’s humble opinion, Postfix hits a sweet spot when addressing the following notes for an MTA. With the most current version of CentOS, Postfix has superseded Sendmail as the default MTA.
Postfix 是一个被广泛使用且文档齐全的 MTA。它在不断地维护和开发之中。它在思想上要求配置极少(这只是电子邮件),而且系统资源利用率高(同样,这只是电子邮件)。
Postfix is a widely used and well documented MTA. It is actively maintained and developed. It requires minimal configuration in mind (this is just email) and is efficient with system resources (again, this is just email).
Step 1 - 从 YUM 包管理器安装 Postfix。
Step 1 − Install Postfix from YUM Package Manager.
[root@centos]# yum -y install postfix
Step 2 - 配置 Postfix 配置文件。
Step 2 − Configure Postfix config file.
Postfix 配置文件位于 - /etc/postfix/main.cf
The Postfix configuration file is located in − /etc/postfix/main.cf
在 Postfix 简单配置中,必须为特定主机配置以下内容:主机名、域、原点、inet_interfaces 和目标。
In a simple Postfix configuration, the following must be configured for a specific host: host name, domain, origin, inet_interfaces, and destination.
Configure the hostname - 主机名是 Postfix 主机的完全限定域名。在 OpenLDAP 章节中,我们在域 vmnet.local 上将 CentOS 服务器命名为:centos。为了本章,我们使用这个名称。
Configure the hostname − The hostname is a fully qualified domain name of the Postfix host. In OpenLDAP chapter, we named the CentOS box: centos on the domain vmnet.local. Let’s stick with that for this chapter.
# The myhostname parameter specifies the internet hostname of this
# mail system. The default is to use the fully-qualified domain name
# from gethostname(). $myhostname is used as a default value for many
# other configuration parameters.
#
myhostname = centos.vmnet.local
Configure the domain - 如上所述,我们将在本教程中使用域 vmnet.local
Configure the domain − As stated above, the domain we will be using in this tutorial is vmnet.local
# The mydomain parameter specifies the local internet domain name.
# The default is to use $myhostname minus the first component.
# $mydomain is used as a default value for many other configuration
# parameters.
#
mydomain = vmnet.local
Configure the origin - 对于单服务器和域设置,我们只需取消以下部分的注释并保留默认 Postfix 变量即可。
Configure the origin − For a single server and domain set up, we just need to uncomment the following sections and leave the default Postfix variables.
# SENDING MAIL
#
# The myorigin parameter specifies the domain that locally-posted
# mail appears to come from. The default is to append $myhostname,
# which is fine for small sites. If you run a domain with multiple
# machines, you should (1) change this to $mydomain and (2) set up
# a domain-wide alias database that aliases each user to
# user@that.users.mailhost.
#
# For the sake of consistency between sender and recipient addresses,
# myorigin also specifies the default domain name that is appended
# to recipient addresses that have no @domain part.
#
myorigin = $myhostname
myorigin = $mydomain
Configure the network interfaces - 我们将保留 Postfix 对我们的单个网络接口和关联于该接口的所有协议和 IP 地址进行监听。只需为 Postfix 启用默认设置即可完成此操作。
Configure the network interfaces − We will leave Postfix listening on our single network interface and all protocols and IP Addresses associated with that interface. This is done by simply leaving the default settings enabled for Postfix.
# The inet_interfaces parameter specifies the network interface
# addresses that this mail system receives mail on. By default,
# the software claims all active interfaces on the machine. The
# parameter also controls delivery of mail to user@[ip.address].
#
# See also the proxy_interfaces parameter, for network addresses that
# are forwarded to us via a proxy or network address translator.
#
# Note: you need to stop/start Postfix when this parameter changes.
#
#inet_interfaces = all
#inet_interfaces = $myhostname
#inet_interfaces = $myhostname, localhost
#inet_interfaces = localhost
# Enable IPv4, and IPv6 if supported
inet_protocols = all
Step 3 - 配置 Postfix 的 SASL 支持。
Step 3 − Configure SASL Support for Postfix.
如果没有 SASL 认证支持,Postfix 将只允许从本地用户发送电子邮件。或者用户从本地域发送电子邮件时将出现中继拒绝错误。
Without SASL Authentication support, Postfix will only allow sending email from local users. Or it will give a relaying denied error when the users send email away from the local domain.
Note - SASL 或 Simple Application Security Layer Framework 是一个为不同应用程序层协议之间的不同技术提供认证支持的框架。而不是将认证机制留给应用程序层协议,SASL 开发人员(和使用者)充分利用了用于高级协议的当前认证协议,这些高级协议可能不具备方便性或者更安全的认证(当谈及对安全服务的访问时)。
Note − SASL or Simple Application Security Layer Framework is a framework designed for authentication supporting different techniques amongst different Application Layer protocols. Instead of leaving authentication mechanisms up to the application layer protocol, SASL developers (and consumers) leverage current authentication protocols for higher level protocols that may not have the convenience or more secure authentication (when speaking of access to secured services) built in.
Install the "cyrus-sasl* package
[root@centos]# yum -y install cyrus-sasl
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: repos.forethought.net
* extras: repos.dfw.quadranet.com
* updates: mirrors.tummy.com
Package cyrus-sasl-2.1.26-20.el7_2.x86_64 already installed and latest version
Nothing to do
Configure /etc/postfix/main.cf for SASL Auth
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions =
permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
My SASL Options in main.conf
##Configure SASL Options Entries:
smtpd_sasl_auth_enable = yes
smptd_recipient_restrictions =
permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
smtp_sasl_type = dovecot
smtp_sasl_path = private/auth/etc
Step 4 - 配置 FirewallD 以允许入站 SMTP 服务。
Step 4 − Configure FirewallD to allow incoming SMTP Services.
[root@centos]# firewall-cmd --permanent --add-service=smtp
success
[root@centos]# firewall-cmd --reload
success
[root@centos]#
现在让我们检查一下我们的 CentOS 主机是否正在允许和响应端口 25(SMTP)上的请求。
Now let’s check to make sure our CentOS host is allowing and responding to the requests on port 25 (SMTP).
Nmap scan report for 172.16.223.132
Host is up (0.00035s latency).
Not shown: 993 filtered ports
PORT STATE SERVICE
20/tcp closed ftp-data
21/tcp open ftp
22/tcp open ssh
25/tcp open smtp
80/tcp open http
389/tcp open ldap
443/tcp open https
MAC Address: 00:0C:29:BE:DF:5F (VMware)
你看,SMTP 正在监听,守护进程正在响应该内部 LAN 发出的请求。
As you can see, SMTP is listening and the daemon is responding to the requests from our internal LAN.
Install Dovecot IMAP and POP3 Server
Dovecot 是一个安全的 IMAP 和 POP3 服务器,设计用于处理小型到大型组织的入站邮件需求。由于它与 CentOS 进行了大量使用,我们将使用 Dovecot 作为在 CentOS 和 MTA SASL 提供程序中安装和配置入站邮件服务器的示例。
Dovecot is a secure IMAP and POP3 Server deigned to handle incoming mail needs of a smaller to larger organization. Due to its prolific use with CentOS, we will be using Dovecot as an example of installing and configuring an incoming mail-server for CentOS and MTA SASL Provider.
如前所述,我们不会为 DNS 配置 MX 记录,也不会创建安全规则以允许我们的服务处理域的邮件。因此,只需在面向因特网的主机上设置这些服务,就有可能为 SPF 记录预留安全漏洞。
As noted previously, we will not be configuring MX records for DNS or creating secure rules allowing our services to handle mail for a domain. Hence, just setting these services up on an Internet facing host may leave leverage room for security holes w/o SPF Records.
Step 1 - 安装 Dovecot。
Step 1 − Install Dovecot.
[root@centos]# yum -y install dovecot
Step 2 配置 dovecot。
Step 2 − Configure dovecot.
dovecot 的主配置文件位于:/etc/dovecot.conf。我们首先来备份主配置文件。进行任何编辑前,最好养成定期备份配置文件的习惯。这样,如果(例如)换行符被文本编辑器破坏了,变更也不会丢失。将当前的备份复制到生产环境就可以轻松还原。
The main configuration file for dovecot is located at: /etc/dovecot.conf. We will first back up the main configuration file. It is a good practice to always backup configuration files before making edits. This way id (for example) line breaks get destroyed by a text editor, and years of changes are lost. Reverting is easy as copying the current backup into production.
Enable protocols and daemon service for dovecot
# Protocols we want to be serving.
protocols = imap imaps pop3 pop3s
现在,我们需要让 dovecot daemon 在启动时开始侦听 -
Now, we need to enable the dovecot daemon to listen on startup −
[root@localhost]# systemctl start dovecot
[root@localhost]# systemctl enable dovecot
让我们确保 Dovecot 在指定端口上对以下服务进行本地侦听:imap、pop3、imap 安全和 pop3 安全。
Let’s make sure Dovecot is listening locally on the specified ports for: imap, pop3, imap secured, and pop3 secured.
[root@localhost]# netstat -antup | grep dovecot
tcp 0 0 0.0.0.0:110 0.0.0.0:* LISTEN 4368/dovecot
tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 4368/dovecot
tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 4368/dovecot
tcp 0 0 0.0.0.0:995 0.0.0.0:* LISTEN 4368/dovecot
tcp6 0 0 :::110 :::* LISTEN 4368/dovecot
tcp6 0 0 :::143 :::* LISTEN 4368/dovecot
tcp6 0 0 :::993 :::* LISTEN 4368/dovecot
tcp6 0 0 :::995 :::* LISTEN 4368/dovecot
[root@localhost]#
如您所见,dovecot 在指定端口上对 IPv4 和 IPv4 进行侦听。
As seen, dovecot is listening on the specified ports for IPv4 and IPv4.
POP3 |
110 |
POP3s |
995 |
IMAP |
143 |
IMAPs |
993 |
现在,我们需要制定一些防火墙规则。
Now, we need to make some firewall rules.
[root@localhost]# firewall-cmd --permanent --add-port=110/tcp
success
[root@localhost]# firewall-cmd --permanent --add-port=143/tcp
success
[root@localhost]# firewall-cmd --permanent --add-port=995/tcp
success
[root@localhost]# firewall-cmd --permanent --add-port=993/tcp
success
[root@localhost]# firewall-cmd --reload
success
[root@localhost]#
我们的传入邮件服务器正在接受 LAN 上的请求以使用 POP3、POP3s、IMAP 和 IMAPs 主机。
Our incoming mail sever is accepting requests for POP3, POP3s, IMAP, and IMAPs to hosts on the LAN.
Port Scanning host: 192.168.1.143
Open TCP Port: 21 ftp
Open TCP Port: 22 ssh
Open TCP Port: 25 smtp
Open TCP Port: 80 http
Open TCP Port: 110 pop3
Open TCP Port: 143 imap
Open TCP Port: 443 https
Open TCP Port: 993 imaps
Open TCP Port: 995 pop3s
Linux Admin - Install Anonymous FTP
在深入了解在 CentOS 上安装 FTP 之前,我们需要了解有关其用法和安全性的少量信息。 FTP 是用于在计算机系统之间传输文件的高效且经过完善的协议。几十年来,FTP 一直在使用和完善。对于通过存在延迟的网络有效传输文件或者为了快速速度传输文件,FTP 是一个极佳的选择。比 SAMBA 或者 SMB 更是如此。
Before delving into installing FTP on CentOS, we need to learn a little about its use and security. FTP is a really efficient and well-refined protocol for transferring files between the computer systems. FTP has been used and refined for a few decades now. For transferring files efficiently over a network with latency or for sheer speed, FTP is a great choice. More so than either SAMBA or SMB.
但是,FTP 确实存在一些安全问题。实际上,存在一些严重的安全问题。FTP 使用非常弱的明文身份验证方法。出于此原因,经过身份验证的会话应该依赖于 sFTP 或 FTPS,其中 TLS 用于登录和传输会话的端到端加密。
However, FTP does possess some security issues. Actually, some serious security issues. FTP uses a really weak plain-text authentication method. It is for this reason authenticated sessions should rely on sFTP or FTPS, where TLS is used for end-to-end encryption of the login and transfer sessions.
即使有上述警告,纯老式 FTP 仍然可以在当今的商业环境中使用。主要用途是匿名 FTP 文件存储库。在这种情况下,无需进行身份验证即可下载或上传文件。匿名 FTP 使用的一些示例包括 -
With the above caveats, plain old FTP still has its use in the business environment today. The main use is, anonymous FTP file repositories. This is a situation where no authentication is warranted to download or upload files. Some examples of anonymous FTP use are −
-
Large software companies still use anonymous ftp repositories allowing Internet users to download shareware and patches.
-
Allowing internet users to upload and download public documents.
-
Some applications will automatically send encrypted, archived logs for or configuration files to a repository via FTP.
因此,作为 CentOS 管理员,仍然具备安装和配置 FTP 的技能非常重要。
Hence, as a CentOS Administrator, being able to install and configure FTP is still a designed skill.
我们将使用一个名为 vsFTP 或非常安全的 FTP 守护程序的 FTP 守护程序。vsFTP 已在开发中使用了一段时间。它以安全、易于安装和配置以及可靠而著称。
We will be using an FTP daemon called vsFTP, or Very Secure FTP Daemon. vsFTP has been used in development for a while. It has a reputation for being secure, easy to install and configure, and is reliable.
Step 1 - 使用 YUM 软件包管理器安装 vsFTPd。
Step 1 − Install vsFTPd with the YUM Package Manager.
[root@centos]# yum -y install vsftpd.x86_64
Step 2 - 使用 systemctl 配置 vsFTP 以在启动时启动。
Step 2 − Configure vsFTP to Start on Boot with systemctl.
[root@centos]# systemctl start vsftpd
[root@centos]# systemctl enable vsftpd
Created symlink from /etc/systemd/system/multi-
user.target.wants/vsftpd.service to /usr/lib/systemd/system/vsftpd.service.
Step 3 - 配置 FirewallD 以允许 FTP 控制和传输会话。
Step 3 − Configure FirewallD to allow FTP control and transfer sessions.
[root@centos]# firewall-cmd --add-service=ftp --permanent
success
[root@centos]#
确保我们的 FTP 守护程序正在运行。
Assure our FTP daemon is running.
[root@centos]# netstat -antup | grep vsftp
tcp6 0 0 :::21 :::* LISTEN 13906/vsftpd
[root@centos]#
Step 4 - 为匿名访问配置 vsFTPD。
Step 4 − Configure vsFTPD For Anonymous Access.
Change owner and group of FTP root to ftp
[root@centos]# chown ftp:ftp /ftp
Set minimal permissions for FTP root:
[root@centos]# chmod -R 666 /ftp/
[root@centos]# ls -ld /ftp/
drw-rw-rw-. 2 ftp ftp 6 Feb 27 02:01 /ftp/
[root@centos]#
在这种情况下,我们向用户授予了对整个根 FTP 树的读/写访问权限。
In this case, we gave users read/write access to the entire root FTP tree.
Configure /etc/vsftpd/vsftpd.conf"
[root@centos]# vim /etc/vsftpd/vsftpd.conf
# Example config file /etc/vsftpd/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
我们希望在 vsftp.conf 文件中更改以下指令。
We will want to change the following directives in the vsftp.conf file.
-
Enable Anonymous uploading by uncommenting anon_mkdir_write_enable=YES
-
chown uploaded files to owned by the system ftp user chown_uploads = YES chown_username = ftp
-
Change system user used by vsftp to the ftp user: nopriv_user = ftp
-
Set the custom banner for the user to read before signing in. ftpd_banner = Welcome to our Anonymous FTP Repo. All connections are monitored and logged.
-
Let’s set IPv4 connections only − listen = YES listen_ipv6 = NO
现在,我们需要重新启动或 HUP vsftp 服务来应用更改。
Now, we need to restart or HUP the vsftp service to apply our changes.
[root@centos]# systemctl restart vsftpd
让我们连接到我们的 FTP 主机并确保我们的 FTP 守护进程正在响应。
Let’s connect to our FTP host and make sure our FTP daemon is responding.
[root@centos rdc]# ftp 10.0.4.34
Connected to localhost (10.0.4.34).
220 Welcome to our Anonymous FTP Repo. All connections are monitored and logged.
Name (localhost:root): anonymous
331 Please specify the password.
Password:
'230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>
Linux Admin - Remote Management
在 CentOS 中作为管理员讨论远程管理时,我们将探讨两种方法 -
When talking about remote management in CentOS as an Administrator, we will explore two methods −
-
Console Management
-
GUI Management
Remote Console Management
远程控制台管理,即通过 ssh 等服务从命令行执行管理任务。要有效使用 CentOS Linux,作为管理员,您需要熟练使用命令行。Linux 的核心设计是可从控制台使用。即使是如今,某些系统管理员仍然更喜欢命令功能并通过运行不带实际终端和未安装 GUI 的精简版 Linux 盒子来节省硬件开支。
Remote Console Management means performing administration tasks from the command line via a service such as ssh. To use CentOS Linux effectively, as an Administrator, you will need to be proficient with the command line. Linux at its heart was designed to be used from the console. Even today, some system administrators prefer the power of the command and save money on the hardware by running bare-bones Linux boxes with no physical terminal and no GUI installed.
Remote GUI Management
远程 GUI 管理通常有两种实现方式:远程 X 会话或 GUI 应用层协议(如 VNC)。它们各有优缺点。但是,对于大部分情况而言,VNC 是管理的最佳选择。它允许使用其他操作系统(例如原生不支持 X Windows 协议的 Windows 或 OS X)进行图形化控制。
Remote GUI Management is usually accomplished in two ways: either a remote X-Session or a GUI application layer protocol like VNC. Each has its strengths and drawbacks. However, for the most part, VNC is the best choice for Administration. It allows graphical control from other operating systems such as Windows or OS X that do not natively support the X Windows protocol.
使用远程 X 会话对于在 X 上运行的 X-Window 窗口管理器和桌面管理器来说是原生的。但是,整个 X 会话架构大多与 Linux 一起使用。并非每个系统管理员在手边都有 Linux Laptop 来建立远程 X 会话。因此,大多数时候会使用一个经过调整的 VNC 服务器版本。
Using remote X Sessions is native to both X-Window’s Window-Managers and DesktopManagers running on X. However, the entire X Session architecture is mostly used with Linux. Not every System Administrator will have a Linux Laptop on hand to establish a remote X Session. Therefore, it is most common to use an adapted version of VNC Server.
VNC 最大的缺点是:VNC 不原生支持多用户环境(如远程 X 会话)。因此,对于最终用户对 GUI 的访问,远程 X 会话是最佳选择。但我们主要关注远程管理 CentOS 服务器。
The biggest drawbacks to VNC are: VNC does not natively support a multi-user environment such as remote X-Sessions. Hence, for GUI access to end-users remote XSessions would be the best choice. However, we are mainly concerned with administering a CentOS server remotely.
我们会讨论在为多个管理员而非数百个最终用户配置 VNC 时,用 VNC 与远程 X 会话进行对比。
We will discuss configuring VNC for multiple administrators versus a few hundred endusers with remote X-Sessions.
Laying the Foundation for Security with SSH for Remote Console Access
现在, ssh 或 Secure Shell 是任何 Linux 服务器的远程管理标准。与 telnet 不同,SSH 使用 TLS 来实现身份验证和通信的端到端加密。在配置得当的情况下,管理员相当确信自己的密码和服务器都可以远程信任。
ssh or Secure Shell is now the standard for remotely administering any Linux server. SSH unlike telnet uses TLS for authenticity and end-to-end encryption of communications. When properly configured an administrator can be pretty sure both their password and the server are trusted remotely.
在配置 SSH 之前,我们先简要讨论一下基本安全性以及最不常见的访问。当 SSH 在其默认端口 22 上运行时,很快,您就会针对常见用户名和密码遭受蛮力字典攻击。这是必然的。不管您将多少个主机添加到拒绝文件中,它们都会每天从不同的 IP 地址流入。
Before configuring SSH, lets talk a little about the basic security and least common access. When SSH is running on its default port of 22; sooner rather than later, you are going to get brute force dictionary attacks against common user names and passwords. This just comes with the territory. No matter how many hosts you add to your deny files, they will just come in from different IP addresses daily.
只需遵循一些常见规则,就可以主动采取一些措施,让坏人浪费他们的时间。以下是一些在生产服务器的远程管理方面使用 SSH 时遵循的安全规则 -
With a few common rules, you can simply take some pro-active steps and let the bad guys waste their time. Following are a few rules of security to follow using SSH for remote administration on a production server −
-
Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com
-
Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH.
-
Password policy is a must: Complex SSH user passwords like: "This&IS&a&GUD&P@ssW0rd&24&me". Change passwords every few months to eliminate susceptibility to incremental brute force attacks.
-
Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example.
-
Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don’t have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits.
Note On Linux Security − 任何对 Linux 管理感兴趣的人,都应积极关注当前的网络安全新闻和技术。虽然我们听到的关于受损的操作系统大多是其他操作系统,但一个不安全的 Linux 盒子是网络犯罪分子梦寐以求的宝库。借助高速互联网连接功能,掌握高超技术的网络犯罪分子可以使用 Linux 来推进对其他操作系统的攻击。
Note On Linux Security − Anyone interested in Linux Administration should actively pursue current Cyber-Security news and technology. While we mostly hear about other operating systems being compromised, an insecure Linux box is a sought-after treasure for cybercriminals. With the power of Linux on a high-speed internet connection, a skilled cybercriminal can use Linux to leverage attacks on other operating systems.
Install and Configure SSH for Remote Access
Step 1 − 安装 SSH 服务器和所有依赖的软件包。
Step 1 − Install SSH Server and all dependent packages.
[root@localhost]# yum -y install openssh-server
'Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: repos.centos.net
* extras: repos.dfw.centos.com
* updates: centos.centos.com
Resolving Dependencies
--> Running transaction check
---> Package openssh-server.x86_64 0:6.6.1p1-33.el7_3 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
Step 2 − 进行安全常规使用以添加 shell 访问。
Step 2 − Make a secure regular use to add for shell access.
[root@localhost ~]# useradd choozer
[root@localhost ~]# usermod -c "Remote Access" -d /home/choozer -g users -G
wheel -a choozer
Note − 我们将新用户添加到 wheel 组,使其能够在 SSH 访问经过身份验证后 su 为 root。我们还使用了通用词表中找不到的用户名。这样,当 SSH 遭到攻击时,我们的帐户就不会被锁定。
Note − We added the new user to the wheel group enabling ability to su into root once SSH access has been authenticated. We also used a username that cannot be found in common word lists. This way, our account will not get locked out when SSH is attacked.
用于保存 sshd 服务器配置设置的文件是 /etc/ssh/sshd_config。
The file holding configuration settings for sshd server is /etc/ssh/sshd_config.
我们最初要编辑的部分是 −
The portions we want to edit initially are −
LoginGraceTime 60m
PermitRootLogin no
Step 3 − 重新加载 SSH 守护进程 sshd。
Step 3 − Reload the SSH daemon sshd.
[root@localhost]# systemctl reload sshd
最好将注销宽限期设置为 60 分钟。一些复杂的管理任务可能会超过默认的 2 分钟。配置或研究更改时 SSH 会话超时,没有比这更令人沮丧的事情了。
It is good to set the logout grace period to 60 minutes. Some complex administration tasks can exceed the default of 2 minutes. There is really nothing more frustrating than having SSH session timeout when configuring or researching changes.
Step 4 − 让我们尝试使用 root 凭据登录。
Step 4 − Let’s try to login using the root credentials.
bash-3.2# ssh centos.vmnet.local
root@centos.vmnet.local's password:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
Step 5 − 我们无法再使用 root 凭据通过 ssh 远程登录。所以让我们登录到我们没有特权的用户帐户中,然后再 su 为 root 帐户。
Step 5 − We can no longer login remotely via ssh with root credentials. So let’s login to our unprivileged user account and su into the root account.
bash-3.2# ssh chooser@centos.vmnet.local
choozer@centos.vmnet.local's password:
[choozer@localhost ~]$ su root
Password:
[root@localhost choozer]#
Step 6 − 最后,让我们确保 SSHD 服务在启动时加载,并且 firewalld 允许外部 SSH 连接。
Step 6 − Finally, let’s make sure the SSHD service loads on boot and firewalld allows outside SSH connections.
[root@localhost]# systemctl enable sshd
[root@localhost]# firewall-cmd --permanent --add-service=ssh
success
[root@localhost]# firewall-cmd --reload
success
[root@localhost]#
SSH 现在已设置完毕,可以进行远程管理。根据你的企业边界,可能需要配置数据包过滤边界设备以允许对企业 LAN 之外的远程 SSH 管理。
SSH is now set up and ready for remote administration. Depending on your enterprise border, the packet filtering border device may need to be configured to allow SSH remote administration outside the corporate LAN.
Configure VNC for Remote CentOS Administration
有几种方法可以在 CentOS 6 - 7 上通过 VNC 启用远程 CentOS 管理。最简单但最受限制的方法只是使用名为 vino 的软件包。 Vino 是一个针对围绕 Gnome 桌面平台设计的 Linux 的虚拟网络桌面连接应用程序。因此,假定该安装已通过 Gnome 桌面完成。如果尚未安装 Gnome 桌面,请在继续之前进行安装。Vino 将默认随 Gnome GUI 安装一起安装。
There are a few ways to enable remote CentOS administration via VNC on CentOS 6 - 7. The easiest, but most limiting way is simply using a package called vino. Vino is a Virtual Network Desktop Connection application for Linux designed around the Gnome Desktop platform. Hence, it is assumed the installation was completed with Gnome Desktop. If the Gnome Desktop has not been installed, please do so before continuing. Vino will be installed with a Gnome GUI install by default.
要在 Gnome 下使用 Vino 配置屏幕共享,我们要进入 CentOS 系统偏好设置以进行屏幕共享。
To configure screen sharing with Vino under Gnome, we want to go into the CentOS System Preferences for screen sharing.
Applications->System Tools->Settings->Sharing
配置 VNC 桌面共享的说明 −
Notes to configuring VNC Desktop Sharing −
-
Disable New Connections must ask for access − This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop.
-
Enable Require a password − This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security).
-
Forward UP&P Ports: If available leave disabled − Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this.
确保 vino 在 VNC 端口 5900 上监听。
Make sure vino is listening on the VNC Port 5900.
[root@localhost]# netstat -antup | grep vino
tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 4873/vino-server
tcp6 0 0 :::5900 :::* LISTEN 4873/vino-server
[root@localhost]#
现在让我们配置防火墙,以允许传入的 VNC 连接。
Let’s now configure our Firewall to allow incoming VNC connections.
[root@localhost]# firewall-cmd --permanent --add-port=5900/tcp
success
[root@localhost]# firewall-cmd --reload
success
[root@localhost rdc]#
最后,正如你所见,我们能够连接 CentOS 计算机盒,并使用 Windows 或 OS X 上的 VNC 客户端对其进行管理。
Finally, as you can see we are able to connect our CentOS Box and administer it with a VNC client on either Windows or OS X.

与我们为 SSH 设置的规则一样,遵守 VNC 的规则同样重要。与 SSH 相同,VNC 会持续在 IP 范围内扫描并测试弱密码。值得注意的是,启用默认 CentOS 登录并使用控制台超时功能有助于确保远程 VNC 安全性。因为攻击者需要 VNC 和用户密码,因此请确保你的屏幕共享密码不同,且与用户密码一样难以猜测。
It is just as important to obey the same rules for VNC as we set forth for SSH. Just like SSH, VNC is continually scanned across IP ranges and tested for weak passwords. It is also worth a note that leaving the default CentOS login enabled with a console timeout does help with remote VNC security. As an attacker will need the VNC and user password, make sure your screen sharing password is different and just as hard to guess as the user password.
输入 VNC 屏幕共享密码后,我们还必须输入用户密码才能访问锁定的桌面。
After entering the the VNC screen sharing password, we must also enter the user password to access a locked desktop.

Security Note − 默认情况下,VNC 不是加密协议。因此,应通过 SSH 传输 VNC 连接以进行加密。
Security Note − By default, VNC is not an encrypted protocol. Hence, the VNC connection should be tunneled through SSH for encryption.
Set Up SSH Tunnel Through VNC
设置 SSH 隧道将为传输 VNC 连接提供一层 SSH 加密。另一个非常棒的功能是它使用 SSH 压缩,为 VNC GUI 屏幕更新添加了另一层压缩。在处理 CentOS 服务器的管理时,更安全、更快速始终是一件好事!
Setting up an SSH Tunnel will provide a layer of SSH encryption to tunnel the VNC connection through. Another great feature is it uses SSH compression to add another layer of compression to the VNC GUI screen updates. More secure and faster is always a good thing when dealing with the administration of CentOS servers!
因此,从将启动 VNC 连接的客户端,让我们设置一个远程 SSH 隧道。在本示范中,我们使用 OS X。首先我们需要 sudo -s 至 root。
So from your client that will be initiating the VNC connection, let’s set up a remote SSH tunnel. In this demonstration, we are using OS X. First we need to sudo -s to root.
bash-3.2# sudo -s
password:
输入用户密码,我们现在应该拥有使用 # 提示符的 root shell −
Enter the user password and we should now have root shell with a # prompt −
bash-3.2#
现在,让我们创建 SSH 隧道。
Now, let’s create our SSH Tunnel.
ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N
让我们分解此命令 −
Let’s break this command down −
-
ssh − Runs the local ssh utility
-
-f − ssh should run in the background after the task fully executes
-
rdc@192.168.1.143 − Remote ssh user on the CentOS server hosting VNC services
-
-L 2200:192.168.1.143:5900 − Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]
-
-N tells ssh we do not wish to execute a command on the remote system
bash-3.2# ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N
rdc@192.168.1.143's password:
成功输入远程 ssh 用户的密码后,我们的 ssh 隧道即已创建。现在进入精彩的部分!要进行连接,我们将 VNC 客户端指向隧道端口(在本例中为端口 2200)上的本地主机。以下是 Mac Laptop 的 VNC 客户端上的配置 −
After successfully entering the remote ssh user’s password, our ssh tunnel is created. Now for the cool part! To connect we point our VNC client at the localhost on the port of our tunnel, in this case port 2200. Following is the configuration on Mac Laptop’s VNC Client −

最后,我们的远程 VNC 桌面连接!
And finally, our remote VNC Desktop Connection!

SSH 通道的优点在于它几乎可用于任何协议。SSH 通道通常用于绕过 ISP 的输出和输入端口过滤,以及欺骗应用层 IDS/IPS,同时避开其他会话层监控。
The cool thing about SSH tunneling is it can be used for almost any protocol. SSH tunnels are commonly used to bypass egress and ingress port filtering by an ISP, as well as trick application layer IDS/IPS while evading other session layer monitoring.
-
Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered).
-
Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data.
SSH 通道是 Linux 管理员工具箱中的一项利器,可以帮助完成各种任务。但作为一个管理员,我们希望探索锁定较低权限用户访问 SSH 通道的可能性。
SSH Tunneling is great tool in a Linux Administrator’s toolbox for getting things done. However, as an Administrator we want to explore locking down the availability of lesser privileged users having access to SSH tunneling.
Administration Security Note − 限制 SSH 通道是管理员需要考虑的问题。首先,评估用户为什么需要 SSH 通道;哪些用户需要通道;以及实际的风险概率和最坏的情况影响。
Administration Security Note − Restricting SSH Tunneling is something that requires thought on the part of an Administrator. Assessing why users need SSH Tunneling in the first place; what users need tunneling; along with practical risk probability and worst-case impact.
这是一个超出中级入门教程范围的高级主题。对于希望达到 CentOS Linux 管理高水平的人员,建议研究此主题。
This is an advanced topic stretching outside the realm of an intermediate level primer. Research on this topic is advised for those who wish to reach the upper echelons of CentOS Linux Administration.
Use SSH Tunnel for Remote X-Windows
Linux 中的 X-Windows 的设计与 Windows 相比确实巧妙。如果我们希望通过另一个 Linux box 控制远程 Linux box,我们可以利用 X 中内置的机制。
The design of X-Windows in Linux is really neat compared to that of Windows. If we want to control a remote Linux box from another Linux boxm we can take advantage of mechanisms built into X.
X-Windows(通常称为“X”)提供了将源自一个 Linux box 的应用窗口显示在另一个 Linux box 上的 X 显示部分的机制。因此,通过 SSH,我们可以请求将一个 X-Windows 应用转发到世界另一端的另一个 Linux box 的显示中!
X-Windows (often called just "X"), provides the mechanism to display application windows originating from one Linux box to the display portion of X on another Linux box. So through SSH we can request an X-Windows application be forwarded to the display of another Linux box across the world!
要通过 ssh 通道远程运行一个 X 应用,我们只需要运行一个简单的命令 −
To run an X Application remotely via an ssh tunnel, we just need to run a single command −
[root@localhost]# ssh -X rdc@192.168.1.105
The syntax is − ssh -X [user]@[host],并且主机必须通过有效用户运行 SSH。
The syntax is − ssh -X [user]@[host], and the host must be running ssh with a valid user.
以下是在 Ubuntu 工作站上通过一个远程 XWindows ssh 通道运行 GIMP 的屏幕截图。
Following is a screenshot of GIMP running on a Ubuntu Workstation through a remote XWindows ssh tunnel.

通过另一个 Linux 服务器或工作站远程运行应用非常简单。我们还可以通过多种方法启动一个整个 X 会话,并通过远程获取整个桌面环境。
It is pretty simple to run applications remotely from another Linux server or workstation. It is also possible to start an entire X-Session and have the entire desktop environment remotely through a few methods.
-
XDMCP
-
Headless software packages such as NX
-
Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE
这种方法最常用于没有物理显示的无头服务器,并且确实超出了中级入门教程的范围。但了解现有的选项是件好事。
This method is most commonly used for headless servers with no physical display and really exceeds the scope of an intermediate level primer. However, it is good to know of the options available.
Linux Admin - Traffic Monitoring in CentOS
有几个第三方工具可以增强 CentOS 流量监控功能。在本教程中,我们重点关注 CentOS 主要分发版本库和 Fedora EPEL 版本库中打包的那些工具。
There are several third party tools that can add enhanced capabilities for CentOS traffic monitoring. In this tutorial, we will focus on those that are packaged in the main CentOS distribution repositories and the Fedora EPEL repository.
管理员(出于某种原因)有时只能使用 CentOS 主要版本库中的工具。讨论最多的实用程序旨在由有物理访问 shell 的管理员使用。当使用可访问的 Web GUI 进行流量监控时,使用如 ntop-ng 或 Nagios 之类的第三方实用程序是最佳选择(而不是从头重新创建此类设施)。
There will always be situations where an Administrator (for one reason or another) is left with only tools in the main CentOS repositories. Most utilities discussed are designed to be used by an Administrator with the shell of physical access. When traffic monitoring with an accessible web-gui, using third party utilities such as ntop-ng or Nagios is the best choice (versus re-creating such facilities from scratch).
如果您想进一步研究可配置的 Web GUI 解决方案,以下提供了几个链接,供您开始研究。
For further research on both configurable web-gui solutions, following are a few links to get started on research.
Traffic Monitoring for LAN / WAN Scenarios
Nagios
Nagios
Nagios 已存在了很长时间,因此,经过了全面测试。曾几何时它完全是免费的和开源的,但此后已发展成企业解决方案,采用付费许可证模式来满足企业级复杂性需求。因此,在计划任何集成 Nagios 的操作之前,请务必确保开源许可版本能够满足您的需求或按照企业预算进行规划。
Nagios has been around for a long time, therefore, it is both tried and tested. At one point it was all free and open-source, but has since advanced into an Enterprise solution with paid licensing models to support the need of Enterprise sophistication. Hence, before planning any rollouts with Nagios, make sure the open-source licensed versions will meet your needs or plan on spending with an Enterprise Budget in mind.
可以在 https://www.nagios.org 中找到大部分开源 Nagios 流量监视软件。
Most open-source Nagios traffic monitoring software can be found at − https://www.nagios.org
有关 Nagious 的历史摘要,请参阅官方 Nagios 历史页面: https://www.nagios.org/about/history/ 。
For a summarized history of Nagious, here is the official Nagios History page: https://www.nagios.org/about/history/
ntopng
ntopng
另一种非常棒的工具允许通过 Web GUI 监视带宽和流量,称为 ntopng。ntopng 类似于 Unix 实用程序 ntop,并且可以收集整个 LAN 或 WAN 的数据。通过提供一个用于管理、配置和绘制图表 Web GUI,使得整个 IT 部门都可以轻松使用它。
Another great tool allowing bandwidth and traffic monitoring via a web-gui is called ntopng. ntopng is similar to the Unix utility ntop, and can collect data for an entire LAN or WAN. Providing a web-gui for administration, configuration, and charting makes it easy to use for the entire IT Departments.
与 Nagious 一样,ntopng 同时提供开源和企业付费版本。有关 ntopng 的更多信息,请访问网站 http://www.ntop.org/ 。
Like Nagious, ntopng has both open-source and paid enterprise versions available. For more information about ntopng, please visit the website − http://www.ntop.org/
Install Fedora EPEL Repository ─ Extra Packages for Enterprise Linux
要访问流量监视所需的一些工具,我们需要配置 CentOS 系统使用 EPEL 存储库。
To access some of the needed tools for traffic monitoring, we will need to configure our CentOS system to use the EPEL Repository.
EPEL 存储库并非 CentOS 官方维护或支持的存储库。但是,一群 Fedora Core 志愿者维护该存储库,以解决 CentOS、Fedora Core 或红帽企业版 Linux 中未包含的、企业级 Linux 专业人员常用的软件包的问题。
The EPEL Repository is not officially maintained or supported by CentOS. However, it is maintained by a group of Fedora Core volunteers to address the packages commonly used by Enterprise Linux professionals not included in either CentOS, Fedora Core, or Red Hat Linux Enterprise.
Caution
Caution
请记住,EPEL 存储库并不是 CentOS 的官方存储库,可能会破坏生产服务器上使用常见依赖项进行兼容性和功能。谨记这一点,建议在关键系统部署之前,始终在运行相同服务且并非生产环境的服务器上进行测试。
Remember, the EPEL Repository is not official for CentOS and may break compatibility and functionality on production servers with common dependencies. With that in mind, it is advised to always test on a non-production server running the same services as production before deploying on a system critical box.
事实上,与 CentOS 的任何其他第三方存储库相比,使用 EHEL 存储库最大的优势在于我们可以确信二进制文件不受污染。从不可信来源使用存储库被认为是一种最佳实践。
Really, the biggest advantage of using the EHEL Repository over any other third party repository with CentOS is that we can be sure the binaries are not tainted. It is considered a best practice to not use the repositories from an untrusted source.
尽管如此,官方 EPEL 存储库在 CentOS 中非常常见,可通过 YUM 轻松进行安装。
With all that said, the official EPEL Repository is so common with CentOS that it can be easily installed via YUM.
[root@CentOS rdc]# yum -y install epel-release
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: repo1.dal.innoscale.net
* extras: repo1.dal.innoscale.net
* updates: mirror.hmc.edu
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-9 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
--{ condensed output }--
安装完 EPEL 存储库后,我们会希望更新该存储库。
After installing the EPEL Repository, we will want to update it.
[root@CentOS rdc]# yum repolist
Loaded plugins: fastestmirror, langpacks
epel/x86_64/metalink
| 11 kB 00:00:00
epel
| 4.3 kB 00:00:00
(1/3): epel/x86_64/group_gz
| 170 kB 00:00:00
(2/3): epel/x86_64/updateinfo
| 753 kB 00:00:01
(3/3): epel/x86_64/primary_db
--{ condensed output }--
此时,我们的 EPEL 存储库应已配置完毕并可以随时使用。让我们先安装 nload 来监视接口带宽。
At this point, our EPEL repository should be configured and ready to use. Let’s start by installing nload for interface bandwidth monitoring.
我们将在本教程中重点介绍的工具有:
The tools we will focus on in this tutorial are −
-
nload
-
ntop
-
ifstst
-
iftop
-
vnstat
-
net hogs
-
Wireshark
-
TCP Dump
-
Traceroute
这些都是 Linux 企业中用于监视流量的标准工具。每种工具从简单到高级都有使用情况,所以我们只会简要讨论 Wireshark 与 TCP Dump 等工具。
These are all standard for monitoring traffic in Linux Enterprises. The usage of each range from simple to advanced, so we will only briefly discuss tools such as Wireshark and TCP Dump.
Install and Use nload
随着我们的 EPEL 存储库在 CentOS 中得以安装和配置,我们现在应该可以安装和使用 nload 了。此实用程序旨在实时绘制每个接口的带宽。
With our EPEL Repositories installed and configured in CentOS, we now should be able to install and use nload. This utility is designed to chart bandwidth per interface in real-time.
与大多数其他基本安装类似,nload 是通过 YUM 软件包管理器安装的。
Like most other basic installs nload is installed via the YUM package manager.
[root@CentOS rdc]# yum -y install nload
Resolving Dependencies
--> Running transaction check
---> Package nload.x86_64 0:0.7.4-4.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch
Version Repository Size
===============================================================================
===============================================================================
Installing:
nload x86_64
0.7.4-4.el7 epel 70 k
Transaction Summary
===============================================================================
===============================================================================
Install 1 Package
Total download size: 70 k
Installed size: 176 k
Downloading packages:
--{ condensed output }--
现在我们已经安装了 nload,并且使用起来非常简单。
Now we have nload installed, and using it is pretty straight forward.
[root@CentOS rdc]# nload enp0s5
nload 将实时监控指定接口。在本例中,Enp0s5 是一个以太网接口,它可以监控网络流量负载和总带宽使用情况。
nload will monitor the specified interface. In this case, enp0s5 an Ethernet interface, in real-time from the terminal for network traffic loads and total bandwidth usage.

如你所见,nload 将绘制出指定接口的传入和传出数据,并使用井号“#”提供数据的物理表示。
As seen, nload will chart both incoming and outgoing data from the specified interface, along with providing a physical representation of the data flow with hash marks "#".
截图描述的是正在加载一个简单网页,同时还有后台守护程序流量。
The depicted screenshot is of a simple webpage being loaded with some background daemon traffic.
nload 的常用命令行开关如下:
Common command line switches for nload are −
Command |
Action |
-a |
Time period |
-t |
Time update interval in milliseconds, the default is 500 |
-u |
Sets display of traffic measurement h |
-U |
Sets total in/out traffic measurement units same options as -u |
nload 的标准语法为:
The standard syntax for nload is −
nload [options] <interface>
如果没有指定接口,nload 将自动获取第一个以太网接口。我们尝试使用兆字节测量总入/出数据,并以兆比特测量当前数据传输速度。
If no interface is specified, nload will automatically grab the first Ethernet interface. Let’s try measuring the total data in/out in Megabytes and current data-transfer speeds in Megabits.
[root@CentOS rdc]# nload -U M -u m
进入/离开当前接口的数据以每秒兆比特为单位测量,每个代表总入/出数据的“Ttl”行都以兆字节显示。
Data coming in/out the current interface is measured in megabits per second and each "Ttl" row, representing total data in/out is displayed in Megabytes.
nload 对于管理员来说非常有用,他们需要查看通过某个接口传递了多少数据,以及当前通过指定接口进入/离开的数据量。
nload is useful for an administrator to see how much data has passed through an interface and how much data is currently coming in/out a specified interface.
想在不关闭 nload 的情况下查看其他接口,只需使用左右箭头键即可。这将在系统上的所有可用接口之间循环。
To see other interfaces without closing nload, simply use the left/right arrow keys. This will cycle through all available interfaces on the system.
可以使用 -m 开关同时监控多个接口:
It is possible to monitor multiple interfaces simultaneously using the -m switch −
[root@CentOS rdc]# nload -u K -U M -m lo -m enp0s5
同时监控两个接口(lo 和 enp0s5):
load monitoring two interfaces simultaneously (lo and enp0s5) −

Linux Admin - Log Management
systemd 已经改变了在 CentOS Linux 中管理系统日志的方式。与系统上的每个守护程序将日志分别放置到某个位置,并使用 tail 或 grep 等工具作为排序和过滤日志项的主要方式不同, journald 为分析系统日志提供了单点管理。
systemd has changed the way system logging is managed for CentOS Linux. Instead of every daemon on the system placing logs into individual locations than using tools such as tail or grep as the primary way of sorting and filtering log entries, journald has brought a single point of administration to analyzing system logs.
systemd 日志背后的主要组件包括:journal、jounralctl 和 journald.conf
The main components behind systemd logging are − journal, jounralctl, and journald.conf
journald 是主要日志守护进程,调整 journald.conf 进行配置,而 journalctl 用于分析 journald 记录的事件。
journald is the main logging daemon and is configured by editing journald.conf while journalctl is used to analyze events logged by journald.
journald 记录的事件包括:内核事件、用户进程和守护程序服务。
Events logged by journald include: kernel events, user processes, and daemon services.
Set the Correct System Time Zone
在使用 journalctl 之前,我们需要确保系统时间设置正确。要做到这一点,我们需要使用 timedatectl。
Before using journalctl, we need to make sure our system time is set to the correct time. To do this, we want to use timedatectl.
让我们检查当前系统时间。
Let’s check the current system time.
[root@centos rdc]# timedatectl status
Local time: Mon 2017-03-20 00:14:49 MDT
Universal time: Mon 2017-03-20 06:14:49 UTC
RTC time: Mon 2017-03-20 06:14:49
Time zone: America/Denver (MDT, -0600)
NTP enabled: yes
NTP synchronized: yes
RTC in local TZ: no
DST active: yes
Last DST change: DST began at
Sun 2017-03-12 01:59:59 MST
Sun 2017-03-12 03:00:00 MDT
Next DST change: DST ends (the clock jumps one hour backwards) at
Sun 2017-11-05 01:59:59 MDT
Sun 2017-11-05 01:00:00 MST
[root@centos rdc]#
当前,系统对应于本地时区。如果您的系统不对应时区,那么让我们设置正确的时区。在更改设置之后,CentOS 会自动计算当前时区的时间偏移量,立即调整系统时钟。
Currently, the system is correct to the local time zone. If your system is not, let’s set the correct time zone. After changing the settings, CentOS will automatically calculate the time zone offset from the current time zone, adjusting the system clock right away.
让我们使用 timedatectl 列出所有时区:-
Let’s list all the time zones with timedatectl −
[root@centos rdc]# timedatectl list-timezones
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
这是 timedatectl list-timezones 返回的输出。要找到特定本地时区,可以使用 grep 命令:
That is the contended output from timedatectl list-timezones. To find a specific local time-zone, the grep command can be used −
[root@centos rdc]# timedatectl list-timezones | grep -i "america/New_York"
America/New_York
[root@centos rdc]#
CentOS 使用的标签通常为 Country/Region,并使用下划线代替空格(New_York 与 "New York")。
The label used by CentOS is usually Country/Region with an underscore instead of space (New_York versus "New York").
现在让我们设置我们的时区:
Now let’s set our time zone −
[root@centos rdc]# timedatectl set-timezone "America/New_York"
[root@centos rdc]# date
Mon Mar 20 02:28:44 EDT 2017
[root@centos rdc]#
您的系统时钟应该自动调整时间。
Your system clock should automatically adjust the time.
Use journalctl to Analyze Logs
使用 journalctl 时的常用命令行切换:
Common command line switches when using journalctl −
Switch |
Action |
-k |
Lists only kernel messages |
-u |
Lists by specific unit (httpd, sshd, etc…) |
-b |
Boots the label offset |
-o |
Logs the output format |
-p |
Filters by log type (either name or number) |
-F |
Fieldname or fieldnamevalue |
--utc |
Time in UTC offset |
--since |
Filter by timeframe |
Examine Boot Logs
首先,我们将检查和配置 CentOS Linux 中的引导日志。您会注意到的第一件事是,默认情况下,CentOS 不会存储在重启后仍然存在的引导日志。
First, we will examine and configure the boot logs in CentOS Linux. The first thing you will notice is that CentOS, by default, doesn’t store boot logging that is persistent across reboots.
要按重启实例检查引导日志,我们可以发出以下命令:
To check boot logs per reboot instance, we can issue the following command −
[root@centos rdc]# journalctl --list-boots
-4 bca6380a31a2463aa60ba551698455b5 Sun 2017-03-19 22:01:57 MDT—Sun 2017-03-19 22:11:02 MDT
-3 3aaa9b84f9504fa1a68db5b49c0c7208 Sun 2017-03-19 22:11:09 MDT—Sun 2017-03-19 22:15:03 MDT
-2 f80b231272bf48ffb1d2ce9f758c5a5f Sun 2017-03-19 22:15:11 MDT—Sun 2017-03-19 22:54:06 MDT
-1 a071c1eed09d4582a870c13be5984ed6 Sun 2017-03-19 22:54:26 MDT—Mon 2017-03-20 00:48:29 MDT
0 9b4e6cdb43b14a328b1fa6448bb72a56 Mon 2017-03-20 00:48:38 MDT—Mon 2017-03-20 01:07:36 MDT
[root@centos rdc]#
在重启系统之后,我们可以看到另一个条目。
After rebooting the system, we can see another entry.
[root@centos rdc]# journalctl --list-boots
-5 bca6380a31a2463aa60ba551698455b5 Sun 2017-03-19 22:01:57 MDT—Sun 2017-03-19 22:11:02 MDT
-4 3aaa9b84f9504fa1a68db5b49c0c7208 Sun 2017-03-19 22:11:09 MDT—Sun 2017-03-19 22:15:03 MDT
-3 f80b231272bf48ffb1d2ce9f758c5a5f Sun 2017-03-19 22:15:11 MDT—Sun 2017-03-19 22:54:06 MDT
-2 a071c1eed09d4582a870c13be5984ed6 Sun 2017-03-19 22:54:26 MDT—Mon 2017-03-20 00:48:29 MDT
-1 9b4e6cdb43b14a328b1fa6448bb72a56 Mon 2017-03-20 00:48:38 MDT—Mon 2017-03-20 01:09:57 MDT
0 aa6aaf0f0f0d4fcf924e17849593d972 Mon 2017-03-20 01:10:07 MDT—Mon 2017-03-20 01:12:44 MDT
[root@centos rdc]#
现在,让我们检查最后的引导日志实例:
Now, let’s examine the last boot logging instance −
root@centos rdc]# journalctl -b -5
-- Logs begin at Sun 2017-03-19 22:01:57 MDT, end at Mon 2017-03-20 01:20:27 MDT. --
Mar 19 22:01:57 localhost.localdomain systemd-journal[97]: Runtime journal is using 8.0M
(max allowed 108.4M
Mar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpuset
Mar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpu
Mar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpuacct
Mar 19 22:01:57 localhost.localdomain kernel: Linux version 3.10.0514.6.2.el7.x86_64
(builder@kbuilder.dev.
Mar 19 22:01:57 localhost.localdomain kernel: Command line:
BOOT_IMAGE=/vmlinuz-3.10.0-514.6.2.el7.x86_64 ro
Mar 19 22:01:57 localhost.localdomain kernel: Disabled fast string operations
Mar 19 22:01:57 localhost.localdomain kernel: e820: BIOS-provided physical RAM map:
以下是我们上次启动的简洁输出。我们还可以参考数小时、数天、数周、数月乃至数年的启动日志。但是,CentOS 默认情况下不存储永久启动日志。要启用永久存储启动日志,我们需要进行一些配置更改 −
Above is the condensed output from our last boot. We could also refer back to a boot log from hours, days, weeks, months, and even years. However, by default CentOS doesn’t store persistent boot logs. To enable persistently storing boot logs, we need to make a few configuration changes −
-
Make central storage points for boot logs
-
Give proper permissions to a new log folder
-
Configure journald.conf for persistent logging
Configure Boot Location for Persistent Boot Logs
journald 将要存储持久化启动日志的初始位置是 /var/log/journal。由于默认情况下不存在,因此让我们创建它 −
The initial place journald will want to store persistent boot logs is /var/log/journal. Since this doesn’t exist by default, let’s create it −
[root@centos rdc]# mkdir /var/log/journal
现在,让我们给目录适当的权限 journald 守护程序访问权限 −
Now, let’s give the directory proper permissions journald daemon access −
systemd-tmpfiles --create --prefix /var/log/journal
最后,让我们告诉 journald 它应该存储永久启动日志。在 vim 或您喜欢的文本编辑器中,打开 /etc/systemd/jounrald.con”。
Finally, let’s tell journald it should store persistent boot logs. In vim or your favorite text editor, open /etc/systemd/jounrald.conf".
# See journald.conf(5) for details.
[Journal]=Storage=peristent
我们关注的行是 Storage=。首先删除注释 #,然后更改为上面所示的 Storage = persistent 。保存并重启您的 CentOS 系统,并注意在运行 journalctl list-boots 时应该有多个条目。
The line we are concerned with is, Storage=. First remove the comment #, then change to Storage = persistent as depicted above. Save and reboot your CentOS system and take care that there should be multiple entries when running journalctl list-boots.
Note -来自 VPS 提供商的不断变化的机器 ID 可能会导致 journald 无法存储持久启动日志。对于这种情况,有很多变通办法。最好浏览发布在 CentOS 管理员论坛上的当前修复程序,而不是遵循已找到合理 VPS 变通办法的那些人的可信建议。
Note − A constantly changing machine-id like that from a VPS provider can cause journald to fail at storing persistent boot logs. There are many workarounds for such a scenario. It is best to peruse the current fixes posted to CentOS Admin forums, than follow the trusted advice from those who have found plausible VPS workarounds.
要检查特定启动日志,我们只需使用 journald --list-boots,使用 -b 开关进行偏移。因此,为了检查第二个启动日志,我们将使用 −
To examine a specific boot log, we simply need to get each offset using journald --list-boots the offset with the -b switch. So to check the second boot log we’d use −
journalctl -b -2
如果没有指定启动日志偏移量,-b 的默认值将始终是最新的启动日志。
The default for -b with no boot log offset specified will always be the current boot log after the last reboot.
Analyze Logs by Log Type
来自 journald 的事件被编号并归类为 7 种不同类型 −
Events from journald are numbered and categorized into 7 separate types −
0 - emerg :: System is unusable
1 - alert :: Action must be taken immediatly
2 - crit :: Action is advised to be taken immediatly
3 - err :: Error effecting functionality of application
4 - warning :: Usually means a common issue that can affect security or usilbity
5 - info :: logged informtation for common operations
6 - debug :: usually disabled by default to troubleshoot functionality
因此,如果我们想查看所有警告,可以通过 journalctl 发布以下命令 −
Hence, if we want to see all warnings the following command can be issued via journalctl −
[root@centos rdc]# journalctl -p 4
-- Logs begin at Sun 2017-03-19 22:01:57 MDT, end at Wed 2017-03-22 22:33:42 MDT. --
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: RSDP 00000000000f6a10 00024
(v02 PTLTD )
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: XSDT 0000000095eea65b 0005C
(v01 INTEL 440BX 06040000 VMW 01
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: FACP 0000000095efee73 000F4
(v04 INTEL 440BX 06040000 PTL 00
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: DSDT 0000000095eec749 1272A
(v01 PTLTD Custom 06040000 MSFT 03
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: FACS 0000000095efffc0 00040
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: BOOT 0000000095eec721 00028
(v01 PTLTD $SBFTBL$ 06040000 LTP 00
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: APIC 0000000095eeb8bd 00742
(v01 PTLTD ? APIC 06040000 LTP 00
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: MCFG 0000000095eeb881 0003C
(v01 PTLTD $PCITBL$ 06040000 LTP 00
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: SRAT 0000000095eea757 008A8
(v02 VMWARE MEMPLUG 06040000 VMW 00
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: HPET 0000000095eea71f 00038
(v01 VMWARE VMW HPET 06040000 VMW 00
Mar 19 22:01:57 localhost.localdomain kernel: ACPI: WAET 0000000095eea6f7 00028
(v01 VMWARE VMW WAET 06040000 VMW 00
Mar 19 22:01:57 localhost.localdomain kernel: Zone ranges:
Mar 19 22:01:57 localhost.localdomain kernel: DMA [mem 0x000010000x00ffffff]
Mar 19 22:01:57 localhost.localdomain kernel: DMA32 [mem 0x010000000xffffffff]
Mar 19 22:01:57 localhost.localdomain kernel: Normal empty
Mar 19 22:01:57 localhost.localdomain kernel: Movable zone start for each node
Mar 19 22:01:57 localhost.localdomain kernel: Early memory node ranges
Mar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x000010000x0009dfff]
Mar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x001000000x95edffff]
Mar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x95f000000x95ffffff]
Mar 19 22:01:57 localhost.localdomain kernel: Built 1 zonelists in Node order,
mobility grouping on. Total pages: 60
Mar 19 22:01:57 localhost.localdomain kernel: Policy zone: DMA32
Mar 19 22:01:57 localhost.localdomain kernel: ENERGY_PERF_BIAS: Set to
'normal', was 'performance'
以上显示了系统过去 4 天内所有警告。
The above shows all warnings for the past 4 days on the system.
以 systemd 查看和浏览日志的新方式确实需要一点点实践和研究才能熟悉。然而,由于不同的输出格式和特别注意使所有打包的守护程序日志通用,因此值得采用。journald 在传统日志分析方法上提供了极大的灵活性和效率。
The new way of viewing and perusing logs with systemd does take little practice and research to become familiar with. However, with different output formats and particular notice to making all packaged daemon logs universal, it is worth embracing. journald offers great flexibility and efficiency over traditional log analysis methods.
Linux Admin - Backup and Recovery
在探索 CentOS 部署标准备份计划的特定方法之前,我们先讨论下标准级备份策略的典型注意事项。首先我们要习惯的是 3-2-1 backup rule 。
Before exploring methods particular to CentOS for deploying a standard backup plan, let’s first discuss typical considerations for a standard level backup policy. The first thing we want to get accustomed to is the 3-2-1 backup rule.
3-2-1 Backup Strategy
在整个行业中,你经常会听到术语 3-2-1 备份模型。这是一种非常好的方法,在实施备份计划时可以遵循。3-2-1 的定义如下: 3 份数据副本;例如,我们可能有工作副本、使用 rsync 复制到 CentOS 服务器上的副本(用于冗余),以及从备份服务器上的数据进行轮换的异地 USB 备份。 2 种不同的备份介质。在本例中,我们实际有三种不同的备份介质:笔记本电脑或工作站上 SSD 的工作副本、RADI6 阵列上的 CentOS 服务器数据,以及存储在 USB 驱动器上的异地备份。 1 份异地数据副本;我们每天晚上都会将 USB 驱动器异地轮换。另一种现代方法是云备份提供商。
Throughout the industry, you’ll often hear the term 3-2-1 backup model. This is a very good approach to live by when implementing a backup plan. 3-2-1 is defined as follows − 3 copies of data; for example, we may have the working copy; a copy put onto the CentOS server designed for redundancy using rsync; and rotated, offsite USB backups are made from data on the backup server. 2 different backup mediums. We would actually have three different backup mediums in this case: the working copy on an SSD of a laptop or workstation, the CentOS server data on a RADI6 Array, and the offsite backups put on USB drives. 1 copy of data offsite; we are rotating the USB drives offsite on a nightly basis. Another modern approach may be a cloud backup provider.
System Recovery
裸机恢复计划只是 CentOS 管理员制定的一项计划,以获取完整数据的关键在线系统。假设 100% 的系统故障以及所有过去系统硬件的丢失,管理员必须制定一项计划,以实现用户数据完好的正常运行时间,从而将停机时间降至最低。Linux 中使用的整体式内核实际上使得使用系统映像进行裸机恢复比 Windows 变得容易得多。Windows 使用微内核架构。
A bare metal restore plan is simply a plan laid out by a CentOS administrator to get vital systems online with all data intact. Assuming 100% systems failure and loss of all past system hardware, an administrator must have a plan to achieve uptime with intact user-data costing minimal downtime. The monolithic kernel used in Linux actually makes bare metal restores using system images much easier than Windows. Where Windows uses a micro-kernel architecture.
完全数据恢复和裸机恢复通常是通过多种方法组合完成的,其中包括已配置的重要操作服务器的工作生产磁盘映像,遵循 3-2-1 规则的用户数据的冗余备份。甚至一些敏感文件可能存储在受限访问受信任公司人员的安全防火保险柜中。
A full data restore and bare metal recovery are usually accomplished through a combination of methods including working, configured production disk-images of key operational servers, redundant backups of user data abiding by the 3-2-1 rule. Even some sensitive files that may be stored in a secure, fireproof safe with limited access to the trusted company personnel.
使用本地 CentOS 工具的多阶段裸机恢复和数据恢复计划可能包括 −
A multiphase bare metal restore and data recovery plan using native CentOS tools may consist of −
-
dd to make and restore production disk-images of configured servers
-
rsync to make incremental backups of all user data
-
tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere.
如果系统因硬件故障或灾难而崩溃,以下将是恢复操作的不同阶段 −
If a system crashes due to a hardware failure or disaster, following will be the different phases of restoring operations −
-
Build a working server with a configured bare metal image
-
Restore data to the working server from backups
-
Have physical access to credentials needed to perform the first two operations
Use rsync for File Level Backups
rsync 是一个出色的实用程序,可以本地或与其他服务器同步文件目录。rsync 多年来一直被系统管理员使用,因此对于备份数据而言,它是非常精炼的。在作者看来,sync 最好的功能之一是它可以从命令行编写脚本。
rsync is a great utility for syncing directories of files either locally or to another server. rsync has been used for years by System Administrators, hence it is very refined for the purpose of backing up data. In the author’s opinion, one of the best features of sync is its ability to be scripted from the command line.
在本教程中,我们将以各种方式讨论 rsync −
In this tutorial, we will discuss rsync in various ways −
-
Explore and talk about some common options
-
Create local backups
-
Create remote backups over SSH
-
Restore local backups
rsync 以其用途命名:Remote Sync(远程同步),并且使用起来功能强大且灵活。
rsync is named for its purpose: Remote Sync and is both powerful and flexible in use.
以下是通过 SSH 进行的 rsync 远程基础备份:
Following is a basic rsync remote backup over ssh −
MiNi:~ rdc$ rsync -aAvz --progress ./Desktop/ImportantStuff/
rdc@192.168.1.143:home/rdc/ Documents/RemoteStuff/
rdc@192.168.1.143's password:
sending incremental file list
6,148 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=23/25)
2017-02-14 16_26_47-002 - Veeam_Architecture001.png
33,144 100% 31.61MB/s 0:00:00 (xfr#2, to-chk=22/25)
A Guide to the WordPress REST API | Toptal.pdf
892,406 100% 25.03MB/s 0:00:00 (xfr#3, to-chk=21/25)
Rick Cardon Technologies, LLC..webloc
77 100% 2.21kB/s 0:00:00 (xfr#4, to-chk=20/25)
backbox-4.5.1-i386.iso
43,188,224 1% 4.26MB/s 0:08:29
sent 2,318,683,608 bytes received 446 bytes 7,302,941.90 bytes/sec
total size is 2,327,091,863 speedup is 1.00
MiNi:~ rdc$
以下同步将通过我们的 LAN 发送将近 2.3GB 的数据。rsync 的优点在于它可以在基于文件的块级别上逐步运作。这意味着,如果我们仅仅更改 1MB 文本文件中两个字符,仅一个或两个块将在下次同步时通过 LAN 传输!
The following sync sent nearly 2.3GB of data across our LAN. The beauty of rsync is it works incrementally at the block level on a file-by-file basis. This means, if we change just two characters in a 1MB text file, only one or two blocks will be transferred across the lan on the next sync!
此外,可以禁用增量函数以改善网络带宽使用情况,从而降低 CPU 利用率。如果每 10 分钟持续复制多个 10MB 数据库文件至 1GB 专用备份 LAN,这样可能会被证明是可取的。原因是:这些文件会始终更改,并且每 10 分钟增量传输并且可能对远程 CPU 造成负载。由于总传输负载不会超过 5 分钟,我们可能只希望完整同步数据库文件。
Furthermore, the incremental function can be disabled in favor of more network bandwidth used for less CPU utilization. This might prove advisable if constantly copying several 10MB database files every 10 minutes on a 1Gb dedicated Backup-Lan. The reasoning is: these will always be changing and will be transmitting incrementally every 10 minutes and may tax load of the remote CPU. Since the total transfer load will not exceed 5 minutes, we may just wish to sync the database files in their entirety.
以下是 rsync 最常见的切换:
Following are the most common switches with rsync −
rsync syntax:
rsync [options] [local path] [[remote host:remote path] or [target path
Switch |
Action |
-a |
Archive mode and assumes -r, -p, -t, -g, -l |
-d |
Sync only directory tree, no files |
-r |
Recursive into directory |
-l |
Copy symlinks as symlinks |
-p |
Preserve permissions |
-g |
Preserve group |
-v |
Verbose output |
-z |
Compress over network link |
-X |
Preserve extended attributes |
-A |
Preserve ACLs |
-t |
Preserve timestamps |
-W |
Transfer whole file, not incremental blocks |
-u |
Do not overwrite files on target |
--progress |
Show transfer progress |
--delete |
Delete older files on target |
--max-size = XXX |
Max file size to sync |
Local Backup With rsync
我们已经看到了如何将文件从一台主机传输到另一台主机。相同的方法可用于本地同步目录和文件。
We have already seen how to transfer files from one host to another. The same method can be used to sync directories and files locally.
让我们在 root 用户的目录中手动增量备份 /etc/。
Let’s make a manual incremental backup of /etc/ in our root user’s directory.
首先,我们需要为同步备份创建 ~/root 的目录:
First, we need to create a directory off ~/root for the synced backup −
[root@localhost rdc]# mkdir /root/etc_baks
然后,确保有足够的可用磁盘空间。
Then, assure there is enough free disk-space.
[root@localhost rdc]# du -h --summarize /etc/
49M /etc/
[root@localhost rdc]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/cl-root 43G 15G 28G 35% /
我们适合同步整个 /etc/ 目录:
We are good for syncing our entire /etc/ directory −
rsync -aAvr /etc/ /root/etc_baks/
我们的同步 /etc/ 目录:
Our synced /etc/ directory −
[root@localhost etc_baks]# ls -l ./
total 1436
drwxr-xr-x. 3 root root 101 Feb 1 19:40 abrt
-rw-r--r--. 1 root root 16 Feb 1 19:51 adjtime
-rw-r--r--. 1 root root 1518 Jun 7 2013 aliases
-rw-r--r--. 1 root root 12288 Feb 27 19:06 aliases.db
drwxr-xr-x. 2 root root 51 Feb 1 19:41 alsa
drwxr-xr-x. 2 root root 4096 Feb 27 17:11 alternatives
-rw-------. 1 root root 541 Mar 31 2016 anacrontab
-rw-r--r--. 1 root root 55 Nov 4 12:29 asound.conf
-rw-r--r--. 1 root root 1 Nov 5 14:16 at.deny
drwxr-xr-x. 2 root root 32 Feb 1 19:40 at-spi2
--{ condensed output }--
让我们现在执行增量 rsync:
Now let’s do an incremental rsync −
[root@localhost etc_baks]# rsync -aAvr --progress /etc/ /root/etc_baks/
sending incremental file list
test_incremental.txt
0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1145/1282)
sent 204620 bytes received 2321 bytes 413882.00 bytes/sec
total size is 80245040 speedup is 387.77
[root@localhost etc_baks]#
只有我们的 test_incremental.txt 文件被复制。
Only our test_incremental.txt file was copied.
Remote Differential Backups With rsync
咱们使用部署了备份计划的服务器进行我们开始的 rsync 完整备份。此示例实际上是将一台 Mac OS X 工作站上的一个文件夹备份到一台 CentOS 服务器上。rsync 的另一个奇妙之处在于它可以在已移植 rsync 的任何平台上使用。
Let’s do our initial rsync full backup onto a server with a backup plan deployed. This example is actually backing up a folder on a Mac OS X Workstation to a CentOS server. Another great aspect of rsync is that it can be used on any platform rsync has been ported to.
MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/
rdc@192.168.1.143:Documents/RemoteStuff
rdc@192.168.1.143's password:
sending incremental file list
./
A Guide to the WordPress REST API | Toptal.pdf
Rick Cardon Tech LLC.webloc
VeeamDiagram.png
backbox-4.5.1-i386.iso
dhcp_admin_script_update.py
DDWRT/
DDWRT/.DS_Store
DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin
DDWRT/ddwrt_mod_notes.docx
DDWRT/factory-to-ddwrt.bin
open_ldap_config_notes/
open_ldap_config_notes/ldap_directory_a.png
open_ldap_config_notes/open_ldap_notes.txt
perl_scripts/
perl_scripts/mysnmp.pl
php_scripts/
php_scripts/chunked.php
php_scripts/gettingURL.php
sent 2,318,281,023 bytes received 336 bytes 9,720,257.27 bytes/sec
total size is 2,326,636,892 speedup is 1.00
MiNi:~ rdc$
我们现在已经将一台工作站上的一个文件夹备份到一台服务器上,该服务器运行一个 RAID6 卷,并把旋转的灾难恢复介质存储在异地。使用 rsync 给了我们标准的 3-2-1 备份,只有一台服务器具有昂贵的冗余磁盘阵列和旋转的差分备份。
We have now backed up a folder from a workstation onto a server running a RAID6 volume with rotated disaster recovery media stored offsite. Using rsync has given us standard 3-2-1 backup with only one server having an expensive redundant disk array and rotated differential backups.
现在让我们使用 rsync 在添加了一个名为 test_file.txt 的新文件后,对同一文件夹执行另一项备份。
Now let’s do another backup of the same folder using rsync after a single new file named test_file.txt has been added.
MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/
rdc@192.168.1.143:Documents/RemoteStuff
rdc@192.168.1.143's password:
sending incremental file list
./
test_file.txt
sent 814 bytes received 61 bytes 134.62 bytes/sec
total size is 2,326,636,910 speedup is 2,659,013.61
MiNi:~ rdc$
如你所见,只有新文件通过 rsync 传递给了服务器。差分比较是在逐个文件的基础上进行的。
As you can see, only the new file was delivered to the server via rsync. The differential comparison was made on a file-by-file basis.
需要注意的几件事是:这仅复制新文件:test_file.txt,因为它是有更改的唯一文件。rsync 使用 ssh。我们根本不需要在任何一台机器上使用我们的根帐户。
A few things to note are: This only copies the new file: test_file.txt, since it was the only file with changes. rsync uses ssh. We did not ever need to use our root account on either machine.
简单、强大而有效,rsync 非常适合备份整个文件夹和目录结构。但是,rsync 本身并不能自动化这个过程。我们需要在这里深入研究我们的工具箱,找到最好、最小的简单工具来完成这项工作。
Simple, powerful and effective, rsync is great for backing up entire folders and directory structures. However, rsync by itself doesn’t automate the process. This is where we need to dig into our toolbox and find the best, small, and simple tool for the job.
要使用 cronjob 自动执行 rsync 备份,必须使用 SSH 密钥设置 SSH 用户进行身份验证。这与 cronjob 结合在一起,可以在时间间隔内自动执行 rsync。
To automate rsync backups with cronjobs, it is essential that SSH users be set up using SSH keys for authentication. This combined with cronjobs enables rsync to be done automatically at timed intervals.
Use DD for Block-by-Block Bare Metal Recovery Images
DD 是一个 Linux 实用程序,它从 Linux 内核满足 GNU 实用程序的曙光之初就已经存在。
DD is a Linux utility that has been around since the dawn of the Linux kernel meeting the GNU Utilities.
简单地说,dd 复制了所选磁盘区域的映像。然后,提供复制物理磁盘选定块的功能。因此,除非你有备份,一旦 dd 写入了磁盘,所有块都会被替换。以前数据的丢失超出了即使是昂贵的专业级数据恢复的恢复能力。
dd in simplest terms copies an image of a selected disk area. Then provides the ability to copy selected blocks of a physical disk. So unless you have backups, once dd writes over a disk, all blocks are replaced. Loss of previous data exceeds the recovery capabilities for even highly priced professional-level data-recovery.
使用 dd 创建可引导系统映像的整个过程如下 −
The entire process for making a bootable system image with dd is as follows −
-
Boot from the CentOS server with a bootable linux distribution
-
Find the designation of the bootable disk to be imaged
-
Decide location where the recovery image will be stored
-
Find the block size used on your disk
-
Start the dd image operation
在本教程中,为了节省时间和简便起见,我们将从 CentOS 虚拟机创建主引导记录的 ISO 映像。然后,我们将把此映像存储在异地。如果我们的 MBR 损坏并需要恢复,可以对整个可引导磁盘或分区应用相同的过程。但是,本教程真正需要的硬盘空间和时间有点太长了。
In this tutorial, for the sake of time and simplicity, we will be creating an ISO image of the master-boot record from a CentOS virtual machine. We will then store this image offsite. In case our MBR becomes corrupted and needs to be restored, the same process can be applied to an entire bootable disk or partition. However, the time and disk space needed really goes a little overboard for this tutorial.
建议 CentOS 管理员在测试环境中精通恢复完全可引导的磁盘/分区并执行裸机恢复。当最终需要在真实情况下完成练习时,当经理和几十个最终用户计算停机时间时,这会减轻很多压力。在这种情况下,花 10 分钟弄清楚事情可能会像永恒一样,并会让人流汗。
It is encouraged for CentOS admins to become proficient in restoring a fully bootable disk/partition in a test environment and perform a bare metal restore. This will take a lot of pressure off when eventually one needs to complete the practice in a real life situation with Managers and a few dozen end-users counting downtime. In such a case, 10 minutes of figuring things out can seem like an eternity and make one sweat.
Note − 在使用 dd 时,请务必不要混淆源卷和目标卷。你可以通过将备份位置复制到引导驱动器来破坏数据和可引导服务器。或者可能更糟,用 DD 在非常低的级别复制数据以永久破坏数据。
Note − When using dd make sure to NOT confuse source and target volumes. You can destroy data and bootable servers by copying your backup location to a boot drive. Or possibly worse destroy data forever by copying over data at a very low level with DD.
以下是 dd 的常用命令行开关和参数 −
Following are the common command line switches and parameters for dd −
Switch |
Action |
if= |
In file or source to be copied |
of= |
Out file or the copy of the in file |
bs |
Set both input and output block size |
obs |
Set output file block size |
ibs |
Set input file block size |
count |
Set the number of blocks to copy |
conv |
Extra options to add for imaging |
Noerror |
Do not stop processing an error |
sync |
Pads unfitted input blocks in the event of error or misalignment |
Note on block size − dd 的默认块大小为 512 字节。这是低密度硬盘驱动器的标准块大小。如今的高密度 HDD 已增加到 4096 字节(4kB)块大小,以支持 1TB 及更大容量的磁盘。因此,在将 dd 用于较新、容量更高的硬盘时,我们要检查磁盘块大小。
Note on block size − The default block size for dd is 512 bytes. This was the standard block size of lower density hard disk drives. Today’s higher density HDDs have increased to 4096 byte (4kB) block sizes to allow for disks ranging from 1TB and larger. Thus, we will want to check disk block size before using dd with newer, higher capacity hard disks.
在本教程中,我们不会在生产服务器上使用 dd,而是在 VMWare 中运行 CentOS 安装。我们还将配置 VMWare,以启动可启动 Linux ISO 映像,而不是使用可启动 U 盘。
For this tutorial, instead of working on a production server with dd, we will be using a CentOS installation running in VMWare. We will also configure VMWare to boot a bootable Linux ISO image instead of working with a bootable USB Stick.
首先,我们需要下载标题为 CentOS Gnome ISO 的 CentOS 映像。该映像文件大小约为 3GB,建议始终保留一个副本以便创建可启动 USB 拇指驱动器,并启动到虚拟服务器安装中进行故障排除和裸机映像。
First, we will need to download the CentOS image entitled − CentOS Gnome ISO. This is almost 3GB and it is advised to always keep a copy for creating bootable USB thumb-drives and booting into virtual server installations for trouble-shooting and bare metal images.
其他可启动 Linux 发行版效果也不错。Linux Mint 可用于可启动 ISO,因为它具有出色的硬件支持和用于维护的经过优化的 GUI 磁盘工具。
Other bootable Linux distros will work just as well. Linux Mint can be used for bootable ISOs as it has great hardware support and polished GUI disk tools for maintenance.
CentOS GNOME 实时可启动映像可从以下网址下载: http://buildlogs.centos.org/rolling/7/isos/x86_64/CentOS-7-x86_64-LiveGNOME.iso
CentOS GNOME Live bootable image can be downloaded from: http://buildlogs.centos.org/rolling/7/isos/x86_64/CentOS-7-x86_64-LiveGNOME.iso
让我们配置 VMWare Workstation 安装,以从 Linux 可启动映像中启动。这些步骤适用于 OS X 上的 VMWare。但是,它们在 Linux、Windows 甚至 Virtual Box 上的 VMWare Workstation 中是相似的。
Let’s configure our VMWare Workstation installation to boot from our Linux bootable image. The steps are for VMWare on OS X. However, they are similar across VMWare Workstation on Linux, Windows, and even Virtual Box.
Note − 使用 Virtual Box 或 VMWare Workstation 等虚拟桌面解决方案是设置学习 CentOS 管理任务的实验环境的绝佳方式。它提供了安装多个 CentOS 安装的能力,实际上不需要硬件配置,从而使使用者能够专注于管理,甚至在进行更改之前保存服务器状态。
Note − Using a virtual desktop solution like Virtual Box or VMWare Workstation is a great way to set up lab scenarios for learning CentOS Administration tasks. It provides the ability to install several CentOS installations, practically no hardware configuration letting the person focus on administration, and even save the server state before making changes.
我们首先配置一个虚拟 CD-ROM,并将其 ISO 映像附加到启动,而不是虚拟 CentOS 服务器安装 −
First let’s configure a virtual cd-rom and attach our ISO image to boot instead of the virtual CentOS server installation −

现在,设置启动磁盘 −
Now, set the startup disk −

现在,启动后,我们的虚拟机会从 CentOS 可启动 ISO 映像启动,并允许访问先前配置的虚拟 CentOS 服务器上的文件。
Now when booted, our virtual machine will boot from the CentOS bootable ISO image and allow access to files on the Virtual CentOS server that was previously configured.
让我们检查我们的磁盘以了解我们想要从哪个地方复制 MBR(简洁的输出如下所示)。
Let’s check our disks to see where we want to copy the MBR from (condensed output is as follows).
MiNt ~ # fdisk -l
Disk /dev/sda: 60 GiB, 21474836480 bytes, 41943040 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/sdb: 20 GiB, 21474836480 bytes, 41943040 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
我们已找到我们的两个物理磁盘:sda 和 sdb。每个具有 512 字节的块大小。所以,我们现在将运行 dd 命令,用于复制 SDA1 上 MBR 的前 512 字节。
We have located both our physical disks: sda and sdb. Each has a block size of 512 bytes. So, we will now run the dd command to copy the first 512 bytes for our MBR on SDA1.
最好的做法如下 −
The best way to do this is −
[root@mint rdc]# dd if=/dev/sda bs=512 count=1 | gzip -c >
/mnt/sdb/images/mbr.iso.gz
1+0 records in
1+0 records out
512 bytes copied, 0.000171388 s, 3.0 MB/s
[root@mint rdc]# ls /mnt/sdb/
mbr-iso.gz
[root@mint rdc]#
就这样,我们拥有主引导记录的完整映像。如果我们有足够的空间来映像引导驱动器,我们可以轻松制作完整的系统引导映像 −
Just like that, we have full image of out master boot record. If we have enough room to image the boot drive, we could just as easily make a full system boot image −
dd if=/dev/INPUT/DEVICE-NAME-HERE conv=sync,noerror bs=4K | gzip -c >
/mnt/sdb/boot-server-centos-image.iso.gz
当必须为物理介质对齐字节时,使用 conv=sync。在这种情况下,如果无法读取确切的 4K 对齐(比如…一个只有 3K 但需要在磁盘占用最小的一个 4K 块的文件。或者,只是读取错误并且文件无法被 dd 读取)。因此,带有 conv=sync,noerror 的 dd 将以平凡但有用的数据填充物理介质中的 3K,以实现 4K 块对齐。在不会导致大操作错误的情况下。
The conv=sync is used when bytes must be aligned for a physical medium. In this case, dd may get an error if exact 4K alignments are not read (say… a file that is only 3K but needs to take minimum of a single 4K block on disk. Or, there is simply an error reading and the file cannot be read by dd.). Thus, dd with conv=sync,noerror will pad the 3K with trivial, but useful data to physical medium in 4K block alignments. While not presenting an error that may end a large operation.
在处理来自磁盘的数据时,我们总是想要包含参数 conv=sync,noerror 。
When working with data from disks we always want to include: conv=sync,noerror parameter.
这仅仅是因为磁盘不像 TCP 数据那样是流。它们是由对齐到某个大小的块组成的。例如,如果我们有 512 字节的块,那么只有 300 字节的文件仍然需要一个 512 字节的硬盘空间(可能是 2 个块,用于权限和其他文件系统信息之类的 inode 信息)。
This is simply because the disks are not streams like TCP data. They are made up of blocks aligned to a certain size. For example, if we have 512 byte blocks, a file of only 300 bytes still needs a full 512 bytes of disk-space (possibly 2 blocks for inode information like permissions and other filesystem information).
Use gzip and tar for Secure Storage
gzip和tar是CentOS管理员必须习惯使用的两个工具。它们被大量用于,而不仅仅是解压缩存档。
gzip and tar are two utilities a CentOS administrator must become accustomed to using. They are used for a lot more than to simply decompress archives.
Using Gnu Tar in CentOS Linux
Tar是一个归档工具,类似于Windows中的winrar。其名称Tape Archive缩写为tar,很好地总结了该工具。tar会获取文件并将它们放入一个存档中以实现逻辑便利性。因此,我们不必存储在/etc中的大量文件,我们只需将它们"tar"到存档中以实现备份和存储的便利性。
Tar is an archiving utility similar to winrar on Windows. Its name Tape Archive abbreviated as tar pretty much sums up the utility. tar will take files and place them into an archive for logical convenience. Hence, instead of the dozens of files stored in /etc. we could just "tar" them up into an archive for backup and storage convenience.
多年以来,tar一直是用于在Unix和Linux上存储归档文件的一种标准。因此,在每个系统上,将tar与gzip或bzip一起使用被认为是对存档的最佳实践。
tar has been the standard for storing archived files on Unix and Linux for many years. Hence, using tar along with gzip or bzip is considered as a best practice for archives on each system.
以下是tar所使用的常见命令行选项和开关 −
Following is a list of common command line switches and options used with tar −
Switch |
Action |
-c |
Creates a new .tar archive |
-C |
Extracts to a different directory |
-j |
Uses bzip2 compression |
-z |
Uses gzip compression |
-v |
Verbose show archiving progress |
-t |
Lists archive contents |
-f |
File name of the archive |
-x |
Extracts tar archive |
以下是用于创建tar存档的基本语法。
Following is the basic syntax for creating a tar archive.
tar -cvf [tar archive name]
Note on Compression mechanisms with tar − 建议使用tar时,坚持两种常见的压缩方案之一:gzip和bzip2。gzip文件消耗更少的CPU资源,但通常大小更大。bzip2虽然需要更长的时间来压缩,它们利用了更多的CPU资源;但最终的文件大小会更小。
Note on Compression mechanisms with tar − It is advised to stick with one of two common compression schemes when using tar: gzip and bzip2. gzip files consume less CPU resources but are usually larger in size. While bzip2 will take longer to compress, they utilize more CPU resources; but will result in a smaller end filesize.
在使用文件压缩时,我们总是希望使用标准文件扩展名,以便让所有人(包括我们自己)知道(而不是通过反复试验进行猜测)需要什么压缩方案来提取存档。
When using file compression, we will always want to use standard file extensions letting everyone including ourselves know (versus guess by trial and error) what compression scheme is needed to extract archives.
bzip2 |
.tbz |
bzip2 |
.tar.tbz |
bzip2 |
.tb2 |
gzip |
.tar.gz |
gzip |
.tgz |
在需要可能在Windows的计算机上提取存档或在Windows上使用时,建议使用.tar.tbz或.tar.gz,因为大多数三个字符的单一扩展名会混淆Windows和Windows唯一的管理员(然而,这有时是所需的结果)
When needing to possibly extract archives on a Windows box or for use on Windows, it is advised to use the .tar.tbz or .tar.gz as most the three character single extensions will confuse Windows and Windows only Administrators (however, that is sometimes the desired outcome)
让我们从Mac工作站复制的文件中创建一个gzipped tar 存档 −
Let’s create a gzipped tar archive from our remote backups copied from the Mac Workstation −
[rdc@mint Documents]$ tar -cvz -f RemoteStuff.tgz ./RemoteStuff/
./RemoteStuff/
./RemoteStuff/.DS_Store
./RemoteStuff/DDWRT/
./RemoteStuff/DDWRT/.DS_Store
./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin
./RemoteStuff/DDWRT/ddwrt_mod_notes.docx
./RemoteStuff/DDWRT/factory-to-ddwrt.bin
./RemoteStuff/open_ldap_config_notes/
./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png
./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt
./RemoteStuff/perl_scripts/
./RemoteStuff/perl_scripts/mysnmp.pl
./RemoteStuff/php_scripts/
./RemoteStuff/php_scripts/chunked.php
./RemoteStuff/php_scripts/gettingURL.php
./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf
./RemoteStuff/Rick Cardon Tech LLC.webloc
./RemoteStuff/VeeamDiagram.png
./RemoteStuff/backbox-4.5.1-i386.iso
./RemoteStuff/dhcp_admin_script_update.py
./RemoteStuff/test_file.txt
[rdc@mint Documents]$ ls -ld RemoteStuff.tgz
-rw-rw-r--. 1 rdc rdc 2317140451 Mar 12 06:10 RemoteStuff.tgz
Note − 不用将所有文件直接添加到存档中,我们将整个 RemoteStuff 文件夹存档。这是最简单的方法。因为解压时,整个 RemoteStuff 目录会连同当前工作目录中的所有文件一起解压为 ./currentWorkingDirectory/RemoteStuff/
Note − Instead of adding all the files directly to the archive, we archived the entire folder RemoteStuff. This is the easiest method. Simply because when extracted, the entire directory RemoteStuff is extracted with all the files inside the current working directory as ./currentWorkingDirectory/RemoteStuff/
现在,让我们在 /root/ 主目录中解压存档。
Now let’s extract the archive inside the /root/ home directory.
[root@centos ~]# tar -zxvf RemoteStuff.tgz
./RemoteStuff/
./RemoteStuff/.DS_Store
./RemoteStuff/DDWRT/
./RemoteStuff/DDWRT/.DS_Store
./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin
./RemoteStuff/DDWRT/ddwrt_mod_notes.docx
./RemoteStuff/DDWRT/factory-to-ddwrt.bin
./RemoteStuff/open_ldap_config_notes/
./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png
./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt
./RemoteStuff/perl_scripts/
./RemoteStuff/perl_scripts/mysnmp.pl
./RemoteStuff/php_scripts/
./RemoteStuff/php_scripts/chunked.php
./RemoteStuff/php_scripts/gettingURL.php
./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf
./RemoteStuff/Rick Cardon Tech LLC.webloc
./RemoteStuff/VeeamDiagram.png
./RemoteStuff/backbox-4.5.1-i386.iso
./RemoteStuff/dhcp_admin_script_update.py
./RemoteStuff/test_file.txt
[root@mint ~]# ping www.google.com
如上所示,所有文件仅仅被解压到当前工作目录中的包含目录中。
As seen above, all the files were simply extracted into the containing directory within our current working directory.
[root@centos ~]# ls -l
total 2262872
-rw-------. 1 root root 1752 Feb 1 19:52 anaconda-ks.cfg
drwxr-xr-x. 137 root root 8192 Mar 9 04:42 etc_baks
-rw-r--r--. 1 root root 1800 Feb 2 03:14 initial-setup-ks.cfg
drwxr-xr-x. 6 rdc rdc 4096 Mar 10 22:20 RemoteStuff
-rw-r--r--. 1 root root 2317140451 Mar 12 07:12 RemoteStuff.tgz
-rw-r--r--. 1 root root 9446 Feb 25 05:09 ssl.conf [root@centos ~]#
Use gzip to Compress File Backups
如前所述,我们可以使用 tar 中的 bzip2 或 gzip 以及 -j 或 -z 命令行开关。我们还可以使用 gzip 压缩单个文件。然而,单独使用 bzip 或 gzip 所能提供的功能并没有其与 tar 结合使用时那么多。
As noted earlier, we can use either bzip2 or gzip from tar with the -j or -z command line switches. We can also use gzip to compress individual files. However, using bzip or gzip alone does not offer as many features as when combined with tar.
使用 gzip 时,默认操作是删除原始文件,将其替换为使用 .gz 扩展名的压缩版本。
When using gzip, the default action is to remove the original files, replacing each with a compressed version adding the .gz extension.
gzip 的一些常用命令行开关为:
Some common command line switches for gzip are −
Switch |
Action |
-c |
Keeps files after placing into the archive |
-l |
Get statistics for the compressed archive |
-r |
Recursively compresses files in the directories |
-1 thru 9 |
Specifies the compression level on a scale of 1 thru 9 |
gzip 更多或少地逐文件操作,而不是像一些 Windows O/S zip 实用程序那样以存档为基础操作。主要原因是 tar 已经提供了高级存档功能。gzip 旨在仅提供压缩机制。
gzip more or less works on a file-by-file basis and not on an archive basis like some Windows O/S zip utilities. The main reason for this is that tar already provides advanced archiving features. gzip is designed to provide only a compression mechanism.
因此,当想到 gzip 时,请想到单个文件。当想到多个文件时,请想到 tar 存档。现在,让我们用我们之前的 tar 存档来探索这一点。
Hence, when thinking of gzip, think of a single file. When thinking of multiple files, think of tar archives. Let’s now explore this with our previous tar archive.
Note − 经验丰富的 Linux 专业人士通常将 tarred 存档称为 tarball。
Note − Seasoned Linux professionals will often refer to a tarred archive as a tarball.
让我们从 rsync 备份中创建一个新的 tar 存档。
Let’s make another tar archive from our rsync backup.
[root@centos Documents]# tar -cvf RemoteStuff.tar ./RemoteStuff/
[root@centos Documents]# ls
RemoteStuff.tar RemoteStuff/
为了演示,我们对新创建的 tarball 执行 gzip 压缩,并告诉 gzip 保留旧文件。默认情况下,如果不使用 -c 选项,gzip 会用 .gz 文件替换整个 tar 存档。
For demonstration purposes, let’s gzip the newly created tarball, and tell gzip to keep the old file. By default, without the -c option, gzip will replace the entire tar archive with a .gz file.
[root@centos Documents]# gzip -c RemoteStuff.tar > RemoteStuff.tar.gz
[root@centos Documents]# ls
RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz
We now have our original directory, our tarred directory and finally our gziped tarball.
我们尝试使用 gzip 测试 -l 开关。
Let’s try to test the -l switch with gzip.
[root@centos Documents]# gzip -l RemoteStuff.tar.gz
compressed uncompressed ratio uncompressed_name
2317140467 2326661120 0.4% RemoteStuff.tar
[root@centos Documents]#
为了演示 gzip 与 Windows Zip 实用程序的不同之处,我们对一个文本文档文件夹运行 gzip。
To demonstrate how gzip differs from Windows Zip Utilities, let’s run gzip on a folder of text files.
[root@centos Documents]# ls text_files/
file1.txt file2.txt file3.txt file4.txt file5.txt
[root@centos Documents]#
现在,我们使用 -r 选项递归压缩目录中的所有文本文档。
Now let’s use the -r option to recursively compress all the text files in the directory.
[root@centos Documents]# gzip -9 -r text_files/
[root@centos Documents]# ls ./text_files/
file1.txt.gz file2.txt.gz file3.txt.gz file4.txt.gz file5.txt.gz
[root@centos Documents]#
看到了吗?这并非部分人所预料的。所有原始文本文档都被删除,而每个文档被单独压缩。由于此种行为,建议在需要处理单个文件时单独考虑 gzip。
See? Not what some may have anticipated. All the original text files were removed and each was compressed individually. Because of this behavior, it is best to think of gzip alone when needing to work in single files.
使用 tarball,我们来把我们的 rsync 后的 tarball 解压缩到一个新目录。
Working with tarballs, let’s extract our rsynced tarball into a new directory.
[root@centos Documents]# tar -C /tmp -zxvf RemoteStuff.tar.gz
./RemoteStuff/
./RemoteStuff/.DS_Store
./RemoteStuff/DDWRT/
./RemoteStuff/DDWRT/.DS_Store
./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin
./RemoteStuff/DDWRT/ddwrt_mod_notes.docx
./RemoteStuff/DDWRT/factory-to-ddwrt.bin
./RemoteStuff/open_ldap_config_notes/
./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png
./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt
./RemoteStuff/perl_scripts/
./RemoteStuff/perl_scripts/mysnmp.pl
./RemoteStuff/php_scripts/
./RemoteStuff/php_scripts/chunked.php
如上所示,我们把我们的 tarball 解压缩到 /tmp 目录。
As seen above, we extracted and decompressed our tarball into the /tmp directory.
[root@centos Documents]# ls /tmp
hsperfdata_root
RemoteStuff
Encrypt TarBall Archives
对 tarball 归档进行加密,以便在发生灾难恢复事件时,可供组织中的其他员工访问存储的安全文档。这是一个棘手的概念,主要有三种方法:使用 GnuPG、openssl 或第三方实用工具。
Encrypting tarball archives for storing secure documents that may need to be accessed by other employees of the organization, in case of disaster recovery, can be a tricky concept. There are basically three ways to do this: either use GnuPG, or use openssl, or use a third part utility.
GnuPG 主要用于非对称加密,而且考虑的是身份关联,而不是密码。诚然,它能与对称加密一起使用,但这并不是 GnuPG 的主要优势。因此,对于需要多人访问(例如,想要防止管理员控制所有密钥的企业经理)的物理安全归档,我会放弃使用 GnuPG。
GnuPG is primarily designed for asymmetric encryption and has an identity-association in mind rather than a passphrase. True, it can be used with symmetrical encryption, but this is not the main strength of GnuPG. Thus, I would discount GnuPG for storing archives with physical security when more people than the original person may need access (like maybe a corporate manager who wants to protect against an Administrator holding all the keys to the kingdom as leverage).
Openssl 就像 GnuPG,能够满足我们的需求,并且使用 CentOS。但同样,它并非专为满足我们的需求而设计,而且加密已经在安全社区中引起了质疑。
Openssl like GnuPG can do what we want and ships with CentOS. But again, is not specifically designed to do what we want and encryption has been questioned in the security community.
我们的选择是一个名为 7zip 的实用工具。7zip 是一种压缩实用工具,类似于 gzip,但功能更多。像 Gnu Gzip 一样,7zip 及其标准在开源社区中。我们只需要从 EHEL 存储库中安装 7zip(下一章将详细介绍安装扩展企业存储库)。
Our choice is a utility called 7zip. 7zip is a compression utility like gzip but with many more features. Like Gnu Gzip, 7zip and its standards are in the open-source community. We just need to install 7zip from our EHEL Repository (the next chapter will cover installing the Extended Enterprise Repositories in detail).
Install 7zip on Centos
一旦我们的 EHEL 存储库已加载并配置到 CentOS 中,安装 7zip 非常简单。
7zip is a simple install once our EHEL repositories have been loaded and configured in CentOS.
[root@centos Documents]# yum -y install p7zip.x86_64 p7zip-plugins.x86_64
Loaded plugins: fastestmirror, langpacks
base
| 3.6 kB 00:00:00
epel/x86_64/metalink
| 13 kB 00:00:00
epel
| 4.3 kB 00:00:00
extras
| 3.4 kB 00:00:00
updates
| 3.4 kB 00:00:00
(1/2): epel/x86_64/updateinfo
| 756 kB 00:00:04
(2/2):
epel/x86_64/primary_db
| 4.6 MB 00:00:18
Loading mirror speeds from cached hostfile
--> Running transaction check
---> Package p7zip.x86_64 0:16.02-2.el7 will be installed
---> Package p7zip-plugins.x86_64 0:16.02-2.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
就这么简单,7zip 就安装好了,可以对我们的 tarball 归档使用 256 位 AES 加密。
Simple as that, 7zip is installed and ready be used with 256-bit AES encryption for our tarball archives.
现在让我们使用 7z 使用密码加密我们的 gzipped 归档。这样做的语法非常简单 −
Now let’s use 7z to encrypt our gzipped archive with a password. The syntax for doing so is pretty simple −
7z a -p <output filename><input filename>
其中, a: 添加到归档中,和 -p: 加密并提示输入密码
Where, a: add to archive, and -p: encrypt and prompt for passphrase
[root@centos Documents]# 7z a -p RemoteStuff.tgz.7z RemoteStuff.tar.gz
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R)
Core(TM) i5-4278U CPU @ 2.60GHz (40651),ASM,AES-NI)
Scanning the drive:
1 file, 2317140467 bytes (2210 MiB)
Creating archive: RemoteStuff.tgz.7z
Items to compress: 1
Enter password (will not be echoed):
Verify password (will not be echoed) :
Files read from disk: 1
Archive size: 2280453410 bytes (2175 MiB)
Everything is Ok
[root@centos Documents]# ls
RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz RemoteStuff.tgz.7z slapD
text_files
[root@centos Documents]#
现在,我们生成了我们的 .7z 归档,由 256 位 AES 加密 gzipped tarball。
Now, we have our .7z archive that encrypts the gzipped tarball with 256-bit AES.
Note − 7zip 使用 AES 256 位加密以及对密码和计数器的 SHA-256 哈希,重复多达 512K 次以生成密钥。如果使用了复杂密钥,此方法应足够安全。
Note − 7zip uses AES 256-bit encryption with an SHA-256 hash of the password and counter, repeated up to 512K times for key derivation. This should be secure enough if a complex key is used.
对归档进行加密和重新压缩的过程可能会花费大量时间,尤其对于较大的归档。
The process of encrypting and recompressing the archive further can take some time with larger archives.
7zip 是一款先进的产品,功能比 gzip 或 bzip2 更多。但它在 CentOS 或 Linux 世界中的实用性并不如其它的产品。因此,应尽可能经常使用其它实用工具。
7zip is an advanced offering with more features than gzip or bzip2. However, it is not as standard with CentOS or amongst the Linux world. Thus, the other utilities should be used often as possible.
Linux Admin - System Updates
CentOS 7 系统可以通过三种方式更新 −
The CentOS 7 system can be updated in three ways −
-
Manually
-
Automatically
-
Update manually for major security issues and configure automatic updates
在生产环境中,建议为生产服务器手动更新。或者至少建立更新计划,以便管理员可以确保对业务运营至关重要的服务。
In a production environment, it is recommended to update manually for production servers. Or at least establish an update plan so the administrator can assure services vital to business operations.
简单的安全更新可能会导致对常见应用程序造成递归问题,这要求管理员进行升级和重新配置。所以,在开发服务器和桌面电脑中进行测试后再安排在生产中自动更新。
It is plausible a simple security update can cause recursive issues with common application that requires upgrading and reconfiguration by an Administrator. So, be weary of scheduling automatic updates in production before testing in development servers and desktops first.
Manually Update CentOS 7
要更新 CentOS 7,我们需要熟悉 yum 命令。 yum 用于处理 CentOS 7 中的软件包存储库。yum 是通常用于以下操作的工具 −
To update CentOS 7, we will want to become familiar with the yum command. yum is used to deal with package repositories in CentOS 7. yum is the tool commonly used to −
-
Update the CentOS 7 Linux System
-
Search for packages
-
Install packages
-
Detect and install required dependencies for packages
为了将 yum 用于更新,CentOS 服务器需要连接到互联网。大多数配置都会安装一个基本系统,然后使用 yum 查询主 CentOS 存储库以获取软件包的其他功能并应用系统更新。
In order to use yum for updates, your CentOS server will need to be connected to the Internet. Most configurations will install a base system, then use yum to query the main CentOS repository for additional functionality in packages and apply system updates.
我们已经使用了 yum 来安装一些软件包。在使用 yum 时,你始终需要作为 root 用户进行操作。或者具有 root 访问权限的用户。因此,让我们搜索并安装一个称为 nano 的易于使用的文本编辑器。
We have already made use of yum to install a few packages. When using yum you will always need to do so as the root user. Or a user with root access. So let’s search for and install an easy to use text-editor called nano.
[root@centos rdc]# yum search nano
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.rackspace.com
* epel: mirror.chpc.utah.edu
* extras: repos.forethought.net
* updates: repos.forethought.net
======================================================================
N/S matched: nano
======================================================================
nano.x86_64 : A small text editor
nodejs-nano.noarch : Minimalistic couchdb driver for Node.js
perl-Time-Clock.noarch : Twenty-four hour clock object with nanosecond precision
Name and summary matches only, use "search all" for everything.
[root@centos rdc]#
现在,让我们安装 nano 文本编辑器。
Now, let’s install the nano text editor.
[root@centos rdc]# yum install nano
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.keystealth.org
* epel: pubmirror1.math.uh.edu
* extras: centos.den.host-engine.com
* updates: repos.forethought.net
Resolving Dependencies
--> Running transaction check
---> Package nano.x86_64 0:2.3.1-10.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
================================================================================
Package Arch
Version Repository Size
================================================================================
Installing:
nano x86_64
2.3.1-10.el7 base 440 k
Transaction Summary
Install 1 Package
Total download size: 440 k
Installed size: 1.6 M
Is this ok [y/d/N]: y
Downloading packages:
nano-2.3.1-10.el7.x86_64.rpm
| 440 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : nano-2.3.1-10.el7.x86_64
1/1
Verifying : nano-2.3.1-10.el7.x86_64
1/1
Installed:
nano.x86_64 0:2.3.1-10.el7
Complete!
[root@centos rdc]#
我们已经安装了 nano 文本编辑器。在我看来,这种方法比在网站上搜索实用程序并手动运行安装程序容易得多。此外,存储库使用数字签名来验证软件包,确保它们来自可信来源并带有 yum。在信任新存储库时,由管理员验证真实性。这就是为什么将第三方存储库视为最佳实践的原因。
We have installed the nano text editor. This method, IMO, is a lot easier than searching for utilities on websites and manually running the installers. Also, repositories use digital signatures to validate packages assuring they are coming from a trusted source with yum. It is up to the administrator to validate authenticity when trusting new repositories. This is why it is considered a best practice to be weary of third party repositories.
Yum 也可用于删除软件包。
Yum can also be used to remove a package.
[root@centos rdc]# yum remove nano
Loaded plugins: fastestmirror, langpacks
Resolving Dependencies
--> Running transaction check
---> Package nano.x86_64 0:2.3.1-10.el7 will be erased
--> Finished Dependency Resolution
Dependencies Resolved
现在让我们检查更新。
Now let’s check for updates.
[root@centos rdc]# yum list updates
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.keystealth.org
* epel: pubmirror1.math.uh.edu
* extras: centos.den.host-engine.com
* updates: repos.forethought.net
Updated Packages
NetworkManager.x86_64 1:1.4.0-17.el7_3 updates
NetworkManager-adsl.x86_64 1:1.4.0-17.el7_3 updates
NetworkManager-glib.x86_64 1:1.4.0-17.el7_3 updates
NetworkManager-libnm.x86_64 1:1.4.0-17.el7_3 updates
NetworkManager-team.x86_64 1:1.4.0-17.el7_3 updates
NetworkManager-tui.x86_64 1:1.4.0-17.el7_3 updates
NetworkManager-wifi.x86_64 1:1.4.0-17.el7_3 updates
audit.x86_64 2.6.5-3.el7_3.1 updates
audit-libs.x86_64 2.6.5-3.el7_3.1 updates
audit-libs-python.x86_64
如上所述,我们有一些待安装的未决更新。事实上,大约有 100 个总更新,因为我们尚未配置自动更新。因此,让我们安装所有待处理的更新。
As depicted, we have a few dozen updates pending to install. Actually, there are about 100 total updates since we have not yet configured automatic updates. Thus, let’s install all pending updates.
[root@centos rdc]# yum update
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirrors.usc.edu
* epel: pubmirror1.math.uh.edu
* extras: repos.forethought.net
* updates: repos.forethought.net
Resolving Dependencies
--> Running transaction check
---> Package NetworkManager.x86_64 1:1.4.0-14.el7_3 will be updated
---> Package NetworkManager.x86_64 1:1.4.0-17.el7_3 will be an update
selinux-policy noarch 3.13.1102.el7_3.15 updates 414 k
selinux-policy-targeted noarch 3.13.1102.el7_3.15 updates 6.4 M
systemd x86_64 21930.el7_3.7 updates 5.2 M
systemd-libs x86_64 21930.el7_3.7 updates 369 k
systemd-python x86_64 21930.el7_3.7 updates 109 k
systemd-sysv x86_64 21930.el7_3.7 updates 63 k
tcsh x86_64 6.18.01-13.el7_3.1 updates 338 k
tzdata noarch 2017a1.el7 updates 443 k
tzdata-java noarch 2017a1.el7 updates 182 k
wpa_supplicant x86_64 1:2.021.el7_3 updates 788 k
Transaction Summary
===============================================================================
Install 2 Packages
Upgrade 68 Packages
Total size: 196 M
Total download size: 83 M
Is this ok [y/d/N]:
在按下 “y” 键后,将开始更新 CentOS 7。yum 在更新时经历的一般过程是 −
After hitting the "y" key, updating of CentOS 7 will commence. The general process that yum goes through when updating is −
-
Checks the current packages
-
Looks in the repository for updated packages
-
Calculates dependencies needed for updated packages
-
Downloads updates
-
Installs updates
现在,让我们确保我们的系统是最新的 −
Now, let’s make sure our system is up to date −
[root@centos rdc]# yum list updates
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* updates: mirror.compevo.com
[root@centos rdc]#
正如你所看到的,没有列出更新。
As you can see, there are no updates listed.
Configure Automatic Updates for YUM
如前文所述,在企业环境中,自动更新可能是安装首选方法,也可能不是。我们来介绍一下使用 yum 配置自动更新的步骤。
In an Enterprise environment, as mentioned earlier, automatic updates may or may not be the preferred method of installation. Let’s go over the steps for configuring automatic updates with yum.
首先,我们安装一个名为 yum-cron 的包。
First, we install a package called yum-cron.
[root@centos rdc]# yum -y install yum-cron
Install 1 Package
Total download size: 61 k
Installed size: 51 k
Downloading packages:
yum-cron-3.4.3-150.el7.centos.noarch.rpm
| 61 kB 00:00:01
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : yum-cron-3.4.3-150.el7.centos.noarch
1/1
Verifying : yum-cron-3.4.3-150.el7.centos.noarch
1/1
Installed:
yum-cron.noarch 0:3.4.3-150.el7.centos
Complete!
[root@centos rdc]#
默认情况下,yum-cron 只会下载更新,而不会安装它们。是否自动安装更新取决于管理员。最大的警告是:某些更新需要系统重启。此外,某些更新可能需要配置更改,服务才能再次运行。
By default, yum-cron will only download updates and not install them. Whether to install updates automatically is on the Administrator. The biggest caveat is: some updates will require a system reboot. Also, some updates may require a configuration change before services are again operational.
在以下情况下,更新依赖关系可能会导致递归问题
Updating dependencies can possibly create a recursive problem in the following situation −
-
An update is recommended by yum for a certain library
-
The library only supports Apache Server 2.4, but we have server 2.3
-
Our commerce site relies on a certain version of PHP
-
The new version of Apache installed for the library requires upgrading PHP
-
Our production web applications have not yet been tested with the newer PHP version
除非配置不执行自动更新操作,否则 Yum 可能继续自动升级 Apache 和 PHP,且不发出任何通知。
Yum may go ahead and automatically upgrade Apache and PHP without notice unless configured not to.
如果所有 5 个场景都发生,它可能导致各种后果,从早晨的巨大麻烦到可能因更新重启和重新配置而暴露用户数据的安全漏洞。尽管上述示例是一种完美的风暴,但我们永远不想看到这种情况发生。
If all 5 scenarios play out, it can result in anything from a big headache in the morning to a possible security compromise exposing the user data. While the aforementioned example is a perfect storm of sorts, we never want such a scenario to play out.
由管理员负责评估因更新重启和重新配置导致可能的停机时间而恢复服务所需时间而导致的潜在收入损失的可能情况。对于每天可能有数百万美元收入且拥有数百万客户的多家百万美元电商网站来说,这种做法可能还不够保守。
It is up to the Administrator for accessing possible scenarios of potential revenue loss from time needed to restore services due to possible downtime from update reboots and reconfigurations. This practice may not be conservative enough for, say, a multi-million dollar per day ecommerce site with millions of customers.
现在,我们来配置 yum-cron 以自动安装系统更新。
Now let’s configure yum-cron to automatically install system updates.
[root@centos rdc]# vim /etc/yum/yum-cron.conf
# Whether updates should be applied when they are available. Note
# that download_updates must also be yes for the update to be applied.
apply_updates = yes
我们要将 apply_updates = no 更改为 apply_updates = yes。现在,我们来配置 yum-cron 的更新时间。
We want to change apply_updates = no to apply_updates = yes. Now let’s configure the update interval for yum-cron.
同样,是否使用自动更新并按需安装更新可以是一把双刃剑,需要由管理员根据每个独特情况进行考虑。
Again, whether to use automatic updates and install updates on demand can be a double edged sword and needs to be considered by an administrator for each unique situation.
Linux Admin - Shell Scripting
Introduction to Bash Shell
与 GNU Linux 的风格类似,shell 有多种类型,且兼容性各不相同。CentOS 中的默认 shell 称为 Bash 或 Bourne Again Shell。Bash shell 是由 Stephen Bourne 开发的 Bourne Shell 的现代版修改版本。Bash 是 Unix 操作系统上最初在贝尔实验室由 Ken Thompson 和 Dennis Ritchie(Stephen Bourne 也受雇于贝尔实验室)开发的最初 Thompson Shell 的直接替代品。
Like flavors of GNU Linux, shells come in many varieties and vary in compatibility. The default shell in CentOS is known as the Bash or Bourne Again Shell. The Bash shell is a modern day, modified version of Bourne Shell developed by Stephen Bourne. Bash was the direct replacement to the original Thompson Shell on the Unix operating system developed at Bell Labs by Ken Thompson and Dennis Ritchie (Stephen Bourne was also employed by Bell Labs)
每个人都有自己最喜欢的 shell,每个 shell 都有其优点和困难。但在大多数情况下,Bash 将成为所有 Linux 发行版中的默认 shell,并且普遍可用。有了经验,每个人都希望探索和使用最适合自己的 shell。但与此同时,每个人也希望精通 Bash shell。
Everyone has a favorite shell and each has its strengths and difficulties. But for the most part, Bash is going to be the default shell across all Linux distributions and most commonly available. With experience, everyone will want to explore and use a shell that is best for them. However at the same time, everyone will also want to master Bash shell.
其他 Linux shell 包括:Tcsh、Csh、Ksh、Zsh 和 Fish。
Other Linux shells include: Tcsh, Csh, Ksh, Zsh, and Fish.
以专家级别使用任何 Linux shell 都是 CentOS 管理员极为重要的技能。如我们之前提到的,与 Windows 不同,Linux 核心是一个命令行操作系统。shell 只是一个用户界面,允许管理员(或用户)向操作系统发出命令。如果 Linux 系统管理员是一位航空公司飞行员,使用 shell 会类似于让飞机脱离自动驾驶状态,并手动接管控制装置进行更加灵活的飞行。
Developing skills to use any Linux shell at an expert level is extremely important to a CentOS administrator. As we mentioned previously, unlike Windows, Linux at its heart is a command line operating system. A shell is simply a user interface that allows an administrator (or user) to issue commands to the operating system. If a Linux system administrator were an airlines pilot, using the shell would be similar to taking the plane off auto-pilot and grabbing the manual controls for more maneuverable flight.
在计算机科学术语中,像 Bash 这样的 Linux 外壳程序被称为 Command Line Interpreter 。Microsoft Windows 还具有两个称为 DOS(不要与原始 DOS 操作系统混淆)和 PowerShell 的命令行解释器。
A Linux shell, like Bash, is known in Computer Science terms as a Command Line Interpreter. Microsoft Windows also has two command line interpreters called DOS (not to be confused with the original DOS operating system) and PowerShell.
像 Bash 这样的大多数现代外壳程序提供 constructs ,允许更复杂的 shell 脚本来自动执行常见和复杂的任务。
Most modern shells like Bash provide constructs allowing more complex shell scripts to automate both common and complex tasks.
构造包括 −
Constructs include −
-
Script flow control (ifthen and else)
-
Logical comparison operations (greater than, less than, equality)
-
Loops
-
Variables
-
Parameters defining operation (similar to switches with commands)
Using Shell Script Versus Scripting Language
管理员在考虑执行任务时经常问自己:我应该使用 shell 脚本还是 Perl、Ruby 或 Python 等脚本语言?
Often when thinking about performing a task administrators ask themselves: Should I use a shell script or a scripting language such as Perl, Ruby or Python?
这里没有固定的规则。shell 与脚本语言之间只有典型的差异。
There is no set rule here. There are only typical differences between shells versus scripting languages.
Shell
Shell 允许使用 Linux 命令,例如 sed、grep、tee、cat 以及 Linux 操作系统上的所有其他基于命令行的实用程序。实际上,几乎所有命令行 Linux 实用程序都可以在 shell 中进行脚本编写。
Shell allows the use of Linux commands such as sed, grep, tee, cat and all other command-line based utilities on the Linux operating system. In fact, pretty much any command line Linux utility can be scripted in your shell.
使用 shell 的一个很好的例子是一个快速脚本,用于检查 DNS 解析的主机列表。
A great example of using a shell would be a quick script to check a list of hosts for DNS resolution.
我们简单的 Bash 脚本用于检查 DNS 名称 −
Our simple Bash Script to check DNS names −
#!/bin/bash
for name in $(cat $1);
do
host $name.$2 | grep "has address"
done
exit
要测试 DNS 解析的小型词表 −
small wordlist to test DNS resolution on −
dns
www
test
dev
mail
rdp
remote
针对 google.com 域的输出 −
Output against google.com domain −
[rdc@centos ~]$ ./dns-check.sh dns-names.txt google.com
-doing dns
dns.google.com has address 172.217.6.46
-doing www
www.google.com has address 172.217.6.36
-doing test
-doing dev
-doing mail
googlemail.l.google.com has address 172.217.6.37
-doing rdp
-doing remote
[rdc@centos ~]$
通过在 shell 中利用简单的 Linux 命令,我们能够编写一个简单的 5 行脚本,以根据单词列表审核 DNS 名称。即使使用精心实现的 DNS 库,这在 Perl、Python 或 Ruby 中也需要花费相当长的时间。
Leveraging simple Linux commands in our shell, we were able to make a simple 5-line script to audit DNS names from a word list. This would have taken some considerable time in Perl, Python, or Ruby even when using a nicely implemented DNS Library.
Scripting Language
脚本语言将在 shell 之外提供更多控制。上述 Bash 脚本使用了 Linux 主机命令周围的包装器。如果我们想做更多并创建自己的应用程序(如托管)在 shell 之外进行交互,该怎么办?这就是我们使用脚本语言的地方。
A scripting language will give more control outside the shell. The above Bash script used a wrapper around the Linux host command. What if we wanted to do more and make our own application like host to interact outside the shell? This is where we would use a scripting language.
此外,借助高度维护的脚本语言,我们知道我们的操作在很大程度上可以在不同的系统上使用。例如,Python 3.5 将在运行 Python 3.5 并安装相同库的任何其他系统上运行。但是,如果我们希望在 Linux 和 HP-UX 上运行我们的 BASH 脚本,则不是这样。
Also, with a highly maintained scripting language we know our actions will work across different systems for the most part. Python 3.5, for example, will work on any other system running Python 3.5 with the same libraries installed. Not so, if we want to run our BASH script on both Linux and HP-UX.
有时,脚本语言和强大的 shell 之间的界限可能会模糊。可以使用 Python、Perl 或 Ruby 自动执行 CentOS Linux 管理任务。这样做实际上很普遍。此外,富有的 shell 脚本开发人员在 Bash 中制作了一个简单但功能齐全的 Web 服务器守护程序。
Sometimes the lines between a scripting language and a powerful shell can be blurred. It is possible to automate CentOS Linux administration tasks with Python, Perl or Ruby. Doing so is really quite commonplace. Also, affluent shell-script developers have made a simple, but otherwise functional, web-server daemon in Bash.
借助在脚本语言和自动执行 shell 中的任务方面的经验,CentOS 管理员将能够在需要解决问题时快速确定从哪里开始。使用 shell 脚本启动项目非常常见。然后,随着项目的复杂性增加,逐渐发展到脚本(或编译)语言。
With experience in scripting languages and automating tasks in shells, a CentOS administrator will be able to quickly determine where to start when needing to solve a problem. It is quite common to start a project with a shell script. Then progress to a scripting (or compiled) language as a project gets more complex.
此外,为项目的不同部分同时使用脚本语言和 shell 脚本也是可以的。一个例子可以是 Perl 脚本来抓取网站。然后,使用 shell 脚本使用 sed、awk 和 egrep 进行解析和格式化。最后,使用 PHP 脚本使用 Web GUI 将格式化数据插入 MySQL 数据库。
Also, it is ok to use both a scripting language and shell script for different parts of a project. An example could be a Perl script to scrape a website. Then, use a shell script to parse and format with sed, awk, and egrep. Finally, use a PHP script for inserting formatted data into MySQL database using a web GUI.
有了有关 shell 的一些理论,我们开始使用 CentOS 中 Bash shell 的基本构建模块来实现任务自动化。
With some theory behind shells, let’s get started with the basic building blocks to automate tasks from a Bash shell in CentOS.
Input Output and Redirection
将标准输出处理到另一个命令中 −
Processing stdout to another command −
[rdc@centos ~]$ cat ~/output.txt | wc -l
6039
[rdc@centos ~]$
在上面,我们已将 cat 的 stdout 传递给 wc 以使用管道符号进行处理。然后 wc 处理来自 cat 的输出,将 output.txt 的行数打印到终端。可将管道符号视作从一个命令传递输出以供下一个命令处理的“管道”。
Above, we have passed cat’sstoud to wc for processing with the pipe character. wc then processed the output from cat, printing the line count of output.txt to the terminal. Think of the pipe character as a "pipe" passing output from one command, to be processed by the next command.
以下是处理命令重定向时需要记住的关键概念 −
Following are the key concepts to remember when dealing with command redirection −
Number |
File descriptor |
Character |
0 |
standard input |
< |
1 |
standard output |
> |
2 |
standard error |
|
append stdout |
>> |
|
assign redirection |
& |
|
pipe stdout into stdin |
我们在第一章中介绍了这一点,但没有太多谈论重定向或分配重定向。当在 Linux 中打开终端时,你的 shell 被视为 − 的默认目标
We introduced this in chapter one without really talking much about redirection or assigning redirection. When opening a terminal in Linux, your shell is seen as the default target for −
-
standard input < 0
-
standard output > 1
-
standard error 2
让我们看看这是如何工作的 −
Let’s see how this works −
[rdc@centos ~]$ lsof -ap $BASHPID -d 0,1,2
COMMAND PID USER **FD** TYPE DEVICE SIZE/OFF NODE NAME
bash 13684 rdc **0u** CHR 136,0 0t0 3 /dev/pts/0
bash 13684 rdc **1u** CHR 136,0 0t0 3 /dev/pts/0
bash 13684 rdc **2u** CHR 136,0 0t0 3 /dev/pts/0
[rdc@centos ~]$
/dev/pts/0 是我们的伪终端。CentOS Linux 会查看它并像考虑我们的开放终端应用程序一样,将其视为插入通过串行接口的键盘和显示器的真实终端。但是,就像管理程序对操作系统抽象硬件一样,/dev/pts 对应用程序抽象了我们的终端。
/dev/pts/0 is our pseudo terminal. CentOS Linux looks at this and thinks of our open terminal application like a real terminal with the keyboard and display plugged in through a serial interface. However, like a hypervisor abstracts hardware to an operating system /dev/pts abstracts our terminal to applications.
从上面的 lsof 命令中,我们可以看到在 FD 列下,所有三个文件描述符都已设置为我们的虚拟终端 (0,1,2)。我们现在可以发送命令、查看命令输出以及与该命令关联的任何错误。
From the above lsof command, we can see under the FD column that all three file-descriptors are set to our virtual terminal (0,1,2). We can now send commands, see command output, as well as any errors associated with the command.
以下为 STDIN 和 STDOUT 的示例 −
Following are examples for STDIN and STDOUT −
STDOUT
[root@centosLocal centos]# echo "I am coming from Standard output or STDOUT." >
output.txt && cat output.txt
I am coming from Standard output or STDOUT.
[root@centosLocal centos]#
将 stdout 和 stderr 分别发送到不同的文件也是可行的 −
It is also possible to send both stdout and stderr to separate files −
bash-3.2# find / -name passwd 1> good.txt 2> err.txt
bash-3.2# cat good.txt
/etc/pam.d/passwd
/etc/passwd
bash-3.2# cat err.txt
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
bash-3.2#
在搜索整个文件系统时遇到了两个错误。每个错误都被发送到一个单独的文件供以后参阅,而返回的结果被放入一个单独的文本文件中。
When searching the entire file system, two errors were encountered. Each were sent to a separate file for later perusal, while the results returned were placed into a separate text file.
当执行会向终端输出大量数据的操作(例如编译应用程序)时,将 stderr 发送到文本文件可能很有用。这将允许查看可能从终端滚动条历史记录中丢失的错误。
Sending stderr to a text file can be useful when doing things that output a lot of data to the terminal like compiling applications. This will allow for perusal of errors that could get lost from terminal scrollback history.
在将 STDOUT 传递到文本文件时需要注意的是 >> 和 > 之间的区别。双重“>>”将附加到文件,而单形式将覆盖文件并写入新内容(因此所有以前的数据都将丢失)。
One note when passing STDOUT to a text file are the differences between >> and >. The double ">>" will append to a file, while the singular form will clobber the file and write new contents (so all previous data will be lost).
STDIN
[root@centosLocal centos]# cat < stdin.txt
Hello,
I am being read form Standard input, STDIN.
[root@centosLocal centos]#
在上面的命令中,文本文件 stdin.txt 被重定向到 cat 命令,该命令将它的内容回显到 STDOUT。
In the above command, the text file stdin.txt was redirected to the cat command which echoed its content to STDOUT.
The pipe character "|"
管道字符将接收第一个命令的输出,并将其作为输入传递到下一个命令,从而允许辅助命令对输出执行操作。
The pipe character will take the output from the first command, passing it as an input into the next command, allowing the secondary command to perform operations on the output.
现在,让我们将 cat 的 stdout “管道”到另一个命令 −
Now, let’s "pipe" the stdout of cat to another command −
[root@centosLocal centos]# cat output.txt | wc -l
2
[root@centosLocal centos]#
在上面,wc 对从管道传递的 cat 输出执行计算。当过滤来自 grep 或 egrep 的输出时,管道命令尤其有用 −
Above, wc performs calculations on output from cat which was passed from the pipe. The pipe command is particularly useful when filtering the output from grep or egrep −
[root@centosLocal centos]# egrep "^[0-9]{4}$" /usr/dicts/nums | wc -l
9000
[root@centosLocal centos]#
在上面的命令中,我们将每个 4 位数字从包含通过 egrep 过滤器传递的 65535 所有数字的文本文件传递给了 wc。
In the above command, we passed every 4 digit number to wc from a text file containing all numbers from 65535 passed through an egrep filter.
Redirecting Output with &
输出可以使用 & 字符进行重定向。如果我们想将 STDOUT 和 STDERR 的输出定向到同一个文件,则可以按如下方式完成 −
Output can be redirected using the & character. If we want to direct the output both STDOUT and STDERR, into the same file, it can be accomplished as follows −
[root@centosLocal centos]# find / -name passwd > out.txt 2>&1
[root@centosLocal centos]# cat out.txt
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/etc/passwd
[root@centosLocal centos]#
使用 & 字符的重定向工作方式是:首先,输出重定向至 out.txt。其次,STDERR 或文件描述符 2 重新分配到与 STDOUT 相同的位置,此处为 out.txt。
Redirecting using the & character works like this: first, the output is redirected into out.txt. Second, STDERR or the file descriptor 2 is reassigned to the same location as STDOUT, in this case out.txt.
重定向极其有用,并且在解决处理大型文本文件、编译源代码、在 shell 脚本中重定向输出和发出复杂的 Linux 命令时遇到的问题中派上了用场。
Redirection is extremely useful and comes in handy while solving problems that surgace when manipulating large text-files, compiling source code, redirecting the output in shell scripts, and issuing complex Linux commands.
尽管很强大,但重定向可能使 CentOS 管理员感到复杂。练习、研究以及偶尔向 Linux 论坛(如 Stack Overflow Linux)提问有助于解决高级解决方案。
While powerful, redirection can get complicated for newer CentOS Administrators. Practice, research, and occasional question to a Linux forum (such as Stack Overflow Linux) will help solve advanced solutions.
Bash Shell Constructs
现在,我们已经很好地了解了 Bash shell 的工作原理,让我们学习一些通常用于编写脚本的基本结构。在本节中,我们将探讨 −
Now that we have a good idea of how the Bash shell works, let’s learn some basic constructs, commonly used, to write scripts. In this section we will explore −
BASH Troubleshooting Hints
与专门的脚本语言相比,BASH 可能有些棘手。BASH 脚本中遇到的最大的问题包括不正确地转义或未转义传递给 shell 的脚本操作。如果您已审阅过某个脚本几次且它并未按预期工作,请不要担心。即使每天使用 BASH 创建复杂脚本的人员,也会遇到这种情况。
BASH can be a little tricky compared to a dedicated scripting language. Some of the biggest hang-ups in BASH scripts are from incorrectly escaping or not escaping script operations being passed to the shell. If you have looked over a script a few times and it is not working as expected, don’t fret. This is common even with those who use BASH to create complex scripts daily.
快速搜索 Google 或在专家 Linux 论坛上注册以提出问题,将获得快速解决办法。极有可能有人遇到过完全相同的问题,并且该问题已得到解决。
A quick search of Google or signing up at an expert Linux forum to ask a question will lead to a quick resolution. There is a very likely chance someone has come across the exact issue and it has already been solved.
BASH 脚本制作是一种快速创建强大脚本以用于从自动化管理任务到创建有用工具等各种任务的好方法。成为专家级 BASH 脚本开发人员需要时间和实践。因此,请尽可能使用 BASH 脚本,这是 CentOS 管理工具箱中的一项很棒工具。
BASH scripting is a great method of quickly creating powerful scripts for everything from automating administration tasks to creating useful tools. Becoming an expert level BASH script developer takes time and practice. Hence, use BASH scripts whenever possible, it is a great tool to have in your CentOS Administration toolbox.
Linux Admin - Package Management
CentOS 中的软件包管理可以通过两种方式进行:从终端和图形用户界面。
Package management in CentOS can be performed in two ways: from the terminal and from the Graphical User Interface.
大多数情况下,CentOS 管理员的大部分时间都用于终端。更新和安装 CentOS 软件包没有什么不同。考虑到这一点,我们首先将在终端中探讨软件包管理,然后讨论如何使用 CentOS 提供的图形软件包管理工具。
More often than not a majority of a CentOS administrator’s time will be using the terminal. Updating and installing packages for CentOS is no different. With this in mind, we will first explore package management in the terminal, then touch on using the graphical package management tool provided by CentOS.
YUM Package Manager
YUM 是 CentOS 中提供的软件包管理工具。我们已在之前的章节中简要讨论了该主题。在本教程中,我们将从干净的 CentOS 安装开始。我们将首先完全更新我们的安装,然后安装应用程序。
YUM is the tool provided for package management in CentOS. We have briefly touched this topic in previous chapters. In this chapter, we will be working from a clean CentOS install. We will first completely update our installation and then install an application.
YUM 已经极大地促进了 Linux 中的软件安装和管理。除了过时的软件包之外,YUM 还会“自动”检查过时的依赖项。与过去从源代码编译每个应用程序相比,这确实减轻了 CentOS 管理员的负担。
YUM has brought software installation and management in Linux a long way. YUM "automagically” checks for out-of-date dependencies, in addition to out-of-date packages. This has really taken a load off the CentOS administrator compared to the old days of compiling every application from source-code.
yum check-update
用于检查可更新候选软件包的检查。在本教程中,我们将假设此产品系统面向互联网,没有生产应用程序需要在升级软件包之前由 DevOps 测试。接下来,让我们在系统上安装更新后的候选软件包。
Checks for packages that can update candidates. For this tutorial, we will assume this a production system that will be facing the Internet with no production applications that needs to be tested by DevOps before upgrading the packages. Let us now install the updated candidates onto the system.
[root@localhost rdc]# yum check-update
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.scalabledns.com
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
NetworkManager.x86_64 1:1.4.0-19.el7_3 updates
NetworkManager-adsl.x86_64 1:1.4.0-19.el7_3 updates
NetworkManager-glib.x86_64 1:1.4.0-19.el7_3 updates
NetworkManager-libnm.x86_64 1:1.4.0-19.el7_3 updates
NetworkManager-team.x86_64 1:1.4.0-19.el7_3 updates
NetworkManager-tui.x86_64 1:1.4.0-19.el7_3 updates
NetworkManager-wifi.x86_64 1:1.4.0-19.el7_3 updates
audit.x86_64 2.6.5-3.el7_3.1 updates
vim-common.x86_64 2:7.4.160-1.el7_3.1 updates
vim-enhanced.x86_64 2:7.4.160-1.el7_3.1 updates
vim-filesystem.x86_64 2:7.4.160-1.el7_3.1 updates
vim-minimal.x86_64 2:7.4.160-1.el7_3.1 updates
wpa_supplicant.x86_64 1:2.0-21.el7_3 updates
xfsprogs.x86_64 4.5.0-9.el7_3 updates
[root@localhost rdc]#
yum update
这将安装所有更新的候选软件包,从而使您的 CentOS 安装保持最新状态。对于新安装,这可能需要一点时间,具体取决于您的安装和互联网连接速度。
This will install all updated candidates making your CentOS installation current. With a new installation, this can take a little time depending on your installation and your internet connection speed.
[root@localhost rdc]# yum update
vim-minimal x86_64 2:7.4.160-1.el7_3.1 updates 436 k
wpa_supplicant x86_64 1:2.0-21.el7_3 updates 788 k
xfsprogs x86_64 4.5.0-9.el7_3 updates 895 k
Transaction Summary
======================================================================================
Install 2 Packages
Upgrade 156 Packages
Total download size: 371 M
Is this ok [y/d/N]:
Install Software via YUM
除了更新 CentOS 系统之外,YUM 软件包管理器也是我们安装软件的工具。从网络监控工具到视频播放器再到文本编辑器,通过使用 YUM,一切都可从中心存储库安装。
Besides updating the CentOS system, the YUM package manager is our go-to tool for installing the software. Everything from network monitoring tools, video players, to text editors can be installed from a central repository with YUM.
在安装一些软件实用程序之前,让我们先看一下几个 YUM 命令。对于日常工作,90% 的 CentOS 管理员使用 YUM 时都会使用约 7 个命令。我们将在希望熟悉以熟练水平操作 YUM 以供日常使用时逐一加以研究。但是,与大多数 Linux 实用程序一样,YUM 提供了丰富的先进功能,始终值得通过手册页来探讨这些功能。使用 man yum 始终是使用任何 Linux 实用程序执行不熟悉操作的第一步。
Before installing some software utilities, let’s look at few YUM commands. For daily work, 90% of a CentOS Admin’s usage of YUM will be with about 7 commands. We will go over each in the hope of becoming familiar with operating YUM at a proficient level for daily use. However, like most Linux utilities, YUM offers a wealth of advanced features that are always great to explore via the man page. Use man yum will always be the first step to performing unfamiliar operations with any Linux utility.
Most Common YUM Commands
以下是一些常用的 YUM 命令。
Following are the commonly used YUM commands.
Command |
Action |
list installed |
Lists packages installed via YUM |
list all |
Lists all currently available packages |
group list |
Lists grouped packages |
info |
Provides detailed information about a package |
search |
Searches package descriptions and names |
install |
Installs a package |
localinstall |
Installs a local rpm package |
remove |
Removes and installs package |
clean all |
Cleans /var/cache/yum to free disk-space |
man yum |
Like all linux commands, the help file |
Install Software with YUM
现在,我们安装一个基于文本的 Web 浏览器,名为 Lynx 。在安装之前,我们必须首先获取包含 Lynx Web 浏览器在内的软件包名称。我们甚至不能 100% 确定我们的默认 CentOS 存储库是否为 Lynx Web 浏览器提供了一个软件包,所以让我们搜索并查看 −
We will now install a text-based web browser called Lynx. Before installation, we must first get the package name containing the Lynx web browser. We are not even 100% sure our default CentOS repository provides a package for the Lynx web browser, so let’s search and see −
[root@localhost rdc]# yum search web browser
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.scalabledns.com
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
=================================================================
N/S matched: web, browser
==================================================================
icedtea-web.x86_64 : Additional Java components for OpenJDK - Java browser
plug-in and Web Start implementation
elinks.x86_64 : A text-mode Web browser
firefox.i686 : Mozilla Firefox Web browser
firefox.x86_64 : Mozilla Firefox Web browser
lynx.x86_64 : A text-based Web browser
Full name and summary matches only, use "search all" for everything.
[root@localhost rdc]#
我们看到,CentOS 确实在存储库中提供了 Lynx Web 浏览器。让我们看看有关该软件包的更多信息。
We see, CentOS does offer the Lynx web browser in the repository. Let’s see some more information about the package.
[root@localhost rdc]# lynx.x86_64
bash: lynx.x86_64: command not found...
[root@localhost rdc]# yum info lynx.x86_64
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.scalabledns.com
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
Available Packages
Name : lynx
Arch : x86_64
Version : 2.8.8
Release : 0.3.dev15.el7
Size : 1.4 M
Repo : base/7/x86_64
Summary : A text-based Web browser
URL : http://lynx.isc.org/
License : GPLv2
Description : Lynx is a text-based Web browser. Lynx does not display any images,
: but it does support frames, tables, and most other HTML tags. One
: advantage Lynx has over graphical browsers is speed; Lynx starts and
: exits quickly and swiftly displays web pages.
[root@localhost rdc]#
不错!版本 2.8 已经是最新的了,所以让我们安装 Lynx。
Nice! Version 2.8 is current enough so let’s install Lynx.
[root@localhost rdc]# yum install lynx
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.scalabledns.com
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
Resolving Dependencies
--> Running transaction check
---> Package lynx.x86_64 0:2.8.8-0.3.dev15.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch
Version Repository Size
===============================================================================
===============================================================================
Installing:
lynx x86_64
2.8.80.3.dev15.el7 base 1.4 M
Transaction Summary
===============================================================================
===============================================================================
Install 1 Package
Total download size: 1.4 M
Installed size: 5.4 M
Is this ok [y/d/N]: y
Downloading packages:
No Presto metadata available for base
lynx-2.8.8-0.3.dev15.el7.x86_64.rpm
| 1.4 MB 00:00:10
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : lynx-2.8.8-0.3.dev15.el7.x86_64
1/1
Verifying : lynx-2.8.8-0.3.dev15.el7.x86_64
1/1
Installed:
lynx.x86_64 0:2.8.8-0.3.dev15.el7
Complete!
[root@localhost rdc]#
接下来,让我们确保 Lynx 确实正确安装了。
Next, let’s make sure Lynx did in fact install correctly.
[root@localhost rdc]# yum list installed | grep -i lynx
lynx.x86_64 2.8.8-0.3.dev15.el7 @base
[root@localhost rdc]#
太棒了!让我们使用 Lynx 来看看没有“喜欢”和漂亮图片的 Web 界面。
Great! Let’s use Lynx to and see what the web looks like without "likes" and pretty pictures.
[root@localhost rdc]# lynx www.tutorialpoint.in
太棒了,现在我们为我们的生产服务器配置了一个 Web 浏览器,无需过分担心通过 Web 发起的远程利用。这对生产服务器来说是一件好事。
Great, now we have a web browser for our production server that can be used without much worry into remote exploits launched over the web. This a good thing for production servers.
我们几乎完成了,然而我们首先需要为开发人员设置该服务器来测试应用程序。因此,让我们确保他们拥有完成工作所需的所有工具。我们可以单独安装所有内容,但是 CentOS 和 YUM 让这个过程快了很多。让我们安装开发群组软件包。
We are almost completed, however first we need to set this server for developers to test applications. Thus, let’s make sure they have all the tools needed for their job. We could install everything individually, but CentOS and YUM have made this a lot faster. Let’s install the Development Group Package.
[root@localhost rdc]# yum groups list
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.scalabledns.com
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
Available Groups:
Compatibility Libraries
Console Internet Tools
Development Tools
Graphical Administration Tools
Legacy UNIX Compatibility
Scientific Support
Security Tools
Smart Card Support
System Administration Tools
System Management
Done
[root@localhost rdc]#
这是 CentOS 提供的较小的一组软件包群组。让我们看看“开发群组”中包含哪些内容。
This is a smaller list of Package Groups provided by CentOS. Let’s see what is included with the "Development Group".
[root@localhost rdc]# yum group info "Development Tools"
Loaded plugins: fastestmirror, langpacks
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Loading mirror speeds from cached hostfile
* base: mirror.scalabledns.com
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
Group: Development Tools
Group-Id: development
Description: A basic development environment.
Mandatory Packages:
autoconf
automake
binutils
bison
输出的第一个屏幕类似于上面看到的。这个完整列表包括很多内容。但是,随着时间的推移,通常需要完整安装此群组。让我们安装完整的开发群组。
The first screen of output is as seen above. This entire list is rather comprehensive. However, this group will usually be needed to be installed in its entirety as time goes by. Let’s install the entire Development Group.
[root@localhost rdc]# yum groupinstall "Development Tools"
这将是一个更大的安装。完成后,你的服务器将拥有大多数用于 Perl、Python、C 和 C++ 语言的开发库和编译器。
This will be a larger install. When completed, your server will have most development libraries and compilers for Perl, Python, C, and C++.
Graphical Package Management in CentOS
Gnome 桌面提供了一个称为 Software 的图形化软件包管理工具。它相当简单易用。CentOS 的 Gnome 软件包管理工具软件可以找到这里:应用程序 → 系统工具 → 软件。
Gnome Desktop provides a graphical package management tool called Software. It is fairly simple to use and straightforward. Software, the Gnome package management tool for CentOS can be found by navigating to: Applications → System Tools → Software.
软件包管理工具分为多个群组,允许管理员选择要安装的软件包。虽然这款工具易于使用,并且对最终用户而言非常简单,但是 YUM 更加强大,可能被管理员更多地使用。
The Software Package Management Tool is divided into groups allowing the administrator to select packages for installation. While this tool is great for ease-of-use and simplicity for end-users, YUM is a lot more powerful and will probably be used more by administrators.
以下是软件包管理工具的屏幕截图,该工具并非专门为系统管理员设计。
Following is a screenshot of the Software Package Management Tool, not really designed for System Administrators.

Linux Admin - Volume Management
Logical Volume Management (LVM) 是 Linux 用来跨不同物理硬盘管理存储卷的方法。不要将其与 RAID 混淆。但它可以被认为与 RAID 0 或 JBOD 类似的概念。利用 LVM,我们有可能(例如)拥有三个 1TB 的物理硬盘,然后一个大约 3TB 的逻辑卷,例如 /dev/sdb。甚至是两个 1.5TB 的逻辑卷,5 个 500GB 的卷,或者任何组合。单个硬盘还可用于逻辑卷的快照。
Logical Volume Management (LVM) is a method used by Linux to manage storage volumes across different physical hard disks. This is not to be confused with RAID. However, it can be thought of in a similar concept as RAID 0 or J-Bod. With LVM, it is possible to have (for example) three physical disks of 1TB each, then a logical volume of around 3TB such as /dev/sdb. Or even two logical volumes of 1.5TB, 5 volumes of 500GB, or any combination. One single disk can even be used for snapshots of Logical Volumes.
Note − 正确配置时,使用逻辑卷实际上会增加磁盘 I/O。这与在不同的硬盘中分配 RAID 0 条带数据的工作方式类似。
Note − Using Logical Volumes actually increases disk I/O when configured correctly. This works in a similar fashion to RAID 0 striping data across separate disks.
在通过 LVM 学习卷管理时,了解 LVM 中的每个组件会更容易。请学习下表,以牢固掌握每个组件。如有需要,请使用 Google 进行学习。了解逻辑卷的每个部分对于管理它们非常重要。
When learning about volume management with LVM, it is easier if we know what each component in LVM is. Please study the following table to get a firm grasp of each component. If you need to, use Google to study. Understanding each piece of a logical volume is important to manage them.
PV |
Physical Volume |
sda |
PP |
Physical Partition |
sda1 , sda2 |
VG |
Volume Group |
Pooled physical resources |
LV |
Logical Volume |
Seen as a storage facility to the operating system |
physical volume 将被视为 /dev/sda、/dev/sdb;由 Linux 检测到的物理硬盘。
A physical volume will be seen as /dev/sda, /dev/sdb; a physical disk that is detected by Linux.
physical partition 将成为磁盘实用工具(比如 fdisk)分区的磁盘部分。记住,在最常见的 LVM 设置中不建议使用物理分区。示例:磁盘 /dev/sda 被分区为包括两个物理分区:/dev/sda1 和 /dev/sda2
A physical partition will be a section of the disk partitioned by a disk utility such as fdisk. Keep in mind, physical partition is not recommended in most common LVM setups. Example: disk /dev/sda is partitioned to include two physical partitions: /dev/sda1 and /dev/sda1
如果我们有两块各 1TB 的物理磁盘,我们可以在两者之间创建一个将近 2TB 的卷组。
If we have two physical disks of 1TB each, we can create a volume group of almost 2TB amongst the two.
从卷组中,我们可以创建三个任意大小的逻辑卷,不超过总卷组大小。
From the volume group, we can create three logical volumes each of any-size not exceeding the total volume group size.
Traditional Linux Disk Administration Tools
在熟悉 CentOS 7 中 LVM 管理的最新最棒的功能工具之前,我们应该首先了解一些用于 Linux 磁盘管理的更传统的工具。这些工具非常方便,并且仍然可以与现今的 LVM 高级工具(如系统存储管理器 − lsblk、parted 和 mkfs.xfs)配合使用。
Before being acquainted with the latest and greatest featured tools for LVM Management in CentOS 7, we should first explore more traditional tools that have been used for Linux disk management. These tools will come handy and still have use with today’s advanced LVM tools such as the System Storage Manager − lsblk, parted, and mkfs.xfs.
现在,假设我们系统中又添加了一块或两块磁盘,我们需要列出 Linux 检测到的磁盘。我建议在执行被认为具有破坏性的操作前每次都列出磁盘。 lsblk 是获取磁盘信息的出色工具。让我们看看 CentOS 检测到哪些磁盘。
Now, assuming we have added another disk or two to our system, we need to enumerate disks detected by Linux. I’d always advise enumerating disks every time before performing operations considered as destructive. lsblk is a great tool for getting disk information. Let’s see what disks CentOS detects.
[root@localhost rdc]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 20G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 19G 0 part
├─cl-root 253:0 0 17G 0 lvm /
└─cl-swap 253:1 0 2G 0 lvm [SWAP]
sdb 8:16 0 6G 0 disk
sdc 8:32 0 4G 0 disk
sr0 11:0 1 1024M 0 rom
如你所见,此系统上有三块磁盘:sda、sdb 和 sdc。
As you can see, we have three disks on this system: sda, sdb, and sdc.
磁盘 sda 包含我们正在运行的 CentOS 安装,所以我们不希望随意更改 sda。sdb 和 sdc 在本教程中都添加到了系统中。让我们让 CentOS 能够使用这些磁盘。
Disk sda contains our working CentOS installation, so we do not want to toy around with sda. Both sdb and sdc were added to the system for this tutorial. Let’s make these disks usable to CentOS.
Create a Disk Label
[root@localhost rdc]# parted /dev/sdb mklabel GPT
Warning: The existing disk label on /dev/sdb will be destroyed and all data on this
disk will be lost. Do you want to continue?
Yes/No? Yes
[root@localhost rdc]#
我们现在有一个带有标签的磁盘。只需按照相同的方式在 sdc 上运行 parted 命令。
We now have one disk labeled. Simply run the parted command in the same manner on sdc.
Create the Partitions on the Disk
我们仅在每个磁盘上创建一个分区。要创建分区,再次使用 parted 命令。
We will only create a single partition on each disk. To create partitions, the parted command is used again.
[root@localhost rdc]# parted -a opt /dev/sdb mkpart primary ext4 0% 100%
Warning − 您从 0.00B 到 6442MB(扇区 0..12582911)请求一个分区。
Warning − You requested a partition from 0.00B to 6442MB (sectors 0..12582911).
我们能够管理的最接近位置是从 17.4kB 到 1048kB(扇区 34..2047)。
The closest location we can manage is 17.4kB to 1048kB (sectors 34..2047).
您是否仍可接受?
Is this still acceptable to you?
是/否?否
Yes/No? NO
[root@localhost rdc]# parted -a opt /dev/sdc mkpart primary ext4 0% 100%
Information − 您可能需要更新 /etc/fstab。
Information − You may need to update /etc/fstab.
[root@localhost rdc]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 20G 0 disk
├─sda1 8:1 0 1G 0 part / boot
└─sda2 8:2 0 19G 0 part
├─cl-root 253:0 0 17G 0 lvm /
└─cl-swap 253:1 0 2G 0 lvm [SWAP]
sdb 8:16 0 6G 0 disk
└─sdb1 8:17 0 6G 0 part
sdc 8:32 0 4G 0 disk
└─sdc1 8:33 0 4G 0 part
sr0 11:0 1 1024M 0 rom
[root@localhost rdc]#
正如从 lsblk 输出中看到的那样,我们现在有两个分区,分别在 sdb 和 sdc 上。
As you can see from lsblk output, we now have two partitions, each on sdb and sdc.
Make the File System
最后,在挂载和使用任何卷之前,我们需要添加文件系统。我们将使用 XFS 文件系统。
Finally, before mounting and using any volume we need to add a file system. We will be using the XFS file system.
root@localhost rdc]# mkfs.xfs -f /dev/sdb1
meta-data = /dev/sdb1 isize = 512 agcount = 4, agsize = 393088 blks
= sectsz = 512 attr = 2, projid32bit = 1
= crc = 1 finobt = 0, sparse = 0
data = bsize = 4096 blocks = 1572352, imaxpct = 25
= sunit = 0 swidth = 0 blks
naming = version 2 bsize = 4096 ascii-ci = 0 ftype = 1
log = internal log bsize = 4096 blocks = 2560, version = 2
= sectsz = 512 sunit = 0 blks, lazy-count = 1
realtime = none extsz = 4096 blocks = 0, rtextents = 0
[root@localhost rdc]# mkfs.xfs -f /dev/sdc1
meta-data = /dev/sdc1 isize = 512 agcount = 4, agsize = 262016 blks
= sectsz = 512 attr = 2, projid32bit = 1
= crc = 1 finobt = 0, sparse = 0
data = bsize = 4096 blocks = 1048064, imaxpct = 25
= sunit = 0 swidth = 0 blks
naming = version 2 bsize = 4096 ascii-ci = 0 ftype = 1
log = internal log bsize = 4096 blocks = 2560, version = 2
= sectsz = 512 sunit = 0 blks, lazy-count = 1
realtime = none extsz = 4096 blocks = 0, rtextents = 0
[root@localhost rdc]#
让我们检查一下确保每个分区都有一个可用的文件系统。
Let’s check to make sure each have a usable file system.
[root@localhost rdc]# lsblk -o NAME,FSTYPE
NAME FSTYPE
sda
├─sda1 xfs
└─sda2 LVM2_member
├─cl-root xfs
└─cl-swap swap
sdb
└─sdb1 xfs
sdc
└─sdc1 xfs
sr0
[root@localhost rdc]#
每个分区现在都在使用 XFS 文件系统。让我们将它们挂载、检查挂载并复制一个文件到每个分区。
Each is now using the XFS file system. Let’s mount them, check the mount, and copy a file to each.
[root@localhost rdc]# mount -o defaults /dev/sdb1 /mnt/sdb
[root@localhost rdc]# mount -o defaults /dev/sdc1 /mnt/sdc
[root@localhost ~]# touch /mnt/sdb/myFile /mnt/sdc/myFile
[root@localhost ~]# ls /mnt/sdb /mnt/sdc
/mnt/sdb:
myFile
/mnt/sdc:
myFile
我们在此时有两个可用的磁盘。但是,只有在手动挂载它们时它们才可用。若要在启动时挂载它们,我们必须编辑 fstab 文件。此外,必须为需要访问新磁盘的组设置权限。
We have two usable disks at this point. However, they will only be usable when we mount them manually. To mount each on boot, we must edit the fstab file. Also, permissions must be set for groups needing access to the new disks.
Create Volume Groups and Logical Volumes
CentOS 7 中最重要的新增功能之一是实用程序 System Storage Manager 或 ssm。 System Storage Manager 大大简化了 Linux 上的 LVM 池和存储卷的管理过程。
One of the greatest addition to CentOS 7 was the inclusion of a utility called System Storage Manager or ssm. System Storage Manager greatly simplifies the process of managing LVM pools and storage volumes on Linux.
我们来一步步了解在 CentOS 中创建简单卷池和逻辑卷的过程。第一步是安装 System Storage Manager。
We will go through the process of creating a simple volume pool and logical volumes in CentOS. The first step is installing the System Storage Manager.
[root@localhost rdc]# yum install system-storage-manager
让我们使用 ssm list 命令查看我们的磁盘。
Let’s look at our disks using the ssm list command.

如上所示,系统上共安装了三块磁盘。
As seen above, a total of three disks are installed on the system.
-
/sdba1 − Hosts our CentOS installation
-
/sdb1 − Mounted at /mnt/sdb
-
/sdc1 − Mounted at /mnt/sdc
我们要做的便是使用两块磁盘 (sdb 和 sdc) 创建卷组。然后为系统提供三个 3GB 逻辑卷。
What we want to do is make a Volume Group using two disks (sdb and sdc). Then make three 3GB Logical Volumes available to the system.
让我们创建我们的卷组。
Let’s create our Volume Group.
[root@localhost rdc]# ssm create -p NEW_POOL /dev/sdb1 /dev/sdc1
默认情况下,ssm 将创建一个单个逻辑卷,扩展整个 10GB 的池。我们不希望这样,所以让我们删除此内容。
By default, ssm will create a single logical volume extending the entire 10GB of the pool. We don’t want this, so let’s remove this.
[root@localhost rdc]# ssm remove /dev/NEW_POOL/lvol001
Do you really want to remove active logical volume NEW_POOL/lvol001? [y/n]: y
Logical volume "lvol001" successfully removed
[root@localhost rdc]#
最后,我们来创建三个逻辑卷。
Finally, let’s create the three Logical Volumes.
[root@localhost rdc]# ssm create -n disk001 --fs xfs -s 3GB -p NEW_POOL
[root@localhost rdc]# ssm create -n disk002 --fs xfs -s 3GB -p NEW_POOL
[root@localhost rdc]# ssm create -n disk003 --fs xfs -s 3GB -p NEW_POOL
现在,让我们检查我们的新卷。
Now, let’s check our new volumes.

现在我们有了跨越两个物理磁盘分区的三块独立逻辑卷。
We now have three separate logical volumes spanned across two physical disk partitions.
逻辑卷是一项现在内置于 CentOS Linux 中的强大功能。我们已经接触到了这些管理内容的皮毛。精通池和逻辑卷需要反复练习和教程中心的扩展学习。现在,你已经了解 CentOS 中 LVM 管理的基础知识,并具备在单一主机上创建基本条带逻辑卷的能力。
Logical volumes are a powerful feature now built into CentOS Linux. We have touched the surface on managing these. Mastering pools and logical volumes come with practice and extended learning from Tutorials Point. For now, you have learned the basics of LVM management in CentOS and possess the ability to create basic striped Logical Volumes on a single host.