Ubuntu 环境搭建

guide 网站推荐:

apt 相关操作

进程查看|端口占用|端口监听

用户|用户组管理

查找搜索 grep | cat | find | tail

grep 使用: ref1 ref2

cat 使用:

find 使用:

ssh安装和配置

参考链接

命令详解

 

systemctl相关命令

nginx 安装和管理

redis 安装|管理|命令行管理数据

参考链接

命令详解

 

php安装和管理:

php安装

php配置和启停

composer 安装和管理

MariaDB

MariaDB安装和基础配置

MariaDB配置文件

端口监听支持外网:MariaDB配置外网访问

MariaDB用户配置和远程连接

 

docker 安装和配置

docker 安装

docker常用命令

docker exec

安装docker-compose

安装docker image和启动

代理设置(暂时的)

git代理设置(长期的)

文件管理

缓存文件夹清理(Seagm-store/tmp为例)

打包压缩

批量移动/删除文件:

find 命令介绍:mac 显示隐藏文件+Find命令

移动、复制、删除

空间查看

权限更改

文件上传下载

npm

npm常用命令

npm package管理

npm 代理设置(长期的)

 

OSS命令行上传(通过“ossutil64”工具)

安装ossutil64

使用ossutil64

 

git:

git reset -hard 21e4615ac29c880171ccb7454b91b08c07e56e65

 

Issues

Error loading Python lib '/tmp/MEI5AbIEA/libpython3.9.so.1.0': dlopen: /lib64/libc.so.6: version `GLIBC_2.28' not found (required by /tmp/MEI5AbIEA/libpython3.9.so.1.0)

connect() to unix:/var/opt/remi/php73/run/php-fpm/www.sock failed (13: Permission denied) while connecting to upstream,

参考:用户和用户组管理

 

 

 

How To Install Nginx on Ubuntu 20.04

Published on April 25, 2020 · Updated on January 6, 2022

 

Introduction

Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is a lightweight choice that can be used as either a web server or reverse proxy.

In this guide, we’ll discuss how to install Nginx on your Ubuntu 20.04 server, adjust the firewall, manage the Nginx process, and set up server blocks for hosting more than one domain from a single server.

Prerequisites

Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. You can learn how to configure a regular user account by following our Initial server setup guide for Ubuntu 20.04.

You will also optionally want to have registered a domain name before completing the last steps of this tutorial. To learn more about setting up a domain name with DigitalOcean, please refer to our Introduction to DigitalOcean DNS.

When you have an account available, log in as your non-root user to begin.

Step 1 – Installing Nginx

Because Nginx is available in Ubuntu’s default repositories, it is possible to install it from these repositories using the apt packaging system.

Since this is our first interaction with the apt packaging system in this session, we will update our local package index so that we have access to the most recent package listings. Afterwards, we can install nginx:

After accepting the procedure, apt will install Nginx and any required dependencies to your server.

Step 2 – Adjusting the Firewall

Before testing Nginx, the firewall software needs to be adjusted to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.

List the application configurations that ufw knows how to work with by typing:

You should get a listing of the application profiles:

As demonstrated by the output, there are three profiles available for Nginx:

It is recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Right now, we will only need to allow traffic on port 80.

You can enable this by typing:

You can verify the change by typing:

The output will indicated which HTTP traffic is allowed:

Step 3 – Checking your Web Server

At the end of the installation process, Ubuntu 20.04 starts Nginx. The web server should already be up and running.

We can check with the systemd init system to make sure the service is running by typing:

As confirmed by this out, the service has started successfully. However, the best way to test this is to actually request a page from Nginx.

You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server’s IP address. If you do not know your server’s IP address, you can find it by using the icanhazip.com tool, which will give you your public IP address as received from another location on the internet:

When you have your server’s IP address, enter it into your browser’s address bar:

You should receive the default Nginx landing page:

Nginx default page

If you are on this page, your server is running correctly and is ready to be managed.

Step 4 – Managing the Nginx Process

Now that you have your web server up and running, let’s review some basic management commands.

To stop your web server, type:

To start the web server when it is stopped, type:

To stop and then start the service again, type:

If you are only making configuration changes, Nginx can often reload without dropping connections. To do this, type:

By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing:

To re-enable the service to start up at boot, you can type:

You have now learned basic management commands and should be ready to configure the site to host more than one domain.

When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name.

Nginx on Ubuntu 20.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.

Create the directory for your_domain as follows, using the -p flag to create any necessary parent directories:

Next, assign ownership of the directory with the $USER environment variable:

The permissions of your web roots should be correct if you haven’t modified your umask value, which sets default file permissions. To ensure that your permissions are correct and allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others, you can input the following command:

Next, create a sample index.html page using nano or your favorite editor:

Inside, add the following sample HTML:

/var/www/your_domain/html/index.html

Save and close the file by pressing Ctrl+X to exit, then when prompted to save, Y and then Enter.

In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/your_domain:

Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:

/etc/nginx/sites-available/your_domain

Notice that we’ve updated the root configuration to our new directory, and the server_name to our domain name.

Next, let’s enable the file by creating a link from it to the sites-enabled directory, which Nginx reads from during startup:

Note: Nginx uses a common practice called symbolic links, or symlinks, to track which of your server blocks are enabled. Creating a symlink is like creating a shortcut on disk, so that you could later delete the shortcut from the sites-enabled directory while keeping the server block in sites-available if you wanted to enable it.

Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives (you can read more about how Nginx processes these directives here):

To avoid a possible hash bucket memory problem that can arise from adding additional server names, it is necessary to adjust a single value in the /etc/nginx/nginx.conf file. Open the file:

Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line. If you are using nano, you can quickly search for words in the file by pressing CTRL and w.

Note: Commenting out lines of code – usually by putting # at the start of a line – is another way of disabling them without needing to actually delete them. Many configuration files ship with multiple options commented out so that they can be enabled or disabled, by toggling them between active code and documentation.

/etc/nginx/nginx.conf

Save and close the file when you are finished.

Next, test to make sure that there are no syntax errors in any of your Nginx files:

If there aren’t any problems, restart Nginx to enable your changes:

Nginx should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like this:

Nginx first server block

Step 6 – Getting Familiar with Important Nginx Files and Directories

Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.

Content

Server Configuration

Server Logs

Conclusion

Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.

If you’d like to build out a more complete application stack, check out the article How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu 20.04.

In order to set up HTTPS for your domain name with a free SSL certificate using Let’s Encrypt, you should move on to How To Secure Nginx with Let’s Encrypt on Ubuntu 20.04.

 

 

 

 

How To Install and Secure Redis on Ubuntu 20.04

Published on May 1, 2020 · Updated on May 2, 2020

Introduction

Redis is an in-memory key-value store known for its flexibility, performance, and wide language support. This tutorial demonstrates how to install, configure, and secure Redis on an Ubuntu 20.04 server.

Prerequisites

To complete this guide, you will need access to an Ubuntu 20.04 server that has a non-root user with sudo privileges and a firewall configured with ufw. You can set this up by following our Initial Server Setup guide for Ubuntu 20.04.

Step 1 — Installing and Configuring Redis

We’ll use the APT package manager to install redis from the official Ubuntu repositories. As of this writing, the version available in the default repositories is 5.0.7.

Begin by updating your local apt package cache:

Then install Redis by typing:

This will download and install Redis and its dependencies. Following this, there is one important configuration change to make in the Redis configuration file, which was generated automatically during the installation.

Open this file with your preferred text editor:

Inside the file, find the supervised directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The supervised directive is set to no by default. Since you are running Ubuntu, which uses the systemd init system, change this to systemd:

That’s the only change you need to make to the Redis configuration file at this point, so save and close it when you are finished. If you used nano to edit the file, do so by pressing CTRL + X, Y, then ENTER.

Then, restart the Redis service to reflect the changes you made to the configuration file:

With that, you’ve installed and configured Redis and it’s running on your machine. Before you begin using it, though, it’s prudent to first check whether Redis is functioning correctly.

Step 2 — Testing Redis

As with any newly-installed software, it’s a good idea to ensure that Redis is functioning as expected before making any further changes to its configuration. We will go over a handful of ways to check that Redis is working correctly in this step.

Start by checking that the Redis service is running:

If it is running without any errors, this command will produce output similar to the following:

Here, you can see that Redis is running and is already enabled, meaning that it is set to start up every time the server boots.

Note: This setting is desirable for many common use cases of Redis. If, however, you prefer to start up Redis manually every time your server boots, you can configure this with the following command:

To test that Redis is functioning correctly, connect to the server using redis-cli, Redis’s command-line client:

In the prompt that follows, test connectivity with the ping command:

This output confirms that the server connection is still alive. Next, check that you’re able to set keys by running:

Retrieve the value by typing:

Assuming everything is working, you will be able to retrieve the value you stored:

After confirming that you can fetch the value, exit the Redis prompt to get back to the shell:

As a final test, we will check whether Redis is able to persist data even after it’s been stopped or restarted. To do this, first restart the Redis instance:

Then connect with the command-line client again:

And confirm that your test value is still available

The value of your key should still be accessible:

Exit out into the shell again when you are finished:

With that, your Redis installation is fully operational and ready for you to use. However, some of its default configuration settings are insecure and provide malicious actors with opportunities to attack and gain access to your server and its data. The remaining steps in this tutorial cover methods for mitigating these vulnerabilities, as prescribed by the official Redis website. Although these steps are optional and Redis will still function if you choose not to follow them, it is strongly recommended that you complete them in order to harden your system’s security.

Step 3 — Binding to localhost

By default, Redis is only accessible from localhost. However, if you installed and configured Redis by following a different tutorial than this one, you might have updated the configuration file to allow connections from anywhere. This is not as secure as binding to localhost.

To correct this, open the Redis configuration file for editing:

Locate this line and make sure it is uncommented (remove the # if it exists):

/etc/redis/redis.conf

Save and close the file when finished (press CTRL + X, Y, then ENTER).

Then, restart the service to ensure that systemd reads your changes:

To check that this change has gone into effect, run the following netstat command:

Note: The netstat command may not be available on your system by default. If this is the case, you can install it (along with a number of other handy networking tools) with the following command:

This output shows that the redis-server program is bound to localhost (127.0.0.1), reflecting the change you just made to the configuration file. If you see another IP address in that column (0.0.0.0, for example), then you should double check that you uncommented the correct line and restart the Redis service again.

Now that your Redis installation is only listening in on localhost, it will be more difficult for malicious actors to make requests or gain access to your server. However, Redis isn’t currently set to require users to authenticate themselves before making changes to its configuration or the data it holds. To remedy this, Redis allows you to require users to authenticate with a password before making changes via the Redis client (redis-cli).

Step 4 — Configuring a Redis Password

Configuring a Redis password enables one of its two built-in security features — the auth command, which requires clients to authenticate to access the database. The password is configured directly in Redis’s configuration file, /etc/redis/redis.conf, so open that file again with your preferred editor:

Scroll to the SECURITY section and look for a commented directive that reads:

/etc/redis/redis.conf

Uncomment it by removing the #, and change foobared to a secure password.

Note: Above the requirepass directive in the redis.conf file, there is a commented warning:

/etc/redis/redis.conf

Thus, it’s important that you specify a very strong and very long value as your password. Rather than make up a password yourself, you can use the openssl command to generate a random one, as in the following example. By piping the output of the first command to the second openssl command, as shown here, it will remove any line breaks produced by that the first command:

Your output should look something like:

After copying and pasting the output of that command as the new value for requirepass, it should read:

After setting the password, save and close the file, then restart Redis:

To test that the password works, open up the Redis client:

The following shows a sequence of commands used to test whether the Redis password works. The first command tries to set a key to a value before authentication:

That won’t work because you didn’t authenticate, so Redis returns an error:

The next command authenticates with the password specified in the Redis configuration file:

Redis acknowledges:

After that, running the previous command again will succeed:

get key1 queries Redis for the value of the new key.

After confirming that you’re able to run commands in the Redis client after authenticating, you can exit redis-cli:

Next, we’ll look at renaming Redis commands which, if entered by mistake or by a malicious actor, could cause serious damage to your machine.

Step 5 — Renaming Dangerous Commands

The other security feature built into Redis involves renaming or completely disabling certain commands that are considered dangerous.

When run by unauthorized users, such commands can be used to reconfigure, destroy, or otherwise wipe your data. Like the authentication password, renaming or disabling commands is configured in the same SECURITY section of the /etc/redis/redis.conf file.

Some of the commands that are considered dangerous include: FLUSHDB, FLUSHALL, KEYS, PEXPIRE, DEL, CONFIG, SHUTDOWN, BGREWRITEAOF, BGSAVE, SAVE, SPOP, SREM, RENAME, and DEBUG. This is not a comprehensive list, but renaming or disabling all of the commands in that list is a good starting point for enhancing your Redis server’s security.

Whether you should disable or rename a command depends on your specific needs or those of your site. If you know you will never use a command that could be abused, then you may disable it. Otherwise, it might be in your best interest to rename it.

To rename or disable Redis commands, open the configuration file once more:

Warning: The following steps showing how to disable and rename commands are examples. You should only choose to disable or rename the commands that make sense for you. You can review the full list of commands for yourself and determine how they might be misused at redis.io/commands.

To disable a command, simply rename it to an empty string (signified by a pair of quotation marks with no characters between them), as shown below:

/etc/redis/redis.conf

To rename a command, give it another name as shown in the examples below. Renamed commands should be difficult for others to guess, but easy for you to remember:

/etc/redis/redis.conf

Save your changes and close the file.

After renaming a command, apply the change by restarting Redis:

To test the new command, enter the Redis command line:

Then, authenticate:

Let’s assume that you renamed the CONFIG command to ASC12_CONFIG, as in the preceding example. First, try using the original CONFIG command. It should fail, because you’ve renamed it:

Calling the renamed command, however, will be successful. It is not case-sensitive:

Finally, you can exit from redis-cli:

Note that if you’re already using the Redis command line and then restart Redis, you’ll need to re-authenticate. Otherwise, you’ll get this error if you type a command:

Regarding the practice of renaming commands, there’s a cautionary statement at the end of the SECURITY section in /etc/redis/redis.conf which reads:

/etc/redis/redis.conf

Note: The Redis project chooses to use the terms “master” and “slave,” while DigitalOcean generally prefers the alternatives “primary” and “secondary.” In order to avoid confusion we’ve chosen to use the terms used in the Redis documentation here.

That means if the renamed command is not in the AOF file, or if it is but the AOF file has not been transmitted to slaves, then there should be no problem.

So, keep that in mind when you’re trying to rename commands. The best time to rename a command is when you’re not using AOF persistence, or right after installation, that is, before your Redis-using application has been deployed.

When you’re using AOF and dealing with a master-slave installation, consider this answer from the project’s GitHub issue page. The following is a reply to the author’s question:

The commands are logged to the AOF and replicated to the slave the same way they are sent, so if you try to replay the AOF on an instance that doesn’t have the same renaming, you may face inconsistencies as the command cannot be executed (same for slaves).

Thus, the best way to handle renaming in cases like that is to make sure that renamed commands are applied to all instances in master-slave installations.

Conclusion

In this tutorial, you installed and configured Redis, validated that your Redis installation is functioning correctly, and used its built-in security features to make it less vulnerable to attacks from malicious actors.

Keep in mind that once someone is logged in to your server, it’s very easy to circumvent the Redis-specific security features we’ve put in place. Therefore, the most important security feature on your Redis server is your firewall (which you configured if you followed the prerequisite Initial Server Setup tutorial), as this makes it extremely difficult for malicious actors to jump that fence.

 

 

 

 

 

 

systemctl命令介绍和使用

Systemd程序

Systemd其实是Linux系统用来管理系统的一个程序,用来代替原来的init进程(用来管理启动系统其它的服务进程),现在很多Linux发行版都已经自带Systemd程序了。


systemctl命令

1. Unit

systemctl命令是Systemd中最重要的一个命令,用于对服务进行启动,停止等操作,在Systemd中有Unit的概念,每个进程都是一个Unit,总共有十二种Unit类型。

2. 常用命令


systemctl中Unit的配置文件

上面说了每个服务都是一个Unit,那每个Unit都会有它的配置文件,这样启动的时候才知道要按照什么方式去启动。Systemd默认从目录/etc/systemd/system/读取配置文件。但是里面存放的大部分文件都是符号链接,指向目录/usr/lib/systemd/system/,真正的配置文件存放在那个目录。

1. 查看Unit的配置文件

可以使用systemctl cat命令来查看服务的配置文件,下面是Mysql的配置文件,很多软件已经支持Systemd程序了,安装的时候会自动配置它的Unit配置文件,例如Mysql和Nginx等等。

2. Unit配置文件的含义

可以看到Unit配置文件有很多标签,不同的标签都代表了不同的意思,这里只列出部分介绍,可以去官网查看Unit配置文件文档介绍,https://www.freedesktop.org/software/systemd/man/systemd.unit.html


自定义服务启动

既然Systemd的作用就是控制服务的启动,那么就可以把自己的服务添加进去,就可以直接使用systemctl命令来控制服务的启动,或者是设置开机自动启动等等。

1. 创建Unit配置文件

/usr/lib/systemd/system目录中创建自己的配置文件,一般都是.service结尾,例如这里创建了一个test-sh.service配置文件,这个Unit是为了启动我们自己的一个shell脚本。

2. 创建脚本

在上面配置文件指定的启动路径/opt/dev/shell/下创建shell脚本,这里只是每秒打印当前时间,并输出到一个文本中。

3. 载入配置文件并启动

使用systemctl daemon-reload命令来载入新添加的配置文件,然后使用systemctl start test-sh.service命令启动,再使用systemctl status test-sh.service命令来查看状态,可以看到已经启动,/opt/dev/shell/test.txt也确实在不停的写入内容,最后使用systemctl stop test-sh.service命令停止服务,可以看到状态也是停止了。

注意的是修改配置文件后一定要使用systemctl daemon-reload命令来载入新添加的配置文件,然后再启动服务。


查看Unit启动日志

Systemd统一管理了所有Unit的启动日志,因此只需要使用journalctl命令就可以查看到服务的日志

 

 

 

 

Systemd 入门教程:命令篇

Systemd 是 Linux 系统工具,用来启动守护进程,已成为大多数发行版的标准配置。

本文介绍它的基本用法,分为上下两篇。今天介绍它的主要命令,下一篇介绍如何用于实战。

一、由来

历史上,Linux 的启动一直采用init进程。

下面的命令用来启动服务。

这种方法有两个缺点。

一是启动时间长。init进程是串行启动,只有前一个进程启动完,才会启动下一个进程。

二是启动脚本复杂。init进程只是执行启动脚本,不管其他事情。脚本需要自己处理各种情况,这往往使得脚本变得很长。

二、Systemd 概述

Systemd 就是为了解决这些问题而诞生的。它的设计目标是,为系统的启动和管理提供一套完整的解决方案。

根据 Linux 惯例,字母d是守护进程(daemon)的缩写。 Systemd 这个名字的含义,就是它要守护整个系统。

使用了 Systemd,就不需要再用init了。Systemd 取代了initd,成为系统的第一个进程(PID 等于 1),其他进程都是它的子进程。

上面的命令查看 Systemd 的版本。

Systemd 的优点是功能强大,使用方便,缺点是体系庞大,非常复杂。事实上,现在还有很多人反对使用 Systemd,理由就是它过于复杂,与操作系统的其他部分强耦合,违反"keep simple, keep stupid"的Unix 哲学

(上图为 Systemd 架构图)

三、系统管理

Systemd 并不是一个命令,而是一组命令,涉及到系统管理的方方面面。

3.1 systemctl

systemctl是 Systemd 的主命令,用于管理系统。

3.2 systemd-analyze

systemd-analyze命令用于查看启动耗时。

3.3 hostnamectl

hostnamectl命令用于查看当前主机的信息。

3.4 localectl

localectl命令用于查看本地化设置。

3.5 timedatectl

timedatectl命令用于查看当前时区设置。

3.6 loginctl

loginctl命令用于查看当前登录的用户。

四、Unit

4.1 含义

Systemd 可以管理所有系统资源。不同的资源统称为 Unit(单位)。

Unit 一共分成12种。

systemctl list-units命令可以查看当前系统的所有 Unit 。

4.2 Unit 的状态

systemctl status命令用于查看系统状态和单个 Unit 的状态。

除了status命令,systemctl还提供了三个查询状态的简单方法,主要供脚本内部的判断语句使用。

4.3 Unit 管理

对于用户来说,最常用的是下面这些命令,用于启动和停止 Unit(主要是 service)。

4.4 依赖关系

Unit 之间存在依赖关系:A 依赖于 B,就意味着 Systemd 在启动 A 的时候,同时会去启动 B。

systemctl list-dependencies命令列出一个 Unit 的所有依赖。

上面命令的输出结果之中,有些依赖是 Target 类型(详见下文),默认不会展开显示。如果要展开 Target,就需要使用--all参数。

五、Unit 的配置文件

5.1 概述

每一个 Unit 都有一个配置文件,告诉 Systemd 怎么启动这个 Unit 。

Systemd 默认从目录/etc/systemd/system/读取配置文件。但是,里面存放的大部分文件都是符号链接,指向目录/usr/lib/systemd/system/,真正的配置文件存放在那个目录。

systemctl enable命令用于在上面两个目录之间,建立符号链接关系。

如果配置文件里面设置了开机启动,systemctl enable命令相当于激活开机启动。

与之对应的,systemctl disable命令用于在两个目录之间,撤销符号链接关系,相当于撤销开机启动。

配置文件的后缀名,就是该 Unit 的种类,比如sshd.socket。如果省略,Systemd 默认后缀名为.service,所以sshd会被理解成sshd.service

5.2 配置文件的状态

systemctl list-unit-files命令用于列出所有配置文件。

这个命令会输出一个列表。

这个列表显示每个配置文件的状态,一共有四种。

注意,从配置文件的状态无法看出,该 Unit 是否正在运行。这必须执行前面提到的systemctl status命令。

一旦修改配置文件,就要让 SystemD 重新加载配置文件,然后重新启动,否则修改不会生效。

5.3 配置文件的格式

配置文件就是普通的文本文件,可以用文本编辑器打开。

systemctl cat命令可以查看配置文件的内容。

从上面的输出可以看到,配置文件分成几个区块。每个区块的第一行,是用方括号表示的区别名,比如[Unit]。注意,配置文件的区块名和字段名,都是大小写敏感的。

每个区块内部是一些等号连接的键值对。

注意,键值对的等号两侧不能有空格。

5.4 配置文件的区块

[Unit]区块通常是配置文件的第一个区块,用来定义 Unit 的元数据,以及配置与其他 Unit 的关系。它的主要字段如下。

[Install]通常是配置文件的最后一个区块,用来定义如何启动,以及是否开机启动。它的主要字段如下。

[Service]区块用来 Service 的配置,只有 Service 类型的 Unit 才有这个区块。它的主要字段如下。

Unit 配置文件的完整字段清单,请参考官方文档

六、Target

启动计算机的时候,需要启动大量的 Unit。如果每一次启动,都要一一写明本次启动需要哪些 Unit,显然非常不方便。Systemd 的解决方案就是 Target。

简单说,Target 就是一个 Unit 组,包含许多相关的 Unit 。启动某个 Target 的时候,Systemd 就会启动里面所有的 Unit。从这个意义上说,Target 这个概念类似于"状态点",启动某个 Target 就好比启动到某种状态。

传统的init启动模式里面,有 RunLevel 的概念,跟 Target 的作用很类似。不同的是,RunLevel 是互斥的,不可能多个 RunLevel 同时启动,但是多个 Target 可以同时启动。

Target 与 传统 RunLevel 的对应关系如下。

它与init进程的主要差别如下。

(1)默认的 RunLevel(在/etc/inittab文件设置)现在被默认的 Target 取代,位置是/etc/systemd/system/default.target,通常符号链接到graphical.target(图形界面)或者multi-user.target(多用户命令行)。

(2)启动脚本的位置,以前是/etc/init.d目录,符号链接到不同的 RunLevel 目录 (比如/etc/rc3.d/etc/rc5.d等),现在则存放在/lib/systemd/system/etc/systemd/system目录。

(3)配置文件的位置,以前init进程的配置文件是/etc/inittab,各种服务的配置文件存放在/etc/sysconfig目录。现在的配置文件主要存放在/lib/systemd目录,在/etc/systemd目录里面的修改可以覆盖原始设置。

七、日志管理

Systemd 统一管理所有 Unit 的启动日志。带来的好处就是,可以只用journalctl一个命令,查看所有日志(内核日志和应用日志)。日志的配置文件是/etc/systemd/journald.conf

journalctl功能强大,用法非常多。

 

 

 

 

 

How To Install MySQL on Ubuntu 20.04

Published on April 24, 2020 · Updated on July 12, 2022

Introduction

MySQL is an open-source database management system, commonly installed as part of the popular LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack. It implements the relational model and uses Structured Query Language (better known as SQL) to manage its data.

This tutorial will go over how to install MySQL version 8.0 on an Ubuntu 20.04 server. By completing it, you will have a working relational database that you can use to build your next website or application.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Installing MySQL

On Ubuntu 20.04, you can install MySQL using the APT package repository. At the time of this writing, the version of MySQL available in the default Ubuntu repository is version 8.0.27.

To install it, update the package index on your server if you’ve not done so recently:

Then install the mysql-server package:

Ensure that the server is running using the systemctl start command:

These commands will install and start MySQL, but will not prompt you to set a password or make any other configuration changes. Because this leaves your installation of MySQL insecure, we will address this next.

Step 2 — Configuring MySQL

For fresh installations of MySQL, you’ll want to run the DBMS’s included security script. This script changes some of the less secure default options for things like remote root logins and sample users.

Warning: As of July 2022, an error will occur when you run the mysql_secure_installation script without some further configuration. The reason is that this script will attempt to set a password for the installation’s root MySQL account but, by default on Ubuntu installations, this account is not configured to connect using a password.

Prior to July 2022, this script would silently fail after attempting to set the root account password and continue on with the rest of the prompts. However, as of this writing the script will return the following error after you enter and confirm a password:

This will lead the script into a recursive loop which you can only get out of by closing your terminal window.

Because the mysql_secure_installation script performs a number of other actions that are useful for keeping your MySQL installation secure, it’s still recommended that you run it before you begin using MySQL to manage your data. To avoid entering this recursive loop, though, you’ll need to first adjust how your root MySQL user authenticates.

First, open up the MySQL prompt:

Then run the following ALTER USER command to change the root user’s authentication method to one that uses a password. The following example changes the authentication method to mysql_native_password:

After making this change, exit the MySQL prompt:

Following that, you can run the mysql_secure_installation script without issue.

Once the security script completes, you can then reopen MySQL and change the root user’s authentication method back to the default, auth_socket. To authenticate as the root MySQL user using a password, run this command:

Then go back to using the default authentication method using this command:

This will mean that you can once again connect to MySQL as your root user using the sudo mysql command.

Run the security script with sudo:

This will take you through a series of prompts where you can make some changes to your MySQL installation’s security options. The first prompt will ask whether you’d like to set up the Validate Password Plugin, which can be used to test the password strength of new MySQL users before deeming them valid.

If you elect to set up the Validate Password Plugin, any MySQL user you create that authenticates with a password will be required to have a password that satisfies the policy you select. The strongest policy level — which you can select by entering 2 — will require passwords to be at least eight characters long and include a mix of uppercase, lowercase, numeric, and special characters:

Regardless of whether you choose to set up the Validate Password Plugin, the next prompt will be to set a password for the MySQL root user. Enter and then confirm a secure password of your choice:

Note that even though you’ve set a password for the root MySQL user, this user is not currently configured to authenticate with a password when connecting to the MySQL shell.

If you used the Validate Password Plugin, you’ll receive feedback on the strength of your new password. Then the script will ask if you want to continue with the password you just entered or if you want to enter a new one. Assuming you’re satisfied with the strength of the password you just entered, enter Y to continue the script:

From there, you can press Y and then ENTER to accept the defaults for all the subsequent questions. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.

Once the script completes, your MySQL installation will be secured. You can now move on to creating a dedicated database user with the MySQL client.

Step 3 — Creating a Dedicated MySQL User and Granting Privileges

Upon installation, MySQL creates a root user account which you can use to manage your database. This user has full privileges over the MySQL server, meaning it has complete control over every database, table, user, and so on. Because of this, it’s best to avoid using this account outside of administrative functions. This step outlines how to use the root MySQL user to create a new user account and grant it privileges.

In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This plugin requires that the name of the operating system user that invokes the MySQL client matches the name of the MySQL user specified in the command, so you must invoke mysql with sudo privileges to gain access to the root MySQL user:

Note: If you installed MySQL with another tutorial and enabled password authentication for root, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating:

Once you have access to the MySQL prompt, you can create a new user with a CREATE USER statement. These follow this general syntax:

After CREATE USER, you specify a username. This is immediately followed by an @ sign and then the hostname from which this user will connect. If you only plan to access this user locally from your Ubuntu server, you can specify localhost. Wrapping both the username and host in single quotes isn’t always necessary, but doing so can help to prevent errors.

You have several options when it comes to choosing your user’s authentication plugin. The auth_socket plugin mentioned previously can be convenient, as it provides strong security without requiring valid users to enter a password to access the database. But it also prevents remote connections, which can complicate things when external programs need to interact with MySQL.

As an alternative, you can leave out the WITH authentication_plugin portion of the syntax entirely to have the user authenticate with MySQL’s default plugin, caching_sha2_password. The MySQL documentation recommends this plugin for users who want to log in with a password due to its strong security features.

Run the following command to create a user that authenticates with caching_sha2_password. Be sure to change sammy to your preferred username and password to a strong password of your choosing:

Note: There is a known issue with some versions of PHP that causes problems with caching_sha2_password. If you plan to use this database with a PHP application — phpMyAdmin, for example — you may want to create a user that will authenticate with the older, though still secure, mysql_native_password plugin instead:

If you aren’t sure, you can always create a user that authenticates with caching_sha2_plugin and then ALTER it later on with this command:

After creating your new user, you can grant them the appropriate privileges. The general syntax for granting user privileges is as follows:

The PRIVILEGE value in this example syntax defines what actions the user is allowed to perform on the specified database and table. You can grant multiple privileges to the same user in one command by separating each with a comma. You can also grant a user privileges globally by entering asterisks (*) in place of the database and table names. In SQL, asterisks are special characters used to represent “all” databases or tables.

To illustrate, the following command grants a user global privileges to CREATE, ALTER, and DROP databases, tables, and users, as well as the power to INSERT, UPDATE, and DELETE data from any table on the server. It also grants the user the ability to query data with SELECT, create foreign keys with the REFERENCES keyword, and perform FLUSH operations with the RELOAD privilege. However, you should only grant users the permissions they need, so feel free to adjust your own user’s privileges as necessary.

You can find the full list of available privileges in the official MySQL documentation.

Run this GRANT statement, replacing sammy with your own MySQL user’s name, to grant these privileges to your user:

Note that this statement also includes WITH GRANT OPTION. This will allow your MySQL user to grant any permissions that it has to other users on the system.

Warning: Some users may want to grant their MySQL user the ALL PRIVILEGES privilege, which will provide them with broad superuser privileges akin to the root user’s privileges, like so:

Such broad privileges should not be granted lightly, as anyone with access to this MySQL user will have complete control over every database on the server.

Following this, it’s good practice to run the FLUSH PRIVILEGES command. This will free up any memory that the server cached as a result of the preceding CREATE USER and GRANT statements:

Then you can exit the MySQL client:

In the future, to log in as your new MySQL user, you’d use a command like the following:

The -p flag will cause the MySQL client to prompt you for your MySQL user’s password in order to authenticate.

Finally, let’s test the MySQL installation.

Step 4 — Testing MySQL

Regardless of how you installed it, MySQL should have started running automatically. To test this, check its status.

You’ll see output similar to the following:

If MySQL isn’t running, you can start it with sudo systemctl start mysql.

For an additional check, you can try connecting to the database using the mysqladmin tool, which is a client that lets you run administrative commands. For example, this command says to connect as a MySQL user named sammy (-u sammy), prompt for a password (-p), and return the version. Be sure to change sammy to the name of your dedicated MySQL user, and enter that user’s password when prompted:

You should see output similar to this:

This means MySQL is up and running.

Conclusion

You now have a basic MySQL setup installed on your server. Here are a few examples of next steps you can take:

 

 

 

 

Linux中的Grep命令使用实例

在本教程中,您将学习如何在Linux中使用非常重要的grep命令。我们将讨论为什么此命令至关重要,以及如何在命令行中将其用于日常任务中。让我们深入了解一些解释和示例。

我们为什么要使用grep?

Grep是Linux用户用来搜索文本字符串的命令行工具。您可以使用它在文件中搜索某个单词或单词的组合,也可以将其他Linux命令的输出通过管道传输到grep,因此grep可以仅显示您需要查看的输出。

让我们看一些非常常见的例子,假设您需要检查目录的内容以查看那里是否存在某个文件,那就是您要使用“ ls”命令进行操作的目的。

但是,为了使检查目录内容的整个过程更快,您可以将ls命令的输出传递给grep命令,让我们在主目录中查找一个名为Documents的文件夹。

现在,让我们尝试再次检查目录,但是这次使用grep专门检查Documents文件夹。

如您在上面的屏幕截图中所见,使用grep命令可以通过快速将搜索到的单词与ls命令产生的其余不必要输出隔离开来,从而节省了我们的时间。

如果“Documents”文件夹不存在,则grep不会返回任何输出。因此,如果grep没有返回任何内容,则意味着它找不到您正在搜索的单词。

查找字符串

如果您需要搜索文本字符串而不是单个单词,则需要将字符串用引号引起来。例如,如果我们需要搜索“My Documents”目录而不是单词“Documents”目录怎么办?

grep的字符串Grep会同时接受单引号和双引号,因此请用其中任意一个将文本字符串包裹起来。

虽然grep通常用于搜索从其他命令行工具管道传输的输出,但是您也可以使用它直接搜索文档。下面是一个我们在文本文档中搜索字符串的示例。

查找多个字符串

您也可以使用grep查找多个单词或字符串。您可以使用-e开关指定多个模式。让我们尝试在文本文档中搜索两个不同的字符串:

注意,我们只需要在包含空格的字符串周围使用引号。

grep egrep fgrep pgrep zgrep之间的区别

不同的grep开关都包含在不同的二进制文件中。在现代Linux系统上,您可以在基本的grep命令中找到这些开关,但是常见的是发行版也支持其他命令。

此开关会将模式解释为扩展的正则表达式。您可以执行许多不同的操作,但是这里有一个示例,说明将正则表达式与grep一起使用的样子。

让我们在文本文档中搜索包含两个连续的“ p”字母的字符串:

此开关会将模式解释为固定字符串的列表,并尝试匹配其中的任何一个。当您需要搜索正则表达式字符时,此功能非常有用。这意味着您不必像常规grep那样转义特殊字符。

pgrep是用于搜索系统上正在运行的进程的名称并返回其相应进程ID的命令。例如,您可以使用它来查找SSH守护进程的进程ID:

这在功能上类似于仅将“ ps”命令的输出传递给grep。

您可以使用此信息来终止正在运行的进程或对系统上运行的服务进行故障排除。

zgrep用于搜索压缩文件中的模式。它使您可以搜索压缩存档中的文件,而不必先解压该存档,基本上可以节省一两个步骤。

zgrep也可用于tar文件,但似乎只能告诉您它是否能够找到匹配项。

我们之所以提及这一点,是因为用gzip压缩的文件通常是tar存档。

find和grep之间的区别

对于刚从Linux命令行开始的用户,重要的是要记住find和grep是两个具有两个截然不同功能的命令,尽管它们都用于“查找”用户指定的内容。

如本教程第一个示例所示,使用grep搜索ls命令的输出时,使用grep可以很方便。

但是,如果您需要递归搜索文件名(如果使用通配符(星号),则需要搜索文件名的一部分),那么使用'find'命令会更方便。

上面的输出显示find命令能够成功找到我们搜索的文件。

递归搜索

可以将-r开关与grep一起使用,以递归方式搜索目录及其子目录中的所有文件,以查找指定的模式。

如果您未指定目录,则grep只会搜索您当前的工作目录。在下面的屏幕截图中,grep找到了两个与我们的模式匹配的文件,并返回了它们的文件名和它们所在的目录。

填充空间或制表符

正如我们在前面关于如何搜索字符串的解释中提到的那样,如果文本包含空格,则可以将文本包装在引号中。选项卡也可以使用相同的方法,但是稍后我们将说明如何在grep命令中添加选项卡。

在引号内放置一个空格或多个空格,以使grep搜索该。

您可以使用grep搜索标签的方法有几种,但是大多数方法都是实验性的,或者在不同的发行版中可能不一致。

最简单的方法是仅搜索制表符本身,您可以通过在键盘上按ctrl + v,然后按Tab来产生该字符。

通常,在终端窗口中按Tab会告诉终端您要自动完成命令,但是事先按ctrl + v组合键将导致按常规方式在文本编辑器中写出Tab字符。

熟悉Linux中的配置文件时,知道此小技巧会特别有用,因为选项卡通常用于将命令与其值分开。

使用正则表达式

通过使用正则表达式进一步扩展了Grep的功能,从而使您的搜索更加灵活。存在几种,在下面的示例中,我们将介绍一些最普通的:

[]括号用于匹配一组字符中的任何一个。

此命令将返回任何显示“ Class 1”,“ Class2”或“ Class 3”的任何行。

带连字符的[-]括号可用于指定数字或字母字符范围。

我们得到与以前相同的输出,但是该命令的键入要容易得多,尤其是当我们使用更大范围的数字或字母时。

^脱字符号用于搜索只出现在行的开头的模式。

带方括号的脱字符号用于从搜索模式中排除字符。

$ dollar符号用于搜索只出现在行的末尾的模式。

.点用于匹配任何一个字符,因此它是通配符,但仅适用于单个字符。

Grep gz文件,无需解压

如前所述,zgrep命令可用于搜索压缩文件,而无需先将其解压。

您还可以使用zcat命令显示gz文件的内容,然后将输出到grep,以隔离包含搜索字符串的行。

压缩文件中的Grep电子邮件地址

我们可以使用一个奇特的正则表达式从zip文件中提取所有电子邮件地址。

-o标志仅提取电子邮件地址,而不显示包含电子邮件地址的整行。这样可以产生更清晰的输出。

与Linux中的大多数事情一样,有多种方法可以做到这一点。您还可以使用egrep和一组不同的表达式。但是上面的示例工作得很好,并且是提取电子邮件地址并忽略其他所有内容的非常简单的方法。

Grep IP地址

IP地址的查询可能会变得有些复杂,因为我们不仅能让grep查找由点号分隔的4个数字,可以,但是该命令也有可能返回无效的IP地址。

以下命令将仅查找和隔离有效的IPv4地址:

我们在Ubuntu服务器上使用它只是为了查看最新的SSH尝试来自何处。

为避免重复信息和使屏幕泛滥,您可能希望像上面的屏幕截图一样,将grep命令传递给“ uniq”和“ more”。

Grep or 条件

您可以通过几种不同的方式对grep使用or条件,但是我们将向您展示一种需要最少击键且最容易记住的方法:

或者,从技术上讲,使用egrep的击键次数甚至更少:

grep或条件忽略大小写默认情况下,grep区分大小写,这意味着您必须精确搜索大写的字符串。您可以通过告诉grep忽略-i开关的情况来避免这种情况。

忽略大小写

默认情况下,grep区分大小写,这意味着您必须精确搜索大写的字符串。通过使用-i开关告诉grep忽略大小写,可以避免这种情况。

搜索时区分大小写

如果我们要搜索一个字符串,其中第一个可以是大写或小写,但字符串的其余部分应该是小写怎么办?在这种情况下,无法使用-i switch 忽略大小写,所以一种简单的方法是使用方括号。

该命令告诉grep除首字母外,其他字母都区分大小写。

Grep精确匹配

在上面的示例中,每当我们在文档中搜索字符串“ apple”时,grep也会在输出中返回“ pineapple”。为了避免这种情况,并严格搜索“ apple”,可以使用以下命令:

您还可以使用-w开关,它将告诉grep该字符串必须与整行匹配。显然,这只适用于您不希望该行的其余部分完全包含任何文本的情况下有效。

排除模式

要查看文件的内容,但要从输出中排除模式,可以使用-v开关。

如您在屏幕截图中所见,当我们使用-v开关运行相同的命令时,不再显示排除的字符串

Grep和替换

传递给sed的grep命令可用于替换文件中字符串的所有实例。此命令将在相对于当前工作目录的所有文件中将“ string1”替换为“ string2”:

带行号的Grep

要显示搜索字符串所在的行数,请使用-n开关。

显示之前和之后的行

如果需要更多grep输出上下文,可以使用-c开关在指定的搜索字符串前后显示一行:

指定您希望显示的行数–在此示例中,我们仅执行了1行。

对结果进行排序

将grep的输出传递给sort命令,以按某种顺序对结果进行排序。默认为字母顺序。

Copyright © 2024 WWW.BBTOO.CN All Rights Reserved    蜀ICP备19037579号-1