id
int64
2.05k
16.6k
title
stringlengths
5
75
fromurl
stringlengths
19
185
date
timestamp[s]
tags
sequencelengths
0
11
permalink
stringlengths
20
37
content
stringlengths
342
82.2k
fromurl_status
int64
200
526
status_msg
stringclasses
339 values
from_content
stringlengths
0
229k
11,614
如何在 Linux 上安装 Java
https://opensource.com/article/19/11/install-java-linux
2019-11-26T06:53:40
[ "Java" ]
https://linux.cn/article-11614-1.html
> > 在桌面上拥抱 Java 应用程序,然后在所有桌面上运行它们。 > > > ![](/data/attachment/album/201911/26/065307hk22caubakkos0u0.jpg) 无论你运行的是哪种操作系统,通常都有几种安装应用程序的方法。有时你可能会在应用程序商店中找到一个应用程序,或者使用 Fedora 上的 DNF 或 Mac 上的 Brew 这样的软件包管理器进行安装,而有时你可能会从网站上下载可执行文件或安装程序。因为 Java 是这么多流行的应用程序的后端,所以最好了解安装它的不同方法。好消息是你有很多选择,本文涵盖了所有这些内容。 坏消息是 Java *太大*,我说的不仅仅是文件大小。Java 是一种开放源代码语言和规范,这意味着从理论上讲,任何人都可以创建它的实现版本。这意味着,在安装任何东西之前,必须确定要安装的 Java 发行版。 ### 我需要 JVM 还是 JRE 或者 JDK? Java 大致分为两个下载类别。<ruby> Java 虚拟机 <rt> Java Virtual Machine </rt></ruby>(JVM)是运行时组件;它是使 Java 应用程序能够在计算机上启动和运行的“引擎”。它包含在 <ruby> Java 运行时环境 <rt> Java Runtime Environment </rt></ruby>(JRE)中。 <ruby> Java 开发工具包 <rt> Java Development Kit </rt></ruby>(JDK)是一个开发工具包:你可以将其视为一个车库,修理工可以坐在那里进行调整、修理和改进。JDK 包含 Java 运行时环境(JRE)。 以下载来说,这意味着: * 如果你是希望运行 Java 应用程序的用户,则只需 JRE(包括了 JVM)。 * 如果你是希望使用 Java 进行编程的开发人员,则需要 JDK(包括 JRE 库,而 JRE 库又包括 JVM)。 ### OpenJDK、IcedTea 和 OracleJDK 有什么不同? 当<ruby> 太阳微系统 <rt> Sun Microsystems </rt></ruby>被 Oracle 收购时,Java 是该交易的主要部分。幸运的是,Java 是一种开源技术,因此,如果你对 Oracle 维护该项目的方式不满意,则可以选择其他方法。Oracle 将专有组件与 Java 下载捆绑在一起,而 OpenJDK 项目是完全开源的。 IcedTea 项目本质上是 OpenJDK,但其目标是使用户在使用完全自由开源的工具时更容易构建和部署 OpenJDK。 (LCTT 译注:阿里巴巴也有一个它自己维护的 Open JDK 发行版“<ruby> 龙井 <rt> Dragonwell </rt></ruby>”。以下引自其官网:“Alibaba Dragonwell 是一款免费的,生产就绪型 Open JDK 发行版,提供长期支持,包括性能增强和安全修复。……Alibaba Dragonwell 作为 Java 应用的基石,支撑了阿里经济体内所有的 Java 业务。Alibaba Dragonwell 完全兼容 Java SE 标准,……”) ### 我应该安装哪个 Java? 如果你对这些选择感到不知所措,那么简单的答案就是你应该安装的 Java 实现应该是最容易安装的那个。当应用程序告诉你需要 Java 12,但你的存储库中只有 Java 8 时,可以安装可以从可靠来源中找到的 Java 12 的任何实现。在 Linux 上,你可以一次安装几个不同版本的 Java,它们不会互相干扰。 如果你是需要选择使用哪个版本的开发人员,则应考虑所需的组件。如果选择 Oracle 的版本,请注意,软件包中包含专有的插件和字体,可能会[影响你分发你的应用程序](https://www.oracle.com/technetwork/java/javase/overview/oracle-jdk-faqs.html)。在 IcedTea 或 OpenJDK 上进行开发是最安全的。 ### 从存储库安装 OpenJDK? 现在,你已经知道要选择什么了,你可以使用软件包管理器搜索 OpenJDK 或 IcedTea,然后安装所需的版本。有些发行版使用关键字 `latest` 来指示最新版本,这通常是你要运行的应用程序所需要的。根据你使用的软件包管理器,你甚至可以考虑使用 `grep` 过滤搜索结果以仅包括最新版本。例如,在 Fedora 上: ``` $ sudo dnf search openjdk | grep latest | cut -f1 -d':' java-latest-openjdk-demo.x86_64 java-openjdk.i686 java-openjdk.x86_64 java-latest-openjdk-jmods.x86_64 java-latest-openjdk-src.x86_64 java-latest-openjdk.x86_64 [...] ``` 只有当你尝试运行的应用程序坚持要求你使用 Java 的旧版本时,你才应该看看 `latest` 之前的版本。 在 Fedora 或类似系统上安装 Java: ``` $ sudo dnf install java-latest-openjdk ``` 如果你的发行版不使用 `latest` 标签,则可以使用其他关键字,例如 `default`。以下是在 Debian 上搜索 OpenJDK 的信息: ``` $ sudo apt search openjdk | less default-jdk Standard Java development kit default-jre Standard Java runtime openjdk-11-jdk OpenJDK development kit (JDK) [...] ``` 在这种情况下,`default-jre` 软件包适合用户,而 `default-jdk` 则适合开发人员。 例如,要在 Debian 上安装 JRE: ``` $ sudo apt install default-jre ``` 现在已安装好 Java。 你的存储库中可能有*许多*与 Java 相关的软件包。要搜索 OpenJDK,如果你是用户,则查找最新的 JRE 或 JVM,如果你是开发人员,则查找最新的 JDK。 ### 从互联网上安装 Java 如果在存储库中找不到 JRE 或 JDK,或者找不到满足你需求的 JRE 或 JDK,则可以从互联网上下载开源的 Java 软件包。你可以在 [openjdk.java.net](http://openjdk.java.net) 中找到需要手动安装的 tar 形式的 OpenJDK 下载文件,或者可以从 Azul 下载 tar 形式的 [Zulu 社区版](https://www.azul.com/downloads/zulu-community)或其可安装的 RPM 或 DEB 软件包。 #### 从 TAR 文件安装 Java 如果从 Java.net 或 Azul 下载 TAR 文件,则必须手动安装。这通常称为“本地”安装,因为你没有将 Java 安装到“全局”位置。你可以在 `PATH` 中选择一个合适的位置。 如果你不知道 `PATH` 中包含什么,请查看一下以找出: ``` $ echo $PATH /usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/home/seth/bin ``` 在此示例 `PATH` 中,位置 `/usr/local/bin` 和 `/home/seth/bin` 是不错的选择。如果你是计算机上的唯一用户,那么你自己的家目录就很有意义。如果你的计算机上有很多用户,则最好选择一个通用位置,例如 `/usr/local` 或 `/opt`。 如果你无权访问需要 `sudo` 权限的 `/usr/local` 之类的系统级目录,则可以在你自己的家目录中创建一个本地 `bin`(意思是 “<ruby> 二进制 <rt> binary </rt></ruby>”,而不是“<ruby> 垃圾箱 <rt> waste bin </rt></ruby>”)或 `Applications` 文件夹: ``` $ mkdir ~/bin ``` 如果它不在你的 `PATH` 中,请将其添加到其中: ``` $ echo PATH=$PATH:$HOME/bin &gt;&gt; ~/.bashrc $ source ~/.bashrc ``` 最后,将压缩包解压缩到你选择的目录中。 ``` $ tar --extract --file openjdk*linux-x64_bin.tar.gz --directory=$HOME/bin ``` Java 现在安装好了。 #### 从 RPM 或 DEB 安装 Java 如果从 Azul.com 下载 RPM 或 DEB 文件,则可以使用软件包管理器进行安装。 对于 Fedora、CentOS、RHEL 等,请下载 RPM 并使用 DNF 进行安装: ``` $ sudo dnf install zulu*linux.x86_64.rpm ``` 对于 Debian、Ubuntu、Pop\_OS 和类似发行版,请下载 DEB 软件包并使用 Apt 安装它: ``` $ sudo dpkg -i zulu*linux_amd64.deb ``` Java 现在安装好了。 #### 用 alternatives 安装你的 Java 版本 一些应用程序是为特定版本的 Java 开发的,不能与其他任何版本一起使用。这种情况很少见,但确实会发生,在 Linux 上,你可以使用本地安装方法(请参阅上面“从 TAR 文件安装 Java”一节)或使用 `alternatives` 应用程序来解决此冲突。 `alternatives` 命令会查找 Linux 系统上安装的应用程序,并让你选择要使用的版本。有些发行版,例如 Slackware,不提供 `alternatives` 命令,因此你必须使用本地安装方法。在 Fedora、CentOS 和类似的发行版上,该命令是 `alternatives`。在 Debian、Ubuntu 和类似的系统上,该命令是 `update-alternatives`。 要获取当前已安装在 Fedora 系统上的应用程序的可用版本列表: ``` $ alternatives --list ``` 在 Debian 上,你必须指定可供替代的应用程序: ``` $ update-alternatives --list java ``` 在 Fedora 上选择要使系统将哪个版本作为默认版本: ``` $ sudo alternatives --config java ``` 在 Debian 上: ``` $ sudo updates-alternatives --config java ``` 你可以根据需要运行的应用程序,根据需要更改默认的 Java 版本。 ### 运行 Java 应用 Java 应用程序通常以 JAR 文件的形式分发。根据你安装 Java 的方式,你的系统可能已经为运行 Java 应用程序配置好了,这使你只需双击应用程序图标(或从应用程序菜单中选择它)即可运行。如果必须执行未与系统其余部分集成的本地 Java 安装,则可以直接从终端启动 Java 应用程序: ``` $ java -jar ~/bin/example.jar & ``` ### Java 是个好东西 Java 是少数将跨平台开发放在首位的编程环境之一。没有什么比问一个应用程序是否能在你的平台上运行然后发现该应用程序是用 Java 编写要让人感到松一口气的了。它是如此简单,无论你是开发人员还是用户,你都可以摆脱任何平台上的焦虑。在桌面上拥抱 Java 应用程序,然后在*所有*桌面上运行它们吧。 --- via: <https://opensource.com/article/19/11/install-java-linux> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
No matter what operating system you're running, there are usually several ways to install an application. Sometimes you might find an application in an app store, or you might install it with a package manager like DNF on Fedora or Brew on Mac, and other times, you might download an executable or an installer from a website. Because Java is such a popular backend for so many applications, it's good to understand the different ways you can install it. The good news is that you have many options, and this article covers them all. The bad news is that Java is *big*, not so much in size as in scope. Java is an open source language and specification, meaning that anyone can, in theory, create an implementation of it. That means, before you can install anything, you have to decide which Java you want to install. ## Do I need a JVM or a JRE or a JDK? Java is broadly split into two downloadable categories. The **Java Virtual Machine** (JVM) is a runtime component; it's the "engine" that enables Java applications to launch and run on your computer. It's included in the Java Runtime Environment (JRE). The **Java Development Kit** (JDK) is a development toolkit: you can think of it as a garage where tinkerers sit around making adjustments, repairs, and improvements. The JDK includes the Java Runtime Environment (JRE). In terms of downloads, this translates to: - If you're a user looking to run a Java application, you only need the JRE (which includes a JVM). - If you're a developer looking to program in Java, you need the JDK (which includes JRE libraries, which in turn includes a JVM). ## What's the difference between OpenJDK, IcedTea, and OracleJDK? When Sun Microsystems was bought by Oracle, Java was a major part of the sale. Luckily, Java is an open source technology, so if you're not happy with the way Oracle maintains the project, you have other options. Oracle bundles proprietary components with its Java downloads, while the OpenJDK project is fully open source. The IcedTea project is essentially OpenJDK, but its goal is to make it easier for users to build and deploy OpenJDK when using fully free and open source tools. ## Which Java should I install? If you feel overwhelmed by the choices, then the easy answer of which Java implementation you should install is whichever is easiest for you to install. When an application tells you that you need Java 12, but your repository only has Java 8, it's fine to install whatever implementation of Java 12 you can find from a reliable source. On Linux, you can have several different versions of Java installed all at once, and they won't interfere with one another. If you're a developer who needs to make the choice, then you should consider what components you need. If you opt for Oracle's version, be aware that there are proprietary plugins and fonts in the package, which could [interfere with distributing your application](https://www.oracle.com/technetwork/java/javase/overview/oracle-jdk-faqs.html). It's safest to develop on IcedTea or OpenJDK. ## Install OpenJDK from a repository Now that you know your choices, you can search for OpenJDK or IcedTea with your package manager and install the version you need. Some distributions use the keyword **latest** to indicate the most recent version, which is usually what you need to run whatever application you're trying to run. Depending on what package manager you use, you might even consider using **grep** to filter the search results to include only the latest versions. For example, on Fedora: ``` $ sudo dnf search openjdk | \ grep latest | cut -f1 -d':' java-latest-openjdk-demo.x86_64 java-openjdk.i686 java-openjdk.x86_64 java-latest-openjdk-jmods.x86_64 java-latest-openjdk-src.x86_64 java-latest-openjdk.x86_64 [...] ``` Only if the application you're trying to run insists that you need a legacy version of Java should you look past the **latest** release. Install Java on Fedora or similar with: `$ sudo dnf install java-latest-openjdk` If your distribution doesn't use the **latest** tag, it may use another keyword, such as **default**. Here's a search for OpenJDK on Debian: ``` $ sudo apt search openjdk | less default-jdk Standard Java development kit default-jre Standard Java runtime openjdk-11-jdk OpenJDK development kit (JDK) [...] ``` In this case, the **default-jre** package is appropriate for users, and the **default-jdk** is suitable for developers. For example, to install the JRE on Debian: `$ sudo apt install default-jre` Java is now installed. There are probably many *many* Java-related packages in your repository. Search on OpenJDK and look for either the most recent JRE or JVM if you're a user and for the most recent JDK if you're a developer. ## Install Java from the internet If you can't find a JRE or JDK in your repository, or the ones you find don't fit your needs, you can download open source Java packages from the internet. You can find downloads of OpenJDK at [adoptopenjdk.net](http://adoptopenjdk.net) in the form of a tarball requiring manual installation, or you can download the [Zulu Community](https://www.azul.com/downloads/zulu-community) edition from Azul in the form of a tarball or installable RPM or DEB packages. ### Installing Java from a TAR file If you download a TAR file from either Java.net or Azul, you must install it manually. This is often called a "local" install because you're not installing Java to a "global" location. Instead, you choose a convenient place in your PATH. If you don't know what's in your PATH, take a look to find out: ``` $ echo $PATH /usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/home/seth/bin ``` In this example PATH, the locations **/usr/local/bin** and **/home/seth/bin** are good options. If you're the only user on your computer, then your own home directory makes sense. If there are many users on your computer, then a common location, such as **/usr/local** or **/opt**, is the best choice. If you don't have access to system-level directories like **/usr/local**, which require **sudo** permissions, then create a local **bin** (for "binary," not a waste bin) or **Applications** folder in your own home folder: `$ mkdir ~/bin` Add this to your PATH, if it's not already there: ``` $ echo PATH=$PATH:$HOME/bin >> ~/.bashrc $ source ~/.bashrc ``` Finally, unarchive the tarball into the directory you've chosen. ``` $ tar --extract --file openjdk*linux-x64_bin.tar.gz \ --directory=$HOME/bin ``` Java is now installed. ### Installing Java from an RPM or DEB If you download an RPM or DEB file from Azul.com, then you can use your package manager to install it. For Fedora, CentOS, RHEL, and similar, download the RPM and install it using DNF: `$ sudo dnf install zulu*linux.x86_64.rpm` For Debian, Ubuntu, Pop_OS, and similar distributions, download the DEB package and install it using Apt: `$ sudo dpkg -i zulu*linux_amd64.deb` Java is now installed. ### Setting your Java version with alternatives Some applications are developed for a specific version of Java and don't work with any other version. This is rare, but it does happen, and on Linux, you can use either the local install method (see [Installing Java from a TAR file](#installing-java-from-a-tar-file)) or the **alternatives** application to deal with this conflict. The **alternatives** command looks at applications installed on your Linux system and lets you choose which version to use. Some distributions, such as Slackware, don't provide an **alternatives** command, so you must use the local install method instead. On Fedora, CentOS, and similar distributions, the command is **alternatives**. On Debian, Ubuntu, and similar, the command is **update-alternatives**. To get a list of available versions of an application currently installed on your Fedora system: `$ alternatives --list` On Debian, you must specify the application you want alternatives for: `$ update-alternatives --list java` To choose which version you want to make the system default on Fedora: `$ sudo alternatives --config java` On Debian: `$ sudo updates-alternatives --config java` You can change the default Java version as needed based on the application you want to run. ## Running a Java application Java applications are typically distributed as JAR files. Depending on how you installed Java, your system may already be configured to run a Java application, which allows you to just double-click the application icon (or select it from an application menu) to run it. If you had to do a local Java install that isn't integrated with the rest of your system, you can launch Java applications directly from a terminal: `$ java -jar ~/bin/example.jar &` ## Java is a good thing Java is one of the few programming environments that places cross-platform development first. There's nothing quite as liberating as asking whether an application runs on your platform, and then discovering that the application was written in Java. As simply as that, you're freed from any platform anxiety you may have had, whether you're a developer or a user. Embrace Java applications on your desktop, and run them on *all* of your desktops. ## Comments are closed.
11,616
谷歌为安卓添加主线 Linux 内核支持
https://itsfoss.com/mainline-linux-kernel-android/
2019-11-27T08:57:01
[ "Android", "Linux" ]
https://linux.cn/article-11616-1.html
当前的安卓生态系统被数百种不同版本的安卓所污染,每种版本都运行着 Linux 内核的不同变体。每个版本均针对不同的手机和不同的配置而设计。谷歌试图通过将主线 Linux 内核添加到安卓来解决该问题。 ### 当前在安卓中是如何处理 Linux 内核的 在到达你的手机之前,你手机上的 Linux 内核经历了[三个主要步骤](https://arstechnica.com/gadgets/2019/11/google-outlines-plans-for-mainline-linux-kernel-support-in-android/)。 首先,谷歌采用了 Linux 内核的 LTS(长期支持)版本,并添加了所有的安卓专用代码。这将成为“安卓通用内核”。 然后,谷歌将此代码发送给创建可运行在手机的片上系统(SoC)的公司。这通常是高通公司。 SoC 制造商添加了支持 CPU 和其他芯片的代码后,便会将该内核传递给实际的设备制造商,例如三星和摩托罗拉。然后,设备制造商添加代码以支持手机的其余部分,例如显示屏和摄像头。 每个步骤都需要一段时间才能完成,并且会导致该内核无法与其他任何设备一起使用。这也意味着内核会非常旧,通常是大约两年前的内核。例如,上个月交付的谷歌 Pixel 4 带有来自 2017 年 11 月的内核,而且它将永远不会得到更新。 谷歌承诺会为较旧的设备创建安全补丁,这意味着他们会一直盯着大量的旧代码。 ### 将来 ![](/data/attachment/album/201911/27/085706ec16q899q5uzflj9.png) 去年,谷歌宣布[计划](https://lwn.net/Articles/771974/)解决此问题。今年,他们在 2019 Linux Plumbers Conference 上展示了他们取得的进展。 > > “我们知道运行安卓需要什么,但不一定是在任何给定的硬件上。因此,我们的目标是从根本上找出所有这些,然后将其交给上游,并尝试尽可能接近主线。” > > > Sandeep Patil,[安卓内核团队负责人](https://arstechnica.com/gadgets/2019/11/google-outlines-plans-for-mainline-linux-kernel-support-in-android/) > > > 他们确实炫耀了运行带有合适的 Linux 内核的小米 Poco F1。但是,有些东西[似乎没有工作](https://www.androidpolice.com/2019/11/19/google-wants-android-to-use-regular-linux-kernel-potentially-improving-updates-and-security/),例如电池电量百分比一直留在 0%。 那么,谷歌计划如何使其工作呢?从他们的 [Treble 项目](https://www.computerworld.com/article/3306443/what-is-project-treble-android-upgrade-fix-explained.html)计划中摘录。在 Treble 项目之前,与设备和安卓本身交互的底层代码是一大堆代码。Treble 项目将两者分开,并使它们模块化,以便可以更快地交付安卓更新,并且在更新时,这些低级代码可以保持不变。 谷歌希望为内核带来同样的模块化。他们的[计划](https://arstechnica.com/gadgets/2019/11/google-outlines-plans-for-mainline-linux-kernel-support-in-android/)“涉及稳定 Linux 的内核 ABI,并为 Linux 内核和硬件供应商提供稳定的接口来进行写入。谷歌希望将 Linux 内核与其硬件支持脱钩。” 因此,这意味着谷歌将交付一个内核,而硬件驱动程序将作为内核模块加载。目前,这只是一个草案。仍然有很多技术问题有待解决。因此,这不会很快有结果。 ### 来自开源的反对意见 开源社区不会对将专有代码放入内核的想法感到满意。[Linux 内核准则](https://www.kernel.org/doc/Documentation/process/stable-api-nonsense.rst)指出,驱动程序必须具有 GPL 许可证才能包含在内核中。他们还指出,如果驱动程序的更改导致错误,应由导致该错误的人来解决。从长远来看,这意味着设备制造商的工作量将减少。 ### 关于将主线内核包含到安卓中的最终想法 到目前为止,这只是一个草案。谷歌有很大的可能会开始进行该项目,除非他们意识到这将需要多少工作后才会放弃。看看谷歌[已经放弃](https://killedbygoogle.com/)了多少个项目! [Android Police](https://www.androidpolice.com/2019/11/19/google-wants-android-to-use-regular-linux-kernel-potentially-improving-updates-and-security/) 指出谷歌正在开发其 [Fuchsia 操作系统](https://itsfoss.com/fuchsia-os-what-you-need-to-know/),这似乎是为了有一天取代谷歌。 那么,问题是谷歌会尝试完成那些艰巨的任务,使安卓以主线 Linux 内核运行,还是完成他们统一的安卓替代产品的工作?只有时间可以回答。 你对此话题有何看法?请在下面的评论中告诉我们。 --- via: <https://itsfoss.com/mainline-linux-kernel-android/> 作者:[John Paul](https://itsfoss.com/author/john/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The current Android ecosystem is polluted with hundreds of different versions of Android, each running a different variant of the Linux kernel. Each version is designed for a different phone and it’s different configurations. Google has been working to fix the problem by adding the mainline Linux kernel to Android. ## How the Linux kernel is currently handled in Android Before it reaches you, the Linux kernel on your cellphone goes through [three major steps](https://arstechnica.com/gadgets/2019/11/google-outlines-plans-for-mainline-linux-kernel-support-in-android/). First, Google takes the LTS (Long Term Support) version of the Linux kernel and adds all of the Android-specific code. This becomes the “Android Common kernel”. Google then sends this code to the company that creates the System on a Chip (SoC) that runs your phone. This is usually Qualcomm. Once the SoC maker finishes add code to support the CPU and other chips, the kernel is then passed on to the actual device maker, such as Samsung or Motorola. The device maker then adds code to support the rest of the phone, such as the display and camera. Each of these steps takes a while to complete and results in a kernel that won’t work with any other device. It also means that the kernel is very old, usually about two years old. For example, the Google Pixel 4, which shipped last month, has a kernel from November 2017, which will never get updated. Google has pledged to create security patches for older devices, which means they’re stuck keeping an eye on a huge hodge-podge of old code. ## The Future ![Mainline Linux Kernel Android](https://itsfoss.com/content/images/wordpress/2019/11/mainline_linux_kernel_android.png) Last year, Google announced [plans](https://lwn.net/Articles/771974/) to fix this mess. This year they revealed what progress they made at the 2019 Linux Plumbers Conference. “We know what it takes to run Android but not necessarily on any given hardware. So our goal is to basically find all of that out, then upstream it and try to be as close to mainline as possible.” Sandeep Patil,[Android Kernel Team Lead] They did show off a Xiaomi Poco F1 running Android with a proper Linux kernel. However, it some things did not [appear to be working](https://www.androidpolice.com/2019/11/19/google-wants-android-to-use-regular-linux-kernel-potentially-improving-updates-and-security/), such as the battery percentage which was stuck at 0%. So, how does Google plan to make this work? By taking a page from their [Project Treble](https://www.computerworld.com/article/3306443/what-is-project-treble-android-upgrade-fix-explained.html) playbook. Before Project Treble, the low-level code that interacted with the device and Android itself was one big mess of code. Project Treble separated the two and made them modular so that Android updates could be shipped quicker and the low-level code could remain unchanged between updates. Google wants to bring the same modularity to the kernel. Their [plan](https://arstechnica.com/gadgets/2019/11/google-outlines-plans-for-mainline-linux-kernel-support-in-android/) “involves stabilizing Linux’s in-kernel ABI and having a stable interface for the Linux kernel and hardware vendors to write to. Google wants to decouple the Linux kernel from its hardware support.” So this means that Google would ship a kernel and hardware drivers would be loaded as kernel modules. Currently, this is just a proposal. There are still quite a few technical problems that have to be solved. so, this won’t happen any time soon. ## Opposition from Open Source The Open Source community will not be happy with the idea of putting proprietary code in the kernel. The [Linux kernel guidelines](https://www.kernel.org/doc/Documentation/process/stable-api-nonsense.rst) state that drivers have to have a GPL license to be included in the kernel. They also point out that if a change in the driver causes an error, it will be resolved by the person who created the error. This means less work for device makers in the long run. ## Final Thoughts on including mainline kernel to Andorid So far, this is just a proposal. There is a good chance that Google will start working on the project only to abandon it once they realize how much work this will take. Just take a look at how many projects Google has [already abandoned](https://killedbygoogle.com/). [Android Police](https://www.androidpolice.com/2019/11/19/google-wants-android-to-use-regular-linux-kernel-potentially-improving-updates-and-security/) made a good point by mentioned that Google is working on its [Fuchsia operating system](https://itsfoss.com/fuchsia-os-what-you-need-to-know/), which seems to have the goal of replacing Android one day. So, the question is which monumental task will Google try to complete, getting Android running with a mainline Linux kernel or complete work on their unified Android replacement? Only time can answer that. What are your thoughts on this topic? Please let us know in the comments below. If you found this article interesting, please take a minute to share it on social media, Hacker News or [Reddit](http://reddit.com/r/linuxusersgroup).
11,617
bauh:在一个界面中管理 Snap、Flatpak 和 AppImage
https://itsfoss.com/bauh-package-manager/
2019-11-27T09:30:00
[ "软件包" ]
https://linux.cn/article-11617-1.html
![](/data/attachment/album/201911/27/092926pzzdtytda80yaany.jpg) [Snap](https://snapcraft.io/)、[Flatpak](https://flatpak.org/) 和 [AppImage](https://appimage.org/) 等通用软件包的最大问题之一就是管理它们。大多数内置的软件包管理器都不能全部支持这些新格式。 幸运的是,我偶然发现了一个支持这几种通用包格式的应用程序。 ### bauh:多包装需求的管理器 [bauh](https://github.com/vinifmor/bauh)(LCTT:我给该软件建议一个中文名:“包豪”)最初名为 fpakman,旨在处理 Flatpak、Snap、[AppImage](https://itsfoss.com/use-appimage-linux/) 和 [AUR](https://itsfoss.com/best-aur-helpers/) 软件包。创建者 [vinifmor](https://github.com/vinifmor) 在 2019 年 6 月启动了该项目,[意图](https://forum.manjaro.org/t/bauh-formerly-known-as-fpakman-a-gui-for-flatpak-and-snap-management/96180)“为 Manjaro 用户提供管理 Flatpak 的图形界面”。此后,他扩展了该应用程序,以添加对基于 Debian 的系统的支持。 ![Bauh About](/data/attachment/album/201911/27/093003z3kzkpz5hvre5uze.jpg) 首次打开 bauh 时,它将扫描已安装的应用程序并检查更新。如果有任何需要更新的内容,它们将列在前面并居中。更新所有软件包后,你将看到已安装的软件包列表。你可以取消选择不需要更新的软件包,以防止其被更新。你也可以选择安装该应用程序的早期版本。 ![With Bauh you can manage various types of packages from one application](/data/attachment/album/201911/27/093005qbd4wi54djbuuf5k.jpg) 你也可以搜索应用程序。bauh 提供了有关已安装和已搜索软件包的详细信息。如果你对一种(或多种)软件包类型不感兴趣,则可以在设置中取消选择它们。 ![Bauh Package Info](/data/attachment/album/201911/27/093007sz87nqm8dwnwt1qq.jpg) ![Bauh Updating](/data/attachment/album/201911/27/093008ui7xzzzfaa3yai33.jpg) ![Bauh Search](/data/attachment/album/201911/27/093011mgbebkr9ooyrbmbb.png) ### 在你的 Linux 发行版上安装 bauh 让我们看看如何安装 bauh。 #### 基于 Arch 的发行版 如果你安装的是最近的 [Manjaro](https://manjaro.org/),则应该一切已经就绪。bauh 默认情况下已安装。如果你安装的是较早版本的 Manjaro(如我一样)或其他基于 Arch 的发行版,则可以在终端中输入以下内容从 [AUR](https://aur.archlinux.org/packages/bauh) 中进行安装: ``` sudo pacman -S bauh ``` #### 基于 Debian/Ubuntu 的发行版 如果你拥有基于 Debian 或 Ubuntu 的 Linux 发行版,则可以使用 `pip` 安装 bauh。首先,请确保[在 Ubuntu 上安装了 pip](https://itsfoss.com/install-pip-ubuntu/)。 ``` sudo apt install python3-pip ``` 然后使用它来安装 bauh: ``` pip3 install bauh ``` 但是,该软件的创建者建议[手动](https://github.com/vinifmor/bauh#manual-installation)安装它,以避免弄乱系统的库。 要手动安装 bauh,你必须先下载其[最新版本](https://github.com/vinifmor/bauh/releases)。下载后,可以[使用图形工具](https://itsfoss.com/unzip-linux/)或 [unzip 命令](https://linuxhandbook.com/unzip-command/)解压缩。接下来,在终端中打开该文件夹。你将需要使用以下步骤来完成安装。 首先,在名为 `env` 的文件夹中创建一个虚拟环境: ``` python3 -m venv env ``` 现在在该环境中安装该应用程序的代码: ``` env/bin/pip install . ``` 启动该应用程序: ``` env/bin/bauh ``` 一旦完成了 bauh 的安装,就可以通过更改环境设置和参数来对其进行[微调](https://github.com/vinifmor/bauh#general-settings)。 ### bauh 的未来之路 bauh 在短短的几个月中增长了很多。它有计划继续增长。当前的[路线图](https://github.com/vinifmor/bauh#roadmap)包括: * 支持其他打包技术 * 每种打包技术一个单独模块 * 内存和性能改进 * 改善用户体验 ### 结语 当我尝试 bauh 时,遇到了两个问题。当我第一次打开它时,它告诉我尚未安装 Snap,如果要使用 Snap 软件包,则必须安装它。我知道我已经安装了 Snap,因为我在终端中运行了 `snap list`,并且可以正常工作。我重新启动系统,Snap 才工作正常。 我遇到的另一个问题是我的一个 AUR 软件包无法更新。我可以用 `yay` 更新软件包,而没有任何问题。可能是我的 Manjaro 有问题,我已经使用了它 3 到 4 年。 总体而言,bauh 可以工作。它做到了宣称的功能。我不能要求更多。 你有没有用过 hauh?如果有的话,你最喜欢的用于管理不同打包格式的工具是什么?在下面的评论中让我们知道。 --- via: <https://itsfoss.com/bauh-package-manager/> 作者:[John Paul](https://itsfoss.com/author/john/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) One of the biggest problems with universal packages like [Snap](https://snapcraft.io/?ref=itsfoss.com), [Flatpak](https://flatpak.org/?ref=itsfoss.com) and [AppImage](https://appimage.org/?ref=itsfoss.com) is managing them. Most built-in package managers do not support all of these new formats. Thankfully, I stumbled across an application that supports several universal package formats. ## Bauh – a Manager for Your Multi-Package Needs Originally named fpakman, [bauh](https://github.com/vinifmor/bauh?ref=itsfoss.com) is designed to handle Flatpak, Snap, [AppImage](https://itsfoss.com/use-appimage-linux/), and [AUR](https://itsfoss.com/best-aur-helpers/) packages. Creator [vinifmor](https://github.com/vinifmor?ref=itsfoss.com) started the project in June 2019 with the [intention](https://forum.manjaro.org/t/bauh-formerly-known-as-fpakman-a-gui-for-flatpak-and-snap-management/96180?ref=itsfoss.com) of “giving a graphical interface to manage Flatpaks for Manjaro users.” Since then, he has expanded the application to add support for Debian-based systems. ![About page of bauh, tool to manage Snaps, Flatpaks, AppImages, etc.](https://itsfoss.com/content/images/2024/05/about-page-of-bauh.png) When you first open bauh, it will scan your installed applications and check for updates. If there are any that need to be updated, they will be listed front and center. Once all the packages are updated, you will see a list of packages you have installed. You can deselect a package with updates to prevent it from being updated. You can also choose to install a previous version of the application. ![The bauh app listing installed applications on your system.](https://itsfoss.com/content/images/2024/05/bauh-lisitng-different-type-of-applications.png) `aptitude` package installed. To do that, just run in the terminal: `sudo apt install aptitude` .You can also search for applications. Bauh has detailed information for both installed and searched packages. If you are not interested in one (or more) of the packaging types, you can deselect them in the settings. ## Installing bauh on your Linux distribution Let’s see how to install bauh. ### Arch-based distributions If you have a recent installation of [Manjaro](https://manjaro.org/?ref=itsfoss.com), you should be all set. Bauh comes installed by default. If you have an older install of Manjaro (like I do) or a different Arch-based distro, you can install it from the [AUR](https://aur.archlinux.org/packages/bauh?ref=itsfoss.com) by typing this in terminal: ``` yay -S bauh ``` **Recommended Read** [What is Arch User Repository (AUR)? How to Use AUR on Arch and Manjaro Linux?What is AUR in Arch Linux? How do I use AUR? Is it safe to use? This article explains it all.](https://itsfoss.com/aur-arch-linux/)![](https://itsfoss.com/content/images/wordpress/2020/04/what-is-aur.png) ![](https://itsfoss.com/content/images/wordpress/2020/04/what-is-aur.png) ### Debian/Ubuntu-based distributions If you have a Debian or Ubuntu-based Linux distribution, you can install bauh with pip. First, make sure to [install pip on Ubuntu](https://itsfoss.com/install-pip-ubuntu/). Also, install several required dependencies using the command: ``` sudo apt-get install python3 python3-pip python3-yaml python3-dateutil python3-pyqt5 python3-packaging python3-requests ``` There are also several optional dependencies, which you can [take a look at the official documentation](https://github.com/vinifmor/bauh?tab=readme-ov-file#optional-dependencies-they-should-be-installed-with-apt-getapt). And then use pip to install bauh: ``` sudo pip3 install bauh ``` However, if you want to install it [manually](https://github.com/vinifmor/bauh?ref=itsfoss.com#manual-installation) in an isolated setup to avoid messing up your system’s libraries, you can do that as well. ### Isolated Installation For isolated installation of bauh, you have to first download the [latest release](https://github.com/vinifmor/bauh/releases?ref=itsfoss.com). Once you download it, you can [unzip using a graphical tool](https://itsfoss.com/unzip-linux/) or the [unzip command](https://linuxhandbook.com/unzip-command/?ref=itsfoss.com). Next, open up the folder in your terminal. You will need to use the following steps to complete the installation. First, create a virtualenv in a folder called *bauh_env*: ``` python3 -m venv bauh_env ``` Now install the application code inside the env: ``` bauh_env/bin/pip install bauh ``` And launch the application: ``` bauh_env/bin/bauh ``` Once you finish installing bauh, you can [fine-tune](https://github.com/vinifmor/bauh?ref=itsfoss.com#general-settings) it by changing the environment setting and arguments. [method described in their official documentation](https://github.com/vinifmor/bauh?tab=readme-ov-file#desktop-entry--menu-shortcut). ### For other distributions bauh project provides an AppImage packaging for their application. So, you can download the AppImage from their releases page on GitHub. There are a couple of dependencies you need to properly run the AppImage. `fuse` : the package name may vary from distribution (libfuse2 in Ubuntu).`qt5dxcb-plugin` (or equivalent): the package name may vary from distribution (qt5dxcb-plugin in Ubuntu). **Recommended Read** Here is how you can run and manage AppImages in Linux. [How to Use AppImage in Linux [Complete Guide]What is AppImage? How to run it? How does it work? Here’s the complete guide about using AppImage in Linux.](https://itsfoss.com/use-appimage-linux/)![](https://itsfoss.com/content/images/wordpress/2017/07/use-appimage-linux.png) ![](https://itsfoss.com/content/images/wordpress/2017/07/use-appimage-linux.png) [Open the AppImage file](https://itsfoss.com/cant-run-appimage-ubuntu/), and the click on the bottom-right settings menu. ![Click on the hamburger menu on the bottom-right and select "Install bauh" to install the AppImage](https://itsfoss.com/content/images/2024/05/select-install-app-to-install-appimage.png) From the dropdown menu, select **Install bauh** to create a desktop entry for the application. ## Managing applications with bauh Once you have installed the application, you can use it for most of the usual package management purposes like installing packages, updating them, removing packages etc. ### Installing applications To install an application, first search for it using the search button. Press enter to start a search. ![Search for an application by name in bauh search bar.](https://itsfoss.com/content/images/2024/06/search-for-an-application-by-name.png) You will get a list of packages, that match the name, from all the sources you have configured. ![Install the app as a particular package of your choice.](https://itsfoss.com/content/images/2024/06/install-package-as-a-particular-package.png) Click on the “Install” button corresponding to a particular packaging format of your choice. If it is either a snap or native deb package, you will be asked to enter the password. Enter it when prompted. ### Install an AppImage File If you have an AppImage file in hand, you can install it using bauh. First, open bauh and click on the hamburger menu on the bottom-right. From that, select “Install AppImage File”. ![Select install appimage file from bauh](https://itsfoss.com/content/images/2024/06/select-install-appimage-file-to-start-install-an-appimage-1.png) In the next window, select the AppImage file on your system by clicking on the field near “File”. ![Select the AppImage file you want to install and click on proceed](https://itsfoss.com/content/images/2024/06/select-install-appimage-file.png) From the file chooser, select the AppImage file. It will automatically fill the other fields. You can select a category from the dropdown list. Now click on “Proceed”. The app will be installed, and you can open it from the system menu. ### Install a Web Application Apps, like Facebook, ChatGPT, etc. are available to install on your system. Search for an app, and then install it as usual using the “Install” button. On the next screen, it will show the installation details. You can set the permissions for the app here. ![Review the application information and permissions](https://itsfoss.com/content/images/2024/06/App-informations-and-permissions.png) Verify the permissions and options and click on Continue. This will ask you to install the required dependencies. Check those and click on Continue. ![Listing the required dependencies for the selected web application](https://itsfoss.com/content/images/2024/06/node-and-several-other-deps-needed.png) It will download and install the selections. ![ChatGPT, running on Linux, as a web application](https://itsfoss.com/content/images/2024/06/chatgpt-running-in-linux.png) ### Removing applications On the home page of bauh app, all the installed apps will be listed. You can uninstall an app by clicking on the “Uninstall” button. ![Click on Uninstall to uninstall an installed application](https://itsfoss.com/content/images/2024/06/click-on-uninstall.png) ### Downgrade an application Applications installed as Snap or Flatpak format can be downgraded to a previous release using bauh. First, you need to click on the menu button corresponding to the app that you want to downgrade and select “History”. ![Select Application history to view the version history of that application](https://itsfoss.com/content/images/2024/06/select-app-history.png) This will show a history of commit for that application, along with the available versions listed neatly. ![Commit history of a particular application](https://itsfoss.com/content/images/2024/06/commit-history-of-an-application.png) Close this window, and from the same menu button, select “Downgrade”. ![Select Downgrade from the menu to downgrade an application](https://itsfoss.com/content/images/2024/06/select-downgrade.png) It will ask for a confirmation, and accept it. The app will be downgraded, and you will be prompted that there is an available update. ![After you downgrade an application, bauh will notify you of an update available](https://itsfoss.com/content/images/2024/06/upgrade-available-after-a-downgrade.png) You can pause the auto-update to this app along with the system update, by using the “Ignore Updates” button. ![Ignore updates for an application](https://itsfoss.com/content/images/2024/06/ignore-updates.png) You can revert this status anytime. ## Bonus: Access Settings and theme the App In order to manage the bauh app settings, click on the settings gear on the bottom-right of the app. ![Click on bauh settings](https://itsfoss.com/content/images/2024/06/click-on-bauh-settings.png) It provides a comprehensive tweaking of both apps, update policies and per source settings. ![bauh app settings window with various settings as separate tabs.](https://itsfoss.com/content/images/2024/06/bauh-settings.png) Similarly, you can change the appearance of bauh using the preinstalled themes. Click on the themes button and select the required appearance style. ![Apply a theme for bauh app, from the list of preinstalled themes.](https://itsfoss.com/content/images/2024/06/apply-a-theme.png) ## The road ahead for bauh Bauh has grown quite a bit in a few short months. It plans to continue to grow. The current [road map](https://github.com/vinifmor/bauh?ref=itsfoss.com#roadmap) includes: - Support for other packaging technologies - Separate modules for each packaging technology - Memory and performance improvements - Improve user experience ## Final thoughts Have you ever used bauh? What is your favorite tool to manage different package formats if there is one? Let us know in the comments below. If you found this article interesting, please take a minute to share it on social media, Hacker News or [Reddit](http://reddit.com/r/linuxusersgroup?ref=itsfoss.com).
11,619
如何使用 TimeShift 备份和还原 Ubuntu Linux
https://www.linuxtechi.com/timeshift-backup-restore-ubuntu-linux/
2019-11-28T00:14:00
[ "备份", "Timeshift" ]
https://linux.cn/article-11619-1.html
你是否曾经想过如何备份和还原 Ubuntu 或 Debian 系统?Timeshift 是一款自由开源工具,可让你创建文件系统的增量快照。你可以使用 RSYNC 或 BTRFS 两种方式创建快照。 ![](/data/attachment/album/201911/27/235959fejmb080e7z0jnu0.jpg) 让我们深入研究并安装 Timeshift。在本教程,我们将安装在 Ubuntu 18.04 LTS 系统上。 ### 在 Ubuntu / Debian Linux 上安装 TimeShift TimeShift 尚未正式托管在 Ubuntu 和 Debian 仓库中。考虑到这一点,我们将运行以下命令来添加 PPA: ``` # add-apt-repository -y ppa:teejee2008/ppa ``` ![Add timeshift repository](/data/attachment/album/201911/28/001558mvh2kqjmrzrkvs18.png) 接下来,使用以下命令更新系统软件包: ``` # apt update ``` 成功更新系统后,使用以下 `apt` 命令安装 Timeshift: ``` # apt install timeshift ``` ![apt install timeshift](/data/attachment/album/201911/28/001417qpv1v3yspypkl9vv.png) ### 准备备份存储设备 最佳实践要求我们将系统快照保存在系统硬盘之外的单独的存储卷上。对于本指南,我们将使用 16GB 闪存作为第二个驱动器,并在该驱动器上保存快照。 ``` # lsblk | grep sdb ``` ![lsblk sdb ubuntu](/data/attachment/album/201911/28/001421nrarp82frkrxjoqt.png) 为了将闪存用作快照的备份位置,我们需要在设备上创建一个分区表。运行以下命令: ``` # parted /dev/sdb mklabel gpt # parted /dev/sdb mkpart primary 0% 100% # mkfs.ext4 /dev/sdb1 ``` ![create partition table on drive ubuntu](/data/attachment/album/201911/28/001425rzbfdn9un4ioditt.jpg) 在 USB 闪存上创建分区表后,我们可以开始创建文件系统的快照! ### 使用 Timeshift 创建快照 要启动 Timeshift,使用应用程序菜单搜索 “Timeshift”。 ![Access timeshift](/data/attachment/album/201911/28/001427b5swwersrye5lspd.jpg) 单击 Timeshift 图标,系统将提示你输入管理员密码。提供密码,然后单击验证。 ![Authentication required](/data/attachment/album/201911/28/001431smjkwpzm46aa1c0m.jpg) 接下来,选择你喜欢的快照类型。 ![Select rsync option](/data/attachment/album/201911/28/001431tfrfor6kizsis4os.jpg) 点击 “Next”。选择快照的目标驱动器。在这里,我的位置是标记为 `/dev/sdb` 的外部 USB 驱动器。 ![Select snapshot location](/data/attachment/album/201911/28/001434m1kbo1q11q1qgqj1.png) 接下来,定义快照级别。级别是指创建快照的时间间隔。你可以选择每月、每周、每天或每小时的快照级别。 ![Select snapshot levels](/data/attachment/album/201911/28/001437bcz28s8auc7zchf3.jpg) 点击 “Finish”。 在下一个窗口中,单击 “Create” 按钮开始创建快照。此后,系统将开始创建快照。 ![Create snapshot](/data/attachment/album/201911/28/001439b32933jyj9z88m95.jpg) 最后,你的快照将显示如下: ![Snapshot created](/data/attachment/album/201911/28/001441qcqklak68c4cqcbk.jpg) ### 从快照还原 Ubuntu / Debian 创建系统快照后,现在让我们看看如何从同一快照还原系统。在同一个 Timeshift 中,单击快照,然后单击 “Restore” 按钮,如图所示。 ![Restore snapshot](/data/attachment/album/201911/28/001444z3udab299qd39adi.jpg) 接下来,将提示你选择目标设备。保留默认选择,然后点击 “Next”。 ![Select target device](/data/attachment/album/201911/28/001448ax09vvc0wzb96lz0.jpg) 恢复过程开始之前,Timeshift 将会试运行。 ![Comparing files dry run](/data/attachment/album/201911/28/001454rico1n1p1112oi3p.jpg) 在下一个窗口中,点击 “Next” 按钮确认显示的操作。 ![Confirm actions](/data/attachment/album/201911/28/001459iwaeriwejni8ra3b.jpg) 如图所示,你会看到警告和免责声明。点击 “Next” 初始化恢复过程。 此后,将开始还原过程,最后,系统之后将重新启动到快照定义的早期版本。 ![Restoring snapshot](/data/attachment/album/201911/28/001507y44rsxkp7j90s1f7.png) ### 总结 如你所见,使用 TimeShift 从快照还原系统非常容易。在备份系统文件时,它非常方便,并允许你在系统故障时进行恢复。因此,不要害怕修改系统或弄乱系统。TimeShift 使你能够返回到一切运行平稳的时间点。 --- via: <https://www.linuxtechi.com/timeshift-backup-restore-ubuntu-linux/> 作者:[James Kiarie](https://www.linuxtechi.com/author/james/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Have you ever wondered how you can backup and restore your Ubuntu or Debian system ? TimeShift, a powerful backup and restore utility. TimeShift allows you to create system snapshots, providing an easy way to revert to a previous state in case of unexpected issues or system malfunctions. You can create a snapshot using either RSYNC or BTRFS. With that. let’s delve in and install Timeshift. For this tutorial, we shall install timeshift on Ubuntu 22.04. ## Installing TimeShift on Ubuntu / Debian Linux Timeshift is package is available in the default package repository (Universe) of Ubuntu and Debian system. So to install it, open the terminal and run following apt commands, $ sudo apt update $ sudo apt install timeshift -y ## Preparing a Backup Storage Device Best practice demands that we save the system snapshot on a separate storage volume, aside from the system’s hard drive. For this guide, we are using a 16 GB flash drive as the secondary drive on which we are going to save the snapshot. # lsblk | grep sdb For the flash drive to be used as a backup location for the snapshot, we need to create a partition table on the device. Run the following [parted command](https://www.linuxtechi.com/create-disk-partitions-parted-command-linux/): # parted /dev/sdb mklabel gpt # parted /dev/sdb mkpart primary 0% 100% # mkfs.ext4 /dev/sdb1 After creating a partition table on the USB flash drive, we are all set to begin creating filesystem’s snapshots! ## Creating Ubuntu / Debian System Backup To launch Timeshift, search timeshift from Activities, Click on the Timeshift icon and the system will prompt you for the Administrator’s password. Provide the password and click on Authenticate. Next, select your preferred snapshot type. Click ‘**Next**’. Select the destination drive for the snapshot. In this case, my location is the external USB drive labeled as **/dev/sdb** Next, define the snapshot levels. Levels refer to the intervals during which the snapshots are created. You can choose to have either monthly, weekly, daily, or hourly snapshot levels. Click ‘Finish’ On the next Window, click on the ‘**Create**’ button to begin creating the snapshot. Thereafter, the system will begin creating the snapshot. Finally, your snapshot will be displayed as shown ## Restoring Ubuntu / Debian from a Snapshot Having created a system snapshot, let’s now see how you can restore your system from the same snapshot. On the same Timeshift window, click on the snapshot and click on the ‘**Restore**’ button as shown. Next, you will be prompted to select the target device. leave the default selection and hit ‘**Next**’. A dry run will be performed by Timeshift before the restore process commences. In the next window, hit the ‘**Next**’ button to confirm actions displayed. You’ll get a warning and a disclaimer as shown. Click ‘**Next**’ to initialize the restoration process. Thereafter, the restore process will commence and finally, the system will thereafter reboot into an earlier version as defined by the snapshot. #### Conclusion As you have seen it quite easy to use TimeShift to restore your system from a snapshot. It comes in handy when backing up system files and allows you to recover in the event of a system fault. So don’t get scared to tinker with your system or mess up. TimeShift will give you the ability to go back to a point in time when everything was running smoothly. Don BakerTimeshift by default does not backup the user /Home directory. You can enable that, but did not see that in your screenshots. Also for a full reinstall to a new disk it does not always get boot correct. It is awesome when it works as designed. JasonIt doesn’t do that for a good reason. It’s meant as a system backup so that you can restore your system in the event something goes wrong but you still want to retain your personal data because it’s fine. The author recommends you not use it to backup your personal files but instead use another backup program. Bramno support for external storage. kimmeRead the “Preparing a backup storage device” part of this article? GB GustafsonMissing: Suppose the system running TimeShift is unbootable. How to restore? This situation is an important use of the TimeShift snapshot. The advice written above implies it is OK to run TimeShift on a broken OS. Kindly explain if that was the intent. Expected: A full discussion for how to restore to a new bootable disk. If TimeShift does this reliably, then explain how. Joe SFor clean install, disaster recovery, use Clonezilla to create an image of your system drive/partition after configuration of Timeshift. Use Timeshift and store your Timeshift backups on a different disk. If you crash your OS drive, restore from Clonezilla image and use Timeshift to bring OS back to latest working version. JamesHi I’m a LInux newbie, I moved from Windows 10 to PopOS. Question: When I use the commands: # parted /dev/sdb mklabel gpt # parted /dev/sdb mkpart primary 0% 100% # mkfs.ext4 /dev/sdb1 Will that delete the drive I use? I have stuff on the drive I want to keep. Should I be using a empty from for the backup location? Thank much VicFicNope they are using the parted, a partition app, to partition the usb drive. No need to worry about your current drive. TilmannHow to select a snapshot that is not made on this machine and is stored on an extern device ? That is impossible. F DeveloperThanks buddy had some issues using the terminal but all is fine
11,620
给新手 Java 开发者的 7 点提示
https://opensource.com/article/19/10/java-basics
2019-11-28T12:04:57
[ "Java" ]
https://linux.cn/article-11620-1.html
> > 如果你才刚开始学习 Java 编程,这里有七个你需要知道的基础知识。 > > > ![](/data/attachment/album/201911/28/120421di3744urqnyyr6xi.jpg) Java 是一个多功能的编程语言,在某种程度上,它用在几乎所有可能涉及计算机的行业了里。Java 的最大优势是,它运行在一个 Java 虚拟机(JVM)中,这是一个翻译 Java 代码为与操作系统兼容的字节码的层。只要有 JVM 存在于你的操作系统上 —— 不管这个操作系统是在一个服务器(或“[无服务器](https://www.redhat.com/en/resources/building-microservices-eap-7-reference-architecture)”,也是同样的)、桌面电脑、笔记本电脑、移动设备,或嵌入式设备 —— 那么,Java 应用程序就可以运行在它上面。 这使得 Java 成为程序员和用户的一种流行语言。程序员知道,他们只需要写一个软件版本就能最终得到一个可以运行在任何平台上的应用程序;用户知道,应用程序可以运行在他们的计算机上,而不用管他们使用的是什么样的操作系统。 很多语言和框架是跨平台的,但是没有实现同样的抽象层。使用 Java,你针对的是 JVM,而不是操作系统。对于程序员,当面对一些编程难题时,这是阻力最小的线路,但是它仅在当你知道如何编程 Java 时有用。如果你刚开始学习 Java 编程,这里有你需要知道的七个基础的提示。 但是,首先,如果你不确定是否你安装了 Java ,你可以在一个终端(例如 [Bash](https://www.gnu.org/software/bash/) 或 [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-6))中找出来,通过运行: ``` $ java --version openjdk 12.0.2 2019-07-16 OpenJDK Runtime Environment 19.3 (build 12.0.2+9) OpenJDK 64-Bit Server VM 19.3 (build 12.0.2+9, mixed mode, sharing) ``` 如果你得到一个错误,或未返回任何东西,那么你应该安装 [Java 开发套件](http://openjdk.java.net/)(JDK)来开始 Java 开发。或者,安装一个 Java 运行时环境(JRE),如果你只是需要来运行 Java 应用程序。 ### 1、Java 软件包 在 Java 语言中,相关的类被分组到一个*软件包*中。当你下载 JDK 时所获得的 Java 基础库将被分组到以 `java` 或 `javax` 开头的软件包中。软件包提供一种类似于计算机上的文件夹的功能:它们为相关的元素提供结构和定义(以编程术语说,*命名空间*)。额外的软件包可以从独立开发者、开源项目和商业供应商获得,就像可以为任何编程语言获得库一样。 当你写一个 Java 程序时,你应该在你的代码是顶部声明一个软件包名称。如果你只是编写一个简单的应用程序来入门 Java,你的软件包名称可以简单地用你的项目名称。如果你正在使用一个 Java 集成开发环境,如 [Eclipse](http://www.eclipse.org/),当你启动一个新的项目时,它为你生成一个合乎情理的软件包名称。 ``` package helloworld; /** * @author seth * An application written in Java. */ ``` 除此之外,你可以通过查找它相对于你的项目整体的路径来确定你的软件包名称。例如,如果你正在写一组类来帮助游戏开发,并且该集合被称为 `jgamer`,那么你可能在其中有一些唯一的类。 ``` package jgamer.avatar; /** * @author seth * An imaginary game library. */ ``` 你的软件包的顶层是 `jgamer`,并且在其内部中每个软件包都是一个独立的派生物,例如 `jgamer.avatar` 和 `jgamer.score` 等等。在你的文件系统里,其目录结构反映了这一点,`jgamer` 是包含文件 `avatar.java` 和 `score.java` 的顶级目录。 ### 2、Java 导入 作为一名通晓多种语言的程序员,最大的乐趣是找出是否用 `include`、`import`、`use`、`require`,或一些其它术语来引入你不管使用何种编程语言编写的库。在 Java 中,顺便说一句,当导入你的代码的需要的库时,使用 `import` 关键字。 ``` package helloworld; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * @author seth * A GUI hello world. */ ``` 导入是基于该环境的 Java 路径。如果 Java 不知道 Java 库存储在系统上的何处,那么,就不能成功导入。只要一个库被存储在系统的 Java 路径中,那么导入能够成功,并且库能够被用于构建和运行一个 Java 应用程序。 如果一个库并不在 Java 路径中(因为,例如,你正在写你自己的库),那么该库可以与你的应用程序绑定在一起(协议许可),以便导入可以按预期地工作。 ### 3、Java 类 Java 类使用关键字 `public class` 声明,以及一个唯一的对应于它的文件名的类名。例如,在项目 `helloworld` 中的一个文件 `Hello.java` 中: ``` package helloworld; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * @author seth * A GUI hello world. */ public class Hello { // this is an empty class } ``` 你可以在一个类内部声明变量和函数。在 Java 中,在一个类中的变量被称为*字段*。 ### 4、Java 方法 Java 的方法本质上是对象中的函数。基于预期返回的数据类型(例如 `void`、`int`、`float` 等等),它们被定义为 `public`(意味着它们可以被任何其它类访问)或 `private`(限制它们的使用)。 ``` public void helloPrompt(ActionEvent event) { String salutation = "Hello %s"; string helloMessage = "World"; message = String.format(salutation, helloMessage); JOptionPane.showMessageDialog(this, message); } private int someNumber (x) { return x*2; } ``` 当直接调用一个方法时,以其类和方法名称来引用。例如,`Hello.someNumber` 指向在 `Hello` 类中的 `someNumber` 方法。 ### 5、static Java 中的 `static` 关键字使代码中的成员可以独立于包含其的对象而被访问。 在面向对象编程中,你编写的代码用作“对象”的模板,这些对象在应用程序运行时产生。例如,你不需要编写一个具体的窗口,而是编写基于 Java 中的窗口类的窗口实例(并由你的代码修改)。由于在应用程序生成它的实例之前,你编写的所有代码都不会“存在”,因此在创建它们所依赖的对象之前,大多数方法和变量(甚至是嵌套类)都无法使用。 然而,有时,在对象被通过应用程序创建前,你需要访问或使用其中的数据。(例如,除非事先知道球是红色时,应用程序无法生成一个红色的球)。对于这些情况,请使用 `static` 关键字。 ### 6、try 和 catch Java 擅长捕捉错误,但是,只有你告诉它遇到错误时该做什么,它才能优雅地恢复。在 Java 中,尝试执行一个动作的级联层次结构以 `try` 开头,出现错误时回落到 `catch`,并以 `finally` 结束。如果 `try` 子句失败,则将调用 `catch`,最后,不管结果如何,总是由 `finally` 来执行一些合理的动作。这里是一个示例: ``` try { cmd = parser.parse(opt, args); if(cmd.hasOption("help")) { HelpFormatter helper = new HelpFormatter(); helper.printHelp("Hello <options>", opt); System.exit(0); } else { if(cmd.hasOption("shell") || cmd.hasOption("s")) { String target = cmd.getOptionValue("tgt"); } // else } // fi } catch (ParseException err) { System.out.println(err); System.exit(1); } //catch finally { new Hello().helloWorld(opt); } //finally } //try ``` 这是一个健壮的系统,它试图避免无法挽回的错误,或者,至少,为你提供让用户提交有用的反馈的选项。经常使用它,你的用户将会感谢你! ### 7、运行 Java 应用程序 Java 文件,通常以 `.java` 结尾,理论上说,可以使用 `java` 命令运行。然而,如果一个应用程序很复杂,运行一个单个文件是否会产生有意义的结果是另外一个问题。 来直接运行一个 `.java` 文件: ``` $ java ./Hello.java ``` 通常,Java 应用程序以 Java 存档(JAR)文件的形式分发,以 `.jar` 结尾。一个 JAR 文件包含一个清单文件(可以指定主类、项目结构的一些元数据),以及运行应用程序所需的所有代码部分。 要运行一个 JAR 文件,你可以双击它的图标(取决于你的操作系统设置),你也可以从终端中启动它: ``` $ java -jar ./Hello.jar ``` ### 适合所有人的 Java Java 是一种强大的语言,由于有了 [OpenJDK](https://openjdk.java.net/) 项目及其它的努力,它是一种开放式规范,允许像 [IcedTea](https://icedtea.classpath.org/wiki/Main_Page)、[Dalvik](https://source.android.com/devices/tech/dalvik/) 和 [Kotlin](https://kotlinlang.org/) 项目的茁壮成长。学习 Java 是一种准备在各种行业中工作的好方法,而且,[使用 Java 的理由很多](https://opensource.com/article/19/9/why-i-use-java)。 --- via: <https://opensource.com/article/19/10/java-basics> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Java is a versatile programming language used, in some way, in nearly every industry that touches a computer. Java's greatest power is that it runs in a Java Virtual Machine (JVM), a layer that translates Java code into bytecode compatible with your operating system. As long as a JVM exists for your operating system, whether that OS is on a server (or [serverless](https://www.redhat.com/en/resources/building-microservices-eap-7-reference-architecture), for that matter), desktop, laptop, mobile device, or embedded device, then a Java application can run on it. This makes Java a popular language for both programmers and users. Programmers know that they only have to write one version of their software to end up with an application that runs on any platform, and users know that an application will run on their computer regardless of what operating system they use. Many languages and frameworks are cross-platform, but none deliver the same level of abstraction. With Java, you target the JVM, not the OS. For programmers, that's the path of least resistance when faced with several programming challenges, but it's only useful if you know how to program Java. If you're just getting started with Java programming, here are seven basic tips you need to know. But first, if you're not sure whether you have Java installed, you can find out in a terminal (such as [Bash](https://www.gnu.org/software/bash/) or [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-6)) by running: ``` $ java --version openjdk 12.0.2 2019-07-16 OpenJDK Runtime Environment 19.3 (build 12.0.2+9) OpenJDK 64-Bit Server VM 19.3 (build 12.0.2+9, mixed mode, sharing) ``` If you get an error or nothing in return, then you should install the [Java Development Kit](http://openjdk.java.net/) (JDK) to get started with Java development. Or install a Java Runtime Environment** **(JRE) if you just need to run Java applications. ## 1. Java packages In Java, related classes are grouped into a *package*. The basic Java libraries you get when you download the JDK are grouped into packages starting with **java** or **javax**. Packages serve a similar function as folders on your computer: they provide structure and definition for related elements (in programming terminology, a *namespace*). Additional packages can be obtained from independent coders, open source projects, and commercial vendors, just as libraries can be obtained for any programming language. When you write a Java program, you should declare a package name at the top of your code. If you're just writing a simple application to get started with Java, your package name can be as simple as the name of your project. If you're using a Java integrated development environment (IDE), like [Eclipse](http://www.eclipse.org/), it generates a sane package name for you when you start a new project. ``` package helloworld; /** * @author seth * An application written in Java. */ ``` Otherwise, you can determine the name of your package by looking at its path in relation to the broad definition of your project. For instance, if you're writing a set of classes to assist in game development and the collection is called **jgamer**, then you might have several unique classes within it. ``` package jgamer.avatar; /** * @author seth * An imaginary game library. */ ``` The top level of your package is **jgamer**, and each package inside it is a descendant, such as **jgamer.avatar** and **jgamer.score** and so on. In your filesystem, the structure reflects this, with **jgamer** being the top directory containing the files **avatar.java** and **score.java**. ## 2. Java imports The most fun you'll ever have as a polyglot programmer is trying to keep track of whether you **include**, **import**, **use**, **require**, or **some other term** a library in whatever programming language you're writing in. Java, for the record, uses the **import** keyword when importing libraries needed for your code. ``` package helloworld; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * @author seth * A GUI hello world. */ ``` Imports work based on an environment's Java path. If Java doesn't know where Java libraries are stored on a system, then an import cannot be successful. As long as a library is stored in a system's Java path, then an import can succeed, and a library can be used to build and run a Java application. If a library is not expected to be in the Java path (because, for instance, you are writing the library yourself), then the library can be bundled with your application (license permitting) so that the import works as expected. ## 3. Java classes A Java class is declared with the keywords **public class** along with a unique class name mirroring its file name. For example, in a file **Hello.java** in project **helloworld**: ``` package helloworld; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * @author seth * A GUI hello world. */ public class Hello { // this is an empty class } ``` You can declare variables and functions inside a class. In Java, variables within a class are called *fields*. ## 4. Java methods Java methods are, essentially, functions within an object. They are defined as being **public** (meaning they can be accessed by any other class) or **private** (limiting their use) based on the expected type of returned data, such as **void**, **int**, **float**, and so on. ``` public void helloPrompt(ActionEvent event) { String salutation = "Hello %s"; string helloMessage = "World"; message = String.format(salutation, helloMessage); JOptionPane.showMessageDialog(this, message); } private int someNumber (x) { return x*2; } ``` When calling a method directly, it is referenced by its class and method name. For instance, **Hello.someNumber** refers to the **someNumber** method in the **Hello** class. ## 5. Static The **static** keyword in Java makes a member in your code accessible independently of the object that contains it. In object-oriented programming, you write code that serves as a template for "objects" that get spawned as the application runs. You don't code a specific window, for instance, but an *instance* of a window based upon a window class in Java (and modified by your code). Since nothing you are coding "exists" until the application generates an instance of it, most methods and variables (and even nested classes) cannot be used until the object they depend upon has been created. However, sometimes you need to access or use data in an object before it is created by the application (for example, an application can't generate a red ball without first knowing that the ball is meant to be red). For those cases, there's the **static** keyword. ## 6. Try and catch Java is excellent at catching errors, but it can only recover gracefully if you tell it what to do. The cascading hierarchy of attempting to perform an action in Java starts with **try**, falls back to **catch**, and ends with **finally**. Should the **try** clause fail, then **catch** is invoked, and in the end, there's always **finally** to perform some sensible action regardless of the results. Here's an example: ``` try { cmd = parser.parse(opt, args); if(cmd.hasOption("help")) { HelpFormatter helper = new HelpFormatter(); helper.printHelp("Hello <options>", opt); System.exit(0); } else { if(cmd.hasOption("shell") || cmd.hasOption("s")) { String target = cmd.getOptionValue("tgt"); } // else } // fi } catch (ParseException err) { System.out.println(err); System.exit(1); } //catch finally { new Hello().helloWorld(opt); } //finally } //try ``` It's a robust system that attempts to avoid irrecoverable errors or, at least, to provide you with the option to give useful feedback to the user. Use it often, and your users will thank you! ## 7. Running a Java application Java files, usually ending in **.java**, theoretically can be run with the **java** command. If an application is complex, however, whether running a single file results in anything meaningful is another question. To run a **.java** file directly: `$ java ./Hello.java` Usually, Java applications are distributed as Java Archives (JAR) files, ending in **.jar**. A JAR file contains a manifest file specifying the main class, some metadata about the project structure, and all the parts of your code required to run the application. To run a JAR file, you may be able to double-click its icon (depending on how you have your OS set up), or you can launch it from a terminal: `$ java -jar ./Hello.jar` ## Java for everyone Java is a powerful language, and thanks to the [OpenJDK](https://openjdk.java.net/) project and other initiatives, it's an open specification that allows projects like [IcedTea](https://icedtea.classpath.org/wiki/Main_Page), [Dalvik](https://source.android.com/devices/tech/dalvik/), and [Kotlin](https://kotlinlang.org/) to thrive. Learning Java is a great way to prepare to work in a wide variety of industries, and what's more, there are plenty of [great reasons to use it](https://opensource.com/article/19/9/why-i-use-java). ## 3 Comments
11,624
如何使用 Sphinx 给 Python 代码写文档
https://opensource.com/article/19/11/document-python-sphinx
2019-11-29T16:38:00
[ "Python", "文档" ]
https://linux.cn/article-11624-1.html
> > 最好将文档作为开发过程的一部分。Sphinx 加上 Tox,让文档可以轻松书写,并且外观漂亮。 > > > ![Python in a coffee cup.](/data/attachment/album/201911/29/163803d0a1ev3f40p4pk61.jpg "Python in a coffee cup.") Python 代码可以在源码中包含文档。这种方式默认依靠 **docstring**,它以三引号格式定义。虽然文档的价值是很大的,但是没有充足的文档的代码还是很常见。让我们演练一个场景,了解出色的文档的强大功能。 经历了太多在白板技术面试上要求你实现斐波那契数列,你已经受够了。你回家用 Python 写了一个可重用的斐波那契计算器,使用浮点技巧来实现 `O(1)` 复杂度。 代码很简单: ``` # fib.py import math _SQRT_5 = math.sqrt(5) _PHI = (1 + _SQRT_5) / 2 def approx_fib(n): return round(_PHI**(n+1) / _SQRT_5) ``` (该斐波那契数列是四舍五入到最接近的整数的几何序列,这是我最喜欢的鲜为人知的数学事实之一。) 作为一个好人,你可以将代码开源,并将它放在 [PyPI](https://pypi.org/) 上。`setup.py` 文件很简单: ``` import setuptools setuptools.setup( name='fib', version='2019.1.0', description='Fibonacci', py_modules=["fib"], ) ``` 但是,没有文档的代码是没有用的。因此,你可以向函数添加 docstring。我最喜欢的 docstring 样式之一是 [“Google” 样式](http://google.github.io/styleguide/pyguide.html#381-docstrings)。标记很轻量,当它放在源代码中时很好。 ``` def approx_fib(n): """ Approximate Fibonacci sequence Args: n (int): The place in Fibonacci sequence to approximate Returns: float: The approximate value in Fibonacci sequence """ # ... ``` 但是函数的文档只是成功的一半。普通文档对于情境化代码用法很重要。在这种情况下,情景是恼人的技术面试。 有一种添加更多文档的方式,专业 Python 人的方式通常是在 `docs/` 添加 rst 文件( [reStructuredText](http://docutils.sourceforge.net/rst.html) 的缩写)。因此 `docs/index.rst` 文件最终看起来像这样: ``` Fibonacci ========= Are you annoyed at tech interviewers asking you to implement the Fibonacci sequence? Do you want to have some fun with them? A simple :code:`pip install fib` is all it takes to tell them to, um, fib off. .. automodule:: fib :members: ``` 我们完成了,对吧?我们已经将文本放在了文件中。人们应该会看的。 ### 使 Python 文档更漂亮 为了使你的文档看起来更漂亮,你可以利用 [Sphinx](http://www.sphinx-doc.org/en/master/),它旨在制作漂亮的 Python 文档。这三个 Sphinx 扩展特别有用: * `sphinx.ext.autodoc`:从模块内部获取文档 * `sphinx.ext.napoleon`:支持 Google 样式的 docstring * `sphinx.ext.viewcode`:将 ReStructured Text 源码与生成的文档打包在一起 为了告诉 Sphinx 该生成什么以及如何生成,我们在 `docs/conf.py` 中配置一个辅助文件: ``` extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode', ] # 该入口点的名称,没有 .rst 扩展名。 # 惯例该名称是 index master_doc = "index" # 这些值全部用在生成的文档当中。 # 通常,发布(release)与版本(version)是一样的, # 但是有时候我们会有带有 rc 标签的发布。 project = "Fib" copyright = "2019, Moshe Zadka" author = "Moshe Zadka" version = release = "2019.1.0" ``` 此文件使我们可以使用所需的所有元数据来发布代码,并注意扩展名(上面的注释说明了方式)。最后,要确保生成我们想要的文档,请使用 [Tox](https://tox.readthedocs.io/en/latest/) 管理虚拟环境以确保我们顺利生成文档: ``` [tox] # 默认情况下,`.tox` 是该目录。 # 将其放在非点文件中可以从 # 文件管理器或浏览器的 # 打开对话框中打开生成的文档, # 这些对话框有时会隐藏点文件。 toxworkdir = {toxinidir}/build/tox [testenv:docs] # 从 `docs` 目录内运行 `sphinx`, # 以确保它不会拾取任何可能进入顶层目录下的 # 虚拟环境或 `build/` 目录下的其他工件的杂散文件。 changedir = docs # 唯一的依赖关系是 `sphinx`。 # 如果我们使用的是单独打包的扩展程序, # 我们将在此处指定它们。 # 更好的做法是指定特定版本的 sphinx。 deps = sphinx # 这是用于生成 HTML 的 `sphinx` 命令。 # 在其他情况下,我们可能想生成 PDF 或电子书。 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html # 我们使用 Python 3.7。 # Tox 有时会根据 testenv 的名称尝试自动检测它, # 但是 `docs` 没有给出有用的线索,因此我们必须明确它。 basepython = python3.7 ``` 现在,无论何时运行 Tox,它都会为你的 Python 代码生成漂亮的文档。 ### 在 Python 中写文档很好 作为 Python 开发人员,我们可以使用的工具链很棒。我们可以从 **docstring** 开始,添加 .rst 文件,然后添加 Sphinx 和 Tox 来为用户美化结果。 你对好的文档有何评价?你还有其他喜欢的方式么?请在评论中分享它们! --- via: <https://opensource.com/article/19/11/document-python-sphinx> 作者:[Moshe Zadka](https://opensource.com/users/moshez) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Python code can include documentation right inside its source code. The default way of doing so relies on **docstrings**, which are defined in a triple quote format. While the value of documentation is well... documented, it seems all too common to not document code sufficiently. Let's walk through a scenario on the power of great documentation. After one too many whiteboard tech interviews that ask you to implement the Fibonacci sequence, you have had enough. You go home and write a reusable Fibonacci calculator in Python that uses floating-point tricks to get to O(1). The code is pretty simple: ``` # fib.py import math _SQRT_5 = math.sqrt(5) _PHI = (1 + _SQRT_5) / 2 def approx_fib(n): return round(_PHI**(n+1) / _SQRT_5) ``` (That the Fibonacci sequence is a geometric sequence rounded to the nearest whole number is one of my favorite little-known math facts.) Being a decent person, you make the code open source and put it on [PyPI](https://pypi.org/). The **setup.py** file is simple enough: ``` import setuptools setuptools.setup( name='fib', version='2019.1.0', description='Fibonacci', py_modules=["fib"], ) ``` However, code without documentation is useless. So you add a docstring to the function. One of my favorite docstring styles is the ["Google" style](http://google.github.io/styleguide/pyguide.html#381-docstrings). It is light on markup, which is nice when it is inside the source code. ``` def approx_fib(n): """ Approximate Fibonacci sequence Args: n (int): The place in Fibonacci sequence to approximate Returns: float: The approximate value in Fibonacci sequence """ # ... ``` But the function's documentation is only half the battle. Prose documentation is important for contextualizing code usage. In this case, the context is annoying tech interviews. There is an option to add more documentation, and the Pythonic pattern is to use an **rst** file (short for [reStructuredText](http://docutils.sourceforge.net/rst.html)) commonly added under a **docs/** directory. So the **docs/index.rst** file ends up looking like this: ``` Fibonacci ========= Are you annoyed at tech interviewers asking you to implement the Fibonacci sequence? Do you want to have some fun with them? A simple :code:`pip install fib` is all it takes to tell them to, um, fib off. .. automodule:: fib :members: ``` And we're done, right? We have the text in a file. Someone should look at it. ## Making Python documentation beautiful To make your documentation look beautiful, you can take advantage of [Sphinx](http://www.sphinx-doc.org/en/master/), which is designed to make pretty Python documents. In particular, these three Sphinx extensions are helpful: **sphinx.ext.autodoc**: Grabs documentation from inside modules**sphinx.ext.napoleon**: Supports Google-style docstrings**sphinx.ext.viewcode**: Packages the ReStructured Text sources with the generated docs In order to tell Sphinx what and how to generate, we configure a helper file at **docs/conf.py**: ``` extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode', ] # The name of the entry point, without the ".rst" extension. # By convention this will be "index" master_doc = "index" # This values are all used in the generated documentation. # Usually, the release and version are the same, # but sometimes we want to have the release have an "rc" tag. project = "Fib" copyright = "2019, Moshe Zadka" author = "Moshe Zadka" version = release = "2019.1.0" ``` This file allows us to release our code with all the metadata we want and note our extensions (the comments above explain how). Finally, to document exactly how we want the documentation generated, use [Tox](https://tox.readthedocs.io/en/latest/) to manage the virtual environment to make sure we generate the documentation smoothly: ``` [tox] # By default, .tox is the directory. # Putting it in a non-dot file allows opening the generated # documentation from file managers or browser open dialogs # that will sometimes hide dot files. toxworkdir = {toxinidir}/build/tox [testenv:docs] # Running sphinx from inside the "docs" directory # ensures it will not pick up any stray files that might # get into a virtual environment under the top-level directory # or other artifacts under build/ changedir = docs # The only dependency is sphinx # If we were using extensions packaged separately, # we would specify them here. # A better practice is to specify a specific version of sphinx. deps = sphinx # This is the sphinx command to generate HTML. # In other circumstances, we might want to generate a PDF or an ebook commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html # We use Python 3.7. Tox sometimes tries to autodetect it based on the name of # the testenv, but "docs" does not give useful clues so we have to be explicit. basepython = python3.7 ``` Now, whenever you run Tox, it will generate beautiful documentation for your Python code. ## Documentation in Python is excellent As a Python developer, the toolchain available to us is fantastic. We can start with **docstrings**, add **.rst** files, then add Sphinx and Tox to beautify the results for users. What do you appreciate about good documentation? Do you have other favorite tactics? Share them in the comments! ## Comments are closed.
11,627
如何在 CentOS 8 / RHEL 8 上安装 VirtualBox 6.0
https://www.linuxtechi.com/install-virtualbox-6-centos-8-rhel-8/
2019-11-30T09:51:00
[ "VirtualBox" ]
https://linux.cn/article-11627-1.html
![](/data/attachment/album/201911/30/095031gbnm59ux0dw979wb.jpg) VirtualBox 是一款自由开源的虚拟化工具,它允许技术人员同时运行多个不同风格的虚拟机(VM)。它通常用于运行桌面(Linux 和 Windows),当人们尝试探索新的 Linux 发行版的功能或希望在 VM 中安装 OpenStack、Ansible 和 Puppet 等软件时,它会非常方便,在这种情况下,我们可以使用 VirtualBox 启动 VM。 VirtualBox 被分类为 2 类虚拟机管理程序,这意味着它需要一个现有的操作系统,在上面安装 VirtualBox 软件。VirtualBox 提供功能来创建本机网络或 NAT 网络。在本文中,我们将演示如何在 CentOS 8 和 RHEL 8 系统上安装最新版本的 VirtualBox 6.0,并演示如何安装 VirtualBox 扩展。 ### 在 CentOS 8 / RHEL 8 上安装 VirtualBox 6.0 的安装步骤 #### 步骤 1: 启用 VirtualBox 和 EPEL 仓库 登录到你的 CentOS 8 或 RHEL 8 系统并打开终端,执行以下命令并启用 VirtualBox 和 EPEL 包仓库: ``` [root@linuxtechi ~]# dnf config-manager --add-repo=https://download.virtualbox.org/virtualbox/rpm/el/virtualbox.repo ``` 使用以下 `rpm` 命令导入 Oracle VirtualBox 公钥: ``` [root@linuxtechi ~]# rpm --import https://www.virtualbox.org/download/oracle_vbox.asc ``` 使用以下 `dnf` 命令启用 EPEL 仓库: ``` [root@linuxtechi ~]# dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y ``` #### 步骤 2: 安装 VirtualBox 构建工具和依赖项 运行以下命令来安装所有 VirtualBox 构建工具和依赖项: ``` [root@linuxtechi ~]# dnf install binutils kernel-devel kernel-headers libgomp make patch gcc glibc-headers glibc-devel dkms -y ``` 成功安装上面的依赖项和构建工具后,使用 `dnf` 命令继续安装 VirtualBox。 #### 步骤 3: 在 CentOS 8 / RHEL 8 上安装 VirtualBox 6.0 如果希望在安装之前列出 VirtualBox 的可用版本,请执行以下 dnf 命令: ``` [root@linuxtechi ~]# dnf search virtualbox Last metadata expiration check: 0:14:36 ago on Sun 17 Nov 2019 04:13:16 AM GMT. =============== Summary & Name Matched: virtualbox ===================== VirtualBox-5.2.x86_64 : Oracle VM VirtualBox VirtualBox-6.0.x86_64 : Oracle VM VirtualBox [root@linuxtechi ~]# ``` 让我们使用以下 `dnf` 命令安装最新版本的 VirtualBox 6.0: ``` [root@linuxtechi ~]# dnf install VirtualBox-6.0 -y ``` 如果有本地用户希望将 usb 设备连接到 VirtualBox VM,那么他/她应该是 `vboxusers` 组的一员,请使用下面的 `usermod` 命令将本地用户添加到 `vboxusers` 组。 ``` [root@linuxtechi ~]# usermod -aG vboxusers pkumar ``` #### 步骤 4: 访问 CentOS 8 / RHEL 8 上的 VirtualBox 有两种方法可以访问 VirtualBox,在命令行输入 `virtualbox` 然后回车: ``` [root@linuxtechi ~]# virtualbox ``` 在桌面环境中,在搜索框中搜索 “VirtualBox”。 ![Access-VirtualBox-CentOS8](/data/attachment/album/201911/30/095327njnisdaxqsox0chj.jpg) 单击 VirtualBox 图标: ![VirtualBox-CentOS8](/data/attachment/album/201911/30/095145l61b1xqx11uqqr2x.jpg) 这确认 VirtualBox 6.0 已成功安装,让我们安装它的扩展包。 #### 步骤 5: 安装 VirtualBox 6.0 扩展包 顾名思义,VirtualBox 扩展包用于扩展 VirtualBox 的功能。它添加了以下功能: * USB 2.0 和 USB 3.0 支持 * 虚拟 RDP(VRDP) * 磁盘镜像加密 * Intel PXE 启动 * 主机网络摄像头 使用下面的 `wget` 命令下载 Virtualbox 扩展包到下载文件夹中: ``` [root@linuxtechi ~]$ cd Downloads/ [root@linuxtechi Downloads]$ wget https://download.virtualbox.org/virtualbox/6.0.14/Oracle_VM_VirtualBox_Extension_Pack-6.0.14.vbox-extpack ``` 下载后,打开 VirtualBox 并依次点击 “File -> Preferences -> Extension”,然后点击 “+” 号图标添加下载的扩展包: ![Install-VirtualBox-Extension-Pack-CentOS8](/data/attachment/album/201911/30/095146zk3s9hknknvqczdv.jpg) 单击 “Install” 开始安装扩展包: ![Accept-VirtualBox-Extension-Pack-License-CentOS8](/data/attachment/album/201911/30/095149fizkghth6na6g19t.jpg) 单击 “I Agree” 接受 VirtualBox 扩展包许可证。 成功安装 VirtualBox 扩展包后,我们将看到下面的页面,单击 “OK” 并开始使用 VirtualBox。 ![VirtualBox-Extension-Pack-Install-Message-CentOS8](/data/attachment/album/201911/30/095151h2puclup2wlyq1o2.jpg) 本文就是这些了,我希望这些步骤可以帮助你在 CentOS 8 和 RHEL 8 系统上安装 VirtualBox 6.0。请分享你的宝贵的反馈和意见。 --- via: <https://www.linuxtechi.com/install-virtualbox-6-centos-8-rhel-8/> 作者:[Pradeep Kumar](https://www.linuxtechi.com/author/pradeep/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
**VirtualBox** is a free and open source **virtualization tool** which allows techies to run multiple virtual machines of different flavor at the same time. It is generally used at desktop level (Linux and Windows), it becomes very handy when someone try to explore the features of new Linux distribution or want to install software like **OpenStack**, **Ansible** and **Puppet** in one VM, so in such scenarios one can launch a VM using VirtualBox. VirtualBox is categorized as **type 2 hypervisor** which means it requires an existing operating system, on top of which VirtualBox software will be installed. VirtualBox provides features to create our own custom host only network and NAT network. In this article we will demonstrate how to install latest version of VirtualBox 6.0 on CentOS 8 and RHEL 8 System and will also demonstrate on how to install VirtualBox Extensions. ### Installation steps of VirtualBox 6.0 on CentOS 8 / RHEL 8 #### Step:1) Enable VirtualBox and EPEL Repository Login to your CentOS 8 or RHEL 8 system and open terminal and execute the following commands to enable VirtualBox and EPEL package repository. [root@linuxtechi ~]# dnf config-manager --add-repo=https://download.virtualbox.org/virtualbox/rpm/el/virtualbox.repo Use below rpm command to import Oracle VirtualBox Public Key [root@linuxtechi ~]# rpm --import https://www.virtualbox.org/download/oracle_vbox.asc Enable EPEL repo using following dnf command, [root@linuxtechi ~]# dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y #### Step:2) Install VirtualBox Build tools and dependencies Run the following command to install all VirtualBox build tools and dependencies, [root@linuxtechi ~]# dnf install binutils kernel-devel kernel-headers libgomp make patch gcc glibc-headers glibc-devel dkms -y Once above dependencies and build tools are installed successfully then proceed with VirtualBox installation using dnf command, #### Step:3) Install VirtualBox 6.0 on CentOS 8 / RHEL 8 If wish to list available versions of VirtualBox before installing it , then execute the following [dnf command](https://www.linuxtechi.com/dnf-command-examples-rpm-management-fedora-linux/), [root@linuxtechi ~]# dnf search virtualbox Last metadata expiration check: 0:14:36 ago on Sun 17 Nov 2019 04:13:16 AM GMT. =============== Summary & Name Matched: virtualbox ===================== VirtualBox-5.2.x86_64 : Oracle VM VirtualBox VirtualBox-6.0.x86_64 : Oracle VM VirtualBox [root@linuxtechi ~]# Let’s install latest version of VirtualBox 6.0 using following dnf command, [root@linuxtechi ~]# dnf install VirtualBox-6.0 -y If any local user want to attach usb device to VirtualBox VMs then he/she should be part “**vboxuser**s ” group, use the beneath usermod command to add local user to “vboxusers” group. [root@linuxtechi ~]# usermod -aG vboxusers pkumar #### Step:4) Access VirtualBox on CentOS 8 / RHEL 8 There are two ways to access VirtualBox, from the command line type “**virtualbox**” then hit enter [root@linuxtechi ~]# virtualbox From Desktop environment, Search “VirtualBox” from Search Dash. Click on VirtualBox icon, This confirms that VirtualBox 6.0 has been installed successfully, let’s install its extension pack. #### Step:5) Install VirtualBox 6.0 Extension Pack As the name suggests, VirtualBox extension pack is used to extend the functionality of VirtualBox. It adds the following features: - USB 2.0 & USB 3.0 support - Virtual RDP (VRDP) - Disk Image Encryption - Intel PXE Boot - Host WebCam Use below wget command to download virtualbox extension pack under download folder, [pkumar@linuxtechi ~]$ cd Downloads/ [pkumar@linuxtechi Downloads]$ wget https://download.virtualbox.org/virtualbox/6.0.14/Oracle_VM_VirtualBox_Extension_Pack-6.0.14.vbox-extpack Once it is downloaded, access VirtualBox and navigate **File** –>**Preferences** –> **Extension** then click on + icon to add downloaded extension pack, Click on “Install” to start the installation of extension pack. Click on “I Agree” to accept VirtualBox Extension Pack License. After successful installation of VirtualBox extension pack, we will get following screen, Click on Ok and start using VirtualBox. That’s all from this article, I hope these steps help you install VirtualBox 6.0 on your CentOS 8 and RHEL 8 system. Please do share your valuable feedback and comments. **Also Read**: [How to Manage Oracle VirtualBox Virtual Machines from Command Line](https://www.linuxtechi.com/manage-virtualbox-virtual-machines-command-line/) JosephThank you so much for creating this how-to, Mr. Kumar! I’ve been battling this all day, but your guide worked perfectly after so many others didn’t. Thanks again! vjgreat help sir Bee CoolIt was breeze following your instructions! Thanks a lot! MahlanguGreat tut, really helped a lot! AmitThank you for the detailed example of installing VirtualBox on Centos & RHEL! Giancarlothanks a lot. Very good and usefull.
11,628
揭开 Kubernetes 的神秘面纱
https://opensourceforu.com/2019/11/demystifying-kubernetes/
2019-11-30T12:12:48
[ "Kubernetes" ]
https://linux.cn/article-11628-1.html
![](/data/attachment/album/201911/30/121252zjglvvff9v9aejam.jpg) > > Kubernetes 是一款生产级的开源系统,用于容器化应用程序的自动部署、扩展和管理。本文关于使用 Kubernetes 来管理容器。 > > > “容器”已成为最新的流行语之一。但是,这个词到底意味着什么呢?说起“容器”,人们通常会把它和 Docker 联系起来,Docker 是一个被定义为软件的标准化单元容器。该容器将软件和运行软件所需的环境封装到一个易于交付的单元中。 容器是一个软件的标准单元,用它来打包代码及其所有依赖项,这样应用程序就可以从一个计算环境到另一个计算环境快速可靠地运行。容器通过创建类似于 ISO 镜像的方式来实现此目的。容器镜像是一个轻量级的、独立的、可执行的软件包,其中包含运行应用程序所需的所有信息,包括代码、运行时、系统工具、系统库和设置。 容器镜像在运行时变成容器,对于 Docker 容器,镜像在 Docker 引擎上运行时变成容器。容器将软件与环境隔离开来,确保不同环境下的实例,都可以正常运行。 ### 什么是容器管理? 容器管理是组织、添加或替换大量软件容器的过程。容器管理使用软件来自动化创建、部署和扩展容器。这一过程就需要容器编排,容器编排是一个自动对基于容器的应用程序进行部署、管理、扩展、联网和提供可用性的工具。 ### Kubernetes Kubernetes 是一个可移植的、可扩展的开源平台,用于管理容器化的工作负载和服务,它有助于配置和自动化。它最初由 Google 开发,拥有一个庞大且快速增长的生态系统。Kubernetes 的服务、技术支持和工具得到广泛应用。 Google 在 2014 年开源了 Kubernetes 项目。Kubernetes 建立在 Google 十五年大规模运行生产工作负载的经验基础上,并结合了社区中最好的想法和实践以及声明式句法的使用。 下面列出了与Kubernetes生态系统相关的一些常用术语。 **Pod**:Pod 是 Kubernetes 应用程序的基本执行单元,是你创建或部署的 Kubernetes 对象模型中的最小和最简单的单元。Pod 代表在 Kubernetes 集群上运行的进程。 Pod 将运行中的容器、存储、网络 IP(唯一)和控制容器应如何运行的命令封装起来。它代表 Kubernetes 生态系统内的单个部署单元,代表一个应用程序的单个实例,该程序可能包含一个或多个紧密耦合并共享资源的容器。 Kubernetes 集群中的 Pod 有两种主要的使用方式。第一种是运行单个容器。即“一个容器一个 Pod”,这种方式是最常见的。第二种是运行多个需要一起工作的容器。 Pod 可能封装一个由紧密关联且需要共享资源的多个同位容器组成的应用程序。 <ruby> 副本集 <rt> ReplicaSet </rt></ruby>:副本集的目的是维护在任何给定时间运行的一组稳定的副本容器集。 副本集包含有关一个特定 Pod 应该运行多少个副本的信息。为了创建多个 Pod 以匹配副本集条件,Kubernetes 使用 Pod 模板。副本集与其 Pod 的链接是通过后者的 `metas.ownerReferences` 字段实现,该字段指定哪个资源拥有当前对象。 <ruby> 服务 <rt> Services </rt></ruby>:服务是一种抽象,用来公开一组 Pod 功能。使用 Kubernetes,你无需修改应用程序即可使用陌生服务发现机制。Kubernetes 给 Pod 提供了其自己的 IP 地址和一组 Pod 的单个 DNS 名称,并且可以在它们之间负载平衡。 服务解决的一个主要问题是 Web 应用程序前端和后端的集成。由于 Kubernetes 将幕后的 IP 地址提供给 Pod,因此当 Pod 被杀死并复活时,IP 地址会更改。这给给定的后端 IP 地址连接到相应的前端 IP 地址带来一个大问题。服务通过在 Pod 上提供抽象来解决此问题,类似于负载均衡器。 <ruby> 卷 <rt> Volumes </rt></ruby>: Kubernetes 卷具有明确的生命周期,与围绕它的 Pod 相同。 因此,卷超过了 Pod 中运行的任何容器的寿命,并且在容器重新启动后保留了数据。当然,当 Pod 不存在时,该卷也将不再存在。也许比这更重要的是 Kubernetes 支持多种类型的卷,并且 Pod 可以同时使用任意数量的卷。 卷的核心只是一个目录,其中可能包含一些数据,Pod 中的容器可以访问该目录。该目录是如何产生的,它后端基于什么存储介质,其中的数据内容是什么,这些都由使用的特定卷类型来决定的。 ### 为什么选择 Kubernetes? 容器是捆绑和运行应用程序的好方法。在生产环境中,你需要管理运行应用程序的容器,并确保没有停机时间。例如,如果一个容器发生故障,则需要启动另一个容器。如果由系统自动实现这一操作,岂不是更好? Kubernetes 就是来解决这个问题的!Kubernetes 提供了一个框架来弹性运行分布式系统。该框架负责扩展需求、故障转移、部署模式等。例如,Kubernetes 可以轻松管理系统的金丝雀部署。 Kubernetes 为用户提供了: 1. 服务发现和负载平衡 2. 存储编排 3. 自动退出和回退 4. 自动打包 5. 自我修复 6. 秘密配置管理 ### Kubernetes 可以做什么? 在本文中,我们将会看到一些从头构建 Web 应用程序时如何使用 Kubernetes 的代码示例。我们将在 Python 中使用 Flask 创建一个简单的后端服务器。 对于那些想从头开始构建 Web 应用程序的人,有一些前提条件,即: 1. 对 Docker、Docker 容器和 Docker 镜像的基本了解。可以访问[这里](https://www.docker.com/sites/default/files/Docker_CheatSheet_08.09.2016_0.pdf)快速了解。 2. 系统中应该安装 Docker。 3. 系统中应该安装 Kubernetes,有关如何在本地计算机上安装的说明,请访问[这里](https://kubernetes.io/docs/setup/learning-environment/minikube/)。 现在,创建一个目录,如下代码片段所示: ``` mkdir flask-kubernetes/app && cd flask-kubernetes/app ``` 接下来,在 `flask-kubernetes/app` 目录中,创建一个名为 `main.py` 的文件,如下面的代码片段所示: ``` touch main.py ``` 在新创建的 `main.py` 文件中,粘贴下面代码: ``` from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello from Kubernetes!" if __name__ == "__main__": app.run(host='0.0.0.0') ``` 使用下面命令在本地安装 Flask: ``` pip install Flask==0.10.1 ``` Flask 安装后,执行下面的命令: ``` python app.py ``` 应该在本地 5000 端口运行 Flask 服务器,这是 Flask 应用程序的默认端口,并且你可以在 <http://localhost:5000> 上看到输出 “Hello from Kubernetes!”。服务器在本地运行之后,我们创建一个供 Kubernetes 使用的 Docker 镜像。创建一个名为 `Dockerfile` 的文件,并将以下代码片段粘贴到其中: ``` FROM python:3.7 RUN mkdir /app WORKDIR /app ADD . /app/ RUN pip install -r requirements.txt EXPOSE 5000 CMD ["python", "/app/main.py"] ``` `Dockerfile` 文件的说明如下: 1. Docker 将从 DockerHub 获取 Python 3.7 镜像。 2. 将在镜像中创建一个应用程序目录。 3. 它将一个 `/app` 目录设置为工作目录。 4. 将内容从主机中的应用程序目录复制到镜像应用程序目录。 5. 发布端口 5000。 6. 最后,它运行命令,启动 Flask 服务器。 接下来,我们将使用以下命令创建 Docker 镜像: ``` docker build -f Dockerfile -t flask-kubernetes:latest . ``` 创建 Docker 镜像后,我们可以使用以下命令在本地运行该镜像进行测试: ``` docker run -p 5001:5000 flask-kubernetes ``` 通过运行容器在本地完成测试之后,我们需要在 Kubernetes 中部署它。我们将首先使用 `kubectl` 命令验证 Kubernetes 是否正在运行。如果没有报错,则说明它正在工作。如果有报错,请参考[该信息](https://kubernetes.io/docs/setup/learning-environment/minikube/)。 接下来,我们创建一个部署文件。这是一个 Yaml 文件,其中包含有关 Kubernetes 的说明,该说明涉及如何以声明性的方式创建 Pod 和服务。因为我们有 Flask Web 应用程序,我们将创建一个 `deployment.yaml` 文件,并在其中包含 Pod 和服务声明。 创建一个名为 `deployment.yaml` 的文件并向其中添加以下内容,然后保存: ``` apiVersion: v1 kind: Service metadata: name: flask-kubernetes -service spec: selector: app: flask-kubernetes ports: - protocol: "TCP" port: 6000 targetPort: 5000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: flask-kubernetes spec: replicas: 4 template: metadata: labels: app: flask-kubernetes spec: containers: - name: flask-kubernetes image: flask-kubernetes:latest imagePullPolicy: Never ports: - containerPort: 5000 ``` 使用以下命令将 yaml 文件发送到 Kubernetes: ``` kubectl apply -f deployment.yaml ``` 如果执行以下命令,你会看到 Pod 正在运行: ``` kubectl get pods ``` 现在,导航至 [http://localhost:6000,你应该会看到](http://localhost:6000%EF%BC%8C%E4%BD%A0%E5%BA%94%E8%AF%A5%E4%BC%9A%E7%9C%8B%E5%88%B0) “Hello from Kubernetes!”消息。成功了! 该应用程序现在正在 Kubernetes 中运行! ### Kubernetes 做不了什么? Kubernetes 不是一个传统的,包罗万象的 PaaS(平台即服务)系统。 由于 Kubernetes 运行在容器级别而非硬件级别,因此它提供了 PaaS 产品共有的一些普遍适用功能,如部署、扩展、负载平衡、日志记录和监控。Kubernetes 为开发人员平台提供了构建块,但在重要的地方保留了用户的选择和灵活性。 * Kubernetes 不限制所支持的应用程序的类型。如果应用程序可以在容器中运行,那么它应该可以在 Kubernetes 上更好地运行。 * 它不部署和构建源代码。 * 它不决定日志记录、监视或警报解决方案。 * 它不提供或不要求配置语言/系统。它提供了一个声明式的 API 供所有人使用。 * 它不提供或不采用任何全面的机器配置、维护、管理或自我修复系统。 --- via: <https://opensourceforu.com/2019/11/demystifying-kubernetes/> 作者:[Abhinav Nath Gupta](https://opensourceforu.com/author/abhinav-gupta/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[Morisun029](https://github.com/Morisun029) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,629
从 Python 2 切换到 Python 3 你所需要了解的
https://opensource.com/article/19/11/end-of-life-python-2
2019-12-01T09:54:04
[ "Python" ]
https://linux.cn/article-11629-1.html
> > Python 2 将在几周内走到生命终点,这篇文章是你迁移到 Python 3 之前应该知道的。 > > > ![](/data/attachment/album/201912/01/095336lbppn8qp1nnnwqqp.jpg) 从 2020 年 1 月 1 日开始,Python 2.7 将不再得到正式支持。在此日期之后,将会发布一个[最终错误修复](https://www.python.org/dev/peps/pep-0373/#maintenance-releases)计划,但是仅此而已。 Python 2 的生命终点(EOL)对你意味着什么?如果正在运行着 Python 2,你需要迁移。 ### 是谁决定 Python 2 的生命终点? 在 [2012](https://github.com/python/peps/commit/a733bc927acbca16bfa3de486fb2c7d3f767a748) 年,维护 Python 编程语言的团队审查了其选项。有两个越来越不同的代码库,Python 2 和 Python 3。这两者都很流行,但是较新的版本并未得到广泛采用。 除了 Python 3 中完全重写的 Unicode 支持改变了处理数据的底层方式造成的断层,这个主要版本的变化还一次性出现了一些非向后兼容的更改。这种断层的决定成文于 [2006 年](https://www.python.org/dev/peps/pep-3000/#compatibility-and-transition)。为了减轻该断层的影响,Python 2 继续保持了维护,并向后移植了一些 Python 3 的功能。为了进一步帮助社区过渡,EOL 日期[从 2015 年延长至 2020 年](https://github.com/python/peps/commit/f82462002b86feff36215b4230be28967039b0cc),又延长了五年。 该团队知道,维护不同的代码库是必须解决的麻烦。最终,他们[宣布了](https://www.python.org/doc/sunset-python-2/)一项决定: > > “我们是制作和照料 Python 编程语言的志愿者。我们已决定 2020 年 1 月 1 日将是我们停止使用 Python 2 的日子。这意味着在这一天之后,即使有人发现其中存在安全问题,我们也将不再对其进行改进。你应尽快升级到 Python 3。” > > > [Nick Coghlan](https://twitter.com/ncoghlan_dev) 是 CPython 的核心开发人员,也是 Python 指导委员会的现任成员,[在他的博客中添加了更多信息](http://python-notes.curiousefficiency.org/en/latest/python3/questions_and_answers.html)。由 [Barry Warsaw](https://twitter.com/pumpichank)(也是 Python 指导委员会的成员)撰写的 [PEP 404](https://www.python.org/dev/peps/pep-0404/) 详细说明了 Python 2.8 永远不会面世的原因。 ### 有人还在支持 Python 2 吗? 提供者和供应商对 Python 2 的支持会有所不同。[Google Cloud 宣布了](https://cloud.google.com/python/docs/python2-sunset/?utm_source=osdc&utm_medium=blog&utm_campaign=pysunset)它计划未来如何支持 Python 2。红帽还[宣布了红帽企业 Linux(RHEL)的计划](https://access.redhat.com/solutions/4455511),而 AWS 宣布了 AWS 命令行界面和 [SDK](https://aws.amazon.com/sdk-for-python/) 的[次要版本更新要求](https://aws.amazon.com/blogs/developer/deprecation-of-python-2-6-and-python-3-3-in-botocore-boto3-and-the-aws-cli/)。 你还可以阅读 [Vicki Boykis](https://twitter.com/vboykis) 在 Stack Overflow 撰写的博客文章“[为什么迁移到 Python 3 需要这么长时间?](https://stackoverflow.blog/2019/11/14/why-is-the-migration-to-python-3-taking-so-long/)”,其中她指出了采用 Python 3 缓慢的三个原因。 ### 使用 Python 3 的原因 不管是否有持续的支持,尽快迁移到 Python 3 是一个好主意。Python 3 将继续受到支持,它具有 Python 2 所没有的一些非常优雅的东西。 最近发布的 [Python 3.8](https://www.python.org/downloads/) 包含 [海象运算符](https://docs.python.org/3.8/whatsnew/3.8.html#assignment-expressions)、[位置参数](https://docs.python.org/3.8/whatsnew/3.8.html#positional-only-parameters)和[自描述的格式化字符串](https://docs.python.org/3.8/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging)等[功能](https://docs.python.org/3.8/whatsnew/3.8.html)。Python 3 的早期版本引入的[功能](https://docs.python.org/3.8/whatsnew/index.html),例如 [异步 IO](https://docs.python.org/3.8/library/asyncio.html#module-asyncio)、[格式化字符串](https://docs.python.org/3.7/whatsnew/3.6.html#pep-498-formatted-string-literals)、[类型提示](https://docs.python.org/3.7/whatsnew/3.5.html#pep-484-type-hints) 和 [pathlib](https://docs.python.org/3.8/library/pathlib.html#module-pathlib),这里只提及了一点点。 下载最多的前 360 个软件包[已迁移到 Python 3](http://py3readiness.org/)。你可以使用 [caniusepython3](https://pypi.org/project/caniusepython3/) 软件包检查你的 `requirements.txt` 文件,以查看你依赖的任何软件包是否尚未迁移。 ### 将 Python 2 移植到 Python 3 的参考资源 有许多参考资源可简化你向 Python 3 的迁移。例如,“[将 Python 2 移植到 Python 3 指南](https://docs.python.org/3/howto/pyporting.html)”列出了许多工具和技巧,可帮助你实现与 Python 2/3 单一源代码的兼容性。在 [Python3statement.org](https://python3statement.org/practicalities/) 上也有一些有用的技巧。 [Dustin Ingram](https://twitter.com/di_codes) 和 [Chris Wilcox](https://twitter.com/chriswilcox47) 在 [Cloud Next ‘19](https://www.youtube.com/watch?v=Bye7Rms0Vgw&utm_source=osdc&utm_medium=blog&utm_campaign=pysunset)上作了一个演讲,详细介绍了向 Python 3 过渡的一些动机和迁移模式。[Trey Hunner](https://twitter.com/treyhunner) 在 [PyCon 2018 演讲](https://www.youtube.com/watch?v=klaGx9Q_SOA)上介绍了 Python 3 最有用的功能,鼓励你进行迁移,以便你可以利用它们。 ### 加入我们! 距 2020 年 1 月 1 日仅有几周了。如果你需要每天提醒一下它即将到来的时间(并且你使用 Twitter 的话),请关注 [Python 2 日落倒计时](https://twitter.com/python2sunset) Twitter 机器人。 --- via: <https://opensource.com/article/19/11/end-of-life-python-2> 作者:[Katie McLaughlin](https://opensource.com/users/glasnt) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Python 2.7 will officially become unsupported beginning January 1, 2020. There is one [final bugfix](https://www.python.org/dev/peps/pep-0373/#maintenance-releases) planned after this date, but then that's it. What does this end of life (EOL) mean for you? If you run Python 2, you need to migrate. ## Who decided to EOL Python 2? In [2012](https://github.com/python/peps/commit/a733bc927acbca16bfa3de486fb2c7d3f767a748), the team maintaining the Python programming language reviewed its options. There were two increasingly different codebases, Python 2 and Python 3. Both were popular, but the newer version was not as widely adopted. In addition to Python 3's disruption of changing the underlying way data is handled by completely reworking Unicode support, a major version change allowed non-backward-compatible changes to happen all at once. This decision was documented [in 2006](https://www.python.org/dev/peps/pep-3000/#compatibility-and-transition). To ease the disruption, Python 2 continued to be maintained, with some features backported. To further help the community transition, the EOL date was extended [from 2015 to 2020](https://github.com/python/peps/commit/f82462002b86feff36215b4230be28967039b0cc), another five years. Maintaining divergent codebases was a hassle the team knew it had to resolve. Ultimately, a decision was [announced](https://www.python.org/doc/sunset-python-2/): "We are volunteers who make and take care of the Python programming language. We have decided that January 1, 2020, will be the day that we sunset Python 2. That means that we will not improve it anymore after that day, even if someone finds a security problem in it. You should upgrade to Python 3 as soon as you can." [Nick Coghlan](https://twitter.com/ncoghlan_dev), a core CPython developer and current member of the Python steering council, [adds more information in his blog](http://python-notes.curiousefficiency.org/en/latest/python3/questions_and_answers.html). And [PEP 404](https://www.python.org/dev/peps/pep-0404/), written by [Barry Warsaw](https://twitter.com/pumpichank) (also a member of the Python steering council), details why Python 2.8 will never be a thing. ## Is anyone still supporting Python 2? Support for Python 2 from providers and vendors will vary. [Google Cloud has announced](https://cloud.google.com/python/docs/python2-sunset/?utm_source=osdc&utm_medium=blog&utm_campaign=pysunset) how it plans to support Python 2 going forward. Red Hat has also [announced plans for Red Hat Enterprise Linux (RHEL)](https://access.redhat.com/solutions/4455511), and AWS has announced [minor version update requirements](https://aws.amazon.com/blogs/developer/deprecation-of-python-2-6-and-python-3-3-in-botocore-boto3-and-the-aws-cli/) for the AWS command-line interface and [SDK](https://aws.amazon.com/sdk-for-python/). You can also read the Stack Overflow blog post "[Why is the Migration to Python 3 Taking So Long?](https://stackoverflow.blog/2019/11/14/why-is-the-migration-to-python-3-taking-so-long/)" by [Vicki Boykis](https://twitter.com/vboykis), in which she identifies three reasons why Python 3 adoption is slow. ## Reasons to use Python 3 Regardless of ongoing support, it's a really good idea to migrate to Python 3 as soon as you can. Python 3 will continue to be supported, and it has some really neat things that Python 2 just doesn't have. The recently released [Python 3.8](https://www.python.org/downloads/) includes such [features](https://docs.python.org/3.8/whatsnew/3.8.html) as the [walrus operator](https://docs.python.org/3.8/whatsnew/3.8.html#assignment-expressions), [positional-only parameters](https://docs.python.org/3.8/whatsnew/3.8.html#positional-only-parameters), and [self-documenting f-strings](https://docs.python.org/3.8/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging). Earlier releases of Python 3 introduced [features](https://docs.python.org/3.8/whatsnew/index.html) such as [asyncio](https://docs.python.org/3.8/library/asyncio.html#module-asyncio), [f-strings](https://docs.python.org/3.7/whatsnew/3.6.html#pep-498-formatted-string-literals), [type hints](https://docs.python.org/3.7/whatsnew/3.5.html#pep-484-type-hints), and [pathlib](https://docs.python.org/3.8/library/pathlib.html#module-pathlib), just to name a few. The top 360 most-downloaded packages [have already migrated to Python 3](http://py3readiness.org/). You can check your requirements.txt file using the [caniusepython3](https://pypi.org/project/caniusepython3/) package to see if any packages you depend on haven't yet been migrated. ## Resources for porting Python 2 to Python 3 There are many resources available to ease your migration to Python 3. For example, the [Porting Python 2 to Python 3 guide](https://docs.python.org/3/howto/pyporting.html) lists a bunch of tools and tricks to help you achieve single-source Python 2/3 compatibility. There are also some useful tips on [Python3statement.org](https://python3statement.org/practicalities/). [Dustin Ingram](https://twitter.com/di_codes) and [Chris Wilcox](https://twitter.com/chriswilcox47) gave a [presentation at Cloud Next '19](https://www.youtube.com/watch?v=Bye7Rms0Vgw&utm_source=osdc&utm_medium=blog&utm_campaign=pysunset) detailing some of the motivations and migration patterns for the transition into Python 3. [Trey Hunner](https://twitter.com/treyhunner) gave a [presentation at PyCon 2018](https://www.youtube.com/watch?v=klaGx9Q_SOA) about Python 3's most useful features to encourage you to migrate so you can take advantage of them. ## Join us! January 1, 2020, is now just weeks away. If you need daily reminders of just how soon that is (and you use Twitter), follow the [Countdown to Python 2 sunset](https://twitter.com/python2sunset) Twitter bot. ## 5 Comments
11,631
如何在 Fedora 30 Server 上安装 LEMP(Linux、Nginx、MariaDB、PHP)
https://www.linuxtechi.com/install-lemp-stack-fedora-30-server/
2019-12-01T10:33:00
[ "LEMP" ]
https://linux.cn/article-11631-1.html
在这篇文章中,我们将看看如何在 Fedora 30 Server 上安装 **LEMP** 。LEMP 代表: * L -> Linux * E -> Nginx * M -> Maria DB * P -> PHP 我假设 [Fedora 30](https://www.linuxtechi.com/fedora-30-workstation-installation-guide/) 已经安装在你的电脑系统上。 ![](/data/attachment/album/201912/01/103537wil7hd36dhcxdh03.jpg) LEMP 是一组强大的软件设置集合,它安装在一个 Linux 服务器上以帮助使用流行的开发平台来构建网站,LEMP 是 LAMP 的一个变种,在其中不是 Apache ,而是使用 EngineX(Nginx),此外,使用 MariaDB 代替 MySQL。这篇入门指南是一个安装 Nginx、Maria DB 和 PHP 的独立指南的作品集合。 ### 在 Fedora 30 Server 上安装 Nginx、PHP 7.3 和 PHP-FPM 让我们看看如何在 Fedora 30 Server 上安装 Nginx 和 PHP 以及 PHP FPM。 #### 步骤 1) 切换到 root 用户 在系统上安装 Nginx 的第一步是切换到 root 用户。使用下面的命令: ``` root@linuxtechi ~]$ sudo -i [sudo] password for pkumar: [root@linuxtechi ~]# ``` #### 步骤 2) 使用 dnf 命令安装 Nginx、PHP 7.3 和 PHP FPM 使用下面的 `dnf` 命令安装 Nginx: ``` [root@linuxtechi ~]# dnf install nginx php php-fpm php-common -y ``` #### 步骤 3) 安装额外的 PHP 模块 PHP 的默认安装仅自带基本模块和最需要的模块,如果你需要额外的模块,像 PHP 支持的 GD、XML、命令行接口、Zend OPCache 功能等等,你总是能够选择你的软件包,并一次性安装所有的东西。查看下面的示例命令: ``` [root@linuxtechi ~]# sudo dnf install php-opcache php-pecl-apcu php-cli php-pear php-pdo php-pecl-mongodb php-pecl-redis php-pecl-memcache php-pecl-memcached php-gd php-mbstring php-mcrypt php-xml -y ``` #### 步骤 4) 开始 & 启用 Nginx 和 PHP-fpm 服务 使用下面的命令来开始并启用 Nginx 服务: ``` [root@linuxtechi ~]# systemctl start nginx && systemctl enable nginx Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service. [root@linuxtechi ~]# ``` 使用下面的命令来开始并启用 PHP-FPM 服务: ``` [root@linuxtechi ~]# systemctl start php-fpm && systemctl enable php-fpm Created symlink /etc/systemd/system/multi-user.target.wants/php-fpm.service → /usr/lib/systemd/system/php-fpm.service. [root@linuxtechi ~]# ``` #### 步骤 5) 核实 Nginx (Web 服务) 和 PHP 安装 注意:假使操作系统防火墙是启用的,并运行在你的 Fedora 30 系统上,那么使用下面的命令来准许 80 和 443 端口: ``` [root@linuxtechi ~]# firewall-cmd --permanent --add-service=http success [root@linuxtechi ~]# [root@linuxtechi ~]# firewall-cmd --permanent --add-service=https success [root@linuxtechi ~]# firewall-cmd --reload success [root@linuxtechi ~]# ``` 打开网页浏览器,输入下面的 URL: http:// 。 ![Test-Page-HTTP-Server-Fedora-30](/data/attachment/album/201912/01/103342noldg8rjravdja9y.jpg) 上面的屏幕证实 Nginx 已经成功地安装。 现在,让我们核实 PHP 安装,使用下面的命令创建一个测试 php 页(`info.php`): ``` [root@linuxtechi ~]# echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/info.php [root@linuxtechi ~]# ``` 在网页浏览器中输入下面的 URL, http:///info.php ![Php-info-page-fedora30](/data/attachment/album/201912/01/103403rm25grq1ckmbb06q.jpg) 上面的页面验证 PHP 7.3.5 已经被成功地安装。现在,让我们安装 MariaDB 数据库服务器。 ### 在 Fedora 30 上安装 MariaDB MariaDB 是 MySQL 数据库的一个极好的替代品,因为它的工作方式与 MySQL 非常类似,并且兼容性也与 MySQL 一致。让我们看看在 Fedora 30 Server 上安装 MariaDB 的步骤。 #### 步骤 1) 切换到 root 用户 在系统上安装 MariaDB 的第一步是切换到 root 用户,或者你可以使用有 root 权限的本地用户。使用下面的命令: ``` [root@linuxtechi ~]# sudo -i [root@linuxtechi ~]# ``` #### 步骤 2) 使用 dnf 命令安装 MariaDB(10.3)的最新版本 在 Fedora 30 Server 上使用下面的命令来安装 MariaDB: ``` [root@linuxtechi ~]# dnf install mariadb-server -y ``` #### 步骤 3) 开启并启用 MariaDB 服务 在步骤 2 中成功地安装 MariaDB 后,接下来的步骤是开启 MariaDB 服务。使用下面的命令: ``` [root@linuxtechi ~]# systemctl start mariadb.service ; systemctl enable mariadb.service ``` #### 步骤 4) 保护安装好的 MariaDB 当我们安装 MariaDB 服务器时,因为默认情况下没有 root 密码,在数据库中也会创建匿名用户。因此,要保护安装好的 MariaDB,运行下面的 `mysql_secure_installation` 命令: ``` [root@linuxtechi ~]# mysql_secure_installation ``` 接下来你将被提示一些问题,仅回答下面展示的问题: ![Secure-MariaDB-Installation-Part1](/data/attachment/album/201912/01/103414qgdlw7lch75ggqxy.jpg) ![Secure-MariaDB-Installation-Part2](/data/attachment/album/201912/01/103416uhqsuzsuybgwbjzs.jpg) #### 步骤 5) 测试 MariaDB 安装 在你安装后,你总是能够测试是否 MariaDB 被成功地安装在 Fedora 30 Server 上。使用下面的命令: ``` [root@linuxtechi ~]# mysql -u root -p Enter password: ``` 接下来,你将被提示一个密码。输入在保护安装好的 MariaDB 期间你设置的密码,接下来你可以看到 MariaDB 欢迎屏幕。 ``` Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 17 Server version: 10.3.12-MariaDB MariaDB Server Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> ``` 最后,我们已经在你的 Fedora 30 Server 上成功地完成安装 LEMP(Linux、Nginx、MariaDB 和 PHP)的所有工作。请在下面的反馈部分发布你的评论和建议,我们将尽快在后面回应。 --- via: <https://www.linuxtechi.com/install-lemp-stack-fedora-30-server/> 作者:[Pradeep Kumar](https://www.linuxtechi.com/author/pradeep/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
In this article, we’ll be looking at how to install **LEMP** stack on Fedora 30 Server. LEMP Stands for: - L -> Linux - E -> Nginx - M -> Maria DB - P -> PHP I am assuming ** Fedora 30 **is already installed on your system. LEMP is a collection of powerful software setup that is installed on a Linux server to help in developing popular development platforms to build websites, LEMP is a variation of LAMP wherein instead of **Apache**, **EngineX (Nginx)** is used as well as **MariaDB** used in place of **MySQL**. This how-to guide is a collection of separate guides to install Nginx, Maria DB and PHP. #### Install Nginx, PHP 7.3 and PHP-FPM on Fedora 30 Server Let’s take a look at how to install Nginx and PHP along with PHP FPM on Fedora 30 Server. #### Step 1) Switch to root user First step in installing Nginx in your system is to switch to root user. Use the following command : pkumar@fedora30-server ~]$ sudo -i [sudo] password for pkumar: [root@fedora30-server ~]# #### Step 2) Install Nginx, PHP 7.3 and PHP FPM using dnf command Install Nginx using the following dnf command: [root@fedora30-server ~]# dnf install nginx php php-fpm php-common -y #### Step 3) Install Additional PHP modules The default installation of PHP only comes with the basic and the most needed modules installed. If you need additional modules like GD, XML support for PHP, command line interface Zend OPCache features etc, you can always choose your packages and install everything in one go. See the sample command below: [root@fedora30-server ~]# sudo dnf install php-opcache php-pecl-apcu php-cli php-pear php-pdo php-pecl-mongodb php-pecl-redis php-pecl-memcache php-pecl-memcached php-gd php-mbstring php-mcrypt php-xml -y #### Step 4) Start & Enable Nginx and PHP-fpm Service Start and enable Nginx service using the following command [root@fedora30-server ~]# systemctl start nginx && systemctl enable nginx Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service. [root@fedora30-server ~]# Use the following command to start and enable PHP-FPM service [root@fedora30-server ~]# systemctl start php-fpm && systemctl enable php-fpm Created symlink /etc/systemd/system/multi-user.target.wants/php-fpm.service → /usr/lib/systemd/system/php-fpm.service. [root@fedora30-server ~]# **Verify Nginx (Web Server) and PHP installation,** **Note:** In case OS firewall is enabled and running on your Fedora 30 system, then allow 80 and 443 ports using beneath commands, [root@fedora30-server ~]# firewall-cmd --permanent --add-service=http success [root@fedora30-server ~]# [root@fedora30-server ~]# firewall-cmd --permanent --add-service=https success [root@fedora30-server ~]# firewall-cmd --reload success [root@fedora30-server ~]# Open the web browser, type the following URL: http://<Your-Server-IP> Above screen confirms that NGINX is installed successfully. Now let’s verify PHP installation, create a test php page(info.php) using the beneath command, [root@fedora30-server ~]# echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/info.php [root@fedora30-server ~]# Type the following URL in the web browser, http://<Your-Server-IP>/info.php Above page confirms that PHP 7.3.5 has been installed successfully. Now let’s install MariaDB database server. #### Install MariaDB on Fedora 30 MariaDB is a great replacement for MySQL DB as it is works much similar to MySQL and also compatible with MySQL steps too. Let’s look at the steps to install MariaDB on Fedora 30 Server #### Step 1) Switch to Root User First step in installing MariaDB in your system is to switch to root user or you can use a local user who has root privilege. Use the following command below: [root@fedora30-server ~]# sudo -i [root@fedora30-server ~]# #### Step 2) Install latest version of MariaDB (10.3) using dnf command Use the following command to install MariaDB on Fedora 30 Server [root@fedora30-server ~]# dnf install mariadb-server -y #### Step 3) Start and enable MariaDB Service Once the mariadb is installed successfully in step 2), next step is to start the MariaDB service. Use the following command: [root@fedora30-server ~]# systemctl start mariadb.service ; systemctl enable mariadb.service #### Step 4) Secure MariaDB Installation When we install MariaDB server, so by default there is no root password, also anonymous users are created in database. So, to secure MariaDB installation, run the beneath “mysql_secure_installation” command [root@fedora30-server ~]# mysql_secure_installation Next you will be prompted with some question, just answer the questions as shown below: #### Step 5) Test MariaDB Installation Once you have installed, you can always test if MariaDB is successfully installed on the server. Use the following command: [root@fedora30-server ~]# mysql -u root -p Enter password: Next you will be prompted for a password. Enter the password same password that you have set during MariaDB secure installation, then you can see the MariaDB welcome screen. Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 17 Server version: 10.3.12-MariaDB MariaDB Server Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> And finally, we’ve completed everything to install LEMP (Linux, Nginx, MariaDB and PHP) on your server successfully. Please post all your comments and suggestions in the feedback section below and we’ll respond back at the earliest. Victor BautistaHi, I followed this guide but got a 404 when loading the php.info() script from the browser. This is the error: [crit] 30091#0: *12 connect() to unix:/run/php-fpm/www.sock failed (2: No such file or directory) while connecting to upstream, client: 192.168.0.2, server: _, request: “GET /info.php HTTP/1.1”, upstream: “fastcgi://unix:/run/php-fpm/www.sock:”, host: “192.168.0.142” What am I doing wrong here?
11,632
在 Fedora 上使用 GIMP 轻松编辑图像
https://fedoramagazine.org/edit-images-on-fedora-easily-with-gimp/
2019-12-01T21:44:00
[ "GIMP" ]
https://linux.cn/article-11632-1.html
![](/data/attachment/album/201912/01/214500n2f4c7wxfoa8bfgg.jpg) GIMP(GNU Image Manipulation Program 的缩写)是自由开源的图像处理软件。它有很多的功能,从简单的图像编辑,到复杂的滤镜、脚本,甚至是动画,它是流行的商业同类软件的一款很好的替代品。 继续阅读来学习如何在 Fedora 上安装和使用 GIMP。这篇文章涉及基本的日常图像编辑工作。 ### 安装 GIMP GIMP 在官方 Fedora 存储库中可获得。为安装它,运行: ``` sudo dnf install gimp ``` ### 单窗口模式 在你打开应用程序后,它显示带有工具箱和主编辑区的暗色主题窗口。注意,它有两种窗口模式,你可以通过选择“<ruby> 窗口 <rt> Windows </rt></ruby> -> <ruby> 单窗口模式 <rt> Single Window Mode </rt></ruby>”在其中切换。通过选中这个选项,用户界面的所有组件将显示在单个窗口中。否则,它们将是分离的。 ### 加载图像 ![](/data/attachment/album/201912/01/214501z4zzv59ve5nklewl.png) 为加载图像,转到“<ruby> 文件 <rt> File </rt></ruby> -> <ruby> 打开 <rt> Open </rt></ruby>”,然后选择你的文件并选择你的图像文件。 ### 重新调整一个图像的大小 为重新调整图像大小,你可以基于一对参数重新调整大小,包括像素和百分比 —— 在编辑图像时,这两个参数很方便。 让我们假使我们需要缩小 Fedora 30 背景图像到它当前大小的 75%。为此,选择“<ruby> 图像 <rt> Image </rt></ruby> -> <ruby> 比例 <rt> Scale </rt></ruby>”,然后在比例对话框上,在单位下拉列表中选择“<ruby> 百分比 <rt> percentage </rt></ruby>”。接下来,输入 “75” 作为宽度或高度,然后按 Tab 键。默认情况下,其它尺寸将自动地调整大小,以相应地与更改的尺寸保持纵横比。现在,保存其它选项不变,并按比例。 ![](/data/attachment/album/201912/01/214501mpv1x33myauolyll.png) 该图像缩小到其原始尺寸的 75%。 ### 旋转图像 旋转是一种变换操作,因此,你可以从主菜单下的“<ruby> 图像 <rt> Image </rt></ruby> -> <ruby> 变换 <rt> Transform </rt></ruby>”下找到它,其中有图像旋转 90° 或 180° 的选项。在上述选项下也有垂直或水平翻转图像的选项。 让我们假使我们需要旋转图像 90°。在应用一次 90° 顺时针旋转和水平翻转后,我们的图像将看起来像这样: ![](/data/attachment/album/201912/01/214502dnm95p9oqjcpjnnz.png) ### 添加文本 添加文本非常简单。只需要从工具箱中选择 “A” 图标,然后,在你的图像上,单击你想要添加文本的位置。如果工具箱不可见,从“<ruby> 窗口 <rt> Windows </rt></ruby> -> <ruby> 新建工具箱 <rt> New Toolbox </rt></ruby>”打开它。 当你编辑文本时,你可能注意到,文本对话框有字体自定义选项,包括字体系列、字体大小等等。 ![](/data/attachment/album/201912/01/214503p9gwwgkk113653ow.png) ### 保存和导出 你可以从“<ruby> 文件 <rt> File </rt></ruby> -> <ruby> 保存 <rt> Save </rt></ruby>”或通过按 `Ctrl+S` 来将你的编辑保存为一个带有 `.xcf` 扩展名的 GIMP 工程。或者,你可以导出你的图像,例如,以 PNG 或 JPEG 格式。为导出图像,转到“<ruby> 文件 <rt> File </rt></ruby> -> <ruby> 导出为 <rt> Export As </rt></ruby>”或按 `Ctrl+Shift+E`,接下来,在你面前将产生一个你可以选择输出图像和名称的对话框。 --- via: <https://fedoramagazine.org/edit-images-on-fedora-easily-with-gimp/> 作者:[Mehdi Haghgoo](https://fedoramagazine.org/author/powergame/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
GIMP (short for GNU Image Manipulation Program) is free and open-source image manipulation software. With many capabilities ranging from simple image editing to complex filters, scripting and even animation, it is a good alternative to popular commercial options. Read on to learn how to install and use GIMP on Fedora. This article covers basic daily image editing. ## Installing GIMP GIMP is available in the official Fedora repository. To install it run: sudo dnf install gimp ## Single window mode Once you open the application, it shows you the dark theme window with toolbox and the main editing area. Note that it has two window modes that you can switch between by selecting *Windows* -> *Single Window Mode*. By checking this option all components of the UI are displayed in a single window. Otherwise, they will be separate. ## Loading an image ![Fedora 30 Background](https://fedoramagazine.org/wp-content/uploads/2019/10/Screenshot-from-2019-10-25-11-00-44-300x165.png) To load an image, go to *File* -> *Open* and choose your file and choose your image file. ## Resizing an image To resize the image, you have the option to resize based on a couple of parameters, including pixel and percentage — the two parameters which are often handy in editing images. Let’s say we need to scale down the Fedora 30 background image to 75% of its current size. To do that, select *Image* -> *Scale* and then on the scale dialog, select percentage in the unit drop down. Next, enter *75* as width or height and press the **Tab** key. By default, the other dimension will automatically resize in correspondence with the changed dimension to preserve aspect ratio. For now, leave other options unchanged and press Scale. ![Scale Dialog In GIMP](https://fedoramagazine.org/wp-content/uploads/2019/10/Screenshot-from-2019-10-25-11-17-33-300x262.png) The image scales to 0.75 percent of its original size. ## Rotating images Rotating is a transform operation, so you find it under *Image* -> *Transform* from the main menu, where there are options to rotate the image by 90 or 180 degrees. There are also options for flipping the image vertically or horizontally under the mentioned option. Let’s say we need to rotate the image 90 degrees. After applying a 90-degree clockwise rotation and horizontal flip, our image will look like this: ![](https://fedoramagazine.org/wp-content/uploads/2019/10/Screenshot-from-2019-10-25-11-41-28-300x243.png) ![](https://fedoramagazine.org/wp-content/uploads/2019/10/Screenshot-from-2019-10-25-11-41-28-300x243.png) ## Adding text Adding text is very easy. Just select the A icon from the toolbox, and click on a point on your image where you want to add the text. If the toolbox is not visible, open it from Windows->New Toolbox. As you edit the text, you might notice that the text dialog has font customization options including font family, font size, etc. ![Add Text To Images](https://fedoramagazine.org/wp-content/uploads/2019/10/Screenshot-from-2019-10-25-11-47-54-300x237.png) ## Saving and exporting You can save your edit as as a GIMP project with the *xcf* extension from *File* -> *Save* or by pressing **Ctrl+S**. Or you can export your image in formats such as PNG or JPEG. To export, go to *File* -> *Export As* or hit **Ctrl+Shift+E** and you will be presented with a dialog where you can select the output image and name. ## tom As a long term Gimp user i can recommend the multi window view, espacially on a two monitor setup where i can put combined toolbox on the secondary screen. Also if one would like to go in deep with the Gimp there is https://www.gimpusers.com/ which serves news arround Gimp as well as a lot professional tutorials. ## Tim Thank you! I had no idea that website existed until now. I will definitely be using it. ## nicu Also a long time professional Gimp user, I use multi window view on the desktop, but when have to do some work on a tiny 10″ portable, go with the single view. Multi window allows you to make better use of the screen space while the single window is less scarry for newcomers. ## hammerhead corvette I had no clue about the gimpusers website. Thanks ## Tao There’s also an upcoming fork with a new name: https://github.com/glimpse-editor/Glimpse GIMP is great software, but a common problem is that FLOSS advocates have a hard time getting it to gain traction in their workplace — because of the name! ## Silvia To be honest, so far I’ve been told many things, mostly in comparison to Photoshop, but not one person pointed to the name being an issue. ## Seoc McPherson I’ve never had an issue suggesting GIMP at work. I don’t see how it’s useful to waste effort attempting to rebrand something that is already so well established. ## Redlove Thanks 🌸 ## Fedora User Open Source GIMP, Krita, Inkscape, sK1, Scribus has Replaced Adobe, Corel, Microsoft & Apple for me as a designer with the Fedora Design Suite! Keep up the good work 8) ## Rene Reichenbach Dont forget about Darktable another gem to be used alongside. ## ewtger4 convert are faster better show script in gimp ## hammerhead corvette I’d like to see a simple way to include arrows and highlights on screenshots, kind of like sketch (MacOS) as I have not found a simple way of doing so on Linux. ## Jonatas Esteves Flameshot is in every distro and does just that: https://github.com/lupoDharkael/flameshot ## hammerhead corvette OMG ! I love you for that ! Thank you !!! ## Craig Parker Wow. I’ve been monkeying with GIMP to do this and never knew that there was a better app for editing screenshots all along. Thanks Jonatas! ## New Path GIMP also offers a scripting language, Script-Fu (https://www.gimp.org/tutorials/Basic_Scheme/), that can be used to create new neat effects or automate pre-defined routines that needs to be applied to many images! ## Joe I did a video tutorial about Gimp and a lot of other Linux stuff. Sorry the video is using LinuxMint, but I also love Fedora. https://opensourcetechtrn.blogspot.com/
11,633
如何在 CentOS 8/RHEL 8 上安装 Ansible(自动化工具)
https://www.linuxtechi.com/install-ansible-centos-8-rhel-8/
2019-12-01T22:32:00
[ "Ansible" ]
https://linux.cn/article-11633-1.html
Ansible 是给 Linux 系统管理员使用的出色自动化工具。它是一种开源配置工具,能让系统管理员可以从一个中心节点(即 Ansible 服务器)管理数百台服务器。将 Ansible 与 Puppet、Chef 和 Salt 等类似工具进行比较时,它是首选的配置工具,因为它不需要任何代理,并且可以工作在 SSH 和 python 上。 ![](/data/attachment/album/201912/01/223012czkxt6dhku6snhxn.jpg) 在本教程中,我们将学习如何在 CentOS 8 和 RHEL 8 系统上安装和使用 Ansble。 Ansible 实验环境信息: * 最小化安装的 CentOS 8 / RHEL 8 服务器(192.168.1.10),且有互联网连接 * 两个 Ansible 节点 - Ubuntu 18.04 LTS (192.168.1.20) 和 CentOS 7 (192.168.1.30) ### CentOS 8 上的 Ansible 安装步骤 Ansible 包不在 CentOS 8 默认的软件包仓库中。因此,我们需要执行以下命令启用 [EPEL 仓库](http://www.linuxtechi.com/enable-epel-repo-centos8-rhel8-server/): ``` [root@linuxtechi ~]$ sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y ``` 启用 epel 仓库后,执行以下 `dnf` 命令安装 Ansible: ``` [root@linuxtechi ~]$ sudo dnf install ansible ``` 上面命令的输出: ![dnf-install-ansible-centos8](/data/attachment/album/201912/01/223311mst7fkd7zdzbal1k.png) 成功安装 Ansible 后,运行以下命令验证它的版本: ``` [root@linuxtechi ~]$ sudo ansible --version ``` ![Ansible-version-CentOS8](/data/attachment/album/201912/01/223217dcl38elkc3sy8338.png) 上面的输出确认在 CentOS 8 上安装完成。 让我们看下 RHEL 8 系统。 ### RHEL 8 上的 Ansible 安装步骤 如果你有有效的 RHEL 8 订阅,请使用以下订阅管理器命令启用 Ansble 仓库: ``` [root@linuxtechi ~]$ sudo subscription-manager repos --enable ansible-2.8-for-rhel-8-x86_64-rpms ``` 启用仓库后,执行以下 `dnf` 命令安装 Ansible: ``` [root@linuxtechi ~]$ sudo dnf install ansible -y ``` 安装 Ansible 及其依赖包后,执行以下命令来验证它的版本: ``` [root@linuxtechi ~]$ sudo ansible --version ``` ### 在 CentOS 8 / RHEL 8 上通过 pip3 安装 Ansible 的可选方法 如果你希望使用 `pip`(Python 的包管理器)安装 Ansible,请首先使用以下命令安装 pyhton3 和 python3-pip 包: ``` [root@linuxtechi ~]$ sudo dnf install python3 python3-pip -y ``` 安装 python3 后,运行以下命令来验证它的版本: ``` [root@linuxtechi ~]$ python3 -V Python 3.6.8 [root@linuxtechi ~]$ ``` 用下面的 `pip3` 命令安装 Ansible: ``` [root@linuxtechi ~]$ pip3 install ansible --user ``` 输出: ![Ansible-Install-pip3-centos8](/data/attachment/album/201912/01/223225qkdkahlad2wwihww.png) 上面的输出确认 Ansible 已成功使用 `pip3` 安装。让我们看下如何使用 Ansible。 ### 如何使用 Ansible 自动化工具? 当我们使用 `yum` 或 `dnf` 命令安装 Ansible 时,它的配置文件、清单文件和角色目录会自动在 `/etc/ansible` 文件夹下创建。 让我们添加一个名称为 `labservers` 的组,并在 `/etc/ansible/hosts` 文件中给该组添加上述的 Ubuntu 18.04 和 CentOS 7 系统的 IP 地址: ``` [root@linuxtechi ~]$ sudo vi /etc/ansible/hosts … [labservers] 192.168.1.20 192.168.1.30 … ``` 保存并退出文件。 更新清单文件(`/etc/ansible/hosts`)后,将用户的 ssh 公钥放到属于 `labservers` 组的远程系统。 让我们首先使用 `ssh-keygen` 命令生成本地用户的公钥和私钥: ``` [root@linuxtechi ~]$ ssh-keygen ``` 现在使用以下命令在 Ansible 服务器及其客户端之间交换公钥: ``` [root@linuxtechi ~]$ ssh-copy-id root@linuxtechi [root@linuxtechi ~]$ ssh-copy-id root@linuxtechi ``` 现在,让我们尝试几个 Ansible 命令,首先使用 `ping` 模块验证 Ansible 服务器与客户端的连接: ``` [root@linuxtechi ~]$ ansible -m ping "labservers" ``` 注意: 如果我们没有在上面的命令中指定清单文件,那么它将引用默认主机文件(即 `/etc/ansible/hosts`)。 输出: ![ansible-ping-module-centos8](/data/attachment/album/201912/01/223237o7i9j03gjim39emh.png) 让我们使用 Ansible shell 命令检查每个客户端的内核版本: ``` [root@linuxtechi ~]$ ansible -m command -a "uname -r" "labservers" 192.168.1.30 | CHANGED | rc=0 >> 4.15.0-20-generic 192.168.1.20 | CHANGED | rc=0 >> 3.10.0-327.el7.x86_64 [root@linuxtechi ~]$ ``` 使用以下命令列出清单文件中的所有主机: ``` [root@linuxtechi ~]$ ansible all -i /etc/ansible/hosts --list-hosts hosts (4): 192.168.100.1 192.168.100.10 192.168.1.20 192.168.1.30 [root@linuxtechi ~]$ ``` 使用以下 Ansible 命令仅列出 `labservers` 组中的主机: ``` root@linuxtechi ~]$ ansible labservers -i /etc/ansible/hosts --list-hosts hosts (2): 192.168.1.20 192.168.1.30 [root@linuxtechi ~]$ ``` 本文就是这些了,我们成功演示了如何在 CentOS 8 和 RHEL 8 系统中安装和使用 Ansible。请分享你的反馈和意见。 --- via: <https://www.linuxtechi.com/install-ansible-centos-8-rhel-8/> 作者:[Pradeep Kumar](https://www.linuxtechi.com/author/pradeep/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
**Ansible** is an awesome automation tool for Linux sysadmins. It is an open source configuration tool which allows sysadmins to manage hundreds of servers from one centralize node i.e** Ansible Server**. Ansible is the preferred configuration tool when it is compared with similar tools like **Puppet**, **Chef** and **Salt** because it doesn’t need any agent and it works on SSH and python. In this tutorial we will learn how to install and use Ansible on CentOS 8 and RHEL 8 system Ansible Lab Details: - Minimal CentOS 8 / RHEL 8 Server (192.168.1.10) with Internet Connectivity - Two Ansible Nodes – Ubuntu 18.04 LTS (192.168.1.20) & CentOS 7 (192.168.1.30) #### Ansible Installation steps on CentOS 8 Ansible package is not available in default CentOS 8 package repository. so we need to enable [EPEL Repository](https://www.linuxtechi.com/enable-epel-repo-centos8-rhel8-server/) by executing the following command, [pkumar@linuxtechi ~]$ sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y Once the epel repository is enabled, execute the following dnf command to install Ansible [pkumar@linuxtechi ~]$ sudo dnf install ansible Output of above command : Once the ansible is installed successfully, verify its version by running the following command [pkumar@linuxtechi ~]$ sudo ansible --version Above output confirms that Installation is completed successfully on CentOS 8. Let’s move to RHEL 8 system #### Ansible Installation steps on RHEL 8 If you have a valid RHEL 8 subscription then use following subscription-manager command to enable Ansible Repo, [pkumar@linuxtechi ~]$ sudo subscription-manager repos --enable ansible-2.8-for-rhel-8-x86_64-rpms Once the repo is enabled then execute the following dnf command to install Ansible, [pkumar@linuxtechi ~]$ sudo dnf install ansible -y Once the ansible and its dependent packages are installed then verify ansible version by executing the following command, [pkumar@linuxtechi ~]$ sudo ansible --version #### Alternate Way to Install Ansible via pip3 on CentOS 8 / RHEL 8 If you wish to install Ansible using **pip** (**python’s package manager**) then first install pyhton3 and python3-pip packages using following command, [pkumar@linuxtechi ~]$ sudo dnf install python3 python3-pip -y After pyhthon3 installation, verify its version by running [pkumar@linuxtechi ~]$ python3 -V Python 3.6.8 [pkumar@linuxtechi ~]$ Now run below pip3 command to install Ansible, [pkumar@linuxtechi ~]$ pip3 install ansible --user Output, Above output confirms that Ansible has been installed successfully using pip3. Let’s see how we can use Ansible #### How to Use Ansible Automation Tool? When we install Ansible using yum or dnf command then its configuration file, inventory file and roles directory created automatically under /etc/ansible folder. So, let’s add a group with name “**labservers**” and under this group add ubuntu 18.04 and CentOS 7 System’s ip address in **/etc/ansible/hosts** file [pkumar@linuxtechi ~]$ sudo vi /etc/ansible/hosts … [labservers] 192.168.1.20 192.168.1.30 … Save & exit file. Once the inventory file (/etc/ansible/hosts) is updated then exchange your user’s ssh public keys with remote systems which are part of “labservers” group. Let’s first generate your local user’s public and private key using ssh-keygen command, [pkumar@linuxtechi ~]$ ssh-keygen Now exchange public key between the ansible server and its clients using the following command, [pkumar@linuxtechi ~]$ ssh-copy-id[[email protected]][pkumar@linuxtechi ~]$ ssh-copy-id[[email protected]] Now let’s try couple of Ansible commands, first verify the connectivity from Ansible server to its clients using ping module, [pkumar@linuxtechi ~]$ ansible -m ping "labservers" **Note:** If we don’t specify the inventory file in above command then it will refer the default hosts file (i.e /etc/ansible/hosts) Output, Let’s check kernel version of each client using Ansible shell command, [pkumar@linuxtechi ~]$ ansible -m command -a "uname -r" "labservers" 192.168.1.30 | CHANGED | rc=0 >> 4.15.0-20-generic 192.168.1.20 | CHANGED | rc=0 >> 3.10.0-327.el7.x86_64 [pkumar@linuxtechi ~]$ Use the following ansible command to list all hosts from the inventory file, [pkumar@linuxtechi ~]$ ansible all -i /etc/ansible/hosts --list-hosts hosts (4): 192.168.100.1 192.168.100.10 192.168.1.20 192.168.1.30 [pkumar@linuxtechi ~]$ Use the following ansible command to list only hosts from “labservers” group pkumar@linuxtechi ~]$ ansible labservers -i /etc/ansible/hosts --list-hosts hosts (2): 192.168.1.20 192.168.1.30 [pkumar@linuxtechi ~]$ That’s all from this article, we have successfully demonstrated on how to install and use Ansible on CentOS 8 and RHEL 8 System. Please do you share your feedback and comments. **Read Also** : [How to Install Ansible AWX with Docker-Compose on CentOS 8](https://www.linuxtechi.com/install-ansible-awx-docker-compose-centos-8/) **Read Also** : [How to Manage Remote Windows Host using Ansible](https://www.linuxtechi.com/manage-windows-host-using-ansible/) huynhHi, Very nice, i had successfully configuration Ansible on a CentOS8 exactely as showed in this helpful support. Many thanks to you
11,635
Linux 资深用户的 6 大特征
https://opensource.com/article/19/10/signs-linux-user
2019-12-02T09:34:25
[ "Linux" ]
https://linux.cn/article-11635-1.html
> > 如果你是 Linux 资深用户,则可能会有这些共同倾向。 > > > ![](/data/attachment/album/201912/02/093348ek4jcyvj4wahytwq.jpg) Linux 用户千差万别,但是我们许多人都有一些相同的习惯。你可能没有本文列出的任何特征,而且如果你是个 Linux 新用户,你可能还不能理解这些特征…… 下面是你可能是 Linux 用户的六个特征。 ### 1、理所当然,纪元始于 1970 年 1 月 1 日 关于 Unix 计算机时钟为何在重置时总是将其设置回 1970-01-01 的传闻有很多。但有点令人感到乏味的事实是,Unix “纪元”是用于同步的通用且简单的参考点。例如,万圣节在儒略历中是今年的 304 日,但我们通常将该节日称为 “31 号”。我们知道指的是哪个月的 31 号,因为我们有个共同的参考点:我们知道万圣节在 10 月庆祝,而 10 月是一年中的第十个月,并且我们知道前面每一个月包含多少天。没有这些值,虽然我们可以使用传统的计时方法(如月相)来跟踪特殊的季节性事件,但是计算机显然不具备这种能力。 计算机需要确定且明确定义的值,因此将值 `1970-01-01T00:00:00Z` 选择为 Unix 纪元的开始。每当 [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) 计算机的时间不准确时,诸如网络时间协议(NTP)之类的服务就可以向其提供自 `1970-01-01T00:00:00Z` 以来的秒数,计算机可以将其转换为人类易于识别的日期。 日期和时间是在计算中要追踪的著名的复杂事物,主要是因为几乎所有标准都有例外。一个月并不总是有 30 天,一年也不总是有 365 天,甚至每年有多少秒钟也往往会有所不同。如果你正在寻找一个有趣而令人沮丧的编程练习,那么请尝试编程一个可靠的日历应用程序! ### 2、输入超过两个字母你就会觉得麻烦 众所周知,最常见的 Unix 命令都超简短。除了 `cd`、`ls` 和 `mv` 之类的命令外,还有一个命令简直不能再短了:`w`(它根据 `/var/run/utmp` 文件显示当前谁登录了)。 一方面,极短的命令似乎很不直观。新用户可能不会猜测到键入 `ls` 会<ruby> 列出 <rt> list </rt></ruby>目录。但是,一旦学习命令,它们肯定是越短越好。如果你整天都在终端上度过,那么你键入的击键次数越少就意味着你可以有更多的时间来完成工作。 幸运的是,单字母命令并不太多,因此你可以使用大多数字母作为别名。例如,我经常使用 Emacs,以至于我觉得 `emacs` 的输入时间太长,因此通过将下面这行添加到 `.bashrc` 文件中,将其别名为 `e`: ``` alias e='emacs' ``` 你也可以临时为命令添加别名。例如,如果你在解决网络问题时发现自己反复运行 [firewall-cmd](https://opensource.com/article/19/7/make-linux-stronger-firewalls),则可以为当前会话创建别名: ``` $ alias f='firewall-cmd' $ f usage: see firewall-cmd man page No option specified. ``` 只要你打开着终端,你的别名就会一直存在。当终端一旦关闭,它便会被遗忘。 ### 3、做任何事都不应该单击两次以上 Linux 用户喜欢效率。尽管并非每个 Linux 用户都总是急于完成工作,但 Linux 桌面中有一些旨在减少完成任务所需的操作数量的惯例。这里有些例子。 * 在 KDE 文件管理器 Dolphin 中,单击即可打开文件或目录。假定如果要选择一个文件,则可以单击并拖动,也可以 `Ctrl + 点击`。这可能会使习惯于双击所有内容的用户感到困惑,但是一旦你尝试了单击操作,通常就无法返回费力的双击操作。 * 在大多数 Linux 桌面上,单击鼠标中键可粘贴剪贴板的最新内容。 * 在许多 Linux 桌面上,可以通过按 `Alt`、`Ctrl` 或 `Shift` 键来修改拖动动作。例如,`Alt + 拖动` 在 KDE 中移动窗口,而 GNOME 中的 `Ctrl + 拖动` 会复制文件而不是移动。 ### 4、任何操作你都不会执行三次以上,因为第三次时你已经将它自动化了 请原谅我有点夸张,但是许多 Linux 用户期望他们的计算机比他们更努力地工作。虽然学习如何自动执行常见任务需要花费时间,但在 Linux 上它往往比在其它平台上更容易,因为 Linux 终端和 Linux 操作系统是如此紧密地集成在一起。最容易自动化的是你在终端中已经执行的操作,因为命令只是你在解释器中键入的字符串,而该解释器(终端)不会在乎你是手动键入字符串还是将其指向一个脚本。 例如,如果你发现自己经常将一组文件从一个位置移动到另一个位置,则或许可以将相同的指令序列用作一个脚本,你可以使用单个命令来触发该脚本。假设你每天早上手动执行此操作: ``` $ cd Documents $ trash reports-latest.txt $ wget myserver.local/reports/daily/report-latest.txt $ cp report-latest.txt reports_daily/2019-31-10.log ``` 这是一个简单的序列,但是每天重复一次并不是消磨时间的最有效方法。做一点点抽象,你可以使用一个简单的脚本将其自动化: ``` #!/bin/sh trash $HOME/Documents/reports-latest.txt wget myserver.local/reports/daily/report-latest.txt \ -P $HOME/Documents/udpates_daily/`date --iso-8601`.log cp $HOME/Documents/udpates_daily/`date --iso-8601`.log \ $HOME/Documents/reports-latest.txt ``` 你可以把你的脚本叫做 `get-reports.sh` 并在每天早晨手动启动它,或者甚至可以将其输入到 crontab 中,以便计算机可以执行此任务而无需你进行任何干预。 对于新用户来说,这可能会有点困扰,因为什么和什么是一体的并不总是很明显。例如,如果你经常发现自己打开图像并将其按比例缩小 50%,那么你可能习惯于执行以下操作: 1. 打开你的照片查看器或编辑器 2. 缩放图像 3. 将图像导出为修改后的文件 4. 关闭应用程序 如果你一天要做几次,你可能会对这种重复感到厌倦。但是,由于你是在图形用户界面(GUI)中执行这些操作的,因此你需要知道如何对 GUI 编写脚本以使其自动化。某些应用程序,例如 [GIMP](https://www.gimp.org/),具有丰富的脚本接口,但是其过程显然不同于仅修改一堆命令并将其存储到文件中那么简单。 再说一次,有时在命令行中有与你在 GUI 中所做的等效的操作。将文档从一种文本格式转换为另一种格式可以使用 [Pandoc](https://opensource.com/article/19/5/convert-markdown-to-word-pandoc),处理图像可以使用 [Image Magick](https://opensource.com/article/17/8/imagemagick),音乐和视频也可以通过命令行进行编辑和转换,等等。最大的问题是你需要知道要查找什么,通常是学习新的(有时是复杂的)命令。但是,在终端中按比例缩小图像比在 GUI 中显然更简单: ``` #!/bin/sh convert "${1}" -scale 50% `basename "${1}" .jpg`_50.jpg ``` 这些麻烦、重复的任务值得研究。你永远不知道你的工作让计算机做起来是有多么的简单和快捷! ### 5、发行版之间跳来跳去 我在家里是一个热情的 Slackware 用户,而在工作时是一个 RHEL 用户。实际上,这不是事实,我现在在工作时是 Fedora 用户。除了有时候我使用 CentOS,偶尔我还会运行 [Mageia](http://mageia.org)。 ![Debian on a PowerPC64 box, image CC BY SA Claudio Miranda](/data/attachment/album/201912/02/093429jvh9lni6xzhlxyih.png "Debian on a PowerPC64 box") *运行在 PowerPC64 机器上的 Debian* 发行版好不好无关紧要,成为 Linux 用户的极致乐趣之一是可以自由决定运行哪个发行版。乍一看,它们基本相同,令人耳目一新。但是根据你的心情,你可能更喜欢 CentOS 的稳定性而不是 Fedora 的不断更新,或者你可能有一天会真正享受 Mageia 的集中控制中心,然后又对原始的 [Debian](http://debian.org) 配置文件进行模块化乐在其中,而有时你又会完全转向其他操作系统。 ![OpenBSD, image CC BY SA Claudio Miranda](/data/attachment/album/201912/02/093431s6mcefaau91qezme.jpg "OpenBSD") *OpenBSD,不是 Linux 发行版* 关键是,Linux 发行版是激情项目,成为其他人的开源激情的一部分很有趣。 ### 6、你对开源充满热情 无论你的经验如何,如果你是 Linux 用户,那么你无疑会对开源充满热情。无论你是每天通过[共创艺术品](http://freesvg.org)还是代码来表达你的热情,还是将其升华到只在自由而自在的环境中完成工作,你都生活并构筑于开源之上。因为有了千千万万个你,所以有了开源社区,社区因你而变得更加丰富。 有太多的东西我没有提到。作为 Linux 用户,还有什么可以出卖你的身份?让我们在评论中知道! --- via: <https://opensource.com/article/19/10/signs-linux-user> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Linux users are a diverse bunch, but many of us share a few habits. You might not have any of the telltale signs listed in this article, and if you're a new Linux user, you may not recognize many of them... yet. Here are six signs you might be a Linux user. ## 1. As far as you know, the world began on January 1, 1970. There are many rumors about why a Unix computer clock always sets itself back to 1970-01-01 when it resets. But the mundane truth is that the Unix "epoch" serves as a common and simple reference point for synchronization. For example, Halloween is the 304th day of this year in the Julian calendar, but we commonly refer to the holiday as being "on the 31st". We know which 31st we mean because we have common reference points: We know that Halloween is celebrated in October and that October is the 10th month of the year, and we know how many days each preceding month contains. Without these values, we could use traditional methods of timekeeping, such as phases of the moon, to keep track of special seasonal events, but of course, a computer doesn't have that ability. A computer requires firm and clearly defined values, so the value 1970-01-01T00:00:00Z was chosen as the beginning of the Unix epoch. Any time a [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) computer loses track of time, a service like the Network Time Protocol (NTP) can provide it the number of seconds since 1970-01-01T00:00:00Z, which the computer can convert to a human-friendly date. Date and time are a famously complex thing to track in computing, largely because there are exceptions to nearly standard. A month doesn't always have 30 days, a year doesn't always have 365 days, and even seconds tend to drift a little each year. If you're looking for a fun and frustrating programming exercise, try to program a reliable calendaring application! ## 2. You think it's a chore to type anything over two letters to get something done. The most common Unix commands are famously short. In addition to commands like **cd** and **ls** and **mv**, there's one command that literally can't get any shorter: **w** (which shows who is currently logged in according to the **/var/run/utmp** file). On the one hand, extremely short commands seem unintuitive. A new user probably isn't going to guess that typing **ls** would *list* directories. Once you learn the commands, though, the shorter they are, the better. If you spend all day in a terminal, the fewer keystrokes you have to type means you can spend more time getting your work done. Luckily, single-letter commands are far and few between, which means you can use most letters for aliases. For example, I use Emacs often enough that I consider **emacs** too long to type, so I alias it to **e** by adding this line to my **.bashrc** file: `alias e='emacs'` You can also alias commands temporarily. For instance, if you find yourself running [firewall-cmd](https://opensource.com/article/19/7/make-linux-stronger-firewalls) repeatedly while you troubleshoot a network issue, then you can create an alias just for your current session: ``` $ alias f='firewall-cmd' $ f usage: see firewall-cmd man page No option specified. ``` As long as the terminal is open, your alias persists. Once the terminal is closed, it's forgotten. ## 3. You think it's a chore to click more than two times to get something done. Linux users are fond of efficiency. While not every Linux user is always in a hurry to get things done, there are conventions in Linux desktops that seek to reduce the number of actions required to accomplish any given task. Here are some examples. - In the KDE file manager Dolphin, a single click opens a file or directory. It's assumed that if you want to select a file, you can either click and drag or else Ctrl+Click instead. This may confuse users who are used to double-clicking everything, but once you've tried single-click actions, you usually can't go back to laborious double-clicks. - On most Linux desktops, a middle-click pastes the most recent contents of the clipboard. - On many Linux desktops, drag actions can be modified by pressing the Alt, Ctrl, or Shift keys. For instance, Alt+Drag moves a window in KDE, and Ctrl+Drag in GNOME causes a file to be copied instead of moved. ## 4. You've never performed any action on a computer more than three times because you've already automated it by the third time. Pardon the hyperbole, but many Linux users expect their computer to work harder than they do. While it takes time to learn how to automate common tasks, it tends to be easier on Linux than on other platforms because the Linux terminal and the Linux operating system are so tightly integrated. The easy things to automate are the actions you already do in a terminal because commands are just strings that you type into an interpreter, and that interpreter (the shell running in the terminal) doesn't care whether you typed the strings out manually or whether you're just pointing it to a script. For instance, if you find yourself frequently moving a set of files from one place to another, then you can probably use the same sequence of instructions as a script, which you can trigger with a single command. Imagine you are doing this manually each morning: ``` $ cd Documents $ trash reports-latest.txt $ wget myserver.local/reports/daily/report-latest.txt $ cp report-latest.txt reports_daily/2019-31-10.log ``` It's a simple sequence, but repeating it daily isn't the most efficient way of spending your time. With a little bit of abstraction, you could automate it with a simple script: ``` #!/bin/sh trash $HOME/Documents/reports-latest.txt wget myserver.local/reports/daily/report-latest.txt \ -P $HOME/Documents/udpates_daily/`date --iso-8601`.log cp $HOME/Documents/udpates_daily/`date --iso-8601`.log \ $HOME/Documents/reports-latest.txt ``` You could call your script **get-reports.sh** and launch it manually each morning, or you could even enter it into your crontab so that your computer performs the task without requiring any intervention from you. This can be confusing for a new user because it's not always obvious what's integrated with what. For instance, if you regularly find yourself opening images and scaling them down by 50%, then you're probably used to doing something like this: - Opening up your photo viewer or editor - Scaling the image - Exporting the image as a modified file - Closing the application If you did this several times a day, you would probably get tired of the repetition. However, because you perform those actions in the graphical user interface (GUI), you would need to know how to script the GUI to automate it. Some applications, like [GIMP](https://www.gimp.org/), have a rich scripting interface, but the process is obviously different than just adapting a bunch of commands and dumping those into a file. Then again, sometimes there are command-line equivalents to things you do in a GUI. Converting documents from one text format to another can be done with [Pandoc](https://opensource.com/article/19/5/convert-markdown-to-word-pandoc), images can be manipulated with [Image Magick](https://opensource.com/article/17/8/imagemagick), music and video can be edited and converted, and so on. It's a matter of knowing what to look for, and usually learning a new (and sometimes complex) command. Scaling images down, however, is notably simpler in the terminal than in a GUI: ``` #!/bin/sh convert "${1}" -scale 50% `basename "${1}" .jpg`_50.jpg ``` It's worth investigating those bothersome, repetitious tasks. You never know how simple and fast your work is for a computer to do! ## 5. You distro hop I'm an ardent Slackware user at home and a RHEL user at work. Actually, that's not true; I'm a Fedora user at work now. Except when I use CentOS. And there was that time I ran [Mageia](http://mageia.org) for a while. ![Debian on a PowerPC64 box Debian on a PowerPC64 box, image CC BY SA Claudio Miranda](https://opensource.com/sites/default/files/uploads/debian.png) Debian on a PowerPC64 box It doesn't matter how great a distribution is; part of the guilty pleasure of being a Linux user is the freedom to be indecisive about which distro you run. At a glance, they're all basically the same, and that's refreshing. But depending on your mood, you might prefer the stability of CentOS to the constant updates of Fedora, or you might truly enjoy the centralized control center of Mageia one day and then frolic in the modularity of raw [Debian](http://debian.org) configuration files another. And sometimes you turn to an alternate OS altogether. ![OpenBSD OpenBSD, image CC BY SA Claudio Miranda](https://opensource.com/sites/default/files/uploads/openbsd.jpg) OpenBSD, not a Linux distro The point is, Linux distributions are passion projects, and it's fun to be a part of other people's open source passions. ## 6. You have a passion for open source. Regardless of your experience, if you're a Linux user, you undoubtedly have a passion for open source. Whether you express that on a daily basis through [Creative Commons artwork](http://freesvg.org) or code or you sublimate it and just get your work done in a liberating (and liberated) environment, you're living in and building upon open source. It's because of you that there's an open source community, and the community is richer for having you as a member. There are lots of things I haven't mentioned. What else betrays you as a Linux user? Let us know in the comments! ## 22 Comments
11,636
在 awk 中怎么使用循环
https://opensource.com/article/19/11/loops-awk
2019-12-02T23:31:45
[ "awk" ]
https://linux.cn/article-11636-1.html
> > 来学习一下多次执行同一条命令的不同类型的循环。 > > > ![](/data/attachment/album/201912/02/232951h3ibohlh77bk77d7.jpg) `awk` 脚本有三个主要部分:`BEGIN` 和 `END` 函数(都可选),用户自己写的每次要执行的函数。某种程度上,`awk` 的主体部分就是一个循环,因为函数中的命令对每一条记录都会执行一次。然而,有时你希望对于一条记录执行多次命令,那么你就需要用到循环。 有多种类型的循环,分别适合不同的场景。 ### while 循环 一个 `while` 循环检测一个表达式,如果表达式为 `true` 就执行命令。当表达式变为 `false` 时,循环中断。 ``` #!/bin/awk -f BEGIN { # Loop through 1 to 10 i=1; while (i <= 10) { print i, " to the second power is ", i*i; i = i+1; } exit; } ``` 在这个简单实例中,`awk` 打印了放在变量 `i` 中的整数值的平方。`while (i <= 10)` 语句告诉 `awk` 仅在 `i` 的值小于或等于 10 时才执行循环。在循环最后一次执行时(`i` 的值是 10),循环终止。 ### do-while 循环 do-while 循环执行在关键字 `do` 之后的命令。在每次循环结束时检测一个测试表达式来决定是否终止循环。仅在测试表达式返回 `true` 时才会重复执行命令(即还没有到终止循环的条件)。如果测试表达式返回 `false`,因为到了终止循环的条件所以循环被终止。 ``` #!/usr/bin/awk -f BEGIN { i=2; do { print i, " to the second power is ", i*i; i = i + 1 } while (i < 10) exit; } ``` ### for 循环 `awk` 中有两种 `for` 循环。 一种 `for` 循环初始化一个变量,检测一个测试表达式,执行变量递增,当表达式的结果为 `true` 时循环就会一直执行。 ``` #!/bin/awk -f BEGIN { for (i=1; i <= 10; i++) { print i, " to the second power is ", i*i; } exit; } ``` 另一种 `for` 循环设置一个有连续索引的数组变量,对每一个索引执行一个命令集。换句话说,它用一个数组“收集”每一条命令执行后的结果。 本例实现了一个简易版的 Unix 命令 `uniq`。通过把一系列字符串作为键加到数组 `a` 中,当相同的键再次出现时就增加键值,可以得到某个字符串出现的次数(就像 `uniq` 的 `--count` 选项)。如果你打印该数组的所有键,将会得到出现过的所有字符串。 用演示文件 `colours.txt`(前一篇文章中的文件)来举例: ``` name color amount apple red 4 banana yellow 6 raspberry red 99 strawberry red 3 grape purple 10 apple green 8 plum purple 2 kiwi brown 4 potato brown 9 pineapple yellow 5 ``` 这是 `awk` 版的简易 `uniq -c`: ``` #! /usr/bin/awk -f NR != 1 { a[$2]++ } END { for (key in a) { print a[key] " " key } } ``` 示例数据文件的第三列是第一列列出的条目的计数。你可以用一个数组和 `for` 循环来按颜色统计第三列的条目。 ``` #! /usr/bin/awk -f BEGIN { FS=" "; OFS="\t"; print("color\tsum"); } NR != 1 { a[$2]+=$3; } END { for (b in a) { print b, a[b] } } ``` 你可以看到,在处理文件之前也需要在 `BEFORE` 函数(仅仅执行一次)中打印一列表头。 ### 循环 在任何编程语言中循环都是很重要的一部分,`awk` 也不例外。使用循环你可以控制 `awk` 脚本怎样去运行,它可以统计什么信息,还有它怎么去处理你的数据。我们下一篇文章会讨论 `switch`、`continue` 和 `next` 语句。 --- via: <https://opensource.com/article/19/11/loops-awk> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Awk scripts have three main sections: the optional BEGIN and END functions and the functions you write that are executed on each record. In a way, the main body of an awk script is a loop, because the commands in the functions run for each record. However, sometimes you want to run commands on a record more than once, and for that to happen, you must write a loop. There are several kinds of loops, each serving a unique purpose. ## While loop A **while** loop tests a condition and performs commands *while* the test returns *true*. Once a test returns *false*, the loop is broken. ``` #!/bin/awk -f BEGIN { # Loop through 1 to 10 i=1; while (i <= 10) { print i, " to the second power is ", i*i; i = i+1; } exit; } ``` In this simple example, awk prints the square of whatever integer is contained in the variable *i*. The **while (i <= 10)** phrase tells awk to perform the loop only as long as the value of *i* is less than or equal to 10. After the final iteration (while *i* is 10), the loop ends. ## Do while loop The **do while** loop performs commands after the keyword **do**. It performs a test afterward to determine whether the stop condition has been met. The commands are repeated only *while* the test returns true (that is, the end condition has *not* been met). If a test fails, the loop is broken because the end condition has been met. ``` #!/usr/bin/awk -f BEGIN { i=2; do { print i, " to the second power is ", i*i; i = i + 1 } while (i < 10) exit; } ``` ## For loops There are two kinds of **for** loops in awk. One kind of **for** loop initializes a variable, performs a test, and increments the variable together, performing commands while the test is true. ``` #!/bin/awk -f BEGIN { for (i=1; i <= 10; i++) { print i, " to the second power is ", i*i; } exit; } ``` Another kind of **for** loop sets a variable to successive indices of an array, performing a collection of commands for each index. In other words, it uses an array to "collect" data from a record. This example implements a simplified version of the Unix command **uniq**. By adding a list of strings into an array called **a** as a key and incrementing the value each time the same key occurs, you get a count of the number of times a string appears (like the **--count** option of **uniq**). If you print the keys of the array, you get every string that appears one or more times. For example, using the demo file **colours.txt** (from the previous articles): ``` name color amount apple red 4 banana yellow 6 raspberry red 99 strawberry red 3 grape purple 10 apple green 8 plum purple 2 kiwi brown 4 potato brown 9 pineapple yellow 5 ``` Here is a simple version of **uniq -c** in awk form: ``` #! /usr/bin/awk -f NR != 1 { a[$2]++ } END { for (key in a) { print a[key] " " key } } ``` The third column of the sample data file contains the number of items listed in the first column. You can use an array and a **for** loop to tally the items in the third column by color: ``` #! /usr/bin/awk -f BEGIN { FS=" "; OFS="\t"; print("color\tsum"); } NR != 1 { a[$2]+=$3; } END { for (b in a) { print b, a[b] } } ``` As you can see, you are also printing a header column in the BEFORE function (which always happens only once) prior to processing the file. ## Loops Loops are a vital part of any programming language, and awk is no exception. Using loops can help you control how your awk script runs, what information it's able to gather, and how it processes your data. Our next article will cover switch statements, **continue**, and **next**. Would you rather listen to this article? It was adapted from an episode of [Hacker Public Radio](http://hackerpublicradio.org/eps.php?id=2330), a community technology podcast by hackers, for hackers. ## 2 Comments
11,637
5 个用于在 Linux 终端中查找域名 IP 地址的命令
https://www.2daygeek.com/linux-command-find-check-domain-ip-address/
2019-12-03T00:04:40
[ "dig", "ping" ]
https://linux.cn/article-11637-1.html
![](/data/attachment/album/201912/03/000402c0ekkgku1f011kzt.jpg) 本教程介绍了如何在 Linux 终端验证域名或计算机名的 IP 地址。本教程将允许你一次检查多个域。你可能已经使用过这些命令来验证信息。但是,我们将教你如何有效使用这些命令在 Linux 终端中识别多个域的 IP 地址信息。 可以使用以下 5 个命令来完成此操作。 * `dig` 命令:它是一个用于查询 DNS 名称服务器的灵活命令行工具。 * `host` 命令:它是用于执行 DNS 查询的简单程序。 * `nslookup` 命令:它用于查询互联网域名服务器。 * `fping` 命令:它用于向网络主机发送 ICMP ECHO\_REQUEST 数据包。 * `ping` 命令:它用于向网络主机发送 ICMP ECHO\_REQUEST 数据包。 为了测试,我们创建了一个名为 `domains-list.txt` 的文件,并添加了以下域。 ``` # vi /opt/scripts/domains-list.txt 2daygeek.com magesh.co.in linuxtechnews.com ``` ### 方法 1:如何使用 dig 命令查找域的 IP 地址 [dig 命令](https://www.2daygeek.com/dig-command-check-find-dns-records-lookup-linux/)代表 “<ruby> 域名信息抓手 <rt> Domain Information Groper </rt></ruby>”,它是一个功能强大且灵活的命令行工具,用于查询 DNS 名称服务器。 它执行 DNS 查询,并显示来自查询的名称服务器的返回信息。大多数 DNS 管理员使用 `dig` 命令来解决 DNS 问题,因为它灵活、易用且输出清晰。 它还有批处理模式,可以从文件读取搜索请求。 ``` # dig 2daygeek.com | awk '{print $1,$5}' 2daygeek.com. 104.27.157.177 2daygeek.com. 104.27.156.177 ``` 使用以下 bash 脚本查找多个域的 IP 地址。 ``` # vi /opt/scripts/dig-command.sh #!/bin/bash for server in `cat /opt/scripts/domains-list.txt` do echo $server "-" dig $server +short done | paste -d " " - - - ``` 添加以上内容到脚本后,给 `dig-command.sh` 文件设置可执行权限。 ``` # chmod +x /opt/scripts/dig-command.sh ``` 最后运行 bash 脚本获得输出。 ``` # sh /opt/scripts/dig-command.sh 2daygeek.com - 104.27.156.177 104.27.157.177 magesh.co.in - 104.18.35.52 104.18.34.52 linuxtechnews.com - 104.27.144.3 104.27.145.3 ``` 如果要在一行中运行上面的脚本,请使用以下脚本。 ``` # for server in 2daygeek.com magesh.co.in linuxtechnews.com; do echo $server "-"; dig $server +short; done | paste -d " " - - - ``` 或者,你可以使用以下 Shell 脚本查找多个域的 IP 地址。 ``` # for server in 2daygeek.com magesh.co.in linuxtechnews.com; do dig $server | awk '{print $1,$5}'; done 2daygeek.com. 104.27.157.177 2daygeek.com. 104.27.156.177 magesh.co.in. 104.18.34.52 magesh.co.in. 104.18.35.52 linuxtechnews.com. 104.27.144.3 linuxtechnews.com. 104.27.145.3 ``` ### 方法 2:如何使用 host 命令查找域的 IP 地址 [host 命令](https://www.2daygeek.com/linux-host-command-check-find-dns-records-lookup/)是一个简单的命令行程序,用于执行 [DNS 查询](https://www.2daygeek.com/category/dns-lookup/)。它通常用于将名称转换为 IP 地址,反之亦然。如果未提供任何参数或选项,`host` 将打印它的命令行参数和选项摘要。 你可以在 `host` 命令中添加特定选项或记录类型来查看域中的所有记录类型。 ``` # host 2daygeek.com | grep "has address" | sed 's/has address/-/g' 2daygeek.com - 104.27.157.177 2daygeek.com - 104.27.156.177 ``` 使用以下 bash 脚本查找多个域的 IP 地址。 ``` # vi /opt/scripts/host-command.sh for server in `cat /opt/scripts/domains-list.txt` do host $server | grep "has address" | sed 's/has address/-/g' done ``` 添加以上内容到脚本后,给 `host-command.sh` 文件设置可执行权限。 ``` # chmod +x /opt/scripts/host-command.sh ``` 最后运行 bash 脚本获得输出。 ``` # sh /opt/scripts/host-command.sh 2daygeek.com - 104.27.156.177 2daygeek.com - 104.27.157.177 magesh.co.in - 104.18.35.52 magesh.co.in - 104.18.34.52 linuxtechnews.com - 104.27.144.3 linuxtechnews.com - 104.27.145.3 ``` ### 方法 3:如何使用 nslookup 命令查找域的 IP 地址 [nslookup 命令](https://www.2daygeek.com/nslookup-command-check-find-dns-records-lookup-linux/)是用于查询互联网[域名服务器(DNS)](https://www.2daygeek.com/check-find-dns-records-of-domain-in-linux-terminal/)的程序。 `nslookup` 有两种模式,分别是交互式和非交互式。交互模式允许用户查询名称服务器以获取有关各种主机和域的信息,或打印域中的主机列表。非交互模式用于仅打印主机或域的名称和请求的信息。 它是一个网络管理工具,可以帮助诊断和解决 DNS 相关问题。 ``` # nslookup -q=A 2daygeek.com | tail -n+4 | sed -e '/^$/d' -e 's/Address://g' | grep -v 'Name|answer' | xargs -n1 104.27.157.177 104.27.156.177 ``` 使用以下 bash 脚本查找多个域的 IP 地址。 ``` # vi /opt/scripts/nslookup-command.sh #!/bin/bash for server in `cat /opt/scripts/domains-list.txt` do echo $server "-" nslookup -q=A $server | tail -n+4 | sed -e '/^$/d' -e 's/Address://g' | grep -v 'Name|answer' | xargs -n1 done | paste -d " " - - - ``` 添加以上内容到脚本后,给 `nslookup-command.sh` 文件设置可执行权限。 ``` # chmod +x /opt/scripts/nslookup-command.sh ``` 最后运行 bash 脚本获得输出。 ``` # sh /opt/scripts/nslookup-command.sh 2daygeek.com - 104.27.156.177 104.27.157.177 magesh.co.in - 104.18.35.52 104.18.34.52 linuxtechnews.com - 104.27.144.3 104.27.145.3 ``` ### 方法 4:如何使用 fping 命令查找域的 IP 地址 [fping 命令](https://www.2daygeek.com/how-to-use-ping-fping-gping-in-linux/)是类似 `ping` 之类的程序,它使用互联网控制消息协议(ICMP)echo 请求来确定目标主机是否响应。 `fping` 与 `ping` 不同,因为它允许用户并行 ping 任意数量的主机。另外,它可以从文本文件输入主机。 `fping` 发送 ICMP echo 请求,并以循环方式移到下一个目标,并且不等到目标主机做出响应。 如果目标主机答复,那么将其标记为活动主机并从要检查的目标列表中删除;如果目标在特定时间限制和/或重试限制内未响应,那么将其指定为不可访问。 ``` # fping -A -d 2daygeek.com magesh.co.in linuxtechnews.com 104.27.157.177 (104.27.157.177) is alive 104.18.35.52 (104.18.35.52) is alive 104.27.144.3 (104.27.144.3) is alive ``` ### 方法 5:如何使用 ping 命令查找域的 IP 地址 [ping 命令](https://www.2daygeek.com/how-to-use-ping-fping-gping-in-linux/)(<ruby> 数据包互联网抓手 <rt> Packet Internet Groper </rt></ruby>)是一个网络程序,用于测试 Internet 协议(IP)网络上主机的可用性/连接性。 通过向目标主机发送互联网控制消息协议(ICMP)Echo 请求数据包并等待 ICMP Echo 应答来验证主机的可用性。 它基于发送的数据包、接收的数据包、丢失的数据包,通常包含最小/平均/最大时间来汇总统计结果。 ``` # ping -c 2 2daygeek.com | head -2 | tail -1 | awk '{print $5}' | sed 's/[(:)]//g' 104.27.157.177 ``` 使用以下 bash 脚本查找多个域的 IP 地址。 ``` # vi /opt/scripts/ping-command.sh #!/bin/bash for server in `cat /opt/scripts/domains-list.txt` do echo $server "-" ping -c 2 $server | head -2 | tail -1 | awk '{print $5}' | sed 's/[(:)]//g' done | paste -d " " - - ``` 添加以上内容到脚本后,给 `ping-command.sh` 文件设置可执行权限。 ``` # chmod +x /opt/scripts/ping-command.sh ``` 最后运行 bash 脚本获得输出。 ``` # sh /opt/scripts/ping-command.sh 2daygeek.com - 104.27.156.177 magesh.co.in - 104.18.35.52 linuxtechnews.com - 104.27.144.3 ``` --- via: <https://www.2daygeek.com/linux-command-find-check-domain-ip-address/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
11,640
Nvidia 悄悄推出更快、更低功耗的 Tesla GPU 加速器
https://www.networkworld.com/article/3482097/nvidia-quietly-unveils-faster-lower-power-tesla-gpu-accelerator.html
2019-12-03T23:35:00
[ "GPU", "Nvidia" ]
https://linux.cn/article-11640-1.html
> > Nvidia 升级了其 Volta 系列的 Tesla GPU 加速卡,使其能够以旧型号的相同功率更快地工作。 > > > ![](/data/attachment/album/201912/03/233540nw1wyyfxxy8fww0y.jpg) Nvidia 上周举行了 Supercomputing 19 大会,不出意外的是公布了很多新闻,这些我们将稍后提到。但被忽略的一条或许是其中最有趣的:一张更快、功耗更低的新一代图形加速卡。 多名与会者与多个新闻站点发现了这点,Nvidia 向我证实这确实是一张新卡。Nvidia 的 “Volta” 这代 Tesla GPU 加速卡在 2017 年就已淘汰,因此升级工作应该早已过期。 V100S 目前仅提供 PCI Express 3 接口,但有望最终支持 Nvidia 的 SXM2 接口。SXM 是 Nvidia 的双插槽卡设计,与 PCIe 卡不同,它不需要连接电源。SXM2 允许 GPU 通过 Nvidia 的 NVLink(一种高带宽、节能的互连)相互之间或与 CPU 进行通信,其数据传输速度比 PCIe 快十倍。 借助此卡,Nvidia 声称拥有单精度 16.4 TFLOPS,双精度 8.2 TFLOPS 并且 Tensor Core 性能高达 130 TFLOPS。这仅比 V100 SXM2 设计提高了 4% 至 5%,但比 PCIe V100 变体提高了 16% 至 17%。 内存容量保持在 32 GB,但 Nvidia 添加了 High Bandwidth Memory 2(HBM2),以将内存性能提高到 1,134 GB/s,这比 PCIe 和 SXM2 都提高了 26%。 通常情况下,性能提升将同时导致功率增加,但在这里,PCIe 卡的总体功率为 250 瓦,与上一代 PCIe 卡相同。因此,在相同功耗下,该卡可额外提供 16-17% 的计算性能,并增加 26% 的内存带宽。 ### 其他新闻 Nvidia 在会上还发布了其他新闻: * 其 GPU 加速的基于 Arm 的高性能计算参考服务器的新参考设计和生态系统支持。该公司表示,它得到了 HPE/Cray、Marvell、富士通和 Ampere 的支持,Ampere 是 Intel 前高管勒尼·詹姆斯(Renee James)领导的一家初创公司,它希望建立基于 Arm 的服务器处理器。 * 这些公司将使用 Nvidia 的参考设计(包括硬件和软件组件)来使用 GPU 构建从超大规模云提供商到高性能存储和百亿亿次超级计算等。该设计还带来了 CUDA-X,这是 Nvidia 用于 Arm 处理器的 CUDA GPU 的特殊版本开发语言。 * 推出 Nvidia Magnum IO 套件,旨在帮助数据科学家和 AI 以及高性能计算研究人员在几分钟而不是几小时内处理大量数据。它经过优化,消除了存储和 I/O 瓶颈,可为多服务器、多 GPU 计算节点提供高达 20 倍的数据处理速度。 * Nvidia 和 DDN (AI 以及多云数据管理开发商)宣布将 DDN 的 A3ITM 数据管理系统与 Nvidia 的 DGX SuperPOD 系统捆绑在一起,以便客户能够以最小的复杂性和更短的时限部署 HPC 基础架构。SuperPOD 还带有新的 NVIDIA Magnum IO 软件栈。 * DDN 表示,SuperPOD 能够在数小时内部署,并且单个设备可扩展至 80 个节点。不同的深度学习模型的基准测试表明,DDN 系统可以使 DGXSuperPOD 系统完全保持数据饱和。 --- via: <https://www.networkworld.com/article/3482097/nvidia-quietly-unveils-faster-lower-power-tesla-gpu-accelerator.html> 作者:[Andy Patrizio](https://www.networkworld.com/author/Andy-Patrizio/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,641
23 款开源的声音、视觉生产工具
https://opensource.com/article/18/2/open-source-audio-visual-production-tools
2019-12-04T09:31:00
[ "视频", "音频" ]
https://linux.cn/article-11641-1.html
> > 无论你是要进行音频、图形、视频、动画还是它们的任意组合,都有一个开源工具可以帮助你产生专业水平的结果。 > > > ![](/data/attachment/album/201912/04/093037w8ab8v0voz0b5u88.jpg) “开源”在云基础设施、网站托管、嵌入式设备和其他领域已经建立的相当完善。很少数人知道开源在生产专业级的声音视觉素材上也是一个不错的选择。 作为一名产品经理(有时候也是市场支持),我为终端用户提供很多内容:文档、文章、视频教学,甚至是展台物料、白皮书、采访等等。我找到了很多可以帮我制作音频、视频、排版、截屏的开源软件。人们选择开源软件而不是专有软件的[原因](https://opensource.com/resources/what-open-source)有很多,而我也为以下人群编制了一份开源音视频工具清单: * 想要入坑 GNU/Linux,但需要在原来的操作系统上慢慢从使用跨平台软件开始 * 热爱开源,但对音视频开源软件所知甚少,不知道该如何选择 * 想要为创造力充电而探索新的工具,并且不想使用其他人使用过的方法工具 * 存在某些其他的原因使用开源音视频解决方案(如果是你,不妨在评论里分享一下) 幸运的是,存在着很多开源的音视频创作软件,也存在着很多硬件来支持这些应用。本文清单里的所有软件都符合以下标准: * 跨平台 * 开源(软件和驱动) * 稳定 * 积极维护 * 良好的文档与技术支持 我将清单中的解决方案划分为图形、音频、视频和动画。注意,本文中提到的应用程序并不完全等同于一些有名的私有软件,它们需要花时间来学习,并且可能需要改变你的工作流程,但是学习新的工具能够让体验全新的创造方式。 ### 图形 我制作过很多出版和网站使用的图形,包括徽标、横幅、视频节目、草图。这里是一些我用过的开源应用,也包括一同使用的硬件。 #### 软件 **1、[Inkscape](https://inkscape.org/)**(矢量图) Inkscape 是一款不错的矢量图编辑器,用来制作 RGB 颜色空间下的 SVG 和 PDF 文件。(它可以制作 CMYK 图像,但不是主要用途)它是为 web 应用制作 SVG 格式的地图和图表的人的救命稻草。你不仅可以使用集成的 XML 编辑器打开文件,也可以用它查看对象的所有参数。但有一个缺点:它在 Mac 上的优化不是很好。有很多样例,可以看[Inkscape 画廊](https://inkscape.org/en/gallery/)。 **2、[GIMP](https://www.gimp.org/)**(图片编辑器) GIMP 是我最喜欢的图片编辑程序,它包括了色彩调整、裁剪和拉伸,并且(尤其是)对于网页使用的文件大小进行了优化(很多使用 Photoshop 的同事让我帮他们做这最后一步)。你也可以从头制作并绘制一张图片,但 GIMP 并不是我最喜欢用来做这件事的工具。在 [GIMP Artists on DevianArt](https://gimp-artists.deviantart.com/gallery/) 上查看众多的样例。 **3、[Krita](https://krita.org/)**(数字绘画) 当你桌子上摆着一个漂亮的 Wacom 数位板,你肯定想试试真正的数字绘画应用。Krita 就是你创作漂亮插画所需要的工具。在 [Krita 画廊](https://krita.org/en/features/gallery/) 里看看我说的东西吧。 **4、[Scribus](https://www.scribus.net/)**(桌面印刷系统) 你可以使用 Scribus 来创建一个完整的文档,或者只是把用 Inkscape 或 Libre Office 制作的 PDF 从 RGB 转换到 CMYK。有一个功能我非常喜欢:你可以试着模拟视觉障碍人士使用 Scribus 时的体验。当我发送 PDF 文件给商业印刷公司时全指望 Scribus。尽管出版社可能使用像 InDesign 这样的私有软件创建文档,但如果你用 Scribus 正确的完成一份文档,那么打印时就不会出现任何问题。免费建议:第一次发送文件给印刷公司时,不要告诉印刷公司创建该文档所使用的软件。你可以在 [Scribus 教程](https://www.scribus.net/category/made-with-scribus/)中寻找创建文档的例子。 **5、[RawTherapee](http://rawtherapee.com/)**(RAW 图像开发工具) RawTherapee 是我所知道唯一跨平台可替代 Lightroom 的软件。你可以将相机调整到 RAW 模式,然后使用 RawTherapee 来修图。它提供了非常强大的引擎和对图片没有破坏的编辑器。例如,可以见 [Raw Therapee 截图](http://rawtherapee.com/blog/screenshots)。 **6、[LibreOffice Draw](https://www.libreoffice.org/discover/draw/)**(桌面印刷系统) 尽管你可能认为 LibraOffice Draw 不是一款专业的桌面印刷解决方案,但它仍然能够在很多情况下帮助你。例如,制作其他人(尽管是那些不懂图形软件的人)以后可以修改的白皮书、图表或海报。它不仅方便使用,而且当创建有趣的文档时也是 Impress 或 PowerPoint 的绝佳替代软件。 #### 图形硬件 **绘图板** [Wacom](http://www.wacom.com/en-us) 数位板(和兼容设备)通常支持所有的操作系统。 **颜色校正** 颜色校正产品通常可用于所有操作系统,也包括了 GNU/Linux。Datacolor 生产的 [Spyder](http://www.datacolor.com/photography-design/product-overview/#workflow_2) 在所有平台上都有应用程序的支持。 **扫描仪和打印机** 图形艺术家需要输出(无论是打印还是电子版)的颜色是精确的。但是真正跨平台的设备,以及所有平台都易于安装的驱动,并不像你想的那样普遍。你的最佳选择是兼容 TWAIN 的扫描仪和兼容 Postscript 的打印机。以我的经验,Epson 和 Xerox 的专业级扫描仪和打印机更不容易出现驱动问题,并且它们通常也是开箱即用,拥有漂亮精确的颜色。 ### 音频 有许多可供音乐家、视频制作者、游戏制作者、音乐出版商等等人群选择的开源音频软件。这里有一些我曾经用来进行内容创作与声音录制时所使用的软件。 #### 软件 **7、**[**Ardour**](https://www.ardour.org/)(数字音频录制) 对录音与编辑来说,最专业级的工具选择当然是唾手可得的 Ardour。听起来很棒,它的混音部分非常的完整灵活,能够提供给你喜欢的插件,并且易于回放、编辑、对比修改。我经常用它进行声音录制和视频混音。要找出一些使用 Ardour 录制好的音乐并不容易,因为音乐家们很少表明他们使用的软件。然而,你可以查看它的[截图](http://ardour.org/features.html)和一些特性来了解它的功能。 (如果你在寻求一种声音制作方面的“模拟体验”,你可以试试 [Harrison Mixbus](http://harrisonconsoles.com/site/mixbus.html),它并不是一个开源项目,但是高度基于 Ardour,拥有模拟显示的终端。我非常喜欢用它进行工作,我的客户也喜欢用它制作的声音。Mixbus 也是跨平台的) **8、[Audacity](http://www.audacityteam.org/)** (声音编辑) Audacity 属于“瑞士军刀”级的声音制作软件。它并不完美,但你几乎可以用它做所有的事情。加上非常易于使用,任何人都能在几分钟之内上手。像 Ardour 一样,很难找到一份归功于 Audacity 的作品,但你可以从这些[截图](http://www.audacityteam.org/about/screenshots/)中了解如何使用它。 **9、[LMMS](https://lmms.io/)** (音乐制作) LMMS,设计作为 FL Studio 的替代品,也许使用并不那么广泛,但它非常完整并易于使用。你可以使用自己最喜欢的插件,使用“钢琴键”编辑乐器,使用<ruby> 步定序器 <rt> step sequencer </rt></ruby>播放鼓点,混合音轨…几乎能做任何事情。在我没有时间为音乐家录音的时候我就使用它为视频创建声音片段。查看[最好的 LMMS](https://lmms.io/showcase/) 榜单来看看一些例子。 **10、[Mixxx](https://www.mixxx.org/)** (DJ,音乐混音) 如果你需要强大的混音和播放 DJ 软件,Mixxx 就可以满足你的需求。它与大多数 MIDI 控制器、唱片、专用声卡所兼容。你可以用它管理音乐库、添加音效,做一些有趣的事情。查看它的[功能](https://www.mixxx.org/features/)来了解它是如何工作的。 #### 音频接口硬件 尽管你可以使用任何一个计算机的声卡录制音频,但要录制的很好,就需要一个音频接口——一个录制高质量音频输入的专用的外部声卡。对于跨平台兼容性来说,大多数“兼容 USB”和“兼容 iOS”的音频接口设备应该都能录制 MIDI 或其他音频。下面是一些我用过的一些有名气的跨平台设备。 **[Behringer U-PHORIA UMC22](http://www.musictri.be/Categories/Behringer/Computer-Audio/Interfaces/UMC22/p/P0AUX)** UMC22 是你可以考虑的最便宜的选择。但它的前置放大器噪音太大,<ruby> 音腔 <rt> box </rt></ruby>质量也比较低。 **[Presonus AudioBox USB](https://www.presonus.com/products/audiobox-usb)** AudioBox USB 是第一个兼容 USB(因此也跨平台)的录音系统。它非常的耐用,经常在二手市场也能见到。 **[Focusrite Scarlett](https://us.focusrite.com/scarlett-range)** Scarlett 在我看来是目前最高质量的跨平台声卡。不同种类的设备可以涵盖 2-18 个输入/输出端口。你可以在二手市场找到它的最初版本,而最新的第二代具有更好的前置放大器与规格。[2i2](https://us.focusrite.com/usb-audio-interfaces/scarlett-2i2) 型号是我经常使用的那一款。 **[Arturia AudioFuse](https://www.arturia.com/products/audio/audiofuse/overview)** AudioFuse 几乎可以让你接入任何设备,从麦克风到黑胶唱片机再到各种数字输入设备。它具有优质的声音与良好的设计,也是我目前用的最多的一款设备。它是跨平台的,但目前配置软件还不能在 GUN/Linux 上使用。即使我把它从 Windows 电脑上断开,它仍然保留着我的配置。但是讲真,Arturia,劳烦认真考虑做一个 Linux 的软件。 #### MIDI 控制器 MIDI 控制器是一种乐器——例如电子琴、鼓垫等等。可以让你控制音乐软件或者硬件。现有的大多数 USB MIDI 控制器都跨平台并兼容主流的录音编辑软件。基于网页的教程可以帮你对不同的软件进行配置。尽管找到有关在 GNU/Linux 上配置的信息可能比较困难,但它们仍然是可以使用的。我用过许多 Akai 和 M-Audio 设备,没有任何问题。在买乐器之前最好先试一下,至少去听一下它们的音质或体验一下按键触感。 #### 音频编解码器 音频编解码器压缩或解压数字音频,用尽可能小的文件大小获得最佳质量的声音。幸运的是,用于收听或流媒体播放的编解码器恰好是开源的:[FLAC](https://en.wikipedia.org/wiki/FLAC)。[Ogg Vorbis](https://xiph.org/vorbis/) 是另一个值得了解的开源音频编解码器;在相同的比特率下比 MP3 好的多。如果你需要输出不同的音频格式,我建议通常存档最好质量的音频,然后再压缩成特定的版本。 ### 视频 视频对于品牌的传播是影响巨大的。即使你不是一个视频专家,学习一些基础的东西也是非常明智的。 #### 软件 **11、[VLC](https://www.videolan.org/)** (视频播放器与转换器) 最初是为流媒体而开发的,VLC 现在因能够在所有设备上读取所有的视频格式被人们熟知。它非常的实用,例如,你可以使用它将视频转换成其他编解码格式或容器,也可以用来恢复破损的视频。 **12、[OpenShot](https://www.openshot.org/)** (视频编辑) OpenShot 是一个简单的软件,但它却可以制作出很好的效果,尤其是在短视频上。(在编辑或改善音质方面有一定的限制,但它也能够完成)我非常喜欢它的移动、拉伸、裁剪工具;用它创建视频的开头或结尾,导出之后使用更复杂的编辑器进行编辑,非常的完美。你可以在 OpenShot 的网站上看这些[例子](https://www.openshot.org/videos/)(并获取更多信息)。 **13、[Shotcut](https://shotcut.com/)** (视频编辑) 我认为 Shotcut 是比 OpenShot 更完整一些的工具——它在你的操作系统上比起其他较为基础的编辑器更具有竞争力,并且它支持 4K 分辨率,具有专业的解码器。尝试一下,我相信你会爱上它的。你可以在这些[视频教程](https://shotcut.org/tutorials/)里看一些范例。 **14、[Blender Velvets](http://blendervelvets.org/)** (视频编辑、合成、特效) 尽管这一章节不是本文的学习重点,但 Blender Velvets 是你能找到的最强大的解决方案之一。它是由一些视频创作者所制作的一系列扩展工具和脚本的合集,是通过 Blender 3D 制作软件转换成的 2D 视频编辑器。尽管它的复杂度意味着不是我的首选视频编辑器,但你仍可以在 YouTube 和其他网站上找到它的教程,并且一旦你学习了它,你就能通过它做任何事情。观看这个[视频教程](http://blendervelvets.org/video-tutorial-new-functions-for-the-blender-velvets/)来了解它的功能与运作方式。 **15、[Natron](https://natron.fr/)**(合成) 我不使用 Natron,但我听说它广受好评。它是 Adobe After Effects 的替代品,但运作方式并不同。想了解更多可以观看一些视频教程,比如这些 Natron 的 [YouTube 频道](https://www.youtube.com/playlist?list=PL2n8LbT_b5IeMwi3AIzqG4Rbg8y7d6Amk)。 **16、[OBS](https://obsproject.com/)** (实时编辑、录制、流媒体) Open Broadcaster Software(OBS)是一个领先的在 YouTube 或 Twitch 上进行现场录制或现场直播电子竞技、电视游戏的解决方案。我经常使用它记录用户的屏幕、会议和聚会。要获取更多信息,查看我曾经在 Opensource.com 上写的关于录制现场汇报的教程,[第一部分:选择你的设备](https://opensource.com/article/17/9/equipment-recording-presentations)和[第二部分:软件安装](https://opensource.com/article/17/9/equipment-setup-live-presentations)。 #### 视频硬件 结论先行:你需要一个强大的工作站以及快速的硬盘和更新的软件和驱动。 **图形处理单元(GPU)** 一部分包含在清单里的软件比如 Blender 和 Shotcut 使用 OpenGL 和硬件加速,这些都高度依赖 GPU。我建议你使用可以负担起的最强大的 GPU。我所使用过的 AMD 和 Nvidia 都有着良好的体验,这取决于使用的平台。不要忘记安装最新的驱动。 **硬盘** 大体上来说,越快越大的硬盘,对视频越好。不要忘记在软件里配置好正确的路径。 **视频录制硬件** * [Blackmagic Design](https://www.blackmagicdesign.com/): Blackmagic 提供了非常好的、专业级的视频录制和回放硬件。驱动支持 Mac、Windows 和 GNU/Linux(但不是所有的发行版) * [Epiphan](https://www.epiphan.com/): 在 Epiphan 的专业级 USB 视频录制设备中有一款新型产品,它适用于 HDMI 和高分辨率的屏幕。然而,你也可以在二手市场找到旧的 VGA 设备,因为他们还在继续为 GNU/Linux 和 Windows 上提供专用的驱动程序。 #### 视频编解码 不幸的是,使用开源的编解码器仍然很困难。例如,许多相机使用专有的编解码器录制 H.264 的视频和 AC3 的音频,组成称为 AVCHD 的格式。因此,我们必须务实,尽可能利用现有资源。 好消息是内容产业正在步向开源的编解码器来避免一些费用,并使用开源标准。对于出版和流媒体,[谷歌](https://www.webmproject.org/)的 [WebM](https://www.webmproject.org/) 便是一款优秀的开源编解码器,并且大多数视频编辑器可以导入这种格式。同样地, [GoPro](https://fr.gopro.com/news/gopro-open-sources-the-cineform-codec)的超高分辨率和 360° 视频编解码器 [Cineform](https://fr.gopro.com/news/gopro-open-sources-the-cineform-codec) 现在也进行了开源。希望更多的设备和供应商将会在不久之后使用它。 ### 2D 和 3D 动画 动画不是我的专业领域,因此我问了从事于动画内容生产的朋友一些建议并加入到清单中,他的工作包含儿童电影和连续剧。 #### 软件 **17、[Blender](https://www.blender.org/)** (3D 模型和渲染) Blender 是顶级的开源跨平台 3D 建模和渲染软件。你可以直接在 Blender 中完成整个项目的工作,或者使用它为电影或视频创建 3D 效果。你能够在网上找到许多视频教程,因此即使它不是一个简单的软件,但也非常容易上手。Blender 是一个非常活跃的项目,经常还会制作一些微电影来展示他们的技术。你可以在 [Blender Open Movies](https://www.blender.org/about/projects/) 上观看。 **18、[Synfig Studio](https://www.synfig.org/)** (2D 动画) 第一次用 Synfig 时,它让我想起了那个不错的 Macromedia 老式 Flash 编辑器。在那之后,它已经发展成一个全功能的 2D 动画工作室。你可以使用它制作宣传故事、商业广告、演示、开场或结尾动画以及视频中的转场,或者甚至用它制作全动画的电影。见 [Synfig 作品集](https://www.synfig.org/#portfolio)。 **19、[TupiTube](https://maefloresta.com/)** (定格 2D 动画) 使用 TupiTube 是一个学习基本 2D 动画的极好方法。你可以将一系列绘画或其他图片转换成一个视频或者创建一个 GIF 循环动画。它是一个相当简单的软件,但非常完整。查看 [TupiTude 的 YouTube](https://www.youtube.com/channel/UCBavSfmoZDnqZalr52QZRDw) 频道获取一些教程和范例。 #### 硬件 动画制作使用与图形设计相同的硬件,因此查看第一小结中的硬件清单获取一些建议。 有一点需要注意:你要用一个强大的 GPU 来进行 3D 建模和渲染。选择可能有些限制,因为这取决于你使用的平台或电脑制造商,但是不要忘记安装最新的驱动。谨慎选择你的显卡:它们非常昂贵,并且在大型的 3D 项目中至关重要,尤其是在渲染步骤中。 ### Linux 上的选择 如果你是 GUN/Linux 用户,那么我为你提供了更多不错的选择。它们并不是完全跨平台的,但部分拥有 Windows 版本,还有一些可以在 Mac 上使用 Macports 安装。 **20、[Kdenlive](https://kdenlive.org/)** (视频编辑) 伴随着最新版本的发布(几个月之前),Kdenlive 成为了我最喜欢的视频编辑器,尤其是当我在 Linux 机器上处理一些长视频的时候。如果你经常使用流行的非线性视频编辑器,Kdenlive(全称是 <ruby> KDE 非线性视频编辑器 <rt> KDE Non-Linear Video Editor </rt></ruby>)对你来说将非常简单。它拥有很棒的视频和音频特效,强大的细节处理能力。并且在 BSD 和 MacOS(尽管它对准的是 GNU/Linux)都能使用,还有望移植到 Windows 上。 **21、[Darktable](https://www.darktable.org/)** (RAW 图像开发) Darktable 是一款由摄影师制作的非常完整的 DxO PhotoLab 替代品。一些研究型项目使用它当做开发平台并测试一些图像处理算法。它是一个非常活跃的项目,我已经等不及的见到它的跨平台版本了。 **22、[MyPaint](http://mypaint.org/)** (digital painting数字绘画) MyPaint 就像数字绘画领域的 light table(LCTT 译注:集成开发环境)。它在 Wacom 设备上表现良好,并且它的笔刷引擎尤其值得赞赏,因此 GIMP 开发人员正在密切的关注它。 **23、[Shutter](http://shutter-project.org/)** (桌面截图) 当我写这篇教程的时候,我使用了许多截图来进行展示。我最喜欢的 GNU/Linux 截图工具就是 Shutter。事实上,我都找不到在 Windows 或 Mac 上能与之抗衡的一些功能。有一点小遗憾:我很期待 Shutter 在将来能够增加新的功能来创建几秒动态的 GIF 截图。 我希望这些足以说服你开源软件是一种非常卓越且可行的音视频内容生产解决方案。如果你正在使用其他开源软件,或者对于使用跨平台软件和硬件进行音视频项目有好的建议,请在评论中分享你的观点。 --- via: <https://opensource.com/article/18/2/open-source-audio-visual-production-tools> 作者:[Antoine Thomas](https://opensource.com/users/ttoine) 译者:[LuuMing](https://github.com/LuuMing) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Open source is well established in cloud infrastructure, web hosting, embedded devices, and many other areas. Fewer people know that open source is a great option for producing professional-level audio-visual materials. As a product owner and sometimes marketing support person, I produce a lot of content for end users: documentation, web articles, video tutorials, event booth materials, white papers, interviews, and more. I have found plenty of great open source software that helps me do my job producing audio, video, print, and screen graphics. There are a lot of [reasons](https://opensource.com/resources/what-open-source) that people choose open source over proprietary options, and I've compiled this list of open source audio and video tools for people who: - want to switch to GNU/Linux, but need to start slowly with cross-platform software on their regular operating system; - are already open source enthusiasts, but are new to open source A/V software and want to know which options to trust; - want to discover new tools to fuel their creativity and don't want to use the same approaches or software everyone else uses; or - have some other reason to use open source A/V solutions (if this is you, share your reason in the comments). Fortunately, there is a lot of open source software available for A/V creators, as well as hardware that supports those applications. All of the software on this list meets the following criteria: - cross-platform - open source (for software and drivers) - stable - actively maintained - well documented and supported I've divided this list into graphics, audio, video, and animation solutions. Note that the software applications in this article are not exact equivalents of well-known proprietary software, they'll require you to learn new applications, and you may need to modify your workflow, but learning new tools enables you to create differently. ## Graphics I create a lot of graphics for print and web, including logos, banners, video titles, and mockups. Here are some of the open source applications I use, as well as the hardware I use with them. ### Software **1. Inkscape **(vector graphics) Inkscape is a good vector graphics editor for creating SVG and PDF files in the RGB color space. (It can create CMYK images, but that's not the main aim.) It's a lifesaver for manipulating SVG maps and charts for web applications; not only can you open files with the integrated XML editor, you can also see all of an object's parameters. One drawback: it is not well optimized on Mac. For examples, see [Inkscape's gallery](https://inkscape.org/en/gallery/). **2. GIMP **(picture editor) GIMP is my favorite application to edit images, including manipulating color, cropping and resizing, and (especially) optimizing file size for the web (many of my Photoshop-using colleagues ask me to do that last step for them). You can also create and draw images from scratch, but GIMP is not my favorite tool for that. See [GIMP Artists on DeviantArt](https://gimp-artists.deviantart.com/gallery/)for examples. **3. Krita **(digital painting) So you have this beautiful Wacom drawing tablet on your desk, and you want to try a true digital painting application? Krita is what you need to create beautiful drawings and paintings. See [Krita's Gallery](https://krita.org/en/features/gallery/)to see what I mean. **4. Scribus **(desktop publishing) You can use Scribus to create a complete document, or just to convert a PDF from Inkscape or Libre Office from RGB to CMYK. One feature I really like: You can simulate and check what people with visual disabilities will experience with a Scribus document. I count on Scribus when I send PDF files to a commercial printer. While printing companies may be used to files created with proprietary solutions like InDesign, if your Scribus file is done correctly, your printer won't have any issues. Free trick: The first time you send a file, don't tell the printer the name of the software you used to create it. See [Made with Scribus](https://www.scribus.net/category/made-with-scribus/)for examples of documents created with this software. **5. RawTherapee **(RAW image photo development) RawTherapee is the only completely cross-platform alternative to Lightroom I know of. You can use your camera in RAW mode, and then use RawTherapee to "develop" your picture. It provides a very powerful engine and a non-destructive editor. For examples, see [RawTherapee screenshots](http://rawtherapee.com/blog/screenshots). **6. LibreOffice Draw **(desktop publishing) Although you may not think of LibreOffice Draw as a professional desktop publishing solution, it can save you in many situations; for example, if you are creating whitepapers, diagrams, or posters that other people (even those who don't know graphics software) can update later. Not only is it easy to use, it's also a great alternative to Impress or PowerPoint for creating interesting documents. ### Graphics hardware **Graphics tablets** [Wacom](http://www.wacom.com/en-us) tablets (and compatibles) are usually well supported on all operating systems. **Color calibration** Color calibration products are available on all operating systems, including GNU/Linux. The [Spyder](http://www.datacolor.com/photography-design/product-overview/#workflow_2) products by Datacolor are well supported with applications for all platforms. **Scanners and printers** Graphic artists need the colors they output (whether print or electronic) to be accurate. But devices that are truly cross-platform, with easy-to-install drivers for all platform, are not as common as you'd think. Your best choices are scanners that are compatible with TWAIN and printers that are compatible with Postscript. In my experience, professional-range printers and scanners from Epson and Xerox are less likely to have driver issues, and they always work out of the box, with beautiful and accurate colors. ## Audio There are plenty of open source audio software options for musicians, video makers, game makers, music publishers, and others. Here are the ones that I've used for content creation and audio recording. ### Software **7. Ardour **(digital audio recording) For recording and editing audio, the best alternative to the professional Pro Tools music-creation software is, hands down, Ardour. It sounds great, the mixer section is complete and flexible, it supports your favorite plugins, and it makes it very easy to edit, listen, and compare your modifications. I use it a lot for audio recording or mixing sound on videos. It's not easy to find music recorded with Ardour, because musicians rarely credit the software they use. However, you can get an idea of its capabilities by looking at its [features and screenshots](http://ardour.org/features.html). (If you are looking for an "analog feeling" in term of sound and workflow, you can try [Harrison Mixbus](http://harrisonconsoles.com/site/mixbus.html), which is not an open source project, but is heavily based on Ardour, with Harrison's analog console emulator. I really like to work with it and my customers like the sound. Mixbus is cross platform.) **8. Audacity** (audio editing) Audacity is the "Swiss Army knife" of audio software. It's not perfect, but you can do almost everything with it. Plus it's very easy to use, and anyone can learn it in a few minutes. Like Ardour, it's hard to find work credited to Audacity, but you can find ways to use it on these [screenshots](http://www.audacityteam.org/about/screenshots/). **9. LMMS** (music production) LMMS, designed as an alternative to FL Studio, might not be as popular, but it is very complete and easy to use. You can use your favorite plugins, edit instruments using "piano roll" sequencing, play drum samples with a step sequencer, mix your tracks ... almost anything is possible. I use it to create audio loops for videos when I don't have the time to record musicians. See [The Best of LMMS](https://lmms.io/showcase/)playlists for examples. **10. Mixxx **(DJ, music mixing) If you need powerful software to mix music and play DJ, Mixx is the one to use. It's compatible with most MIDI controllers, timecoded discs, and dedicated sound cards. You can manage your music library, add effects, and have fun. Take a look at the [features](https://www.mixxx.org/features/)to see how it works. ### Audio interface hardware While you can record audio with any computer's sound card, to record *well*, you need an audio interface—a specialized type of external sound card that records high-quality audio input. For cross-platform compatibility, most "USB Class Compliant" or "compatible with iOS" audio interface devices should work for MIDI or other audio. Below is a list of cross-platform devices I use and know well. [Behringer U-PHORIA UMC22](http://www.musictri.be/Categories/Behringer/Computer-Audio/Interfaces/UMC22/p/P0AUX) The UMC22 is the cheapest option you should consider. With less expensive options, the preamps are too noisy and the quality of the box is very low. [Presonus AudioBox USB](https://www.presonus.com/products/audiobox-usb) The AudioBox USB is one of the first USB Class Compliant (and thereby cross-platform) recording systems out there. It is very robust and available on the second-hand market. [Focusrite Scarlett](https://us.focusrite.com/scarlett-range) The Scarlett range is, in my opinion, the highest quality cross-platform sound card available. The various options range from devices with two to 18 input/outputs. You can find first-version models on the second-hand market, and the new second version offers better preamps and specs. I've worked a lot with the [2i2](https://us.focusrite.com/usb-audio-interfaces/scarlett-2i2) model. [Arturia AudioFuse](https://www.arturia.com/products/audio/audiofuse/overview) The AudioFuse allows you to plug in nearly anything, from a microphone to a vinyl disc player to various digital inputs. It provides both great sound and great design, and it's what I'm using the most now. It is cross-platform, but the configuration software is not yet available for GNU/Linux. It remembers my configuration even after I unplug it from my Windows PC, but really, Arturia, please be serious and make the software available for GNU/Linux. ### MIDI controllers A MIDI controller is a musical instrument—e.g., keyboards, drum pads, etc.—that allow you to control music software and hardware. Most of the recent USB MIDI controllers are cross-platform and compatible with the main software used to record and edit audio. Web-based tutorials will help you configure them for different software; although it may be harder to find info on GNU/Linux configurations, they will work. I've used many Akai and M-Audio devices without any issues. It's best to try a musical instrument before you buy, at least to listen to the sound quality or to touch the buttons. ### Audio codecs Audio codecs compress and decompress digital audio to deliver the best-quality audio at the smallest possible file size. Fortunately, the best codec for listening and streaming happens to be open source: [FLAC](https://en.wikipedia.org/wiki/FLAC). [Ogg Vorbis](https://xiph.org/vorbis/) is another open source audio codec worth checking out; it's far better than MP3 at the same bitrate. If you need to export audio in different file formats, I recommend always exporting and archiving audio at the best possible quality, then compressing a specific version if it's needed. ## Video The impact of video in brand communications is significant. Even if you are not a video specialist, it's smart to learn the basics. ### Software **11. VLC** (video player and converter) Originally developed for media streaming, VLC is now known for its ability to read all video formats on all devices. It's very useful; for example, you can also use it to convert a video into another codec or container or to recover a broken video. **12. OpenShot** (video editor) OpenShot is simple software that produces great results, especially for short videos. (It is a bit limited in terms of editing or improving the sound of a video, but it will do the job.) I especially like the tool to move, resize, or crop a clip; it's perfect to create intros and outros that you can export, then use in a more complex editor. You can see [examples](https://www.openshot.org/videos/)(and get more information) on OpenShot's website. **13. Shotcut** (video editor) I think Shotcut is a bit more complete than OpenShot—it's a very good competitor to the basic editors in your operating system, and it supports 4K and professional codecs. Give it a try, I think you will love it. You can see examples in these [video tutorials](https://shotcut.org/tutorials/). **14. Blender Velvets** (vdeo editing, compositing, effects) While the learning curve is not the lightest on this list, Blender Velvets is one of the most powerful solutions you will find. It is a collection of extensions and scripts, created by movie makers, that transform the Blender 3D creation software into a 2D video editor. While it's complexity means it's not my top choice for video editing, you can find plenty of tutorials on YouTube and other sites, and once you learn it, you can do everything with this software. Watch this [tutorial video](http://blendervelvets.org/video-tutorial-new-functions-for-the-blender-velvets/)to see its functions and how it works. **15. Natron** (compositing) I don't use Natron, but I've gotten great feedback from people who do. It's an alternative to Adobe's After Effects, but works differently. To learn more, watch a few video tutorials, like these on [Natron's YouTube](https://www.youtube.com/playlist?list=PL2n8LbT_b5IeMwi3AIzqG4Rbg8y7d6Amk)channel. **16. OBS** (live editing, recording, and streaming) Open Broadcaster Software (OBS) is the leading solution for recording or [livestreaming](https://opensource.com/article/17/7/obs-studio-pro-level-streaming)e-sports and video games on YouTube or Twitch. I use it a lot to record users' screens, conferences, meetups, etc. For more information, see the tutorial I wrote for Opensource.com about recording live presentations, [Part 1: Choosing your equipment](https://opensource.com/article/17/9/equipment-recording-presentations)and [Part 2: Software setup](https://opensource.com/article/17/9/equipment-setup-live-presentations). ### Video hardware First things first: You will need a powerful workstation with a fast hard drive and updated software and drivers. **Graphics processing unit (GPU)** Some software on this list, including Blender and Shotcut, use OpenGL and hardware acceleration, which have high GPU demands. I recommend the most powerful GPU you can afford. I've had good experience with AMD and Nvidia, depending on the platform. Don't forget to install the latest drivers. **Hard drives** In general, the faster and bigger the hard drive, the better it is for video. Don't forget to configure your software to use the right path. **Video capture hardware** [Blackmagic Design](https://www.blackmagicdesign.com/): Blackmagic provides very good, professional-grade video capture and playback hardware. Drivers are available for Mac, Windows, and GNU/Linux (but not all distributions).[Epiphan](https://www.epiphan.com/): Among Epiphan's professional USB video capture devices is a new USB Class Compliant model for HDMI and high screen resolutions. However, you can find the older VGA devices on the secondhand market, for which they continue to provide dedicated drivers for GNU/Linux and Windows. ### Video codecs Unfortunately, it is still difficult to work with open source codecs. For example, many cameras use proprietary codecs to record videos in H.264 and sound in AC3, in a format called AVCHD. Therefore, we have to be pragmatic and use what is available. The good news is that the content industry is moving to open source codecs to avoid fees and to use open standards. For distribution and streaming, [Google'](https://www.webmproject.org/)[s WebM](https://www.webmproject.org/) is a good open source codec, and most video editors can export in that format. Also, [GoPro's ](https://fr.gopro.com/news/gopro-open-sources-the-cineform-codec)[Cineform](https://fr.gopro.com/news/gopro-open-sources-the-cineform-codec) codec for very high resolution and 360° video is now open source. Hopefully more devices and vendors will use it soon. ## 2D and 3D animation Animation is not my field of expertise, so I've asked my friends who are working on animated content, including movies and series for kids, for their recommendations to compile this list. ### Software **17. Blender **(3D modeling and rendering) Blender is the top open source and cross-platform software for 3D modeling and rendering. You can do your entire project directly in Blender, or use it to create 3D effects for a movie or video. You will find a lot of video tutorials on the web, so even though it isn't simple software, it's very easy to get started. Blender is a very active project and regularly produces short movies to showcase the technology. You can see some of them on [Blender Open Movies](https://www.blender.org/about/projects/). **18. Synfig Studio** (2D animation) The first time I used Synfig, it reminded me of the good, old Macromedia Flash editor. Since then, it has grown into a full-featured 2D animation studio. You can use it to produce promotional stories, commercials, presentations, or original intros, outros, and transitions for your videos, or even to work on full animated movies. See [Synfig's portfolio](https://www.synfig.org/#portfolio)for some examples. **19. TupiTube** (stop-motion, 2D animation) TupiTube is an excellent way to learn the basics of 2D animation. You can transform a set of drawings or other pictures into a video or create an animated GIF or small loops. It's quite simple software, but very complete. Check out [TupiTube's YouTube](https://www.youtube.com/channel/UCBavSfmoZDnqZalr52QZRDw)channel for some tutorials and examples. ### Hardware Animation uses the same hardware as graphic design, so look at the hardware list in the first section of this article for recommendations. One additional note: You will need a powerful GPU for 3D modeling and rendering. The choices can be limited, depending on your platform or PC maker, but don't forget to install the latest drivers. Carefully choose your graphics card: they are expensive and critical for big 3D projects, particularly in the rendering step. ## Linux options If you are a GNU/Linux user, I have some more good options for you. They aren't fully cross-platform, but some of them have a Windows installer, and some can be installed on Mac with Macports. **20. Kdenlive** (video editor) With its last release (a few months ago), Kdenlive became my favorite video editor, especially when I work on a long video on my Linux machine. If you are a regular user of popular non-linear video editors, Kdenlive (which stands for KDE Non-Linear Video Editor) will be easy for you to use. It has good video and audio effects, is great when you need to work on details, and works on BSD and MacOS (although it's aimed at GNU/Linux) and is being ported to Windows. **21. Darktable** (RAW development) Darktable is a very complete alternative to DxO that is made by photographers for photographers. Some research projects are using it as a platform for development and testing of new image processing algorithms. It is a very active project, and I can't wait until it becomes truly cross-platform. **22. MyPaint **(digital painting) MyPaint is like a light table for digital painting. It works well with Wacom devices, and its brush engine is particularly appreciated, so GIMP developers are looking closely at it. **23. Shutter **(desktop screenshots) When I create tutorials, I use a lot of screenshots to illustrate them. My favorite screenshot tool for GNU/Linux is Shutter; actually, I can't find an equivalent in terms of features for Windows or Mac. One missing piece: I would like to see Shutter add a feature to create animated GIF screenshots over a few seconds. I hope this has convinced you that open source software is an excellent, viable solution for A/V content producers. If you are using other open source software—or have advice about using cross-platform software and hardware—for audio and video projects, please share your ideas in the comments. ## 10 Comments
11,643
在 Linux 上使用 Multitail
https://www.networkworld.com/article/3445228/using-multitail-on-linux.html
2019-12-05T05:34:56
[ "multitail" ]
https://linux.cn/article-11643-1.html
![](/data/attachment/album/201912/05/053423mpnrn95hqqknzheq.jpg) 当你想同时查看多个文件(尤其是日志文件)的活动时,`multitail` 命令会非常有用。它的工作方式类似于多窗口形式的 `tail -f` 命令。也就是说,它显示这些文件的底部和添加的新行。虽然通常使用简单,但是 `multitail` 提供了一些命令行和交互式选项,在开始使用它之前,你应该了解它们。 ### 基本 multitail 使用 `multitail` 的最简单用法是在命令行中列出你要查看的文件名称。此命令水平分割屏幕(即顶部和底部),并显示每个文件的底部以及更新。 ``` $ multitail /var/log/syslog /var/log/dmesg ``` 显示内容将像这样拆分: ``` +-----------------------+ | | | | +-----------------------| | | | | +-----------------------+ ``` 每个文件都有一行显示该文件的文件编号(从 00 开始)、文件名、文件大小、最新内容的添加日期和时间。每个文件将被分配一半空间,而不论它的大小和活动情况。比如: ``` content lines from my1.log more content more lines 00] my1.log 59KB - 2019/10/14 12:12:09 content lines from my2.log more content more lines 01] my2.log 120KB - 2019/10/14 14:22:29 ``` 请注意,如果你要求 `multitail` 显示非文本文件或者你无权查看的文件,它不会报错。你只是看不到内容。 你还可以使用通配符指定要查看的文件: ``` $ multitail my*.log ``` 要记住的一件事是,`multitail` 将平均分割屏幕。如果指定的文件太多,那么除非你采取额外的步骤查看之后的文件(参考下面的滚动选项),否则你将只会看到前面 7 个文件的前面几行。确切的结果取决于终端窗口中有多少行可用。 按 `q` 退出 `multitail` 并返回到正常的屏幕视图。 ### 分割屏幕 如果你愿意,`multitail` 也可以垂直分割你的终端窗口(即,左和右)。为此,请使用 `-s` 选项。如果指定了三个文件,那么屏幕右侧的窗口将会水平分隔。四个文件的话,你将拥有四个大小相等的窗口。 ``` +-----------+-----------+ +-----------+-----------+ +-----------+-----------+ | | | | | | | | | | | | | | | | | | | | | | +-----------+ +-----------+-----------+ | | | | | | | | | | | | | | | | | | +-----------+-----------+ +-----------+-----------+ +-----------+-----------+ 2 个文件 3 个文件 4 个文件 ``` 如果要将屏幕分为三列,请使用 `multitail -s 3 file1 file2 file3`。 ``` +-------+-------+-------+ | | | | | | | | | | | | | | | | | | | | +-------+-------+-------+ 3 个文件带上 -s 3 选项 ``` ### 滚动 你可以上下滚动文件,但是需要按下 `b` 弹出选择菜单,然后使用向上和向下箭头按钮选择要滚动浏览的文件。然后按下回车键。然后,你可以再次使用向上和向下箭头在放大的区域中滚动浏览各行。完成后按下 `q` 返回正常视图。 ### 获得帮助 在 `multitail` 中按下 `h` 将打开一个帮助菜单,其中描述了一些基本操作,但是手册页提供了更多信息,如果莫想了解更多有关使用此工具的信息,请仔细阅读。 默认情况下,你的系统上不会安装 `multitail`,但是使用 `apt-get` 或 `yum` 可以使你轻松安装。该工具提供了许多功能,不过它是基于字符显示的,窗口边框只是 `q` 和 `x` 的字符串组成的。当你需要关注文件更新时,它非常方便。 --- via: <https://www.networkworld.com/article/3445228/using-multitail-on-linux.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,644
多语言编程必备的十大 Vim 插件
https://opensource.com/article/19/11/vim-plugins
2019-12-05T06:23:38
[ "Vim", "插件" ]
https://linux.cn/article-11644-1.html
> > 使用这 10 个 Vim 插件,可以让你在写代码或运维时,感觉更棒。 > > > ![](/data/attachment/album/201912/05/062256bnauidfsf7155d1n.jpeg) 我使用 [Vim](https://www.vim.org/) 文本编辑器大约 20 年了。有一段时间,我一直在定制我的 Vim 配置,但在只有在最近两年我才会使用插件。 最近,当我重新安装系统时(就像我经常做的那样),我觉得这是一次好的机会,我想找出多种编程语言环境下的最佳 Vim 插件,以及如何将这些插件和每种语言结合起来。 有时,我会为特定的语言和配置使用特定的插件(例如,我只在 Ansible 配置中安装 Rocannon),在此不细讲了。不过下面介绍的 10 个 Vim 插件都是我的最爱,无论使用哪种编程语言,我几乎都会使用它们。 ### 1、Volt 我的首选并不是一个插件,但是它可以替换类似于 [Vundle](https://github.com/VundleVim/Vundle.vim) 的插件,所以在此介绍。 [Volt](https://github.com/vim-volt/volt) 是一个不依存于 Vim 的 Vim 插件管理器。你可以用它安装插件,并创建名为“profile”的插件组合。你可以使用一个简单的命令 `volt profile set myprofile` 启用新的配置。这样我可以做到这样的事情,如为 Python 配置单独启用 [indentpython](https://github.com/vim-scripts/indentpython.vim) 插件。Volt 还提供了一种针对每个插件配置的简单方法,这些配置会在“profile”之间共享,因此只需要安装一次插件,就可以在多个“profile”之间使用。 Volt 还是相对较新且不够完美(比如,不管你想要使用多少个“profile”,每个插件只能有一个配置文件),但除此之外,我发现它非常方便、快速和简单。 ![Volt plugin](/data/attachment/album/201912/05/062340rz2hfhu5uullblbl.gif "Volt plugin") ### 2、Vim-Rainbow 除了 Python,几乎所有的主流编程语言都使用括号(小括号、方括号和大括号)。通常,它们会嵌套使用多对括号,因此很难搞清楚某个括号的开闭区间。我发现自己经常要数小括号,尤其是在复杂的 Bash 脚本中,以确保无误。 这时候就需要 [vim-rainbow](http://github.com/frazrepo/vim-rainbow) 插件!它为每对括号设置不同的颜色,因此很容易识别出哪些括号是一对括号。它非常有用而且五彩斑斓。 ![vim-rainbow plugin](/data/attachment/album/201912/05/062341ima6c9a1w2acwuyz.png "vim-rainbow plugin") ### 3、lightline Vim 有很多这种插件,例如 [Powerline](https://github.com/powerline/powerline),它会在底部栏显示你正在处理的文件、光标所在的文件位置以及文件类型等信息。这些插件各有利弊,在简单比较后,我选择了 [lightline](http://github.com/itchyny/lightline.vim)。它相对较小,便于安装和扩展,并且不依赖于其他工具或插件。 ![Lightline plugin](/data/attachment/album/201912/05/062341zbqwr88dvfq6sd8s.png "Lightline plugin") ### 4、NERDTree [NERDTree](http://github.com/scrooloose/nerdtree) 是一个很经典的插件。在大型项目中,你可能很难找到想要编辑的内容所在文件的确切名称和路径。使用快捷键(我使用的是 `F7`,因为我在 `.vimrc` 中配置了这个快捷键),搜索窗会以垂直分屏的方式打开,就可以轻松找到所需文件并打开它。对于大型项目,这是必备插件。对于那些经常忘记文件名的人也很有用,比如我。 ![NERDTree vim plugin](/data/attachment/album/201912/05/062342w464yfz4z9f9h99y.gif "NERDTree vim plugin") ### 5、NERD Commenter 程序员们在写代码时,有时会遇到一些难以调试的问题,导致他们想要注释或不执行某段代码。这时候就需要 [NERD Commenter](http://github.com/scrooloose/nerdcommenter) 出场了。选择代码段,按 `Leader 键 + cc`,代码就会被注释掉。(标准的 Vim Leader 键 是 `/` 字符。)按 `Leader 键 + cn`,取消注释。对于大多数文件类型,NERD Commenter 会自动使用正确的注释符。例如,如果你正在编辑 [BIND 区域文件](https://en.wikipedia.org/wiki/Zone_file#File_format),并将文件类型设置为 BIND 区域文件,Vim 会正确地使用 `;`(分号)字符进行注释。 ![NERD Commenter](/data/attachment/album/201912/05/062343mcopxuiwjimmoip3.gif "NERD Commenter") ### 6、Solarized 我喜欢我的 Vim 主题配色。我也喜欢终端的主题色。我一直在 Vim 上使用 [Solarized](https://github.com/altercation/vim-colors-solarized) 配色,并且将我的终端、文件夹配色和 Vim 设为一致。 但是,有时我会根据周边环境、屏幕亮度以及是否需要分享投屏,来切换明暗模式。 显然,你可以选择自己喜欢的任何配色方案,但我喜欢 `Solarized`,因为它有明暗模式功能,它可以简单快捷地切换两种模式。我的第二个选择是 [Monokai](https://github.com/sickill/vim-monokai)。Volt 插件管理器让我可以轻松地在两者之间切换,因此我在 Python 编程时,使用 Monokai;Bash 编程时,使用 Solarized。 我没有给 Solarized 找相应的图片,因为本文中的所有其他图片都使用了 Solarized 中的浅色或深色效果,可以确认一下这些图片。 ### 7、fzf 当寻找一个文件时,有时你想要一个文件浏览器,有时你只想在键盘上敲打出与文件名模糊匹配的内容,对吗? [fzf](https://github.com/junegunn/fzf.vim)(全称 “模糊查找器”)插件提供了这一功能。打出 `:FZF` 并输入文件名内容。不断缩短的列表将显示出与你输入的文件名内容相匹配的一些文件。我经常使用它,最近使用它的频率估计比使用 NERDTree 还多。缺点是这个插件依赖于 `fzf binary`,因此也必须安装这个依赖包。它适用于 Fedora、Debian 和 Arch,据我所知并不在 EPEL 中。 ![fzf Vim plugin](/data/attachment/album/201912/05/062343biuiilog4fwicqw7.gif "fzf Vim plugin") ### 8、ack 有时,你需要搜索包含特定行或特定单词的文件。我真的很喜欢使用 [ack](https://github.com/mileszs/ack.vim) 插件,最好与 `ag` 结合使用,它俩的组合又被称为 “[silver searcher](https://github.com/ggreer/the_silver_searcher)”。这一组合的速度非常快,覆盖了 `grep` 或 `vimgrep` 的绝大多数使用场景。缺点是你需要安装 `ack` 或 `ag` 才能正常运行。好消息是 Fedora 和 EPEL7 都可以使用 `ag` 和 `ack`。 ![ack vim plugin](/data/attachment/album/201912/05/062344puy0y3xgtxiarjdb.gif "ack vim plugin") ### 9、gitgutter 大多数 IT 人员都使用 [Git](https://opensource.com/resources/what-is-git) 和 Git 仓库中的文件进行工作。[gitgutter](https://github.com/airblade/vim-gitgutter) 插件在行号附近添加了一列,通过符号显示该行的状态为:已更改(`~`)、已添加(`+`)或者已删除(`-`)。这有利于跟踪你所做的更改,并且可以使你专注于手头的任务,例如编写补丁来修复一个关键错误。 ![gitgutter vim plugin](/data/attachment/album/201912/05/062344c0p1pkryufhr1fmz.png "gitgutter vim plugin") ### 10、Tag List 如果你在一个很大的文件中编写代码,会很容易忘记当前所在的位置,你可能需要上下滚动来查找某个功能。使用 [Tag List](https://github.com/vim-scripts/taglist.vim) 插件,只需要输入 `:Tlist`,就能垂直分屏显示出包含变量、类型、类和函数的代码,你可以轻松跳转到这些变量、类型、类和函数。这个功能对于多语言同样适用,例如 Java、Python 以及任何能够使用 `ctags` 功能的文件类型。 ![Tag List vim plugin](/data/attachment/album/201912/05/062345d4fkme7550me7xji.gif "Tag List vim plugin) ) ) ") 以上介绍的 10 个 Vim 插件使我作为系统管理员和兼职程序员的生活变得更轻松。你正在使用哪些 Vim 插件?请在评论中分享你最爱的插件。 --- via: <https://opensource.com/article/19/11/vim-plugins> 作者:[Maxim Burgerhout](https://opensource.com/users/wzzrd) 选题:[lujun9972](https://github.com/lujun9972) 译者:[hello-wn](https://github.com/hello-wn) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
I've been a user of the [Vim](https://www.vim.org/) text editor for about two decades. For a little while, I have been customizing my Vim configuration, only using plugins for the last couple of years. Recently, when I was redoing my setup (as I do every so often), I decided it was a good opportunity to identify the best Vim plugins for programming in multiple languages and a way to combine those plugins for each language I program in. I do use certain plugins for specific languages and profiles (e.g., I only install Rocannon in my Ansible profile), and I won't go into those here—that would be a *long* list. But the 10 Vim plugins described below are my favorites, the ones I use in virtually every profile I have, no matter what programming language I'm using. ## 1. Volt My number one pick isn't even a plugin; rather, it replaces plugins like [Vundle](https://github.com/VundleVim/Vundle.vim), so I'm listing it here. [Volt](https://github.com/vim-volt/volt) is a Vim plugin manager that lives outside Vim. You can use it to install plugins and create combinations of plugins called "profiles." You can enable a new profile with a single command: **volt profile set myprofile**. That way, I can do things like enable the [indentpython](https://github.com/vim-scripts/indentpython.vim) plugin for just my Python profile. Volt also offers a simple way to do per-plugin configurations. The configuration is shared between profiles, so you can install plugins once and use them in multiple profiles. Volt is still relatively new and not perfect (e.g., you can have just one configuration file per plugin, no matter how many profiles you are using), but apart from that, I find it extremely handy, extremely fast, and extremely simple. ![Volt plugin Volt plugin](https://opensource.com/sites/default/files/uploads/vim-volt.gif) ## 2. Vim-Rainbow Except for Python, virtually all major programming languages use brackets. Round ones, square ones, and curly ones. Often, they use multiple pairs of brackets, with one pair embedded in another. Figuring out which closing bracket belongs to what opening bracket can become difficult and annoying. I often find myself counting round brackets—especially in complicated Bash scripts—to make sure I got everything right. Here's the [vim-rainbow](http://github.com/frazrepo/vim-rainbow) plugin to the rescue! It gives every pair of brackets a unique color, so it's easy to identify which brackets belong to each other. It's very useful and very colorful, too. ![vim-rainbow plugin vim-rainbow plugin](https://opensource.com/sites/default/files/uploads/vim-rainbox.png) ## 3. lightline There are a lot of plugins for Vim, such as [Powerline](https://github.com/powerline/powerline), that put a bar at the bottom of the screen to show you what file you are working on, where you are in the file, what type of file it is, etc. Each of these plugins has advantages and disadvantages, and after briefly weighing them, I chose [lightline](http://github.com/itchyny/lightline.vim). It's relatively small, easy to set up, quite extensible if you are into that kind of thing, and doesn't require any other tooling or plugins. ![Lightline plugin Lightline plugin](https://opensource.com/sites/default/files/uploads/lightline.png) ## 4. NERDTree [NERDTree](http://github.com/scrooloose/nerdtree) is a classic. In large projects, it can be hard to find the exact name and location of the one file that includes the one line you need to edit. With a quick keystroke (**F7**, in my case, as I bound NERDTree to F7 in my .vimrc configuration file), an explorer window opens in a vertical split, and I can easily browse to the file I want and open it. It's a must for large bodies of code. Or for people that tend to forget filenames, like me. ![NERDTree vim plugin NERDTree vim plugin](https://opensource.com/sites/default/files/uploads/nerdtree.gif) ## 5. NERD Commenter All programmers, at some time, write code that introduces a hard-to-debug problem that leads them to decide to comment out or undo the code. This is where [NERD Commenter](http://github.com/scrooloose/nerdcommenter) comes in. Select the code, hit **Leader+cc**, and your code is commented. (The standard Vim Leader key is the **/** character.) Hit **Leader+cn, **and your code is uncommented. NERD Commenter should automatically use the right commenting character for most file types. For example, if you are editing a [BIND zone file](https://en.wikipedia.org/wiki/Zone_file#File_format) and set the file type to bind zone, Vim will correctly use the **;** (semicolon) character to comment lines out. ![NERD Commenter NERD Commenter](https://opensource.com/sites/default/files/uploads/nerdcommenter.gif) ## 6. Solarized I love my Vim colors. Really, I love terminal colors in general. I've been using the [Solarized](https://github.com/altercation/vim-colors-solarized) color scheme for Vim for a long time, and I set up my terminal, dir_colors, and Vim to be consistent. Every now and then, though, I toggle between light and dark modes, depending on what kind of environment I'm in, the amount of light falling on my screen, and whether I need to put something on a big screen for others to read. Obviously, you can grab any ol' color scheme you like, but I like the fact that Solarized has light and dark modes, an easy way to switch between the two, and it's not too intrusive. My second choice is [Monokai](https://github.com/sickill/vim-monokai). The Volt plugin manager makes it easy for me to switch between the two, so I can use Monokai for Python programming and Solarized for Bash. I'm not including an image for Solarized, because all the other images in this article use Solarized light or dark, so check them out. ## 7. fzf When you're looking for a file, sometimes you want a file explorer, and sometimes you just want to ram something on your keyboard that vaguely resembles the filename you are looking for, amirite? The [fzf](https://github.com/junegunn/fzf.vim) (or "fuzzy finder") plugin gives you just that. Hit **:FZF** and start typing. An ever-shortening list will show you files that more or less match what you are looking for. I use this a lot, probably even more than NERDTree these days. A slight downside is that this plugin has an external dependency in the fzf binary, so you'll have to install that, too. It's available for Fedora, Debian and, Arch, but I don't think it exists for EPEL. ![fzf Vim plugin fzf Vim plugin](https://opensource.com/sites/default/files/uploads/fzf.gif) ## 8. ack Every once in a while, you want to search for a file that contains a certain line or a certain word. I really like the [ack](https://github.com/mileszs/ack.vim) plugin for this, preferably in combination with **ag**, a command known as "the [silver searcher](https://github.com/ggreer/the_silver_searcher)." This combination is phenomenally fast and covers the vast majority of things I would use **grep** or **vimgrep** for. The downside is you'll need to install either ack or ag for it to work. The good news is that both ag and ack are available for Fedora and EPEL7. ![ack vim plugin ack vim plugin](https://opensource.com/sites/default/files/uploads/ack.gif) ## 9. gitgutter The majority of IT folks have worked with [Git](https://opensource.com/resources/what-is-git) and files in Git repositories. The [gitgutter](https://github.com/airblade/vim-gitgutter) plugin adds a column near your line numbers that shows symbols for changed (**~**), added (**+**), and removed (**-**) lines. This is quite useful for keeping track of what you have changed, and it keeps you focused on the task at hand, like writing a patch to fix one key bug. This plugin has a slight performance gap, and it sometimes takes a quick second for the plugin to catch up with your changes, but it's still quite useful. ![gitgutter vim plugin gitgutter vim plugin](https://opensource.com/sites/default/files/uploads/gitgutter.png) ## 10. Tag List If you are programming in a file of any significant size, it's easy to lose track of where you are, and you might find yourself scrolling up and down looking for a certain function. With the [Tag List](https://github.com/vim-scripts/taglist.vim) plugin, you can just type **:Tlist** and get a vertical split with variables, types, classes, and functions that you can easily jump to. This works for a host of languages, like Java, Python, and any other file type the **ctags** utility works with … which is a lot. ![Tag List vim plugin Tag List vim plugin](https://opensource.com/sites/default/files/uploads/taglist.gif) So there you are: the 10 plugins for Vim that have made my life as a sysadmin and part-time programmer a little easier and a little better. What Vim plugins you are using? Please share your favorites in the comments. ## 4 Comments
11,645
Bash 脚本实现每次登录到 Shell 时可以查看 Linux 系统信息
https://www.2daygeek.com/bash-shell-script-view-linux-system-information/
2019-12-05T06:50:00
[ "Linux" ]
https://linux.cn/article-11645-1.html
![](/data/attachment/album/201912/05/064953aelh05hk0hfz00fe.jpg) Linux 中有很多可以查看系统信息如处理器信息、生产商名字、序列号等的命令。你可能需要执行多个命令来收集这些信息。同时,记住所有的命令和他们的选项也是有难度。 你可以写一个 [shell 脚本](https://www.2daygeek.com/category/shell-script/) 基于你的需求来自定义显示的信息。 以前我们出于不同的目的需要写很多个 [bash 脚本](https://www.2daygeek.com/category/bash-script/)。 现在我们写一个新的 shell 脚本,在每次登录到 shell 时显示需要的系统信息。 这个脚本有 6 部分,细节如下: 1. 通用系统信息 2. CPU/内存当前使用情况 3. 硬盘使用率超过 80% 4. 列出系统 WWN 详情 5. Oracle DB 实例 6. 可更新的包 我们已经基于我们的需求把可能需要到的信息加到了每个部分。之后你可以基于自己的意愿修改这个脚本。 这个j脚本需要用到很多工具,其中大部分我们之前已经涉及到了。 你可以参照以前文章,了解工具详情。 * [inxi – 在 Linux 上检查硬件信息的绝佳工具](https://www.2daygeek.com/inxi-system-hardware-information-on-linux/) * [Dmidecode – 获取 Linux 系统硬件信息的简便方法](https://www.2daygeek.com/dmidecode-get-print-display-check-linux-system-hardware-information/) * [LSHW(硬件列表程序)– 在 Linux 上获取硬件信息的漂亮工具](https://www.2daygeek.com/lshw-find-check-system-hardware-information-details-linux/) * [hwinfo(硬件信息)– 在 Linux 上检测系统硬件信息的漂亮工具](https://www.2daygeek.com/hwinfo-check-display-detect-system-hardware-information-linux/) * [python-hwinfo:使用标准 Linux 实用工具显示硬件信息摘要](https://www.2daygeek.com/python-hwinfo-check-display-system-hardware-configuration-information-linux/) * [如何使用 lspci、lsscsi、lsusb 和 lsblk 获取 Linux 系统设备信息](https://www.2daygeek.com/check-system-hardware-devices-bus-information-lspci-lsscsi-lsusb-lsblk-linux/) * [如何在 Linux 中检查系统硬件制造商、型号和序列号](https://www.2daygeek.com/how-to-check-system-hardware-manufacturer-model-and-serial-number-in-linux/) * [如何在 Linux 中查找 HBA 卡的 WWN、WWNN 和 WWPN 号](https://www.2daygeek.com/how-to-find-wwn-wwnn-and-wwpn-number-of-hba-card-in-linux/) * [如何从 Linux 命令行检查 HP iLO 固件版本](https://www.2daygeek.com/how-to-check-hp-ilo-firmware-version-from-linux-command-line/) * [如何从 Linux 命令行检查无线网卡和 WiFi 信息](https://www.2daygeek.com/linux-find-out-wireless-network-wifi-speed-signal-strength-quality/) * [如何在 Linux 上检查 CPU 和硬盘温度](https://www.2daygeek.com/view-check-cpu-hard-disk-temperature-linux/) * [Hegemon – Linux 的模块化系统和硬件监视工具](https://www.2daygeek.com/hegemon-a-modular-system-and-hardware-monitoring-tool-for-linux/) * [如何在 Linux 上检查系统配置和硬件信息](https://www.2daygeek.com/check-linux-hardware-information-system-configuration/) 如果你想为这个脚本增加其他的信息,请在评论去留下你的需求,以便我们帮助你。 ### Bash 脚本实现每次登录到 Shell 时可以查看 Linux 系统信息 这个脚本会在你每次登录 shell 时把系统信息打印到 terminal。 ``` # vi /opt/scripts/system-info.sh ``` ``` #!/bin/bash echo -e "-------------------------------System Information----------------------------" echo -e "Hostname:\t\t"`hostname` echo -e "uptime:\t\t\t"`uptime | awk '{print $3,$4}' | sed 's/,//'` echo -e "Manufacturer:\t\t"`cat /sys/class/dmi/id/chassis_vendor` echo -e "Product Name:\t\t"`cat /sys/class/dmi/id/product_name` echo -e "Version:\t\t"`cat /sys/class/dmi/id/product_version` echo -e "Serial Number:\t\t"`cat /sys/class/dmi/id/product_serial` echo -e "Machine Type:\t\t"`vserver=$(lscpu | grep Hypervisor | wc -l); if [ $vserver -gt 0 ]; then echo "VM"; else echo "Physical"; fi` echo -e "Operating System:\t"`hostnamectl | grep "Operating System" | cut -d ' ' -f5-` echo -e "Kernel:\t\t\t"`uname -r` echo -e "Architecture:\t\t"`arch` echo -e "Processor Name:\t\t"`awk -F':' '/^model name/ {print $2}' /proc/cpuinfo | uniq | sed -e 's/^[ \t]*//'` echo -e "Active User:\t\t"`w | cut -d ' ' -f1 | grep -v USER | xargs -n1` echo -e "System Main IP:\t\t"`hostname -I` echo "" echo -e "-------------------------------CPU/Memory Usage------------------------------" echo -e "Memory Usage:\t"`free | awk '/Mem/{printf("%.2f%"), $3/$2*100}'` echo -e "Swap Usage:\t"`free | awk '/Swap/{printf("%.2f%"), $3/$2*100}'` echo -e "CPU Usage:\t"`cat /proc/stat | awk '/cpu/{printf("%.2f%\n"), ($2+$4)*100/($2+$4+$5)}' | awk '{print $0}' | head -1` echo "" echo -e "-------------------------------Disk Usage >80%-------------------------------" df -Ph | sed s/%//g | awk '{ if($5 > 80) print $0;}' echo "" echo -e "-------------------------------For WWN Details-------------------------------" vserver=$(lscpu | grep Hypervisor | wc -l) if [ $vserver -gt 0 ] then echo "$(hostname) is a VM" else cat /sys/class/fc_host/host?/port_name fi echo "" echo -e "-------------------------------Oracle DB Instances---------------------------" if id oracle >/dev/null 2>&1; then /bin/ps -ef|grep pmon then else echo "oracle user does not exist on $(hostname)" fi echo "" if (( $(cat /etc/*-release | grep -w "Oracle|Red Hat|CentOS|Fedora" | wc -l) > 0 )) then echo -e "-------------------------------Package Updates-------------------------------" yum updateinfo summary | grep 'Security|Bugfix|Enhancement' echo -e "-----------------------------------------------------------------------------" else echo -e "-------------------------------Package Updates-------------------------------" cat /var/lib/update-notifier/updates-available echo -e "-----------------------------------------------------------------------------" fi ``` 把上面脚本内容保存到一个文件 `system-info.sh`,之后添加可执行权限: ``` # chmod +x ~root/system-info.sh ``` 当脚本准备好后,把脚本文件的路径加到 `.bash_profile` 文件末尾(红帽系列的系统:CentOS、Oracle Linux 和 Fedora): ``` # echo "/root/system-info.sh" >> ~root/.bash_profile ``` 执行以下命令,来让修改的内容生效: ``` # source ~root/.bash_profile ``` 对于 Debian 系统的系统,你可能需要把文件路径加到 `.profile` 文件中: ``` # echo "/root/system-info.sh" >> ~root/.profile ``` 运行以下命令使修改生效: ``` # source ~root/.profile ``` 你以前运行上面 `source` 命令时可能见过类似下面的输出。从下次开始,你在每次登录 shell 时会看到这些信息。当然,如果有必要你也可以随时手动执行这个脚本。 ``` -------------------------------System Information--------------------------- Hostname: daygeek-Y700 uptime: 1:20 1 Manufacturer: LENOVO Product Name: 80NV Version: Lenovo ideapad Y700-15ISK Serial Number: AA0CMRN1 Machine Type: Physical Operating System: Manjaro Linux Kernel: 4.19.80-1-MANJARO Architecture: x86_64 Processor Name: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz Active User: daygeek renu thanu System Main IP: 192.168.1.6 192.168.122.1 -------------------------------CPU/Memory Usage------------------------------ Memory Usage: 37.28% Swap Usage: 0.00% CPU Usage: 15.43% -------------------------------Disk Usage >80%------------------------------- Filesystem Size Used Avail Use Mounted on /dev/nvme0n1p1 217G 202G 4.6G 98 / /dev/loop0 109M 109M 0 100 /var/lib/snapd/snap/odrive-unofficial/2 /dev/loop1 91M 91M 0 100 /var/lib/snapd/snap/core/6405 /dev/loop2 90M 90M 0 100 /var/lib/snapd/snap/core/7713 -------------------------------For WWN Details------------------------------- CentOS8.2daygeek.com is a VM -------------------------------Oracle DB Instances--------------------------- oracle user does not exist on CentOS8.2daygeek.com -------------------------------Package Updates------------------------------- 13 Security notice(s) 9 Important Security notice(s) 3 Moderate Security notice(s) 1 Low Security notice(s) 35 Bugfix notice(s) 1 Enhancement notice(s) ----------------------------------------------------------------------------- ``` --- via: <https://www.2daygeek.com/bash-shell-script-view-linux-system-information/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
11,647
5 个鲜为人知 GNU 调试器(GDB)技巧
https://opensource.com/article/19/9/tips-gnu-debugger
2019-12-05T20:37:12
[ "gdb", "调试" ]
https://linux.cn/article-11647-1.html
> > 了解如何使用 gdb 的一些鲜为人知的功能来检查和修复代码。 > > > ![](/data/attachment/album/201912/05/203701ss8onfvpsnvnsnn5.jpg) [GNU 调试器](https://www.gnu.org/software/gdb/)(`gdb`)是一种宝贵的工具,可用于在开发程序时检查正在运行的进程并解决问题。 你可以在特定位置(按函数名称、行号等)设置断点、启用和禁用这些断点、显示和更改变量值,并执行所有调试器希望执行的所有标准操作。但是它还有许多其它你可能没有尝试过的功能。这里有五个你可以尝试一下。 ### 条件断点 设置断点是学习使用 GNU 调试器的第一步。程序在达到断点时停止,你可以运行 `gdb` 的命令对其进行检查或更改变量,然后再允许该程序继续运行。 例如,你可能知道一个经常调用的函数有时会崩溃,但仅当它获得某个参数值时才会崩溃。你可以在该函数的开始处设置一个断点并运行程序。每次碰到该断点时都会显示函数参数,并且如果未提供触发崩溃的参数值,则可以继续操作,直到再次调用该函数为止。当这个惹了麻烦的参数触发崩溃时,你可以单步执行代码以查看问题所在。 ``` (gdb) break sometimes_crashes Breakpoint 1 at 0x40110e: file prog.c, line 5. (gdb) run [...] Breakpoint 1, sometimes_crashes (f=0x7fffffffd1bc) at prog.c:5 5 fprintf(stderr, (gdb) continue Breakpoint 1, sometimes_crashes (f=0x7fffffffd1bc) at prog.c:5 5 fprintf(stderr, (gdb) continue ``` 为了使此方法更具可重复性,你可以在你感兴趣的特定调用之前计算该函数被调用的次数,并在该断点处设置一个计数器(例如,`continue 30` 以使其在接下来的 29 次到达该断点时忽略它)。 但是断点真正强大的地方在于它们在运行时评估表达式的能力,这使你可以自动化这种测试。 ``` break [LOCATION] if CONDITION (gdb) break sometimes_crashes if !f Breakpoint 1 at 0x401132: file prog.c, line 5. (gdb) run [...] Breakpoint 1, sometimes_crashes (f=0x0) at prog.c:5 5 fprintf(stderr, (gdb) ``` 条件断点使你不必让 `gdb` 每次调用该函数时都去问你要做什么,而是让条件断点仅在特定表达式的值为 `true` 时才使 `gdb` 停止在该位置。如果执行到达条件断点的位置,但表达式的计算结果为 `false`,调试器会自动使程序继续运行,而无需询问用户该怎么做。 ### 断点命令 GNU 调试器中断点的一个甚至更复杂的功能是能够编写对到达断点的响应的脚本。断点命令使你可以编写一系列 GNU 调试器命令,以在到达该断点时运行。 我们可以使用它来规避在 `sometimes_crashes` 函数中我们已知的错误,并在它提供空指针时使其无害地从该函数返回。 我们可以使用 `silent` 作为第一行,以更好地控制输出。否则,每次命中断点时,即使在运行断点命令之前,也会显示堆栈帧。 ``` (gdb) break sometimes_crashes Breakpoint 1 at 0x401132: file prog.c, line 5. (gdb) commands 1 Type commands for breakpoint(s) 1, one per line. End with a line saying just "end". >silent >if !f >frame >printf "Skipping call\n" >return 0 >continue >end >printf "Continuing\n" >continue >end (gdb) run Starting program: /home/twaugh/Documents/GDB/prog warning: Loadable section ".note.gnu.property" outside of ELF segments Continuing Continuing Continuing #0 sometimes_crashes (f=0x0) at prog.c:5 5 fprintf(stderr, Skipping call [Inferior 1 (process 9373) exited normally] (gdb) ``` ### 转储二进制内存 GNU 调试器内置支持使用 `x` 命令以各种格式检查内存,包括八进制、十六进制等。但是我喜欢并排看到两种格式:左侧为十六进制字节,右侧为相同字节表示的 ASCII 字符。 当我想逐字节查看文件的内容时,经常使用 `hexdump -C`(`hexdump` 来自 [util-linux](https://en.wikipedia.org/wiki/Util-linux) 软件包)。这是 `gdb` 的 `x` 命令显示的十六进制字节: ``` (gdb) x/33xb mydata 0x404040 <mydata> : 0x02 0x01 0x00 0x02 0x00 0x00 0x00 0x01 0x404048 <mydata+8> : 0x01 0x47 0x00 0x12 0x61 0x74 0x74 0x72 0x404050 <mydata+16>: 0x69 0x62 0x75 0x74 0x65 0x73 0x2d 0x63 0x404058 <mydata+24>: 0x68 0x61 0x72 0x73 0x65 0x75 0x00 0x05 0x404060 <mydata+32>: 0x00 ``` 如果你想让 `gdb` 像 `hexdump` 一样显示内存怎么办?这是可以的,实际上,你可以将这种方法用于你喜欢的任何格式。 通过使用 `dump` 命令以将字节存储在文件中,结合 `shell` 命令以在文件上运行 `hexdump` 以及`define` 命令,我们可以创建自己的新的 `hexdump` 命令来使用 `hexdump` 显示内存内容。 ``` (gdb) define hexdump Type commands for definition of "hexdump". End with a line saying just "end". >dump binary memory /tmp/dump.bin $arg0 $arg0+$arg1 >shell hexdump -C /tmp/dump.bin >end ``` 这些命令甚至可以放在 `~/.gdbinit` 文件中,以永久定义 `hexdump` 命令。以下是它运行的例子: ``` (gdb) hexdump mydata sizeof(mydata) 00000000 02 01 00 02 00 00 00 01 01 47 00 12 61 74 74 72 |.........G..attr| 00000010 69 62 75 74 65 73 2d 63 68 61 72 73 65 75 00 05 |ibutes-charseu..| 00000020 00 |.| 00000021 ``` ### 行内反汇编 有时你想更多地了解导致崩溃的原因,而源代码还不够。你想查看在 CPU 指令级别发生了什么。 `disassemble` 命令可让你查看实现函数的 CPU 指令。但是有时输出可能很难跟踪。通常,我想查看与该函数源代码的特定部分相对应的指令。为此,请使用 `/s` 修饰符在反汇编中包括源代码行。 ``` (gdb) disassemble/s main Dump of assembler code for function main: prog.c: 11 { 0x0000000000401158 <+0>: push %rbp 0x0000000000401159 <+1>: mov %rsp,%rbp 0x000000000040115c <+4>: sub $0x10,%rsp 12 int n = 0; 0x0000000000401160 <+8>: movl $0x0,-0x4(%rbp) 13 sometimes_crashes(&n); 0x0000000000401167 <+15>: lea -0x4(%rbp),%rax 0x000000000040116b <+19>: mov %rax,%rdi 0x000000000040116e <+22>: callq 0x401126 <sometimes_crashes> [...snipped...] ``` 这里,用 `info` 寄存器查看所有 CPU 寄存器的当前值,以及用如 `stepi` 这样命令一次执行一条指令,可以使你对程序有了更详细的了解。 ### 反向调试 有时,你希望自己可以逆转时间。想象一下,你已经达到了变量的监视点。监视点像是一个断点,但不是在程序中的某个位置设置,而是在表达式上设置(使用 `watch` 命令)。每当表达式的值更改时,执行就会停止,并且调试器将获得控制权。 想象一下你已经达到了这个监视点,并且由该变量使用的内存已更改了值。事实证明,这可能是由更早发生的事情引起的。例如,内存已释放,现在正在重新使用。但是它是何时何地被释放的呢? GNU 调试器甚至可以解决此问题,因为你可以反向运行程序! 它通过在每个步骤中仔细记录程序的状态来实现此目的,以便可以恢复以前记录的状态,从而产生时间倒流的错觉。 要启用此状态记录,请使用 `target record-full` 命令。然后,你可以使用一些听起来不太可行的命令,例如: * `reverse-step`,倒退到上一个源代码行 * `*reverse-next`,它倒退到上一个源代码行,向后跳过函数调用 * `reverse-finish`,倒退到当前函数即将被调用的时刻 * `reverse-continue`,它返回到程序中的先前状态,该状态将(现在)触发断点(或其他导致断点停止的状态) 这是运行中的反向调试的示例: ``` (gdb) b main Breakpoint 1 at 0x401160: file prog.c, line 12. (gdb) r Starting program: /home/twaugh/Documents/GDB/prog [...] Breakpoint 1, main () at prog.c:12 12 int n = 0; (gdb) target record-full (gdb) c Continuing. Program received signal SIGSEGV, Segmentation fault. 0x0000000000401154 in sometimes_crashes (f=0x0) at prog.c:7 7 return *f; (gdb) reverse-finish Run back to call of #0 0x0000000000401154 in sometimes_crashes (f=0x0) at prog.c:7 0x0000000000401190 in main () at prog.c:16 16 sometimes_crashes(0); ``` 这些只是 GNU 调试器可以做的一些有用的事情。还有更多有待发现。你最喜欢 `gdb` 的哪个隐藏的、鲜为人知或令人吃惊的功能?请在评论中分享。 --- via: <https://opensource.com/article/19/9/tips-gnu-debugger> 作者:[Tim Waugh](https://opensource.com/users/twaugh) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The [GNU Debugger](https://www.gnu.org/software/gdb/) (gdb) is an invaluable tool for inspecting running processes and fixing problems while you're developing programs. You can set breakpoints at specific locations (by function name, line number, and so on), enable and disable those breakpoints, display and alter variable values, and do all the standard things you would expect any debugger to do. But it has many other features you might not have experimented with. Here are five for you to try. ## Conditional breakpoints Setting a breakpoint is one of the first things you'll learn to do with the GNU Debugger. The program stops when it reaches a breakpoint, and you can run gdb commands to inspect it or change variables before allowing the program to continue. For example, you might know that an often-called function crashes sometimes, but only when it gets a certain parameter value. You could set a breakpoint at the start of that function and run the program. The function parameters are shown each time it hits the breakpoint, and if the parameter value that triggers the crash is not supplied, you can continue until the function is called again. When the troublesome parameter triggers a crash, you can step through the code to see what's wrong. ``` (gdb) break sometimes_crashes Breakpoint 1 at 0x40110e: file prog.c, line 5. (gdb) run [...] Breakpoint 1, sometimes_crashes (f=0x7fffffffd1bc) at prog.c:5 5 fprintf(stderr, (gdb) continue Breakpoint 1, sometimes_crashes (f=0x7fffffffd1bc) at prog.c:5 5 fprintf(stderr, (gdb) continue ``` To make this more repeatable, you could count how many times the function is called before the specific call you are interested in, and set a counter on that breakpoint (for example, "continue 30" to make it ignore the next 29 times it reaches the breakpoint). But where breakpoints get really powerful is in their ability to evaluate expressions at runtime, which allows you to automate this kind of testing. Enter: conditional breakpoints. ``` break [LOCATION] if CONDITION (gdb) break sometimes_crashes if !f Breakpoint 1 at 0x401132: file prog.c, line 5. (gdb) run [...] Breakpoint 1, sometimes_crashes (f=0x0) at prog.c:5 5 fprintf(stderr, (gdb) ``` Instead of having gdb ask what to do every time the function is called, a conditional breakpoint allows you to make gdb stop at that location only when a particular expression evaluates as true. If the execution reaches the conditional breakpoint location, but the expression evaluates as false, the debugger automatically lets the program continue without asking the user what to do. ## Breakpoint commands An even more sophisticated feature of breakpoints in the GNU Debugger is the ability to script a response to reaching a breakpoint. Breakpoint commands allow you to write a list of GNU Debugger commands to run whenever it reaches a breakpoint. We can use this to work around the bug we already know about in the **sometimes_crashes** function and make it return from that function harmlessly when it provides a null pointer. We can use **silent** as the first line to get more control over the output. Without this, the stack frame will be displayed each time the breakpoint is hit, even before our breakpoint commands run. ``` (gdb) break sometimes_crashes Breakpoint 1 at 0x401132: file prog.c, line 5. (gdb) commands 1 Type commands for breakpoint(s) 1, one per line. End with a line saying just "end". >silent >if !f >frame >printf "Skipping call\n" >return 0 >continue >end >printf "Continuing\n" >continue >end (gdb) run Starting program: /home/twaugh/Documents/GDB/prog warning: Loadable section ".note.gnu.property" outside of ELF segments Continuing Continuing Continuing #0 sometimes_crashes (f=0x0) at prog.c:5 5 fprintf(stderr, Skipping call [Inferior 1 (process 9373) exited normally] (gdb) ``` ## Dump binary memory GNU Debugger has built-in support for examining memory using the **x** command in various formats, including octal, hexadecimal, and so on. But I like to see two formats side by side: hexadecimal bytes on the left, and ASCII characters represented by those same bytes on the right. When I want to view the contents of a file byte-by-byte, I often use **hexdump -C** (hexdump comes from the [util-linux](https://en.wikipedia.org/wiki/Util-linux) package). Here is gdb's **x** command displaying hexadecimal bytes: ``` (gdb) x/33xb mydata 0x404040 <mydata>: 0x02 0x01 0x00 0x02 0x00 0x00 0x00 0x01 0x404048 <mydata+8>: 0x01 0x47 0x00 0x12 0x61 0x74 0x74 0x72 0x404050 <mydata+16>: 0x69 0x62 0x75 0x74 0x65 0x73 0x2d 0x63 0x404058 <mydata+24>: 0x68 0x61 0x72 0x73 0x65 0x75 0x00 0x05 0x404060 <mydata+32>: 0x00 ``` What if you could teach gdb to display memory just like hexdump does? You can, and in fact, you can use this method for any format you prefer. By combining the **dump** command to store the bytes in a file, the **shell** command to run hexdump on the file, and the **define** command, we can make our own new **hexdump** command to use hexdump to display the contents of memory. ``` (gdb) define hexdump Type commands for definition of "hexdump". End with a line saying just "end". >dump binary memory /tmp/dump.bin $arg0 $arg0+$arg1 >shell hexdump -C /tmp/dump.bin >end ``` Those commands can even go in the **~/.gdbinit** file to define the hexdump command permanently. Here it is in action: ``` (gdb) hexdump mydata sizeof(mydata) 00000000 02 01 00 02 00 00 00 01 01 47 00 12 61 74 74 72 |.........G..attr| 00000010 69 62 75 74 65 73 2d 63 68 61 72 73 65 75 00 05 |ibutes-charseu..| 00000020 00 |.| 00000021 ``` ## Inline disassembly Sometimes you want to understand more about what happened leading up to a crash, and the source code is not enough. You want to see what's going on at the CPU instruction level. The **disassemble** command lets you see the CPU instructions that implement a function. But sometimes the output can be hard to follow. Usually, I want to see what instructions correspond to a certain section of source code in the function. To achieve this, use the **/s** modifier to include source code lines with the disassembly. ``` (gdb) disassemble/s main Dump of assembler code for function main: prog.c: 11 { 0x0000000000401158 <+0>: push %rbp 0x0000000000401159 <+1>: mov %rsp,%rbp 0x000000000040115c <+4>: sub $0x10,%rsp 12 int n = 0; 0x0000000000401160 <+8>: movl $0x0,-0x4(%rbp) 13 sometimes_crashes(&n); 0x0000000000401167 <+15>: lea -0x4(%rbp),%rax 0x000000000040116b <+19>: mov %rax,%rdi 0x000000000040116e <+22>: callq 0x401126 <sometimes_crashes> [...snipped...] ``` This, along with **info registers** to see the current values of all the CPU registers and commands like **stepi** to step one instruction at a time, allow you to have a much more detailed understanding of the program. ## Reverse debug Sometimes you wish you could turn back time. Imagine you've hit a watchpoint on a variable. A watchpoint is like a breakpoint, but instead of being set at a location in the program, it is set on an expression (using the **watch** command). Whenever the value of the expression changes, execution stops, and the debugger takes control. So imagine you've hit this watchpoint, and the memory used by a variable has changed value. This can turn out to be caused by something that occurred much earlier; for example, the memory was freed and is now being re-used. But when and why was it freed? The GNU Debugger can solve even this problem because you can run your program in reverse! It achieves this by carefully recording the state of the program at each step so that it can restore previously recorded states, giving the illusion of time flowing backward. To enable this state recording, use the **target record-full** command. Then you can use impossible-sounding commands, such as: **reverse-step**, which rewinds to the previous source line**reverse-next**, which rewinds to the previous source line, stepping backward over function calls**reverse-finish**, which rewinds to the point when the current function was about to be called**reverse-continue**, which rewinds to the previous state in the program that would (now) trigger a breakpoint (or anything else that causes it to stop) Here is an example of reverse debugging in action: ``` (gdb) b main Breakpoint 1 at 0x401160: file prog.c, line 12. (gdb) r Starting program: /home/twaugh/Documents/GDB/prog [...] Breakpoint 1, main () at prog.c:12 12 int n = 0; (gdb) target record-full (gdb) c Continuing. Program received signal SIGSEGV, Segmentation fault. 0x0000000000401154 in sometimes_crashes (f=0x0) at prog.c:7 7 return *f; (gdb) reverse-finish Run back to call of #0 0x0000000000401154 in sometimes_crashes (f=0x0) at prog.c:7 0x0000000000401190 in main () at prog.c:16 16 sometimes_crashes(0); ``` These are just a handful of useful things the GNU Debugger can do. There are many more to discover. Which hidden, little-known, or just plain amazing feature of gdb is your favorite? Please share it in the comments. ## 1 Comment
11,648
21 个 curl 命令练习
https://jvns.ca/blog/2019/08/27/curl-exercises/
2019-12-05T21:04:05
[ "curl" ]
https://linux.cn/article-11648-1.html
![](/data/attachment/album/201912/05/210334mg36oidhkb585hg5.jpg) 最近,我对人们如何学习新事物感兴趣。我正在读 Kathy Sierra 的好书《[Badass: Making Users Awesome](https://www.amazon.com/Badass-Making-Awesome-Kathy-Sierra/dp/1491919019)》,它探讨了有关“刻意练习”的想法。这个想法是,你找到一个可以用三节 45 分钟课程内能够学会的小技能,并专注于学习这项小技能。因此,作为一项练习,我尝试考虑一项能够在三节 45 分钟课程内学会的计算机技能。 我认为使用 `curl` 构造 HTTP 请求也许就是这样的一项技能,所以这里有一些 `curl` 练习作为实验! ### 什么是 curl ? `curl` 是用于构造 HTTP 请求的命令行工具。我喜欢使用 `curl`,因为它能够很轻松地测试服务器或 API 的行为是否符合预期,但是刚开始接触它的时候会让你感到一些困惑! 下面是一幅解释 `curl` 常用命令行参数的漫画 (在我的 [Bite Size Networking](https://wizardzines.com/zines/bite-size-networking) 杂志的第 6 页)。 ![](/data/attachment/album/201912/05/210411aqpo59rka1kt51gk.jpg) ### 熟能生巧 对于任何命令行工具,我认为熟练使用是很有帮助的,能够做到只输入必要的命令真是太好了。例如,最近我在测试 Gumroad API,我只需要输入: ``` curl https://api.gumroad.com/v2/sales \ -d "access_token=<SECRET>" \ -X GET -d "before=2016-09-03" ``` 就能从命令行中得到想要的结果。 ### 21 个 curl 练习 这些练习是用来理解如何使用 `curl` 构造不同种类的 HTTP 请求的,它们是故意有点重复的,基本上包含了我需要 `curl` 做的任何事情。 为了简单起见,我们将对 <https://httpbin.org> 发起一系列 HTTP 请求,httpbin 接受 HTTP 请求,然后在响应中回显你所发起的 HTTP 请求。 1. 请求 <https://httpbin.org> 2. 请求 <https://httpbin.org/anything>,它将会解析你发起的请求,并且在响应中回显。`curl` 默认发起的是 GET 请求 3. 向 <https://httpbin.org/anything> 发起 GET 请求 4. 向 <https://httpbin.org/anything> 发起 GET 请求,但是这次需要添加一些查询参数(设置 `value=panda`) 5. 请求 Google 的 `robots.txt` 文件 ([www.google.com/robots.txt](http://www.google.com/robots.txt)) 6. 向 <https://httpbin.org/anything> 发起 GET 请求,并且设置请求头为 `User-Agent: elephant` 7. 向 <https://httpbin.org/anything> 发起 DELETE 请求 8. 请求 <https://httpbin.org/anything> 并获取响应头信息 9. 向 <https://httpbin.com/anything> 发起请求体为 JSON `{"value": "panda"}` 的 POST 请求 10. 发起与上一次相同的 POST 请求,但是这次要把请求头中的 `Content-Type` 字段设置成 `application/json`(因为 POST 请求需要一个与请求体相匹配的 `Content-Type` 请求头字段)。查看响应体中的 `json` 字段,对比上一次得到的响应体 11. 向 <https://httpbin.org/anything> 发起 GET 请求,并且在请求头中设置 `Accept-Encoding: gzip`(将会发生什么?为什么会这样?) 12. 将一些 JSON 放在文件中,然后向 <https://httpbin.org/anything> 发起请求体为该文件的 POST 请求 13. 设置请求头为 `Accept: image/png` 并且向 <https://httpbin.org/image> 发起请求,将输出保存为 PNG 文件,然后使用图片浏览器打开。尝试使用不同的 `Accept:` 字段去请求此 URL 14. 向 <https://httpbin.org/anything> 发起 PUT 请求 15. 请求 <https://httpbin.org/image/jpeg> 并保存为文件,然后使用你的图片编辑器打开这个文件 16. 请求 <https://www.twitter.com>,你将会得到空的响应。让 `curl` 显示出响应头信息,并尝试找出响应内容为空的原因 17. 向 <https://httpbin.org/anything> 发起任意的请求,同时设置一些无意义的请求头(例如:`panda: elephant`) 18. 请求 <https://httpbin.org/status/404> 和 <https://httpbin.org/status/200>,然后再次请求它们并且让 curl 显示响应头信息 19. 请求 <https://httpbin.org/anything> 并且设置用户名和密码(使用 `-u username:password`) 20. 设置 `Accept-Language: es-ES` 的请求头用以下载 Twitter 的西班牙语主页 (<https://twitter.com>) 21. 使用 `curl` 向 Stripe API 发起请求(请查看 <https://stripe.com/docs/development> 了解如何使用,他们会给你一个测试用的 API key)。尝试向 <https://httpbin.org/anything> 发起相同的请求 --- via: <https://jvns.ca/blog/2019/08/27/curl-exercises/> 作者:[Julia Evans](https://jvns.ca/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[hanwckf](https://github.com/hanwckf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Recently I’ve been interested in how people learn things. I was reading Kathy Sierra’s great book [Badass: Making Users Awesome](https://www.amazon.com/Badass-Making-Awesome-Kathy-Sierra/dp/1491919019). It talks about the idea of *deliberate practice*. The idea is that you find a small micro-skill that can be learned in maybe 3 sessions of 45 minutes, and focus on learning that micro-skill. So, as an exercise, I was trying to think of a computer skill that I thought could be learned in 3 45-minute sessions. I thought that making HTTP requests with `curl` might be a skill like that, so here are some curl exercises as an experiment! ### what’s curl? curl is a command line tool for making HTTP requests. I like it because it’s an easy way to test that servers or APIs are doing what I think, but it’s a little confusing at first! Here’s a drawing explaining curl’s most important command line arguments (which is page 6 of my [Bite Size Networking](https://wizardzines.com/zines/bite-size-networking) zine). You can click to make it bigger. ### fluency is valuable With any command line tool, I think having fluency is really helpful. It’s really nice to be able to just type in the thing you need. For example recently I was testing out the Gumroad API and I was able to just type in: ``` curl https://api.gumroad.com/v2/sales \ -d "access_token=<SECRET>" \ -X GET -d "before=2016-09-03" ``` and get things working from the command line. ### 21 curl exercises These exercises are about understanding how to make different kinds of HTTP requests with curl. They’re a little repetitive on purpose. They exercise basically everything I do with curl. To keep it simple, we’re going to make a lot of our requests to the same website: [https://httpbin.org](https://httpbin.org). httpbin is a service that accepts HTTP requests and then tells you what request you made. - Request [https://httpbin.org](https://httpbin.org) - Request [https://httpbin.org/anything](https://httpbin.org/anything). httpbin.org/anything will look at the request you made, parse it, and echo back to you what you requested. curl’s default is to make a GET request. - Make a POST request to [https://httpbin.org/anything](https://httpbin.org/anything) - Make a GET request to [https://httpbin.org/anything](https://httpbin.org/anything), but this time add some query parameters (set`value=panda` ). - Request google’s robots.txt file ( [www.google.com/robots.txt](https://www.google.com/robots.txt)) - Make a GET request to [https://httpbin.org/anything](https://httpbin.org/anything)and set the header`User-Agent: elephant` . - Make a DELETE request to [https://httpbin.org/anything](https://httpbin.org/anything) - Request [https://httpbin.org/anything](https://httpbin.org/anything)and also get the response headers - Make a POST request to [https://httpbin.org/anything](https://httpbin.org/anything)with the JSON body`{"value": "panda"}` - Make the same POST request as the previous exercise, but set the Content-Type header to `application/json` (because POST requests need to have a content type that matches their body). Look at the`json` field in the response to see the difference from the previous one. - Make a GET request to [https://httpbin.org/anything](https://httpbin.org/anything)and set the header`Accept-Encoding: gzip` (what happens? why?) - Put a bunch of a JSON in a file and then make a POST request to [https://httpbin.org/anything](https://httpbin.org/anything)with the JSON in that file as the body - Make a request to [https://httpbin.org/image](https://httpbin.org/image)and set the header ‘Accept: image/png’. Save the output to a PNG file and open the file in an image viewer. Try the same thing with different`Accept:` headers. - Make a PUT request to [https://httpbin.org/anything](https://httpbin.org/anything) - Request [https://httpbin.org/image/jpeg](https://httpbin.org/image/jpeg), save it to a file, and open that file in your image editor. - Request [https://www.twitter.com](https://www.twitter.com). You’ll get an empty response. Get curl to show you the response headers too, and try to figure out why the response was empty. - Make any request to [https://httpbin.org/anything](https://httpbin.org/anything)and just set some nonsense headers (like`panda: elephant` ) - Request [https://httpbin.org/status/404](https://httpbin.org/status/404)and[https://httpbin.org/status/200](https://httpbin.org/status/200). Request them again and get curl to show the response headers. - Request [https://httpbin.org/anything](https://httpbin.org/anything)and set a username and password (with`-u username:password` ) - Download the Twitter homepage ( [https://twitter.com](https://twitter.com)) in Spanish by setting the`Accept-Language: es-ES` header. - Make a request to the Stripe API with curl. (see [https://stripe.com/docs/development](https://stripe.com/docs/development)for how, they give you a test API key). Try making exactly the same request to[https://httpbin.org/anything](https://httpbin.org/anything).
11,650
在 Linux 上使用 Window Maker 桌面
https://opensource.com/article/19/12/linux-window-maker-desktop
2019-12-07T12:53:47
[ "桌面" ]
https://linux.cn/article-11650-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。让我们和 Window Maker 一起时光倒流,它为如今的用户实现了老式 Unix NeXTSTEP 环境。 > > > ![](/data/attachment/album/201912/07/125301pfehyxjlo4osix5l.jpg) 在 Mac OS X 之前,有一个奇怪的闭源 Unix 系统,称为 [NeXTSTEP](https://en.wikipedia.org/wiki/NeXTSTEP)。Sun Microsystems 后来将 NeXTSTEP 的底层设为开放规范,这使其它项目可以创建许多自由开源的 NeXT 库和组件。GNUStep 实现了许多 NeXTSTEP 库,而 [Window Maker](https://www.windowmaker.org/) 实现了其桌面环境。 Window Maker 非常接近地模仿了 NeXTSTEP 桌面 GUI,并提供了一个有趣的视角,可以让人了解 80 年代末 90 年代初的 Unix 是什么样子的。它还揭示了窗口管理器(例如 Fluxbox 和 Openbox)背后的一些基本概念。 你可以从发行版的仓库中安装 Window Maker。要尝试它,请在安装完成后退出桌面会话。默认情况下,会话管理器(KDM、GDM、LightDM 或 XDM,这取决于你的设置)将继续将登录到默认桌面,因此登录时必须覆盖默认设置。 要在 GDM 上切换到 Window Maker: ![Selecting the Window Maker desktop in GDM](/data/attachment/album/201912/07/125350vi113iees02ei820.jpg "Selecting the Window Maker desktop in GDM") 在 KDM 上: ![Selecting the Window Maker desktop in KDM](/data/attachment/album/201912/07/125352sersqqrfcgejos5e.jpg "Selecting the Window Maker desktop in KDM") ### Window Maker 程序坞 默认情况下,Window Maker 桌面是空的,但每个角落都有几个*程序坞*。像在 NeXTSTEP 中一样,在 Window Maker 中,在程序坞区域,应用可最小化成图标后停靠,可创建启动器来快速访问常见应用,并且可运行微型的 “dockapp”。 你可以在软件仓库中搜索 “dockapp” 来试用 dockapp。它们常常是网络和系统监控器、音频设置面板、时钟等。这是在 Fedora 上运行的 Window Maker: ![Window Maker running on Fedora](/data/attachment/album/201912/07/125355an3k1ev3o3n1pcol.jpg "Window Maker running on Fedora") ### 应用菜单 要访问应用菜单,请右键单击桌面上的任意位置。要关闭它,请再次单击鼠标右键。Window Maker 不是桌面环境(DE),而是一个窗口管理器(DM)。它可以帮助你安排和管理窗口。它唯一捆绑的程序是 [WPrefs](http://www.windowmaker.org/docs/guidedtour/prefs.html)(或更常见的说法 Window Maker 偏好),它可帮助你配置常用设置,而应用菜单则提供对其他选项(包括主题)的访问。 运行什么应用完全由你决定。在 Window Maker 中,你可以选择运行 KDE 应用、GNOME 应用以及不被视为任何其他主流桌面应用的程序。你可以创建自己的工作环境,并且可以使用 Window Maker 对其进行管理。 --- via: <https://opensource.com/article/19/12/linux-window-maker-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Before Mac OS X, there was a quirky closed-source Unix system called [NeXTSTEP](https://en.wikipedia.org/wiki/NeXTSTEP). Sun Microsystems later made NeXTSTEP's underpinnings an open specification, which enabled other projects to create free and open source versions of many NeXT libraries and components. GNUStep implemented the bulk of NeXTSTEP's libraries, and [Window Maker](https://www.windowmaker.org/) implemented its desktop environment. Window Maker mimics the NeXTSTEP desktop GUI closely and provides some interesting insight into what Unix was like in the late '80s and early '90s. It also reveals some of the foundational concepts behind window managers like Fluxbox and Openbox. You can install Window Maker from your distribution's repository. To try it out, log out of your desktop session after the installation is complete. By default, your session manager (KDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your default desktop, so you must override the default when logging in. To switch to Window Maker on GDM: ![Selecting the Window Maker desktop in GDM Selecting the Window Maker desktop in GDM](https://opensource.com/sites/default/files/uploads/advent-windowmaker-gdm.jpg) And on KDM: ![Selecting the Window Maker desktop in KDM Selecting the Window Maker desktop in KDM](https://opensource.com/sites/default/files/uploads/advent-windowmaker-kdm.jpg) ## Window Maker dock By default, the Window Maker desktop is empty but for a few *docks* in each corner. As in NeXTSTEP, in Window Maker, a dock area is where major applications can go to be minimized as icons, where launchers can be created for quick access to common applications, and where tiny "dockapps" can run. You can try out a dockapp by searching for "dockapp" in your software repository. They tend to be network and system monitors, audio-setting panels, clocks, and similar. Here's Window Maker running on Fedora: ![Window Maker running on Fedora Window Maker running on Fedora](https://opensource.com/sites/default/files/uploads/advent-windowmaker.jpg) ## Application menu To access the application menu, right-click anywhere on the desktop. To close it again, right-click. Window Maker isn't a desktop environment; rather it's a window manager. It helps you arrange and manage windows. Its only bundled application is called [WPrefs](http://www.windowmaker.org/docs/guidedtour/prefs.html) (or more commonly, Window Maker Preferences), a settings application that helps you configure commonly used settings, while the application menu provides access to other options, including themes. The applications you run are entirely up to you. Within Window Maker, you can choose to run KDE applications, GNOME applications, and applications that are not considered part of any major desktop. Your work environment is yours to create, and you can manage it with Window Maker. ## Comments are closed.
11,651
Fedora 中的 Toolbox 简介
https://fedoramagazine.org/a-quick-introduction-to-toolbox-on-fedora/
2019-12-07T13:14:12
[ "Toolbox", "容器" ]
https://linux.cn/article-11651-1.html
![](/data/attachment/album/201912/07/131415qt3etlh04m2mb7l4.jpg) Toolbox 使你可以[在容器中分类和管理开发环境](https://docs.fedoraproject.org/en-US/fedora-silverblue/toolbox/),而无需 root 权限或手动添加卷。它创建一个容器,你可以在其中安装自己的命令行工具,而无需在基础系统中安装它们。当你没有 root 权限或无法直接安装程序时,也可以使用它。本文会介绍 Toolbox 及其功能。 ### 安装 Toolbox [Silverblue](https://fedoramagazine.org/what-is-silverblue/) 默认包含 Toolbox。对于 Workstation 和 Server 版本,你可以使用 `dnf install toolbox` 从默认仓库中获取它。 ### 创建 Toolbox 打开终端并运行 `toolbox enter`。程序将自动请求许可来下载最新的镜像,创建第一个容器并将你的 shell 放在该容器中。 ``` $ toolbox enter No toolbox containers found. Create now? [y/N] y Image required to create toolbox container. Download registry.fedoraproject.org/f30/fedora-toolbox:30 (500MB)? [y/N]: y ``` 当前,Toolbox 和你的基本系统之间没有区别。你的文件系统和软件包未曾改变。下面是一个使用仓库的示例,它包含 `~/src/resume` 文件夹下的简历的文档源文件。简历是使用 `pandoc` 工具构建的。 ``` $ pwd /home/rwaltr $ cd src/resume/ $ head -n 5 Makefile all: pdf html rtf text docx pdf: init pandoc -s -o BUILDS/resume.pdf markdown/* $ make pdf bash: make: command not found $ pandoc -v bash: pandoc: command not found ``` 这个 toolbox 没有构建简历所需的程序。你可以通过使用 `dnf` 安装工具来解决此问题。由于正在容器中运行,因此不会提示你输入 root 密码。 ``` $ sudo dnf groupinstall "Authoring and Publishing" -y && sudo dnf install pandoc make -y ... $ make all #Successful builds mkdir -p BUILDS pandoc -s -o BUILDS/resume.pdf markdown/* pandoc -s -o BUILDS/resume.html markdown/* pandoc -s -o BUILDS/resume.rtf markdown/* pandoc -s -o BUILDS/resume.txt markdown/* pandoc -s -o BUILDS/resume.docx markdown/* $ ls BUILDS/ resume.docx resume.html resume.pdf resume.rtf resume.txt ``` 运行 `exit` 可以退出 toolbox。 ``` $ cd BUILDS/ $ pandoc --version || ls pandoc 2.2.1 Compiled with pandoc-types 1.17.5.4, texmath 0.11.1.2, skylighting 0.7.5 ... for a particular purpose. resume.docx resume.html resume.pdf resume.rtf resume.txt $ exit logout $ pandoc --version || ls bash: pandoc: command not found... resume.docx resume.html resume.pdf resume.rtf resume.txt ``` 你会在主目录中得到由 toolbox 创建的文件。而在 toolbox 中安装的程序无法在外部访问。 ### 提示和技巧 本介绍仅涉及 toolbox 的表面。还有一些其他提示,但是你也可以查看[官方文档](https://docs.fedoraproject.org/en-US/fedora-silverblue/toolbox/)。 * `toolbox –help` 会显示 Toolbox 的手册页。 * 你可以一次有多个 toolbox。使用 `toolbox create -c Toolboxname` 和 `toolbox enter -c Toolboxname`。 * Toolbox 使用 [Podman](https://podman.io/) 来完成繁重的工作。使用 `toolbox list` 可以查找 Toolbox 创建的容器的 ID。Podman 可以使用这些 ID 来执行 `rm` 和 `stop` 之类的操作。 (你也可以在[此文章](https://fedoramagazine.org/running-containers-with-podman/)中阅读有关 Podman 的更多信息。) --- via: <https://fedoramagazine.org/a-quick-introduction-to-toolbox-on-fedora/> 作者:[Ryan Walter](https://fedoramagazine.org/author/rwaltr/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Toolbox allows you to [sort and manage your development environments in containers](https://docs.fedoraproject.org/en-US/fedora-silverblue/toolbox/) without requiring root privileges or manually attaching volumes. It creates a container where you can install your own CLI tools, without installing them on the base system itself. You can also utilize it when you do not have root access or cannot install programs directly. This article gives you an introduction to toolbox and what it does. ## Installing Toolbox [Silverblue](https://fedoramagazine.org/what-is-silverblue/) includes Toolbox by default. For the Workstation and Server editions, you can grab it from the default repositories using *dnf install toolbox*. ## Creating Toolboxes Open your terminal and run *toolbox enter*. The utility will automatically request permission to download the latest image, create your first container, and place your shell inside this container. $ toolbox enter No toolbox containers found. Create now? [y/N] y Image required to create toolbox container. Download registry.fedoraproject.org/f30/fedora-toolbox:30 (500MB)? [y/N]: y Currently there is no difference between the toolbox and your base system. Your filesystems and packages appear unchanged. Here is an example using a repository that contains documentation source for a resume under a *~/src/resume* folder. The resume is built using the *pandoc* tool. $ pwd /home/rwaltr $ cd src/resume/ $ head -n 5 Makefile all: pdf html rtf text docx pdf: init pandoc -s -o BUILDS/resume.pdf markdown/* $ make pdf bash: make: command not found $ pandoc -v bash: pandoc: command not found This toolbox does not have the programs required to build the resume. You can remedy this by installing the tools with *dnf*. You will not be prompted for the root password, because you are running in a container. $ sudo dnf groupinstall "Authoring and Publishing" -y && sudo dnf install pandoc make -y ... $ make all #Successful builds mkdir -p BUILDS pandoc -s -o BUILDS/resume.pdf markdown/* pandoc -s -o BUILDS/resume.html markdown/* pandoc -s -o BUILDS/resume.rtf markdown/* pandoc -s -o BUILDS/resume.txt markdown/* pandoc -s -o BUILDS/resume.docx markdown/* $ ls BUILDS/ resume.docx resume.html resume.pdf resume.rtf resume.txt Run *exit* at any time to exit the toolbox. $ cd BUILDS/ $ pandoc --version || ls pandoc 2.2.1 Compiled with pandoc-types 1.17.5.4, texmath 0.11.1.2, skylighting 0.7.5 ... for a particular purpose. resume.docx resume.html resume.pdf resume.rtf resume.txt $ exit logout $ pandoc --version || ls bash: pandoc: command not found... resume.docx resume.html resume.pdf resume.rtf resume.txt You retain the files created by your toolbox in your home directory. None of the programs installed in your toolbox will be available outside of it. ## Tips and tricks This introduction to toolbox only scratches the surface. Here are some additional tips, but you can also check out [the official documentation](https://docs.fedoraproject.org/en-US/fedora-silverblue/toolbox/). *Toolbox –help*will show you the man page for Toolbox- You can have multiple toolboxes at once. Use *toolbox create -c Toolboxname*and*toolbox enter -c Toolboxname* - Toolbox uses [Podman](https://podman.io/)to do the heavy lifting. Use*toolbox list*to find the IDs of the containers Toolbox creates. Podman can use these IDs to perform actions such as*rm*and*stop*. (You can also read more about Podman[in this Magazine article](https://fedoramagazine.org/running-containers-with-podman/).) *Photo courtesy of Florian Richter from Flickr.* ## Martin Ueding That’s a bad Makefile, it will always re-build everything because the targets are not the files that are generated. ## Ryan Walter Thank you for pointing that out, I learned something new! ## Ryan Walter Thank you for mentioning that! Learned something new today! ## Maciej Toolbox is the tool that I thought docker is when I didn’t knew anything about docker. 🙂 ## Ryan Walter Interesting that you say that. I’ve never thought of docker in that way, but I can completely see where you are coming from. Especialy if you don’t have the filesystem sandbox concepts of docker understood yet. ## Ryan Walter Interesting that you say that, I can definitely see what you are talking about, especially if you do not have the filesystem sandboxing fully understood. ## Maciej My thinking was Docker = Containers = Much better “chroot” When I installed docker for the first time I was thinking that I’m installing some sort of tool for isolating stuff easily. Than came confusion about the difference between image and container, and OMG where are my all changes after container stopped, and what do you mean I should run only one service in one container? Maybe I still have physical server and I want to run couple of services in one place and just move one big blob around? Moreover why you (docker) insist so much on running this stuff that other people made? Why I can’t just point you too my own rootfs and run that? It was painful and I don’t think I like docker that much. Yes I know it’s for running stuff in the clouds, but still… ## Gr The same view of all that Dockers! Still confused of using Docker and cant move of virtual machine, old-school nice little virtual machines. Do anybody have a raw howto to explain why “docker vs vms” is winnig? ## Maciej I really don’t like compering these technologies. Containers are only able to isolate and run many different “userlands”, so no different kernels and no different OSs. You can use docker and you will probably not even know that there is still some VM underneath. ## Guus Bonnema I do have a question: how does toolbox and the files I can maintain using toolbox relate to backup programs? I.e. If I want to backup my files and I have say 5 toolbox instances, how does that work? Could you add that to the article? ## Ryan Walter For the files (Such as the ones under /home/rwaltr/src/resume In the above example. ) you can use any tool that can handle file level replication such as Rsync, SCP, Restic, etc. Toolbox does not separate your home directory from your base system, So any backups you are running on the base system would also pick up on any changes that were performed in Toolbox. The Toolbox containers themselves are actually ran by Podman, You can find where your podman containers are stored with “grep graphroot $HOME/.config/containers/storage.conf ” I suppose you could run the backups directly in the container, But I am unsure of the use case for that. ## Alex There just seem layer after layer coming up in the containers space, hard to track what’s going on, and how everything works… I pretty much use Singularity (https://sylabs.io/docs/) for purposes explained in this article, but that’s because it came first, and has an excellent support for parallel execution on clusters and supercomputers. Would love to see more detailed comparison between various container solutions for developers. ## Danie How do I make new instances of non-default images? I thought it would be: toolbox create –release=32 ## Ryan Walter I was able to use the options are -r and –release, Not -release= ## Ed Nicholson Do Toolbox containers run on Docker in Windows10 I hate to ask, but work… ## Ryan Walter I am unable to test, But I wouldn’t see why not, need to check that the right volumes are being passed though,
11,653
在 AWS 中使用 Ansible 来管理你的 SSH 密钥
https://fedoramagazine.org/using-ansible-to-organize-your-ssh-keys-in-aws/
2019-12-08T09:31:00
[ "密钥", "AWS" ]
https://linux.cn/article-11653-1.html
![](/data/attachment/album/201912/08/093119pzwt6w8peb98ew8s.jpg) 如果你长期使用亚马逊 Web 服务(AWS)中的实例,你可能会遇到下面这个常见的问题,它不是因为技术性的原因导致的,更多的是因为人类追求方便舒适的天性:当你登录一台你最近没有使用的区域的新实例,你最终会创建一个新的 SSH 密钥对,久而久之这最终就会造成个人拥有太多密钥,导致管理起来复杂混乱。 本文将会介绍一种在所有区域中使用你的公钥的方法。最近,一篇 [Fedora Magazine 的文章](https://fedoramagazine.org/ssh-key-aws-regions/)介绍了另一种解决方案。但本文中的解决方案可以进一步的以更简洁和可扩展的方式实现自动化。 假设你有一个 Fedora 30 或 31 系统,其中存储了你的密钥,并且还安装了 Ansible。当这两件事同时满足时,就提供了解决这个问题的办法,甚至它还能做到更多。 使用 Ansible 的 [ec2\_key 模块](https://docs.ansible.com/ansible/latest/modules/ec2_key_module.html),你可以创建一个简单的 Ansible 剧本来在所有区域中维护你的 SSH 密钥对。如果你需要增加或者删除密钥,在 Ansible 中这就像从文件中添加和删除行一样简单。 ### 设置和运行 Ansible 剧本 如果要使用剧本,首先需要安装 `ec2_key` 模块的必要依赖项: ``` $ sudo dnf install python3-boto python3-boto3 ``` 该剧本很简单:你只需要像下面的例子一样,修改其中的密钥及其对应的名称。然后,运行该剧本,它会帮你遍历所有列出的公共 AWS 区域。该示例还包括一些你可能要访问的受限区域,只需根据需要来取消对应行的注释,然后,保存文件重新运行剧本即可。 ``` --- - name: Maintain an ssh key pair in ec2 hosts: localhost connection: local gather_facts: no vars: ansible_python_interpreter: python tasks: - name: Make available your ssh public key in ec2 for new instances ec2_key: name: "YOUR KEY NAME GOES HERE" key_material: 'YOUR KEY GOES HERE' state: present region: "{{ item }}" with_items: - us-east-2 #US East (Ohio) - us-east-1 #US East (N. Virginia) - us-west-1 #US West (N. California) - us-west-2 #US West (Oregon) - ap-east-1 #Asia Pacific (Hong Kong) - ap-south-1 #Asia Pacific (Mumbai) - ap-northeast-2 #Asia Pacific (Seoul) - ap-southeast-1 #Asia Pacific (Singapore) - ap-southeast-2 #Asia Pacific (Sydney) - ap-northeast-1 #Asia Pacific (Tokyo) - ca-central-1 #Canada (Central) - eu-central-1 #EU (Frankfurt) - eu-west-1 #EU (Ireland) - eu-west-2 #EU (London) - eu-west-3 #EU (Paris) - eu-north-1 #EU (Stockholm) - me-south-1 #Middle East (Bahrain) - sa-east-1 #South America (Sao Paulo) # - us-gov-east-1 #AWS GovCloud (US-East) # - us-gov-west-1 #AWS GovCloud (US-West) # - ap-northeast-3 #Asia Pacific (Osaka-Local) # - cn-north-1 #China (Beijing) # - cn-northwest-1 #China (Ningxia) ``` 这个剧本需要通过 API 访问 AWS,为此,请使用环境变量,如下所示: ``` $ AWS_ACCESS_KEY="aws-access-key-id" AWS_SECRET_KEY="aws-secret-key-id" ansible-playbook ec2-playbook.yml ``` 另一个方式是安装 aws 命令行工具并添加凭据,如以前的一篇 [Fedora Magazine 文章](https://fedoramagazine.org/aws-tools-fedora/)所述。如果你在线存储它们,这些参数将**不建议**插入到剧本中!你可以在 [GitHub](https://github.com/dlabreu/aws) 中找到本文的剧本代码。 完成该剧本之后,请确认你的密钥在 AWS 控制台上可用。为此,可以做如下操作: 1. 登录你的 AWS 控制台 2. 转到 “EC2 > Key Pairs” 3. 你应该会看到列出的密钥。唯一的限制是你必须使用此方法逐个区域来检查。 另一种方法是在 shell 中使用一个快速命令来为你做这些检查。 首先在剧本上创建一个包含所有区域的变量: ``` AWS_REGION="us-east-1 us-west-1 us-west-2 ap-east-1 ap-south-1 ap-northeast-2 ap-southeast-1 ap-southeast-2 ap-northeast-1 ca-central-1 eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-north-1 me-south-1 sa-east-1" ``` 然后,执行如下循环,你就可以从 aws 的 API 获得结果: ``` for each in ${AWS_REGION} ; do aws ec2 describe-key-pairs --key-name <YOUR KEY GOES HERE> ; done ``` 请记住,要执行上述操作,你需要安装 aws 命令行。 --- via: <https://fedoramagazine.org/using-ansible-to-organize-your-ssh-keys-in-aws/> 作者:[Daniel Leite de Abreu](https://fedoramagazine.org/author/dabreu/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[hj24](https://github.com/hj24) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
If you’ve worked with instances in Amazon Web Services (AWS) for a long time, you may run into this common issue. It’s not technical, but more to do with the human nature of getting too comfortable. When you launch a new instance in a region you haven’t used recently, you may end up creating a new SSH key pair. This leads to having too many keys, which can become complicated and disordered. This article shows you a way to have your public key in all regions. A recent [Fedora Magazine article](https://fedoramagazine.org/ssh-key-aws-regions/) includes one solution. But the solution in this article is automated even further, and in a more concise and scalable way. Say you have a Fedora 30 or 31 desktop system where your key is stored, and Ansible is installed as well. These two things together provide the solution to this problem and many more. With Ansible’s [ec2_key module](https://docs.ansible.com/ansible/latest/modules/ec2_key_module.html), you can create a simple playbook that will maintain your SSH key pair in all regions. If you need to add or remove keys, it’s as simple as adding and removing lines from a file. ## Setting up and running the playbook To use the playbook, first install necessary dependencies for the *ec2_key* module: $ sudo dnf install python3-boto python3-boto3 The playbook is simple: you need only to change your key and its name as in the example below. After that, run the playbook and it iterates over all the public AWS regions listed. The example also includes the restricted regions in case you have access. To include them, uncomment each line as needed, save the file, and then run the playbook again. --- - name: Maintain an ssh key pair in ec2 hosts: localhost connection: local gather_facts: no vars: ansible_python_interpreter: python tasks: - name: Make available your ssh public key in ec2 for new instances ec2_key: name: "YOUR KEY NAME GOES HERE" key_material: 'YOUR KEY GOES HERE' state: present region: "{{ item }}" with_items: - us-east-2 #US East (Ohio) - us-east-1 #US East (N. Virginia) - us-west-1 #US West (N. California) - us-west-2 #US West (Oregon) - ap-east-1 #Asia Pacific (Hong Kong) - ap-south-1 #Asia Pacific (Mumbai) - ap-northeast-2 #Asia Pacific (Seoul) - ap-southeast-1 #Asia Pacific (Singapore) - ap-southeast-2 #Asia Pacific (Sydney) - ap-northeast-1 #Asia Pacific (Tokyo) - ca-central-1 #Canada (Central) - eu-central-1 #EU (Frankfurt) - eu-west-1 #EU (Ireland) - eu-west-2 #EU (London) - eu-west-3 #EU (Paris) - eu-north-1 #EU (Stockholm) - me-south-1 #Middle East (Bahrain) - sa-east-1 #South America (Sao Paulo) # - us-gov-east-1 #AWS GovCloud (US-East) # - us-gov-west-1 #AWS GovCloud (US-West) # - ap-northeast-3 #Asia Pacific (Osaka-Local) # - cn-north-1 #China (Beijing) # - cn-northwest-1 #China (Ningxia) This playbook requires AWS access via API, as well. To do this, use environment variables as follows: $ AWS_ACCESS_KEY="aws-access-key-id"AWS_SECRET_KEY="aws-secret-key-id"ansible-playbook ec2-playbook.yml Another option is to install the aws cli tools and add the credentials as explained in a [previous Fedora Magazine article](https://fedoramagazine.org/aws-tools-fedora/). It is **not recommended** to insert these values in the playbook if you store it anywhere online! You can find this playbook code on [GitHub](https://github.com/dlabreu/aws). After the playbook finishes, confirm that your key is available on the AWS console. To do that: - Log into your AWS console - Go to **EC2 > Key Pairs** - You should see your key listed. The only limitation is that you have to check region-by-region with this method. Another way is to use a quick command in a shell to do this check for you. First create a variable with all regions on the playbook: AWS_REGION="us-east-1 us-west-1 us-west-2 ap-east-1 ap-south-1 ap-northeast-2 ap-southeast-1 ap-southeast-2 ap-northeast-1 ca-central-1 eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-north-1 me-south-1 sa-east-1" Then do a for loop and you will get the result from aws API: for each in ${AWS_REGION} ; do aws ec2 describe-key-pairs --key-name <YOUR KEY GOES HERE> ; done Keep in mind that to do the above you need to have the aws cli installed. ## JP Nice work Daniel! ## Dilip Daniel, The for loop is missing the variable. Also shouldn’t the ecs command be passed with the AWS_REGION… variable being assigned the for loop variable, each time ? ## Dayyehm Great article Daniel Awesome work champ, but I noticed you have to put the key material in the ansible file, is that the only secure way to do that? ## Paul W. Frields @Dayyehm: If I understand correctly you’re shipping public key material, which is usually not a problem in that regard. However, you could use Ansible’s “vault” capability if this is an issue.
11,654
如何把 awk 脚本移植到 Python
https://opensource.com/article/19/11/awk-to-python
2019-12-08T09:53:09
[ "awk", "Python" ]
https://linux.cn/article-11654-1.html
> > 将一个 awk 脚本移植到 Python 主要在于代码风格而不是转译。 > > > ![](/data/attachment/album/201912/08/095256ko6xdfwooe8zctfz.jpg) 脚本是解决问题的有效方法,而 awk 是编写脚本的出色语言。它特别擅长于简单的文本处理,它可以带你完成配置文件的某些复杂重写或目录中文件名的重新格式化。 ### 何时从 awk 转向 Python 但是在某些方面,awk 的限制开始显现出来。它没有将文件分解为模块的真正概念,它缺乏质量错误报告,并且缺少了现在被认为是编程语言工作原理的其他内容。当编程语言的这些丰富功能有助于维护关键脚本时,移植将是一个不错的选择。 我最喜欢的完美移植 awk 的现代编程语言是 Python。 在将 awk 脚本移植到 Python 之前,通常值得考虑一下其原始使用场景。例如,由于 awk 的局限性,通常从 Bash 脚本调用 awk 代码,其中包括一些对 `sed`、`sort` 之类的其它命令行常见工具的调用。 最好将所有内容转换为一个一致的 Python 程序。有时,脚本会做出过于宽泛的假设,例如,即使实际上只运行一个文件,该代码也可能允许任意数量的文件。 在仔细考虑了上下文并确定了要用 Python 替代的东西之后,该编写代码了。 ### 标准 awk 到 Python 功能 以下 Python 功能是有用的,需要记住: ``` with open(some_file_name) as fpin: for line in fpin: pass # do something with line ``` 此代码将逐行循环遍历文件并处理这些行。 如果要访问行号(相当于 awk 的 `NR`),则可以使用以下代码: ``` with open(some_file_name) as fpin: for nr, line in enumerate(fpin): pass # do something with line ``` ### 在 Python 中实现多文件的 awk 式行为 如果你需要能够遍历任意数量的文件同时保持行数的持续计数(类似 awk 的 `FNR`),则此循环可以做到这一点: ``` def awk_like_lines(list_of_file_names): def _all_lines(): for filename in list_of_file_names: with open(filename) as fpin: yield from fpin yield from enumerate(_all_lines()) ``` 此语法使用 Python 的*生成器*和 `yield from` 来构建*迭代器*,该迭代器将遍历所有行并保持一个持久计数。 如果你需要同时使用 `FNR` 和 `NR`,这是一个更复杂的循环: ``` def awk_like_lines(list_of_file_names): def _all_lines(): for filename in list_of_file_names: with open(filename) as fpin: yield from enumerate(fpin) for nr, (fnr, line) in _all_lines: yield nr, fnr, line ``` ### 更复杂的 FNR、NR 和行数的 awk 行为 如果 `FNR`、`NR` 和行数这三个你全都需要,仍然会有一些问题。如果确实如此,则使用三元组(其中两个项目是数字)会导致混淆。命名参数可使该代码更易于阅读,因此最好使用 `dataclass`: ``` import dataclass @dataclass.dataclass(frozen=True) class AwkLikeLine: content: str fnr: int nr: int def awk_like_lines(list_of_file_names): def _all_lines(): for filename in list_of_file_names: with open(filename) as fpin: yield from enumerate(fpin) for nr, (fnr, line) in _all_lines: yield AwkLikeLine(nr=nr, fnr=fnr, line=line) ``` 你可能想知道,为什么不一直用这种方法呢?使用其它方式的的原因是总用这种方法太复杂了。如果你的目标是把一个通用库更容易地从 awk 移植到 Python,请考虑这样做。但是编写一个可以使你确切地了解特定情况所需的循环的方法通常更容易实现,也更容易理解(因而易于维护)。 ### 理解 awk 字段 一旦有了与一行相对应的字符串,如果要转换 awk 程序,则通常需要将其分解为*字段*。Python 有几种方法可以做到这一点。这将把行按任意数量的连续空格拆分,返回一个字符串列表: ``` line.split() ``` 如果需要另一个字段分隔符,比如以 `:` 分隔行,则需要 `rstrip` 方法来删除最后一个换行符: ``` line.rstrip("\n").split(":") ``` 完成以下操作后,列表 `parts` 将存有分解的字符串: ``` parts = line.rstrip("\n").split(":") ``` 这种拆分非常适合用来处理参数,但是我们处于[偏差一个的错误](https://en.wikipedia.org/wiki/Off-by-one_error)场景中。现在 `parts[0]` 将对应于 awk 的 `$1`,`parts[1]` 将对应于 awk 的 `$2`,依此类推。之所以偏差一个,是因为 awk 计数“字段”从 1 开始,而 Python 从 0 开始计数。在 awk 中,`$0` 是整个行 —— 等同于 `line.rstrip("\n")`,而 awk 的 `NF`(字段数)更容易以 `len(parts)` 的形式得到。 ### 移植 awk 字段到 Python 例如,让我们将这个单行代码“[如何使用 awk 从文件中删除重复行](https://opensource.com/article/19/10/remove-duplicate-lines-files-awk)”转换为 Python。 `awk` 中的原始代码是: ``` awk '!visited[$0]++' your_file > deduplicated_file ``` “真实的” Python 转换将是: ``` import collections import sys visited = collections.defaultdict(int) for line in open("your_file"): did_visit = visited[line] visited[line] += 1 if not did_visit: sys.stdout.write(line) ``` 但是,Python 比 awk 具有更多的数据结构。与其计数访问次数(除了知道是否看到一行,我们不使用它),为什么不记录访问的行呢? ``` import sys visited = set() for line in open("your_file"): if line in visited: continue visited.add(line) sys.stdout.write(line) ``` ### 编写 Python 化的 awk 代码 Python 社区提倡编写 Python 化的代码,这意味着它要遵循公认的代码风格。更加 Python 化的方法将区分*唯一性*和输入/输出的关注点。此更改将使对代码进行单元测试更加容易: ``` def unique_generator(things): visited = set() for thing in things: if thing in visited: continue visited.add(things) yield thing import sys for line in unique_generator(open("your_file")): sys.stdout.write(line) ``` 将所有逻辑置于输入/输出代码之外,可以更好地分离问题,并提高代码的可用性和可测试性。 ### 结论:Python 可能是一个不错的选择 将 awk 脚本移植到 Python 时,通常是在考虑适当的 Python 代码风格时重新实现核心需求,而不是按条件/操作进行笨拙的音译。考虑原始上下文并产生高质量的 Python 解决方案。虽然有时候使用 awk 的 Bash 单行代码可以完成这项工作,但 Python 编码是通往更易于维护的代码的途径。 另外,如果你正在编写 awk 脚本,我相信您也可以学习 Python!如果你有任何疑问,请告诉我。 --- via: <https://opensource.com/article/19/11/awk-to-python> 作者:[Moshe Zadka](https://opensource.com/users/moshez) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Scripts are potent ways to solve a problem repeatedly, and awk is an excellent language for writing them. It excels at easy text processing in particular, and it can bring you through some complicated rewriting of config files or reformatting file names in a directory. ## When to move from awk to Python At some point, however, awk's limitations start to show. It has no real concept of breaking files into modules, it lacks quality error reporting, and it's missing other things that are now considered fundamentals of how a language works. When these rich features of a programming language are helpful to maintain a critical script, porting becomes a good option. My favorite modern programming language that is perfect for porting awk is Python. Before porting an awk script to Python, it is often worthwhile to consider its original context. For example, because of awk's limitations, the awk code is commonly called from a Bash script and includes some calls to other command-line favorites like sed, sort, and the gang. It's best to convert all of it into one coherent Python program. Other times, the script makes overly broad assumptions; for example, the code might allow for any number of files, even though it's run with only one in practice. After carefully considering the context and determining the thing to substitute with Python, it is time to write code. ## Standard awk to Python functionality The following Python functionality is useful to remember: ``` with open(some_file_name) as fpin: for line in fpin: pass # do something with line ``` This code will loop through a file line-by-line and process the lines. If you want to access a line number (equivalent to awk's **NR**), you can use the following code: ``` with open(some_file_name) as fpin: for nr, line in enumerate(fpin): pass # do something with line ``` ## awk-like behavior over multiple files in Python If you need to be able to iterate through any number of files while keeping a persistent count of the number of lines (like awk's **FNR**), this loop can do it: ``` def awk_like_lines(list_of_file_names): def _all_lines(): for filename in list_of_file_names: with open(filename) as fpin: yield from fpin yield from enumerate(_all_lines()) ``` This syntax uses Python's *generators* and **yield from** to build an *iterator* that loops through all lines and keeps a persistent count. If you need the equivalent of both **FNR** and **NR**, here is a more sophisticated loop: ``` def awk_like_lines(list_of_file_names): def _all_lines(): for filename in list_of_file_names: with open(filename) as fpin: yield from enumerate(fpin) for nr, (fnr, line) in _all_lines: yield nr, fnr, line ``` ## More complex awk functionality with FNR, NR, and line The question remains if you need all three: **FNR**, **NR**, and **line**. If you really do, using a three-tuple where two of the items are numbers can lead to confusion. Named parameters can make this code easier to read, so it's better to use a **dataclass**: ``` import dataclass @dataclass.dataclass(frozen=True) class AwkLikeLine: content: str fnr: int nr: int def awk_like_lines(list_of_file_names): def _all_lines(): for filename in list_of_file_names: with open(filename) as fpin: yield from enumerate(fpin) for nr, (fnr, line) in _all_lines: yield AwkLikeLine(nr=nr, fnr=fnr, line=line) ``` You might wonder, why not start with this approach? The reason to start elsewhere is that this is almost always too complicated. If your goal is to make a generic library that makes porting awk to Python easier, then consider doing so. But writing a loop that gets you exactly what you need for a specific case is usually easier to do and easier to understand (and thus maintain). ## Understanding awk fields Once you have a string that corresponds to a line, if you are converting an awk program, you often want to break it up into *fields*. Python has several ways of doing that. This will return a list of strings, splitting the line on any number of consecutive whitespaces: `line.split()` If another field separator is needed, something like this will split the line by **:**; the **rstrip** method is needed to remove the last newline: `line.rstrip("\n").split(":")` After doing the following, the list **parts** will have the broken-up string: `parts = line.rstrip("\n").split(":")` This split is good for choosing what to do with the parameters, but we are in an [off-by-one error](https://en.wikipedia.org/wiki/Off-by-one_error) scenario. Now **parts[0]** will correspond to awk's **$1**, **parts[1]** will correspond to awk's **$2**, etc. This off-by-one is because awk starts counting the "fields" from 1, while Python counts from 0. In awk's **$0** is the whole line -- equivalent to **line.rstrip("\n") **and awk's **NF** (number of fields) is more easily retrieved as **len(parts)**. ## Porting awk fields in Python As an example, let's convert the one-liner from "[How to remove duplicate lines from files with awk](https://opensource.com/article/19/10/remove-duplicate-lines-files-awk)" to Python. The original in awk is: `awk '!visited[$0]++' your_file > deduplicated_file` An "authentic" Python conversion would be: ``` import collections import sys visited = collections.defaultdict(int) for line in open("your_file"): did_visit = visited[line] visited[line] += 1 if not did_visit: sys.stdout.write(line) ``` However, Python has more data structures than awk. Instead of *counting* visits (which we do not use, except to know whether we saw a line), why not record the visited lines? ``` import sys visited = set() for line in open("your_file"): if line in visited: continue visited.add(line) sys.stdout.write(line) ``` ## Making Pythonic awk code The Python community advocates for writing Pythonic code, which means it follows a commonly agreed-upon code style. An even more Pythonic approach will separate the concerns of *uniqueness* and *input/output*. This change would make it easier to unit test your code: ``` def unique_generator(things): visited = set() for thing in things: if thing in visited: continue visited.add(thing) yield thing import sys for line in unique_generator(open("your_file")): sys.stdout.write(line) ``` Putting all logic away from the input/output code leads to better separation of concerns and more usability and testability of code. ## Conclusion: Python can be a good choice Porting an awk script to Python is often more a matter of reimplementing the core requirements while thinking about proper Pythonic code style than a slavish transliteration of condition/action by condition/action. Take the original context into account and produce a quality Python solution. While there are times when a Bash one-liner with awk can get the job done, Python coding is a path toward more easily maintainable code. Also, if you're writing awk scripts, I am confident you can learn Python as well! Let me know if you have any questions in the comments. ## 6 Comments
11,656
自动共享和上传文件到兼容的托管站点
https://www.ostechnix.com/anypaste-share-upload-files-compatible-hosting-sites-automatically/
2019-12-09T06:15:59
[ "上传" ]
https://linux.cn/article-11656-1.html
![](/data/attachment/album/201912/09/061603iu8j8eofe8n3fono.png) 前阵子我们写了一个关于 [Transfer.sh](https://www.ostechnix.com/easy-fast-way-share-files-internet-command-line/)的指南,它允许你使用命令行通过互联网来分享文件。今天,我们来看看另一种文件分享实用工具 Anypaste。这是一个基于文件类型自动共享和上传文件到兼容托管站点的简单脚本。你不需要去手动登录到托管站点来上传或分享你的文件。Anypaste 将会根据你想上传的文件的类型来**自动挑选合适的托管站点**。简单地说,照片将被上传到图像托管站点,视频被传到视频站点,代码被传到 pastebin。难道不是很酷的吗?Anypaste 是一个完全开源、免费、轻量的脚本,你可以通过命令行完成所有操作。因此,你不需要依靠那些臃肿的、需要消耗大量内存的 GUI 应用来上传和共享文件。 ### 安装 正如我所说,这仅仅是一个脚本。所以不存在任何复杂的安装步骤。只需要将脚本下载后放置在你想要运行的位置(例如 `/usr/bin/`),并将其设置为可执行文件后就可以直接使用了。此外,你也可以通过下面的这两条命令来快速安装 Anypaste。 ``` sudo curl -o /usr/bin/anypaste https://anypaste.xyz/sh sudo chmod +x /usr/bin/anypaste ``` 就是这样简单。如果需要更新老的 Anypaste 版本,只需要用新的可执行文件覆写旧的即可。 现在,让我们看看一些实例。 ### 配置 Anypaste 开箱即用,并不需要特别的配置。默认的配置文件是 `~/.config/anypaste.conf`,这个文件在你第一次运行 Anypaste 时会自动创建。 需要配置的选项只有 `ap_plugins`。Anypaste 使用插件系统上传文件。每个站点(的上传)都由一个特定的插件表示。你可以在 `anypaste.conf` 文件中的 `ap-plugins directive` 位置浏览可用的插件列表。 ``` # List of plugins # If there are multiple compatible plugins, precedence is determined # by which one is listed first in this array ap_plugins=( # Videos/Gifs 'sendvid' 'streamable' 'gfycat' # Images 'tinyimg' 'vgyme' # Audio 'instaudio' # Text 'hastebin' 'ixio' 'sprunge' # Documents 'docdroid' # Any file 'jirafeau' 'fileio' ) [...] ``` 如果你要安装一个新的插件,将它添加进这个列表中就可以了。如果你想禁用一个默认插件,只需要将它从列表中移除即可。如果有多个兼容的插件,排列中的第一个会被选择,因此**顺序很重要**。 ### 用法 上传一个简单的文件,例如 `test.png`,可以运行以下命令: ``` anypaste test.png ``` 输出示例: ``` Current file: test.png Attempting to upload with plugin 'tinyimg' ######################################################################## 100.0% Direct Link: https://tinyimg.io/i/Sa1zsjj.png Upload complete. All files processed. Have a nice day! ``` 正如输出结果中所看到的,Anypaste 通过自动匹配图像文件 `test.png` 发现了兼容的托管站点([https://tinyimg.io),并将文件上传到了该站点。此外,Anypaste](https://tinyimg.io%EF%BC%89%EF%BC%8C%E5%B9%B6%E5%B0%86%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%88%B0%E4%BA%86%E8%AF%A5%E7%AB%99%E7%82%B9%E3%80%82%E6%AD%A4%E5%A4%96%EF%BC%8CAnypaste) 也为我们提供了用于直接浏览/下载该文件的链接。 不仅是 png 格式文件,你还可以上传任何其他图片格式的文件。例如,下面的命令将会上传 gif 格式文件: ``` $ anypaste file.gif Current file: file.gif Plugin 'streamable' is compatible, but missing config parameters: 'streamable_email' 'streamable_password' You can set them in /home/sk/.config/anypaste.conf Attempting to upload with plugin 'gfycat' ######################################################################## 100.0% Reminder: Gfycat needs time to encode. Your video will not appear right away. Link: https://gfycat.com/MisguidedQuaintBergerpicard Direct(ish) Link: https://thumbs.gfycat.com/MisguidedQuaintBergerpicard-size_restricted.gif Upload complete. All files processed. Have a nice day! ``` 你可以将链接分享给你的家庭、朋友和同事们。下图是我刚刚将图片上传到 gfycat 网站的截图。 ![](/data/attachment/album/201912/09/061605jywfdyydmgv5fzud.png) 也可以一次同时上传多个(相同格式或不同格式)文件。 下面的例子提供参考,这里我会上传两个不同的文件,包含一个图片文件和一个视频文件: ``` anypaste image.png video.mp4 ``` 输出示例: ``` Current file: image.png Attempting to upload with plugin 'tinyimg' ######################################################################## 100.0% Direct Link: https://tinyimg.io/i/au1PHpg.png Upload complete. Current file: video.mp4 Plugin 'streamable' is compatible, but missing config parameters: 'streamable_email' 'streamable_password' You can set them in /home/sk/.config/anypaste.conf Attempting to upload with plugin 'sendvid' ######################################################################## 100.0% Link: http://sendvid.com/wwy7w96h Delete/Edit: http://sendvid.com/wwy7w96h?secret=39c0af2d-d8bf-4d3d-bad3-ad37432a40a5 Upload complete. All files processed. Have a nice day! ``` Anypaste 针对两个文件自动发现了与之相兼容的托管站点并成功上传。 正如你在上述用法介绍部分的例子中注意到的,Anypaste 会自动挑选最佳的插件。此外,你可以指定插件进行文件上传,这里提供一个上传到 gfycat 的案例,运行以下命令: ``` anypaste -p gfycat file.gif ``` 输出示例: ``` Current file: file.gif Plugin 'streamable' is compatible, but missing config parameters: 'streamable_email' 'streamable_password' You can set them in /home/sk/.config/anypaste.conf Attempting to upload with plugin 'gfycat' ######################################################################## 100.0% Reminder: Gfycat needs time to encode. Your video will not appear right away. Link: https://gfycat.com/GrayDifferentCollie Direct(ish) Link: https://thumbs.gfycat.com/GrayDifferentCollie-size_restricted.gif Upload complete. All files processed. Have a nice day! ``` 如果要使用特定插件进行文件上传,可以通过以下命令绕过兼容性检查: ``` anypaste -fp gfycat file.gif ``` 如果你发现在配置文件中忽略了特定的插件,你仍然可以强制 Anypaste 去使用特定的插件,只不过需要加上 `-xp` 参数。 ``` anypaste -xp gfycat file.gif ``` 如果想要以交互模式上传文件,可以在命令后加上 `-i` 标签: ``` $ anypaste -i file.gif Current file: file.gif Determine compatible plugins automatically? [Y/n] **n** The following plugins were found: 'sendvid' 'streamable' 'gfycat' 'tinyimg' 'vgyme' 'instaudio' 'hastebin' 'ixio' 'sprunge' 'docdroid' 'jirafeau' 'fileio' Enter the (partial) name of a plugin, or nothing for automatic selection **gfycat** Attempt to upload with plugin 'gfycat'? [Y/n] **y** Attempting to upload with plugin 'gfycat' ######################################################################## 100.0% Reminder: Gfycat needs time to encode. Your video will not appear right away. Link: https://gfycat.com/WaryAshamedBlackbear Direct(ish) Link: https://thumbs.gfycat.com/WaryAshamedBlackbear-size_restricted.gif Upload complete. All files processed. Have a nice day! ``` 正如你所见,Anypaste 首先询问了我是否需要自动确定插件。因为我不想自动寻找插件,所以我回复了 “No”。之后,Anypaste 列出了所有可选择的插件,并要求我从列表中选择一个。同样的,你可以上传和共享不同类型的文件,相关文件会被上传到相兼容的站点。 无论你何时上传一个视频文件,Anypaste 都会将其上传到以下站点中的一个: 1. sendvid 2. streamable 3. gfycat 这里注意列表顺序,Anypaste 将首先将文件上传到 sendvid 站点,如果没有 sendvid 的插件可供使用,Anypaste 将会尝试顺序中的另外两个站点。当然你也可以通过更改配置文件来修改顺序。 图像文件上传站点: 1. tinyimg.io 2. vgy.me 音频文件上传站点: 1. instaud 文本文件上传站点: 1. hastebin 2. ix.io 3. sprunge.us 文档上传站点: 1. docdroid 其他任意类型的文件上传站点: 1. jirafeau 2. file.io 上面列出来的部分站点一段特定的时间后会删除上传的内容,所以在上传和分享内容时应先明确这些站点的条款和条件。 ### 结论 在我看来,识别文件并决定将其上传到何处的想法非常棒,而且开发者也以恰当的方式完美地实现了它。毫无疑问,Anypaste 对那些在互联网上需要频繁分享文件的人们非常有用,我希望你也能这么觉得。 这就是今天的全部内容,后面会有越来越多的好东西分享给大家。再见啦! --- via: <https://www.ostechnix.com/anypaste-share-upload-files-compatible-hosting-sites-automatically/> 作者:[SK](https://www.ostechnix.com/author/sk/) 译者:[lixin555](https://github.com/lixin555) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
11,657
在命令行用 sort 进行排序
https://opensource.com/article/19/10/get-sorted-sort
2019-12-09T06:54:54
[ "sort", "排序" ]
https://linux.cn/article-11657-1.html
> > 在 Linux、BSD 或 Mac 的终端中使用 sort 命令,按自己的需求重新整理数据。 > > > ![](/data/attachment/album/201912/09/065444f42xl2lddxillz09.jpg) 如果你曾经用过数据表应用程序,你就会知道可以按列的内容对行进行排序。例如,如果你有一个费用列表,你可能希望对它们进行按日期或价格升序抑或按类别进行排序。如果你熟悉终端的使用,你不会仅为了排序文本数据就去使用庞大的办公软件。这正是 [sort](https://en.wikipedia.org/wiki/Sort_(Unix)) 命令的用处。 ### 安装 你不必安装 `sort` ,因为它向来都包含在 [POSIX](https://en.wikipedia.org/wiki/POSIX) 系统里。在大多数 Linux 系统中,`sort` 命令来自 GNU 组织打包的实用工具集合中。在其他的 POSIX 系统中,像 BSD 和 Mac,默认的 `sort` 命令不是 GNU 提供的,所以有一些选项可能不一样。本文中我尽量对 GNU 和 BSD 两者的实现都进行说明。 ### 按字母顺序排列行 `sort` 命令默认会读取文件每行的第一个字符并对每行按字母升序排序后输出。两行中的第一个字符相同的情况下,对下一个字符进行对比。例如: ``` $ cat distro.list Slackware Fedora Red Hat Enterprise Linux Ubuntu Arch 1337 Mint Mageia Debian $ sort distro.list 1337 Arch Debian Fedora Mageia Mint Red Hat Enterprise Linux Slackware Ubuntu ``` 使用 `sort` 不会改变原文件。`sort` 仅起到过滤的作用,所以如果你希望按排序后的格式保存数据,你需要用 `>` 或 `tee` 进行重定向。 ``` $ sort distro.list | tee distro.sorted 1337 Arch Debian [...] $ cat distro.sorted 1337 Arch Debian [...] ``` ### 按列排序 复杂数据集有时候不止需要对每行的第一个字符进行排序。例如,假设有一个动物列表,每个都有其种和属,用可预见的分隔符分隔每一个“字段”(即数据表中的“单元格”)。这类由数据表导出的格式很常见,CSV(以逗号分隔的数据comma-separated values)后缀可以标识这些文件(虽然 CSV 文件不一定用逗号分隔,有分隔符的文件也不一定用 CSV 后缀)。以下数据作为示例: ``` Aptenodytes;forsteri;Miller,JF;1778;Emperor Pygoscelis;papua;Wagler;1832;Gentoo Eudyptula;minor;Bonaparte;1867;Little Blue Spheniscus;demersus;Brisson;1760;African Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed Eudyptes;chrysocome;Viellot;1816;Southern Rockhopper Torvaldis;linux;Ewing,L;1996;Tux ``` 对于这组示例数据,你可以用 `--field-separator` (在 BSD 和 Mac 用 `-t`,在 GNU 上也可以用简写 `-t` )设置分隔符为分号(因为该示例数据中是用分号而不是逗号,理论上分隔符可以是任意字符),用 `--key`(在 BSD 和 Mac 上用 `-k`,在 GNU 上也可以用简写 `-k`)选项指定哪个字段被排序。例如,对每行第二个字段进行排序(计数以 1 开头而不是 0): ``` sort --field-separator=";" --key=2 Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed Eudyptes;chrysocome;Viellot;1816;Sothern Rockhopper Spheniscus;demersus;Brisson;1760;African Aptenodytes;forsteri;Miller,JF;1778;Emperor Torvaldis;linux;Ewing,L;1996;Tux Eudyptula;minor;Bonaparte;1867;Little Blue Pygoscelis;papua;Wagler;1832;Gentoo ``` 结果有点不容易读,但是 Unix 以构造命令的管道方式而闻名,所以你可以使用 `column` 命令美化输出结果。使用 GNU `column`: ``` $ sort --field-separator=";" \ \--key=2 penguins.list | column --table --separator ";" Megadyptes antipodes Milne-Edwards 1880 Yellow-eyed Eudyptes chrysocome Viellot 1816 Southern Rockhopper Spheniscus demersus Brisson 1760 African Aptenodytes forsteri Miller,JF 1778 Emperor Torvaldis linux Ewing,L 1996 Tux Eudyptula minor Bonaparte 1867 Little Blue Pygoscelis papua Wagler 1832 Gentoo ``` 对于初学者可能有点不好理解(但是写起来简单),BSD 和 Mac 上的命令选项: ``` $ sort -t ";" \ -k2 penguins.list | column -t -s ";" Megadyptes antipodes Milne-Edwards 1880 Yellow-eyed Eudyptes chrysocome Viellot 1816 Southern Rockhopper Spheniscus demersus Brisson 1760 African Aptenodytes forsteri Miller,JF 1778 Emperor Torvaldis linux Ewing,L 1996 Tux Eudyptula minor Bonaparte 1867 Little Blue Pygoscelis papua Wagler 1832 Gentoo ``` 当然 `-k` 不一定非要设为 `2`。任意存在的字段都可以被设为排序的键。 ### 逆序排列 你可以用 `--reverse`(BSD/Mac 上用 `-r`,GNU 上也可以用简写 `-r`)选项来颠倒已经排好序的列表。 ``` $ sort --reverse alphabet.list z y x w [...] ``` 你也可以把输出结果通过管道传给命令 [tac](https://opensource.com/article/19/9/tac-command) 来实现相同的效果。 ### 按月排序(仅 GNU 支持) 理想情况下,所有人都按照 ISO 8601 标准来写日期:年、月、日。这是一种合乎逻辑的指定精确日期的方法,也可以很容易地被计算机理解。也有很多情况下,人类用其他的方式标注日期,包括用很名字随意的月份。 幸运的是,GNU `sort` 命令能识别这种写法,并可以按月份的名称正确排序。使用 `--month-sort`(`-M`)选项: ``` $ cat month.list November October September April [...] $ sort --month-sort month.list January February March April May [...] November December ``` 月份的全称和简写都可以被识别。 ### 人类可读的数字排序(仅 GNU 支持) 另一个人类和计算机的常见混淆点是数字的组合。例如,人类通常把 “1024 kilobytes” 写成 “1KB”,因为人类解析 “1 KB” 比 “1024” 要容易且更快(数字越大,这种差异越明显)。对于计算机来说,一个 9 KB 的字符串要比诸如 1 MB 的字符串大(尽管 9 KB 是 1 MB 很小一部分)。GNU `sort` 命令提供了`--human-numeric-sort`(`-h`)选项来帮助正确解析这些值。 ``` $ cat sizes.list 2M 12MB 1k 9k 900 7000 $ sort --human-numeric-sort 900 7000 1k 9k 2M 12MB ``` 有一些情况例外。例如,“16000 bytes” 比 “1 KB” 大,但是 `sort` 识别不了。 ``` $ cat sizes0.list 2M 12MB 16000 1k $ sort -h sizes0.list 16000 1k 2M 12MB ``` 逻辑上来说,这个示例中 16000 应该写成 16 KB,所以也不应该全部归咎于GNU `sort`。只要你确保数字的一致性,`--human-numeric-sort` 可以用一种计算机友好的方式解析成人类可读的数字。 ### 随机排序(仅 GNU 支持) 有时候工具也提供了一些与设计初衷相悖的选项。某种程度上说,`sort` 命令提供对一个文件进行随机排序的能力没有任何意义。这个命令的工作流让这个特性变得很方便。你*可以*用其他的命令,像 [shuf](https://www.gnu.org/software/coreutils/manual/html_node/shuf-invocation.html) ,或者你可以用现在的命令添加一个选项。不管你认为它是一个臃肿的还是极具创造力的用户体验设计,GNU `sort` 命令提供了对文件进行随机排序的功能。 最纯粹的随机排序格式选项是 `--random-sort` 或 `-R`(不要跟 `-r` 混淆,`-r` 是 `--reverse` 的简写)。 ``` $ sort --random-sort alphabet.list d m p a [...] ``` 每次对文件运行随机排序都会有不同的结果。 ### 结语 GNU 和 BSD 的 `sort` 命令还有很多功能,所以花点时间去了解这些选项。你会惊异于 `sort` 的灵活性,尤其是当它和其他的 Unix 工具一起使用时。 --- via: <https://opensource.com/article/19/10/get-sorted-sort> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
If you've ever used a spreadsheet application, then you know that rows can be sorted by the contents of a column. For instance, if you have a list of expenses, you might want to sort them by date or by ascending price or by category, and so on. If you're comfortable using a terminal, you may not want to have to use a big office application just to sort text data. And that's exactly what the [ sort](https://en.wikipedia.org/wiki/Sort_(Unix)) command is for. ## Installing You don't need to install **sort** because it's invariably included on any [POSIX](https://en.wikipedia.org/wiki/POSIX) system. On most Linux systems, the **sort** command is bundled in a collection of utilities from the GNU organization. On other POSIX systems, such as BSD and Mac, the default **sort** command is not from GNU, so some options may differ. I'll attempt to account for both GNU and BSD implementations in this article. ## Sort lines alphabetically The **sort** command, by default, looks at the first character of each line of a file and outputs each line in ascending alphabetic order. In the event that two characters on multiple lines are the same, it considers the next character. For example: ``` $ cat distro.list Slackware Fedora Red Hat Enterprise Linux Ubuntu Arch 1337 Mint Mageia Debian $ sort distro.list 1337 Arch Debian Fedora Mageia Mint Red Hat Enterprise Linux Slackware Ubuntu ``` Using **sort** doesn't change the original file. Sort is a filter, so if you want to preserve your data in its sorted form, you must redirect the output using either **>** or **tee**: ``` $ sort distro.list | tee distro.sorted 1337 Arch Debian [...] $ cat distro.sorted 1337 Arch Debian [...] ``` ## Sort by column Complex data sets sometimes need to be sorted by something other than the first letter of each line. Imagine, for instance, a list of animals and each one's species and genus, and each "field" (a "cell" in a spreadsheet) is defined by a predictable delimiter character. This is such a common data format for spreadsheet exports that the CSV (comma-separated values) file extension exists to identify such files (although a CSV file doesn't have to be comma-separated, nor does a delimited file have to use the CSV extension to be valid and usable). Consider this example data set: ``` Aptenodytes;forsteri;Miller,JF;1778;Emperor Pygoscelis;papua;Wagler;1832;Gentoo Eudyptula;minor;Bonaparte;1867;Little Blue Spheniscus;demersus;Brisson;1760;African Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed Eudyptes;chrysocome;Viellot;1816;Southern Rockhopper Torvaldis;linux;Ewing,L;1996;Tux ``` Given this sample data set, you can use the **--field-separator** (use **-t** on BSD and Mac—or on GNU to reduce typing) option to set the delimiting character to a semicolon (because this example uses semicolons instead of commas, but it could use any character), and use the **--key** (**-k** on BSD and Mac or on GNU to reduce typing) option to define which field to sort by. For example, to sort by the second field (starting at 1, not 0) of each line: ``` sort --field-separator=";" --key=2 Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed Eudyptes;chrysocome;Viellot;1816;Sothern Rockhopper Spheniscus;demersus;Brisson;1760;African Aptenodytes;forsteri;Miller,JF;1778;Emperor Torvaldis;linux;Ewing,L;1996;Tux Eudyptula;minor;Bonaparte;1867;Little Blue Pygoscelis;papua;Wagler;1832;Gentoo ``` That's somewhat difficult to read, but Unix is famous for its *pipe* method of constructing commands, so you can use the **column** command to "prettify" the output. Using GNU **column**: ``` $ sort --field-separator=";" \ --key=2 penguins.list | \ column --table --separator ";" Megadyptes antipodes Milne-Edwards 1880 Yellow-eyed Eudyptes chrysocome Viellot 1816 Southern Rockhopper Spheniscus demersus Brisson 1760 African Aptenodytes forsteri Miller,JF 1778 Emperor Torvaldis linux Ewing,L 1996 Tux Eudyptula minor Bonaparte 1867 Little Blue Pygoscelis papua Wagler 1832 Gentoo ``` Slightly more cryptic to the new user (but shorter to type), the command options on BSD and Mac: ``` $ sort -t ";" \ -k2 penguins.list | column -t -s ";" Megadyptes antipodes Milne-Edwards 1880 Yellow-eyed Eudyptes chrysocome Viellot 1816 Southern Rockhopper Spheniscus demersus Brisson 1760 African Aptenodytes forsteri Miller,JF 1778 Emperor Torvaldis linux Ewing,L 1996 Tux Eudyptula minor Bonaparte 1867 Little Blue Pygoscelis papua Wagler 1832 Gentoo ``` The **key** definition doesn't have to be set to **2**, of course. Any existing field may be used as the sorting key. ## Reverse sort You can reverse the order of a sorted list with the **--reverse** (**-r** on BSD or Mac or GNU for brevity): ``` $ sort --reverse alphabet.list z y x w [...] ``` You can achieve the same result by piping the output of a normal sort through [tac](https://opensource.com/article/19/9/tac-command). ## Sorting by month (GNU only) In a perfect world, everyone would write dates according to the ISO 8601 standard: year, month, day. It's a logical method of specifying a unique date, and it's easy for computers to understand. And yet quite often, humans use other means of identifying dates, including months with pretty arbitrary names. Fortunately, the GNU **sort** command accounts for this and is able to sort correctly by month name. Use the **--month-sort** (**-M**) option: ``` $ cat month.list November October September April [...] $ sort --month-sort month.list January February March April May [...] November December ``` Months may be identified by their full name or some portion of their names. ## Human-readable numeric sort (GNU only) Another common point of confusion between humans and computers is groups of numbers. For instance, humans often write "1024 kilobytes" as "1KB" because it's easier and quicker for the human brain to parse "1KB" than "1024" (and it gets easier the larger the number becomes). To a computer, though, a string such as 9KB is larger than, for instance, 1MB (even though 9KB is only a fraction of a megabyte). The GNU **sort** command provides the **--human-numeric-sort** (**-h**) option to help parse these values correctly. ``` $ cat sizes.list 2M 12MB 1k 9k 900 7000 $ sort --human-numeric-sort 900 7000 1k 9k 2M 12MB ``` There are some inconsistencies. For example, 16,000 bytes is greater than 1KB, but **sort** fails to recognize that: ``` $ cat sizes0.list 2M 12MB 16000 1k $ sort -h sizes0.list 16000 1k 2M 12MB ``` Logically, 16,000 should be written 16KB in this context, so GNU **sort** is not entirely to blame. As long as you are sure that your numbers are consistent, the **--human-numeric-sort** can help parse human-readable numbers in a computer-friendly way. ## Randomized sort (GNU only) Sometimes utilities provide the option to do the opposite of what they're meant to do. In a way, it makes no sense for a **sort** command to have the ability to "sort" a file randomly. Then again, the workflow of the command makes it a convenient feature to have. You *could* use a different command, like [ shuf](https://www.gnu.org/software/coreutils/manual/html_node/shuf-invocation.html), or you could just add an option to the command you're using. Whether it's bloat or ingenious UX design, the GNU **sort**command provides the means to sort a file arbitrarily. The purest form of arbitrary sorting is the **--random-sort** or **-R** option (not to be confused with the **-r** option, which is short for **--reverse**). ``` $ sort --random-sort alphabet.list d m p a [...] ``` You can run a random sort multiple times on a file for different results each time. ## Sorted There are many more features available with the **sort** GNU and BSD commands, so spend some time getting to know the options. You'll be surprised at how flexible **sort** can be, especially when it's combined with other Unix utilities. ## 7 Comments
11,658
千面 awk
https://www.networkworld.com/article/3454979/the-many-faces-of-awk.html
2019-12-09T07:05:45
[ "awk" ]
https://linux.cn/article-11658-1.html
> > `awk` 命令不仅提供了简单的输入字符串筛选功能,还包含提取数据列、打印简单文本、筛选内容——甚至做一些数学计算。 > > > ![Thinkstock](/data/attachment/album/201912/09/070548uomf0z10kpz306po.jpg) 如果你仅使用 `awk` 选取一行中的特定文本,那么你可能错过了它的很多功能。在这篇文章中,我们会来看看使用 `awk` 可以帮你做一些其他的什么事情,并提供一些例子。 ### 提取数据列 `awk` 所提供的最简单与最常用的功能便是从文件或管道传输的数据中选取特定的内容。默认使用空格当做分隔符,这非常简单。 ``` $ echo one two three four five | awk ‘{print $4}’ four $ who | awk ‘{print $1}’ jdoe fhenry ``` 空格指的是一系列的 `space` 或 `tab` 字符。在下面所展示的命令里,`awk` 从提供的数据中筛选第一和第四项。 `awk` 命令也可以通过在其后增加文件名参数的方式从文本文件中获取数据。 ``` $ awk '{print $1,$5,$NF}' HelenKellerQuote The beautiful heart. ``` (LCTT 译注:“The best and most beautiful things in the world can not be seen or even touched , they must be felt with heart.” ——海伦凯勒) 在这个例子中,`awk` 挑选了一行中的第一个、第五个和最后一个字段。 命令中的 `$NF` 指定选取每行的最后一个字段。这是因为 `NF` 代表一行中的<ruby> 字段数量 <rt> Number of Field </rt></ruby>,也就是 23,而 `$NF` 就代表着那个字段的值,也就是`heart`。最后的句号也包含进去了,因为它是最后一个字符串的一部分。 字段能以任何有用的形式打印。在这个例子中,我们将字段以日期的格式进行打印输出。 ``` $ date | awk '{print $4,$3,$2}' 2019 Nov 22 ``` 如果你省略了 `awk` 命令中字段指示符之间的逗号,输出将会挤成一个字符串。 ``` $ date | awk '{print $4 $3 $2}' 2019Nov21 ``` 如果你将通常使用的逗号替换为连字符,`awk` 就会尝试将两个字段的值相减——或许这并不是你想要的。它不会将连字符插入到输出结果中。相反地,它对输出做了一些数学计算。 ``` $ date | awk '{print $4-$3-$2}' 1997 ``` 在这个例子中,它将年 “2019” 和日期 “22” 相减,并忽略了中间的 “Nov”。 如果你想要空格之外的字符作为输出分隔符,你可以通过 `OFS`(<ruby> 输出分隔符 <rt> output field separator </rt></ruby>)指定分隔符,就像这样: ``` $ date | awk '{OFS="-"; print $4,$3,$2}' 2019-Nov-22 ``` ### 打印简单文本 你也可以使用 `awk` 简单地显示一些文本。当然了,比起 `awk` 你可能更想使用 `echo` 命令。但换句话说,作为 `awk` 脚本的一部分,打印某些相关性文本将会非常实用。这里有一个没什么用的例子: ``` $ awk 'BEGIN {print "Hello, World" }' Hello, World ``` 下面的例子更加合理,添加一行文本标签来更好的辨识数据。 ``` $ who | awk 'BEGIN {print "Current logins:"} {print $1}' Current logins: shs nemo ``` ### 指定字段分隔符 不是所有的输入都以空格作为分隔符的。如果你的文本通过其它的字符作为分隔符(例如:逗号、冒号、分号),你可以通过 `-F` 选项(输入分隔符)告诉 `awk`: ``` $ cat testfile a:b:c,d:e $ awk -F : '{print $2,$3}' testfile b c,d ``` 下面是一个更加有用的例子——从冒号分隔的 `/etc/passwd` 文件中获取数据: ``` $ awk -F: '{print $1}' /etc/passwd | head -11 root daemon bin sys sync games man lp mail news uucp ``` ### 筛选内容 你也可以使用 `awk` 命令评估字段。例如你仅仅想列出 `/etc/passwd` 中的用户账号,就可以对第三个字段做一些筛选。下面的例子中我们只关注大于等于 1000 的 UID: ``` $ awk -F":" ' $3 >= 1000 ' /etc/passwd nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin shs:x:1000:1000:Sandra Henry-Stocker,,,:/home/shs:/bin/bash nemo:x:1001:1001:Nemo,,,:/home/nemo:/usr/bin/zsh dory:x:1002:1002:Dory,,,:/home/dory:/bin/bash ... ``` 如果你想为输出增加标题,可以添加 `BEGIN` 从句: ``` $ awk -F":" 'BEGIN {print "user accounts:"} $3 >= 1000 ' /etc/passwd user accounts: nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin shs:x:1000:1000:Sandra Henry-Stocker,,,:/home/shs:/bin/bash nemo:x:1001:1001:Nemo,,,:/home/nemo:/usr/bin/zsh dory:x:1002:1002:Dory,,,:/home/dory:/bin/bash ``` 如果你想要不止一行的标题,你可以通过 `"\n"` 分隔输出: ``` $ awk -F":" 'BEGIN {print "user accounts\n============="} $3 >= 1000 ' /etc/passwd user accounts ============= nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin shs:x:1000:1000:Sandra Henry-Stocker,,,:/home/shs:/bin/bash nemo:x:1001:1001:Nemo,,,:/home/nemo:/usr/bin/zsh dory:x:1002:1002:Dory,,,:/home/dory:/bin/bash ``` ### 在 awk 中进行数学计算 `awk` 提供了惊人的数学计算能力,并且可以开平方,算 `log`,算 `tan` 等等。 这里有一对例子: ``` $ awk 'BEGIN {print sqrt(2019)}' 44.9333 $ awk 'BEGIN {print log(2019)}' 7.61036 ``` 想要详细了解 `awk` 的数学计算能力,可以看《[使用 awk 进行数学计算](https://www.networkworld.com/article/2974753/doing-math-with-awk.html)》这篇文章。 ### awk 脚本 你也可以使用 `awk` 写一套单独的脚本。下面的例子模仿了之前写过的一个,不过还计算了系统里账户的数量。 ``` #!/usr/bin/awk -f # 这一行是注释 BEGIN { printf "%s\n","User accounts:" print "==============" FS=":" n=0 } # 现在开始遍历数据 { if ($3 >= 1000) { print $1 n ++ } } END { print "==============" print n " accounts" } ``` 注意 `BEGIN` 那一节是如何提供标题、指定字段分隔符和初始化计数器的,它仅在脚本初始化时期执行。这个脚本也包含 `END` 节,它仅在中间所有命令处理完成之后运行,显示了所有中间小节所筛选数据的最终行数(第三个字段大于等于 1000)。 作为一个长存于 Unix 之上的命令,`awk` 依旧提供着非常有用的服务,这也是我几十年前爱上 Unix 的原因之一。 --- via: <https://www.networkworld.com/article/3454979/the-many-faces-of-awk.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[LuuMing](https://github.com/LuuMing) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,660
为何 Elementary OS 中使用 Pantheon 桌面
https://opensource.com/article/19/12/pantheon-linux-desktop
2019-12-10T08:54:00
[ "Elementary" ]
https://linux.cn/article-11660-1.html
> > 本文是 Linux 桌面特别系列的一部分。通过在 Elementary OS 上运行 Pantheon 桌面获得广受喜爱的 Mac OS 特性。 > > > ![](/data/attachment/album/201912/10/085342dfgngrpt6sgzl3af.jpg) 你愿意为 Linux 桌面支付 20 美元吗?事实上,我会在下载自由软件时选择支付更多的钱!我这样做的原因是开源是值得的。对于 [Elementary OS](https://elementary.io/) 的拷贝,默认价格是 20 美元(你可以选择 1 美元,如果你无法负担,你甚至可以用 0 美元下载)。作为回报,你将获得一个出色且精心制作的发行版,同时拥有它自己的 Pantheon 桌面设计。 你可能会发现 Pantheon 已包含在软件仓库中,因为它是开源的,但你更可能需要下载并安装 [Elementary](http://elementary.io) Linux 才能体验它。如果你还不准备在计算机上将 Elementary 作为主操作系统,那么可以将其安装到虚拟机中,例如 [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization) 中。 Pantheon 桌面整洁、吸引人,并且有许多用户希望在桌面中获得的东西,但在普通的 Linux 桌面上却无法获得。 ### Pantheon 桌面之旅 乍一看,Pantheon 桌面看起来有点像 Cinnamon、Budgie 或 GNOME 3 的经典模式。但是,Pantheon 最令人兴奋的功能是极小的接触。它在你很少注意到的地方都表现出色,直到有一天这里成为了你一天都会看的地方,并且会意识到它的工作方式确实改善了你的生活质量,更不用说让你过得愉快多了。 最明显的例子是“文件名高亮”。几十年来,Mac OS 一直有一个广受欢迎的功能,你可以高亮显示重要文件的名称。人们使用此功能作为快速视觉指示器,来告诉自己哪个文件是这几个的“最佳”版本,或者哪个文件应该发送给朋友,或者哪个文件仍然需要处理。它们可以是任意颜色,可以表示用户想要的任何含义。最重要的是,它是引人注目的视觉元数据。 从 Mac OS 切换过来用户往往在 GNOME 和 KDE 以及其他 Linux 中可选的桌面中怀念这个功能。Pantheon 悄悄地随手解决了这个问题。 ![A highlighted file in the Pantheon desktop](/data/attachment/album/201912/10/085405chh7wi7uyiprwpwh.jpg "A highlighted file in the Pantheon desktop") 当然,那只是其中一个例子。Pantheon 有很多你直到用才会想到的小功能。 桌面精致而吸引人,有所有其他很多桌面缺少的直观组件。在许多方面,它充分吸取了其他桌面好的想法,并避免实现多余的东西。 ![Pantheon desktop on Elementary OS](/data/attachment/album/201912/10/085407ldyru03zvli1xk3g.jpg "Pantheon desktop on Elementary OS") ### 自定义 Pantheon 桌面 Pantheon 桌面表达了如何操作计算机的清晰愿景。这种设计的“问题”(至少在开源之外)是,一个人的偏好可能无法满足另一个人的效率。 但它是开源的。它可以更改,任何不能改变的东西都可以被丢弃。Pantheon 绝对是针对特定用户群的桌面,但是即使对于那些对桌面应该如何工作抱有自己期望的人,Pantheon 也会比初看上去更加灵活。许多内置设计都具有替代选项,当你无法根据自己的喜好进行调整时,你可以轻松选择其他应用。主题引擎可确保你的替换应用看起来与桌面的其它部分和谐一致,而通常的 Linux 系统兼容性可确保你选择的所有应用都能按预期相互配合。 ![Which one is the guest?](/data/attachment/album/201912/10/085408qgwpgmgmkkkcm9r4.jpg "Which one is the guest?") 这些替代品,可使你事半功倍。 ### 受欢迎的补充 撇开这个桌面的词源不说,此桌面确实是许多 Linux 用户祈祷的答案(LCTT 译注:Pantheon 的意思是“万神庙”)。无论它是否是你的风格,Pantheon 桌面都是 Linux 用户体验中重要且受欢迎的补充。自己尝试一下,看看它是否是你一直期待的。 --- via: <https://opensource.com/article/19/12/pantheon-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Would you pay $20 for a Linux desktop? I would, and in fact, I regularly choose to pay more than that when I download free software! The reason I do this is that open source is worth it. For a copy of [Elementary OS](https://elementary.io/), US$ 20 happens to be the default asking price (you can download it for $1 or even $0 if you can't afford anything more). What you get in return is an excellent and heavily curated distribution that ships with its own Pantheon desktop design. You may find Pantheon included in a software repository, as it is open source, but more likely, you'll have to download and install [Elementary](http://elementary.io) Linux to experience it. If you're not ready to install Elementary on your computer as the main OS, you can install it into a virtual machine, like [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization). The Pantheon desktop is clean, attractive, and features many of the little things many users want in a desktop but could never quite get from the usual Linux desktops. ## Pantheon desktop tour At first glance, the Pantheon desktop looks a little like Cinnamon or Budgie or the Classic mode of GNOME 3. However, the most exciting features of Pantheon are the smallest touches. It excels in all the places you notice the very least, until that place is the only thing you're looking at one day, and you realize that the way it works has literally improved your quality of life, to say nothing of making your day a lot nicer. The clearest example of this is **file name highlighting**. For decades, Mac OS has had a much-loved feature whereby you can highlight the displayed name of an important file. People use this feature as a quick visual indicator to tell themselves which file is the "best" version of several, or which file should be sent to a friend, or which file still needs work. They're arbitrary colors and can mean whatever the user wants them to mean. Most importantly, it's noticeable visual metadata. Users switching from Mac OS tend to miss this feature in GNOME and KDE and every other desktop option Linux has on offer. Pantheon quietly and casually solves that problem. ![A highlighted file in the Pantheon desktop A highlighted file in the Pantheon desktop](https://opensource.com/sites/default/files/uploads/advent-pantheon-highlight.jpg) Of course, that's just one example of many. Pantheon is filled with small features that you don't think about until you need them. The desktop is refined and attractive, with all the intuitive parts that have disappeared from many other desktops. In many ways, it has taken the best of the good ideas of many different interfaces and refrained from implementing the excesses. ![Pantheon desktop on Elementary OS Pantheon desktop on Elementary OS](https://opensource.com/sites/default/files/uploads/advent-pantheon.jpg) ## Customizing the Pantheon desktop The Pantheon desktop represents a pretty clear vision of how a computer ought to be operated. The "problem" with this kind of design (outside of open source, at least) is that one person's preference may not be another person's efficiency. But this is open source. Things can be changed, and whatever can't be changed can be discarded for a different option. Pantheon is definitely a desktop for a specific set of users, but even those of us with our own expectations of how a desktop ought to work might find Pantheon refreshingly more flexible than it first appears. There are overrides for many built-in designs, and when you can't adjust something to your liking, you can easily choose an alternative application. The theme engine ensures that your replacement application looks integrated with the rest of your desktop, and the usual Linux system buses ensure that all of your chosen applications communicate with one another as expected. ![Which one is the guest? Which one is the guest?](https://opensource.com/sites/default/files/uploads/advent-pantheon-pcmanfm.jpg) As compromises go, this one does a lot to meet you halfway. ## A welcome addition Etymology aside, this desktop truly is an answer to the prayers of many Linux users. Whether it's your style or not, the Pantheon desktop is an important and welcome addition to the Linux user experience. Try it for yourself and see if it's the good news you've been waiting for. ## Comments are closed.
11,661
在 Linux 终端快速检测网站是否宕机的 6 个方法
https://www.2daygeek.com/linux-command-check-website-is-up-down-alive/
2019-12-10T09:38:26
[ "ping" ]
https://linux.cn/article-11661-1.html
> > 本教程教你怎样在 Linux 终端快速检测一个网站是否宕机。 > > > ![](/data/attachment/album/201912/10/093801u332115oocxz4531.jpg) 你可能已经了解了一些类似的命令,像 `ping`、`curl` 和 `wget`。我们在本教程中又加入了一些其他命令。同时,我们也加入了不同的选项来检测单个和多个主机的信息。 本文将帮助你检测网站是否宕机。但是如果你在维护一些网站,希望网站宕掉时得到实时的报警,我推荐你去使用实时网站监控工具。这种工具有很多,有些是免费的,大部分收费。根据你的需求,选择合适的工具。在后续的文章中我们会涉及这个主题。 ### 方法 1:使用 fping 命令检测一个网站是否宕机 [fping 命令](https://www.2daygeek.com/how-to-use-ping-fping-gping-in-linux/) 是一个类似 `ping` 的程序,使用互联网控制消息协议(ICMP)的<ruby> 回应请求报文 <rt> echo request </rt></ruby>来判断目标主机是否能回应。`fping` 与 `ping` 的不同之处在于它可以并行地 `ping` 任意数量的主机,也可以从一个文本文件读入主机名称。`fping` 发送一个 ICMP 回应请求后不等待目标主机响应,就以轮询模式向下一个目标主机发请求。如果一个目标主机有响应,那么它就被标记为存活的,然后从检查目标列表里去掉。如果一个目标主机在限定的时间和(或)重试次数内没有响应,则被指定为网站无法到达的。 ``` # fping 2daygeek.com linuxtechnews.com magesh.co.in 2daygeek.com is alive linuxtechnews.com is alive magesh.co.in is alive ``` ### 方法 2:使用 http 命令检测一个网站是否宕机 HTTPie(读作 aitch-tee-tee-pie)是一个命令行 HTTP 客户端。[httpie](https://www.2daygeek.com/httpie-curl-wget-alternative-http-client-linux/) 是一个可以与 web 服务通过 CLI 进行交互的现代工具。httpie 工具提供了简单的 `http` 命令,可以通过发送简单的、自然语言语法的任意 HTTP 请求得到多彩的结果输出。HTTPie 可以用来对 HTTP 服务器进行测试、调试和基本的交互。 ``` # http 2daygeek.com HTTP/1.1 301 Moved Permanently CF-RAY: 535b66722ab6e5fc-LHR Cache-Control: max-age=3600 Connection: keep-alive Date: Thu, 14 Nov 2019 19:30:28 GMT Expires: Thu, 14 Nov 2019 20:30:28 GMT Location: https://2daygeek.com/ Server: cloudflare Transfer-Encoding: chunked Vary: Accept-Encoding ``` ### 方法 3:使用 curl 命令检测一个网站是否宕机 [curl 命令](https://www.2daygeek.com/curl-linux-command-line-download-manager/) 是一个用于在服务器间通过支持的协议(DICT、FILE、FTP、FTPS、GOPHER、HTTP、HTTPS、IMAP、IMAPS、LDAP、LDAPS、POP3、POP3S、RTMP、RTSP、SCP、SFTP、SMTP、SMTPS、TELNET 和 TFTP)传输数据的工具。这个工具不支持用户交互。`curl` 也支持使用代理、用户认证、FTP 上传、HTTP POST 请求、SSL 连接、cookie、断点续传、Metalink 等等。`curl`由 libcurl 库提供所有与传输有关的能力。 ``` # curl -I https://www.magesh.co.in HTTP/2 200 date: Thu, 14 Nov 2019 19:39:47 GMT content-type: text/html set-cookie: __cfduid=db16c3aee6a75c46a504c15131ead3e7f1573760386; expires=Fri, 13-Nov-20 19:39:46 GMT; path=/; domain=.magesh.co.in; HttpOnly vary: Accept-Encoding last-modified: Sun, 14 Jun 2015 11:52:38 GMT x-cache: HIT from Backend cf-cache-status: DYNAMIC expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server: cloudflare cf-ray: 535b74123ca4dbf3-LHR ``` 如果你只想看 HTTP 状态码而不是返回的全部信息,用下面的 `curl` 命令: ``` # curl -I "www.magesh.co.in" 2>&1 | awk '/HTTP\// {print $2}' 200 ``` 如果你想看一个网站是否宕机,用下面的 bash 脚本: ``` # vi curl-url-check.sh #!/bin/bash if curl -I "https://www.magesh.co.in" 2>&1 | grep -w "200\|301" ; then echo "magesh.co.in is up" else echo "magesh.co.in is down" fi ``` 当你把脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh curl-url-check.sh HTTP/2 200 magesh.co.in is up ``` 如果你想看多个网站的状态,使用下面的 shell 脚本: ``` # vi curl-url-check-1.sh #!/bin/bash for site in www.google.com google.co.in www.xyzzz.com do if curl -I "$site" 2>&1 | grep -w "200\|301" ; then echo "$site is up" else echo "$site is down" fi echo "----------------------------------" done ``` 当你把上面脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh curl-url-check-1.sh HTTP/1.1 200 OK www.google.com is up ---------------------------------- HTTP/1.1 301 Moved Permanently google.co.in is up ---------------------------------- www.xyzzz.com is down ---------------------------------- ``` ### 方法 4:使用 wget 命令检测一个网站是否宕机 [wget 命令](https://www.2daygeek.com/wget-linux-command-line-download-utility-tool/)(前身是 Geturl)是一个自由开源的命令行下载工具,通过 HTTP、HTTPS、FTP 和其他广泛使用的互联网协议获取文件。`wget` 是非交互式的命令行工具,由 World Wide Web 和 get 得名。`wget` 相对于其他工具来说更优秀,功能包括后台运行、递归下载、多文件下载、断点续传、非交互式下载和大文件下载。 ``` # wget -S --spider https://www.magesh.co.in Spider mode enabled. Check if remote file exists. --2019-11-15 01:22:00-- https://www.magesh.co.in/ Loaded CA certificate '/etc/ssl/certs/ca-certificates.crt' Resolving www.magesh.co.in (www.magesh.co.in)… 104.18.35.52, 104.18.34.52, 2606:4700:30::6812:2334, … Connecting to www.magesh.co.in (www.magesh.co.in)|104.18.35.52|:443… connected. HTTP request sent, awaiting response… HTTP/1.1 200 OK Date: Thu, 14 Nov 2019 19:52:01 GMT Content-Type: text/html Connection: keep-alive Set-Cookie: __cfduid=db73306a2f1c72c1318ad4709ef49a3a01573761121; expires=Fri, 13-Nov-20 19:52:01 GMT; path=/; domain=.magesh.co.in; HttpOnly Vary: Accept-Encoding Last-Modified: Sun, 14 Jun 2015 11:52:38 GMT X-Cache: HIT from Backend CF-Cache-Status: DYNAMIC Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Server: cloudflare CF-RAY: 535b85fe381ee684-LHR Length: unspecified [text/html] Remote file exists and could contain further links, but recursion is disabled -- not retrieving. ``` 如果你只想看 HTTP 状态码而不是返回的全部结果,用下面的 `wget` 命令: ``` # wget --spider -S "www.magesh.co.in" 2>&1 | awk '/HTTP\// {print $2}' 200 ``` 如果你想看一个网站是否宕机,用下面的 bash 脚本: ``` # vi wget-url-check.sh #!/bin/bash if wget --spider -S "https://www.google.com" 2>&1 | grep -w "200\|301" ; then echo "Google.com is up" else echo "Google.com is down" fi ``` 当你把脚本内容添加到一个文件后,执行文件,查看结果: ``` # wget-url-check.sh HTTP/1.1 200 OK Google.com is up ``` 如果你想看多个网站的状态,使用下面的 shell 脚本: ``` # vi curl-url-check-1.sh #!/bin/bash for site in www.google.com google.co.in www.xyzzz.com do if wget --spider -S "$site" 2>&1 | grep -w "200\|301" ; then echo "$site is up" else echo "$site is down" fi echo "----------------------------------" done ``` 当你把上面脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh wget-url-check-1.sh HTTP/1.1 200 OK www.google.com is up ---------------------------------- HTTP/1.1 301 Moved Permanently google.co.in is up ---------------------------------- www.xyzzz.com is down ---------------------------------- ``` ### 方法 5:使用 lynx 命令检测一个网站是否宕机 [lynx](https://www.2daygeek.com/best-text-mode-based-command-line-web-browser-for-linux/) 是一个在<ruby> 可寻址光标字符单元终端 <rt> cursor-addressable character cell terminals </rt></ruby>上使用的基于文本的高度可配的 web 浏览器,它是最古老的 web 浏览器并且现在仍在活跃开发。 ``` # lynx -head -dump http://www.magesh.co.in HTTP/1.1 200 OK Date: Fri, 15 Nov 2019 08:14:23 GMT Content-Type: text/html Connection: close Set-Cookie: __cfduid=df3cb624024b81df7362f42ede71300951573805662; expires=Sat, 1 4-Nov-20 08:14:22 GMT; path=/; domain=.magesh.co.in; HttpOnly Vary: Accept-Encoding Last-Modified: Sun, 14 Jun 2015 11:52:38 GMT X-Cache: HIT from Backend CF-Cache-Status: DYNAMIC Server: cloudflare CF-RAY: 535fc5704a43e694-LHR ``` 如果你只想看 HTTP 状态码而不是返回的全部结果,用下面的 `lynx` 命令: ``` # lynx -head -dump https://www.magesh.co.in 2>&1 | awk '/HTTP\// {print $2}' 200 ``` 如果你想看一个网站是否宕机,用下面的 bash 脚本: ``` # vi lynx-url-check.sh #!/bin/bash if lynx -head -dump http://www.magesh.co.in 2>&1 | grep -w "200\|301" ; then echo "magesh.co.in is up" else echo "magesh.co.in is down" fi ``` 当你把脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh lynx-url-check.sh HTTP/1.1 200 OK magesh.co.in is up ``` 如果你想看多个网站的状态,使用下面的 shell 脚本: ``` # vi lynx-url-check-1.sh #!/bin/bash for site in http://www.google.com https://google.co.in http://www.xyzzz.com do if lynx -head -dump "$site" 2>&1 | grep -w "200\|301" ; then echo "$site is up" else echo "$site is down" fi echo "----------------------------------" done ``` 当你把上面脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh lynx-url-check-1.sh HTTP/1.0 200 OK http://www.google.com is up ---------------------------------- HTTP/1.0 301 Moved Permanently https://google.co.in is up ---------------------------------- www.xyzzz.com is down ---------------------------------- ``` ### 方法 6:使用 ping 命令检测一个网站是否宕机 [ping 命令](https://www.2daygeek.com/how-to-use-ping-fping-gping-in-linux/)(Packet Internet Groper)是网络工具的代表,用于在互联网协议(IP)的网络中测试一个目标主机是否可用/可连接。通过向目标主机发送 ICMP 回应请求报文包并等待 ICMP 回应响应报文来检测主机的可用性。它基于已发送的包、接收到的包和丢失了的包来统计结果数据,通常包含最小/平均/最大响应时间。 ``` # ping -c 5 2daygeek.com PING 2daygeek.com (104.27.157.177) 56(84) bytes of data. 64 bytes from 104.27.157.177 (104.27.157.177): icmp_seq=1 ttl=58 time=228 ms 64 bytes from 104.27.157.177 (104.27.157.177): icmp_seq=2 ttl=58 time=227 ms 64 bytes from 104.27.157.177 (104.27.157.177): icmp_seq=3 ttl=58 time=250 ms 64 bytes from 104.27.157.177 (104.27.157.177): icmp_seq=4 ttl=58 time=171 ms 64 bytes from 104.27.157.177 (104.27.157.177): icmp_seq=5 ttl=58 time=193 ms --- 2daygeek.com ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 13244ms rtt min/avg/max/mdev = 170.668/213.824/250.295/28.320 ms ``` ### 附加 1:使用 telnet 命令检测一个网站是否宕机 `telnet` 命令是一个使用 TELNET 协议用于 TCP/IP 网络中多个主机相互通信的古老的网络协议。它通过 23 端口连接其他设备如计算机和网络设备。`telnet` 是不安全的协议,现在由于用这个协议发送的数据没有经过加密可能被黑客拦截,所以不推荐使用。大家都使用经过加密且非常安全的 SSH 协议来代替 `telnet`。 ``` # telnet google.com 80 Trying 216.58.194.46… Connected to google.com. Escape character is '^]'. ^] telnet> quit Connection closed. ``` ### 附加 2:使用 bash 脚本检测一个网站是否宕机 简而言之,一个 [shell 脚本](https://www.2daygeek.com/category/shell-script/) 就是一个包含一系列命令的文件。shell 从文件读取内容按输入顺序逐行在命令行执行。为了让它更有效,我们添加一些条件。这也减轻了 Linux 管理员的负担。 如果你想想用 `wget` 命令看多个网站的状态,使用下面的 shell 脚本: ``` # vi wget-url-check-2.sh #!/bin/bash for site in www.google.com google.co.in www.xyzzz.com do if wget --spider -S "$site" 2>&1 | grep -w "200\|301" > /dev/null ; then echo "$site is up" else echo "$site is down" fi done ``` 当你把上面脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh wget-url-check-2.sh www.google.com is up google.co.in is up www.xyzzz.com is down ``` 如果你想用 `wget` 命令看多个网站的状态,使用下面的 [shell 脚本](https://www.2daygeek.com/category/bash-script/): ``` # vi curl-url-check-2.sh #!/bin/bash for site in www.google.com google.co.in www.xyzzz.com do if curl -I "$site" 2>&1 | grep -w "200\|301" > /dev/null ; then echo "$site is up" else echo "$site is down" fi done ``` 当你把上面脚本内容添加到一个文件后,执行文件,查看结果: ``` # sh curl-url-check-2.sh www.google.com is up google.co.in is up www.xyzzz.com is down ``` --- via: <https://www.2daygeek.com/linux-command-check-website-is-up-down-alive/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
11,663
在 Linux 命令行发送邮件的 5 种方法
https://www.2daygeek.com/6-ways-to-send-email-from-the-linux-command-line/
2019-12-11T08:18:26
[ "邮件", "mail" ]
https://linux.cn/article-11663-1.html
![](/data/attachment/album/201912/11/081806v1p8b444qozbp84u.jpg) 当你需要在 shell 脚本中创建邮件时,就需要用到命令行发送邮件的知识。Linux 中有很多命令可以实现发送邮件。本教程中包含了最流行的 5 个命令行邮件客户端,你可以选择其中一个。这 5 个命令分别是: * `mail` / `mailx` * `mutt` * `mpack` * `sendmail` * `ssmtp` ### 工作原理 我先从整体上来解释下 Linux 中邮件命令怎么把邮件传递给收件人的。邮件命令撰写邮件并发送给一个本地邮件传输代理(MTA,如 sendmail、Postfix)。邮件服务器和远程邮件服务器之间通信以实际发送和接收邮件。下面的流程可以看得更详细。 ![](/data/attachment/album/201912/11/081830xntnd4iny5nl9ran.png) ### 1) 如何在 Linux 上安装 mail/mailx 命令 `mail` 命令是 Linux 终端发送邮件用的最多的命令。`mailx` 是 `mail` 命令的更新版本,基于 Berkeley Mail 8.1,意在提供 POSIX `mailx` 命令的功能,并支持 MIME、IMAP、POP3、SMTP 和 S/MIME 扩展。mailx 在某些交互特性上更加强大,如缓冲邮件消息、垃圾邮件评分和过滤等。在 Linux 发行版上,`mail` 命令是 `mailx` 命令的软链接。可以运行下面的命令从官方发行版仓库安装 `mail` 命令。 对于 Debian/Ubuntu 系统,使用 [APT-GET 命令](https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/) 或 [APT 命令](https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/) 安装 mailutils。 ``` $ sudo apt-get install mailutils ``` 对于 RHEL/CentOS 系统,使用 [YUM 命令](https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/) 安装 mailx。 ``` $ sudo yum install mailx ``` 对于 Fedora 系统,使用 [DNF 命令](https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/) 安装 mailx。 ``` $ sudo dnf install mailx ``` #### 1a) 如何在 Linux 上使用 mail 命令发送邮件 `mail` 命令简单易用。如果你不需要发送附件,使用下面的 `mail` 命令格式就可以发送邮件了: ``` $ echo "This is the mail body" | mail -s "Subject" [email protected] ``` 如果你要发送附件,使用下面的 `mail` 命令格式: ``` $ echo "This is the mail body" | mail -a test1.txt -s "Subject" [email protected] ``` * `-a`:用于在基于 Red Hat 的系统上添加附件。 * `-A`:用于在基于 Debian 的系统上添加附件。 * `-s`:指定消息标题。 ### 2) 如何在 Linux 上安装 mutt 命令 `mutt` 是另一个很受欢迎的在 Linux 终端发送邮件的命令。`mutt` 是一个小而强大的基于文本的程序,用来在 unix 操作系统下阅读和发送电子邮件,并支持彩色终端、MIME、OpenPGP 和按邮件线索排序的模式。可以运行下面的命令从官方发行版仓库安装 `mutt` 命令。 对于 Debian/Ubuntu 系统,使用 [APT-GET 命令](https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/) 或 [APT 命令](https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/) 安装 mutt。 ``` $ sudo apt-get install mutt ``` 对于 RHEL/CentOS 系统,使用 [YUM 命令](https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/) 安装 mutt。 ``` $ sudo yum install mutt ``` 对于 Fedora 系统,使用 [DNF 命令](https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/) 安装 mutt。 ``` $ sudo dnf install mutt ``` #### 2b) 如何在 Linux 上使用 mutt 命令发送邮件 `mutt` 一样简单易用。如果你不需要发送附件,使用下面的 `mutt` 命令格式就可以发送邮件了: ``` $ echo "This is the mail body" | mutt -s "Subject" [email protected] ``` 如果你要发送附件,使用下面的 `mutt` 命令格式: ``` $ echo "This is the mail body" | mutt -s "Subject" [email protected] -a test1.txt ``` ### 3) 如何在 Linux 上安装 mpack 命令 `mpack` 是另一个很受欢迎的在 Linux 终端上发送邮件的命令。`mpack` 程序会在一个或多个 MIME 消息中对命名的文件进行编码。编码后的消息被发送到一个或多个收件人。可以运行下面的命令从官方发行版仓库安装 `mpack` 命令。 对于 Debian/Ubuntu 系统,使用 [APT-GET 命令](https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/) 或 [APT 命令](https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/) 安装 mpack。 ``` $ sudo apt-get install mpack ``` 对于 RHEL/CentOS 系统,使用 [YUM 命令](https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/) 安装 mpack。 ``` $ sudo yum install mpack ``` 对于 Fedora 系统,使用 [DNF 命令](https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/) 安装 mpack。 ``` $ sudo dnf install mpack ``` #### 3a) 如何在 Linux 上使用 mpack 命令发送邮件 `mpack` 同样简单易用。如果你不需要发送附件,使用下面的 `mpack` 命令格式就可以发送邮件了: ``` $ echo "This is the mail body" | mpack -s "Subject" [email protected] ``` 如果你要发送附件,使用下面的 mpack 命令格式: ``` $ echo "This is the mail body" | mpack -s "Subject" [email protected] -a test1.txt ``` ### 4) 如何在 Linux 上安装 sendmail 命令 sendmail 是一个上广泛使用的通用 SMTP 服务器,你也可以从命令行用 `sendmail` 发邮件。可以运行下面的命令从官方发行版仓库安装 `sendmail` 命令。 对于 Debian/Ubuntu 系统,使用 [APT-GET 命令](https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/) 或 [APT 命令](https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/)安装 sendmail。 ``` $ sudo apt-get install sendmail ``` 对于 RHEL/CentOS 系统,使用 [YUM 命令](https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/) 安装 sendmail。 ``` $ sudo yum install sendmail ``` 对于 Fedora 系统,使用 [DNF 命令](https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/) 安装 sendmail。 ``` $ sudo dnf install sendmail ``` #### 4a) 如何在 Linux 上使用 sendmail 命令发送邮件 `sendmail` 同样简单易用。使用下面的 `sendmail` 命令发送邮件。 ``` $ echo -e "Subject: Test Mail\nThis is the mail body" > /tmp/send-mail.txt ``` ``` $ sendmail [email protected] < send-mail.txt ``` ### 5) 如何在 Linux 上安装 ssmtp 命令 `ssmtp` 是类似 `sendmail` 的一个只发送不接收的工具,可以把邮件从本地计算机传递到配置好的 邮件主机(mailhub)。用户可以在 Linux 命令行用 `ssmtp` 把邮件发送到 SMTP 服务器。可以运行下面的命令从官方发行版仓库安装 `ssmtp` 命令。 对于 Debian/Ubuntu 系统,使用 [APT-GET 命令](https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/) 或 [APT 命令](https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/)安装 ssmtp。 ``` $ sudo apt-get install ssmtp ``` 对于 RHEL/CentOS 系统,使用 [YUM 命令](https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/) 安装 ssmtp。 ``` $ sudo yum install ssmtp ``` 对于 Fedora 系统,使用 [DNF 命令](https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/) 安装 ssmtp。 ``` $ sudo dnf install ssmtp ``` ### 5a) 如何在 Linux 上使用 ssmtp 命令发送邮件 `ssmtp` 同样简单易用。使用下面的 `ssmtp` 命令格式发送邮件。 ``` $ echo -e "Subject: Test Mail\nThis is the mail body" > /tmp/ssmtp-mail.txt ``` ``` $ ssmtp [email protected] < /tmp/ssmtp-mail.txt ``` --- via: <https://www.2daygeek.com/6-ways-to-send-email-from-the-linux-command-line/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
11,664
Dell XPS 13 7390:最好的 Linux 桌面笔记本
https://www.linux.com/articles/dell-xps-13-7390-review-the-best-laptop-for-desktop-linux-user/
2019-12-11T09:14:00
[ "Linux", "XPS" ]
https://linux.cn/article-11664-1.html
![](/data/attachment/album/201912/11/090509vwdm33q8dwqdgnnx.jpg) 曾经,我们必须进行大量研究、阅读大量评论,才能找到一种在所选的 Linux 桌面发行版上可以以最少的麻烦工作的机器。而如今,这种日子已经一去不复返了,几乎每台机器都可以运行 Linux。Linux 内核社区在设备驱动程序支持方面做得非常出色,可以使一切都开箱即用。 不过,有的是**可以**运行 Linux 的机器,有的是运行 Linux 的机器。戴尔计算机属于后一类。五年前,Barton George 在戴尔内部启动了一项计划,将桌面版 Linux 引入到消费级的高端戴尔系统。从一台机器开始,到现在整套从产品线的高端笔记本电脑和台式机都可以运行 Linux。 在这些机器中,XPS 13 是我的最爱。尽管我需要一个功能强大的台式机来处理 4K UHD、多机位视频制作,但我还需要一台超便携的笔记本电脑,可以随身携带,而不必担心笨重的背包和充电器。XPS 13 也是我的第一台笔记本电脑,陪了我 7 年多。因此,是的,这还有一个怀旧因素。 戴尔几乎每年都会更新其 XPS 产品线,并且最新的[产品展示宣布于 10 月](https://bartongeorge.io/2019/08/21/please-welcome-the-9th-generation-of-the-xps-13-developer-edition/)。[XPS 13(7390)](https://blog.dell.com/en-us/dells-new-consumer-pc-portfolio-unveiled-ifa-2019/) 是该系列的增量更新,而且戴尔非常乐意向我寄来一台测评设备。 ![](/data/attachment/album/201912/11/090524z2xk670shp0080mx.jpg) 它由 6 核 Core i7-10710U CPU 所支持。它配备 16GB 内存和 1TB SSD。在 1.10 GHz 的基本频率(可以超频到 4.1 GHz)的情况下,这是一台用于常规工作负载的出色机器。它没有使用任何专用的 GPU,因此它并不适合进行游戏或从源代码进行编译的 Gentoo Linux 或 Arch Linux。但是,我确实设法在上面运行了一些 Steam 游戏。 如果你想运行 Kubernetes 集群、AI 框架或虚拟现实,那么 Precision 系列中还有更强大的机器,这些机器可以运行 Red Hat Enterprise Linux 和 Ubuntu。 该机器的底盘与上一代相同。边框保持与上一代一样的薄,依旧比 MacBook 和微软的 Surface Pro 薄。 它具有三个端口,其中两个是 USB-C Thunderbolt 3,可用于连接 4K 显示器、USB 附件以及用于对等网络的计算机之间的高速数据传输。 它还具有一个 microSD 插槽。作为视频记者,SD 卡插槽会更有用。大量使用树莓派的用户也会喜欢这种卡。 它具有 4 个麦克风和一个改进的摄像头,该摄像头现在位于顶部(再见,鼻孔摄像头!)。 XPS 13(7390)光滑纤薄。它的重量仅为 2.7 磅(1.2kg),可以与苹果的 MacBook Air 相提并论。 这台机器可以成为你的旅行伴侣,并且可以执行日常任务,例如检查电子邮件、浏览网络和写作。 其 4K UHD 屏幕支持 HDR,这意味着你将可以尽享《The Mandalorian》的全部美妙之处。另外,车载扬声器并没有那么好,听起来有些沉闷。它们适合进行视频聊天或休闲的 YouTube 观看,但是如果你想在今年晚些时候观看《The Witcher》剧集,或者想欣赏 Amazon、Apple Music 或 YouTube Music 的音乐,则需要耳机或外接扬声器。 ![](/data/attachment/album/201912/11/091107p8de88jk5pwffd4a.jpg) 但是,在插入充电线之前,你可以能使用这台机器多少时间?在正常工作量的情况下,它为我提供了大约 7-8 个小时的电池续航时间:我打开了几个选项卡浏览网络,只是看看电影或听音乐。多任务处理,尤其是各种 Web 活动,都会加速消耗电池电量。在 Linux 上进行一些微调可能会给你带来更多的续航时间,而在 Windows 10 上,我可以使用 10 多个小时呢! 作为仍在从事大量写作工作的视频记者,我非常喜欢键盘。但是,我们这么多年来在 Linux 台式机上听到的触控板故事一直没变:它与 MacBook 或 Windows 上的品质相差甚远。这或许有一天能改变。值得称道的是,他们确实发布了可增强体验的触控板驱动程序,但我没有运行此系统随附的提供的 Ubuntu 18.04 LTS。我全新安装了 Ubuntu 19.10,因为 Gnome 在 18.04 中的运行速度非常慢。我尝试过 openSUSE Tumbleweed、Zorin OS、elementary OS、Fedora、KDE neon 和 Arch Linux。一切正常,尽管有些需要额外的努力才能运行。 那么,该系统适用于谁?显然,这是给那些想要设计精良的、他们信赖的品牌的高端机器的专业人士打造的。适用于喜欢 MacBook Air,但更喜欢 Linux 台式机生态系统的用户。适用于那些希望使用 Linux 来工作,而不是使 Linux 可以工作的人。 我使用这台机器一周的时间,进一步说明了为什么我如此喜欢戴尔的 XPS 系列。它们是目前最好的 Linux 笔记本电脑。这款 XPS 13(7390),你值得拥有! --- via: <https://www.linux.com/articles/dell-xps-13-7390-review-the-best-laptop-for-desktop-linux-user/> 作者:[Swapnil Bhartiya](https://www.linux.com/author/swapnil/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,666
怎样使用 awk 删掉文件中重复的行
https://opensource.com/article/19/10/remove-duplicate-lines-files-awk
2019-12-12T12:43:35
[ "awk" ]
/article-11666-1.html
> > 学习怎样使用 awk 的 `!visited[$0]++` 在不重新排序或改变原排列顺序的前提下删掉重复的行。 > > > ![](/data/attachment/album/201912/12/124322vwe3tq3wlw33tw1f.jpg) 假设你有一个文本文件,你需要删掉所有重复的行。 ### TL;DR *要保持原来的排列顺序*删掉重复行,使用: ``` awk '!visited[$0]++' your_file > deduplicated_file ``` ### 工作原理 这个脚本维护一个关联数组,索引(键)为文件中去重后的行,每个索引对应的值为该行出现的次数。对于文件的每一行,如果这行(之前)出现的次数为 0,则值加 1,并打印这行,否则值加 1,不打印这行。 我之前不熟悉 `awk`,我想弄清楚这么短小的一个脚本是怎么实现的。我调研了下,下面是调研心得: * 这个 awk “脚本” `!visited[$0]++` 对输入文件的*每一行*都执行。 * `visited[]` 是一个[关联数组](http://kirste.userpage.fu-berlin.de/chemnet/use/info/gawk/gawk_12.html)(又名[映射](https://en.wikipedia.org/wiki/Associative_array))类型的变量。`awk` 会在第一次执行时初始化它,因此我们不需要初始化。 * `$0` 变量的值是当前正在被处理的行的内容。 * `visited[$0]` 通过与 `$0`(正在被处理的行)相等的键来访问该映射中的值,即出现次数(我们在下面设置的)。 * `!` 对表示出现次数的值取反: + 在 `awk` 中,[任意非零的数或任意非空的字符串的值是 `true`](https://www.gnu.org/software/gawk/manual/html_node/Truth-Values.html)。 + [变量默认的初始值为空字符串](https://ftp.gnu.org/old-gnu/Manuals/gawk-3.0.3/html_chapter/gawk_8.html),如果被转换为数字,则为 0。 + 也就是说: - 如果 `visited[$0]` 的值是一个比 0 大的数,取反后被解析成 `false`。 - 如果 `visited[$0]` 的值为等于 0 的数字或空字符串,取反后被解析成 `true` 。 + `++` 表示变量 `visited[$0]` 的值加 1。 - 如果该值为空,`awk` 自动把它转换为 `0`(数字) 后加 1。 - 注意:加 1 操作是在我们取到了变量的值之后执行的。 总的来说,整个表达式的意思是: * `true`:如果表示出现次数为 0 或空字符串 * `false`:如果出现的次数大于 0 `awk` 由 [模式或表达式和一个与之关联的动作](http://kirste.userpage.fu-berlin.de/chemnet/use/info/gawk/gawk_9.html) 组成: ``` <模式/表达式> { <动作> } ``` 如果匹配到了模式,就会执行后面的动作。如果省略动作,`awk` 默认会打印(`print`)输入。 > > 省略动作等价于 `{print $0}`。 > > > 我们的脚本由一个 `awk` 表达式语句组成,省略了动作。因此这样写: ``` awk '!visited[$0]++' your_file > deduplicated_file ``` 等于这样写: ``` awk '!visited[$0]++ { print $0 }' your_file > deduplicated_file ``` 对于文件的每一行,如果表达式匹配到了,这行内容被打印到输出。否则,不执行动作,不打印任何东西。 ### 为什么不用 uniq 命令? `uniq` 命令仅能对相邻的行去重。这是一个示例: ``` $ cat test.txt A A A B B B A A C C C B B A $ uniq < test.txt A B A C B A ``` ### 其他方法 #### 使用 sort 命令 我们也可以用下面的 [sort](http://man7.org/linux/man-pages/man1/sort.1.html) 命令来去除重复的行,但是*原来的行顺序没有被保留*。 ``` sort -u your_file > sorted_deduplicated_file ``` #### 使用 cat + sort + cut 上面的方法会产出一个去重的文件,各行是基于内容进行排序的。[通过管道连接命令](https://stackoverflow.com/a/20639730/2292448)可以解决这个问题。 ``` cat -n your_file | sort -uk2 | sort -nk1 | cut -f2- ``` **工作原理** 假设我们有下面一个文件: ``` abc ghi abc def xyz def ghi klm ``` `cat -n test.txt` 在每行前面显示序号: ``` 1 abc 2 ghi 3 abc 4 def 5 xyz 6 def 7 ghi 8 klm ``` `sort -uk2` 基于第二列(`k2` 选项)进行排序,对于第二列相同的值只保留一次(`u` 选项): ``` 1 abc 4 def 2 ghi 8 klm 5 xyz ``` `sort -nk1` 基于第一列排序(`k1` 选项),把列的值作为数字来处理(`-n` 选项): ``` 1 abc 2 ghi 4 def 5 xyz 8 klm ``` 最后,`cut -f2-` 从第二列开始打印每一行,直到最后的内容(`-f2-` 选项:留意 `-` 后缀,它表示这行后面的内容都包含在内)。 ``` abc ghi def xyz klm ``` ### 参考 * [GNU awk 用户手册](https://www.gnu.org/software/gawk/manual/html_node/) * [awk 中的数组](http://kirste.userpage.fu-berlin.de/chemnet/use/info/gawk/gawk_12.html) * [Awk — 真值](https://www.gnu.org/software/gawk/manual/html_node/Truth-Values.html) * [Awk 表达式](https://ftp.gnu.org/old-gnu/Manuals/gawk-3.0.3/html_chapter/gawk_8.html) * [Unix 怎么删除文件中重复的行?](https://stackoverflow.com/questions/1444406/how-can-i-delete-duplicate-lines-in-a-file-in-unix) * [不用排序去掉重复的行(去重)](https://stackoverflow.com/questions/11532157/remove-duplicate-lines-without-sorting) * [‘!a[$0]++’ 工作原理](https://unix.stackexchange.com/questions/159695/how-does-awk-a0-work/159734#159734) 以上为全文。 --- via: <https://opensource.com/article/19/10/remove-duplicate-lines-files-awk> 作者:[Lazarus Lazaridis](https://opensource.com/users/iridakos) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,667
在软件部署中使用 strace 进行调试
https://theartofmachinery.com/2019/11/14/deployment_debugging_strace.html
2019-12-12T13:05:25
[ "strace" ]
https://linux.cn/article-11667-1.html
![](/data/attachment/album/201912/12/130413poennny2pbrgy9ot.jpg) 我的大部分工作都涉及到部署软件系统,这意味着我需要花费很多时间来解决以下问题: * 这个软件可以在原开发者的机器上工作,但是为什么不能在我这里运行? * 这个软件昨天可以在我的机器上工作,但是为什么今天就不行? 这是一种调试的类型,但是与一般的软件调试有所不同。一般的调试通常只关心代码的逻辑,但是在软件部署中的调试关注的是程序的代码和它所在的运行环境之间的相互影响。即便问题的根源是代码的逻辑错误,但软件显然可以在别的机器上运行的事实意味着这类问题与运行环境密切相关。 所以,在软件部署过程中,我没有使用传统的调试工具(例如 `gdb`),而是选择了其它工具进行调试。我最喜欢的用来解决“为什么这个软件无法在这台机器上运行?”这类问题的工具就是 `strace`。 ### 什么是 strace? [strace](https://strace.io/) 是一个用来“追踪系统调用”的工具。它主要是一个 Linux 工具,但是你也可以在其它系统上使用类似的工具(例如 [DTrace](http://dtrace.org/blogs/about/) 和 [ktrace](https://man.openbsd.org/ktrace))。 它的基本用法非常简单。只需要在 `strace` 后面跟上你需要运行的命令,它就会显示出该命令触发的所有系统调用(你可能需要先安装好 `strace`): ``` $ strace echo Hello ...Snip lots of stuff... write(1, "Hello\n", 6) = 6 close(1) = 0 close(2) = 0 exit_group(0) = ? +++ exited with 0 +++ ``` 这些系统调用都是什么?它们就像是操作系统内核提供的 API。很久以前,软件拥有直接访问硬件的权限。如果软件需要在屏幕上显示一些东西,它将会与视频硬件的端口和内存映射寄存器纠缠不清。当多任务操作系统变得流行以后,这就导致了混乱的局面,因为不同的应用程序将“争夺”硬件,并且一个应用程序的错误可能致使其它应用程序崩溃,甚至导致整个系统崩溃。所以 CPU 开始支持多种不同的特权模式(或者称为“保护环”)。它们让操作系统内核在具有完全硬件访问权限的最高特权模式下运行,于此同时,其它在低特权模式下运行的应用程序必须通过向内核发起系统调用才能够与硬件进行交互。 在二进制级别上,发起系统调用相比简单的函数调用有一些区别,但是大部分程序都使用标准库提供的封装函数。例如,POSIX C 标准库包含一个 `write()` 函数,该函数包含用于进行 `write` 系统调用的所有与硬件体系结构相关的代码。 ![](/data/attachment/album/201912/12/130528ylzhw0wh36lb66jw.svg) 简单来说,一个应用程序与其环境(计算机系统)的交互都是通过系统调用来完成的。所以当软件在一台机器上可以工作但是在另一台机器无法工作的时候,追踪系统调用是一个很好的查错方法。具体地说,你可以通过追踪系统调用分析以下典型操作: * 控制台输入与输出 (IO) * 网络 IO * 文件系统访问以及文件 IO * 进程/线程生命周期管理 * 原始内存管理 * 访问特定的设备驱动 ### 什么时候可以使用 strace? 理论上,`strace` 适用于任何用户空间程序,因为所有的用户空间程序都需要进行系统调用。`strace` 对于已编译的低级程序最有效果,但如果你可以避免运行时环境和解释器带来的大量额外输出,则仍然可以与 Python 等高级语言程序一起使用。 当软件在一台机器上正常工作,但在另一台机器上却不能正常工作,同时抛出了有关文件、权限或者不能运行某某命令等模糊的错误信息时,`strace` 往往能大显身手。不幸的是,它不能诊断高等级的问题,例如数字证书验证错误等。这些问题通常需要组合使用 `strace`(有时候是 [`ltrace`](https://linux.die.net/man/1/ltrace))和其它高级工具(例如使用 `openssl` 命令行工具调试数字证书错误)。 本文中的示例基于独立的服务器,但是对系统调用的追踪通常也可以在更复杂的部署平台上完成,仅需要找到合适的工具。 ### 一个简单的例子 假设你正在尝试运行一个叫做 `foo` 的服务器应用程序,但是发生了以下情况: ``` $ foo Error opening configuration file: No such file or directory ``` 显然,它没有找到你已经写好的配置文件。之所以会发生这种情况,是因为包管理工具有时候在编译应用程序时指定了自定义的路径,所以你应当遵循特定发行版提供的安装指南。如果错误信息告诉你正确的配置文件应该在什么地方,你就可以在几秒钟内解决这个问题,但如果没有告诉你呢?你该如何找到正确的路径? 如果你有权访问源代码,则可以通过阅读源代码来解决问题。这是一个好的备用计划,但不是最快的解决方案。你还可以使用类似 `gdb` 的单步调试器来观察程序的行为,但使用专门用于展示程序与系统环境交互作用的工具 `strace` 更加有效。 一开始, `strace` 产生的大量输出可能会让你不知所措,幸好你可以忽略其中大部分的无用信息。我经常使用 `-o` 参数把输出的追踪结果保存到单独的文件里: ``` $ strace -o /tmp/trace foo Error opening configuration file: No such file or directory $ cat /tmp/trace execve("foo", ["foo"], 0x7ffce98dc010 /* 16 vars */) = 0 brk(NULL) = 0x56363b3fb000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=25186, ...}) = 0 mmap(NULL, 25186, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f2f12cf1000 close(3) = 0 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260A\2\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=1824496, ...}) = 0 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2f12cef000 mmap(NULL, 1837056, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f2f12b2e000 mprotect(0x7f2f12b50000, 1658880, PROT_NONE) = 0 mmap(0x7f2f12b50000, 1343488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22000) = 0x7f2f12b50000 mmap(0x7f2f12c98000, 311296, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a000) = 0x7f2f12c98000 mmap(0x7f2f12ce5000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b6000) = 0x7f2f12ce5000 mmap(0x7f2f12ceb000, 14336, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f2f12ceb000 close(3) = 0 arch_prctl(ARCH_SET_FS, 0x7f2f12cf0500) = 0 mprotect(0x7f2f12ce5000, 16384, PROT_READ) = 0 mprotect(0x56363b08b000, 4096, PROT_READ) = 0 mprotect(0x7f2f12d1f000, 4096, PROT_READ) = 0 munmap(0x7f2f12cf1000, 25186) = 0 openat(AT_FDCWD, "/etc/foo/config.json", O_RDONLY) = -1 ENOENT (No such file or directory) dup(2) = 3 fcntl(3, F_GETFL) = 0x2 (flags O_RDWR) brk(NULL) = 0x56363b3fb000 brk(0x56363b41c000) = 0x56363b41c000 fstat(3, {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0x8), ...}) = 0 write(3, "Error opening configuration file"..., 60) = 60 close(3) = 0 exit_group(1) = ? +++ exited with 1 +++ ``` `strace` 输出的第一页通常是低级的进程启动过程。(你可以看到很多 `mmap`、`mprotect`、`brk` 调用,这是用来分配原始内存和映射动态链接库的。)实际上,在查找错误时,最好从下往上阅读 `strace` 的输出。你可以看到 `write` 调用在最后返回了错误信息。如果你向上找,你将会看到第一个失败的系统调用是 `openat`,它在尝试打开 `/etc/foo/config.json` 时抛出了 `ENOENT` (“No such file or directory”)的错误。现在我们已经知道了配置文件应该放在哪里。 这是一个简单的例子,但我敢说在 90% 的情况下,使用 `strace` 进行调试不需要更多复杂的工作。以下是完整的调试步骤: 1. 从程序中获得含糊不清的错误信息 2. 使用 `strace` 运行程序 3. 在输出中找到错误信息 4. 往前追溯并找到第一个失败的系统调用 第四步中的系统调用很可能向你显示出问题所在。 ### 小技巧 在开始更加复杂的调试之前,这里有一些有用的调试技巧帮助你高效使用 `strace`: #### man 是你的朋友 在很多 \*nix 操作系统中,你可以通过 `man syscalls` 查看系统调用的列表。你将会看到类似于 `brk(2)` 之类的东西,这意味着你可以通过运行 `man 2 brk` 得到与此相关的更多信息。 一个小问题:`man 2 fork` 会显示出在 GNU `libc` 里封装的 `fork()` 手册页,而 `fork()` 现在实际上是由 `clone` 系统调用实现的。`fork` 的语义与 `clone` 相同,但是如果我写了一个含有 `fork()` 的程序并使用 `strace` 去调试它,我将找不到任何关于 `fork` 调用的信息,只能看到 `clone` 调用。如果将源代码与 `strace` 的输出进行比较的时候,像这种问题会让人感到困惑。 #### 使用 -o 将输出保存到文件 `strace` 可以生成很多输出,所以将输出保存到单独的文件是很有帮助的(就像上面的例子一样)。它还能够在控制台中避免程序自身的输出与 `strace` 的输出发生混淆。 #### 使用 -s 查看更多的参数 你可能已经注意到,错误信息的第二部分没有出现在上面的例子中。这是因为 `strace` 默认仅显示字符串参数的前 32 个字节。如果你需要捕获更多参数,请向 `strace` 追加类似于 `-s 128` 之类的参数。 #### -y 使得追踪文件或套接字更加容易 “一切皆文件”意味着 \*nix 系统通过文件描述符进行所有 IO 操作,不管是真实的文件还是通过网络或者进程间管道。这对于编程而言是很方便的,但是在追踪系统调用时,你将很难分辨出 `read` 和 `write` 的真实行为。 `-y` 参数使 `strace` 在注释中注明每个文件描述符的具体指向。 #### 使用 -p 附加到正在运行的进程中 正如我们将在后面的例子中看到的,有时候你想追踪一个正在运行的程序。如果你知道这个程序的进程号为 1337 (可以通过 `ps` 查询),则可以这样操作: ``` $ strace -p 1337 ...system call trace output... ``` 你可能需要 root 权限才能运行。 #### 使用 -f 追踪子进程 `strace` 默认只追踪一个进程。如果这个进程产生了一个子进程,你将会看到创建子进程的系统调用(一般是 `clone`),但是你看不到子进程内触发的任何调用。 如果你认为在子进程中存在错误,则需要使用 `-f` 参数启用子进程追踪功能。这样做的缺点是输出的内容会让人更加困惑。当追踪一个进程时,`strace` 显示的是单个调用事件流。当追踪多个进程的时候,你将会看到以 `<unfinished ...>` 开始的初始调用,接着是一系列针对其它线程的调用,最后才出现以 `<... foocall resumed>` 结束的初始调用。此外,你可以使用 `-ff` 参数将所有的调用分离到不同的文件中(查看 [strace 手册](https://linux.die.net/man/1/strace) 获取更多信息)。 #### 使用 -e 进行过滤 正如你所看到的,默认的追踪输出是所有的系统调用。你可以使用 `-e` 参数过滤你需要追踪的调用(查看 [strace 手册](https://linux.die.net/man/1/strace))。这样做的好处是运行过滤后的 `strace` 比起使用 `grep` 进行二次过滤要更快。老实说,我大部分时间都不会被打扰。 #### 并非所有的错误都是不好的 一个简单而常用的例子是一个程序在多个位置搜索文件,例如 shell 搜索哪个 `bin/` 目录包含可执行文件: ``` $ strace sh -c uname ... stat("/home/user/bin/uname", 0x7ffceb817820) = -1 ENOENT (No such file or directory) stat("/usr/local/bin/uname", 0x7ffceb817820) = -1 ENOENT (No such file or directory) stat("/usr/bin/uname", {st_mode=S_IFREG|0755, st_size=39584, ...}) = 0 ... ``` “错误信息之前的最后一次失败调用”这种启发式方法非常适合于查找错误。无论如何,自下而上地查找是有道理的。 #### C 编程指南非常有助于理解系统调用 标准 C 库函数调用不属于系统调用,但它们仅是系统调用之上的唯一一个薄层。所以如果你了解(甚至只是略知一二)如何使用 C 语言,那么阅读系统调用追踪信息就非常容易。例如,如果你在调试网络系统调用,你可以尝试略读 [Beej 经典的《网络编程指南》](https://beej.us/guide/bgnet/html/index.html)。 ### 一个更复杂的调试例子 就像我说的那样,简单的调试例子表现了我在大部分情况下如何使用 `strace`。然而,有时候需要一些更加细致的工作,所以这里有一个稍微复杂(且真实)的例子。 [bcron](https://untroubled.org/bcron/) 是一个任务调度器,它是经典 \*nix `cron` 守护程序的另一种实现。它已经被安装到一台服务器上,但是当有人尝试编辑作业时间表时,发生了以下情况: ``` # crontab -e -u logs bcrontab: Fatal: Could not create temporary file ``` 好的,现在 bcron 尝试写入一些文件,但是它失败了,也没有告诉我们原因。以下是 `strace` 的输出: ``` # strace -o /tmp/trace crontab -e -u logs bcrontab: Fatal: Could not create temporary file # cat /tmp/trace ... openat(AT_FDCWD, "bcrontab.14779.1573691864.847933", O_RDONLY) = 3 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f82049b4000 read(3, "#Ansible: logsagg\n20 14 * * * lo"..., 8192) = 150 read(3, "", 8192) = 0 munmap(0x7f82049b4000, 8192) = 0 close(3) = 0 socket(AF_UNIX, SOCK_STREAM, 0) = 3 connect(3, {sa_family=AF_UNIX, sun_path="/var/run/bcron-spool"}, 110) = 0 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f82049b4000 write(3, "156:Slogs\0#Ansible: logsagg\n20 1"..., 161) = 161 read(3, "32:ZCould not create temporary f"..., 8192) = 36 munmap(0x7f82049b4000, 8192) = 0 close(3) = 0 write(2, "bcrontab: Fatal: Could not creat"..., 49) = 49 unlink("bcrontab.14779.1573691864.847933") = 0 exit_group(111) = ? +++ exited with 111 +++ ``` 在程序结束之前有一个 `write` 的错误信息,但是这次有些不同。首先,在此之前没有任何相关的失败系统调用。其次,我们看到这个错误信息是由 `read` 从别的地方读取而来的。这看起来像是真正的错误发生在别的地方,而 `bcrontab` 只是在转播这些信息。 如果你查阅了 `man 2 read`,你将会看到 `read` 的第一个参数 (`3`) 是一个文件描述符,这是 \*nix 操作系统用于所有 IO 操作的句柄。你该如何知道文件描述符 3 代表什么?在这种情况下,你可以使用 `-y` 参数运行 `strace`(如上文所述),它将会在注释里告诉你文件描述符的具体指向,但是了解如何从上面这种输出中分析追踪结果是很有用的。 一个文件描述符可以来自于许多系统调用之一(这取决于它是用于控制台、网络套接字还是真实文件等的描述符),但不论如何,我们都可以搜索返回值为 `3` 的系统调用(例如,在 `strace` 的输出中查找 `=3`)。在这次 `strace` 中可以看到有两个这样的调用:最上面的 `openat` 以及中间的 `socket`。`openat` 打开一个文件,但是紧接着的 `close(3)` 表明其已经被关闭。(注意:文件描述符可以在打开并关闭后重复使用。)所以 `socket` 调用才是与此相关的(它是在 `read` 之前的最后一个),这告诉我们 `brcontab` 正在与一个网络套接字通信。在下一行,`connect` 表明文件描述符 3 是一个连接到 `/var/run/bcron-spool` 的 Unix 域套接字。 因此,我们需要弄清楚 Unix 套接字的另一侧是哪个进程在监听。有两个巧妙的技巧适用于在服务器部署中调试。一个是使用 `netstat` 或者较新的 `ss`。这两个命令都描述了当前系统中活跃的网络套接字,使用 `-l` 参数可以显示出处于监听状态的套接字,而使用 `-p` 参数可以得到正在使用该套接字的程序信息。(它们还有更多有用的选项,但是这两个已经足够完成工作了。) ``` # ss -pl | grep /var/run/bcron-spool u_str LISTEN 0 128 /var/run/bcron-spool 1466637 * 0 users:(("unixserver",pid=20629,fd=3)) ``` 这告诉我们 `/var/run/bcron-spool` 套接字的监听程序是 `unixserver` 这个命令,它的进程 ID 为 20629。(巧合的是,这个程序也使用文件描述符 `3` 去连接这个套接字。) 第二个常用的工具就是使用 `lsof` 查找相同的信息。它可以列出当前系统中打开的所有文件(或文件描述符)。或者,我们可以得到一个具体文件的信息: ``` # lsof /var/run/bcron-spool COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME unixserve 20629 cron 3u unix 0x000000005ac4bd83 0t0 1466637 /var/run/bcron-spool type=STREAM ``` 进程 20629 是一个常驻进程,所以我们可以使用 `strace -o /tmp/trace -p 20629` 去查看该进程的系统调用。如果我们在另一个终端尝试编辑 cron 的计划任务表,就可以在错误发生时捕获到以下信息: ``` accept(3, NULL, NULL) = 4 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7faa47c44810) = 21181 close(4) = 0 accept(3, NULL, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set) --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=21181, si_uid=998, si_status=0, si_utime=0, si_stime=0} --- wait4(0, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], WNOHANG|WSTOPPED, NULL) = 21181 wait4(0, 0x7ffe6bc36764, WNOHANG|WSTOPPED, NULL) = -1 ECHILD (No child processes) rt_sigaction(SIGCHLD, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, 8) = 0 rt_sigreturn({mask=[]}) = 43 accept(3, NULL, NULL) = 4 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7faa47c44810) = 21200 close(4) = 0 accept(3, NULL, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set) --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=21200, si_uid=998, si_status=111, si_utime=0, si_stime=0} --- wait4(0, [{WIFEXITED(s) && WEXITSTATUS(s) == 111}], WNOHANG|WSTOPPED, NULL) = 21200 wait4(0, 0x7ffe6bc36764, WNOHANG|WSTOPPED, NULL) = -1 ECHILD (No child processes) rt_sigaction(SIGCHLD, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, 8) = 0 rt_sigreturn({mask=[]}) = 43 accept(3, NULL, NULL ``` (最后一个 `accept` 调用没有在追踪期间完成。)不幸的是,这次追踪没有包含我们想要的错误信息。我们没有观察到 `bcrontan` 往套接字发送或接受的任何信息。然而,我们看到了很多进程管理操作(`clone`、`wait4`、`SIGCHLD`,等等)。这个进程产生了子进程,我们猜测真实的工作是由子进程完成的。如果我们想捕获子进程的追踪信息,就必须往 `strace` 追加 `-f` 参数。以下是我们最终使用 `strace -f -o /tmp/trace -p 20629` 找到的错误信息: ``` 21470 openat(AT_FDCWD, "tmp/spool.21470.1573692319.854640", O_RDWR|O_CREAT|O_EXCL, 0600) = -1 EACCES (Permission denied) 21470 write(1, "32:ZCould not create temporary f"..., 36) = 36 21470 write(2, "bcron-spool[21470]: Fatal: logs:"..., 84) = 84 21470 unlink("tmp/spool.21470.1573692319.854640") = -1 ENOENT (No such file or directory) 21470 exit_group(111) = ? 21470 +++ exited with 111 +++ ``` 现在我们知道了进程 ID 21470 在尝试创建文件 `tmp/spool.21470.1573692319.854640` (相对于当前的工作目录)时得到了一个没有权限的错误。如果我们知道当前的工作目录,就可以得到完整路径并能指出为什么该进程无法在此处创建临时文件。不幸的是,这个进程已经退出了,所以我们不能使用 `lsof -p 21470` 去找出当前的工作目录,但是我们可以往前追溯,查找进程 ID 21470 使用哪个系统调用改变了它的工作目录。这个系统调用是 `chdir`(可以在搜索引擎很轻松地找到)。以下是一直往前追溯到服务器进程 ID 20629 的结果: ``` 20629 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7faa47c44810) = 21470 ... 21470 execve("/usr/sbin/bcron-spool", ["bcron-spool"], 0x55d2460807e0 /* 27 vars */) = 0 ... 21470 chdir("/var/spool/cron") = 0 ... 21470 openat(AT_FDCWD, "tmp/spool.21470.1573692319.854640", O_RDWR|O_CREAT|O_EXCL, 0600) = -1 EACCES (Permission denied) 21470 write(1, "32:ZCould not create temporary f"..., 36) = 36 21470 write(2, "bcron-spool[21470]: Fatal: logs:"..., 84) = 84 21470 unlink("tmp/spool.21470.1573692319.854640") = -1 ENOENT (No such file or directory) 21470 exit_group(111) = ? 21470 +++ exited with 111 +++ ``` (如果你在这里迷糊了,你可能需要阅读 [我之前有关 \*nix 进程管理和 shell 的文章](https://theartofmachinery.com/2018/11/07/writing_a_nix_shell.html)) 现在 PID 为 20629 的服务器进程没有权限在 `/var/spool/cron/tmp/spool.21470.1573692319.854640` 创建文件。最可能的原因就是典型的 \*nix 文件系统权限设置。让我们检查一下: ``` # ls -ld /var/spool/cron/tmp/ drwxr-xr-x 2 root root 4096 Nov 6 05:33 /var/spool/cron/tmp/ # ps u -p 20629 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND cron 20629 0.0 0.0 2276 752 ? Ss Nov14 0:00 unixserver -U /var/run/bcron-spool -- bcron-spool ``` 这就是问题所在!这个服务进程以 `cron` 用户运行,但是只有 `root` 用户才有向 `/var/spool/cron/tmp/` 目录写入的权限。一个简单 `chown cron /var/spool/cron/tmp/` 命令就能让 `bcron` 正常工作。(如果不是这个问题,那么下一个最有可能的怀疑对象是诸如 SELinux 或者 AppArmor 之类的内核安全模块,因此我将会使用 `dmesg` 检查内核日志。) ### 总结 最初,系统调用追踪可能会让人不知所措,但是我希望我已经证明它们是调试一整套常见部署问题的快速方法。你可以设想一下尝试用单步调试器去调试多进程的 `bcron` 问题。 通过一连串的系统调用解决问题是需要练习的,但正如我说的那样,在大多数情况下,我只需要使用 `strace` 从下往上追踪并查找错误。不管怎样,`strace` 节省了我很多的调试时间。我希望这也对你有所帮助。 --- via: <https://theartofmachinery.com/2019/11/14/deployment_debugging_strace.html> 作者:[Simon Arneaud](https://theartofmachinery.com) 选题:[lujun9972](https://github.com/lujun9972) 译者:[hanwckf](https://github.com/hanwckf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Translations:[русский](https://habr.com/ru/company/southbridge/blog/478626/) Most of my paid work involves deploying software systems, which means I spend a lot of time trying to answer the following questions: - This software works on the original developer’s machine, so why doesn’t it work on mine? - This software worked on my machine yesterday, so why doesn’t it work today? That’s a kind of debugging, but it’s a different kind of debugging from normal software debugging. Normal debugging is usually about the logic of the code, but deployment debugging is usually about the interaction between the code and its environment. Even when the root cause is a logic bug, the fact that the software apparently worked on another machine means that the environment is usually involved somehow. So, instead of using normal debugging tools like `gdb` , I have another toolset for debugging deployments. My favourite tool for “Why isn’t this software working on this machine?” is `strace` . ## What is `strace` ? [ strace](https://strace.io/) is a tool for “system call tracing”. It’s primarily a Linux tool, but you can do the same kind of debugging tricks with tools for other systems (such as [DTrace](http://dtrace.org/blogs/about/)and [ktrace](https://man.openbsd.org/ktrace)). The basic usage is very simple. Just run it against a command and it dumps all the system calls (you’ll probably need to install `strace` first): ``` $ strace echo Hello ...Snip lots of stuff... write(1, "Hello\n", 6) = 6 close(1) = 0 close(2) = 0 exit_group(0) = ? +++ exited with 0 +++ ``` What are these system calls? They’re like the API for the operating system kernel. Once upon a time, software used to have direct access to the hardware it ran on. If it needed to display something on the screen, for example, it could twiddle with ports and/or memory-mapped registers for the video hardware. That got chaotic when multitasking computer systems became popular because different applications would “fight” over hardware, and bugs in one application could crash other applications, or even bring down the whole system. So CPUs started supporting different privilege modes (or “protection rings”). They let an operating system kernel run in the most privileged mode with full hardware access, while spawning less-privileged software applications that must ask the kernel to interact with the hardware for them using system calls. At the binary level, making a system call is a bit different from making a simple function call, but most programs use wrappers in a standard library. E.g. the POSIX C standard library contains a `write()` function call that contains all the architecture-dependent code for making the `write` system call. ![How system calls sit between applications and the kernel](/images/strace/system_calls.svg) In short, an application’s interaction with its environment (the computer system) is all done through system calls. So when software works on one machine but not another, looking at system call traces is a good way to find what’s wrong. More specifically, here are the typical things you can analyse using a system call trace: - Console input and output (IO) - Network IO - Filesystem access and file IO - Process/thread lifetime management - Raw memory management - Access to special device drivers ## When can `strace` be used? In theory, `strace` can be used with any userspace program because all userspace programs have to make system calls. It’s more effective with compiled, lower-level programs, but still works with high-level languages like Python if you can wade through the extra noise from the runtime environment and interpreter. `strace` shines with debugging software that works fine on one machine, but on another machine fails with a vague error message about files or permissions or failure to run some command or something. Unfortunately, it’s not so great with higher-level problems, like a certificate verification failure. They usually need a combination of `strace` , sometimes [ ltrace](https://linux.die.net/man/1/ltrace), and higher-level tooling (like the `openssl` command line tool for certificate debugging).The examples in this post are based on a standalone server, but system call tracing can often be done on more complicated deployment platforms, too. Just search for appropriate tooling. ## A simple debugging example Let’s say you’re trying to run an awesome server application called foo, but here’s what happens: ``` $ foo Error opening configuration file: No such file or directory ``` Obviously it’s not finding the configuration file that you’ve written. This can happen because package managers sometimes customise the expected locations of files when compiling an application, so following an installation guide for one distro leads to files in the wrong place on another distro. You could fix the problem in a few seconds if only the error message told you where the configuration file is expected to be, but it doesn’t. How can you find out? If you have access to the source code, you could read it and work it out. That’s a good fallback plan, but not the fastest solution. You also could use a stepping debugger like `gdb` to see what the program does, but it’s more efficient to use a tool that’s specifically designed to show the interaction with the environment: `strace` . The output of `strace` can be a bit overwhelming at first, but the good news is that you can ignore most of it. It often helps to use the `-o` switch to save the trace to a separate file: ``` $ strace -o /tmp/trace foo Error opening configuration file: No such file or directory $ cat /tmp/trace execve("foo", ["foo"], 0x7ffce98dc010 /* 16 vars */) = 0 brk(NULL) = 0x56363b3fb000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=25186, ...}) = 0 mmap(NULL, 25186, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f2f12cf1000 close(3) = 0 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260A\2\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=1824496, ...}) = 0 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2f12cef000 mmap(NULL, 1837056, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f2f12b2e000 mprotect(0x7f2f12b50000, 1658880, PROT_NONE) = 0 mmap(0x7f2f12b50000, 1343488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22000) = 0x7f2f12b50000 mmap(0x7f2f12c98000, 311296, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a000) = 0x7f2f12c98000 mmap(0x7f2f12ce5000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b6000) = 0x7f2f12ce5000 mmap(0x7f2f12ceb000, 14336, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f2f12ceb000 close(3) = 0 arch_prctl(ARCH_SET_FS, 0x7f2f12cf0500) = 0 mprotect(0x7f2f12ce5000, 16384, PROT_READ) = 0 mprotect(0x56363b08b000, 4096, PROT_READ) = 0 mprotect(0x7f2f12d1f000, 4096, PROT_READ) = 0 munmap(0x7f2f12cf1000, 25186) = 0 openat(AT_FDCWD, "/etc/foo/config.json", O_RDONLY) = -1 ENOENT (No such file or directory) dup(2) = 3 fcntl(3, F_GETFL) = 0x2 (flags O_RDWR) brk(NULL) = 0x56363b3fb000 brk(0x56363b41c000) = 0x56363b41c000 fstat(3, {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0x8), ...}) = 0 write(3, "Error opening configuration file"..., 60) = 60 close(3) = 0 exit_group(1) = ? +++ exited with 1 +++ ``` The first page or so of `strace` output is typically low-level process startup. (You can see a lot of `mmap` , `mprotect` , `brk` calls for things like allocating raw memory and mapping dynamic libraries.) Actually, when debugging an error, `strace` output is best read from the bottom up. You can see the `write` call that outputs the error message at the end. If you work up, the first failing system call is the `openat` call that fails with `ENOENT` (“No such file or directory”) trying to open `/etc/foo/config.json` . And now we know where the configuration file is supposed to be. That’s a simple example, but I’d say at least 90% of the time I use `strace` , I’m not doing anything more complicated. Here’s the complete debugging formula step-by-step: - Get frustrated by a vague system-y error message from a program - Run the program again with `strace` - Find the error message in the trace - Work upwards to find the first failing system call There’s a very good chance the system call in step 4 shows you what went wrong. ## Some tips Before walking through a more complicated example, here are some useful tips for using `strace` effectively: `man` is your friend On many *nix systems, you can get a list of all kernel system calls by running `man syscalls` . You’ll see things like `brk(2)` , which means you can get more information by running `man 2 brk` . One little gotcha: `man 2 fork` shows me the man page for the `fork()` wrapper in GNU `libc` , which is actually now implemented using the `clone` system call instead. The semantics of `fork` are the same, but if I write a program using `fork()` and `strace` it, I won’t find any `fork` calls in the trace, just `clone` calls. Gotchas like that are only confusing if you’re comparing source code to `strace` output. ### Use `-o` to save output to a file `strace` can generate a lot of output so it’s often helpful to store the trace in a separate file (as in the example above). It also avoids mixing up program output with `strace` output in the console. ### Use `-s` to see more argument data You might have noticed that the second part of the error message doesn’t appear in the example trace above. That’s because `strace` only shows the first 32 bytes of string arguments by default. If you need to capture more, add something like `-s 128` to the `strace` invocation. `-y` makes it easier to track files/sockets/etc “Everything is a file” means *nix systems do all IO using file descriptors, whether it’s to an actual file or over networks or through interprocess pipes. That’s convenient for programming, but makes it harder to follow what’s really going on when you see generic `read` and `write` in the system call trace. Adding the `-y` switch makes `strace` annotate every file descriptor in the output with a note about what it points to. ### Attach to an already-running process with `-p` As we’ll see in the example later, sometimes you want to trace a program that’s already running. If you know it’s running as process 1337 (say, by looking at the output of `ps` ), you can trace it like this: ``` $ strace -p 1337 ...system call trace output... ``` You probably need root. ### Use `-f` to follow child processes By default, `strace` only traces the one process. If that process spawns a child process, you’ll see the system call for spawning the process (normally `clone` nowadays), but not any of the calls made by the child process. If you think the bug is in a child process, you’ll need to use the `-f` switch to enable tracing it. A downside is that the output can be more confusing. When tracing one process and one thread, `strace` can show you a single stream of call events. When tracing multiple processes, you might see the start of a call cut off with `<unfinished ...>` , then a bunch of calls for other threads of execution, before seeing the end of the original call with `<... foocall resumed>` . Alternatively, you can separate all the traces into different files by using the `-ff` switch as well (see [the strace manual](https://linux.die.net/man/1/strace) for details). ### You can filter the trace with `-e` As you’ve seen, the default trace output is a firehose of all system calls. You can filter which calls get traced using the `-e` flag (see [the strace manual](https://linux.die.net/man/1/strace)). The main advantage is that it’s faster to run the program under a filtered `strace` than to trace everything and `grep` the results later. Honestly, I don’t bother most of the time.### Not all errors are bad A simple and common example is a program searching for a file in multiple places, like a shell searching for which `bin/` directory has an executable: ``` $ strace sh -c uname ... stat("/home/user/bin/uname", 0x7ffceb817820) = -1 ENOENT (No such file or directory) stat("/usr/local/bin/uname", 0x7ffceb817820) = -1 ENOENT (No such file or directory) stat("/usr/bin/uname", {st_mode=S_IFREG|0755, st_size=39584, ...}) = 0 ... ``` The “last failed call before the error message” heuristic is pretty good at finding relevent errors. In any case, working from the bottom up makes sense. ### C programming guides are good for understanding system calls Standard C library calls aren’t system calls, but they’re only thin layers on top. So if you understand (even just roughly) how to do something in C, it’s easier to read a system call trace. For example, if you’re having trouble debugging networking system calls, you could try skimming through [Beej’s classic Guide to Network Programming](https://beej.us/guide/bgnet/html/index.html). ## A more complicated debugging example As I said, that simple debugging example is representative of most of my `strace` usage. However, sometimes a little more detective work is required, so here’s a slightly more complicated (and real) example. [ bcron](https://untroubled.org/bcron/) is a job scheduler that’s yet another implementation of the classic *nix `cron` daemon. It’s been installed on a server, but here’s what happens when someone tries to edit a job schedule:``` # crontab -e -u logs bcrontab: Fatal: Could not create temporary file ``` Okay, so bcron tried to write some file, but it couldn’t, and isn’t telling us why. This is a debugging job for `strace` : ``` # strace -o /tmp/trace crontab -e -u logs bcrontab: Fatal: Could not create temporary file # cat /tmp/trace ... openat(AT_FDCWD, "bcrontab.14779.1573691864.847933", O_RDONLY) = 3 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f82049b4000 read(3, "#Ansible: logsagg\n20 14 * * * lo"..., 8192) = 150 read(3, "", 8192) = 0 munmap(0x7f82049b4000, 8192) = 0 close(3) = 0 socket(AF_UNIX, SOCK_STREAM, 0) = 3 connect(3, {sa_family=AF_UNIX, sun_path="/var/run/bcron-spool"}, 110) = 0 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f82049b4000 write(3, "156:Slogs\0#Ansible: logsagg\n20 1"..., 161) = 161 read(3, "32:ZCould not create temporary f"..., 8192) = 36 munmap(0x7f82049b4000, 8192) = 0 close(3) = 0 write(2, "bcrontab: Fatal: Could not creat"..., 49) = 49 unlink("bcrontab.14779.1573691864.847933") = 0 exit_group(111) = ? +++ exited with 111 +++ ``` There’s the error message `write` near the end, but a couple of things are different this time. First, there’s no relevant system call error that happens before it. Second, we see that the error message has just been `read` from somewhere else. It looks like the real problem is happening somewhere else, and `bcrontab` is just replaying the message. If you look at `man 2 read` , you’ll see that the first argument (the 3) is a file descriptor, which is what *nix uses for all IO handles. How do you know what file descriptor 3 represents? In this specific case, you could run `strace` with the `-y` switch (as explained above) and it would tell you automatically, but it’s useful to know how to read and analyse traces to figure things like this out. A file descriptor can come from one of many system calls (depending on whether it’s a descriptor for the console, a network socket, an actual file, or something else), but in any case we can search for calls returning 3 (i.e., search for “= 3” in the trace). There are two in this trace: the `openat` at the top, and the `socket` in the middle. `openat` opens a file, but the `close(3)` afterwards shows that it gets closed again. (Gotcha: file descriptors can be reused as they’re opened and closed.) The `socket` call is the relevant one (it’s the last one before the `read` ), which tells us `bcrontab` is talking to something over a network socket. The next line, `connect` shows file descriptor 3 being configured as a Unix domain socket connection to `/var/run/bcron-spool` . So now we need to figure out what’s listening on the other side of the Unix socket. There are a couple of neat tricks for that, both useful for debugging server deployments. One is to use `netstat` or the newer `ss` (“socket status”). Both commands describe active network sockets on the system, and take the `-l` switch for describing listening (server) sockets, and the `-p` switch to get information about what program is using the socket. (There are many more useful options, but those two are enough to get this job done.) ``` # ss -pl | grep /var/run/bcron-spool u_str LISTEN 0 128 /var/run/bcron-spool 1466637 * 0 users:(("unixserver",pid=20629,fd=3)) ``` That tells us that the listener is a command `unixserver` running as process ID 20629. (It’s a coincidence that it’s also using file descriptor 3 for the socket.) The second really useful tool for finding the same information is `lsof` . It can list all open files (or file descriptors) on the system. Alternatively, we can get information about a specific file: ``` # lsof /var/run/bcron-spool COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME unixserve 20629 cron 3u unix 0x000000005ac4bd83 0t0 1466637 /var/run/bcron-spool type=STREAM ``` Process 20629 is a long-running server, so we can attach `strace` to it using something like `strace -o /tmp/trace -p 20629` . If we then try to edit the cron schedule in another terminal, we can capture a trace while the error is happening. Here’s the result: ``` accept(3, NULL, NULL) = 4 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7faa47c44810) = 21181 close(4) = 0 accept(3, NULL, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set) --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=21181, si_uid=998, si_status=0, si_utime=0, si_stime=0} --- wait4(0, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], WNOHANG|WSTOPPED, NULL) = 21181 wait4(0, 0x7ffe6bc36764, WNOHANG|WSTOPPED, NULL) = -1 ECHILD (No child processes) rt_sigaction(SIGCHLD, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, 8) = 0 rt_sigreturn({mask=[]}) = 43 accept(3, NULL, NULL) = 4 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7faa47c44810) = 21200 close(4) = 0 accept(3, NULL, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set) --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=21200, si_uid=998, si_status=111, si_utime=0, si_stime=0} --- wait4(0, [{WIFEXITED(s) && WEXITSTATUS(s) == 111}], WNOHANG|WSTOPPED, NULL) = 21200 wait4(0, 0x7ffe6bc36764, WNOHANG|WSTOPPED, NULL) = -1 ECHILD (No child processes) rt_sigaction(SIGCHLD, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, {sa_handler=0x55d244bdb690, sa_mask=[CHLD], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7faa47ab9840}, 8) = 0 rt_sigreturn({mask=[]}) = 43 accept(3, NULL, NULL ``` (The last `accept` doesn’t complete during the trace period.) Unfortunately, once again, this trace doesn’t contain the error we’re after. We don’t see any of the messages that we saw `bcrontab` sending to and receiving from the socket. Instead, we see a lot of process management (`clone` , `wait4` , `SIGCHLD` , etc.). This process is spawning a child process, which we can guess is doing the real work. If we want to catch a trace of that, we have to add `-f` to the `strace` invocation. Here’s what we find if we search for the error message after getting a new trace with ``` strace -f -o /tmp/trace -p 20629 ``` : ``` 21470 openat(AT_FDCWD, "tmp/spool.21470.1573692319.854640", O_RDWR|O_CREAT|O_EXCL, 0600) = -1 EACCES (Permission denied) 21470 write(1, "32:ZCould not create temporary f"..., 36) = 36 21470 write(2, "bcron-spool[21470]: Fatal: logs:"..., 84) = 84 21470 unlink("tmp/spool.21470.1573692319.854640") = -1 ENOENT (No such file or directory) 21470 exit_group(111) = ? 21470 +++ exited with 111 +++ ``` Now we’re getting somewhere. Process ID 21470 is getting a permission denied error trying to create a file at the path `tmp/spool.21470.1573692319.854640` (relative to the current working directory). If we just knew the current working directory, we would know the full path and could figure out why the process can’t create create its temporary file there. Unfortunately, the process has already exited, so we can’t just use `lsof -p 21470` to find out the current directory, but we can work backwards looking for PID 21470 system calls that change directory. (If there aren’t any, PID 21470 must have inherited it from its parent, and we can ``` lsof -p ``` that.) That system call is `chdir` (which is easy to find out using today’s web search engines). Here’s the result of working backwards through the trace, all the way to the server PID 20629: ``` 20629 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7faa47c44810) = 21470 ... 21470 execve("/usr/sbin/bcron-spool", ["bcron-spool"], 0x55d2460807e0 /* 27 vars */) = 0 ... 21470 chdir("/var/spool/cron") = 0 ... 21470 openat(AT_FDCWD, "tmp/spool.21470.1573692319.854640", O_RDWR|O_CREAT|O_EXCL, 0600) = -1 EACCES (Permission denied) 21470 write(1, "32:ZCould not create temporary f"..., 36) = 36 21470 write(2, "bcron-spool[21470]: Fatal: logs:"..., 84) = 84 21470 unlink("tmp/spool.21470.1573692319.854640") = -1 ENOENT (No such file or directory) 21470 exit_group(111) = ? 21470 +++ exited with 111 +++ ``` (If you’re getting lost here, you might want to read [my previous post about *nix process management and shells](/2018/11/07/writing_a_nix_shell.html).) Okay, so the server PID 20629 doesn’t have permission to create a file at `/var/spool/cron/tmp/spool.21470.1573692319.854640` . The most likely reason would be classic *nix filesystem permission settings. Let’s check: ``` # ls -ld /var/spool/cron/tmp/ drwxr-xr-x 2 root root 4096 Nov 6 05:33 /var/spool/cron/tmp/ # ps u -p 20629 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND cron 20629 0.0 0.0 2276 752 ? Ss Nov14 0:00 unixserver -U /var/run/bcron-spool -- bcron-spool ``` There’s the problem! The server is running as user `cron` , but only `root` has permissions to write to that `/var/spool/cron/tmp/` directory. A simple `chown cron /var/spool/cron/tmp/` makes `bcron` work properly. (If that weren’t the problem, the next most likely suspect would be a kernel security module like SELinux or AppArmor, so I’d check the kernel logs with `dmesg` .) ## Summary System call traces can be overwhelming at first, but I hope I’ve shown that they’re a fast way to debug a whole class of common deployment problems. Imagine trying to debug that multi-process `bcron` problem using a stepping debugger. Working back through a chain of system calls takes practice, but as I said, most of the time I use `strace` I just get a trace and look for errors, working from the bottom up. In any case, `strace` has saved me hours and hours of debugging time. I hope it’s useful for you, too.
11,669
在 Linux 上安全传输文件的 14 SCP 命令示例
https://www.linuxtechi.com/scp-command-examples-in-linux/
2019-12-13T10:02:00
[ "scp" ]
https://linux.cn/article-11669-1.html
![](/data/attachment/album/201912/13/100239f31is1ios31vvoo3.jpg) SCP(<ruby> 安全复制 <rt> Secure Copy </rt></ruby>)是 Linux 和 Unix 之类的系统中的命令行工具,用于通过网络安全地跨系统传输文件和目录。当我们使用 `scp` 命令将文件和目录从本地系统复制到远程系统时,则在后端与远程系统建立了 ssh 连接。换句话说,我们可以说 `scp` 在后端使用了相同的 SSH 安全机制,它需要密码或密钥进行身份验证。 在本教程中,我们将讨论 14 个有用的 Linux `scp` 命令示例。 `scp` 命令语法: ``` # scp <选项> <文件或目录> 用户名@目标主机:/<文件夹> # scp <选项> 用户名@目标主机:/文件 <本地文件夹> ``` `scp` 命令的第一个语法演示了如何将文件或目录从本地系统复制到特定文件夹下的目标主机。 `scp` 命令的第二种语法演示了如何将目标主机中的文件复制到本地系统中。 下面列出了 `scp` 命令中使用最广泛的一些选项, * `-C` 启用压缩 * `-i` 指定识别文件或私钥 * `-l` 复制时限制带宽 * `-P` 指定目标主机的 ssh 端口号 * `-p` 复制时保留文件的权限、模式和访问时间 * `-q` 禁止 SSH 警告消息 * `-r` 递归复制文件和目录 * `-v` 详细输出 现在让我们跳入示例! ### 示例:1)使用 scp 将文件从本地系统复制到远程系统 假设我们要使用 `scp` 命令将 jdk 的 rpm 软件包从本地 Linux 系统复制到远程系统(172.20.10.8),请使用以下命令, ``` [root@linuxtechi ~]$ scp jdk-linux-x64_bin.rpm root@linuxtechi:/opt root@linuxtechi's password: jdk-linux-x64_bin.rpm 100% 10MB 27.1MB/s 00:00 [root@linuxtechi ~]$ ``` 上面的命令会将 jdk 的 rpm 软件包文件复制到 `/opt` 文件夹下的远程系统。 ### 示例:2)使用 scp 将文件从远程系统复制到本地系统 假设我们想将文件从远程系统复制到本地系统下的 `/tmp` 文件夹,执行以下 `scp` 命令, ``` [root@linuxtechi ~]$ scp root@linuxtechi:/root/Technical-Doc-RHS.odt /tmp root@linuxtechi's password: Technical-Doc-RHS.odt 100% 1109KB 31.8MB/s 00:00 [root@linuxtechi ~]$ ls -l /tmp/Technical-Doc-RHS.odt -rwx------. 1 pkumar pkumar 1135521 Oct 19 11:12 /tmp/Technical-Doc-RHS.odt [root@linuxtechi ~]$ ``` ### 示例:3)使用 scp 传输文件时的详细输出(-v) 在 `scp` 命令中,我们可以使用 `-v` 选项启用详细输出。使用详细输出,我们可以轻松地发现后台确切发生了什么。这对于调试连接、认证和配置等问题非常有用。 ``` root@linuxtechi ~]$ scp -v jdk-linux-x64_bin.rpm root@linuxtechi:/opt Executing: program /usr/bin/ssh host 172.20.10.8, user root, command scp -v -t /opt OpenSSH_7.8p1, OpenSSL 1.1.1 FIPS 11 Sep 2018 debug1: Reading configuration data /etc/ssh/ssh_config debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config debug1: /etc/ssh/ssh_config.d/05-redhat.conf line 8: Applying options for * debug1: Connecting to 172.20.10.8 [172.20.10.8] port 22. debug1: Connection established. ………… debug1: Next authentication method: password root@linuxtechi's password: ``` ### 示例:4)将多个文件传输到远程系统 可以使用 `scp` 命令一次性将多个文件复制/传输到远程系统,在 `scp` 命令中指定多个文件,并用空格隔开,示例如下所示 ``` [root@linuxtechi ~]$ scp install.txt index.html jdk-linux-x64_bin.rpm root@linuxtechi:/mnt root@linuxtechi's password: install.txt 100% 0 0.0KB/s 00:00 index.html 100% 85KB 7.2MB/s 00:00 jdk-linux-x64_bin.rpm 100% 10MB 25.3MB/s 00:00 [root@linuxtechi ~]$ ``` ### 示例:5)在两个远程主机之间传输文件 使用 `scp` 命令,我们可以在两个远程主机之间复制文件和目录,假设我们有一个可以连接到两个远程 Linux 系统的本地 Linux 系统,因此从我的本地 Linux 系统中,我可以使用 `scp` 命令在这两个系统之间复制文件, 命令语法: ``` # scp 用户名@远程主机1:/<要传输的文件> 用户名@远程主机2:/<文件夹> ``` 示例如下: ``` # scp root@linuxtechi:~/backup-Oct.zip root@linuxtechi:/tmp # ssh root@linuxtechi "ls -l /tmp/backup-Oct.zip" -rwx------. 1 root root 747438080 Oct 19 12:02 /tmp/backup-Oct.zip ``` ### 示例:6)递归复制文件和目录(-r) 在 `scp` 命令中使用 `-r` 选项将整个目录从一个系统递归地复制到另一个系统,示例如下所示: ``` [root@linuxtechi ~]$ scp -r Downloads root@linuxtechi:/opt ``` 使用以下命令验证 `Downloads` 文件夹是否已复制到远程系统, ``` [root@linuxtechi ~]$ ssh root@linuxtechi "ls -ld /opt/Downloads" drwxr-xr-x. 2 root root 75 Oct 19 12:10 /opt/Downloads [root@linuxtechi ~]$ ``` ### 示例:7)通过启用压缩来提高传输速度(-C) 在 `scp` 命令中,我们可以通过使用 `-C` 选项启用压缩来提高传输速度,它将自动在源主机上启用压缩并在目标主机上解压缩。 ``` root@linuxtechi ~]$ scp -r -C Downloads root@linuxtechi:/mnt ``` 在以上示例中,我们正在启用压缩的情况下传输下载目录。 ### 示例:8)复制时限制带宽(-l) 在 `scp` 命令中使用 `-l` 选项设置复制时对带宽使用的限制。带宽以 Kbit/s 为单位指定,示例如下所示: ``` [root@linuxtechi ~]$ scp -l 500 jdk-linux-x64_bin.rpm root@linuxtechi:/var ``` ### 示例:9)在 scp 时指定其他 ssh 端口(-P) 在某些情况下,目标主机上的 ssh 端口会更改,因此在使用 `scp` 命令时,我们可以使用 `-P` 选项指定 ssh 端口号。 ``` [root@linuxtechi ~]$ scp -P 2022 jdk-linux-x64_bin.rpm root@linuxtechi:/var ``` 在上面的示例中,远程主机的 ssh 端口为 “2022”。 ### 示例:10)复制时保留文件的权限、模式和访问时间(-p) 从源复制到目标时,在 `scp` 命令中使用 `-p` 选项保留权限、访问时间和模式。 ``` [root@linuxtechi ~]$ scp -p jdk-linux-x64_bin.rpm root@linuxtechi:/var/tmp jdk-linux-x64_bin.rpm 100% 10MB 13.5MB/s 00:00 [root@linuxtechi ~]$ ``` ### 示例:11)在 scp 中以安静模式传输文件(-q) 在 `scp` 命令中使用 `-q` 选项可禁止显示 ssh 的传输进度、警告和诊断消息。示例如下所示: ``` [root@linuxtechi ~]$ scp -q -r Downloads root@linuxtechi:/var/tmp [root@linuxtechi ~]$ ``` ### 示例:12)在传输时使用 scp 中的识别文件(-i) 在大多数 Linux 环境中,首选基于密钥的身份验证。在 `scp` 命令中,我们使用 `-i` 选项指定识别文件(私钥文件),示例如下所示: ``` [root@linuxtechi ~]$ scp -i my_key.pem -r Downloads root@linuxtechi:/root ``` 在上面的示例中,`my_key.pem` 是识别文件或私钥文件。 ### 示例:13)在 scp 中使用其他 ssh\_config 文件(-F) 在某些情况下,你使用不同的网络连接到 Linux 系统,可能某些网络位于代理服务器后面,因此在这种情况下,我们必须具有不同的 `ssh_config` 文件。 通过 `-F` 选项在 `scp` 命令中指定了不同的 `ssh_config` 文件,示例如下所示: ``` [root@linuxtechi ~]$ scp -F /home/pkumar/new_ssh_config -r Downloads root@linuxtechi:/root root@linuxtechi's password: jdk-linux-x64_bin.rpm 100% 10MB 16.6MB/s 00:00 backup-Oct.zip 100% 713MB 41.9MB/s 00:17 index.html 100% 85KB 6.6MB/s 00:00 [root@linuxtechi ~]$ ``` ### 示例:14)在 scp 命令中使用其他加密方式(-c) 默认情况下,`scp` 使用 AES-128 加密方式来加密文件。如果你想在 `scp` 命令中使用其他加密方式,请使用 `-c` 选项,后接加密方式名称。 假设我们要在用 `scp` 命令传输文件时使用 3des-cbc 加密方式,请运行以下 `scp` 命令: ``` [root@linuxtechi ~]# scp -c 3des-cbc -r Downloads root@linuxtechi:/root ``` 使用以下命令列出 `ssh` 和 `scp` 支持的加密方式: ``` [root@linuxtechi ~]# ssh -Q cipher localhost | paste -d , -s - 3des-cbc,aes128-cbc,aes192-cbc,aes256-cbc,root@linuxtechi,aes128-ctr,aes192-ctr,aes256-ctr,root@linuxtechi,root@linuxtechi,root@linuxtechi [root@linuxtechi ~]# ``` 以上就是本教程的全部内容,要获取有关 `scp` 命令的更多详细信息,请参考其手册页。请在下面的评论部分中分享你的反馈和评论。 --- via: <https://www.linuxtechi.com/scp-command-examples-in-linux/> 作者:[Pradeep Kumar](https://www.linuxtechi.com/author/pradeep/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
In this blog post, we will learn scp command in Linux with 14 different examples. SCP is a command line tool in Linux and UNIX distributions, which is used to copy files and directories across the systems securely over the network. SCP stands for secure copy as it copies files using ssh protocol. When we scp command is invoked then it makes ssh connection to remote system and uses the same SSH security mechanism in the backend, it needs either password or keys for authentication. #### SCP Command Syntax SCP syntax is straightforward and mirrors that of the traditional [cp command](https://www.linuxtechi.com/cp-command-examples-linux-beginners/): Copy from Local to Remote Host # scp <options> <files_or_directories> user@target_host:/<folder> Copy from Remote Host to local system # scp <options> user@target_host:/files <folder_local_system> Options - -C Enable Compression - -i identity File or private key - -l limit the bandwidth while copying - -P ssh port number of target host - -p Preserves permissions, modes and access time of files while copying - -q Suppress warning message of SSH - -r Copy files and directories recursively - -v verbose output Let’s delve into 14 SCP command examples that will empower you to securely copy files in Linux. ## 1) Copy File From Local to Remote System $ scp /path/to/local/file username@remote_server:/path/to/destination/ Let’s assume we want to copy jdk rpm package from our local Linux system to remote system (172.20.10.8) using scp command, run $ scp jdk-linux-x64_bin.rpm[[email protected]]:/opt[[email protected]]'s password: jdk-linux-x64_bin.rpm 100% 10MB 27.1MB/s 00:00 $ Above command will copy jdk rpm package file to remote system under /opt folder. ## 2) Copy File from Remote to Local System Suppose we want to copy a file from remote system to our local system under the /tmp folder, execute the following, $ scp[[email protected]]:/root/Technical-Doc-RHS.odt /tmp[[email protected]]'s password: Technical-Doc-RHS.odt 100% 1109KB 31.8MB/s 00:00 $ ls -l /tmp/Technical-Doc-RHS.odt -rwx------. 1 pkumar pkumar 1135521 Oct 19 11:12 /tmp/Technical-Doc-RHS.odt $ ## 3) Verbose Output While Copying Files We can enable verbose output with -v option while copying files via scp command. Using verbose output we can easily find what exactly is happening in the background. This becomes very useful in debugging connection, authentication and configuration problems. $ scp -v jdk-linux-x64_bin.rpm[[email protected]]:/opt Executing: program /usr/bin/ssh host 172.20.10.8, user root, command scp -v -t /opt OpenSSH_7.8p1, OpenSSL 1.1.1 FIPS 11 Sep 2018 debug1: Reading configuration data /etc/ssh/ssh_config debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config debug1: /etc/ssh/ssh_config.d/05-redhat.conf line 8: Applying options for * debug1: Connecting to 172.20.10.8 [172.20.10.8] port 22. debug1: Connection established. ………… debug1: Next authentication method: password[[email protected]]'s password: ## 4) Copy Multiple Files to Remote System Multiple files can be copied to remote system using scp command in one go. Specify the multiple files separated by space, example is shown below $ scp install.txt index.html jdk-linux-x64_bin.rpm[[email protected]]:/mnt[[email protected]]'s password: install.txt 100% 0 0.0KB/s 00:00 index.html 100% 85KB 7.2MB/s 00:00 jdk-linux-x64_bin.rpm 100% 10MB 25.3MB/s 00:00 [pkumar@linuxtechi ~]$ ## 5) Copy Files Across Two Remote Systems Using scp command we can copy files and directories between two remote hosts, let’s suppose we have a local Linux system which can connect to two remote Linux systems, so from my local system I can use scp command to copy files across these two systems, Syntax: $scp user@remote_hosts1:/<files_to_transfer> user@remote_host2:/<folder> Example is shown below, $ scp[[email protected]]:~/backup-Oct.zip[[email protected]]:/tmp $ ssh[[email protected]]"ls -l /tmp/backup-Oct.zip" -rwx------. 1 root root 747438080 Oct 19 12:02 /tmp/backup-Oct.zip ## 6) Copy Files and Directories Recursively Use -r option in scp command to recursively copy the entire directory from one system to another, example is shown below, $ scp -r Downloads[[email protected]]:/opt Use below command to verify whether Download folder is copied to remote system or not, $ ssh[[email protected]]"ls -ld /opt/Downloads" drwxr-xr-x. 2 root root 75 Oct 19 12:10 /opt/Downloads $ ## 7) Increase Copy Speed by Enabling Compression We can increase the transfer or copy speed by enabling the compression using -C option, it will automatically enable compression at source and decompress at destination. $ scp -r -C Downloads[[email protected]]:/mnt In the above example we are transferring the Download directory with compression enabled. ## 8) Limit Bandwidth While Copying Use ‘-l’ option in scp command to put limit on bandwidth usage while copying. Bandwidth is specified in Kbit/s, example is shown below, $ scp -l 500 jdk-linux-x64_bin.rpm[[email protected]]:/var ## 9) Use Different SSH Port in SCP There can be some scenario where ssh port is changed on destination host, so while using scp command we can specify the ssh port number using ‘-P’ option. $ scp -P 2022 jdk-linux-x64_bin.rpm[[email protected]]:/var In above example, ssh port for remote host is “2022” ## 10) Preserves Permissions, Modes and Access Time While Copying Use ‘-p’ option in scp command to preserve permissions, access time and modes while copying from source to destination $ scp -p jdk-linux-x64_bin.rpm[[email protected]]:/var/tmp jdk-linux-x64_bin.rpm 100% 10MB 13.5MB/s 00:00 $ ## 11) Copying Files in Quiet Mode Use ‘-q’ option in scp command to suppress transfer progress, warning and diagnostic messages of ssh. Example is shown below, $ scp -q -r Downloads[[email protected]]:/var/tmp ## 12) Use Identify File in scp while Copying In most of the Linux environments, keys-based authentication is preferred. In scp command we can specify the identify file or private key file using ‘-i’ option, example is shown below, $ scp -i my_key.pem -r Downloads[[email protected]]:/root In above example, “my_key.pem” is the identity file or private key file. ## 13) Use Different ssh_config File in scp There are some scenarios where you use different networks to connect to Linux systems, may be some network is behind proxy servers, so in that case we must have different **ssh_config** file. Different ssh_config file in scp command is specified via ‘-F’ option, example is shown below $ scp -F /home/pkumar/new_ssh_config -r Downloads \[[email protected]]:/root[[email protected]]'s password: jdk-linux-x64_bin.rpm 100% 10MB 16.6MB/s 00:00 backup-Oct.zip 100% 713MB 41.9MB/s 00:17 index.html 100% 85KB 6.6MB/s 00:00 $ ## 14) Use Different Cipher in scp Command By default, scp uses ‘AES-128’ cipher to encrypt the files. If you want to use another cipher in scp command then use ‘-c’ option followed by cipher name, Let’s suppose we want to use ‘3des-cbc’ cipher in scp command while transferring the files, run the following scp command $ scp -c 3des-cbc -r Downloads[[email protected]]:/root Use the below command to list ssh and scp ciphers, $ ssh -Q cipher localhost | paste -d , -s - 3des-cbc,aes128-cbc,aes192-cbc,aes256-cbc,[[email protected]],\ aes128-ctr,aes192-ctr,aes256-ctr,[[email protected]],[[email protected]],\[[email protected]]$ That’s all from this post, to get more details about scp command, kindly refer its man page. Feel free to share your feedback and comments in below comments section. Also Read : [How to Setup Passwordless SSH Login in Linux with Keys](https://www.linuxtechi.com/passwordless-ssh-login-keys-linux/)
11,670
Pekwm:一个轻量级的 Linux 桌面
https://opensource.com/article/19/12/pekwm-linux-desktop
2019-12-13T13:37:11
[ "桌面环境" ]
https://linux.cn/article-11670-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。如果你是一个觉得传统桌面会妨碍你的极简主义者,那么试试 Pekwm Linux 桌面。 > > > ![](/data/attachment/album/201912/13/133626l5t2z2awjstu9zbe.png) 假设你想要一个轻量级桌面环境,它只需要能在屏幕上显示图形、四处移动窗口,而别无杂物。你会发现传统桌面的通知、任务栏和系统托盘会妨碍你的工作。你想主要通过终端工作,但也希望运行图形应用。如果听起来像是你的想法,那么 [Pekwm](http://www.pekwm.org/) 可能是你一直在寻找的东西。 Pekwm 的灵感大概来自于 Window Maker 和 Fluxbox 等。它提供了一个应用菜单、窗口装饰、而不是一大堆其他东西。它非常适合极简主义者,即那些希望节省资源的用户和喜欢在终端工作的用户。 从发行版仓库安装 Pekwm。安装后,请先退出当前桌面会话,以便可以登录到新桌面。默认情况下,会话管理器(KDM、GDM、LightDM 或 XDM,具体取决于你的设置)将继续登录到以前的桌面,因此需要在登录之前修改它。 在 GDM 中覆盖之前的桌面: ![Selecting your desktop in GDM](/data/attachment/album/201912/13/133713utjff3rff2kmqvqq.jpg "Selecting your desktop in GDM") 在 KDM 中: ![Selecting your desktop in KDM](/data/attachment/album/201912/13/133714v5jj8omzrzhqhmkj.jpg "Selecting your desktop in KDM") 第一次登录 Pekwm 时,你可能会看到黑屏。可能难以置信,但这是正常的。你看到的是一个空白桌面,没有背景壁纸。你可以使用 `feh` 命令设置壁纸(你可能需要从仓库中安装它)。此命令有几个用于设置背景的选项,包括 `--bg-fill` 用壁纸填充屏幕,`--bg-scale` 缩放到合适大小,等等。 ``` $ feh --bg-fill ~/Pictures/wallpapers/mybackground.jpg ``` ### 应用菜单 默认情况下,Pekwm 自动生成一个菜单,可在桌面上的任意位置右键单击,从而可让你运行应用。此菜单还提供一些首选项设置,例如选择主题和注销 Pekwm 会话。 ![Pekwm running on Fedora](/data/attachment/album/201912/13/133721tdbjjj2bjlylbgv2.jpg "Pekwm running on Fedora") ### 配置 Pekwm 主要通过保存在 `$HOME/.pekwm` 下的文本配置文件来配置。`menu` 文件定义你的应用菜单,`keys` 文件定义键盘快捷键,等等。 `start` 文件是在 Pekwm 启动后执行的 shell 脚本。它类似于传统 Unix 系统上的 `rc.local`。它故意放在最后执行的,因此这里的东西将覆盖之前的一切。这是一个重要文件,它可能是你要设置背景的地方,以便*你的*选择会覆盖正在使用的主题的默认值。 `start` 文件也是可以启动 dockapp 的地方。dockapp 是一种小程序,它在 Window Maker 和 Fluxbox 引起了人们的关注。它们通常有网络监视器、时钟、音频设置,和其它你可能会在系统托盘或作为一个 KDE plasmoid 或者完整桌面环境中看到的小部件。你可能会在发行版仓库中找到一些 dockapp,或者可以在 [dockapps.net](http://dockapps.net) 上在线查找它们。 你可以在启动时运行 dockapp,将它们列在 `start` 文件中,跟上 `&` 符号: ``` feh --bg-fill ~/Pictures/wallpapers/mybackground.jpg wmnd &amp; bubblemon -d &amp; ``` `start` 文件必须[设置为可执行](https://opensource.com/article/19/6/understanding-linux-permissions),才能在 Pekwm 启动时运行。 ``` $ chmod +x $HOME/.pekwm/start ``` ### 功能 Pekwm 的功能不多,但这就是它的美。如果你希望在桌面上运行额外的服务,那么由你来启动这些服务。如果你仍在学习 Linux,这是了解那些与完整的桌面环境捆绑在一起时通常不会注意到的微小 GUI 组件的好方法(像是[任务栏](https://opensource.com/article/19/1/productivity-tool-tint2))。这也习惯一些 Linux 命令(例如 [nmcli](https://opensource.com/article/19/5/set-static-network-connection-linux))的好方法。 Pekwm 是一个有趣的窗口管理器。它分散、简洁、轻巧。请试试看! --- via: <https://opensource.com/article/19/12/pekwm-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Let's say you want a lightweight desktop environment, with just enough to get graphics on the screen, move some windows around, and not much else. You find traditional desktops get in your way, with their notifications and taskbars and system trays. You want to live your life primarily from a terminal, but you also want the luxury of launching graphical applications. If that sounds like you, then [Pekwm](http://www.pekwm.org/) may be what you've been looking for all along. Pekwm is, presumably, inspired by the likes of Window Maker and Fluxbox. It provides an application menu, window decoration, and not a whole lot more. It's ideal for minimalists—users who want to conserve resources and users who prefer to work from a terminal. Install Pekwm from your distribution's software repository. After installing, log out of your current desktop session so you can log into your new desktop. By default, your session manager (KDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. To override the previous desktop on GDM: ![Selecting your desktop in GDM Selecting your desktop in GDM](https://opensource.com/sites/default/files/uploads/advent-gdm_1.jpg) And on SDDM: ![Selecting your desktop in KDM Selecting your desktop in KDM](https://opensource.com/sites/default/files/uploads/advent-enlightenment-kdm_0.jpg) The first time you log into Pekwm, you may encounter nothing but a black screen. Believe it or not, that's normal. What you're seeing is a blank desktop without background wallpaper. You can set a wallpaper with the **feh** command (you may need to install it from your repository). This command has a few options for setting the background, including **--bg-fill** to fill the screen with your wallpaper, **--bg-scale** to scale it to fit, and so on. `$ feh --bg-fill ~/Pictures/wallpapers/mybackground.jpg` ## Application menu By default, Pekwm auto-generates a menu, available with a right-click anywhere on the desktop, that gives you access to applications. This menu also provides a few preference settings, such as the ability to pick a theme and to log out of your Pekwm session. ![Pekwm running on Fedora Pekwm running on Fedora](https://opensource.com/sites/default/files/uploads/advent-pekwm.jpg) ## Configuration Pekwm is primarily configured in text config files stored in **$HOME/.pekwm**. The **menu** file defines your application menu, the **keys** file defines keyboard shortcuts, and so on. The **start** file is a shell script that is executed after Pekwm launches. It is analogous to the **rc.local** file on a traditional Unix system; it's intentionally last in line, so whatever you put into it overrides everything that came before it. This is an important file—it's probably where you want to set your background so that *your* choice overrides the default on the theme you're using. The **start** file is also where you can launch dockapps. Dockapps are tiny applets that rose to prominence with Window Maker and Fluxbox. They usually provide network monitors, a clock, audio settings, and other things you might be used to seeing in a system tray or as a KDE plasmoid or widget in a full desktop environment. You might find some dockapps in your distribution's repository, or you can look for them online at [dockapps.net](http://dockapps.net). You can launch dockapps at startup by listing them in the **start** file followed by an **&** symbol: ``` feh --bg-fill ~/Pictures/wallpapers/mybackground.jpg wmnd & bubblemon -d & ``` The **start** file must be [marked executable](https://opensource.com/article/19/6/understanding-linux-permissions) for it to run when Pekwm starts. `$ chmod +x $HOME/.pekwm/start` ## Features There's not much to Pekwm, and that's the beauty of it. If you want extra services to run on your desktop, it's up to you to launch them. If you're still learning Linux, this is a great way to learn about the minute GUI components you usually don't think about when they come bundled with a complete desktop environment (like [a taskbar](https://opensource.com/article/19/1/productivity-tool-tint2)). It's also a good way to get used to some of the Linux commands, like [nmcli](https://opensource.com/article/19/5/set-static-network-connection-linux), that you've been meaning to learn. Pekwm is a fun window manager. It's sparse, terse, and very lightweight. Give it a try! ## Comments are closed.
11,672
用 bash 倒计时日期
https://www.networkworld.com/article/3487712/counting-down-the-days-using-bash.html
2019-12-13T14:07:37
[ "日期", "date" ]
https://linux.cn/article-11672-1.html
> > 需要知道重要事件发生前有多少天吗?让 Linux bash 和 date 命令可以帮助你! > > > ![](/data/attachment/album/201912/13/140725vdc3c7zj0o7ozc7j.jpg) 随着即将来临的重要假期,你可能需要提醒你还要准备多久。 幸运的是,你可以从 `date` 命令获得很多帮助。在本篇中,我们将研究 `date` 和 bash 脚本如何告诉你从今天到你预期的事件之间有多少天。 首先,在进行之前有几个提示。`date` 命令的 `%j` 选项将以 1 至 366 之间的数字显示当前日期。如你所想的一样,1 月 1 日将显示为 1,12 月 31 日将显示为 365 或 366,这取决于是否是闰年。继续尝试。你应该会看到以下内容: ``` $ date +%j 339 ``` 但是,你可以通过以下方式,在 `date` 命令中得到一年中*任何*一天的数字: ``` $ date -d "Mar 18" +%j 077 ``` 要记住的是,即使该日期是过去的日期,上面命令也会向你显示*当年*的日期。但是,你可以在命令中添加年来修复该问题: ``` $ date -d "Apr 29" +%j 119 $ date -d "Apr 29 2020" +%j 120 ``` 在闰年中,4 月 29 日将是一年的 120 天,而不是 119 天。 如果你想倒数圣诞节之前的日子并且不想在挂历上留下指纹,你可以使用以下脚本: ``` #!/bin/sh XMAS=`date -d "Dec 25" +%j` TODAY=`date +%j` DAYS=$(($XMAS - $TODAY)) case $DAYS in 0) echo "It's today! Merry Christmas!";; [0-9]*) echo "$DAYS days remaining";; -[0-9]*) echo "Oops, you missed it";; esac ``` 在此脚本中,我们获取 12 月 25 日和今天的日期,然后相减。如果结果是正数,我们将显示剩余天数。如果为零,则发出 “Merry Christmas” 的消息,如果为负,那么仅告诉运行脚本的人他们错过了假期。也许他们沉迷在蛋酒中了。 `case` 语句由用来打印信息的语句组成,当剩余时间等于 0,或任意数字或以 `-` 符号开头的数字(也就是过去)分别打印不同的信息。 对于人们想要关注的任何日期,都可以使用相同方法。实际上,我们可以要求运行脚本的人员提供日期,然后让他们知道从现在到那天还有多少天。这个脚本是这样的。 ``` #!/bin/sh echo -n "Enter event date (e.g., June 6): " read dt EVENT=`date -d "$dt" +%j` TODAY=`date +%j` DAYS=`expr $EVENT - $TODAY` case $DAYS in 0) echo "It's today!";; [0-9]*) echo "$DAYS days remaining";; -[0-9]*) echo "Oops, you missed it";; esac ``` 使用此脚本会遇到的一个问题,如果运行该脚本的人希望知道到第二年这个特殊日子还有多少天,他们会感到失望。即使他们输入日期时提供了年,`date -d` 命令仍将仅提供今年中的天数,而不会提供从现在到那时的天数。 计算从今天到某年的日期之间的天数可能有些棘手。你需要包括所有中间年份,并注意那些闰年。 ### 使用 Unix 纪元时间 计算从现在到某个特殊日期之间的天数的另一种方法是利用 Unix 系统存储日期的方法。如果将自 1970 年 1 月 1 日开始的秒数转换为天数,那么就可以很容易地执行此操作,如下脚本所示: ``` #!/bin/bash echo -n "Enter target date (e.g., Mar 18 2021)> " read target_date today=`echo $(($(date --utc --date "$1" +%s)/86400))` target=`echo $(($(date --utc --date "$target_date" +%s)/86400))` days=`expr $target - $today` echo "$days days until $target_date" ``` 解释一下,86400 是一天中的秒数。将自 Unix 纪元开始以来的秒数除该数即为天数。 ``` $ ./countdown Enter target date (e.g., Mar 18 2021)> Mar 18 2020 104 days until Mar 18 2020 ``` --- via: <https://www.networkworld.com/article/3487712/counting-down-the-days-using-bash.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,673
24 个必知必会的系统管理员面试问题
https://opensource.com/article/19/7/sysadmin-job-interview-questions
2019-12-14T12:50:06
[ "面试", "系统管理员" ]
https://linux.cn/article-11673-1.html
> > 即将进行系统管理员工作面试吗?阅读本文,了解你可能会遇到的一些问题以及可能的答案。 > > > ![](/data/attachment/album/201912/14/124906g3vrkr3vrvqdkw7f.jpg) 作为一个经常与计算机打交道的极客,在硕士毕业后在 IT 行业选择我的职业是很自然的选择。因此,我认为走上系统管理员之路是正确的路径。在我的职业生涯中,我对求职面试过程非常熟悉。现在来看一下对该职位的预期、职业发展道路,以及一系列常见面试问题及我的回答。 ### 系统管理员的典型任务和职责 组织需要了解系统工作原理的人员,以确保数据安全并保持服务平稳运行。你可能会问:“等等,是不是系统管理员还能做更多的事情?” 你是对的。现在,一般来说,让我们看一下典型的系统管理员的日常任务。根据公司的需求和人员的技能水平,系统管理员的任务从管理台式机、笔记本电脑、网络和服务器到设计组织的 IT 策略不等。有时,系统管理员甚至负责购买和订购新的 IT 设备。 那些寻求系统管理工作以作为其职业发展道路的人可能会发现,由于 IT 领域的快速变化是不可避免的,因此难以保持其技能和知识的最新状态。所有人都会想到的下一个自然而然的问题是 IT 专业人员如何掌握最新的更新和技能。 ### 简单的问题 这是你将遇到的一些最基本的问题,以及我的答案: **1、你在 \*nix 服务器上登录后键入的前五个命令是什么?** > > * `lsblk` 以查看所有的块设备信息 > * `who` 查看谁登录到服务器 > * `top`,以了解服务器上正在运行的进程 > * `df -khT` 以查看服务器上可用的磁盘容量 > * `netstat` 以查看哪些 TCP 网络连接处于活动状态 > > > **2、如何使进程在后台运行,这样做的好处是什么?** > > 你可以通过在命令末尾添加特殊字符 `&` 来使进程在后台运行。通常,执行时间太长并且不需要用户交互的应用程序可以放到后台,以便我们可以在终端中继续工作。([引文](https://github.com/trimstray/test-your-sysadmin-skills)) > > > **3、以 root 用户身份运行这些命令是好事还是坏事?** > > 由于两个主要问题,以 root 身份运行(任何命令)是不好的。第一个是*风险*。当你以 **root** 身份登录时,无法避免你由于粗心大意而犯错。如果你尝试以带有潜在危害的方式更改系统,则需要使用 `sudo`,它会引入一个暂停(在你输入密码时),以确保你不会犯错。 > > > 第二个原因是*安全*。如果你不知道管理员用户的登录信息,则系统更难被攻击。拥有 root 的访问权限意味着你已经能够进行管理员身份下的一半工作任务。 > > > **4、`rm` 和 `rm -rf` 有什么区别?** > > `rm` 命令本身仅删除指明的文件(而不删除目录)。使用 `-rf` 标志,你添加了两个附加功能:`-r`(或等价的 `-R`、`--recursive`)标志可以递归删除目录的内容,包括隐藏的文件和子目录;而 `-f`(或 `--force`)标志使 `rm` 忽略不存在的文件,并且从不提示你进行确认。 > > > **5、有一个大小约为 15GB 的 `Compress.tgz` 文件。你如何列出其内容,以及如何仅提取出特定文件?** > > 要列出文件的内容: > > > `tar tf archive.tgz` > > > 要提取特定文件: > > > `tar xf archive.tgz filename` > > > ### 有点难度的问题 这是你可能会遇到的一些较难的问题,以及我的答案: **6、什么是 RAID?什么是 RAID 0、RAID 1、RAID 5、RAID 6 和 RAID 10?** > > RAID(<ruby> 廉价磁盘冗余阵列 <rt> Redundant Array of Inexpensive Disks </rt></ruby>)是一种用于提高数据存储性能和/或可靠性的技术。RAID 级别为: > > > * RAID 0:也称为磁盘条带化,这是一种分解文件并将数据分布在 RAID 组中所有磁盘驱动器上的技术。它没有防止磁盘失败的保障。([引文](https://www.waytoeasylearn.com/2016/05/netapp-filer-tutorial.html)) > * RAID 1:一种流行的磁盘子系统,通过在两个驱动器上写入相同的数据来提高安全性。RAID 1 被称为*镜像*,它不会提高写入性能,但读取性能可能会提高到每个磁盘性能的总和。另外,如果一个驱动器发生故障,则会使用第二个驱动器,发生故障的驱动器需要手动更换。更换后,RAID 控制器会将可工作的驱动器的内容复制到新驱动器上。 > * RAID 5:一种磁盘子系统,可通过计算奇偶校验数据来提高安全性和提高速度。RAID 5 通过跨三个或更多驱动器交错数据(条带化)来实现此目的。在单个驱动器发生故障时,后续读取可以从分布式奇偶校验计算出,从而不会丢失任何数据。 > * RAID 6:通过添加另一个奇偶校验块来扩展 RAID 5。此级别至少需要四个磁盘,并且可以在任何两个并发磁盘故障的情况下继续执行读/写操作。RAID 6 不会对读取操作造成性能损失,但由于与奇偶校验计算相关的开销,因此确实会对写入操作造成性能损失。 > * RAID 10:RAID 10 也称为 RAID 1 + 0,它结合了磁盘镜像和磁盘条带化功能来保护数据。它至少需要四个磁盘,并且跨镜像对对数据进行条带化。只要每个镜像对中的一个磁盘起作用,就可以检索数据。如果同一镜像对中的两个磁盘发生故障,则所有数据将丢失,因为带区集中没有奇偶校验。([引文](https://searchstorage.techtarget.com/definition/RAID-10-redundant-array-of-independent-disks)) > > > **7、`ping` 命令使用哪个端口?** > > `ping` 命令使用 ICMP。具体来说,它使用 ICMP 回显请求和应答包。 > > > ICMP 不使用 UDP 或 TCP 通信服务:相反,它使用原始的 IP 通信服务。这意味着,ICMP 消息直接承载在 IP 数据报数据字段中。 > > > **8、路由器和网关之间有什么区别?什么是默认网关?** > > *路由器*描述的是一种通用技术功能(第 3 层转发)或用于该目的的硬件设备,而*网关*描述的是本地网段的功能(提供到其他地方的连接性)。你还可以说“将路由器设置为网关”。另一个术语是“跳”,它描述了子网之间的转发。 > > > 术语*默认网关*表示局域网上的路由器,它的责任是作为对局域网外部的计算机通信的第一个联系点。 > > > **9、解释一下 Linux 的引导过程。** > > BIOS -> 主引导记录(MBR) -> GRUB -> 内核 -> 初始化 -> 运行级 > > > **10、服务器启动时如何检查错误消息?** > > 内核消息始终存储在 kmsg 缓冲区中,可通过 `dmesg` 命令查看。 > > > 引导出现的问题和错误要求系统管理员结合某些特定命令来查看某些重要文件,这些文件不同版本的 Linux 处理方式不同: > > > * `/var/log/boot.log` 是系统引导日志,其中包含系统引导过程中展开的所有内容。 > * `/var/log/messages` 存储全局系统消息,包括系统引导期间记录的消息。 > * `/var/log/dmesg` 包含内核环形缓冲区信息。 > > > **11、符号链接和硬链接有什么区别?** > > *符号链接*(*软链接*)实际是到原始文件的链接,而*硬链接*是原始文件的镜像副本。如果删除原始文件,则该软链接就没有用了,因为它指向的文件不存在了。如果是硬链接,则完全相反。如果删除原始文件,则硬链接仍然包含原始文件中的数据。([引文](https://www.answers.com/Q/What_is_hard_link_and_soft_link_in_Linux)) > > > **12、如何更改内核参数?你可能需要调整哪些内核选项?** > > 要在类 Unix 系统中设置内核参数,请首先编辑文件 `/etc/sysctl.conf`。进行更改后,保存文件并运行 `sysctl -p` 命令。此命令使更改永久生效,而无需重新启动计算机 > > > **13、解释一下 `/proc` 文件系统。** > > `/proc` 文件系统是虚拟的,并提供有关内核、硬件和正在运行的进程的详细信息。由于 `/proc` 包含虚拟文件,因此称为“虚拟文件系统”。这些虚拟文件具有独特性。其中大多数显示为零字节。 > > > 虚拟文件,例如 `/proc/interrupts`、`/proc/meminfo`、`/proc/mounts` 和 `/proc/partitions`,提供了系统硬件的最新信息。其他诸如 `/proc/filesystems` 和 `/proc/sys` 目录提供系统配置信息和接口。 > > > **14、如何在没有密码的情况下以其他用户身份运行脚本?** > > 例如,如果你可以编辑 sudoers 文件(例如 `/private/etc/sudoers`),则可以使用 `visudo` 添加以下[内容](https://github.com/trimstray/test-your-sysadmin-skills): > > > `user1 ALL =(user2)NOPASSWD:/opt/scripts/bin/generate.sh` > > > **15、什么是 UID 0 toor 帐户?是被入侵了么?** > > `toor` 用户是备用的超级用户帐户,其中 `toor` 是 `root` 反向拼写。它预期与非标准 shell 一起使用,因此 `root` 的默认 shell 不需要更改。 > > > 此用途很重要。这些 shell 不是基本发行版的一部分,而是从 ports 或软件包安装的,它们安装在 `/usr/local/bin` 中,默认情况下,位于其他文件系统上。如果 root 的 shell 位于 `/usr/local/bin` 中,并且未挂载包含 `/usr/local/bin` 的文件系统,则 root 无法登录以解决问题,并且系统管理员必须重新启动进入单用户模式来输入 shell 程序的路径。 > > > ### 更难的问题 这是你可能会遇到的甚至更困难的问题: **16、`tracert` 如何工作,使用什么协议?** > > 命令 `tracert`(或 `traceroute`,具体取决于操作系统)使你可以准确地看到在连接到最终目的地的连接链条中所触及的路由器。如果你遇到无法连接或无法 `ping` 通最终目的地的问题,则可以使用 `tracert` 来帮助你确定连接链在何处停止。([引文](https://www.wisdomjobs.com/e-university/network-administrator-interview-questions.html)) > > > 通过此信息,你可以联系正确的人;无论是你自己的防火墙、ISP、目的地的 ISP 还是中间的某个位置。 `tracert` 命令像 `ping` 一样使用 ICMP 协议,但也可以使用 TCP 三步握手的第一步来发送 SYN 请求以进行响应。 > > > **17、使用 `chroot` 的主要优点是什么?我们何时以及为什么使用它?在 chroot 环境中,`mount /dev`、`mount /proc` 和 `mount /sys` 命令的作用是什么?** > > chroot 环境的优点是文件系统与物理主机是隔离的,因为 chroot 在文件系统内部有一个单独的文件系统。区别在于 `chroot` 使用新创建的根目录(`/`)作为其根目录。 > > > chroot 监狱可让你将进程及其子进程与系统其余部分隔离。它仅应用于不以 root 身份运行的进程,因为 root 用户可以轻松地脱离监狱。 > > > 该思路是创建一个目录树,在其中复制或链接运行该进程所需的所有系统文件。然后,你可以使用 `chroot()` 系统调用来告诉它根目录现在位于此新树的基点上,然后启动在该 chroot 环境中运行的进程。由于该命令因此而无法引用修改后的根目录之外的路径,因此它无法在这些位置上执行恶意操作(读取、写入等)。([引文](https://unix.stackexchange.com/questions/105/chroot-jail-what-is-it-and-how-do-i-use-it)) > > > **18、如何保护你的系统免遭黑客攻击?** > > 遵循最低特权原则和这些做法: > > > * 使用公钥加密,它可提供出色的安全性。 > * 增强密码复杂性。 > * 了解为什么要对上述规则设置例外。 > * 定期检查你的例外情况。 > * 让具体的人对失败负责。(它使你保持警惕。)([引文](https://serverfault.com/questions/391370/how-to-prevent-zero-day-attacks)) > > > **19、什么是 LVM,使用 LVM 有什么好处?** > > LVM(逻辑卷管理)是一种存储设备管理技术,该技术使用户能够合并和抽象化组件存储设备的物理布局,从而可以更轻松、灵活地进行管理。使用设备映射器的 Linux 内核框架,当前迭代(LVM2)可用于将现有存储设备收集到组中,并根据需要从组合的空间分配逻辑单元。 > > > **20、什么是粘性端口?** > > 粘性端口是网络管理员最好的朋友,也是最头痛的事情之一。它们允许你设置网络,以便通过将交换机上的每个端口锁定到特定的 MAC 地址,仅允许一台(或你指定的数字)计算机在该端口上进行连接。 > > > **21、解释一下端口转发?** > > 尝试与安全的网络内部的系统进行通信时,从外部进行通信可能非常困难,这是很显然的。因此,在路由器本身或其他连接管理设备中使用端口转发表可以使特定流量自动转发到特定目的地。例如,如果你的网络上运行着一台 Web 服务器,并且想从外部授予对该服务器的访问权限,则可以将端口转发设置为该服务器上的端口 80。这意味着在 Web 浏览器中输入你的(外网)IP 地址的任何人都将立即连接到该服务器的网站。 > > > 请注意,通常不建议允许从你的网络外部直接访问服务器。 > > > **22、对于 IDS,误报和漏报是什么?** > > 当入侵检测系统(IDS)设备为实际上没有发生的入侵生成警报时,这是<ruby> 误报(假阳性) <rt> false positive </rt></ruby>。如果设备未生成任何警报,而入侵实际上已发生,则为<ruby> 漏报(假阴性)</ruby>。 > > > **23、解释一下 `:(){ :|:& };:`,如果已经登录系统,如何停止此代码?** > > 这是一枚复刻炸弹。它分解如下: > > > * `:()` 定义了函数,以 `:` 作为函数名,并且空括号表示它不接受任何参数。 > * `{}` 是函数定义的开始和结束。 > * `:|:` 将函数 `:` 的副本加载到内存中,并将其输出通过管道传递给函数 `:` 的另一个副本,该副本也必须加载到内存中。 > * `&` 使前一个命令行成为后台进程,因此即使父进程被自动杀死,子进程也不会被杀死。 > * `:` 执行该函数,因此连锁反应开始。 > > > 保护多用户系统的最佳方法是使用特权访问管理(PAM)来限制用户可以使用的进程数。 > > > 复刻炸弹的最大问题是它发起了太多进程。因此,如果你已经登录系统,我们有两种尝试解决此问题的方法。一种选择是执行一个 `SIGSTOP` 命令来停止进程,例如: > > > `killall -STOP -u user1` > > > 如果由于占用了所有进程而无法使用命令行,则必须使用 `exec` 强制其运行: > > > `exec killall -STOP -u user1` > > > 对于复刻炸弹,最好的选择是防患于未然。 > > > **24、什么是 OOM 杀手,它如何决定首先杀死哪个进程?** > > 如果内存被进程彻底耗尽,可能会威胁到系统的稳定性,那么<ruby> 内存不足 <rt> out of memory </rt></ruby>(OOM)杀手就登场了。 > > > OOM 杀手首先必须选择要杀死的最佳进程。*最佳*在这里指的是在被杀死时将释放最大内存的进程,并且对系统来说最不重要。主要目标是杀死最少数量的进程,以最大程度地减少造成的损害,同时最大化释放的内存量。 > > > 为了实现此目标,内核为每个进程维护一个 `oom_score`。你可以在 `/proc` 文件系统中的 `pid` 目录下的看到每个进程的 `oom_score`: > > > `$ cat /proc/10292/oom_score` > > > 任何进程的 `oom_score` 值越高,在内存不足的情况下被 OOM 杀手杀死的可能性就越高。([引文](https://unix.stackexchange.com/a/153586/8369)) > > > ### 总结 系统管理人员的薪水[差别很大](https://blog.netwrix.com/2018/07/23/systems-administrator-salary-in-2018-how-much-can-you-earn/),有些网站上说年薪在 70,000 到 100,000 美元之间,具体取决于地点、组织的规模以及你的教育水平以及多年的工作经验。系统管理的职业道路最终归结为你对使用服务器和解决那些酷问题的兴趣。现在,我要说,继续前进,实现你的梦想之路吧! --- via: <https://opensource.com/article/19/7/sysadmin-job-interview-questions> 作者:[DirectedSoul](https://opensource.com/users/directedsoul) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
As a geek who always played with computers, a career after my masters in IT was a natural choice. So, I decided the sysadmin path was the right one. In the process of my career, I have grown quite familiar with the job interview process. Here is a look at what to expect, the general career path, and a set of common questions and my answers to them. ## Typical sysadmin tasks and duties Organizations need someone who understands the basics of how a system works so that they can keep their data safe, and keep their services running smoothly. You might ask: "Wait, isn’t there more that a sysadmin can do?" You are right. Now, in general, let’s look at what might be a typical sysadmin’s day-to-day tasks. Depending on their company’s needs and the person’s skill level, a sysadmin’s tasks vary from managing desktops, laptops, networks, and servers, to designing the organization’s IT policies. Sometimes sysadmins are even in charge of purchasing and placing orders for new IT equipment. Those seeking system administration as their career paths might find it difficult to keep their skills and knowledge up to date, as rapid changes in the IT field are inevitable. The next natural question that arises out of anyone’s mind is how IT professionals keep up with the latest updates and skills. ## Low difficulty questions Here are some of the more basic questions you will encounter, and my answers: - What are the first five commands you type on a *nix server after login? lsblkto see information on all block deviceswhoto see who is logged into the servertopto get a sense of what is running on the serverdf -khTto view the amount of disk space available on the servernetstatto see what TCP network connections are active - How do you make a process run in the background, and what are the advantages of doing so? You can make a process run in the background by adding the special character &at the end of the command. Generally, applications that take too long to execute, and don’t require user interaction are sent to the background so that we can continue our work in the terminal. ([Citation]) - Is running these commands as root a good or bad idea? Running (everything) as root is bad due to two major issues. The first is risk. Nothing prevents you from making a careless mistake when you are logged in asroot. If you try to change the system in a potentially harmful way, you need to usesudo, which introduces a pause (while you’re entering the password) to ensure that you aren’t about to make a mistake.The second reason is security. Systems are harder to hack if you don’t know the admin user’s login information. Having access to root means you already have one half of the working set of admin credentials. - What is the difference between **rm**and**rm -rf**? The rmcommand by itself only deletes the named files (and not directories). With-rfyou add two additional features: The-r,-R, or --recursiveflag recursively deletes the directory’s contents, including hidden files and subdirectories, and the-f, or --force, flag makesrmignore nonexistent files, and never prompt for confirmation. **Compress.tgz**has a file size of approximately 15GB. How can you list its contents, and how do you list them only for a specific file? To list the file’s contents: tar tf archive.tgzTo extract a specific file: tar xf archive.tgz filename ## Medium difficulty questions Here are some harder questions you might encounter, and my answers: - What is RAID? What is RAID 0, RAID 1, RAID 5, RAID 6, and RAID 10? A RAID (Redundant Array of Inexpensive Disks) is a technology used to increase the performance and/or reliability of data storage. The RAID levels are: - RAID 0: Also known as disk striping, which is a technique that breaks up a file, and spreads the data across all of the disk drives in a RAID group. There are no safeguards against failure. ( [Citation])- RAID 1: A popular disk subsystem that increases safety by writing the same data on two drives. Called mirroring, RAID1 does not increase write performance, but read performance may increase up to the sum of each disks’ performance. Also, if one drive fails, the second drive is used, and the failed drive is manually replaced. After replacement, the RAID controller duplicates the contents of the working drive onto the new one.- RAID 5: A disk subsystem that increases safety by computing parity data and increasing speed. RAID 5 does this by interleaving data across three or more drives (striping). Upon failure of a single drive, subsequent reads can be calculated from the distributed parity such that no data is lost. - RAID 6: Which extends RAID 5 by adding another parity block. This level requires a minimum of four disks, and can continue to execute read/write with any two concurrent disk failures. RAID 6 does not have a performance penalty for reading operations, but it does have a performance penalty on write operations because of the overhead associated with parity calculations. - RAID 10: Also known as RAID 1+0, RAID 10 combines disk mirroring and disk striping to protect data. It requires a minimum of four disks, and stripes data across mirrored pairs. As long as one disk in each mirrored pair is functional, data can be retrieved. If two disks in the same mirrored pair fail, all data will be lost because there is no parity in the striped sets. ( [Citation]) - Which port is used for the **ping**command? The pingcommand uses ICMP. Specifically, it uses ICMP echo requests and ICMP echo reply packets.ICMP does not use either UDP or TCP communication services: Instead, it uses raw IP communication services. This means that the ICMP message is carried directly in an IP datagram data field. - What is the difference between a router and a gateway? What is the default gateway? Routerdescribes the general technical function (layer 3 forwarding), or a hardware device intended for that purpose, whilegatewaydescribes the function for the local segment (providing connectivity to elsewhere). You could also state that you "set up a router as a gateway." Another term ishop, which describes forwarding between subnets.The term default gatewayis used to mean the router on your LAN, which has the responsibility of being the first point of contact for traffic to computers outside the LAN. - Explain the boot process for Linux. BIOS -> Master Boot Record (MBR) -> GRUB -> the kernel -> init -> runlevel - How do you check the error messages while the server is booting up? Kernel messages are always stored in the kmsg buffer, visible via the dmesgcommand.Boot issues and errors call for a system administrator to look into certain important files, in conjunction with particular commands, which are each handled differently by different versions of Linux: /var/log/boot.logis the system boot log, which contains all that unfolded during the system boot./var/log/messagesstores global system messages, including the messages logged during system boot./var/log/dmesgcontains kernel ring buffer information. - What is the difference between a symbolic link and a hard link? Updated Aug 30, 2019 | Editor's note:this answer original said 'a hard link is a mirror copy of the original file,' which is not accurate. Thank you toBruce Bowenfor providing the following answer: A hard link is a directory reference to the same inode that the first directory entry refers to, and the inode is updated to increase the reference count to know there is a new link to the data. This means that when a file is 'deleted', the directory is updated to remove the file name and the inode for the data has the reference count decremented. The data of the file won't be freed unless the reference count goes to 0. Since inodes are unique for each file system, hard links can't cross file systems. Soft links create a way to for a directory entry to say "the file information is really stored in another directory entry". Soft links break if the 'another directory entry' is deleted. So a 'user' way to describe the difference between a hard and soft link is that a hard link is a link to the file data and a soft link is a link to another file name. - How do you change kernel parameters? What kernel options might you need to tune? To set the kernel parameters in Unix-like systems, first edit the file /etc/sysctl.conf. After making the changes, save the file and run thesysctl -pcommand. This command makes the changes permanent without rebooting the machine - Explain the **/proc**filesystem. The /procfilesystem is virtual, and provides detailed information about the kernel, hardware, and running processes. Since/proccontains virtual files, it is called thevirtual file system. These virtual files have unique qualities. Most of them are listed as zero bytes in size.Virtual files such as /proc/interrupts,/proc/meminfo,/proc/mountsand/proc/partitionsprovide an up-to-the-moment glimpse of the system’s hardware. Others, such as/proc/filesystemsand the/proc/sysdirectory provide system configuration information and interfaces. - How do you run a script as another user without their password? For example, if you were editing the sudoers file (such as /private/etc/sudoers), you might usevisudoto add the following: - What is the UID 0 toor account? Have you been compromised? The toor user is an alternative superuser account, where toor is root spelled backward. It is intended to be used with a non-standard shell, so the default shell for root does not need to change. This purpose is important. Shells which are not part of the base distribution, but are instead installed from ports or packages, are installed in /usr/local/bin; which, by default, resides on a different file system. If root’s shell is located in/usr/local/binand the file system containing/usr/local/binis not mounted, root could not log in to fix a problem, and the sysadmin would have to reboot into single-user mode to enter the shell’s path. ## Advanced questions Here are the even more difficult questions you may encounter: - How does **tracert**work and what protocol does it use? The command tracert—ortraceroutedepending on the operating system—allows you to see exactly what routers you touch as you move through the chain of connections to your final destination. If you end up with a problem where you can’t connect to orpingyour final destination, atracertcan help in that you can tell exactly where the chain of connections stops. ([Citation])With this information, you can contact the correct people; whether it be your own firewall, your ISP, your destination’s ISP, or somewhere in the middle. The tracertcommand—likeping—uses the ICMP protocol, but also can use the first step of the TCP three-way handshake to send SYN requests for a response. - What is the main advantage of using **chroot**? When and why do we use it? What is the purpose of the**mount /dev**,**mount /proc**, and**mount /sys**commands in a**chroot**environment? An advantage of having a chrootenvironment is that the filesystem is isolated from the physical host, sincechroothas a separate filesystem inside your filesystem. The difference is thatchrootuses a newly created root (/) as its root directory.A chrootjail lets you isolate a process and its children from the rest of the system. It should only be used for processes that don’t run asroot, asrootusers can break out of the jail easily.The idea is that you create a directory tree where you copy or link in all of the system files needed for the process to run. You then use the chroot()system call to tell it the root directory now exists at the base of this new tree, and then start the process running in thatchroot’d environment. Since the command then can’t reference paths outside the modified root directory, it can’t perform operations (read, write, etc.) maliciously on those locations. ([Citation]) - How do you protect your system from getting hacked? By following the principle of least privileges and these practices: - Encrypt with public keys, which provides excellent security. - Enforce password complexity. - Understand why you are making exceptions to the rules above. - Review your exceptions regularly. - Hold someone to account for failure. (It keeps you on your toes.) ( [Citation]) - What is LVM, and what are the advantages of using it? LVM, or Logical Volume Management, uses a storage device management technology that gives users the power to pool and abstract the physical layout of component storage devices for easier and flexible administration. Using the device mapper Linux kernel framework, the current iteration (LVM2) can be used to gather existing storage devices into groups and allocate logical units from the combined space as needed. - What are sticky ports? Sticky ports are one of the network administrator’s best friends and worst headaches. They allow you to set up your network so that each port on a switch only permits one (or a number that you specify) computer to connect on that port, by locking it to a particular MAC address. - Explain port forwarding? When trying to communicate with systems on the inside of a secured network, it can be very difficult to do so from the outside—and with good reason. Therefore, the use of a port forwarding table within the router itself, or other connection management device, can allow specific traffic to automatically forward to a particular destination. For example, if you had a web server running on your network and you wanted to grant access to it from the outside, you would set up port forwarding to port 80 on the server in question. This would mean that anyone entering your IP address in a web browser would connect to the server’s website immediately. Please note, it is usually not recommended to allow access to a server from the outside directly into your network. - What is a false positive and false negative in the case of IDS? When the Intrusion Detection System (IDS) device generates an alert for an intrusion which has actually not happened, this is false positive. If the device has not generated any alert and the intrusion has actually happened, this is the case of a false negative. - Explain **:(){ :|:& };:**and how to stop this code if you are already logged into the system? This is a fork bomb. It breaks down as follows: :()defines the function, with:as the function name, and the empty parenthesis shows that it will not accept any arguments.{ }shows the beginning and end of the function definition.:|:loads a copy of the function:into memory, and pipes its output to another copy of the:function, which also has to be loaded into memory.&makes the previous item a background process, so that the child processes will not get killed even though the parent gets auto-killed.:at the end executes the function again, and hence the chain reaction begins.The best way to protect a multi-user system is to use Privileged Access Management (PAM) to limit the number of processes a user can use. The biggest problem with a fork bomb is the fact it takes up so many processes. So, we have two ways of attempting to fix this if you are already logged into the system. One option is to execute a SIGSTOP command to stop the process, such as: killall -STOP -u user1If you can’t use the command line due to all processes being used, you will have to use execto force it to run: exec killall -STOP -u user1With fork bombs, your best option is preventing them from becoming too big of an issue in the first place - What is OOM killer and how does it decide which process to kill first? If memory is exhaustively used up by processes to the extent that possibly threatens the system’s stability, then the out of memory (OOM) killer comes into the picture. An OOM killer first has to select the best process(es) to kill. Besthere refers to the process which will free up the maximum memory upon being killed, and is also the least important to the system. The primary goal is to kill the least number of processes to minimize the damage done, and at the same time maximize the amount of memory freed.To facilitate this goal, the kernel maintains an oom_score for each of the processes. You can see the oom_score of each of the processes in the /procfilesystem under thepiddirectory: $ cat /proc/10292/oom_scoreThe higher the value of oom_score for any process, the higher its likelihood is of being killed by the OOM Killer in an out-of-memory situation. ( [Citation]) ## Conclusion System administration salaries have a [wide range](https://blog.netwrix.com/2018/07/23/systems-administrator-salary-in-2018-how-much-can-you-earn/) with some sites mentioning $70,000 to $100,000 a year, depending on the location, the size of the organization, and your education level plus years of experience. In the end, the system administration career path boils down to your interest in working with servers and solving cool problems. Now, I would say go ahead and achieve your dream path. ## 11 Comments
11,675
GNOME Linux 桌面入门
https://opensource.com/article/19/12/gnome-linux-desktop
2019-12-14T15:05:34
[ "桌面", "GNOME" ]
/article-11675-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。GNOME 是大多数现代 Linux 发行版的默认桌面,它干净、简单、组织良好。 > > > ![](/data/attachment/album/201912/14/150510z2227x177x8liwww.jpg) [GNOME](https://www.gnome.org/) 项目理所应当是 Linux 桌面的宠儿。它起初是专有桌面(当时包括 KDE)的自由开源的桌面替代品,此后一直发展强劲。GNOME 采用了[由 GIMP 项目开发](https://www.gtk.org/overview.php)的 GTK+,并将其开发为强大的通用 GTK 框架。该项目开创了用户界面的先声,挑战了桌面“应有”外观的先入之见,并为用户提供了新的范例和选项。 在大多数主流现代 Linux 发行版(包括 RHEL、Fedora、Debian 和 Ubuntu)中,GNOME 作为默认桌面而广泛使用。如果你的发行版不提供它的某个版本,那么你可以从软件仓库中安装 GNOME。但是,在执行此操作之前,请注意,为了提供完整的桌面体验,这会随桌面一起安装许多 GNOME 应用。如果你在用其他桌面,那么你可能会发现有冗余的应用(两个 PDF 阅读器、两个媒体播放器、两个文件管理器,等等)。如果你只想尝试 GNOME 桌面,请考虑在虚拟机,如 [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization),中安装 GNOME 发行版。 ### GNOME 功能 GNOME 桌面很干净,顶部有一个简单的任务栏,右上角的系统托盘中只有很少的图标。GNOME 上没有桌面图标,这是设计使然。如果你是喜欢在桌面上保存*任何东西*的用户,那么你可能会意识到桌面会定期地变得混乱,而且,更糟糕的是,由于你的应用掩盖了桌面,因此桌面永远不会显示出来。 GNOME 解决了两个问题:(在功能上)没有桌面,并且动态生成新的虚拟工作区,因此你可以在全屏模式下运行应用。如果你常把屏幕弄乱,那么可能需要一些时间来习惯,但实际上,从各个方面来说,这都是一种改进的工作流程。你将学习如何使文件井井有条(或者将它们分散在家目录中),并且可以像在手机上一样快速地在屏幕之间切换。 当然,并非所有应用都设计为在全屏模式下运行,因此,如果你更喜欢单击切换窗口,也可以这样做。 ![GNOME running on Debian](/data/attachment/album/201912/14/150539f3wb1rn5nx1nr5rq.jpg "GNOME running on Debian") GNOME 哲学褒扬了 Canonical 对常见任务的解决方案。在 GNOME 中,你通常不会发现“回字有四种写法”。你会找到一种或两种官方方法来完成一项任务,你了解了这些方法后,便只需记住这些即​​可。它非常简单,但由于它在 Linux 上运行,因此在技术上也很灵活(毕竟,你不必因为运行 GNOME 桌面而必须要使用 GNOME 应用)。 ### 应用菜单 要访问名为“活动”的应用菜单,请在桌面的左上角单击。此菜单将占满整个屏幕,屏幕最左侧有一栏常见应用的 dock,或可以在网格中浏览应用的图标。你可以通过浏览已安装的应用,或输入软件的头几个字母来过滤列表,然后来启动应用。 ![GNOME activities](/data/attachment/album/201912/14/150542q6gs9ekww9j1eu1u.jpg "GNOME activities") ### GNOME 应用 GNOME 不仅是桌面。它是一个桌面以及一组丰富的集成应用,例如 Gedit 文本编辑器、Evince PDF 查看器、Web 浏览器、图像查看器、Nautilus 文件管理器等等。GNOME 应用(例如桌面本身)遵循 [GNOME 人机界面指南](https://developer.gnome.org/hig/stable/),因此用户体验既愉悦又一致。无论你是否使用 GNOME 桌面,都可能使用 GTK 应用,也可能会使用 GNOME 应用。 ### GNOME 3 及更高版本 GNOME 项目进展顺利,还有几个令人兴奋的项目(例如 MATE 和 [Cinnamon](https://opensource.com/article/19/11/advent-2019-cinnamon))。它流行、令人舒适,被视为 Linux 桌面的代表。 --- via: <https://opensource.com/article/19/12/gnome-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,676
5 个最酷的终端分页器
https://fedoramagazine.org/5-cool-terminal-pagers-in-fedora/
2019-12-15T12:34:44
[ "分页器", "more", "less" ]
https://linux.cn/article-11676-1.html
![](/data/attachment/album/201912/15/123448sdj96ojjotj33fd9.jpg) 像日志或源代码这样的大文件可能会多达成千上万行,这使得在文件内导航非常困难,尤其是在终端上。此外,大多数终端仿真器的回滚缓冲区只有几百行。这可能使得无法使用打印到标准输出的实用程序(例如 `cat`、`head` 和 `tail`)在终端中浏览大型文件。在计算时代的早期,程序员通过开发用于以虚拟“页面”形式显示文本的实用程序来解决这些问题,该实用程序被形象地描述为<ruby> 分页器 <rt> pager </rt></ruby>。 *分页器*提供了许多使文本文件导航更加简单的功能,包括滚动、搜索功能,以及作为命令[管道](https://fedoramagazine.org/command-line-quick-tips-using-pipes-to-connect-tools/)的一部分而具有的功能。与大多数文本编辑器相比,某些终端分页器不需要加载整个文件即可查看,这使得它们更快,特别是对于非常大的文件。 在现代 Linux 计算时代,终端仿真器比以往更加复杂。它们提供了对缤纷的色彩、终端尺寸调整以及许多其它功能的支持,这些功能使得辨析屏幕上的文本变得更加轻松和高效。从诸如 `pg` 和 `more` 这样极其简单的 UNIX 实用程序,到涵盖各种使用场景的、功能广泛的复杂程序,终端分页器也经历了类似的演变。考虑到这一点,我们或“多”或“少”地汇总了一些最受欢迎的终端分页实用程序的列表。 ### more `more` 是最早的分页器之一,最初在 3.0 BSD 版本中出现。`more` 的第一个实现由 [Daniel Halbert](https://danhalbert.org/more.html) 编写于 1978 年。从那时起,`more` 已成为许多操作系统的普遍功能,包括 Windows、OS/2,MacOS 和大多数 Linux 发行版。 `more` 是一个非常轻量级的实用程序。util-linux 软件包中提供的版本只有不到 2100 行的 C 语言代码。但是,这种较小的代码大小是有代价的。大多数版本的 `more` 的功能相对有限,不支持向后滚动或搜索。命令也同样精简:按回车键可滚动一行,或按空格键滚动一页。其他一些有用的命令包括: * 在阅读时按 `v` 键以在默认的终端编辑器中打开当前文件。 * `/模式` 可以让你搜索下一个出现的“模式”。 * 以多个文件作为参数调用 `more` 时,`:n` 和 `:p` 将分别打开下一个和上一个文件 ### less `less` 最初被认为是 `more` 的继承者,解决了它的一些局限性。`less` 以 `more` 的功能为基础,增加了许多有用的功能,包括向后滚动、向后搜索。它也更适合窗口大小调整。 `less` 中的导航方式与 `more` 类似,尽管 `less` 也从 `vi` 编辑器借用了一些有用的命令。用户可以使用熟悉的<ruby> 主行导航键 <rt> home row navigational keys </rt></ruby>(LCTT 译注:指 左手的 `A`、`S`、`D`、`F` 和右手的 `J`、`K`、`L`、`;`,及大拇指所在的空格键)浏览文档。看一眼 `less` 的手册页,就会发现相当多的可用命令。一些特别有用的示例包括: * `?模式` 可让你在文件中向后搜索“模式”。 * `&模式` 仅显示具有“模式”特征的行。这对于发现自己经常要使用 `$ grep 模式 | less` 的人特别有用。 * 使用 `-s`(或 `–sqeueeze-blank-lines`)标志来调用 `less`,使你可以查看空白较大的文本文件。 多个换行符被简化为单个中断行。 * 在该程序中调用的 `s 文件名` 将输入保存到 `文件名`中(如果输入来自管道)。 * 或者,使用 `-o 文件名` 标志来调用 `less` 将把 `less` 的输入保存到 `文件名` 中。 随着这些增强的功能也带来了体积的略微增大。在写作本文时,Fedora 随附的 `less` 版本大约有 25000 行源代码。当然,除非是受存储限制最大的系统,在所有其它的系统上这都不是问题。`less` 比 `more` 功能更多。 ### most `less` 旨在扩展 `more` 的现有功能,而 `most` 采用另一种方法。`most` 不是在传统的单个文件视图上进行扩展,而是使用户能够将其视图拆分为“窗口”。每个窗口以不同的查看模式包含不同的文件。 重要的是,`most` 考虑了其输入文本的宽度。默认的查看模式是不换行的(`less` 中的 `-S` 参数),此功能在处理“宽”文件时特别有用。尽管对于某些用户来说,这些设计决策可能代表着与传统的重大偏离,但最终结果却非常强大。 除了 `more` 提供的导航命令外,`most` 使用直观的助记符进行文件导航。例如,`t` 移至文件的顶部(Top),而 `b` 移至底部(Bottom)。这样,不熟悉 `vi` 及其衍生品的用户会发现 `most` 非常简单好用。 `most` 的与众不同之处在于它能够快速轻松地拆分窗口和上下文。例如,可以使用以下命令打开两个不同的文本文件: ``` $ most textFile1.txt textFile2.txt ``` 为了水平拆分屏幕,请使用组合键 `Ctrl+x, 2` 或 `Ctrl+w, 2`。 `:n` 命令将在给定窗口中打开下一个文件参数,提供两个文件的分屏视图: ![](/data/attachment/album/201912/15/123449t6h3ahmhh3v2hvhn.png) 如果在一个窗口中关闭自动换行,它不会影响其他窗口的行为。(行末的)`\` 字符表示换行或折叠,而 `$` 字符表示文件超出了当前窗口的限制。 ### pspg 使用 SQL 数据库的人员通常需要能够一目了然地检查数据库的内容。许多流行的开源 DBMS(例如 MySQL 和 PostGreSQL)的命令行界面都使用系统默认的分页器来查看无法显示在单个屏幕上的输出。诸如 `more` 和 `less` 之类的实用程序是围绕呈现文本文件的想法而设计的,但是对于更结构化的数据,还有一些不足之处。天真的文本分页程序没有宽的表格数据的概念,当处理大型查询时,这可能会令人感到沮丧。 [pspg](https://github.com/okbob/pspg) 试图通过为用户提供在查看时冻结列、*原位*排序数据并为输出着色的功能来解决此问题。尽管`pspg` 最初是专门用作 `psql` 的分页器的替代品,但该程序还支持查看 CSV 数据,并且是 `mysql` 和 `pgcli` 的合适的直接替代品。 ### Vim 在现代的颜色鲜明的终端中,无休止的黑色页面上的灰色文字感觉太过时了。强大的文本编辑器(如 `vim`)提供的语法高亮显示选项对于浏览源代码很有用。此外,`vim` 提供的搜索功能远远超过了竞争对手。考虑到这一点,`vim` 附带了一个 shell 脚本 `less.sh`,该脚本可以使 `vim` 替代传统的分页器。 要将 `vim` 设置为手册页的[默认分页器](https://zameermanji.com/blog/2012/12/30/using-vim-as-manpager/),请将以下内容添加到 shell 的配置中(如果使用默认的bash shell 的话是 `~/.bashrc`): ``` export MANPAGER="/bin/sh -c \"col -b | vim -c 'set ft=man ts=8 nomod nolist nonu noma' -\"" ``` 或者,要将 `vim` 设置为系统范围内的默认分页器,请找到 `less.sh` 脚本。(你可以在当前 Fedora 系统上的 `/usr/share/vim/vim81/macros/` 找到它。)将此位置导出为变量 `PAGER` 以将其设置为默认值,或者将其设置为别名以显式调用它。 --- via: <https://fedoramagazine.org/5-cool-terminal-pagers-in-fedora/> 作者:[Jacob Burns](https://fedoramagazine.org/author/jaek/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Large files like logs or source code can run into the thousands of lines. That makes navigating them difficult, particularly from the terminal. Additionally, most terminal emulators have a scrollback buffer of only a few hundred lines. That can make it impossible to browse large files in the terminal using utilities which print to standard output like *cat*, *head* and *tail*. In the early days of computing, programmers solved these problems by developing utilities for displaying text in the form of virtual “pages” — utilities imaginatively described as *pagers*. Pagers offer a number of features which make text file navigation much simpler, including scrolling, search functions, and the ability to feature as part of a [pipeline](https://fedoramagazine.org/command-line-quick-tips-using-pipes-to-connect-tools/) of commands. In contrast to most text editors, some terminal pagers do not require loading the entire file for viewing, which makes them faster, especially for very large files. In the modern era of Linux computing, terminal emulators are more sophisticated than ever. They offer support for a kaleidoscope of colors, terminal resizing, as well as a host of other features to make parsing text on screen easier and more efficient. Terminal pagers have undergone a similar evolution, from extremely simple UNIX utilities like *pg* and *more*, to sophisticated programs with a wide range of features, covering any number of use cases. With this in mind, we’ve put together a list of some of the most popular terminal paging utilities — more or less. ### More *more* is one of the earliest pagers, initially featured in version 3.0 BSD. The first implementation of *more* was written in 1978 by [Daniel Halbert](https://danhalbert.org/more.html). Since then, *more* has become a ubiquitous feature of many operating systems, including Windows, OS/2, MacOS and most linux distributions. *more* is a very lightweight utility. The version featured in util-linux runs to just under 2100 lines of C. However, this small footprint comes at a price. Most versions of *more* feature relatively limited functionality, with no support for backwards scroll or search. Commands are similarly stripped back: press enter to scroll one line, or space to scroll one page. Some other useful commands include: - Press v while reading to open the current file in your default terminal editor. - ‘/ *pattern*‘ let’s you search for the next occurrence of*pattern*. - :n and :p will open the next and previous files respectively when more is called with more than one file as arguments ### Less *less* was initially conceived as a successor to *more*, addressing some of its limitations. Building on the functionality of *more*, *less* adds a number of useful features including backwards scroll, backwards search. It is also more amenable to window resizing. Navigation in *less* is similar to *more*, though *less* borrows a few useful commands from the *vi* editor as well. Users can navigate the document using the familiar home row navigational keys. A glance at the man page for *less* reveals a fairly rich repertoire of available commands. Some particularly useful examples include: - ? *pattern*lets you search backwards in the file for*pattern* - & *pattern*shows only lines which feature*pattern*. This is particularly useful for those who find themselves issuing**$ grep pattern | less**regularly. - Calling less with the -s (–sqeueeze-blank-lines) flag allows you to view text files with large gaps. Multiple newline characters are reduced to single breaks. - s *filename*, called from within the program, saves input to*filename*(if input is a pipe). - Alternatively, calling less with the -o *filename*flag will save the input of less to*filename.* With this enhanced functionality comes a little extra weight. The version of *less* that ships with Fedora at the time of writing clocks in at around 25000 lines of source code. Granted, for all but the most storage constrained systems, this is a non-issue. Besides, *less* is more than *more*. ### Most While *less* aims to expand on the existing capabilities of *more*, *most* takes a different approach. Rather than expanding on the traditional single file view, *most* gives users the ability to split their view into “windows.” Each window contains different files in different viewing modes. Significantly, *most* takes into account the width of its input text. The default viewing mode doesn’t wrap text (-S in less), a feature particularly useful when dealing with “wide” files. While these design decisions might represent a significant departure from tradition for some users, the end result is very powerful. In addition to the navigation commands offered by *more*, *most* uses intuitive mnemonics for file navigation. For example, * t* moves to the **t**op of a file, and *moves to the bottom. As a result, users unfamiliar with* **b***vi*and its descendants will find most to be refreshingly simple. The distinguishing feature of *most* is its ability to split windows and contexts quickly and easily. For example, one could open two distinct text files using the following: $ most textFile1.txt textFile2.txt In order to split the screen horizontally, use the key combos **Ctrl+x, 2** or **Ctrl+w, 2**. The command *:n* will open the next file argument in a given window, offering a split screen view of two files: ![](https://fedoramagazine.org/wp-content/uploads/2019/11/image-2.png) If you turn wrap off in one window, it does not affect the behavior of other windows. The \ character indicates a wrap or fold, while the $ character indicates that the file extends past the limitations of the current window. ### pspg Those who work with SQL databases often need to be able to examine the contents of our databases at a glance. The command line interfaces for many popular open source DBMS’s, such as MySQL and PostGreSQL, use the system default pager to view outputs that don’t fit on a single screen. Utilities like *more* and *less* are designed around the idea of presenting text files, but for more structured data, leave something to be desired. Naive text paginating programs have no concept of broad, tabular data, which can be frustrating when dealing with large queries. [pspg](https://github.com/okbob/pspg) attempts to address this by offering users the ability to freeze columns while viewing, sort data *in situ*, and colourize output. While *pspg* was intended initially to serve as a pager replacement for *psql* specifically, the program also supports the viewing of CSV data, and is a suitable drop-in replacement for *mysql* and *pgcli*. ### Vim In a modern, technicolor terminal, the idea of endless pages of drab grey on black text can feel like something of an anachronism. The syntax highlighting options offered by powerful text editors like *vim* can be useful for browsing source code. Furthermore, the search functions offered by *vim* vastly outclass the competition. With this in mind, *vim* ships with a shell script *less.sh* that lets *vim* serve as a replacement for conventional pagers. To set *vim* as [the default pager](https://zameermanji.com/blog/2012/12/30/using-vim-as-manpager/) for man pages, add the following to your shell’s config (such as *~/.bashrc* if using the default bash shell): export MANPAGER="/bin/sh -c \"col -b | vim -c 'set ft=man ts=8 nomod nolist nonu noma' -\"" Alternatively, to set *vim* as the default pager system-wide, locate the *less.sh* script. (You can find it at */usr/share/vim/vim81/macros/* on current Fedora systems.) Export this location as the variable *PAGER* to set it as default, or under an alias to invoke it explicitly. ## qoheniac Vim comes with a utility called view that starts in read-only mode and ignores the .vimrc file. I think this could be really handy but “view –version | grep syntax” tells me that syntax highlighting unfortunately isn’t supported. :/ ## RMPR Very useful article, as a vim user I am thrilled to know that’s possible, however I just tested it and after a “man nslookup” I noticed that many things aren’t formatted correctly, like 1mNAME0m instead of NAME in bold. ## Robin A. Meade @RMPR try: export MANPAGER="/bin/sh -c "ansifilter | vim -c MANPAGER -"" More info here: https://bugzilla.redhat.com/show_bug.cgi?id=1570182 ## mountaineerbr @RMPR That seems like colour codes. Check Dr Chip’s AnsiEsc. http://www.drchip.org/astronaut/vim/index.html#ANSIESC%20 ## Seirdy (https://github.com/walles/moar) is a colorizing pager that also adds things like line numbering. Install with (http://w3m.sourceforge.net/) is a TUI web browser that can also act as a generic pager. Install with (https://github.com/sharkdp/bat) can act as a pager (it actually uses your existing $PAGER underneath). Like , bat adds syntax highlighting, line numbers, etc. Install with or . Run to install the latest pre-release version. ## jjerphan is also a nice pager is you are looking for syntax highlighting in your terminal: https://github.com/sharkdp/bat ## mountaineerbr I’ve heard of Most recently, tried it and it seems to be a good pager. However, only More or Less can show you input before stdin (from a pipe) is closed. Vim Pager does not show you input while it is reading from stdin, neither does Most. Also, I can not find a similar option for Most or Vim Pager such as Less +F for opening files.. So, still, More and Less may be more than Most sometimes. But maybe I am overlooking these features in these other pagers.. ## andrej can ‘most’ scroll 2 files synchronously (like the vimdiff / vim -d could for diffed files)? ## Allen more is one of the earliest pagers, initially featured in version 3.0 BSD. The first implementation of more was written in 1978 by Daniel Halbert. Since then, more has become a ubiquitous feature of many operating systems, including Windows, OS/2, MacOS and most linux distributions. ## John Use vimpager!## John https://github.com/rkitover/vimpager
11,678
如何在 Linux 中找出 CPU 占用高的进程
https://www.2daygeek.com/how-to-find-high-cpu-consumption-processes-in-linux/
2019-12-15T15:26:35
[ "top", "CPU" ]
https://linux.cn/article-11678-1.html
![](/data/attachment/album/201912/15/152614cp9bjmfwpofwvsx1.jpg) 在之前的文章中我们已经讨论过 [如何在 Linux 中找出内存消耗最大的进程](/article-11542-1.html)。你可能也会遇到在 Linux 系统中找出 CPU 占用高的进程的情形。如果是这样,那么你需要列出系统中 CPU 占用高的进程列表来确定。我认为只有两种方法能实现:使用 [top 命令](https://www.2daygeek.com/linux-top-command-linux-system-performance-monitoring-tool/) 和 [ps 命令](https://www.2daygeek.com/linux-ps-command-find-running-process-monitoring/)。出于一些理由,我更倾向于用 `top` 命令而不是 `ps` 命令。但是两个工具都能达到你要的目的,所以你可以根据需求决定使用哪个。这两个工具都被 Linux 系统管理员广泛使用。 ### 1) 怎样使用 top 命令找出 Linux 中 CPU 占用高的进程 在所有监控 Linux 系统性能的工具中,Linux 的 `top` 命令是最好的也是最知名的一个。`top` 命令提供了 Linux 系统运行中的进程的动态实时视图。它能显示系统的概览信息和 Linux 内核当前管理的进程列表。它显示了大量的系统信息,如 CPU 使用、内存使用、交换内存、运行的进程数、目前系统开机时间、系统负载、缓冲区大小、缓存大小、进程 PID 等等。默认情况下,`top` 命令的输出结果按 CPU 占用进行排序,每 5 秒中更新一次结果。如果你想要一个更清晰的视图来更深入的分析结果,[以批处理模式运行 top 命令](https://www.2daygeek.com/linux-run-execute-top-command-in-batch-mode/) 是最好的方法。同时,你需要 [理解 top 命令输出结果的含义](https://www.2daygeek.com/understanding-linux-top-command-output-usage/) ,这样才能解决系统的性能问题。 ``` # top -b | head -50 top - 00:19:17 up 14:23, 1 user, load average: 2.46, 2.18, 1.97 Tasks: 306 total, 1 running, 305 sleeping, 0 stopped, 0 zombie %Cpu0 : 10.4 us, 3.0 sy, 0.0 ni, 83.9 id, 0.0 wa, 1.3 hi, 1.3 si, 0.0 st %Cpu1 : 17.0 us, 3.0 sy, 0.0 ni, 78.7 id, 0.0 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu2 : 13.0 us, 4.0 sy, 0.0 ni, 81.3 id, 0.0 wa, 0.3 hi, 1.3 si, 0.0 st %Cpu3 : 12.3 us, 3.3 sy, 0.0 ni, 82.5 id, 0.3 wa, 0.7 hi, 1.0 si, 0.0 st %Cpu4 : 12.2 us, 3.0 sy, 0.0 ni, 82.8 id, 0.7 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu5 : 6.4 us, 2.7 sy, 0.0 ni, 89.2 id, 0.0 wa, 0.7 hi, 1.0 si, 0.0 st %Cpu6 : 26.7 us, 3.4 sy, 0.0 ni, 68.6 id, 0.0 wa, 0.7 hi, 0.7 si, 0.0 st %Cpu7 : 15.6 us, 4.0 sy, 0.0 ni, 78.8 id, 0.0 wa, 0.7 hi, 1.0 si, 0.0 st KiB Mem : 16248556 total, 1448920 free, 8571484 used, 6228152 buff/cache KiB Swap: 17873388 total, 17873388 free, 0 used. 4596044 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 2179 daygeek 20 3106324 613584 327564 S 79.5 3.8 14:19.76 Web Content 1714 daygeek 20 4603372 974600 403504 S 20.2 6.0 65:18.91 firefox 1227 daygeek 20 4192012 376332 180348 S 13.9 2.3 20:43.26 gnome-shell 18324 daygeek 20 3296192 766040 127948 S 6.3 4.7 9:18.12 Web Content 1170 daygeek 20 1008264 572036 546180 S 6.0 3.5 18:07.85 Xorg 4684 daygeek 20 3363708 1.1g 1.0g S 3.6 7.2 13:49.92 VirtualBoxVM 4607 daygeek 20 4591040 1.7g 1.6g S 3.0 11.0 14:09.65 VirtualBoxVM 1211 daygeek 9 -11 2865268 21032 16588 S 2.0 0.1 10:46.37 pulseaudio 4562 daygeek 20 1096888 28812 21044 S 1.7 0.2 4:42.93 VBoxSVC 1783 daygeek 20 3123888 376896 134788 S 1.3 2.3 39:32.56 Web Content 3286 daygeek 20 3089736 404088 184968 S 1.0 2.5 41:57.44 Web Content ``` 上面的命令的各部分解释: * `top`:命令 * `-b`:批次档模式 * `head -50`:显示输出结果的前 50 个 * `PID`:进程的 ID * `USER`:进程的归属者 * `PR`:进程的等级 * `NI`:进程的 NICE 值 * `VIRT`:进程使用的虚拟内存 * `RES`:进程使用的物理内存 * `SHR`:进程使用的共享内存 * `S`:这个值表示进程的状态: `S` = 睡眠,`R` = 运行,`Z` = 僵尸进程 * `%CPU`:进程占用的 CPU 比例 * `%MEM`:进程使用的 RAM 比例 * `TIME+`:进程运行了多长时间 * `COMMAND`:进程名字 如果你想看命令的完整路径而不是命令名字,以运行下面的格式 `top` 命令: ``` # top -c -b | head -50 top - 00:28:49 up 14:33, 1 user, load average: 2.43, 2.49, 2.23 Tasks: 305 total, 1 running, 304 sleeping, 0 stopped, 0 zombie %Cpu0 : 11.7 us, 3.7 sy, 0.0 ni, 82.3 id, 0.0 wa, 1.0 hi, 1.3 si, 0.0 st %Cpu1 : 13.6 us, 3.3 sy, 0.0 ni, 81.1 id, 0.7 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu2 : 10.9 us, 2.6 sy, 0.0 ni, 85.1 id, 0.0 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu3 : 16.0 us, 2.6 sy, 0.0 ni, 80.1 id, 0.0 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu4 : 9.2 us, 3.6 sy, 0.0 ni, 85.9 id, 0.0 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu5 : 15.6 us, 2.9 sy, 0.0 ni, 80.5 id, 0.0 wa, 0.3 hi, 0.7 si, 0.0 st %Cpu6 : 11.6 us, 4.3 sy, 0.0 ni, 82.7 id, 0.0 wa, 0.3 hi, 1.0 si, 0.0 st %Cpu7 : 8.0 us, 3.0 sy, 0.0 ni, 87.3 id, 0.0 wa, 0.7 hi, 1.0 si, 0.0 st KiB Mem : 16248556 total, 1022456 free, 8778508 used, 6447592 buff/cache KiB Swap: 17873388 total, 17873388 free, 0 used. 4201560 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 18527 daygeek 20 3151820 624808 325748 S 52.8 3.8 59:26.72 /usr/lib/firefox/firefox -contentproc -childID 18 -isForBrowser -prefsLen 10002 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /+ 1714 daygeek 20 4764668 910940 443228 S 21.5 5.6 68:59.33 /usr/lib/firefox/firefox --new-window 1227 daygeek 20 4193108 377344 181404 S 11.6 2.3 21:47.36 /usr/bin/gnome-shell 1170 daygeek 20 1008820 572700 546844 S 5.6 3.5 19:05.10 /usr/lib/Xorg vt2 -displayfd 3 -auth /run/user/1000/gdm/Xauthority -nolisten tcp -background none -noreset -keeptty -verbose 3 18324 daygeek 20 3300288 789344 127948 S 5.0 4.9 9:46.89 /usr/lib/firefox/firefox -contentproc -childID 16 -isForBrowser -prefsLen 10002 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /+ 4684 daygeek 20 3363708 1.1g 1.0g S 3.6 7.2 14:10.18 /usr/lib/virtualbox/VirtualBoxVM --comment CentOS7 --startvm 002f47b8-2af2-48f5-be1d-67b67e03514c --no-startvm-errormsgbox 4607 daygeek 20 4591040 1.7g 1.6g S 3.0 11.0 14:28.86 /usr/lib/virtualbox/VirtualBoxVM --comment Ubuntu-18.04 --startvm e8c32dbb-8b01-41b0-977a-bf28b9db1117 --no-startvm-errormsgbox 1783 daygeek 20 3132640 451924 132168 S 2.6 2.8 39:49.66 /usr/lib/firefox/firefox -contentproc -childID 1 -isForBrowser -prefsLen 1 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/l+ 1211 daygeek 9 -11 2865268 21272 16828 S 2.0 0.1 11:01.29 /usr/bin/pulseaudio --daemonize=no 4562 daygeek 20 1096888 28812 21044 S 1.7 0.2 4:49.33 /usr/lib/virtualbox/VBoxSVC --auto-shutdown 16865 daygeek 20 3073364 430596 124652 S 1.3 2.7 8:04.02 /usr/lib/firefox/firefox -contentproc -childID 15 -isForBrowser -prefsLen 10002 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /+ 2179 daygeek 20 2945348 429644 172940 S 1.0 2.6 15:20.90 /usr/lib/firefox/firefox -contentproc -childID 6 -isForBrowser -prefsLen 7821 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /us+ ``` ### 2) 怎样使用 ps 命令找出 Linux 中 CPU 占用高的进程 `ps` 是<ruby> 进程状态 <rt> process status </rt></ruby>的缩写,它能显示系统中活跃的/运行中的进程的信息。它提供了当前进程及其详细信息,诸如用户名、用户 ID、CPU 使用率、内存使用、进程启动日期时间、命令名等等的快照。 ``` # ps -eo pid,ppid,%mem,%cpu,cmd --sort=-%cpu | head PID PPID %MEM %CPU CMD 18527 1714 4.2 40.3 /usr/lib/firefox/firefox -contentproc -childID 18 -isForBrowser -prefsLen 10002 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 1714 true tab 1714 1152 5.6 8.0 /usr/lib/firefox/firefox --new-window 18324 1714 4.9 6.3 /usr/lib/firefox/firefox -contentproc -childID 16 -isForBrowser -prefsLen 10002 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 1714 true tab 3286 1714 2.0 5.1 /usr/lib/firefox/firefox -contentproc -childID 14 -isForBrowser -prefsLen 8078 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 1714 true tab 1783 1714 3.0 4.5 /usr/lib/firefox/firefox -contentproc -childID 1 -isForBrowser -prefsLen 1 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 1714 true tab 1227 1152 2.3 2.5 /usr/bin/gnome-shell 1170 1168 3.5 2.2 /usr/lib/Xorg vt2 -displayfd 3 -auth /run/user/1000/gdm/Xauthority -nolisten tcp -background none -noreset -keeptty -verbose 3 16865 1714 2.5 2.1 /usr/lib/firefox/firefox -contentproc -childID 15 -isForBrowser -prefsLen 10002 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 1714 true tab 2179 1714 2.7 1.8 /usr/lib/firefox/firefox -contentproc -childID 6 -isForBrowser -prefsLen 7821 -prefMapSize 213431 -parentBuildID 20191031132559 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 1714 true tab ``` 上面的命令的各部分解释: * `ps`:命令名字 * `-e`:选择所有进程 * `-o`:自定义输出格式 * `–sort=-%cpu`:基于 CPU 使用率对输出结果排序 * `head`:显示结果的前 10 行 * `PID`:进程的 ID * `PPID`:父进程的 ID * `%MEM`:进程使用的 RAM 比例 * `%CPU`:进程占用的 CPU 比例 * `Command`:进程名字 如果你只想看命令名字而不是命令的绝对路径,以运行下面的格式 `ps` 命令: ``` # ps -eo pid,ppid,%mem,%cpu,comm --sort=-%cpu | head PID PPID %MEM %CPU COMMAND 18527 1714 4.1 40.4 Web Content 1714 1152 5.7 8.0 firefox 18324 1714 4.9 6.3 Web Content 3286 1714 2.0 5.1 Web Content 1783 1714 3.0 4.5 Web Content 1227 1152 2.3 2.5 gnome-shell 1170 1168 3.5 2.2 Xorg 16865 1714 2.4 2.1 Web Content 2179 1714 2.7 1.8 Web Content ``` --- via: <https://www.2daygeek.com/how-to-find-high-cpu-consumption-processes-in-linux/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
11,679
Java 与 Python:你应该选择哪个?
https://opensource.com/article/19/12/java-vs-python
2019-12-16T09:50:42
[ "Java", "Python" ]
https://linux.cn/article-11679-1.html
> > 比较世界上最流行的两种编程语言,并在投票中让我们知道你喜欢哪一个。 > > > ![](/data/attachment/album/201912/16/095025dppnl2lgtykgggkt.jpg) 让我们比较一下世界上两种最受欢迎、最强大的编程语言:Java 和 Python!这两种语言有巨大的社区支持和库来执行几乎任何编程任务,尽管选择编程语言通常取决于开发人员的场景。在比较和对比之后,请投票分享你的观点。 ### 是什么? * **Java** 是一门通用面向对象的编程语言,主要用于开发从移动端到 Web 到企业级应用的各种应用。 * **Python** 是一门高级面向对象的编程语言,主要用于 Web 开发、人工智能、机器学习、自动化和其他数据科学应用。 ### 创建者 * **Java** 是由 James Gosling(Sun Microsystems)创造的。 * **Python** 是由 Guido van Rossum 创造的。 ### 开源状态 * **Java** 是免费的,(大部分)开源,但商业用途除外。 * **Python** 对于所有场景都是免费、开源的。 ### 平台依赖 * **Java** 根据它的 WORA (“<ruby> 一次编写,到处运行 <rt> write once, run anywhere </rt></ruby>”)哲学,它是平台无关的。 * **Python** 依赖于平台。 ### 编译或解释 * **Java** 是一门编译语言。Java 程序在编译时转换为字节码,而不是运行时。 * **Python** 是一门解释性语言。Python 程序在运行时进行解释。 ### 文件创建 * **Java**:编译后生成 `<filename>.class` 文件。 * **Python**:在运行期,创建 `<filename>.pyc` 文件。 ### 错误类型 * **Java** 有 2 种错误类型:编译和运行时错误。 * **Python** 有 1 种错误类型:回溯(或运行时)错误。 ### 静态或动态类型 * **Java** 是静态类型。当初始化变量时,需要在程序中指定变量的类型,因为类型检查是在编译时完成的。 * **Python** 是动态类型。变量不需要在初始化时指定类型,因为类型检查是在运行时完成的。 ### 语法 * **Java**:每个语句都需要以分号(`;` )结尾,并且代码块由大括号( `{}` )分隔。 * **Python**:代码块通过缩进分隔(用户可以选择要使用的空格数,但在整个块中应保持一致)。 ### 类的数量 * **Java**:在 Java 中的单个文件中只能存在一个公有顶级类。 * **Python**:Python 中的单个文件中可以存在任意数量的类。 ### 代码多少? * **Java** 通常比 Python 要写更多代码行。 * **Python**通常比 Java 要写更少代码行。 ### 多重继承 * **Java** 不支持多重继承(从两个或多个基类继承)。 * **Python** 支持多重继承,但由于继承复杂性、层次结构、依赖等各种问题,它很少实现。 ### 多线程 * **Java** 多线程可以支持同时运行的两个或多个并发线程。 * **Python** 使用全局解释器锁 (GIL),一次只允许运行单个线程(一个 CPU 核)。 ### 执行速度 * **Java** 的执行时间通常比 Python 快。 * **Python** 的执行时间通常比 Java 慢。 ### Hello world Java 的: ``` public class Hello { public static void main([String][3][] args) { [System][4].out.println("Hello Opensource.com from Java!"); } } ``` Python 的: ``` print("Hello Opensource.com from Java!") ``` ### 运行程序 ![Java vs. Python](/data/attachment/album/201912/16/095053hg3t61o1x441vyrb.png "Java vs. Python") 要运行 java 程序 `Hello.java`,你需要先编译它,这将创建一个 `Hello.class` 文件。只需运行类名 `java Hello`。对于 Python,只需运行文件 `python3 helloworld.py`。 --- via: <https://opensource.com/article/19/12/java-vs-python> 作者:[Archit Modi](https://opensource.com/users/architmodi) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
This article is how I compare the two most popular and powerful programming languages in the world: Java and Python! Both languages have huge community support and libraries to perform almost any programming task, although selecting a programming language usually depends on the developer's use case. After you compare and contrast, please make sure to answer the poll to [share your opinion](#poll) on which is best. ## What is it? **Java**is a general-purpose object-oriented programming language used mostly for developing a wide range of applications from mobile to web to enterprise apps.**Python**is a high-level object-oriented programming language used mostly for web development, artificial intelligence, machine learning, automation, and other data science applications. ## Creator **Java**was created by James Gosling (Sun Microsystems).**Python**was created by Guido van Rossum. ## Open source status **Java**is free and (mostly) open source except for corporate use.**Python**is free and open source for all use cases. ## Platform dependencies **Java**is platform-independent (although JVM isn't) per its WORA ("write once, run anywhere") philosophy.**Python**is platform-dependent. ## Compiled or interpreted **Java**is a compiled language. Java programs are translated to byte code at compile time and not runtime.**Python**is an interpreted language. Python programs are translated at runtime. ## File creation **Java**: After compilation,**<filename>.class**is generated.**Python**: During runtime,**<filename>.pyc**is created. ## Errors types **Java**has**Python**has 1 error type: traceback (or runtime) error. ## Statically or dynamically typed **Java**is statically typed. When initiating variables, their types need to be specified in the program because type checking is done at compile time.**Python**is dynamically typed. Variables don't need to have a type specified when initiated because type checking is done at runtime. ## Syntax **Java**: Every statement needs to end with a semicolon (**;**), and blocks of code are separated by curly braces (**{}**).**Python**: Blocks of code are separated by indentation (the user can choose how many white spaces to use, but it should be consistent throughout the block). ## Number of classes **Java**: Only one public top-level class can exist in a single file in Java.**Python**: Any number of classes can exist in a single file in Python. ## More or less code? **Java**generally involves writing more lines of code compared to Python.**Python**involves writing fewer lines of code compared to Java. ## Multiple inheritance **Java**does not support multiple inheritance (inheriting from two or more base classes)**Python**supports multiple inheritance although it is rarely implemented due to various issues like inheritance complexity, hierarchy, dependency issues, etc. ## Multi-threading **Java**multi-threading can support two or more concurrent threads running at the same time.**Python**uses a global interpreter lock (GIL), allowing only a single thread (CPU core) to run at a time. ## Execution speed **Java**is usually faster in execution time than Python.**Python**is usually slower in execution time than Java. ## Hello world in Java ``` public class Hello { public static void main(String[] args) { System.out.println("Hello Opensource.com from Java!"); } } ``` ## Hello world in Python `print("Hello Opensource.com from Java!")` ## Run the programs ![Java vs. Python Java vs. Python](https://opensource.com/sites/default/files/uploads/python-java-hello-world_0.png) To run the java program "Hello.java" you need to compile it first which creates a "Hello.class" file. To run just the class name, use "java Hello." For Python, you would just run the file "python3 helloworld.py." ## Comments are closed.
11,681
每周开源点评:Kubernetes 傻瓜指南、低代码开发人员和其他行业趋势
https://opensource.com/article/19/12/technology-advice-and-other-industry-trends
2019-12-16T10:55:23
[ "Kubernetes", "低代码" ]
/article-11681-1.html
> > 每周开源社区、市场和行业趋势。 > > > ![Person standing in front of a giant computer screen with numbers, data](/data/attachment/album/201912/16/105530ocd5715c1jjj75ea.png "Person standing in front of a giant computer screen with numbers, data") 作为我在具有开源开发模型的企业软件公司担任高级产品营销经理的角色的一部分,我为产品营销人员、经理和其他影响者定期发布有关开源社区,市场和行业趋势的定期更新。这里有该更新中我和他们最喜欢的四篇文章。 ### Kubernetes 傻瓜指南 * [文章链接](https://www.cbronline.com/feature/an-idiots-guide-to-kubernetes) > > Kubernetes 已经发展出了新的特性,这使其成为企业软件的更好的容器平台。安全性和高级网络等元素已被纳入 Kubernetes 上游代码的主体,并且现在可供所有人使用。 > > > 然而,企业解决方案的其他方面总会有补充需求;比如日志记录和性能监控。这就是像 Istio 等辅助包发挥作用的地方,它带来了额外的功能,但是仍使 Kubernetes 的核心保持了合理的大小和特性集。 > > > **影响**: 我总是发现,人们很容易把对技术发展的认识视为理所当然。当与你打交道的每个人都处于“最前沿”时,你的观点就会歪曲到这样的程度:你甚至可能会认为对最新的(*此处插入首选技术*)一无所知的人跟不上潮流,而实际上这并没有开始影响他们做自己需要做的事情的能力。那些人不是白痴;他们是我们的朋友、客户、合作伙伴、合作者和社区。 ### Gartner: 采用低代码开发之前应该考虑什么 * [文章链接](https://www.computerweekly.com/feature/Gartner-What-to-consider-before-adopting-low-code-development) > > 尽管专注于商业 IT 团队,但 Gartner 发现,一个日益重要的开发人员社区是需要快速开发简单应用程序或构建最低可行产品或多体验功能的核心 IT 专业开发人员。当应用程序领导者在传统的应用程序项目中使用低代码时,他们可能希望使用标准的 IT DevOps 自动化方法和低代码工具。 > > > **影响**: 越来越多的用例和用户体验可以通过需要更少时间和技能来创建的应用程序来处理和交互。而低代码开发人员也可能会结合成一个具有他们自己的规范和亚文化的独特群体。 ### 诺基亚认为云原生对 5G 核心至关重要 * [文章链接](https://www.sdxcentral.com/articles/news/nokia-argues-cloud-native-is-essential-to-5g-core/2019/11/) > > 诺基亚概述了 5G 的五个关键业务目标,这些目标只能通过云原生环境来实现。其中包括:更好的带宽、延迟和密度;通过网络切片将服务扩展到新的企业、行业和[物联网](https://www.sdxcentral.com/5g/iot/ "IoT")市场;根据敏捷性和效率定义的快速服务部署;超越传统带宽、语音和信息传递的新服务;以及利用端到端网络获取更多收入的数字服务的出现。 > > > **影响**: 在越来越多的事物连接到网络的情况下,这是最有意义的。4G 主要与越来越多的手机有关;只有当你开始连接其他所有东西时,5G 才是真正必要的。4G 意味着我们的手机上有更丰富的应用程序,而 5G 几乎与手机无关。 ### API:隐藏的业务加速器 * [文章链接](https://www.cbronline.com/opinion/digital-transformation-3) > > 要想让组织成功地进行数字化转型,API 策略至关重要。从解锁有价值的数据到加快开发时间,API 都是数字时代的幕后英雄。那些已经尝试过 API 的人已经感受到了好处。例如,研究表明,使用 API 的企业中,有 53% 认为它们提高了生产力,而 29% 声称它们的收入增长是使用 API 的直接结果。当 API 被视为存在于一个项目之外的可发现和可重用的产品时,它有助于为持续的变更奠定灵活的基础。 > > > **影响**: 隐藏的业务加速器实际上是这样一种思想,即功能应该以一种方式进行打包,使其能够在原始提供者没有预料到的环境中进行重新利用和组合。 我希望你喜欢这份上周给我留下深刻印象的列表,并于下周一回来了解更多开源社区、市场和行业的趋势。 --- via: <https://opensource.com/article/19/12/technology-advice-and-other-industry-trends> 作者:[Tim Hildred](https://opensource.com/users/thildred) 选题:[lujun9972](https://github.com/lujun9972) 译者:[algzjh](https://github.com/algzjh) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,682
使用 split 命令分割 Linux 文件
https://www.networkworld.com/article/3489256/breaking-linux-files-into-pieces-with-the-split-command.html
2019-12-16T11:11:48
[ "split" ]
https://linux.cn/article-11682-1.html
> > 一些简单的 Linux 命令能让你根据需要分割以及重新组合文件,来适应存储或电子邮件附件大小的限制。 > > > ![Marco Verch](/data/attachment/album/201912/16/111204d5pznhjqi7nxbhzw.jpg) Linux 系统提供了一个非常易于使用的命令来分割文件。在将文件上传到限制大小的存储网站或者作为邮件附件之前,你可能需要执行此操作。要将文件分割为多个文件块,只需使用 `split` 命令。 ``` $ split bigfile ``` 默认情况下,`split` 命令使用非常简单的命名方案。文件块将被命名为 `xaa`、`xab`、`xac` 等,并且,大概地,如果你将足够大的文件分割,你甚至可能会得到名为 `xza` 和 `xzz` 的块。 除非你要求,否则该命令将无任何反馈地运行。但是,如果你想在创建文件块时看到反馈,可以使用 `--verbose` 选项。 ``` $ split –-verbose bigfile creating file 'xaa' creating file 'xab' creating file 'xac' ``` 你还可以给文件命名前缀。例如,要将你原始文件分割并命名为 `bigfile.aa`、`bigfile.ab` 等,你可以将前缀添加到 `split` 命令的末尾,如下所示: ``` $ split –-verbose bigfile bigfile. creating file 'bigfile.aa' creating file 'bigfile.ab' creating file 'bigfile.ac' ``` 请注意,上述命令中显示的前缀的末尾会添加一个点。否则,文件将是 `bigfileaa` 之类的名称,而不是 `bigfile.aa`。 请注意,`split` 命令*不会*删除你的原始文件,只是创建了文件块。如果要指定文件块的大小,可以使用 `-b` 选项将其添加到命令中。例如: ``` $ split -b100M bigfile ``` 文件大小可以是 KB、MB,GB,最大可以是 YB!只需使 K、M、G、T、P、E、Z 和 Y 这些合适的字母。 如果要基于每个块中的行数而不是字节数来拆分文件,那么可以使用 `-l`(行)选项。在此示例中,每个文件将有 1000 行,当然,最后一个文件可能有较少的行。 ``` $ split --verbose -l1000 logfile log. creating file 'log.aa' creating file 'log.ab' creating file 'log.ac' creating file 'log.ad' creating file 'log.ae' creating file 'log.af' creating file 'log.ag' creating file 'log.ah' creating file 'log.ai' creating file 'log.aj' ``` 如果你需要在远程站点上重新组合文件,那么可以使用如下所示的 `cat` 命令轻松地完成此操作: ``` $ cat x?? > original.file $ cat log.?? > original.file ``` 上面所示的分割和组合命令适合于二进制和文本文件。在此示例中,我们将 zip 二进制文件分割为 50KB 的块,之后使用 `cat` 重新组合了它们,然后比较了组合后的文件和原始文件。`diff` 命令验证文件是否相同。 ``` $ split --verbose -b50K zip zip. creating file 'zip.aa' creating file 'zip.ab' creating file 'zip.ac' creating file 'zip.ad' creating file 'zip.ae' $ cat zip.a? > zip.new $ diff zip zip.new $ <== 无输出 = 无差别 ``` 我唯一要提醒的一点的是,如果你经常使用 `split` 并使用默认命名,那么某些文件块可能会覆盖其他的文件块,甚至会比你预期的更多,因为有些是更早之前分割的。 --- via: <https://www.networkworld.com/article/3489256/breaking-linux-files-into-pieces-with-the-split-command.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,684
帮助你排序文本文件的 Awk 命令行或脚本
https://opensource.com/article/19/11/how-sort-awk
2019-12-17T09:53:45
[ "awk" ]
/article-11684-1.html
> > Awk 是一个强大的工具,可以执行某些可能由其它常见实用程序(包括 `sort`)来完成的任务。 > > > ![](/data/attachment/album/201912/17/095222q7m5da4h8facvmtv.jpg) Awk 是个普遍存在的 Unix 命令,用于扫描和处理包含可预测模式的文本。但是,由于它具有函数功能,因此也可以合理地称之为编程语言。 令人困惑的是,有不止一个 awk。(或者,如果你认为只有一个,那么其它几个就是克隆。)有 `awk`(由Aho、Weinberger 和 Kernighan 编写的原始程序),然后有 `nawk` 、`mawk` 和 GNU 版本的 `gawk`。GNU 版本的 awk 是该实用程序的一个高度可移植的自由软件版本,具有几个独特的功能,因此本文是关于 GNU awk 的。 虽然它的正式名称是 `gawk`,但在 GNU+Linux 系统上,它的别名是 `awk`,并用作该命令的默认版本。 在其他没有带有 GNU awk 的系统上,你必须先安装它并将其称为 `gawk`,而不是 `awk`。本文互换使用术语 `awk` 和 `gawk`。 `awk` 既是命令语言又是编程语言,这使其成为一个强大的工具,可以处理原本留给 `sort`、`cut`、`uniq` 和其他常见实用程序的任务。幸运的是,开源中有很多冗余空间,因此,如果你面临是否使用 `awk` 的问题,答案可能是肯定的“随便”。 `awk` 的灵活之美在于,如果你已经确定使用 `awk` 来完成一项任务,那么无论接下来发生什么,你都可以继续使用 `awk`。这包括对数据排序而不是按交付给你的顺序的永恒需求。 ### 样本数据集 在探索 `awk` 的排序方法之前,请生成要使用的样本数据集。保持简单,这样你就不会为极端情况和意想不到的复杂性所困扰。这是本文使用的样本集: ``` Aptenodytes;forsteri;Miller,JF;1778;Emperor Pygoscelis;papua;Wagler;1832;Gentoo Eudyptula;minor;Bonaparte;1867;Little Blue Spheniscus;demersus;Brisson;1760;African Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed Eudyptes;chrysocome;Viellot;1816;Sothern Rockhopper Torvaldis;linux;Ewing,L;1996;Tux ``` 这是一个很小的数据集,但它提供了多种数据类型: * 属名和种名,彼此相关但又是分开的 * 姓,有时是以逗号开头的首字母缩写 * 代表日期的整数 * 任意术语 * 所有字段均以分号分隔 根据你的教育背景,你可能会认为这是二维数组或表格,或者只是行分隔的数据集合。你如何看待它只是你的问题,而 `awk` 只认识文本。由你决定告诉 `awk` 你想如何解析它。 ### 只想排序 如果你只想按特定的可定义字段(例如电子表格中的“单元格”)对文本数据集进行排序,则可以使用 [sort 命令](https://opensource.com/article/19/10/get-sorted-sort)。 ### 字段和记录 无论输入的格式如何,都必须在其中找到模式才可以专注于对你重要的数据部分。在此示例中,数据由两个因素定界:行和字段。每行都代表一个新的*记录*,就如你在电子表格或数据库转储中看到的一样。在每一行中,都有用分号(`;`)分隔的不同的*字段*(将其视为电子表格中的单元格)。 `awk` 一次只处理一条记录,因此,当你在构造发给 `awk` 的这指令时,你可以只关注一行记录。写下你想对一行数据执行的操作,然后在下一行进行测试(无论是心理上还是用 `awk` 进行测试),然后再进行其它的一些测试。最后,你要对你的 `awk` 脚本要处理的数据做好假设,以便可以按你要的数据结构提供给你数据。 在这个例子中,很容易看到每个字段都用分号隔开。为简单起见,假设你要按每行的第一字段对列表进行排序。 在进行排序之前,你必须能够让 `awk` 只关注在每行的第一个字段上,因此这是第一步。终端中 awk 命令的语法为 `awk`,后跟相关选项,最后是要处理的数据文件。 ``` $ awk --field-separator=";" '{print $1;}' penguins.list Aptenodytes Pygoscelis Eudyptula Spheniscus Megadyptes Eudyptes Torvaldis ``` 因为字段分隔符是对 Bash shell 具有特殊含义的字符,所以必须将分号括在引号中或在其前面加上反斜杠。此命令仅用于证明你可以专注于特定字段。你可以使用另一个字段的编号尝试相同的命令,以查看数据的另一个“列”的内容: ``` $ awk --field-separator=";" '{print $3;}' penguins.list Miller,JF Wagler Bonaparte Brisson Milne-Edwards Viellot Ewing,L ``` 我们尚未进行任何排序,但这是良好的基础。 ### 脚本编程 `awk` 不仅仅是命令,它是一种具有索引、数组和函数的编程语言。这很重要,因为这意味着你可以获取要排序的字段列表,将列表存储在内存中,进行处理,然后打印结果数据。对于诸如此类的一系列复杂操作,在文本文件中进行操作会更容易,因此请创建一个名为 `sort.awk` 的新文件并输入以下文本: ``` #!/bin/gawk -f BEGIN { FS=";"; } ``` 这会将该文件建立为 `awk` 脚本,该脚本中包含执行的行。 `BEGIN` 语句是 `awk` 提供的特殊设置功能,用于只需要执行一次的任务。定义内置变量 `FS`,它代表<ruby> 字段分隔符 <rt> field separator </rt></ruby>,并且与你在 `awk` 命令中使用 `--field-separator` 设置的值相同,它只需执行一次,因此它包含在 `BEGIN` 语句中。 #### awk 中的数组 你已经知道如何通过使用 `$` 符号和字段编号来收集特定字段的值,但是在这种情况下,你需要将其存储在数组中而不是将其打印到终端。这是通过 `awk` 数组完成的。`awk` 数组的重要之处在于它包含键和值。 想象一下有关本文的内容;它看起来像这样:`author:"seth",title:"How to sort with awk",length:1200`。诸如作者、标题和长度之类的元素是键,跟着的内容为值。 在排序的上下文中这样做的好处是,你可以将任何字段分配为键,将任何记录分配为值,然后使用内置的 `awk` 函数 `asorti()`(按索引排序)按键进行排序。现在,随便假设你*只*想按第二个字段排序。 *没有*被特殊关键字 `BEGIN` 或 `END` 引起来的 `awk` 语句是在每个记录都要执行的循环。这是脚本的一部分,该脚本扫描数据中的模式并进行相应的处理。每次 `awk` 将注意力转移到一条记录上时,都会执行 `{}` 中的语句(除非以 `BEGIN` 或 `END` 开头)。 要将键和值添加到数组,请创建一个包含数组的变量(在本示例脚本中,我将其称为 `ARRAY`,虽然不是很原汁原味,但很清楚),然后在方括号中分配给它键,用等号(`=`)连接值。 ``` { # dump each field into an array ARRAY[$2] = $R; } ``` 在此语句中,第二个字段的内容(`$2`)用作关键字,而当前记录(`$R`)用作值。 ### asorti() 函数 除了数组之外,`awk` 还具有一些基本函数,你可以将它们用作常见任务的快速简便的解决方案。GNU awk中引入的函数之一 `asorti()` 提供了按键(*索引*)或值对数组进行排序的功能。 你只能在对数组进行填充后对其进行排序,这意味着此操作不能对每个新记录都触发,而只能在脚本的最后阶段进行。为此,`awk` 提供了特殊的 `END` 关键字。与 `BEGIN` 相反,`END` 语句仅在扫描了所有记录之后才触发一次。 将这些添加到你的脚本: ``` END { asorti(ARRAY,SARRAY); # get length j = length(SARRAY); for (i = 1; i &lt;= j; i++) { printf("%s %s\n", SARRAY[i],ARRAY[SARRAY[i]]) } } ``` `asorti()` 函数获取 `ARRAY` 的内容,按索引对其进行排序,然后将结果放入名为 `SARRAY` 的新数组(我在本文中发明的任意名称,表示“排序的 ARRAY”)。 接下来,将变量 `j`(另一个任意名称)分配给 `length()` 函数的结果,该函数计算 `SARRAY` 中的项数。 最后,使用 `for` 循环使用 `printf()` 函数遍历 `SARRAY` 中的每一项,以打印每个键,然后在 `ARRAY` 中打印该键的相应值。 ### 运行该脚本 要运行你的 `awk` 脚本,先使其可执行: ``` $ chmod +x sorter.awk ``` 然后针对 `penguin.list` 示例数据运行它: ``` $ ./sorter.awk penguins.list antipodes Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed chrysocome Eudyptes;chrysocome;Viellot;1816;Sothern Rockhopper demersus Spheniscus;demersus;Brisson;1760;African forsteri Aptenodytes;forsteri;Miller,JF;1778;Emperor linux Torvaldis;linux;Ewing,L;1996;Tux minor Eudyptula;minor;Bonaparte;1867;Little Blue papua Pygoscelis;papua;Wagler;1832;Gentoo ``` 如你所见,数据按第二个字段排序。 这有点限制。最好可以在运行时灵活选择要用作排序键的字段,以便可以在任何数据集上使用此脚本并获得有意义的结果。 ### 添加命令选项 你可以通过在脚本中使用字面值 `var` 将命令变量添加到 `awk` 脚本中。更改脚本,以使迭代子句在创建数组时使用 `var`: ``` { # dump each field into an array ARRAY[$var] = $R; } ``` 尝试运行该脚本,以便在执行脚本时使用 `-v var` 选项将其按第三字段排序: ``` $ ./sorter.awk -v var=3 penguins.list Bonaparte Eudyptula;minor;Bonaparte;1867;Little Blue Brisson Spheniscus;demersus;Brisson;1760;African Ewing,L Torvaldis;linux;Ewing,L;1996;Tux Miller,JF Aptenodytes;forsteri;Miller,JF;1778;Emperor Milne-Edwards Megadyptes;antipodes;Milne-Edwards;1880;Yellow-eyed Viellot Eudyptes;chrysocome;Viellot;1816;Sothern Rockhopper Wagler Pygoscelis;papua;Wagler;1832;Gentoo ``` ### 修正 本文演示了如何在纯 GNU awk 中对数据进行排序。你可以对脚本进行改进,以便对你有用,花一些时间在`gawk` 的手册页上研究 [awk 函数](https://www.gnu.org/software/gawk/manual/html_node/Built_002din.html#Built_002din)并自定义脚本以获得更好的输出。 这是到目前为止的完整脚本: ``` #!/usr/bin/awk -f # GPLv3 appears here # usage: ./sorter.awk -v var=NUM FILE BEGIN { FS=";"; } { # dump each field into an array ARRAY[$var] = $R; } END { asorti(ARRAY,SARRAY); # get length j = length(SARRAY); for (i = 1; i &lt;= j; i++) { printf("%s %s\n", SARRAY[i],ARRAY[SARRAY[i]]) } } ``` --- via: <https://opensource.com/article/19/11/how-sort-awk> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,687
怎样用 Bash 编程:逻辑操作符和 shell 扩展
https://opensource.com/article/19/10/programming-bash-logical-operators-shell-expansions
2019-12-17T17:36:00
[ "脚本", "bash" ]
https://linux.cn/article-11687-1.html
> > 学习逻辑操作符和 shell 扩展,本文是三篇 Bash 编程系列的第二篇。 > > > ![](/data/attachment/album/201912/17/173459pxhz0aiicimzd1m2.jpg) Bash 是一种强大的编程语言,完美契合命令行和 shell 脚本。本系列(三篇文章,基于我的 [三集 Linux 自学课程](http://www.both.org/?page_id=1183))讲解如何在 CLI 使用 Bash 编程。 [第一篇文章](/article-11552-1.html) 讲解了 Bash 的一些简单命令行操作,包括如何使用变量和控制操作符。第二篇文章探讨文件、字符串、数字等类型和各种各样在执行流中提供控制逻辑的的逻辑运算符,还有 Bash 中的各类 shell 扩展。本系列第三篇也是最后一篇文章,将会探索能重复执行操作的 `for` 、`while` 和 `until` 循环。 逻辑操作符是程序中进行判断的根本要素,也是执行不同的语句组合的依据。有时这也被称为流控制。 ### 逻辑操作符 Bash 中有大量的用于不同条件表达式的逻辑操作符。最基本的是 `if` 控制结构,它判断一个条件,如果条件为真,就执行一些程序语句。操作符共有三类:文件、数字和非数字操作符。如果条件为真,所有的操作符返回真值(`0`),如果条件为假,返回假值(`1`)。 这些比较操作符的函数语法是,一个操作符加一个或两个参数放在中括号内,后面跟一系列程序语句,如果条件为真,程序语句执行,可能会有另一个程序语句列表,该列表在条件为假时执行: ``` if [ arg1 operator arg2 ] ; then list 或 if [ arg1 operator arg2 ] ; then list ; else list ; fi ``` 像例子中那样,在比较表达式中,空格不能省略。中括号的每部分,`[` 和 `]`,是跟 `test` 命令一样的传统的 Bash 符号: ``` if test arg1 operator arg2 ; then list ``` 还有一个更新的语法能提供一点点便利,一些系统管理员比较喜欢用。这种格式对于不同版本的 Bash 和一些 shell 如 ksh(Korn shell)兼容性稍差。格式如下: ``` if [[ arg1 operator arg2 ]] ; then list ``` #### 文件操作符 文件操作符是 Bash 中一系列强大的逻辑操作符。图表 1 列出了 20 多种不同的 Bash 处理文件的操作符。在我的脚本中使用频率很高。 | 操作符 | 描述 | | --- | --- | | `-a filename` | 如果文件存在,返回真值;文件可以为空也可以有内容,但是只要它存在,就返回真值 | | `-b filename` | 如果文件存在且是一个块设备,如 `/dev/sda` 或 `/dev/sda1`,则返回真值 | | `-c filename` | 如果文件存在且是一个字符设备,如 `/dev/TTY1`,则返回真值 | | `-d filename` | 如果文件存在且是一个目录,返回真值 | | `-e filename` | 如果文件存在,返回真值;与上面的 `-a` 相同 | | `-f filename` | 如果文件存在且是一个一般文件,不是目录、设备文件或链接等的其他的文件,则返回 真值 | | `-g filename` | 如果文件存在且 `SETGID` 标记被设置在其上,返回真值 | | `-h filename` | 如果文件存在且是一个符号链接,则返回真值 | | `-k filename` | 如果文件存在且粘滞位已设置,则返回真值 | | `-p filename` | 如果文件存在且是一个命名的管道(FIFO),返回真值 | | `-r filename` | 如果文件存在且有可读权限(它的可读位被设置),返回真值 | | `-s filename` | 如果文件存在且大小大于 0,返回真值;如果一个文件存在但大小为 0,则返回假值 | | `-t fd` | 如果文件描述符 `fd` 被打开且被关联到一个终端设备上,返回真值 | | `-u filename` | 如果文件存在且它的 `SETUID` 位被设置,返回真值 | | `-w filename` | 如果文件存在且有可写权限,返回真值 | | `-x filename` | 如果文件存在且有可执行权限,返回真值 | | `-G filename` | 如果文件存在且文件的组 ID 与当前用户相同,返回真值 | | `-L filename` | 如果文件存在且是一个符号链接,返回真值(同 `-h`) | | `-N filename` | 如果文件存在且从文件上一次被读取后文件被修改过,返回真值 | | `-O filename` | 如果文件存在且你是文件的拥有者,返回真值 | | `-S filename` | 如果文件存在且文件是套接字,返回真值 | | `file1 -ef file2` | 如果文件 `file1` 和文件 `file2` 指向同一设备的同一 INODE 号,返回真值(即硬链接) | | `file1 -nt file2` | 如果文件 `file1` 比 `file2` 新(根据修改日期),或 `file1` 存在而 `file2` 不存在,返回真值 | | `file1 -ot file2` | 如果文件 `file1` 比 `file2` 旧(根据修改日期),或 `file1` 不存在而 `file2` 存在 | *图表 1:Bash 文件操作符* 以测试一个文件存在与否来举例: ``` [student@studentvm1 testdir]$ File="TestFile1" ; if [ -e $File ] ; then echo "The file $File exists." ; else echo "The file $File does not exist." ; fi The file TestFile1 does not exist. [student@studentvm1 testdir]$ ``` 创建一个用来测试的文件,命名为 `TestFile1`。目前它不需要包含任何数据: ``` [student@studentvm1 testdir]$ touch TestFile1 ``` 在这个简短的 CLI 程序中,修改 `$File` 变量的值相比于在多个地方修改表示文件名的字符串的值要容易: ``` [student@studentvm1 testdir]$ File="TestFile1" ; if [ -e $File ] ; then echo "The file $File exists." ; else echo "The file $File does not exist." ; fi The file TestFile1 exists. [student@studentvm1 testdir]$ ``` 现在,运行一个测试来判断一个文件是否存在且长度不为 0(表示它包含数据)。假设你想判断三种情况: 1. 文件不存在; 2. 文件存在且为空; 3. 文件存在且包含数据。 因此,你需要一组更复杂的测试代码 — 为了测试所有的情况,使用 `if-elif-else` 结构中的 `elif` 语句: ``` [student@studentvm1 testdir]$ File="TestFile1" ; if [ -s $File ] ; then echo "$File exists and contains data." ; fi [student@studentvm1 testdir]$ ``` 在这个情况中,文件存在但不包含任何数据。向文件添加一些数据再运行一次: ``` [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is file $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; fi TestFile1 exists and contains data. [student@studentvm1 testdir]$ ``` 这组语句能返回正常的结果,但是仅仅是在我们已知三种可能的情况下测试某种确切的条件。添加一段 `else` 语句,这样你就可以更精确地测试。把文件删掉,你就可以完整地测试这段新代码: ``` [student@studentvm1 testdir]$ File="TestFile1" ; rm $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi TestFile1 does not exist or is empty. ``` 现在创建一个空文件用来测试: ``` [student@studentvm1 testdir]$ File="TestFile1" ; touch $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi TestFile1 does not exist or is empty. ``` 向文件添加一些内容,然后再测试一次: ``` [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is file $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi TestFile1 exists and contains data. ``` 现在加入 `elif` 语句来辨别是文件不存在还是文件为空: ``` [student@studentvm1 testdir]$ File="TestFile1" ; touch $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; elif [ -e $File ] ; then echo "$File exists and is empty." ; else echo "$File does not exist." ; fi TestFile1 exists and is empty. [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; elif [ -e $File ] ; then echo "$File exists and is empty." ; else echo "$File does not exist." ; fi TestFile1 exists and contains data. [student@studentvm1 testdir]$ ``` 现在你有一个可以测试这三种情况的 Bash CLI 程序,但是可能的情况是无限的。 如果你能像保存在文件中的脚本那样组织程序语句,那么即使对于更复杂的命令组合也会很容易看出它们的逻辑结构。图表 2 就是一个示例。 `if-elif-else` 结构中每一部分的程序语句的缩进让逻辑更变得清晰。 ``` File="TestFile1" echo "This is $File" > $File if [ -s $File ] then echo "$File exists and contains data." elif [ -e $File ] then echo "$File exists and is empty." else echo "$File does not exist." fi ``` *图表 2: 像在脚本里一样重写书写命令行程序* 对于大多数 CLI 程序来说,让这些复杂的命令变得有逻辑需要写很长的代码。虽然 CLI 可能是用 Linux 或 Bash 内置的命令,但是当 CLI 程序很长或很复杂时,创建一个保存在文件中的脚本将更有效,保存到文件中后,可以随时运行。 #### 字符串比较操作符 字符串比较操作符使我们可以对字符串中的字符按字母顺序进行比较。图表 3 列出了仅有的几个字符串比较操作符。 | 操作符 | 描述 | | --- | --- | | `-z string` | 如果字符串的长度为 0 ,返回真值 | | `-n string` | 如果字符串的长度不为 0 ,返回真值 | | `string1 == string2` 或 `string1 = string2` | 如果两个字符串相等,返回真值。处于遵从 POSIX 一致性,在测试命令中应使用一个等号 `=`。与命令 `[[` 一起使用时,会进行如上描述的模式匹配(混合命令)。 | | `string1 != string2` | 两个字符串不相等,返回真值 | | `string1 < string2` | 如果对 `string1` 和 `string2` 按字母顺序进行排序,`string1` 排在 `string2` 前面(即基于地区设定的对所有字母和特殊字符的排列顺序) | | `string1 > string2` | 如果对 `string1` 和 `string2` 按字母顺序进行排序,`string1` 排在 `string2` 后面 | *图表 3: Bash 字符串逻辑操作符* 首先,检查字符串长度。比较表达式中 `$MyVar` 两边的双引号不能省略(你仍应该在目录 `~/testdir` 下 )。 ``` [student@studentvm1 testdir]$ MyVar="" ; if [ -z "" ] ; then echo "MyVar is zero length." ; else echo "MyVar contains data" ; fi MyVar is zero length. [student@studentvm1 testdir]$ MyVar="Random text" ; if [ -z "" ] ; then echo "MyVar is zero length." ; else echo "MyVar contains data" ; fi MyVar is zero length. ``` 你也可以这样做: ``` [student@studentvm1 testdir]$ MyVar="Random text" ; if [ -n "$MyVar" ] ; then echo "MyVar contains data." ; else echo "MyVar is zero length" ; fi MyVar contains data. [student@studentvm1 testdir]$ MyVar="" ; if [ -n "$MyVar" ] ; then echo "MyVar contains data." ; else echo "MyVar is zero length" ; fi MyVar is zero length ``` 有时候你需要知道一个字符串确切的长度。这虽然不是比较,但是也与比较相关。不幸的是,计算字符串的长度没有简单的方法。有很多种方法可以计算,但是我认为使用 `expr`(求值表达式)命令是相对最简单的一种。阅读 `expr` 的手册页可以了解更多相关知识。注意表达式中你检测的字符串或变量两边的引号不要省略。 ``` [student@studentvm1 testdir]$ MyVar="" ; expr length "$MyVar" 0 [student@studentvm1 testdir]$ MyVar="How long is this?" ; expr length "$MyVar" 17 [student@studentvm1 testdir]$ expr length "We can also find the length of a literal string as well as a variable." 70 ``` 关于比较操作符,在我们的脚本中使用了大量的检测两个字符串是否相等(例如,两个字符串是否实际上是同一个字符串)的操作。我使用的是非 POSIX 版本的比较表达式: ``` [student@studentvm1 testdir]$ Var1="Hello World" ; Var2="Hello World" ; if [ "$Var1" == "$Var2" ] ; then echo "Var1 matches Var2" ; else echo "Var1 and Var2 do not match." ; fi Var1 matches Var2 [student@studentvm1 testdir]$ Var1="Hello World" ; Var2="Hello world" ; if [ "$Var1" == "$Var2" ] ; then echo "Var1 matches Var2" ; else echo "Var1 and Var2 do not match." ; fi Var1 and Var2 do not match. ``` 在你自己的脚本中去试一下这些操作符。 #### 数字比较操作符 数字操作符用于两个数字参数之间的比较。像其他类操作符一样,大部分都很容易理解。 | 操作符 | 描述 | | --- | --- | | `arg1 -eq arg2` | 如果 `arg1` 等于 `arg2`,返回真值 | | `arg1 -ne arg2` | 如果 `arg1` 不等于 `arg2`,返回真值 | | `arg1 -lt arg2` | 如果 `arg1` 小于 `arg2`,返回真值 | | `arg1 -le arg2` | 如果 `arg1` 小于或等于 `arg2`,返回真值 | | `arg1 -gt arg2` | 如果 `arg1` 大于 `arg2`,返回真值 | | `arg1 -ge arg2` | 如果 `arg1` 大于或等于 `arg2`,返回真值 | *图表 4: Bash 数字比较逻辑操作符* 来看几个简单的例子。第一个示例设置变量 `$X` 的值为 1,然后检测 `$X` 是否等于 1。第二个示例中,`$X` 被设置为 0,所以比较表达式返回结果不为真值。 ``` [student@studentvm1 testdir]$ X=1 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi X equals 1 [student@studentvm1 testdir]$ X=0 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi X does not equal 1 [student@studentvm1 testdir]$ ``` 自己来多尝试一下其他的。 #### 杂项操作符 这些杂项操作符展示一个 shell 选项是否被设置,或一个 shell 变量是否有值,但是它不显示变量的值,只显示它是否有值。 | 操作符 | 描述 | | --- | --- | | `-o optname` | 如果一个 shell 选项 `optname` 是启用的(查看内建在 Bash 手册页中的 set `-o` 选项描述下面的选项列表),则返回真值 | | `-v varname` | 如果 shell 变量 `varname` 被设置了值(被赋予了值),则返回真值 | | `-R varname` | 如果一个 shell 变量 `varname` 被设置了值且是一个名字引用,则返回真值 | *图表 5: 杂项 Bash 逻辑操作符* 自己来使用这些操作符实践下。 ### 扩展 Bash 支持非常有用的几种类型的扩展和命令替换。根据 Bash 手册页,Bash 有七种扩展格式。本文只介绍其中五种:`~` 扩展、算术扩展、路径名称扩展、大括号扩展和命令替换。 #### 大括号扩展 大括号扩展是生成任意字符串的一种方法。(下面的例子是用特定模式的字符创建大量的文件。)大括号扩展可以用于产生任意字符串的列表,并把它们插入一个用静态字符串包围的特定位置或静态字符串的两端。这可能不太好想象,所以还是来实践一下。 首先,看一下大括号扩展的作用: ``` [student@studentvm1 testdir]$ echo {string1,string2,string3} string1 string2 string3 ``` 看起来不是很有用,对吧?但是用其他方式使用它,再来看看: ``` [student@studentvm1 testdir]$ echo "Hello "{David,Jen,Rikki,Jason}. Hello David. Hello Jen. Hello Rikki. Hello Jason. ``` 这看起来貌似有点用了 — 我们可以少打很多字。现在试一下这个: ``` [student@studentvm1 testdir]$ echo b{ed,olt,ar}s beds bolts bars ``` 我可以继续举例,但是你应该已经理解了它的用处。 #### ~ 扩展 资料显示,使用最多的扩展是波浪字符(`~`)扩展。当你在命令中使用它(如 `cd ~/Documents`)时,Bash shell 把这个快捷方式展开成用户的完整的家目录。 使用这个 Bash 程序观察 `~` 扩展的作用: ``` [student@studentvm1 testdir]$ echo ~ /home/student [student@studentvm1 testdir]$ echo ~/Documents /home/student/Documents [student@studentvm1 testdir]$ Var1=~/Documents ; echo $Var1 ; cd $Var1 /home/student/Documents [student@studentvm1 Documents]$ ``` #### 路径名称扩展 路径名称扩展是展开文件通配模式为匹配该模式的完整路径名称的另一种说法,匹配字符使用 `?` 和 `*`。文件通配指的是在大量操作中匹配文件名、路径和其他字符串时用特定的模式字符产生极大的灵活性。这些特定的模式字符允许匹配字符串中的一个、多个或特定字符。 * `?` — 匹配字符串中特定位置的一个任意字符 * `*` — 匹配字符串中特定位置的 0 个或多个任意字符 这个扩展用于匹配路径名称。为了弄清它的用法,请确保 `testdir` 是当前工作目录(`PWD`),先执行基本的列出清单命令 `ls`(我家目录下的内容跟你的不一样)。 ``` [student@studentvm1 testdir]$ ls chapter6 cpuHog.dos dmesg1.txt Documents Music softlink1 testdir6 Videos chapter7 cpuHog.Linux dmesg2.txt Downloads Pictures Templates testdir testdir cpuHog.mac dmesg3.txt file005 Public testdir tmp cpuHog Desktop dmesg.txt link3 random.txt testdir1 umask.test [student@studentvm1 testdir]$ ``` 现在列出以 `Do`、`testdir/Documents` 和 `testdir/Downloads` 开头的目录: ``` Documents: Directory01 file07 file15 test02 test10 test20 testfile13 TextFiles Directory02 file08 file16 test03 test11 testfile01 testfile14 file01 file09 file17 test04 test12 testfile04 testfile15 file02 file10 file18 test05 test13 testfile05 testfile16 file03 file11 file19 test06 test14 testfile09 testfile17 file04 file12 file20 test07 test15 testfile10 testfile18 file05 file13 Student1.txt test08 test16 testfile11 testfile19 file06 file14 test01 test09 test18 testfile12 testfile20 Downloads: [student@studentvm1 testdir]$ ``` 然而,并没有得到你期望的结果。它列出了以 `Do` 开头的目录下的内容。使用 `-d` 选项,仅列出目录而不列出它们的内容。 ``` [student@studentvm1 testdir]$ ls -d Do* Documents Downloads [student@studentvm1 testdir]$ ``` 在两个例子中,Bash shell 都把 `Do*` 模式展开成了匹配该模式的目录名称。但是如果有文件也匹配这个模式,会发生什么? ``` [student@studentvm1 testdir]$ touch Downtown ; ls -d Do* Documents Downloads Downtown [student@studentvm1 testdir]$ ``` 因此所有匹配这个模式的文件也被展开成了完整名字。 #### 命令替换 命令替换是让一个命令的标准输出数据流被当做参数传给另一个命令的扩展形式,例如,在一个循环中作为一系列被处理的项目。Bash 手册页显示:“命令替换可以让你用一个命令的输出替换为命令的名字。”这可能不太好理解。 命令替换有两种格式:``command`` 和 `$(command)`。在更早的格式中使用反引号(```),在命令中使用反斜杠(`\`)来保持它转义之前的文本含义。然而,当用在新版本的括号格式中时,反斜杠被当做一个特殊字符处理。也请注意带括号的格式打开个关闭命令语句都是用一个括号。 我经常在命令行程序和脚本中使用这种能力,一个命令的结果能被用作另一个命令的参数。 来看一个非常简单的示例,这个示例使用了这个扩展的两种格式(再一次提醒,确保 `testdir` 是当前工作目录): ``` [student@studentvm1 testdir]$ echo "Todays date is `date`" Todays date is Sun Apr 7 14:42:46 EDT 2019 [student@studentvm1 testdir]$ echo "Todays date is $(date)" Todays date is Sun Apr 7 14:42:59 EDT 2019 [student@studentvm1 testdir]$ ``` `-seq` 工具用于一个数字序列: ``` [student@studentvm1 testdir]$ seq 5 1 2 3 4 5 [student@studentvm1 testdir]$ echo `seq 5` 1 2 3 4 5 [student@studentvm1 testdir]$ ``` 现在你可以做一些更有用处的操作,比如创建大量用于测试的空文件。 ``` [student@studentvm1 testdir]$ for I in $(seq -w 5000) ; do touch file-$I ; done ``` `seq` 工具加上 `-w` 选项后,在生成的数字前面会用 0 补全,这样所有的结果都等宽,例如,忽略数字的值,它们的位数一样。这样在对它们按数字顺序进行排列时很容易。 `seq -w 5000` 语句生成了 1 到 5000 的数字序列。通过把命令替换用于 `for` 语句,`for` 语句就可以使用该数字序列来生成文件名的数字部分。 #### 算术扩展 Bash 可以进行整型的数学计算,但是比较繁琐(你一会儿将看到)。数字扩展的语法是 `$((arithmetic-expression))` ,分别用两个括号来打开和关闭表达式。算术扩展在 shell 程序或脚本中类似命令替换;表达式结算后的结果替换了表达式,用于 shell 后续的计算。 我们再用一个简单的用法来开始: ``` [student@studentvm1 testdir]$ echo $((1+1)) 2 [student@studentvm1 testdir]$ Var1=5 ; Var2=7 ; Var3=$((Var1*Var2)) ; echo "Var 3 = $Var3" Var 3 = 35 ``` 下面的除法结果是 0,因为表达式的结果是一个小于 1 的整型数字: ``` [student@studentvm1 testdir]$ Var1=5 ; Var2=7 ; Var3=$((Var1/Var2)) ; echo "Var 3 = $Var3" Var 3 = 0 ``` 这是一个我经常在脚本或 CLI 程序中使用的一个简单的计算,用来查看在 Linux 主机中使用了多少虚拟内存。 `free` 不提供我需要的数据: ``` [student@studentvm1 testdir]$ RAM=`free | grep ^Mem | awk '{print $2}'` ; Swap=`free | grep ^Swap | awk '{print $2}'` ; echo "RAM = $RAM and Swap = $Swap" ; echo "Total Virtual memory is $((RAM+Swap))" ; RAM = 4037080 and Swap = 6291452 Total Virtual memory is 10328532 ``` 我使用 ``` 字符来划定用作命令替换的界限。 我用 Bash 算术扩展的场景主要是用脚本检查系统资源用量后基于返回的结果选择一个程序运行的路径。 ### 总结 本文是 Bash 编程语言系列的第二篇,探讨了 Bash 中文件、字符串、数字和各种提供流程控制逻辑的逻辑操作符还有不同种类的 shell 扩展。 --- via: <https://opensource.com/article/19/10/programming-bash-logical-operators-shell-expansions> 作者:[David Both](https://opensource.com/users/dboth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Bash is a powerful programming language, one perfectly designed for use on the command line and in shell scripts. This three-part series (which is based on my [three-volume Linux self-study course](http://www.both.org/?page_id=1183)) explores using Bash as a programming language on the command-line interface (CLI). The [first article](https://opensource.com/article/19/10/programming-bash-part-1) explored some simple command-line programming with Bash, including using variables and control operators. This second article looks into the types of file, string, numeric, and miscellaneous logical operators that provide execution-flow control logic and different types of shell expansions in Bash. The third and final article in the series will explore the **for**, **while**, and **until** loops that enable repetitive operations. Logical operators are the basis for making decisions in a program and executing different sets of instructions based on those decisions. This is sometimes called flow control. ## Logical operators Bash has a large set of logical operators that can be used in conditional expressions. The most basic form of the **if** control structure tests for a condition and then executes a list of program statements if the condition is true. There are three types of operators: file, numeric, and non-numeric operators. Each operator returns true (0) if the condition is met and false (1) if the condition is not met. The functional syntax of these comparison operators is one or two arguments with an operator that are placed within square braces, followed by a list of program statements that are executed if the condition is true, and an optional list of program statements if the condition is false: ``` if [ arg1 operator arg2 ] ; then list or if [ arg1 operator arg2 ] ; then list ; else list ; fi ``` The spaces in the comparison are required as shown. The single square braces, **[** and **]**, are the traditional Bash symbols that are equivalent to the **test** command: `if test arg1 operator arg2 ; then list` There is also a more recent syntax that offers a few advantages and that some sysadmins prefer. This format is a bit less compatible with different versions of Bash and other shells, such as ksh (the Korn shell). It looks like: `if [[ arg1 operator arg2 ]] ; then list` ### File operators File operators are a powerful set of logical operators within Bash. Figure 1 lists more than 20 different operators that Bash can perform on files. I use them quite frequently in my scripts. Operator | Description | ---|---| -a filename | True if the file exists; it can be empty or have some content but, so long as it exists, this will be true | -b filename | True if the file exists and is a block special file such as a hard drive like /dev/sda or /dev/sda1 | -c filename | True if the file exists and is a character special file such as a TTY device like /dev/TTY1 | -d filename | True if the file exists and is a directory | -e filename | True if the file exists; this is the same as -a above | -f filename | True if the file exists and is a regular file, as opposed to a directory, a device special file, or a link, among others | -g filename | True if the file exists and is set-group-id, SETGID | -h filename | True if the file exists and is a symbolic link | -k filename | True if the file exists and its "sticky'" bit is set | -p filename | True if the file exists and is a named pipe (FIFO) | -r filename | True if the file exists and is readable, i.e., has its read bit set | -s filename | True if the file exists and has a size greater than zero; a file that exists but that has a size of zero will return false | -t fd | True if the file descriptor fd is open and refers to a terminal | -u filename | True if the file exists and its set-user-id bit is set | -w filename | True if the file exists and is writable | -x filename | True if the file exists and is executable | -G filename | True if the file exists and is owned by the effective group ID | -L filename | True if the file exists and is a symbolic link | -N filename | True if the file exists and has been modified since it was last read | -O filename | True if the file exists and is owned by the effective user ID | -S filename | True if the file exists and is a socket | file1 -ef file2 | True if file1 and file2 refer to the same device and iNode numbers | file1 -nt file2 | True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not | file1 -ot file2 | True if file1 is older than file2, or if file2 exists and file1 does not | *Fig. 1: The Bash file operators* As an example, start by testing for the existence of a file: ``` [student@studentvm1 testdir]$ File="TestFile1" ; if [ -e $File ] ; then echo "The file $File exists." ; else echo "The file $File does not exist." ; fi The file TestFile1 does not exist. [student@studentvm1 testdir]$ ``` Next, create a file for testing named **TestFile1**. For now, it does not need to contain any data: `[student@studentvm1 testdir]$ touch TestFile1` It is easy to change the value of the **$File** variable rather than a text string for the file name in multiple locations in this short CLI program: ``` [student@studentvm1 testdir]$ File="TestFile1" ; if [ -e $File ] ; then echo "The file $File exists." ; else echo "The file $File does not exist." ; fi The file TestFile1 exists. [student@studentvm1 testdir]$ ``` Now, run a test to determine whether a file exists and has a non-zero length, which means it contains data. You want to test for three conditions: 1. the file does not exist; 2. the file exists and is empty; and 3. the file exists and contains data. Therefore, you need a more complex set of tests—use the **elif** stanza in the **if-elif-else** construct to test for all of the conditions: ``` [student@studentvm1 testdir]$ File="TestFile1" ; if [ -s $File ] ; then echo "$File exists and contains data." ; fi [student@studentvm1 testdir]$ ``` In this case, the file exists but does not contain any data. Add some data and try again: ``` [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is file $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; fi TestFile1 exists and contains data. [student@studentvm1 testdir]$ ``` That works, but it is only truly accurate for one specific condition out of the three possible ones. Add an **else** stanza so you can be somewhat more accurate, and delete the file so you can fully test this new code: ``` [student@studentvm1 testdir]$ File="TestFile1" ; rm $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi TestFile1 does not exist or is empty. ``` Now create an empty file to test: ``` [student@studentvm1 testdir]$ File="TestFile1" ; touch $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi TestFile1 does not exist or is empty. ``` Add some content to the file and test again: ``` [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is file $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi TestFile1 exists and contains data. ``` Now, add the **elif** stanza to discriminate between a file that does not exist and one that is empty: ``` [student@studentvm1 testdir]$ File="TestFile1" ; touch $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; elif [ -e $File ] ; then echo "$File exists and is empty." ; else echo "$File does not exist." ; fi TestFile1 exists and is empty. [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; elif [ -e $File ] ; then echo "$File exists and is empty." ; else echo "$File does not exist." ; fi TestFile1 exists and contains data. [student@studentvm1 testdir]$ ``` Now you have a Bash CLI program that can test for these three different conditions… but the possibilities are endless. It is easier to see the logic structure of the more complex compound commands if you arrange the program statements more like you would in a script that you can save in a file. Figure 2 shows how this would look. The indents of the program statements in each stanza of the **if-elif-else** structure help to clarify the logic. ``` File="TestFile1" echo "This is $File" > $File if [ -s $File ] then echo "$File exists and contains data." elif [ -e $File ] then echo "$File exists and is empty." else echo "$File does not exist." fi ``` *Fig. 2: The command line program rewritten as it would appear in a script* Logic this complex is too lengthy for most CLI programs. Although any Linux or Bash built-in commands may be used in CLI programs, as the CLI programs get longer and more complex, it makes more sense to create a script that is stored in a file and can be executed at any time, now or in the future. ### String comparison operators String comparison operators enable the comparison of alphanumeric strings of characters. There are only a few of these operators, which are listed in Figure 3. Operator | Description | ---|---| -z string | True if the length of string is zero | -n string | True if the length of string is non-zero | string1 == string2 or string1 = string2 | True if the strings are equal; a single = should be used with the test command for POSIX conformance. When used with the [[ command, this performs pattern matching as described above (compound commands). | string1 != string2 | True if the strings are not equal | string1 < string2 | True if string1 sorts before string2 lexicographically (refers to locale-specific sorting sequences for all alphanumeric and special characters) | string1 > string2 | True if string1 sorts after string2 lexicographically | **Fig. 3: Bash string logical operators** First, look at string length. The quotes around **$MyVar** in the comparison must be there for the comparison to work. (You should still be working in **~/testdir**.) ``` [student@studentvm1 testdir]$ MyVar="" ; if [ -z "" ] ; then echo "MyVar is zero length." ; else echo "MyVar contains data" ; fi MyVar is zero length. [student@studentvm1 testdir]$ MyVar="Random text" ; if [ -z "" ] ; then echo "MyVar is zero length." ; else echo "MyVar contains data" ; fi MyVar is zero length. ``` You could also do it this way: ``` [student@studentvm1 testdir]$ MyVar="Random text" ; if [ -n "$MyVar" ] ; then echo "MyVar contains data." ; else echo "MyVar is zero length" ; fi MyVar contains data. [student@studentvm1 testdir]$ MyVar="" ; if [ -n "$MyVar" ] ; then echo "MyVar contains data." ; else echo "MyVar is zero length" ; fi MyVar is zero length ``` Sometimes you may need to know a string's exact length. This is not a comparison, but it is related. Unfortunately, there is no simple way to determine the length of a string. There are a couple of ways to do it, but I think using the **expr** (evaluate expression) command is easiest. Read the man page for **expr** for more about what it can do. Note that quotes are required around the string or variable you're testing. ``` [student@studentvm1 testdir]$ MyVar="" ; expr length "$MyVar" 0 [student@studentvm1 testdir]$ MyVar="How long is this?" ; expr length "$MyVar" 17 [student@studentvm1 testdir]$ expr length "We can also find the length of a literal string as well as a variable." 70 ``` Regarding comparison operators, I use a lot of testing in my scripts to determine whether two strings are equal (i.e., identical). I use the non-POSIX version of this comparison operator: ``` [student@studentvm1 testdir]$ Var1="Hello World" ; Var2="Hello World" ; if [ "$Var1" == "$Var2" ] ; then echo "Var1 matches Var2" ; else echo "Var1 and Var2 do not match." ; fi Var1 matches Var2 [student@studentvm1 testdir]$ Var1="Hello World" ; Var2="Hello world" ; if [ "$Var1" == "$Var2" ] ; then echo "Var1 matches Var2" ; else echo "Var1 and Var2 do not match." ; fi Var1 and Var2 do not match. ``` Experiment some more on your own to try out these operators. ### Numeric comparison operators Numeric operators make comparisons between two numeric arguments. Like the other operator classes, most are easy to understand. Operator | Description | ---|---| arg1 -eq arg2 | True if arg1 equals arg2 | arg1 -ne arg2 | True if arg1 is not equal to arg2 | arg1 -lt arg2 | True if arg1 is less than arg2 | arg1 -le arg2 | True if arg1 is less than or equal to arg2 | arg1 -gt arg2 | True if arg1 is greater than arg2 | arg1 -ge arg2 | True if arg1 is greater than or equal to arg2 | *Fig. 4: Bash numeric comparison logical operators* Here are some simple examples. The first instance sets the variable **$X** to 1, then tests to see if **$X** is equal to 1. In the second instance, **X** is set to 0, so the comparison is not true. ``` [student@studentvm1 testdir]$ X=1 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi X equals 1 [student@studentvm1 testdir]$ X=0 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi X does not equal 1 [student@studentvm1 testdir]$ ``` Try some more experiments on your own. ### Miscellaneous operators These miscellaneous operators show whether a shell option is set or a shell variable has a value, but it does not discover the value of the variable, just whether it has one. Operator | Description | ---|---| -o optname | True if the shell option optname is enabled (see the list of options under the description of the -o option to the Bash set builtin in the Bash man page) | -v varname | True if the shell variable varname is set (has been assigned a value) | -R varname | True if the shell variable varname is set and is a name reference | **Fig. 5: Miscellaneous Bash logical operators** Experiment on your own to try out these operators. ## Expansions Bash supports a number of types of expansions and substitutions that can be quite useful. According to the Bash man page, Bash has seven forms of expansions. This article looks at five of them: tilde expansion, arithmetic expansion, pathname expansion, brace expansion, and command substitution. ### Brace expansion Brace expansion is a method for generating arbitrary strings. (This tool is used below to create a large number of files for experiments with special pattern characters.) Brace expansion can be used to generate lists of arbitrary strings and insert them into a specific location within an enclosing static string or at either end of a static string. This may be hard to visualize, so it's best to just do it. First, here's what a brace expansion does: ``` [student@studentvm1 testdir]$ echo {string1,string2,string3} string1 string2 string3 ``` Well, that is not very helpful, is it? But look what happens when you use it just a bit differently: ``` [student@studentvm1 testdir]$ echo "Hello "{David,Jen,Rikki,Jason}. Hello David. Hello Jen. Hello Rikki. Hello Jason. ``` That looks like something useful—it could save a good deal of typing. Now try this: ``` [student@studentvm1 testdir]$ echo b{ed,olt,ar}s beds bolts bars ``` I could go on, but you get the idea. ### Tilde expansion Arguably, the most common expansion is the tilde (**~**) expansion. When you use this in a command like **cd ~/Documents**, the Bash shell expands it as a shortcut to the user's full home directory. Use these Bash programs to observe the effects of the tilde expansion: ``` [student@studentvm1 testdir]$ echo ~ /home/student [student@studentvm1 testdir]$ echo ~/Documents /home/student/Documents [student@studentvm1 testdir]$ Var1=~/Documents ; echo $Var1 ; cd $Var1 /home/student/Documents [student@studentvm1 Documents]$ ``` ### Pathname expansion Pathname expansion is a fancy term expanding file-globbing patterns, using the characters **?** and *****, into the full names of directories that match the pattern. File globbing refers to special pattern characters that enable significant flexibility in matching file names, directories, and other strings when performing various actions. These special pattern characters allow matching single, multiple, or specific characters in a string. **?**— Matches only one of any character in the specified location within the string*****— Matches zero or more of any character in the specified location within the string This expansion is applied to matching directory names. To see how this works, ensure that **testdir** is the present working directory (PWD) and start with a plain listing (the contents of my home directory will be different from yours): ``` [student@studentvm1 testdir]$ ls chapter6 cpuHog.dos dmesg1.txt Documents Music softlink1 testdir6 Videos chapter7 cpuHog.Linux dmesg2.txt Downloads Pictures Templates testdir testdir cpuHog.mac dmesg3.txt file005 Public testdir tmp cpuHog Desktop dmesg.txt link3 random.txt testdir1 umask.test [student@studentvm1 testdir]$ ``` Now list the directories that start with **Do**, **testdir/Documents**, and **testdir/Downloads**: ``` Documents: Directory01 file07 file15 test02 test10 test20 testfile13 TextFiles Directory02 file08 file16 test03 test11 testfile01 testfile14 file01 file09 file17 test04 test12 testfile04 testfile15 file02 file10 file18 test05 test13 testfile05 testfile16 file03 file11 file19 test06 test14 testfile09 testfile17 file04 file12 file20 test07 test15 testfile10 testfile18 file05 file13 Student1.txt test08 test16 testfile11 testfile19 file06 file14 test01 test09 test18 testfile12 testfile20 Downloads: [student@studentvm1 testdir]$ ``` Well, that did not do what you wanted. It listed the contents of the directories that begin with **Do**. To list only the directories and not their contents, use the **-d** option. ``` [student@studentvm1 testdir]$ ls -d Do* Documents Downloads [student@studentvm1 testdir]$ ``` In both cases, the Bash shell expands the **Do*** pattern into the names of the two directories that match the pattern. But what if there are also files that match the pattern? ``` [student@studentvm1 testdir]$ touch Downtown ; ls -d Do* Documents Downloads Downtown [student@studentvm1 testdir]$ ``` This shows the file, too. So any files that match the pattern are also expanded to their full names. ### Command substitution Command substitution is a form of expansion that allows the STDOUT data stream of one command to be used as the argument of another command; for example, as a list of items to be processed in a loop. The Bash man page says: "Command substitution allows the output of a command to replace the command name." I find that to be accurate if a bit obtuse. There are two forms of this substitution, **`command`** and **$(command)**. In the older form using back tics (**`**), using a backslash (**\**) in the command retains its literal meaning. However, when it's used in the newer parenthetical form, the backslash takes on its meaning as a special character. Note also that the parenthetical form uses only single parentheses to open and close the command statement. I frequently use this capability in command-line programs and scripts where the results of one command can be used as an argument for another command. Start with a very simple example that uses both forms of this expansion (again, ensure that **testdir** is the PWD): ``` [student@studentvm1 testdir]$ echo "Todays date is `date`" Todays date is Sun Apr 7 14:42:46 EDT 2019 [student@studentvm1 testdir]$ echo "Todays date is $(date)" Todays date is Sun Apr 7 14:42:59 EDT 2019 [student@studentvm1 testdir]$ ``` The **-w** option to the **seq** utility adds leading zeros to the numbers generated so that they are all the same width, i.e., the same number of digits regardless of the value. This makes it easier to sort them in numeric sequence. The **seq** utility is used to generate a sequence of numbers: ``` [student@studentvm1 testdir]$ seq 5 1 2 3 4 5 [student@studentvm1 testdir]$ echo `seq 5` 1 2 3 4 5 [student@studentvm1 testdir]$ ``` Now you can do something a bit more useful, like creating a large number of empty files for testing: `[student@studentvm1 testdir]$ for I in $(seq -w 5000) ; do touch file-$I ; done` In this usage, the statement **seq -w 5000** generates a list of numbers from one to 5,000. By using command substitution as part of the **for** statement, the list of numbers is used by the **for** statement to generate the numerical part of the file names. ### Arithmetic expansion Bash can perform integer math, but it is rather cumbersome (as you will soon see). The syntax for arithmetic expansion is **$((arithmetic-expression))**, using double parentheses to open and close the expression. Arithmetic expansion works like command substitution in a shell program or script; the value calculated from the expression replaces the expression for further evaluation by the shell. Once again, start with something simple: ``` [student@studentvm1 testdir]$ echo $((1+1)) 2 [student@studentvm1 testdir]$ Var1=5 ; Var2=7 ; Var3=$((Var1*Var2)) ; echo "Var 3 = $Var3" Var 3 = 35 ``` The following division results in zero because the result would be a decimal value of less than one: ``` [student@studentvm1 testdir]$ Var1=5 ; Var2=7 ; Var3=$((Var1/Var2)) ; echo "Var 3 = $Var3" Var 3 = 0 ``` Here is a simple calculation I often do in a script or CLI program that tells me how much total virtual memory I have in a Linux host. The **free** command does not provide that data: ``` [student@studentvm1 testdir]$ RAM=`free | grep ^Mem | awk '{print $2}'` ; Swap=`free | grep ^Swap | awk '{print $2}'` ; echo "RAM = $RAM and Swap = $Swap" ; echo "Total Virtual memory is $((RAM+Swap))" ; RAM = 4037080 and Swap = 6291452 Total Virtual memory is 10328532 ``` I used the **`** character to delimit the sections of code used for command substitution. I use Bash arithmetic expansion mostly for checking system resource amounts in a script and then choose a program execution path based on the result. ## Summary This article, the second in this series on Bash as a programming language, explored the Bash file, string, numeric, and miscellaneous logical operators that provide execution-flow control logic and the different types of shell expansions. The third article in this series will explore the use of loops for performing various types of iterative operations. ## 3 Comments
11,688
开源软件名称中的故事
https://opensource.com/article/19/10/open-source-name-origins
2019-12-17T23:00:00
[ "开源" ]
https://linux.cn/article-11688-1.html
> > 有没有想过你喜欢的开源项目或编程语言的名称来自何处?让我们按字母顺序了解一下流行的技术术语背后的起源故事。 > > > ![](/data/attachment/album/201912/17/225902ogkk85zm4gqlim9h.jpg) GNOME、Java、Jupyter、Python……如果你的朋友或家人曾留意过你的工作对话,他们可能会认为你从事文艺复兴时期的民间文学艺术、咖啡烘焙、天文学或动物学工作。这些开源技术的名称从何而来?我们请我们的作者社区提供意见,并汇总了一些我们最喜欢的技术名称的起源故事。 ### Ansible “Ansible”这个名称直接来自科幻小说。Ursula Le Guin 的《Rocannon's World》一书中能进行即时(比光速更快)通信的设备被称为 ansibles(显然来自 “answerable” 一词)。Ansibles 开始流行于科幻小说之中,Orson Scott Card 的《Ender's Game》(后来成为受欢迎的电影)中,该设备控制了许多远程太空飞船。对于控制分布式机器的软件来说,这似乎是一个很好的模型,因此 Michael DeHaan(Ansible 的创建者和创始人)借用了这个名称。 ### Apache [Apache](https://httpd.apache.org/) 是最初于 1995 年发布的开源 Web 服务器。它的名称与著名的美国原住民部落无关;相反,它是指对原始软件代码的重复补丁。因此称之为,“<ruby> 一个修补的 <rt> A-patchy </rt></ruby>服务器”。 ### awk “awk(1) 代表着 Aho、Weinberger、Kernighan(作者)”—— Michael Greenberg ### Bash “最初的 Unix shell,即 Bourne shell,是以其创造者的名字命名的。在开发出来 Bash 时,csh(发音为 ‘seashell’)实际上更受交互登录用户的欢迎。Bash 项目旨在赋予 Bourne shell 新的生命,使其更适合于交互式使用,因此它被命名为 ‘Bourne again shell’,是‘<ruby> 重生 <rt> born again </rt></ruby>’的双关语。”——Ken Gaillot ### C 在早期,AT&T 的 Ken Thompson 和 Dennis Ritchie 发现可以使用更高级的编程语言(而不是低级的、可移植性更低的汇编编程)来编写操作系统和工具。早期有一个叫做 BCPL(<ruby> 基本组合编程语言 <rt> Basic Combined programming Language </rt></ruby>)的编程系统,Thompson 创建了一个名为 B 的简化版 BCPL,但 B 的灵活性和速度都不高。然后,Ritchie 把 B 的思想扩展成一种叫做 C 的编译语言。”——Jim Hall ### dd “我想你发表这样一篇文章不能不提到 dd。我的外号叫 Didi。发音正确的话听起来像 ‘dd’。我开始学的是 Unix,然后是 Linux,那是在 1993 年,当时我还是个学生。然后我去了军队,来到了我的部队中少数几个使用 Unix(Ultrix)的部门之一(其它部门主要是 VMS),那里的一个人说:‘这么说,你是一个黑客,对吗?你以为你了解 Unix 吗?好的,那么 dd 这个名字的是怎么来的呢?’我不知道,试着猜道:‘<ruby> 数据复印机 <rt> Data duplicator </rt></ruby>?’所以他说,‘我要告诉你 dd 的故事。dd 是<ruby> 转换 <rt> convert </rt></ruby>和<ruby> 复制 <rt> copy </rt></ruby>的缩写(如今人们仍然可以在手册页中看到),但由于 cc 这个缩写已经被 C 编译器占用,所以它被命名为 dd。’就在几年后,我听闻了关于 JCL 的数据定义和 Unix dd 命令不统一的、半开玩笑的语法的真实故事,某种程度是基于此的。”——Yedidyah Bar David ### Emacs 经典的<ruby> 反 vi <rt> anti-vi </rt></ruby>编辑器,其名称的真正词源并不明显,因为它源自“<ruby> 编辑宏 <rt> Editing MACroS </rt></ruby>”。但是,它作为一个伟大的宗教亵渎和崇拜的对象,吸引了许多恶作剧般的缩写,例如“Escape Meta Alt Control Shift”(以调侃其对键盘的大量依赖),“<ruby> 8MB 并经常发生内存交换 <rt> Eight Megabytes And Constantly Swapping </rt></ruby>”(从那时起就很吃内存了),“<ruby> 最终分配了所有的计算机存储空间 <rt> Eventually malloc()s All Computer Storage </rt></ruby>”和 “<ruby> EMACS 使一台计算机慢 <rt> EMACS Makes A Computer Slow </rt></ruby>”——改编自 Jargon File/Hacker's Dictionary ### Enarx [Enarx](https://enarx.io) 是机密计算领域的一个新项目。该项目的设计原则之一是它应该是“可替代的”。因此最初的名字是“psilocybin”(著名的魔术蘑菇)。一般情况下,经理级别的人可能会对这个名称有所抵触,因此考虑使用新名称。该项目的两位创始人 Mike Bursell 和 Nathaniel McCallum 都是古老语言极客,因此他们考虑了许多不同的想法,包括 тайна(Tayna——俄语中代表秘密或神秘——虽然俄语并不是一门古老的语言,但你就不要在乎这些细节了),crypticon(希腊语的意思是完全私生的),cryptidion(希腊中表示小密室),arconus(拉丁语中表示秘密的褒义形容词),arcanum(拉丁语中表示秘密的中性形容词)和 ærn(盎格鲁撒克逊人表示地方、秘密的地方、壁橱、住所、房子,或小屋的词汇)。最后,由于各种原因,包括域名和 GitHub 项目名称的可用性,他们选择了 enarx,这是两个拉丁词根的组合:en-(表示内部)和 -arx(表示城堡、要塞或堡垒)。 ### GIMP 没有 [GIMP](https://www.gimp.org/) 我们会怎么样?<ruby> GNU 图像处理项目 <rt> GNU Image Manipulation Project </rt></ruby>多年来一直是开源的重要基础。[维基百科](https://en.wikipedia.org/wiki/GIMP)指出,“1995 年,[Spencer Kimball](https://en.wikipedia.org/wiki/Spencer_Kimball_(computer_programmer)) 和 [Peter Mattis](https://en.wikipedia.org/wiki/Peter_Mattis) 在加州大学伯克利分校开始为<ruby> 实验计算设施 <rt> eXperimental Computing Facility </rt></ruby>开发 GIMP,这是一个为期一个学期的项目。” ### GNOME 你有没有想过为什么 GNOME 被称为 GNOME?根据[维基百科](https://en.wikipedia.org/wiki/GNOME),GNOME 最初是一个表示“<ruby> GNU 网络对象模型环境 <rt> GNU Network Object Model Environment </rt></ruby>”的缩写词。现在,该名称不再表示该项目,并且该项目已被放弃,但这个名称仍然保留了下来。[GNOME 3](https://www.gnome.org/gnome-3/) 是 Fedora、红帽企业版、Ubuntu、Debian、SUSE Linux 企业版等发行版的默认桌面环境。 ### Java 你能想象这种编程语言还有其它名称吗?Java 最初被称为 Oak,但是遗憾的是,Sun Microsystems 的法律团队由于已有该商标而否决了它。所以开发团队又重新给它命名。[据说](https://www.javaworld.com/article/2077265/so-why-did-they-decide-to-call-it-java-.html)该语言的工作组在 1995 年 1 月举行了一次大规模的头脑风暴。许多其它名称也被扔掉了,包括 Silk、DNA、WebDancer 等。该团队不希望新名称与过度使用的术语“web”或“net”有任何关系。取而代之的是,他们在寻找更有活力、更有趣、更容易记住的东西。Java 满足了这些要求,并且奇迹般地,团队同意通过了! ### Jupyter 现在许多数据科学家和学生在工作中使用 [Jupyter](https://jupyter.org/) 笔记本。“Jupyter”这个名字是三种开源计算机语言的融合,这三种语言在这个笔记本中都有使用,在数据科学中也很突出:[Julia](https://julialang.org/)、[Python](https://www.python.org/) 和 [R](https://www.r-project.org/)。 ### Kubernetes Kubernetes 源自希腊语中的舵手。Kubernetes 项目创始人 Craig McLuckie 在 [2015 Hacker News](https://news.ycombinator.com/item?id=9653797) 回应中证实了这种词源。他坚持航海主题,解释说,这项技术可以驱动集装箱,就像舵手或驾驶员驾驶集装箱船一样,因此,他选择了 Kubernetes 这个名字。我们中的许多人仍然在尝试正确的发音(koo-bur-NET-eez),因此 替代使用 K8s 也是可以接受的。有趣的是,它与英语单词“<ruby> 行政长官 <rp> ( </rp> <rt> governor </rt> <rp> ) </rp></ruby>”具有相同的词源,也与蒸汽机上的机械负反馈装置相同。 ### KDE 那 K 桌面呢?KDE 最初代表“<ruby> 酷桌面环境 <rt> Kool Desktop Environment </rt></ruby>”。 它由 [Matthias Ettrich](https://en.wikipedia.org/wiki/Matthias_Ettrich) 于 1996 年创立。根据[维基百科](https://en.wikipedia.org/wiki/KDE)上的说法,该名称是对 Unix 上 <ruby> <a href="https://sourceforge.net/projects/cdesktopenv/"> 通用桌面环境 </a> <rt> Common Desktop Environment </rt></ruby>(CDE)一词的调侃。 ### Linux [Linux](https://en.wikipedia.org/wiki/Linux) 因其发明者 Linus Torvalds 的名字命名的。Linus 最初想将他的作品命名为“Freax”,因为他认为以他自己的名字命名太自负了。根据[维基百科](https://en.wikipedia.org/wiki/Linux)的说法,“赫尔辛基科技大学 Torvalds 的同事 Ari Lemmke 当时是 FTP 服务器的志愿管理员之一,他并不认为‘Freax’是个好名字。因此,他没有征询 Torvalds 就将服务器上的这个项目命名为‘Linux’。” 以下是一些最受欢迎的 Linux 发行版。 #### CentOS [CentOS](https://www.centos.org/) 是<ruby> 社区企业操作系统 <rt> Community Enterprise Operating System </rt></ruby>的缩写。它包含来自 Red Hat Enterprise Linux 的上游软件包。 #### Debian [Debian](https://www.debian.org/) Linux 创建于 1993 年 9 月,是其创始人 Ian Murdock 和他当时的女友 Debra Lynn 的名字的混成词。 #### RHEL [Red Hat Linux](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux) 得名于它的创始人 Marc Ewing,他戴着一顶祖父送给他的康奈尔大学红色<ruby> 软呢帽 <rt> fedora </rt></ruby>。红帽公司成立于 1993 年 3 月 26 日。[Fedora Linux](https://getfedora.org/) 最初是一个志愿者项目,旨在为红帽发行版提供额外的软件,它的名字来自红帽的“Shadowman”徽标。 #### Ubuntu [Ubuntu](https://ubuntu.com/about) 旨在广泛分享开源软件,它以非洲哲学“<ruby> 人的本质 <rt> ubuntu </rt></ruby>”命名,可以翻译为“对他人的人道主义”或“我之所以是我,是因为我们都是这样的人”。 ### Moodle 开源学习平台 [Moodle](https://moodle.org/) 是“<ruby> 模块化面向对象动态学习环境 <rt> modular object-oriented dynamic learning environment </rt></ruby>”的首字母缩写。Moodle 仍然是领先的线上学习平台。全球有近 10.4 万个注册的 Moodle 网站。 另外两个流行的开源内容管理系统是 Drupal 和 Joomla。Drupal 的名字来自荷兰语 “druppel”,意思是“掉落”。根据维基百科,Joomla 是斯瓦希里语单词“jumla”的[英式拼写](https://en.wikipedia.org/wiki/Joomla#Historical_background),在阿拉伯语、乌尔都语和其他语言中是“在一起”的意思。 ### Mozilla [Mozilla](https://www.mozilla.org/en-US/) 是一个成立于 1998 年的开源软件社区。根据其网站,“Mozilla 项目创建于 1998 年,发布了 Netscape 浏览器套件源代码。其旨在利用互联网上成千上万的程序员的创造力,并推动浏览器市场上前所未有的创新水平。” 这个名字是 [Mosaic](https://en.wikipedia.org/wiki/Mosaic_(web_browser)) 和 Godzilla 的混成词。 ### Nginx “许多技术人员都试图装酷,并将它念成‘n’‘g’‘n’‘x’。实际上,很少的一些人做点基本的调查工作,就可以很快发现该名称实际上应该被念成是“EngineX”,指的是功能强大的 web 服务器,像个引擎。”——Jean Sebastien Tougne ### Perl Perl 的创始人 Larry Wall 最初将他的项目命名为“Pearl”。根据维基百科,Wall 想给这种语言起一个有积极含义的简短名字。在 Perl 正式发布之前,Wall 发现了已有 [PEARL](https://en.wikipedia.org/wiki/PEARL_(programming_language)) 编程语言,于是更改了名称的拼写。 ### Piet 和 Mondrian “有两种编程语言以艺术家 Piet Mondrian 命名。一种叫做‘Piet’,另一种叫做‘Mondrian’。(David Morgan-Mar [写道](http://www.dangermouse.net/esoteric/piet.html)):‘Piet 是一种编程语言,其中的程序看起来像抽象绘画。该语言以几何抽象艺术的开创者 Piet Mondrian 的名字命名。我曾想将这种语言命名为 Mondrian,但是有人告诉我这会让它看起来像一种很普通的脚本语言。哦,好吧,我想我们不能都是深奥的语言作家。’”——Yuval Lifshitz ### Python Python 编程语言的独特名称来自其创建者 Guido Van Rossum,他是英国六人喜剧团体 Monty Python 的粉丝。 ### Raspberry Pi Raspberry Pi 以其微小但强大的功能和对低廉的价格而闻名,在开源社区中是最受欢迎的。但是它可爱(和好吃)的名字是从哪里来的呢?在 70 年代和 80 年代,以水果命名的计算机是一种流行的趋势。苹果、橘子、杏……有人饿了吗?根据创始人 Eben Upton 的 [2012 采访](https://www.techspot.com/article/531-eben-upton-interview/),“<ruby> 树莓派 <rt> Raspberry Pi </rt></ruby>”这个名称是对这种趋势的致敬。树莓也很小,但却很有味道。名称中的“Pi”暗示着这样的事实:最初,该计算机只能运行 Python。 ### Samba [Server Message Block](https://www.samba.org/) 用于在 Linux 上共享 Windows 文件。 ### ScummVM [ScummVM](https://www.scummvm.org/)(《疯狂大楼》虚拟机的脚本创建实用程序)是一个程序,可以在现代计算机上运行一些经典的计算机冒险游戏。最初,它旨在玩用 SCUMM 构建的 LucasArts 的冒险游戏,该游戏最初用于开发《疯狂大楼》,后来又被用来开发 LucasArts 的其它大多数冒险游戏。目前,ScummVM 支持大量游戏引擎,包括 Sierra Online 的 AGI 和 SCI,但仍保留着名称 ScummVM。 有一个相关的项目 [ResidualVM](https://www.residualvm.org/) 之所以得名,是因为它涵盖了 ScummVM 未涵盖的“<ruby> 剩余的 <rt> residual </rt></ruby>” LucasArts 冒险游戏。 ResidualVM 涵盖的 LucasArts 游戏是使用 GrimE(Grim Engine)开发的,该引擎最初用于开发 Grim Fandango,因此 ResidualVM 的名称是双关语。 ### SQL “你可能知道 SQL 代表<ruby> 结构化查询语言 <rt> Structured Query Language </rt></ruby>,但你知道为什么它经常被读作‘sequel’吗?它是作为原本的‘QUEL’(<ruby> 查询语言 <rt> QUEry Language </rt></ruby>)的后续(如<ruby> 结局 <rt> sequel </rt></ruby>)而创建的。”——Ken Gaillot ### XFCE [XFCE](https://www.xfce.org/) 是由 [Olivier Fourdan](https://en.wikipedia.org/wiki/Olivier_Fourdan) 创建的一个流行的桌面。它在 1996 年作为 CDE 的替代品出现,最初是 <ruby> XForms 公共环境 <rt> XForms Common Environment </rt></ruby>的缩写。 ### Zsh Zsh 是一个交互式登录 shell。1990 年,普林斯顿大学的学生 Paul Falstad 写了该 shell 的第一个版本。他在看到当时在普林斯顿大学担任助教的 Zhong Sha 的登录 ID(zsh)后,觉得这个名字听起来像 [shell 的好名字](http://www.zsh.org/mla/users/2005/msg00951.html),给它起了这个名字。 还有更多的项目和名称还没有包括在这个列表中。请一定要在评论中分享你的收藏。 --- via: <https://opensource.com/article/19/10/open-source-name-origins> 作者:[Joshua Allen Holm](https://opensource.com/users/holmja) 选题:[lujun9972](https://github.com/lujun9972) 译者:[laingke](https://github.com/laingke) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
GNOME, Java, Jupyter, Python. If your friends or family members have ever eavesdropped on your work conversations, they might think you've made a career in Renaissance folklore, coffee roasting, astronomy, or zoology. Where did the names of these open source technologies come from? We asked our writer community for input and rounded up some of our favorite tech name origin stories. ## Ansible The name "Ansible" is lifted directly from science fiction. Ursula Le Guin's book *Rocannon's World* had devices allowing instantaneous (faster than light) communication called ansibles (derived, apparently, from the word "answerable"). Ansibles became a staple of science fiction, including in Orson Scott Card's *Ender's Game* (which later became a popular film), where the device controlled many remote space ships. This seemed to be a good model for software that controls distributed machines, so Michael DeHaan (creator and founder of Ansible) borrowed the name. ## Apache [Apache](https://httpd.apache.org/) is an open source web server that was originally released in 1995. Its name is not related to the famous Native American tribe; it instead refers to the repeated patches to its original software code. Hence, "A-patchy server." ## awk "awk(1) Stands for Aho, Weinberger, Kernighan (authors)" —Michael Greenberg ## Bash "The original Unix shell, the Bourne shell, was named after its creator. At the time Bash was being developed, csh (pronounced 'seashell') was actually more popular for interactive user logins. The Bash project aimed to give new life to the Bourne shell by making it more suitable for interactive use, thus it was named the 'Bourne again shell,' a pun on 'born again.'" —Ken Gaillot ## C "In early days, Ken Thompson and Dennis Ritchie at AT&T found it interesting that you could use a higher-level programming language (instead of low-level and less-portable assembly programming) to write operating systems and tools. There was an early programming system called BCPL (Basic Combined Programming Language), and Thompson created a stripped-down version of BCPL called B. But B wasn't very flexible or fast. Ritchie then took the ideas of B and expanded it into a compiled language called C." —Jim Hall ## dd "I don't think you can publish such an article without mentioning dd. My nickname is Didi. Correctly pronounced, it sounds like 'dd.' I first learned Unix, and then Linux, in 1993 as a student. Then I went to the army, arrived to one of the very few sections in my unit that used Unix (Ultrix) (the rest were mainly VMS), and one of the people there said: 'So, you are a hacker, right? You think you know Unix? OK, so what's the reason for the name dd?' I had no idea and tried to guess: "Data duplicator?" So he said, 'I'll tell you the story of dd. dd is short for *convert and copy* (as anyone can still see today on the manpage), but since cc was already taken by the c compiler, it was named dd.' Only years later, I heard the true story about JCL's data definition and the non-uniform, semi-joking syntax for the Unix dd command somewhat being based on it." —Yedidyah Bar David ## Emacs The classic anti-vi editor, the true etymology of the name is unremarkable, in that it derives from "Editing MACroS." Being an object of great religious opprobrium and worship it has, however, attracted many spoof bacronyms such as "Escape Meta Alt Control Shift" (to spoof its heavy reliance on keystrokes), "Eight Megabytes And Constantly Swapping" (from when that was a lot of memory), "Eventually malloc()s All Computer Storage," and "EMACS Makes A Computer Slow." —Adapted from the Jargon File/Hacker's Dictionary ## Enarx [Enarx](https://enarx.io) is a new project in the confidential computing space. One of the project's design principles was that it should be "fungible." so an initial name was "psilocybin" (the famed magic mushroom). The general feeling was that manager types would probably be resistant, so new names were considered. The project's two founders, Mike Bursell and Nathaniel McCallum, are both ancient language geeks, so they considered lots of different ideas, including тайна (Tayna—Russian for secret or mystery—although Russian, admittedly, is not ancient, but hey), crypticon (total bastardization of Greek), cryptidion (Greek for small secret place), arcanus (Latin masculine adjective for secret), arcanum (Latin neuter adjective for secret), and ærn (Anglo-Saxon for place, secret place, closet, habitation, house, or cottage). In the end, for various reasons, including the availability of domains and GitHub project names, they settled on enarx, a combination of two Latin roots: en- (meaning within) and -arx (meaning citadel, stronghold, or fortress). ## GIMP Where would we be without [GIMP](https://www.gimp.org/)? The GNU Image Manipulation Project has been an open source staple for many years. [Wikipedia](https://en.wikipedia.org/wiki/GIMP) states, "In 1995, [Spencer Kimball](https://en.wikipedia.org/wiki/Spencer_Kimball_(computer_programmer)) and [Peter Mattis](https://en.wikipedia.org/wiki/Peter_Mattis) began developing GIMP as a semester-long project at the University of California, Berkeley, for the eXperimental Computing Facility." ## GNOME Have you ever wondered why GNOME is called GNOME? According to [Wikipedia](https://en.wikipedia.org/wiki/GNOME), GNOME was originally an acronym that represented the "GNU Network Object Model Environment." Now that name no longer represents the project and has been dropped, but the name has stayed. [GNOME 3 ](https://www.gnome.org/gnome-3/)is the default desktop environment for Fedora, Red Hat Enterprise, Ubuntu, Debian, SUSE Linux Enterprise, and more. ## Java Can you imagine this programming language being named anything else? Java was originally called Oak, but alas, the legal team at Sun Microsystems vetoed that name due to its existing trademark. So it was back to the drawing board for the development team. [Legend has it](https://www.javaworld.com/article/2077265/so-why-did-they-decide-to-call-it-java-.html) that a massive brainstorm was held by the language's working group in January 1995. Lots of other names were tossed around including Silk, DNA, WebDancer, and so on. The team did not want the new name to have anything to do with the overused terms, "web" or "net." Instead, they were searching for something more dynamic, fun, and easy to remember. Java met the requirements and miraculously, the team agreed! ## Jupyter Many of today's data scientists and students use [Jupyter](https://jupyter.org/) notebooks in their work. The name Jupyter is an amalgamation of three open source computer languages that are used in the notebooks and prominent in data science: [Julia](https://julialang.org/), [Python](https://www.python.org/), and [R](https://www.r-project.org/). ## Kubernetes Kubernetes is derived from the Greek word for helmsman. This etymology was corroborated in a [2015 Hacker News](https://news.ycombinator.com/item?id=9653797) response by a Kubernetes project founder, Craig McLuckie. Wanting to stick with the nautical theme, he explained that the technology drives containers, much like a helmsman or pilot drives a container ship. Thus, Kubernetes was the chosen name. Many of us are still trying to get the pronunciation right (koo-bur-NET-eez), so K8s is an acceptable substitute. Interestingly, it shares its etymology with the English word "governor," so has that in common with the mechanical negative-feedback device on steam engines. ## KDE What about the K desktop? KDE originally represented the "Kool Desktop Environment." It was founded in 1996 by [Matthias Ettrich](https://en.wikipedia.org/wiki/Matthias_Ettrich). According to [Wikipedia](https://en.wikipedia.org/wiki/KDE), the name was a play on the words [Common Desktop Environment](https://sourceforge.net/projects/cdesktopenv/) (CDE) on Unix. ## Linux [Linux](https://en.wikipedia.org/wiki/Linux) was named for its inventor, Linus Torvalds. Linus originally wanted to name his creation "Freax" as he thought that naming the creation after himself was too egotistical. According to [Wikipedia](https://en.wikipedia.org/wiki/Linux), "Ari Lemmke, Torvalds' coworker at the Helsinki University of Technology, who was one of the volunteer administrators for the FTP server at the time, did not think that 'Freax' was a good name. So, he named the project 'Linux' on the server without consulting Torvalds." Following are some of the most popular Linux distributions. ### CentOS [CentOS](https://www.centos.org/) is an acronym for Community Enterprise Operating System. It contains the upstream packages from Red Hat Enterprise Linux. ### Debian [Debian](https://www.debian.org/) Linux, founded in September 1993, is a portmanteau of its founder, Ian Murdock, and his then-girlfriend Debra Lynn. ### RHEL [Red Hat Linux](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux) got its name from its founder Marc Ewing, who wore a red Cornell University fedora given to him by his grandfather. Red Hat was founded on March 26, 1993. [Fedora Linux](https://getfedora.org/) began as a volunteer project to provide extra software for the Red Hat distribution and got its name from Red Hat's "Shadowman" logo. ### Ubuntu [Ubuntu](https://ubuntu.com/about) aims to share open source widely and is named after the African philosophy of ubuntu, which can be translated as "humanity to others" or "I am what I am because of who we all are." ## Moodle The open source learning platform [Moodle](https://moodle.org/) is an acronym for "modular object-oriented dynamic learning environment." Moodle continues to be a leading platform for e-learning. There are nearly 104,000 registered Moodle sites worldwide. Two other popular open source content management systems are Drupal and Joomla. Drupal's name comes from the Dutch word for "druppel" which means "drop." Joomla is an [anglicized spelling](https://en.wikipedia.org/wiki/Joomla#Historical_background) of the Swahili word "jumla," which means "all together" in Arabic, Urdu, and other languages, according to Wikipedia. ## Mozilla [Mozilla](https://www.mozilla.org/en-US/) is an open source software community founded in 1998. According to its website, "The Mozilla project was created in 1998 with the release of the Netscape browser suite source code. It was intended to harness the creative power of thousands of programmers on the internet and fuel unprecedented levels of innovation in the browser market." The name was a portmanteau of [Mosaic](https://en.wikipedia.org/wiki/Mosaic_(web_browser)) and Godzilla. ## Nginx "Many tech people try to be cool and say it 'n' 'g' 'n' 'x'. Few actually did the basic actions of researching a bit more to find out very quickly that the name is actually supposed to be said as 'EngineX,' in reference to the powerful web server, like an engine." —Jean Sebastien Tougne ## Perl Perl's founder Larry Wall originally named his project "Pearl." According to Wikipedia, Wall wanted to give the language a short name with positive connotations. Wall discovered the existing [PEARL](https://en.wikipedia.org/wiki/PEARL_(programming_language)) programming language before Perl's official release and changed the spelling of the name. ## Piet and Mondrian "There are two programming language named after the artist Piet Mondrian. One is called 'Piet' and the other 'Mondrian.' [David Morgan-Mar [writes](http://www.dangermouse.net/esoteric/piet.html)]: 'Piet is a programming language in which programs look like abstract paintings. The language is named after Piet Mondrian, who pioneered the field of geometric abstract art. I would have liked to call the language Mondrian, but someone beat me to it with a rather mundane-looking scripting language. Oh well, we can't all be esoteric language writers, I suppose.'" —Yuval Lifshitz ## Python The Python programming language received its unique name from its creator, Guido Van Rossum, who was a fan of the comedy group Monty Python. ## Raspberry Pi Known for its tiny-but-mighty capabilities and wallet-friendly price tag, the Raspberry Pi is a favorite in the open source community. But where did its endearing (and yummy) name come from? In the '70s and '80s, it was a popular trend to name computers after fruit. Apple, Tangerine, Apricot... anyone getting hungry? According to a [2012 interview](https://www.techspot.com/article/531-eben-upton-interview/) with founder Eben Upton, the name "Raspberry Pi" is a nod to that trend. Raspberries are also tiny in size, yet mighty in flavor. The "Pi" in the name alludes to the fact that, originally, the computer could only run Python. ## Samba [Server Message Block](https://www.samba.org/) for sharing Windows files on Linux. ## ScummVM [ScummVM](https://www.scummvm.org/) (Script Creation Utility for Maniac Mansion Virtual Machine) is a program that makes it possible to run some classic computer adventure games on a modern computer. Originally, it was designed to play LucasArts adventure games that were built using SCUMM, which was originally used to develop Maniac Mansion before being used to develop most of LucasArts's other adventure games. Currently, ScummVM supports a large number of game engines, including Sierra Online's AGI and SCI, but still retains the name ScummVM. A related project, [ResidualVM](https://www.residualvm.org/), got its name because it covers the "residual" LucasArts adventure games not covered by ScummVM. The LucasArts games covered by ResidualVM were developed using GrimE (Grim Engine), which was first used to develop Grim Fandango, so the ResidualVM name is a double pun. ## SQL "You may know [SQL] stands for Structured Query Language, but do you know why it's often pronounced 'sequel'? It was created as a follow-up (i.e. sequel) to the original 'QUEL' (QUEry Language)." —Ken Gaillot ## XFCE [XFCE](https://www.xfce.org/) is a popular desktop founded by [Olivier Fourdan](https://en.wikipedia.org/wiki/Olivier_Fourdan). It began as an alternative to CDE in 1996 and its name was originally an acronym for XForms Common Environment. ## Zsh Zsh is an interactive login shell. In 1990, the first version of the shell was written by Princeton student Paul Falstad. He named it after seeing the login ID of Zhong Sha (zsh), then a teaching assistant at Princeton, and thought that it sounded like a [good name for a shell](http://www.zsh.org/mla/users/2005/msg00951.html). There are many more projects and names that we have not included in this list. Be sure to share your favorites in the comments. ## 15 Comments
11,690
新人必读:区块链实用型技能树
https://mp.weixin.qq.com/s/hxWdXtxXY-BSW9_-B6iyKA
2019-12-19T09:38:00
[ "区块链" ]
https://linux.cn/article-11690-1.html
![](/data/attachment/album/201912/19/093756b6823xlnl9dxtl33.jpg) 随着新一波的区块链热潮,许多同学怀着巨大的热情进入了这个领域,同时也会遇到不少疑惑,区块链开发需要哪些知识?怎么学习?从哪里学习?遇到问题怎么办?本文将试图给区块链领域新人一个快速实用的指引。 ### 一、基本 IT 技能 区块链堪称“黑科技”,本身具有大量的技术元素,有志于从技术角度切入区块链的人,应该具备或掌握基本的 IT 技能,达到至少是常规级别“程序员”或“系统管理员”的技能水平。 ![](/data/attachment/album/201912/19/093827lnhpueuhimivpxp7.png) #### 首先需要熟练的 Linux 操作系统知识 大多数区块链系统是可以跑在 Linux 上的,包括 CentOS 和 Ubuntu 等,你至少要会一些基本的 Linux 操作指令,比如 `ls` 查看目录、`ps` 或 `top` 查看进程、`find` 查找文件、`netstat` 查看网络、`ulimit` 检查系统参数限制、`df`/`du` 查看磁盘空间、用 `apt`/`yum` 安装软件等等,如果这些基本命令都不掌握,在 Linux 上操作肯定是举步维艰的。 这方面的书和资料都很多,相信一星期就能上手。另外,善于 Linux 的 `man` 指令,可以获得每个命令的详细帮助。如果学会写 shell 脚本,那更如虎添翼,可以把大量的繁琐操作给自动化了。 #### 要有清晰的网络概念 区块链本来是分布式系统,节点之间一定是通过网络相连的,只是跑起来的话,不需要多高深的网络知识,只需要了解什么是 TCP/IP;公网、内网、本地地址的区别;端口如何配置;节点和节点、SDK 和节点之间的互联是否会被防火墙和网络策略挡住;采用 `ifconfig`、`telnet`、`ping`、`netstat` 等命令检查网络信息和进行探测、定位网络问题。一般来说,Linux 书籍也都会介绍这部分内容。 区块链周边的支持,如浏览器、中间件、业务应用,会依赖一些第三方基础软件,如 MySQL/MariaDB 数据库、Nginx 服务、Tomcat 服务等,至少懂得怎么去安装指定版本的软件,掌握修改这些软件的配置文件并使之生效的基本操作,了解各款软件的密码、权限配置和网络安全策略,以保护自身安全。 如果是基于云、Docker 或者 k8s 等容器环境构建,需要了解使用的服务商或容器的功能、性能、配置方式,包括对资源的分配:CPU、内存、带宽、存储等,以及安全和权限的配置、网络策略配置、运维方式,达到轻松分发构建的同时,还能保持其稳定性和可用性。 各种云服务商和容器解决方案都有周全的文档和客服服务渠道,可以帮助用户顺畅地使用。 #### 到编程语言阶段,可以根据自己的学习路径,选择不同的语言 如果是使用 Java 语言,那就应该熟练掌握 Eclipse、IntelliJ IDEA 等集成 IDE,熟悉 Gradle 为主的工程管理软件,熟悉 Spring、Springboot 等 Java 的基础开发组件,熟悉在 IDE 或命令行下对资源路径如 ApplicationContext 等路径的定义,或许还有 myBatis 等流行的组件,这些都可以在 Java 相关的社区和网站找到资料和书籍。 在熟练使用 Java 语言的情况下,采用 Java SDK 接入到区块链,跑起一个演示示例,将是非常轻松写意的事情。 如果是采用其他语言,我们也提供了 Python、Node.js、Golang 等语言的区块链 SDK。 不同的语言,其安装包有不同的稳定版本,会采用不同的环境和依赖安装配置方法,会有不同的 IDE 和调试方法,就不在本文一一罗列,相信学习和使用语言这件事本身,于程序员已经是最基本的技能了。 #### 最后,作为在开源世界里冲浪的玩家,“全球最大同性交友网站”——GitHub 一定是要上的了 注册 GitHub 账号,掌握 Git 版本管理工具的基本操作,克隆和拉取开源软件代码,提交议题,提交自己的修改,给开源项目提交拉取请求,再顺手点个星标,激情而有范儿,在开源世界里留下你的姓名。 ### 二、区块链领域的基础知识栈 以下部分的知识和区块链或区块链某一个平台更加相关,从底到上依次是: ![](/data/attachment/album/201912/19/093827uzyejyfhxsfetfh8.jpg) #### HASH(哈希算法)、签名、证书 严格来说,这并不是区块链领域的专有知识,只是必须具备的基础知识,包括 SHA3/SHA256/RIPEMD160 等摘要算法,以及这些算法和“区块链地址”的关系,基于公私钥的数字签名和验证方法,数字证书的概念和格式,比如 X.509 证书,以及保存证书/公私钥的文件格式,如 PEM 文件、keystore文件等。 #### 基础应用密码学 基础应用密码学其实范围很广,作为入门者,至少要了解对称和非对称加密的常见算法,如 AES 对称加密,RSA、ECDSA 椭圆曲线等非对称加密算法,以及这些算法在签名验签、数据加密、通信协商和保护方面的作用。如果要使用国密,那么需要了解 SM2~SM9 一系列算法的概念和使用。 #### 分布式网络结构 区块链是先天的“分布式网络系统”,节点和节点通过网络的 P2P 端口互连,客户端、SDK 通过 RPC/通道端口互连,首先要保证网络之间是互通的,监听的地址和端口是对的,端口是开放的,防火墙和网络策略是正确的,用于安全连接的证书已经到位,才能保证区块链的“通则不痛”。 这也要求使用者具备基本的网络知识、网络工具,同时了解区块链特有的节点类型(共识节点、观察节点、轻节点等)、互连方式(点对点双向连接、JSON RPC 的 HTTP 短连接、通道长连接等)。详情点击参考[《FISCO BCOS 网络端口讲解》](http://mp.weixin.qq.com/s?__biz=MzU5NTg0MjA4MA==&mid=2247484395&idx=1&sn=fb2c47ca54c986484bc935d1904d6b65&chksm=fe6a86a4c91d0fb2067ccde86a5da9f9e4b78bc876b2fd5dc26cabd5f3006586bcc90abdd3c1&scene=21#wechat_redirect)。 #### 智能合约 智能合约可说是应用开发者直面区块链的一道大门,入得此门,精彩无穷。流行的智能合约语言是 Solidity 语言,这门源自以太坊,从诞生开始就是为区块链而来的。 Solidity 语言更新活跃、文档完备,具有良好的一致性和事务性,功能足够实现中型的商业应用。 当然,它在实时调试、第三库支持、运行速度等方面还比不上成熟的语言,如果开发者想要用 C++ 等语言编写智能合约,那就要对区块链上的计算范式进行深入了解,避免写出无法共识的智能合约来,一般是建议有深入的了解后再采用 Solidity 之外的其他语言编写合约。 要掌握 Solidity 合约,当然是通读文档,并动手尝试。具体参考[该文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/manual/smart_contract.html)。 #### ABI 接口原理 在采用 EVM 作为虚拟机的区块链上,EVM 执行的是 Solidity 语言的合约。合约编译会生成后缀名为 ABI 的文件,其实里面就是该合约接口定义的 JSON 文本,可以用文本查看器查阅,了解你写的合约如何翻译成 ABI 里的接口,接口返回类型,参数列表,参数类型等,只要有合约的 ABI 文件,就可以调用区块链 SDK 的接口,解析这个合约相关的交易、返回值、回执等。 #### 区块数据结构 <ruby> 区块 <rp> ( </rp> <rt> Block </rt> <rp> ) </rp></ruby>有区块头和区块体。区块体有交易列表,交易列表里的每个<ruby> 交易 <rp> ( </rp> <rt> Transaction </rt> <rp> ) </rp></ruby>(Tx)有发起方、目标地址、调用方法和参数,以及发送者签名。交易的结果会生成一个“<ruby> 回执 <rp> ( </rp> <rt> Receipt </rt> <rp> ) </rp></ruby>”,回执里包含被调用方法的返回值、运行过程生成的 EventLog 等…… 了解这些,基本上就掌握了区块链数据的脉络,还可以继续深究数据结构里的梅克尔根以及对应的梅克尔树是如何生成的,有什么作用(如用于 SPV:Simplified PaymentVerification)。具体参考[该文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/design/protocol_description.html)。 #### RPC 接口 这里把区块链节点暴露的功能接口统称为“RPC 接口”。查看链上数据,包括区块、交易、回执、系统信息、配置信息,向链上发起交易,以调用智能合约、修改系统配置等,或者通过 AMOP 协议发送消息、监听事件,都是通过 RPC 接口。 几十个 RPC 接口建议一一走读,或善用搜索,以发现自己想要的接口。 接口通信采用的协议可能是 JSON RPC,或者是 FISCO BCOS 独创的通道协议,SDK 基本上已经对接口和协议进行了良好的包装,也可以在深入理解 ABI 和 RLP 等编码模式前提下自行开发接口客户端。具体参考[该文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/api.html)。 #### 准入和权限模型 联盟链强调安全可控,节点准入是第一步,在链初始化后,其他节点或者 SDK 配置了相应的证书,才能接入到既有的联盟链上。 链上的角色用权限模型控制,包括管理员权限、发布合约的权限、创建表的权限、参数配置权限等,以避免角色之间操作混淆,某些角色既当运动员又当裁判员。 初学者需要仔细阅读区块链平台提供的技术文档了解原理,遵循操作手册的步骤进行操作。具体参考[该文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/manual/permission_control.html)。 #### 数据存储模型 区块链节点会采用文件数据库(LevelDB 或 RocksDB),或者关系型数据库如 MySQL 保存数据,所以,链上是真的有“数据库”的。 写入数据库的数据包括区块、交易、回执、合约产生的状态数据等,是否写入“调用合约产生的历史数据”根据不同的平台而定, FISCO BCOS 默认只保存最新的状态值,可以选择性地将修改记录写入“回执”或“历史表”里进行追踪。 FISCO BCOS 还提供方案,将历史数据导出到链下数据库进行关联分析。具体参考[该文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/design/storage/index.html)。 #### 共识机制原理 联盟链通常采用插件化共识机制实现,FISCO BCOS 提供 PBFT 和 RAFT 两种高效共识算法,而不会采用“挖矿”这些高耗能低效率的共识。 共识机制是区块链的灵魂,对共识机制进行深入学习,才可以深入理解区块链通过多方协作、达成高度一致性、支持交易事务性、防篡改防作恶的功效。具体参考[该文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/design/consensus/index.html)。 区块链的知识包罗万象,更深层次的知识还有分布式系统理论、博弈论、前沿密码学、经济学、社会学等,掌握以上的基础知识,再深入学习,举一反三,用场景去验证和探索创新式应用,方可发挥技术的潜力,感受分布式商业的魅力。 ### 三、做一个怎样的学习者 在这个过程中,希望学习者做到: #### 读文档的耐心 我们的开源项目文档足有 20 万字以上的篇幅,公众号里还有大量的技术解析和科普文章,这都是程序员们在编码之外,用尽自己仅有的语文储备,码出的海量文字,是一笔巨大的技术财富,涵盖了相关开源项目的方方面面。如果能通读,或者记住文档结构和标题,需要时快速打开,足以解惑且深入。 #### 搜资料的能力 文档、公众号都有搜索功能,当想起和开源社区有关的问题时,可以随手用关键字搜索,一般都能找到答案。如果有语言不详之处,可以向开源项目团队提出,或者根据自己的理解进行补充。通用的知识点,如操作系统、网络等,通过公网搜索引擎,一般都能找到答案。 #### 排查环境和依赖问题的能力 开源软件牵涉的系统环境、第三方软件、软件的版本等常常有错综复杂的依赖关系,太高或太低的版本都可能会有一些问题,请注意阅读项目文档对软硬件环境和依赖的描述,保证自己的环境符合要求,并善用配置管理工具、软件安装工具获取和设置合适的版本。 #### 调试能力 如上所述,Solidity 语言的调试工具完善程度尚未达到完美,但可以善用合约的返回值、EventLog 等方式,通过 WeBASE、控制台等趁手的工具进行调试,并查阅 Solidity 文档,了解问题可能出在哪里。 区块链节点的日志开启 debug 级别后,也会打印详细的信息,可以查阅运行日志,获取运行信息和可能的错误信息,将这些信息与自己所做的操作比如发交易的流程结合起来进行分析,提高调试效率。 同时,目前的开源软件通常会在屏幕上打印错误原因和解决问题的提示,仔细查看操作反馈,大概率能了解错误原因和解决方案。 #### 代码阅读能力 开源软件的最大效能是把代码毫无遗漏的摊到了开发者和学习者面前,了解代码结构,查阅代码里的关键流程,用关键字去搜索代码里的对应实现,都可以深入系统细节,挖掘设计思想,定位问题,寻找优化方法。一个好学且硬核的程序员,足可通过代码,和世界对话。 #### 问问题的方式方法 “一个好问题,比答案还重要”。我们的社区非常活跃,大家都很热情地答复和解决问题。我们鼓励在社区里公开提出问题,一方面使大家都可以分享问题,找到解决方案,另一方面提问者也可以得到更多人的帮助。同时,希望提问者提出问题时,一次性描述详尽,把相关的操作步骤、系统环境、软件版本、出错提示以及希望得到的解决方案都提出来。 如果是通用性的问题,可以先搜索再提问,有利于培养独立解决问题的能力。希望提问者能向社区反馈更深层次的问题,以帮助社区快速优化。对很多典型问题,社区也积累了一些行之有效的解决方案,我们会整理和公布出来,以便查阅。 从新人到老鸟的路也许漫漫,如果能参考这篇小文的一些方法,可以少踩许多坑,多写一些应用。Enjoy blockchain,社区与你共同进步。 ### 资源链接 * 各项开源组件索引: <https://fintech.webank.com/> * FISCO BCOS 开源文档: <https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/> * 关键概念:<https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/tutorial/key_concepts.html> * 以及使用手册:<https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/manual/index.html>
200
OK
该公众号已迁移 该公众号已迁移至新的账号,原账号已回收。若需访问原文章链接,请点击下方按钮。 访问文章 : , 。 视频 小程序 赞 ,轻点两下取消赞 在看 ,轻点两下取消在看 分享 留言 收藏
11,691
从命令行轻松将文本片段上传到类似 Pastebin 的服务中
https://www.ostechnix.com/how-to-easily-upload-text-snippets-to-pastebin-like-services-from-commandline/
2019-12-19T09:51:20
[ "Pastebin" ]
https://linux.cn/article-11691-1.html
![](/data/attachment/album/201912/19/095124upi8f388p989838e.png) 每当需要在线共享代码片段时,我们想到的第一个便是 Pastebin.com,这是 Paul Dixon 于 2002 年推出的在线文本共享网站。现在,有几种可供选择的文本共享服务可以上传和共享文本片段、错误日志、配置文件、命令输出或任何类型的文本文件。如果你碰巧经常使用各种类似于 Pastebin 的服务来共享代码,那么这对你来说确实是个好消息。向 Wgetpaste 打个招呼吧,它是一个命令行 BASH 实用程序,可轻松地将文本摘要上传到类似 Pastebin 的服务中。使用 Wgetpaste 脚本,任何人都可以与自己的朋友、同事或想在类似 Unix 的系统中的命令行中查看/使用/审查代码的人快速共享文本片段。 ### 安装 Wgetpaste Wgetpaste 在 Arch Linux [Community] 存储库中可用。要将其安装在 Arch Linux 及其变体(如 Antergos 和 Manjaro Linux)上,只需运行以下命令: ``` $ sudo pacman -S wgetpaste ``` 对于其他发行版,请从 [Wgetpaste 网站](http://wgetpaste.zlin.dk/) 获取源代码,并按如下所述手动安装。 首先下载最新的 Wgetpaste tar 文件: ``` $ wget http://wgetpaste.zlin.dk/wgetpaste-2.28.tar.bz2 ``` 提取它: ``` $ tar -xvjf wgetpaste-2.28.tar.bz2 ``` 它将 tar 文件的内容提取到名为 `wgetpaste-2.28` 的文件夹中。 转到该目录: ``` $ cd wgetpaste-2.28/ ``` 将 `wgetpaste` 二进制文件复制到 `$PATH` 中,例如 `/usr/local/bin/`。 ``` $ sudo cp wgetpaste /usr/local/bin/ ``` 最后,使用命令使其可执行: ``` $ sudo chmod +x /usr/local/bin/wgetpaste ``` ### 将文本片段上传到类似 Pastebin 的服务中 使用 Wgetpaste 上传文本片段很简单。让我向你展示一些示例。 #### 1、上传文本文件 要使用 Wgetpaste 上传任何文本文件,只需运行: ``` $ wgetpaste mytext.txt ``` 此命令将上传 `mytext.txt` 文件的内容。 示例输出: ``` Your paste can be seen here: https://paste.pound-python.org/show/eO0aQjTgExP0wT5uWyX7/ ``` ![](/data/attachment/album/201912/19/095126aql8zbjl9fbm4aj8.png) 你可以通过邮件、短信、whatsapp 或 IRC 等任何媒体共享 pastebin 的 URL。拥有此 URL 的人都可以访问它,并在他们选择的 Web 浏览器中查看文本文件的内容。 这是 Web 浏览器中 `mytext.txt` 文件的内容: ![](/data/attachment/album/201912/19/095126fudroodpnd0exdrz.png) 你也可以使用 `tee` 命令显示粘贴的内容,而不是盲目地上传它们。 为此,请使用如下的 `-t` 选项。 ``` $ wgetpaste -t mytext.txt ``` ![](/data/attachment/album/201912/19/095128hc74fn35cvc84kf5.png) #### 2、将文字片段上传到其他服务 默认情况下,Wgetpaste 会将文本片段上传到 poundpython(<https://paste.pound-python.org/>)服务。 要查看支持的服务列表,请运行: ``` $ wgetpaste -S ``` 示例输出: ``` Services supported: (case sensitive): Name: | Url: =============|================= bpaste | https://bpaste.net/ codepad | http://codepad.org/ dpaste | http://dpaste.com/ gists | https://api.github.com/gists *poundpython | https://paste.pound-python.org/ ``` 在这里,`*` 表示默认服务。 如你所见,Wgetpaste 当前支持五种文本共享服务。我并没有全部尝试,但是我相信所有服务都可以使用。 要将内容上传到其他服务,例如 bpaste.net,请使用如下所示的 `-s` 选项。 ``` $ wgetpaste -s bpaste mytext.txt Your paste can be seen here: https://bpaste.net/show/5199e127e733 ``` #### 3、从标准输入读取输入 Wgetpaste 也可以从标准输入读取。 ``` $ uname -a | wgetpaste ``` 此命令将上传 `uname -a` 命令的输出。 #### 4、上传命令及命令的输出 有时,你可能需要粘贴命令及其输出。为此,请在如下所示的引号内指定命令的内容。 ``` $ wgetpaste -c 'ls -l' ``` 这会将命令 `ls -l` 及其输出上传到 pastebin 服务。 当你想让其他人清楚地知道你刚运行的确切命令及其输出时,此功能很有用。 ![](/data/attachment/album/201912/19/095129tovdosaahmyhpjj1.png) 如你在输出中看到的,我运行了 `ls -l` 命令。 #### 5、上载系统日志文件、配置文件 就像我已经说过的,我们可以上载你的系统中任何类型的文本文件,而不仅仅是普通的文本文件,例如日志文件、特定命令的输出等。例如,你刚刚更新了 Arch Linux 机器,最后系统损坏了。你问你的同事该如何解决此问题,他(她)想阅读 `pacman.log` 文件。 这是上传 `pacman.log` 文件内容的命令: ``` $ wgetpaste /var/log/pacman.log ``` 与你的同事共享 pastebin URL,以便他/她可以查看 `pacman.log`,并通过查看日志文件来帮助你解决问题。 通常,日志文件的内容可能太长,你不希望全部共享它们。在这种情况下,只需使用 `cat` 命令读取输出,然后使用 `tail -n` 命令定义要共享的行数,最后将输出通过管道传递到 Wgetpaste,如下所示。 ``` $ cat /var/log/pacman.log | tail -n 50 | wgetpaste ``` 上面的命令将仅上传 `pacman.log` 文件的“最后 50 行”。 #### 6、将输入网址转换为短链接 默认情况下,Wgetpaste 将在输出中显示完整的 pastebin URL。如果要将输入 URL 转换为短链接,只需使用 `-u` 选项。 ``` $ wgetpaste -u mytext.txt Your paste can be seen here: http://tinyurl.com/y85d8gtz ``` #### 7、设定语言 默认情况下,Wgetpaste 将上传“纯文本”中的文本片段。 要列出指定服务支持的语言,请使用 `-L` 选项。 ``` $ wgetpaste -L ``` 该命令将列出默认服务(poundpython <https://paste.pound-python.org/>)支持的所有语言。 我们可以使用 `-l` 选项来改变它。 ``` $ wgetpaste -l Bash mytext.txt ``` #### 8、在输出中禁用语法突出显示或 html 如上所述,文本片段将以特定的语言格式(纯文本、Bash 等)显示。 但是,你可以更改此行为,以使用 `-r` 选项显示原始文本摘要。 ``` $ wgetpaste -r mytext.txt Your raw paste can be seen here: https://paste.pound-python.org/raw/CUJhQ3jEmr2UvfmD2xCL/ ``` ![](/data/attachment/album/201912/19/095129dllyppq8ppp8509u.png) 如你在上面的输出中看到的,没有语法突出显示,没有 html 格式。只是原始输出。 #### 9、更改 Wgetpaste 默认值 所有默认值(`DEFAULT_{NICK,LANGUAGE,EXPIRATION}[_${SERVICE}]` 和 `DEFAULT_SERVICE`)都可以在 `/etc/wgetpaste.conf` 中全局更改,也可以在 `~/.wgetpaste.conf` 文件中针对每个用户更改。但是,这些文件在我的系统中默认情况下并不存在。我想我们需要手动创建它们。开发人员已经在[这里](http://wgetpaste.zlin.dk/zlin.conf)和[这里](http://wgetpaste.zlin.dk/wgetpaste.example)为这两个文件提供了示例内容。只需使用给定的样本内容手动创建这些文件,并相应地修改参数即可更改 Wgetpaste 的默认设置。 #### 10、获得帮助 要显示帮助部分,请运行: ``` $ wgetpaste -h ``` --- via: <https://www.ostechnix.com/how-to-easily-upload-text-snippets-to-pastebin-like-services-from-commandline/> 作者:[SK](https://www.ostechnix.com/author/sk/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
11,692
简单就是易于调试
https://arp242.net/weblog/easy.html
2019-12-19T10:50:14
[ "简单" ]
https://linux.cn/article-11692-1.html
![](/data/attachment/album/201912/19/104839covf7uno6vpyy4n4.png) 对于框架、库或者工具来说,怎样做才算是“简单”?也许有很多的定义,但我的理解通常是**易于调试**。我经常见到人们宣传某个特定的程序、框架、库、文件格式或者其它什么东西是简单的,因为他们会说“看,我只需要这么一点工作量就能够完成某项工作,这太简单了”。非常好,但并不完善。 你可能只编写一次软件,但几乎总要经历好几个调试周期。注意我说的调试周期并不意味着“代码里面有 bug 你需要修复”,而是说“我需要再看一下这份代码来修复 bug”。为了调试代码,你需要理解它,因此“易于调试”延伸来讲就是“易于理解”。 抽象使得程序易于编写,但往往是以难以理解为代价。有时候这是一个很好的折中,但通常不是。大体上,如果能使程序在日后易于理解和调试,我很乐意花更多的时间来写一些东西,因为这样实际上更省时间。 简洁并不是让程序易于调试的**唯一**方法,但它也许是最重要的。良好的文档也是,但不幸的是好的文档太少了。(注意,质量并**不**取决于字数!) 这种影响是真是存在的。难以调试的程序会有更多的 bug,即使最初的 bug 数量与易于调试的程序完全相同,而是因为修复 bug 更加困难、更花时间。 在公司的环境中,把时间花在难以修复的 bug 上通常被认为是不划算的投资。而在开源的环境下,人们花的时间会更少。(大多数项目都有一个或多个定期的维护者,但成百上千的贡献者提交的仅只是几个补丁) --- 这并不全是 1974 年由 Brian W. Kernighan 和 P. J. Plauger 合著的《<ruby> 编程风格的元素 <rt> The Elements of Programming Style </rt></ruby>》中的观点: > > 每个人都知道调试比起编写程序困难两倍。当你写程序的时候耍小聪明,那么将来应该怎么去调试? > > > 我见过许多看起来写起来“极尽精妙”,但却导致难以调试的代码。我会在下面列出几种样例。争论这些东西本身有多坏并不是我的本意,我仅想强调对于“易于使用”和“易于调试”之间的折中。 * <ruby> ORM <rt> 对象关系映射 </rt></ruby> 库可以让数据库查询变得简单,代价是一旦你想解决某个问题,事情就变得难以理解。 * 许多测试框架让调试变得困难。Ruby 的 rspec 就是一个很好的例子。有一次我不小心使用错了,结果花了很长时间搞清楚**究竟**哪里出了问题(因为它给出错误提示非常含糊)。 我在《[测试并非万能](https://www.arp242.net/testing.html)》这篇文章中写了更多关于以上的例子。 * 我用过的许多 JavaScript 框架都很难完全理解。Clever(LCTT 译注:一种 JS 框架)的语句一向很有逻辑,直到某条语句不能如你预期的工作,这时你就只能指望 Stack Overflow 上的某篇文章或 GitHub 上的某个回帖来帮助你了。 这些函数库**确实**让任务变得非常简单,使用它们也没有什么错。但通常人们都过于关注“易于使用”而忽视了“易于调试”这一点。 * Docker 非常棒,并且让许多事情变得非常简单,直到你看到了这条提示: ``` ERROR: for elasticsearch Cannot start service elasticsearch: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:258: applying cgroup configuration for process caused \"failed to write 898 to cgroup.procs: write /sys/fs/cgroup/cpu,cpuacct/docker/b13312efc203e518e3864fc3f9d00b4561168ebd4d9aad590cc56da610b8dd0e/cgroup.procs: invalid argument\"" ``` 或者这条: ``` ERROR: for elasticsearch Cannot start service elasticsearch: EOF ``` 那么…你怎么看? * `Systemd` 比起 `SysV`、`init.d` 脚本更加简单,因为编写 `systemd` 单元文件比起编写 `shell` 脚本更加方便。这也是 Lennart Poetterin 在他的 [systemd 神话](http://0pointer.de/blog/projects/the-biggest-myths.html) 中解释 `systemd` 为何简单时使用的论点。 我非常赞同 Poettering 的观点——也可以看 [shell 脚本陷阱](https://www.arp242.net/shell-scripting-trap.html) 这篇文章。但是这种角度并不全面。单元文件简单的背后意味着 `systemd` 作为一个整体要复杂的多,并且用户确实会受到它的影响。看看我遇到的这个[问题](https://unix.stackexchange.com/q/185495/33645)和为它所做的[修复](https://cgit.freedesktop.org/systemd/systemd/commit/?id=6e392c9c45643d106673c6643ac8bf4e65da13c1)。看起来很简单吗? --- via: <https://arp242.net/weblog/easy.html> 作者:[Martin Tournoij](https://arp242.net/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[LuuMing](https://github.com/LuuMing) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,695
在 Linux 上使用 Ksnip 注释截图
https://opensource.com/article/19/12/annotate-screenshots-linux-ksnip
2019-12-20T00:30:07
[ "截屏" ]
https://linux.cn/article-11695-1.html
> > Ksnip 让你能轻松地在 Linux 中创建和标记截图。 > > > ![](/data/attachment/album/201912/20/002955l3o4unq6ieuzxeqx.jpg) 我最近从 MacOS 切换到了 [Elementary OS](https://elementary.io/),这是一个专注于易用性和隐私性的 Linux 发行版。作为用户体验设计师和自由软件支持者,我会经常截图并进行注释。在尝试了几种不同的工具之后,到目前为止,我最喜欢的工具是 [Ksnip](https://github.com/damirporobic/ksnip),它是 GPLv2 许可下的一种开源工具。 ![Ksnip screenshot](/data/attachment/album/201912/20/003035etwouuw399ofzs8a.png "Ksnip screenshot") ### 安装 使用你首选的包管理器安装 Ksnip。我通过 Apt 安装了它: ``` sudo apt-get install ksnip ``` ### 配置 Ksnip 有许多配置选项,包括: * 保存截图的地方 * 默认截图的文件名 * 图像采集器行为 * 光标颜色和宽度 * 文字字体 你也可以将其与你的 Imgur 帐户集成。 ![Ksnip configuration options](/data/attachment/album/201912/20/003046yeeub6e44vhqmtqp.png "Ksnip configuration options") ### 用法 Ksnip 提供了大量的[功能](https://github.com/DamirPorobic/ksnip#features)。我最喜欢的 Ksnip 部分是它拥有我需要的所有注释工具(还有一个我没想到的工具!)。 你可以使用以下注释: * 钢笔 * 记号笔 * 矩形 * 椭圆 * 文字 你还可以模糊区域来移除敏感信息。还有使用我最喜欢的新工具:用于在界面上表示步骤的带数字的点。 ### 关于作者 我非常喜欢 Ksnip,因此我联系了作者 [Damir Porobic](https://github.com/damirporobic/) 来了解有关该项目的更多信息。 当我问到是什么启发了他编写 Ksnip 时,他说: > > “几年前我从 Windows 切换到 Linux,却没有了在 Windows 中常用的 Windows Snipping Tool。当时的所有其他截图工具要么很大(很多按钮和复杂功能),要么缺少诸如注释等关键功能,所以我决定编写一个简单的 Windows Snipping Tool 克隆版,但是随着时间的流逝,它开始有越来越多的功能。“ > > > 这正是我在评估截图工具时发现的。他花时间构建解决方案并免费共享给他人使用,这真是太好了。 至于 Ksnip 的未来,Damir 希望添加全局快捷方式(至少对于 Windows 是这样)和用于新截图的选项卡,并允许该应用在后台运行。GitHub 上的功能请求列表也越来越多。 ### 帮助的方式 Damir 最需要的是帮助开发 Ksnip。他和他的妻子很快就会有孩子了,所以他将没有太多的时间放在这个项目上。不过,他可以检查和接受拉取请求。 此外,此项目还可以通过 Snap 、Flatpak 以及 MacOS 安装包、Windows 安装包等其他安装方式安装。如果你想提供帮助,请查看 Ksnip 的 README 的 [Contribution](https://github.com/DamirPorobic/ksnip/blob/master/README.md#contribution) 部分。 --- > > 此文章最初发表在 [Agaric Tech Cooperative 的博客](https://agaric.coop/blog/annotate-screenshots-linux-ksnip)上,并经允许重新发布。 > > > --- via: <https://opensource.com/article/19/12/annotate-screenshots-linux-ksnip> 作者:[Clayton Dewey](https://opensource.com/users/cedewey) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
I recently switched from MacOS to [Elementary OS](https://elementary.io/), a Linux distribution focused on ease of use and privacy. As a user-experience designer and a free software supporter, I take screenshots and annotate them all the time. After trying out several different tools, the one I enjoy the most by far is [Ksnip](https://github.com/damirporobic/ksnip), an open source tool licensed under GPLv2. ![Ksnip screenshot Ksnip screenshot](https://opensource.com/sites/default/files/uploads/ksnip.png) ## Installation Install Ksnip with your preferred package manager. I installed it via Apt: `sudo apt-get install ksnip` ## Configuration Ksnip comes with quite a few configuration options, including: - Location to save screenshots - Default screenshot filename - Image grabber behavior - Cursor color and thickness - Text font You can also integrate it with your Imgur account. ![Ksnip configuration options Ksnip configuration options](https://opensource.com/sites/default/files/uploads/ksnip-configuration.png) ## Usage Ksnip offers a wide range of [features](https://github.com/DamirPorobic/ksnip#features). My favorite part of Ksnip is that it has all the annotation tools I need (plus one I hadn't thought of!). You can annotate with: - Pen - Marker - Rectangles - Ellipses - Text You can also blur areas to remove sensitive information. And use my new favorite tool: numbered dots for steps on an interface. ## About the creator I'm enjoying Ksnip so much that I reached out to the creator, [Damir Porobic](https://github.com/damirporobic/), to learn more about the project. When I asked what inspired him to create Ksnip, he said: "I switched from Windows to Linux a few years ago and missed the Windows Snipping Tool that I was used to on Windows. All other screenshot tools at that time were either huge (a lot of buttons and complex features) or lacked key features like annotations, so I decided to build a simple Snipping Tool clone, but with time it got more and more features. So here we are." This is exactly what I found as I was evaluating screenshot tools. It's great that he took the time to build a solution and freely share it for others to benefit. As for the future of Ksnip, Damir would like to add global shortcuts (at least for Windows) and tabs for new screenshots and allow the application to run in the background. There is also a growing list of feature requests on GitHub. ## Ways to help Damir's biggest need for Ksnip help is with development. He and his wife are expecting a baby soon, so he won't have as much time to devote to the project. He is available to review and accept pull requests, though. Also, the project could benefit from additional installation options via Snap and Flatpak and installers for MacOS and a setup for Windows. If you would like to help, check out the [Contribution](https://github.com/DamirPorobic/ksnip/blob/master/README.md#contribution) section of Ksnip's README. *This article originally appeared on Agaric Tech Cooperative's blog and is republished with permission.* ## Comments are closed.
11,696
将你的应用迁移到 Python 3 的三个步骤
https://opensource.com/article/19/12/update-apps-python-3
2019-12-20T09:52:51
[ "Python" ]
https://linux.cn/article-11696-1.html
> > Python 2 气数将尽,是时候将你的项目从 Python 2 迁移到 Python 3 了。 > > > ![](/data/attachment/album/201912/20/095224r0kp79s0cnc0z77p.jpg) Python 2.x 很快就要[失去官方支持](/article-11629-1.html)了,尽管如此,从 Python 2 迁移到 Python 3 却并没有想象中那么难。我在上周用了一个晚上的时间将一个 3D 渲染器的前端代码及其对应的 [PySide](https://pypi.org/project/PySide/) 迁移到 Python 3,回想起来,尽管在迁移过程中无可避免地会遇到一些牵一发而动全身的修改,但整个过程相比起痛苦的重构来说简直是出奇地简单。 每个人都别无选择地有各种必须迁移的原因:或许是觉得已经拖延太久了,或许是依赖了某个在 Python 2 下不再维护的模块。但如果你仅仅是想通过做一些事情来对开源做贡献,那么把一个 Python 2 应用迁移到 Python 3 就是一个简单而又有意义的做法。 无论你从 Python 2 迁移到 Python 3 的原因是什么,这都是一项重要的任务。按照以下三个步骤,可以让你把任务完成得更加清晰。 ### 1、使用 2to3 从几年前开始,Python 在你或许还不知道的情况下就已经自带了一个名叫 [2to3](https://docs.python.org/3.1/library/2to3.html) 的脚本,它可以帮助你实现大部分代码从 Python 2 到 Python 3 的自动转换。 下面是一段使用 Python 2.6 编写的代码: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- mystring = u'abcdé' print ord(mystring[-1]) ``` 对其执行 2to3 脚本: ``` $ 2to3 example.py RefactoringTool: Refactored example.py --- example.py (original) +++ example.py (refactored) @@ -1,5 +1,5 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -mystring = u'abcdé' -print ord(mystring[-1]) +mystring = 'abcdé' +print(ord(mystring[-1])) RefactoringTool: Files that need to be modified: RefactoringTool: example.py ``` 在默认情况下,`2to3` 只会对迁移到 Python 3 时必须作出修改的代码进行标示,在输出结果中显示的 Python 3 代码是直接可用的,但你可以在 2to3 加上 `-w` 或者 `--write` 参数,这样它就可以直接按照给出的方案修改你的 Python 2 代码文件了。 ``` $ 2to3 -w example.py [...] RefactoringTool: Files that were modified: RefactoringTool: example.py ``` `2to3` 脚本不仅仅对单个文件有效,你还可以把它用于一个目录下的所有 Python 文件,同时它也会递归地对所有子目录下的 Python 文件都生效。 ### 2、使用 Pylint 或 Pyflakes 有一些不良的代码在 Python 2 下运行是没有异常的,在 Python 3 下运行则会或多或少报出错误,这种情况并不鲜见。因为这些不良代码无法通过语法转换来修复,所以 `2to3` 对它们没有效果,但一旦使用 Python 3 来运行就会产生报错。 要找出这种问题,你需要使用 [Pylint](https://opensource.com/article/19/10/python-pylint-introduction)、[Pyflakes](https://pypi.org/project/pyflakes/)(或 [flake8](https://opensource.com/article/19/5/python-flake8) 封装器)这类工具。其中我更喜欢 Pyflakes,它会忽略代码风格上的差异,在这一点上它和 Pylint 不同。尽管代码优美是 Python 的一大特点,但在代码迁移的层面上,“让代码功能保持一致”无疑比“让代码风格保持一致”重要得多。 以下是 Pyflakes 的输出样例: ``` $ pyflakes example/maths example/maths/enum.py:19: undefined name 'cmp' example/maths/enum.py:105: local variable 'e' is assigned to but never used example/maths/enum.py:109: undefined name 'basestring' example/maths/enum.py:208: undefined name 'EnumValueCompareError' example/maths/enum.py:208: local variable 'e' is assigned to but never used ``` 上面这些由 Pyflakes 输出的内容清晰地给出了代码中需要修改的问题。相比之下,Pylint 会输出多达 143 行的内容,而且多数是诸如代码缩进这样无关紧要的问题。 值得注意的是第 19 行这个容易产生误导的错误。从输出来看你可能会以为 `cmp` 是一个在使用前未定义的变量,实际上 `cmp` 是 Python 2 的一个内置函数,而它在 Python 3 中被移除了。而且这段代码被放在了 `try` 语句块中,除非认真检查这段代码的输出值,否则这个问题很容易被忽略掉。 ``` try: result = cmp(self.index, other.index) except: result = 42 return result ``` 在代码迁移过程中,你会发现很多原本在 Python 2 中能正常运行的函数都发生了变化,甚至直接在 Python 3 中被移除了。例如 PySide 的绑定方式发生了变化、`importlib` 取代了 `imp` 等等。这样的问题只能见到一个解决一个,而涉及到的功能需要重构还是直接放弃,则需要你自己权衡。但目前来说,大多数问题都是已知的,并且有[完善的文档记录](https://docs.python.org/3.0/whatsnew/3.0.html)。所以难的不是修复问题,而是找到问题,从这个角度来说,使用 Pyflake 是很有必要的。 ### 3、修复被破坏的 Python 2 代码 尽管 `2to3` 脚本能够帮助你把代码修改成兼容 Python 3 的形式,但对于一个完整的代码库,它就显得有点无能为力了,因为一些老旧的代码在 Python 3 中可能需要不同的结构来表示。在这样的情况下,只能人工进行修改。 例如以下代码在 Python 2.6 中可以正常运行: ``` class CLOCK_SPEED: TICKS_PER_SECOND = 16 TICK_RATES = [int(i * TICKS_PER_SECOND) for i in (0.5, 1, 2, 3, 4, 6, 8, 11, 20)] class FPS: STATS_UPDATE_FREQUENCY = CLOCK_SPEED.TICKS_PER_SECOND ``` 类似 `2to3` 和 Pyflakes 这些自动化工具并不能发现其中的问题,但如果上述代码使用 Python 3 来运行,解释器会认为 `CLOCK_SPEED.TICKS_PER_SECOND` 是未被明确定义的。因此就需要把代码改成面向对象的结构: ``` class CLOCK_SPEED: def TICKS_PER_SECOND(): TICKS_PER_SECOND = 16 TICK_RATES = [int(i * TICKS_PER_SECOND) for i in (0.5, 1, 2, 3, 4, 6, 8, 11, 20)] return TICKS_PER_SECOND class FPS: STATS_UPDATE_FREQUENCY = CLOCK_SPEED.TICKS_PER_SECOND() ``` 你也许会认为如果把 `TICKS_PER_SECOND()` 改写为一个构造函数(用 `__init__` 函数设置默认值)能让代码看起来更加简洁,但这样就需要把这个方法的调用形式从 `CLOCK_SPEED.TICKS_PER_SECOND()` 改为 `CLOCK_SPEED()` 了,这样的改动或多或少会对整个库造成一些未知的影响。如果你对整个代码库的结构烂熟于心,那么你确实可以随心所欲地作出这样的修改。但我通常认为,只要我做出了修改,都可能会影响到其它代码中的至少三处地方,因此我更倾向于不使代码的结构发生改变。 ### 坚持信念 如果你正在尝试将一个大项目从 Python 2 迁移到 Python 3,也许你会觉得这是一个漫长的过程。你可能会费尽心思也找不到一条有用的报错信息,这种情况下甚至会有将代码推倒重建的冲动。但从另一个角度想,代码原本在 Python 2 中就可以运行,要让它能在 Python 3 中继续运行,你需要做的只是对它稍加转换而已。 但只要你完成了迁移,你就得到了这个模块或者整个应用程序的 Python 3 版本,外加 Python 官方的长期支持。 --- via: <https://opensource.com/article/19/12/update-apps-python-3> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[HankChow](https://github.com/HankChow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The 2.x series of Python is [officially over as of January 2020](https://opensource.com/article/19/11/end-of-life-python-2), and [unsupported after April 2020](https://www.python.org/psf/press-release/pr20191220/), but converting code to Python 3 is easier than you think. Over the weekend, I spent an evening converting the frontend code of a 3D renderer (and its corresponding [Python for Qt/PySide](https://pypi.org/project/PySide/) version) to Python 3, and it was surprisingly simple in retrospect, although it seemed relatively hopeless during the refactoring process. The conversion process can seem a little like a labyrinth, with every change you make revealing a dozen more changes you need to make. You may or may not *want* to do the conversion, but—whether it's because you procrastinated too long or you rely on a module that won't be maintained unless you convert—sometimes you just don't have a choice. And if you're looking for an easy task to start your contribution to open source, converting a Python 2 app to Python 3 is a great way to make an easy but meaningful impression. Whatever your reason for refactoring Python 2 code into Python 3, it's an important job. Here are three steps to approach the task with clarity. ## 1. Run 2to3 For the past several years, Python has shipped with a script called [ 2to3](https://docs.python.org/3.1/library/2to3.html), which does the bulk of the conversion from Python 2 to Python 3 for you. Automatically. And you already have it installed (whether you realize it or not). Here's a short snippet of code written in Python 2.6: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- mystring = u'abcdé' print ord(mystring[-1]) ``` Run the **2to3** script: ``` $ 2to3 example.py RefactoringTool: Refactored example.py --- example.py (original) +++ example.py (refactored) @@ -1,5 +1,5 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -mystring = u'abcdé' -print ord(mystring[-1]) +mystring = 'abcdé' +print(ord(mystring[-1])) RefactoringTool: Files that need to be modified: RefactoringTool: example.py ``` By default, **2to3** prints only the changes required to bring old Python code up to Python 3 standards. The output is a usable patch you can use to change your file, but it's easier to just let Python do that for you, using the **--write** (or **-w**) option: ``` $ 2to3 -w example.py [...] RefactoringTool: Files that were modified: RefactoringTool: example.py ``` The **2to3** script doesn't work on just a single file. You can run it on an entire directory of Python files, with or without the **--write** option, to process all ***.py** files in the directory and its subdirectories. ## 2. Use Pylint or Pyflakes It's not uncommon to discover code quirks that ran without issue in Python 2 but don't work so well in Python 3. Because these quirks can't be fixed by converting syntax, they get past **2to3** unchanged, but they fail once you try to run the code. To detect such issues, you can use an application like [Pylint](https://opensource.com/article/19/10/python-pylint-introduction) or a tool like [Pyflakes](https://pypi.org/project/pyflakes/) (or the [flake8](https://opensource.com/article/19/5/python-flake8) wrapper). I prefer Pyflakes because, unlike Pylint, it ignores deviations in the *style* of your code. While the "prettiness" of Python is often praised as one of its strong points, when porting someone else's code from 2 to 3, treating style and function as two separate bugs is a matter of prioritization. Here's example output from Pyflakes: ``` $ pyflakes example/maths example/maths/enum.py:19: undefined name 'cmp' example/maths/enum.py:105: local variable 'e' is assigned to but never used example/maths/enum.py:109: undefined name 'basestring' example/maths/enum.py:208: undefined name 'EnumValueCompareError' example/maths/enum.py:208: local variable 'e' is assigned to but never used ``` This output (compared to 143 lines from Pylint, most of which were complaints about indentation) clearly displays the problems in the code that you should repair. The most interesting error here is the first one, on line 19. It's a little misleading because you might think that **cmp** is a variable that was never defined, but **cmp** is really a function from Python 2 that doesn't exist in Python 3. It's wrapped in a **try** statement, so the issue could easily go unnoticed until it becomes obvious that the **try** result is not getting produced. ``` try: result = cmp(self.index, other.index) except: result = 42 return result ``` There are countless examples of functions that no longer exist or that have changed between when an application was maintained as a Python 2 codebase and when you decide to port it. PySide(2) bindings have changed, Python functions have disappeared or been transformed (**imp** to **importlib**, for example), and so on. Fix them one by one as you encounter them. Even though it's up to you to reimplement or replace those missing functions, by now, most of these issues are known and [well-documented](https://docs.python.org/3.0/whatsnew/3.0.html). The real challenge is more about catching the errors than fixing them, so use Pyflakes or a similar tool. ## 3. Repair broken Python 2 code The **2to3** script gets your code Python 3 compliant, but it only knows about differences between Python 2 and 3. It generally can't make adjustments to account for changes in libraries that worked one way back in 2010 but have had major revisions since then. You must update that code manually. For instance, this code apparently worked back in the days of Python 2.6: ``` class CLOCK_SPEED: TICKS_PER_SECOND = 16 TICK_RATES = [int(i * TICKS_PER_SECOND) for i in (0.5, 1, 2, 3, 4, 6, 8, 11, 20)] class FPS: STATS_UPDATE_FREQUENCY = CLOCK_SPEED.TICKS_PER_SECOND ``` Automated tools like **2to3** and **Pyflakes** don't detect the problem, but Python 3 doesn't see **GAME_SPEED.TICKS_PER_SECOND** as a valid statement because the function being called was never explicitly declared. Adjusting the code is a simple exercise in object-oriented programming: ``` class CLOCK_SPEED: def TICKS_PER_SECOND(): TICKS_PER_SECOND = 16 TICK_RATES = [int(i * TICKS_PER_SECOND) for i in (0.5, 1, 2, 3, 4, 6, 8, 11, 20)] return TICKS_PER_SECOND class FPS: STATS_UPDATE_FREQUENCY = CLOCK_SPEED.TICKS_PER_SECOND() ``` You may be inclined to make it cleaner still by replacing the **TICKS_PER_SECOND** function with a constructor (an **__init__** function to set default values), but that would change the required call from **CLOCK_SPEED.TICKS_PER_SECOND()** to just **CLOCK_SPEED()**, which may or may not have ramifications elsewhere in the codebase. If you know the code well, then you can use your better judgment about how much alteration is *required* and how much would just be pleasant, but generally, I prefer to assume every change I make inevitably demands at least three changes to every other file in the project, so I try to work within its existing structure. ## Don't stop believing If you're porting a very large project, it sometimes starts to feel like there's no end in sight. It can seem like forever before you see a useful error message that's *not* about a Python 2 quirk that slipped past the scripts and linters, and once you get to that point, you'll start to suspect it would be easier to just start from scratch. The bright side is that you (presumably) know that the codebase you're porting works (or worked) in Python 2, and once you make your adjustments, it will work again in Python 3; it's just a matter of conversion. Once you've done the legwork, you'll have a Python 3 module or application, and regular maintenance (and those style changes to make Pylint happy) can begin anew! ## Comments are closed.
11,698
如何为 Linux 桌面配置 Openbox
https://opensource.com/article/19/12/openbox-linux-desktop
2019-12-20T10:23:41
[]
https://linux.cn/article-11698-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。Openbox 窗口管理器占用很小的系统资源、易于配置、使用愉快。 > > > ![](/data/attachment/album/201912/20/102327hdl3gcychsc53y3m.jpg) 你可能不知道你使用过 [Openbox](http://openbox.org) 桌面:尽管 Openbox 本身是一个出色的窗口管理器,但它还是 LXDE 和 LXQT 等桌面环境的窗口管理器“引擎”,它甚至可以管理 KDE 和 GNOME。除了作为多个桌面的基础之外,Openbox 可以说是最简单的窗口管理器之一,可以为那些不想学习那么多配置选项的人配置。通过使用基于菜单的 obconf 的配置应用,可以像在 GNOME 或 KDE 这样的完整桌面中一样轻松地设置所有常用首选项。 ### 安装 Openbox 你可能会在 Linux 发行版的软件仓库中找到 Openbox,也可以在 [Openbox.org](http://openbox.org/wiki/Openbox:Download) 中找到它。如果你已经在运行其他桌面,那么可以安全地在同一系统上安装 Openbox,因为 Openbox 除了几个配置面板之外,不包括任何捆绑的应用。 安装后,退出当前桌面会话,以便你可以登录 Openbox 桌面。默认情况下,会话管理器(KDM、GDM、LightDM 或 XDM,这取决于你的设置)将继续登录到以前的桌面,因此你必须在登录之前覆盖该选择。 要使用 GDM 覆盖它: ![Select your desktop session in GDM](/data/attachment/album/201912/20/102343or9aa60asgpsipsi.jpg "Select your desktop session in GDM") 要使用 SDDM 覆盖它: ![Select your desktop session with KDM](/data/attachment/album/201912/20/102344dj2xb7rrrmmjjrb2.jpg "Select your desktop session with KDM") ### 配置 Openbox 桌面 默认情况下,Openbox 包含 obconf 应用,你可以使用它来选择和安装主题、修改鼠标行为、设置桌面首选项等。你可能会在仓库中发现其他配置应用,如 obmenu,用于配置窗口管理器的其他部分。 ![Openbox Obconf configuration application](/data/attachment/album/201912/20/102345v60rknt55uuwwbuw.jpg "Openbox Obconf configuration application") 构建你自己的桌面环境相对容易。它有一些所有常见的桌面组件,例如系统托盘 [stalonetray](https://sourceforge.net/projects/stalonetray/)、任务栏 [Tint2](https://opensource.com/article/19/1/productivity-tool-tint2) 或 [Xfce4-panel](http://xfce.org) 等几乎你能想到的。任意组合应用,直到拥有梦想的开源桌面为止。 ![Openbox](/data/attachment/album/201912/20/102346hlt000e6wmwmkwfi.jpg "Openbox") ### 为何使用 Openbox Openbox 占用的系统资源很小、易于配置、使用起来很愉悦。它基本不会让你感觉到阻碍,会是一个容易熟悉的系统。你永远不会知道你面前的桌面环境秘密使用了 Openbox 作为窗口管理器(知道如何自定义它会不会很高兴?)。如果开源吸引你,那么试试看 Openbox。 --- via: <https://opensource.com/article/19/12/openbox-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
You may have used the [Openbox](http://openbox.org) desktop without knowing it: While Openbox is a great window manager on its own, it also serves as the window manager "engine" for desktop environments like LXDE and LXQT, and it can even manage KDE and GNOME. Aside from being the foundation for several desktops, Openbox is arguably one of the easiest window managers to configure for anyone who doesn't want to learn all the options to put into a config file. By using the **obconf** menu-based configuration application, all the common preferences can be set just as easily as in a full desktop, like GNOME or KDE. ## Installing Openbox You are likely to find Openbox in the software repository of your Linux distribution, but you can also find it on [Openbox.org](http://openbox.org/wiki/Openbox:Download). If you're already running a different desktop, it's safe to install Openbox on the same system, because Openbox doesn't include any bundled applications aside from a few configuration panels. After installing it, log out of your current desktop session so you can log into your Openbox desktop. By default, your session manager (KDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. To override it with GDM: ![Select your desktop session in GDM Select your desktop session in GDM](https://opensource.com/sites/default/files/advent-gdm_0.jpg) With SDDM: ![Select your desktop session with KDM Select your desktop session with KDM](https://opensource.com/sites/default/files/advent-kdm.jpg) ## Configure the Openbox desktop By default, Openbox includes the **obconf** application, which you can use to choose and install themes, modify mouse behavior, set desktop preferences, and do much more. You can probably find other configuration applications, like **obmenu**, in your repository to configure other parts of your window manager. ![Openbox Obconf configuration application Openbox Obconf configuration application](https://opensource.com/sites/default/files/uploads/advent-openbox-obconf_675px.jpg) Building your own desktop experience is relatively easy. There are little components for all the usual desktop tropes, like [stalonetray](https://sourceforge.net/projects/stalonetray/) for a system tray, [Tint2](https://opensource.com/article/19/1/productivity-tool-tint2) for a taskbar, or [Xfce4-panel](http://xfce.org) for nearly anything you can think of. String any set of applications together until you have the open source desktop of your dreams. ![Openbox Openbox](https://opensource.com/sites/default/files/uploads/advent-openbox_675px.jpg) ## Why you should use Openbox Openbox is light on system resources, easy to configure, and a pleasure to use. It pops up in the unlikeliest of places, so it can be a good system to get familiar with. You never know when you'll be in front of a desktop that secretly uses Openbox as its window manager (and won't it be nice that you know how to customize it?). If critical mass and open source appeal to you, open up the Openbox box and get started. ## Comments are closed.
11,699
互联网的安全是如何保证的:TLS、SSL 和 CA
https://opensource.com/article/19/11/internet-security-tls-ssl-certificate-authority
2019-12-21T08:46:11
[ "HTTPS", "SSL" ]
https://linux.cn/article-11699-1.html
> > 你的浏览器里的锁的图标的后面是什么? > > > ![Lock](/data/attachment/album/201912/21/084614pr4qbwrbranqurus.jpg) 每天你都会重复这件事很多次,访问网站,网站需要你用你的用户名或者电子邮件地址和你的密码来进行登录。银行网站、社交网站、电子邮件服务、电子商务网站和新闻网站。这里只在使用了这种机制的网站中列举了其中一小部分。 每次你登录进一个这种类型的网站时,你实际上是在说:“是的,我信任这个网站,所以我愿意把我的个人信息共享给它。”这些数据可能包含你的姓名、性别、实际地址、电子邮箱地址,有时候甚至会包括你的信用卡信息。 但是你怎么知道你可以信任这个网站?换个方式问,为了让你可以信任它,网站应该如何保护你的交易? 本文旨在阐述使网站变得安全的机制。我会首先论述 web 协议 http 和 https,以及<ruby> 传输层安全 <rt> Transport Layer Security </rt></ruby>(TLS)的概念,后者是<ruby> 互联网协议 <rt> Internet Protocol </rt></ruby>(IP)层中的加密协议之一。然后,我会解释<ruby> 证书颁发机构 <rt> certificate authority </rt></ruby>和自签名证书,以及它们如何帮助保护一个网站。最后,我会介绍一些开源的工具,你可以使用它们来创建和管理你的证书。 ### 通过 https 保护路由 了解一个受保护的网站的最简单的方式就是在交互中观察它,幸运的是,在今天的互联网上,发现一个安全的网站远远比找到一个不安全的网站要简单。但是,因为你已经在 Opensource.com 这个网站上了,我会使用它来作为案例,无论你使用的是哪个浏览器,你应该在你的地址栏旁边看到一个像锁一样的图标。点击这个锁图标,你应该会看见一些和下面这个类似的东西。 ![Certificate information](/data/attachment/album/201912/21/084618xx1d14j17f7pxojk.jpg) 默认情况下,如果一个网站使用的是 http 协议,那么它是不安全的。为通过网站主机的路由添加一个配置过的证书,可以把这个网站从一个不安全的 http 网站变为一个安全的 https 网站。那个锁图标通常表示这个网站是受 https 保护的。 点击证书来查看网站的 CA,根据你的浏览器,你可能需要下载证书来查看它。 ![Certificate information](/data/attachment/album/201912/21/084622my6906ys22n22npj.jpg) 在这里,你可以了解有关 Opensource.com 证书的信息。例如,你可以看到 CA 是 DigiCert,并以 Opensource.com 的名称提供给 Red Hat。 这个证书信息可以让终端用户检查该网站是否可以安全访问。 > > 警告:如果你没有在网站上看到证书标志,或者如果你看见的标志显示这个网站不安全——请不要登录或者做任何需要你个人数据的操作。这种情况非常危险! > > > 如果你看到的是警告标志,对于大多数面向公众开放的网站来说,这很少见,它通常意味着该证书已经过期或者是该证书是自签名的,而非通过一个受信任的第三方来颁发。在我们进入这些主题之前,我想解释一下 TLS 和 SSL。 ### 带有 TLS 和 SSL 的互联网协议 TLS 是旧版<ruby> 安全套接字层协议 <rt> Secure Socket Layer </rt></ruby>(SSL)的最新版本。理解这一点的最好方法就是仔细理解互联网协议的不同协议层。 ![IP layers](/data/attachment/album/201912/21/084624qhhqdt2dbfl2l1a1.jpg) 我们知道当今的互联网是由 6 个层面组成的:物理层、数据链路层、网络层、传输层、安全层、应用层。物理层是基础,这一层是最接近实际的硬件设备的。应用层是最抽象的一层,是最接近终端用户的一层。安全层可以被认为是应用层的一部分,TLS 和 SSL,是被设计用来在一个计算机网络中提供通信安全的加密协议,它们位于安全层中。 这个过程可以确保终端用户使用网络服务时,通信的安全性和保密性。 ### 证书颁发机构和自签名证书 <ruby> 证书颁发机构 <rt> Certificate authority </rt></ruby>(CA)是受信任的组织,它可以颁发数字证书。 TLS 和 SSL 可以使连接更安全,但是这个加密机制需要一种方式来验证它;这就是 SSL/TLS 证书。TLS 使用了一种叫做非对称加密的加密机制,这个机制有一对称为私钥和公钥的安全密钥。(这是一个非常复杂的主题,超出了本文的讨论范围,但是如果你想去了解这方面的东西,你可以阅读“[密码学和公钥密码基础体系简介](https://opensource.com/article/18/5/cryptography-pki)”)你要知道的基础内容是,证书颁发机构们,比如 GlobalSign、DigiCert 和 GoDaddy,它们是受人们信任的可以颁发证书的供应商,它们颁发的证书可以用于验证网站使用的 TLS/SSL 证书。网站使用的证书是导入到主机服务器里的,用于保护网站。 然而,如果你只是要测试一下正在开发中的网站或服务,CA 证书可能对你而言太昂贵或者是太复杂了。你必须有一个用于生产目的的受信任的证书,但是开发者和网站管理员需要有一种更简单的方式来测试网站,然后他们才能将其部署到生产环境中;这就是自签名证书的来源。 自签名证书是一种 TLS/SSL 证书,是由创建它的人而非受信任的 CA 机构颁发的。用电脑生成一个自签名证书很简单,它可以让你在无需购买昂贵的 CA 颁发的证书的情况下测试一个安全网站。虽然自签名证书肯定不能拿到生产环境中去使用,但对于开发和测试阶段来说,这是一种简单灵活的方法。 ### 生成证书的开源工具 有几种开源工具可以用来管理 TLS/SSL 证书。其中最著名的就是 openssl,这个工具包含在很多 Linux 发行版中和 MacOS 中。当然,你也可以使用其他开源工具。 | 工具名 | 描述 | 许可证 | | --- | --- | --- | | [OpenSSL](https://www.openssl.org/) | 实现 TLS 和加密库的最著名的开源工具 | Apache License 2.0 | | [EasyRSA](https://github.com/OpenVPN/easy-rsa) | 用于构建 PKI CA 的命令行实用工具 | GPL v2 | | [CFSSL](https://github.com/cloudflare/cfssl) | 来自 cloudflare 的 PKI/TLS 瑞士军刀 | BSD 2-Clause Simplified License | | [Lemur](https://github.com/Netflix/lemur) | 来自<ruby> 网飞 <rt> Netflix </rt></ruby>的 TLS 创建工具 | Apache License 2.0 | 如果你的目的是扩展和对用户友好,网飞的 Lemur 是一个很有趣的选择。你在[网飞的技术博客](https://medium.com/netflix-techblog/introducing-lemur-ceae8830f621)上可以查看更多有关它的信息。 ### 如何创建一个 Openssl 证书 你可以靠自己来创建证书,下面这个案例就是使用 Openssl 生成一个自签名证书。 1、使用 `openssl` 命令行生成一个私钥: ``` openssl genrsa -out example.key 2048 ``` ![](/data/attachment/album/201912/21/084626b2clfjd9dy8cz2ov.jpg) 2、使用在第一步中生成的私钥来创建一个<ruby> 证书签名请求 <rt> certificate signing request </rt></ruby>(CSR): ``` openssl req -new -key example.key -out example.csr -subj "/C=US/ST=TX/L=Dallas/O=Red Hat/OU=IT/CN=test.example.com" ``` ![](/data/attachment/album/201912/21/084632jmmxbk4vulnrcvvb.jpg) 3、使用你的 CSR 和私钥创建一个证书: ``` openssl x509 -req -days 366 -in example.csr -signkey example.key -out example.crt ``` ![](/data/attachment/album/201912/21/084634zssm9s6r8hmriqti.jpg) ### 了解更多关于互联网安全的知识 如果你想要了解更多关于互联网安全和网站安全的知识,请看我为这篇文章一起制作的 Youtube 视频。 你有什么问题?发在评论里让我们知道。 --- via: <https://opensource.com/article/19/11/internet-security-tls-ssl-certificate-authority> 作者:[Bryant Son](https://opensource.com/users/brson) 选题:[lujun9972](https://github.com/lujun9972) 译者:[hopefully2333](https://github.com/hopefully2333) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Multiple times every day, you visit websites that ask you to log in with your username or email address and password. Banking websites, social networking sites, email services, e-commerce sites, and news sites are just a handful of the types of sites that use this mechanism. Every time you sign into one of these sites, you are, in essence, saying, "yes, I trust this website, so I am willing to share my personal information with it." This data may include your name, gender, physical address, email address, and sometimes even credit card information. But how do you know you can trust a particular website? To put this a different way, what is the website doing to secure your transaction so that you can trust it? This article aims to demystify the mechanisms that make a website secure. I will start by discussing the web protocols HTTP and HTTPS and the concept of Transport Layer Security (TLS), which is one of the cryptographic protocols in the internet protocol's (IP) layers. Then, I will explain certificate authorities (CAs) and self-signed certificates and how they can help secure a website. Finally, I will introduce some open source tools you can use to create and manage certificates. ## Securing routes through HTTPS The easiest way to understand a secured website is to see it in action. Fortunately, it is far easier to find a secured website than an unsecured website on the internet today. But, since you are already on Opensource.com, I'll use it as an example. No matter what browser you're using, you should see an icon that looks like a lock next to the address bar. Click on the lock icon, and you should see something similar to this. ![Certificate information Certificate information](https://opensource.com/sites/default/files/uploads/1_certificatecheckwebsite.jpg) By default, a website is not secure if it uses the HTTP protocol. Adding a certificate configured through the website host to the route can transform the website from an unsecured HTTP site to a secured HTTPS site. The lock icon usually indicates that the site is secured through HTTPS. Click on Certificate to see the site's CA. Depending on your browser, you may need to download the certificate to see it. ![Certificate information Certificate information](https://opensource.com/sites/default/files/uploads/2_certificatedisplaywebsite.jpg) Here, you can learn something about Opensource.com's certificate. For example, you can see that the CA is DigiCert, and it is given to Red Hat under the name Opensource.com. This certificate information enables the end user to check that the website is safe to visit. WARNING: If you do not see a certificate sign on a website—or if you see a sign that indicates that the website is not secure—please do not log in or do any activity that requires your private data. Doing so is quite dangerous! If you see a warning sign, which is rare for most publicly facing websites, it usually means that the certificate is expired or uses a self-signed certificate instead of one issued through a trusted CA. Before we get into those topics, I want to explain the TLS and SSL. ## Internet protocols with TLS and SSL TLS is the current generation of the old Secure Socket Layer (SSL) protocol. The best way to understand this is by examining the different layers of the IP. ![IP layers IP layers](https://opensource.com/sites/default/files/uploads/3_internetprotocol.jpg) There are six layers that make up the internet as we know it today: physical, data, network, transport, security, and application. The physical layer is the base foundation, and it is closest to the actual hardware. The application layer is the most abstract layer and the one closest to the end user. The security layer can be considered a part of the application layer, and TLS and SSL, which are the cryptographic protocols designed to provide communications security over a computer network, are in the security layer. This process ensures that communication is secure and encrypted when an end user consumes the service. ## Certificate authorities and self-signed certificates A CA is a trusted organization that can issue a digital certificate. TLS and SSL can make a connection secure, but the encryption mechanism needs a way to validate it; this is the SSL/TLS certificate. TLS uses a mechanism called asymmetric encryption, which is a pair of security keys called a private key and a public key. (This is a very complex topic that is beyond the scope of this article, but you can read "[An introduction to cryptography and public key infrastructure](https://opensource.com/article/18/5/cryptography-pki)" if you would like to learn about it.) The essential thing to know is that CAs, like GlobalSign, DigiCert, and GoDaddy, are the external trusted vendors that issue certificates that are used to validate the TLS/SSL certificate used by the website. This certificate is imported to the hosted server to secure the website. However, a CA might be too expensive or complicated when you're just trying to test a website or service in development. You must have a trusted CA for production purposes, but developers and website administrators need a simpler way to test websites before they're deployed to production; this is where self-signed certificates come in. A self-signed certificate is a TLS/SSL certificate that is signed by the person who creates it rather than a trusted CA. It's easy to generate a self-signed certificate from a computer, and it can enable you to test a secure website without buying an expensive CA-signed certificate right away. While the self-signed certificate is definitely risky to put into production use, it is an easy and flexible option for developing and testing in pre-production stages. ## Open source tools for generating certificates Several open source tools are available for managing TLS/SSL certificates. The most well-known one is OpenSSL, which is included in many Linux distributions and on macOS. However, other open source tools are also available. Tool Name | Description | License | ---|---|---| | [EasyRSA](https://github.com/OpenVPN/easy-rsa)[CFSSL](https://github.com/cloudflare/cfssl)[Lemur](https://github.com/Netflix/lemur)Netflix's Lemur is a particularly interesting option when you consider its goals of scaling and being user friendly. You can read more about it on [Netflix's tech blog](https://medium.com/netflix-techblog/introducing-lemur-ceae8830f621). ## How to create an OpenSSL certificate We have the power to create certificates on our own. This example generates a self-signed certificate using OpenSSL. - Create a private key using the **openssl**command: `openssl genrsa -out example.key 2048` ![Generating key with OpenSSL Generating key with OpenSSL](https://opensource.com/sites/default/files/uploads/4_openssl_generatekey.jpg) - Create a certificate signing request (CSR) using the private key generated in step 1: `openssl req -new -key example.key -out example.csr \ -subj "/C=US/ST=TX/L=Dallas/O=Red Hat/OU=IT/CN=test.example.com"` ![Generating CSR Generating CSR](https://opensource.com/sites/default/files/uploads/5_openssl_generatecsr.jpg) - Create a certificate using your CSR and private key: `openssl x509 -req -days 366 -in example.csr \ -signkey example.key -out example.crt` ![Creating a certificate with OpenSSL Creating a certificate with OpenSSL](https://opensource.com/sites/default/files/uploads/6_openssl_generatecert.jpg) ## Learn more on internet security ## If you'd like to learn more about the internet and website security, watch the companion YouTube video I made for this article. What questions do you have? Let me know in the comments. ## Comments are closed.
11,701
如何使用 Flask 编写 Python Web API
https://opensource.com/article/19/11/python-web-api-flask
2019-12-21T11:23:05
[ "Flask" ]
https://linux.cn/article-11701-1.html
> > 这是一个快速教程,用来展示如何通过 Flask(目前发展最迅速的 Python 框架之一)来从服务器获取数据。 > > > ![spiderweb diagram](/data/attachment/album/201912/21/112324fx6z8i11yyz7j8y8.png "spiderweb diagram") [Python](https://www.python.org/) 是一个以语法简洁著称的高级的、面向对象的程序语言。它一直都是一个用来构建 RESTful API 的顶级编程语言。 [Flask](https://palletsprojects.com/p/flask/) 是一个高度可定制化的 Python 框架,可以为开发人员提供用户访问数据方式的完全控制。Flask 是一个基于 Werkzeug 的 [WSGI](https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface) 工具包和 Jinja 2 模板引擎的”微框架“。它是一个被设计来开发 RESTful API 的 web 框架。 Flask 是 Python 发展最迅速的框架之一,很多知名网站如:Netflix、Pinterest 和 LinkedIn 都将 Flask 纳入了它们的开发技术栈。下面是一个简单的示例,展示了 Flask 是如何允许用户通过 HTTP GET 请求来从服务器获取数据的。 ### 初始化一个 Flask 应用 首先,创建一个你的 Flask 项目的目录结构。你可以在你系统的任何地方来做这件事。 ``` $ mkdir tutorial $ cd tutorial $ touch main.py $ python3 -m venv env $ source env/bin/activate (env) $ pip3 install flask-restful Collecting flask-restful Downloading https://files.pythonhosted.org/packages/17/44/6e49...8da4/Flask_RESTful-0.3.7-py2.py3-none-any.whl Collecting Flask>=0.8 (from flask-restful) [...] ``` ### 导入 Flask 模块 然后,在你的 `main.py` 代码中导入 `flask` 模块和它的 `flask_restful` 库: ``` from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class Quotes(Resource): def get(self): return { 'William Shakespeare': { 'quote': ['Love all,trust a few,do wrong to none', 'Some are born great, some achieve greatness, and some greatness thrust upon them.'] }, 'Linus': { 'quote': ['Talk is cheap. Show me the code.'] } } api.add_resource(Quotes, '/') if __name__ == '__main__': app.run(debug=True) ``` ### 运行 app Flask 包含一个内建的用于测试的 HTTP 服务器。来测试一下这个你创建的简单的 API: ``` (env) $ python main.py * Serving Flask app "main" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` 启动开发服务器时将启动 Flask 应用程序,该应用程序包含一个名为 `get` 的方法来响应简单的 HTTP GET 请求。你可以通过 `wget`、`curl` 命令或者任意的 web 浏览器来测试它。 ``` $ curl http://localhost:5000 { "William Shakespeare": { "quote": [ "Love all,trust a few,do wrong to none", "Some are born great, some achieve greatness, and some greatness thrust upon them." ] }, "Linus": { "quote": [ "Talk is cheap. Show me the code." ] } } ``` 要查看使用 Python 和 Flask 的类似 Web API 的更复杂版本,请导航至美国国会图书馆的 [Chronicling America](https://chroniclingamerica.loc.gov/about/api) 网站,该网站可提供有关这些信息的历史报纸和数字化报纸。 ### 为什么使用 Flask? Flask 有以下几个主要的优点: 1. Python 很流行并且广泛被应用,所以任何熟悉 Python 的人都可以使用 Flask 来开发。 2. 它轻巧而简约。 3. 考虑安全性而构建。 4. 出色的文档,其中包含大量清晰,有效的示例代码。 还有一些潜在的缺点: 1. 它轻巧而简约。但如果你正在寻找具有大量捆绑库和预制组件的框架,那么这可能不是最佳选择。 2. 如果必须围绕 Flask 构建自己的框架,则你可能会发现维护自定义项的成本可能会抵消使用 Flask 的好处。 如果你要构建 Web 程序或 API,可以考虑选择 Flask。它功能强大且健壮,并且其优秀的项目文档使入门变得容易。试用一下,评估一下,看看它是否适合你的项目。 在本课中了解更多信息关于 Python 异常处理以及如何以安全的方式进行操作。 --- via: <https://opensource.com/article/19/11/python-web-api-flask> 作者:[Rachel Waston](https://opensource.com/users/rachelwaston) 选题:[lujun9972](https://github.com/lujun9972) 译者:[hj24](https://github.com/hj24) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
[Python](https://www.python.org/) is a high-level, object-oriented programming language known for its simple syntax. It is consistently among the top-rated programming languages for building RESTful APIs. [Flask](https://palletsprojects.com/p/flask/) is a customizable Python framework that gives developers complete control over how users access data. Flask is a "micro-framework" based on Werkzeug's [WSGI](https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface) toolkit and Jinja 2's templating engine. It is designed as a web framework for RESTful API development. Flask is one of the fastest-growing Python frameworks, and popular websites, including Netflix, Pinterest, and LinkedIn, have incorporated Flask into their development stacks. Here's an example of how Flask can permit users to fetch data from a server using the HTTP GET method. ## Set up a Flask application First, create a structure for your Flask application. You can do this at any location on your system. ``` $ mkdir tutorial $ cd tutorial $ touch main.py $ python3 -m venv env $ source env/bin/activate (env) $ pip3 install flask-restful Collecting flask-restful Downloading https://files.pythonhosted.org/packages/17/44/6e49...8da4/Flask_RESTful-0.3.7-py2.py3-none-any.whl Collecting Flask>=0.8 (from flask-restful) [...] ``` ## Import the Flask modules Next, import the **flask** module and its **flask_restful** library into your **main.py** code: ``` from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class Quotes(Resource): def get(self): return { 'William Shakespeare': { 'quote': ['Love all,trust a few,do wrong to none', 'Some are born great, some achieve greatness, and some greatness thrust upon them.'] }, 'Linus': { 'quote': ['Talk is cheap. Show me the code.'] } } api.add_resource(Quotes, '/') if __name__ == '__main__': app.run(debug=True) ``` ## Run the app Flask includes a built-in HTTP server for testing. Test the simple API you built: ``` (env) $ python main.py * Serving Flask app "main" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` Starting the development server starts your Flask application, which contains a method named **get** to respond to a simple HTTP GET request. You can test it using **wget** or **curl** or any web browser. The URL to use is provided in Flask's output after you start the server. ``` $ curl http://localhost:5000 { "William Shakespeare": { "quote": [ "Love all,trust a few,do wrong to none", "Some are born great, some achieve greatness, and some greatness thrust upon them." ] }, "Linus": { "quote": [ "Talk is cheap. Show me the code." ] } } ``` To see a more complex version of a similar web API using Python and Flask, navigate to the Library of Congress' [Chronicling America](https://chroniclingamerica.loc.gov/about/api) website, which provides access to information about historic newspapers and digitized newspaper pages. ## Why use Flask? Flask has several major benefits: - Python is popular and widely used, so anyone who knows Python can develop for Flask. - It's lightweight and minimalistic. - Built with security in mind. - Great documentation with plenty of clear, working example code. There are also some potential drawbacks: - It's lightweight and minimalistic. If you're looking for a framework with lots of bundled libraries and prefabricated components, this may not be your best option. - If you have to build your own framework around Flask, you might find that the cost of maintaining your customization negates the benefit of using Flask. If you're looking to build a web app or API, Flask is a good option to consider. It's powerful and robust, and the project documentation makes it easy to get started. Try it out, evaluate it, and see if it's right for your project. ## 2 Comments
11,702
如何在 Linux 系统中输入 emoji
https://opensource.com/article/19/10/how-type-emoji-linux
2019-12-22T00:38:00
[ "emoji" ]
https://linux.cn/article-11702-1.html
> > 使用 GNOME 桌面可以让你在文字中轻松加入 emoji。 > > > ![](/data/attachment/album/201912/22/003829tsuogoonoxunn33o.jpg) emoji 是潜藏在 Unicode 字符空间里的有趣表情图,它们已经风靡于整个互联网。emoji 可以用来在社交媒体上表示自己的心情状态,也可以作为重要文件名的视觉标签,总之它们的各种用法层出不穷。在 Linux 系统中有很多种方式可以输入 Unicode 字符,但 GNOME 桌面能让你更轻松地查找和输入 emoji。 ![Emoji in Emacs](/data/attachment/album/201912/22/003848e3cz56t8tqq36pdr.jpg "Emoji in Emacs") ### 准备工作 首先,你需要一个运行 [GNOME](https://www.gnome.org/) 桌面的 Linux 系统。 同时还需要安装一款支持 emoji 的字体。符合这个要求的字体有很多,使用你喜欢的软件包管理器直接搜索 `emoji` 并选择一款安装就可以了。 例如在 Fedora 上: ``` $ sudo dnf search emoji emoji-picker.noarch : An emoji selection tool unicode-emoji.noarch : Unicode Emoji Data Files eosrei-emojione-fonts.noarch : A color emoji font twitter-twemoji-fonts.noarch : Twitter Emoji for everyone google-android-emoji-fonts.noarch : Android Emoji font released by Google google-noto-emoji-fonts.noarch : Google “Noto Emoji” Black-and-White emoji font google-noto-emoji-color-fonts.noarch : Google “Noto Color Emoji” colored emoji font [...] ``` 对于 Ubuntu 或者 Debian,需要使用 `apt search`。 在这篇文章中,我会使用 [Google Noto Color Emoji](https://www.google.com/get/noto/help/emoji/) 这款字体为例。 ### 设置 要开始设置,首先打开 GNOME 的设置面板。 1、在左边侧栏中,选择“<ruby> 地区与语言 <rt> Region &amp; Language </rt></ruby>”类别。 2、点击“<ruby> 输入源 <rt> Input Sources </rt></ruby>”选项下方的加号(+)打开“<ruby> 添加输入源 <rt> Add an Input Source </rt></ruby>”面板。 ![Add a new input source](/data/attachment/album/201912/22/003856mlyccrw0cw5wl4gr.png "Add a new input source") 3、在“<ruby> 添加输入源 <rt> Add an Input Source </rt></ruby>”面板中,点击底部的菜单按钮。 ![Add an Input Source panel](/data/attachment/album/201912/22/003859ebu2b1xduzu0vy59.png "Add an Input Source panel") 4、滑动到列表底部并选择“<ruby> 其它 <rt> Other </rt></ruby>”。 5、在“<ruby> 其它 <rt> Other </rt></ruby>”列表中,找到“<ruby> 其它 <rt> Other </rt></ruby>(<ruby> 快速输入 <rt> Typing Booster </rt></ruby>)”。 ![Find Other (Typing Booster) in inputs](/data/attachment/album/201912/22/003912xp5olfcqqlq5gwhw.png "Find Other (Typing Booster) in inputs") 6、点击右上角的“<ruby> 添加 <rt> Add </rt></ruby>”按钮,将输入源添加到 GNOME 桌面。 以上操作完成之后,就可以关闭设置面板了。 #### 切换到快速输入 现在 GNOME 桌面的右上角会出现一个新的图标,一般情况下是当前语言的双字母缩写(例如英语是 en,世界语是 eo,西班牙语是 es,等等)。如果你按下了<ruby> 超级键 <rt> Super key </rt></ruby>(也就是键盘上带有 Linux 企鹅/Windows 徽标/Mac Command 标志的键)+ 空格键的组合键,就会切换到输入列表中的下一个输入源。在这里,我们只有两个输入源,也就是默认语言和快速输入。 你可以尝试使用一下这个组合键,观察图标的变化。 #### 配置快速输入 在快速输入模式下,点击右上角的输入源图标,选择“<ruby> Unicode 符号和 emoji 联想 <rt> Unicode symbols and emoji predictions </rt></ruby>”选项,设置为“<ruby> 开 <rt> On </rt></ruby>”。 ![Set Unicode symbols and emoji predictions to On](/data/attachment/album/201912/22/003920r7ca9tdsa4cdz4o3.jpg "Set Unicode symbols and emoji predictions to On") 现在快速输入模式已经可以输入 emoji 了。这正是我们现在所需要的,当然快速输入模式的功能也并不止于此。 ### 输入 emoji 在快速输入模式下,打开一个文本编辑器,或者网页浏览器,又或者是任意一种支持输入 Unicode 字符的软件,输入“thumbs up”,快速输入模式就会帮你迅速匹配的 emoji 了。 ![Typing Booster searching for emojis](/data/attachment/album/201912/22/003925wfg8i8pu1ki5do5l.jpg "Typing Booster searching for emojis") 要退出 emoji 模式,只需要再次使用超级键+空格键的组合键,输入源就会切换回你的默认输入语言。 ### 使用其它切换方式 如果你觉得“超级键+空格键”这个组合用起来不顺手,你也可以换成其它键的组合。在 GNOME 设置面板中选择“<ruby> 设备 <rt> Device </rt></ruby>”→“<ruby> 键盘 <rt> Keyboard </rt></ruby>”。 在“<ruby> 键盘 <rt> Keyboard </rt></ruby>”页面中,将“<ruby> 切换到下一个输入源 <rt> Switch to next input source </rt></ruby>”更改为你喜欢的组合键。 ![Changing keystroke combination in GNOME settings](/data/attachment/album/201912/22/003930ylk6qpu6wdak6lag.jpg "Changing keystroke combination in GNOME settings") ### 输入 Unicode 实际上,现代键盘的设计只是为了输入 26 个字母以及尽可能多的数字和符号。但 ASCII 字符的数量已经比键盘上能看到的字符多得多了,遑论上百万个 Unicode 字符。因此,如果你想要在 Linux 应用程序中输入 Unicode,但又不想使用快速输入,你可以尝试一下 Unicode 输入。 1. 打开任意一种支持输入 Unicode 字符的软件,但仍然使用你的默认输入语言 2. 使用 `Ctrl+Shift+U` 组合键进入 Unicode 输入模式 3. 在 Unicode 输入模式下,只需要输入某个 Unicode 字符的对应序号,就实现了对这个 Unicode 字符的输入。例如 `1F44D` 对应的是 ?,而 `2620` 则对应了 ☠。想要查看所有 Unicode 字符的对应序号,可以参考 [Unicode 规范](http://unicode.org/emoji/charts/full-emoji-list.html)。 ### emoji 的实用性 emoji 可以让你的文本变得与众不同,这就是它们有趣和富有表现力的体现。同时 emoji 也有很强的实用性,因为它们本质上是 Unicode 字符,在很多支持自定义字体的地方都可以用到它们,而且跟使用其它常规字符没有什么太大的差别。因此,你可以使用 emoji 来对不同的文件做标记,在搜索的时候就可以使用 emoji 把这些文件快速筛选出来。 ![Labeling a file with emoji](/data/attachment/album/201912/22/003933k5alz3ap1rrza9rd.png "Labeling a file with emoji") 你可以在 Linux 中尽情地使用 emoji,因为 Linux 是一个对 Unicode 友好的环境,未来也会对 Unicode 有着越来越好的支持。 --- via: <https://opensource.com/article/19/10/how-type-emoji-linux> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[HankChow](https://github.com/HankChow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Emoji are those fanciful pictograms that snuck into the Unicode character space. They're all the rage online, and people use them for all kinds of surprising things, from signifying reactions on social media to serving as visual labels for important file names. There are many ways to enter Unicode characters on Linux, but the GNOME desktop makes it easy to find and type an emoji. ![Emoji in Emacs Emoji in Emacs](https://opensource.com/sites/default/files/uploads/emacs-emoji.jpg) ## Requirements For this easy method, you must be running Linux with the [GNOME](https://www.gnome.org/) desktop. You must also have an emoji font installed. There are many to choose from, so do a search for *emoji* using your favorite software installer application or package manager. For example, on Fedora: ``` `````` $ sudo dnf search emoji emoji-picker.noarch : An emoji selection tool unicode-emoji.noarch : Unicode Emoji Data Files eosrei-emojione-fonts.noarch : A color emoji font twitter-twemoji-fonts.noarch : Twitter Emoji for everyone google-android-emoji-fonts.noarch : Android Emoji font released by Google google-noto-emoji-fonts.noarch : Google “Noto Emoji” Black-and-White emoji font google-noto-emoji-color-fonts.noarch : Google “Noto Color Emoji” colored emoji font [...] ``` On Ubuntu or Debian, use **apt search** instead. I'm using [Google Noto Color Emoji](https://www.google.com/get/noto/help/emoji/) in this article. ## Get set up To get set up, launch GNOME's Settings application. - In Settings, click the **Keyboard**category in the left column. - Click the plus symbol ( **+**) under the**Input Sources**heading to bring up the**Add an Input Source**panel. ![Add a new input source Add a new input source](https://opensource.com/sites/default/files/uploads/gnome-setting-region-add.png) - In the **Add an Input Source**panel, click the hamburger menu at the bottom of the input list. ![Add an Input Source panel Add an Input Source panel](https://opensource.com/sites/default/files/uploads/gnome-setting-input-list.png) - Scroll to the bottom of the list and select **Other**. - In the **Other**list, find**Other (Typing Booster)**. (You can type**boost**in the search field at the bottom to filter the list.) ![Find Other (Typing Booster) in inputs Find Other (Typing Booster) in inputs](https://opensource.com/sites/default/files/uploads/gnome-setting-input-other-typing-booster.png) - Click the **Add**button in the top-right corner of the panel to add the input source to GNOME. Once you've done that, you can close the Settings window. ### Switch to Typing Booster You now have a new icon in the top-right of your GNOME desktop. By default, it's set to the two-letter abbreviation of your language (**en** for English, **eo** for Esperanto, **es** for Español, and so on). If you press the **Super** key (the key with a Linux penguin, Windows logo, or Mac Command symbol) and the **Spacebar** together on your keyboard, you will switch input sources from your default source to the next on your input list. In this example, you only have two input sources: your default language and Typing Booster. Try pressing **Super**+**Spacebar** together and watch the input name and icon change. ### Configure Typing Booster With the Typing Booster input method active, click the input sources icon in the top-right of your screen, select **Unicode symbols and emoji predictions**, and set it to **On**. ![Set Unicode symbols and emoji predictions to On Set Unicode symbols and emoji predictions to On](https://opensource.com/sites/default/files/uploads/emoji-input-on.jpg) This makes Typing Booster dedicated to typing emoji, which isn't all Typing Booster is good for, but in the context of this article it's exactly what is needed. ## Type emoji With Typing Booster still active, open a text editor like Gedit, a web browser, or anything that you know understands Unicode characters, and type "*thumbs up*." As you type, Typing Booster searches for matching emoji names. ![Typing Booster searching for emojis](https://opensource.com/sites/default/files/uploads/emoji-input.jpg) To leave emoji mode, press **Super**+**Spacebar** again, and your input source goes back to your default language. ## Switch the switcher If the **Super**+**Spacebar** keyboard shortcut is not natural for you, then you can change it to a different combination. In GNOME Settings, navigate to **Devices** and select **Keyboard**. In the top bar of the **Keyboard** window, search for **Input** to filter the list. Set **Switch to next input source** to a key combination of your choice. ![Changing keystroke combination in GNOME settings Changing keystroke combination in GNOME settings](https://opensource.com/sites/default/files/uploads/gnome-setting-keyboard-switch-input.jpg) ## Unicode input The fact is, keyboards were designed for a 26-letter (or thereabouts) alphabet along with as many numerals and symbols. ASCII has more characters than what you find on a typical keyboard, to say nothing of the millions of characters within Unicode. If you want to type Unicode characters into a modern Linux application but don't want to switch to Typing Booster, then you can use the Unicode input shortcut. - With your default language active, open a text editor like Gedit, a web browser, or any application you know accepts Unicode. - Press **Ctrl**+**Shift**+**U**on your keyboard to enter Unicode entry mode. Release the keys. - You are currently in Unicode entry mode, so type a number of a Unicode symbol. For instance, try **1F44D**for a ? symbol, or**2620**for a ☠ symbol. To get the number code of a Unicode symbol, you can search the internet or refer to the[Unicode specification](http://unicode.org/emoji/charts/full-emoji-list.html). ## Pragmatic emoji-ism Emoji are fun and expressive. They can make your text unique to you. They can also be utilitarian. Because emoji are Unicode characters, they can be used anywhere a font can be used, and they can be used the same way any alphabetic character can be used. For instance, if you want to mark a series of files with a special symbol, you can add an emoji to the name, and you can filter by that emoji in Search. ![Labeling a file with emoji Labeling a file with emoji](https://opensource.com/sites/default/files/uploads/file-label.png) Use emoji all you want because Linux is a Unicode-friendly environment, and it's getting friendlier with every release. ## Comments are closed.
11,703
GNOME 2 粉丝喜欢 Mate Linux 桌面的什么?
https://opensource.com/article/19/12/mate-linux-desktop
2019-12-22T07:38:38
[ "Mate" ]
https://linux.cn/article-11703-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。如果你还在怀念 GNOME 2,那么 Mate Linux 桌面将满足你的怀旧情怀。 > > > ![](/data/attachment/album/201912/22/073751ugrt47kye0begk3k.jpg) 如果你以前听过这个传闻:当 GNOME3 第一次发布时,很多 GNOME 用户还没有准备好放弃 GNOME 2。[Mate](https://mate-desktop.org/)(以<ruby> 马黛茶 <rt> yerba mate </rt></ruby>植物命名)项目的开始是为了延续 GNOME 2 桌面,刚开始时它使用 GTK 2(GNOME 2 所基于的工具包),然后又合并了 GTK 3。由于 Linux Mint 的简单易用,使得该桌面变得非常流行,并且从那时起,它已经普遍用于 Fedora、Ubuntu、Slackware、Arch 和许多其他 Linux 发行版上。今天,Mate 继续提供一个传统的桌面环境,它的外观和感觉与 GNOME 2 完全一样,使用 GTK 3 工具包。 你可以在你的 Linux 发行版的软件仓库中找到 Mate,也可以下载并[安装](https://mate-desktop.org/install/)一个把 Mate 作为默认桌面的发行版。不过,在你这样做之前,请注意为了提供完整的桌面体验,所以许多 Mate 应用程序都是随该桌面一起安装的。如果你运行的是不同的桌面,你可能会发现自己有多余的应用程序(两个 PDF 阅读器、两个媒体播放器、两个文件管理器,等等)。所以如果你只想尝试 Mate 桌面,可以在虚拟机(例如 [GNOME box](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization))中安装基于 Mate 的发行版。 ### Mate 桌面之旅 Mate 项目不仅仅可以让你想起来 GNOME 2;它就是 GNOME 2。如果你是 00 年代中期 Linux 桌面的粉丝,至少,你会从中感受到 Mate 的怀旧情怀。我不是 GNOME 2 的粉丝,我更倾向于使用 KDE,但是有一个地方我无法想象没有 GNOME 2:[OpenSolaris](https://en.wikipedia.org/wiki/OpenSolaris)。OpenSolaris 项目并没有持续太久,在 Sun Microsystems 被并入 Oracle 之前,Ian Murdock 加入 Sun 时它就显得非常突出,我当时是一个初级的 Solaris 管理员,使用 OpenSolaris 来让自己更多学会那种 Unix 风格。这是我使用过 GNOME 2 的唯一平台(因为我一开始不知道如何更改桌面,后来习惯了它),而今天的 [OpenIndiana project](https://www.openindiana.org/documentation/faq/#what-is-openindiana) 是 OpenSolaris 的社区延续,它通过 Mate 桌面使用 GNOME 2。 ![Mate on OpenIndiana](/data/attachment/album/201912/22/073841t8cb4blgt2co22kz.jpg "Mate on OpenIndiana") Mate 的布局由左上角的三个菜单组成:应用程序、位置和系统。应用程序菜单提供对系统上安装的所有的应用程序启动器的快速访问。位置菜单提供对常用位置(如家目录、网络文件夹等)的快速访问。系统菜单包含全局选项,如关机和睡眠。右上角是一个系统托盘,屏幕底部有一个任务栏和一个虚拟桌面切换栏。 就桌面设计而言,这是一种稍微有点奇怪的配置。它从早期的 Linux 桌面、MacFinder 和 Windows 中借用了一些相同的部分,但是又创建了一个独特的配置,这种配置很直观而有些熟悉。Mate 执意保持这个模型,而这正是它的用户喜欢的地方。 ### Mate 和开源 Mate 是一个最直接的例子,展示了开源如何使开发人员能够对抗项目生命的终结。从理论上讲,GNOME 2 会被 GNOME 3 所取代,但它依然存在,因为一个开发人员建立了该代码的一个分支并继续发展了下去。它的发展势头越来越庞大,更多的开发人员加入进来,并且这个让用户喜爱的桌面比以往任何时候都要更好。并不是所有的软件都有第二次机会,但是开源永远是一个机会,否则就永远没有机会。 使用和支持开源意味着支持用户和开发人员的自由。而且 Mate 桌面是他们的努力的有力证明。 --- via: <https://opensource.com/article/19/12/mate-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[mayunmeiyouming](https://github.com/mayunmeiyouming) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Stop me if you've heard this one before: When GNOME 3 was first released, many GNOME users were not ready to give up GNOME 2. The [Mate](https://mate-desktop.org/) (named after the *yerba mate* plant) project began as an effort to continue the GNOME 2 desktop, at first using GTK 2 (the toolkit GNOME 2 was based upon) and later incorporating GTK 3. The desktop became wildly popular, due in no small part to Linux Mint's prompt adoption of it, and since then, it has become commonly available on Fedora, Ubuntu, Slackware, Arch, and many other Linux distributions. Today, Mate continues to deliver a traditional desktop environment that looks and feels exactly like GNOME 2 did, using the GTK 3 toolkit. You may find Mate included in the software repository of your Linux distribution, or you can download and [install](https://mate-desktop.org/install/) a distribution that ships Mate as its default desktop. Before you do, though, be aware that it is meant to provide a full desktop experience, so many Mate apps are installed along with the desktop. If you're running a different desktop, you may find yourself with redundant applications (two PDF readers, two media players, two file managers, and so on). If you just want to try the Mate desktop, you can install a Mate-based distribution in a virtual machine, such as [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization). ## Mate desktop tour The Mate project doesn't just evoke GNOME 2; it *is* GNOME 2. If you were a fan of the Linux desktop back in the mid-'00s, at the very least, you'll find Mate nostalgic. I was not a fan of GNOME 2 and tended to use KDE instead, but there's one place I can't imagine without GNOME 2: [OpenSolaris](https://en.wikipedia.org/wiki/OpenSolaris). The OpenSolaris project didn't last long, coming to prominence when Ian Murdock joined Sun Microsystems just before it was subsumed by Oracle, but I was a low-level Solaris admin at the time and used OpenSolaris to teach myself more about that flavor of Unix. It was the only platform where I used GNOME 2 (because I didn't know how to change the desktop at first and then just got used to it), and today the [OpenIndiana project](https://www.openindiana.org/documentation/faq/#what-is-openindiana), a community continuation of OpenSolaris, uses GNOME 2 by way of the Mate desktop. ![Mate on OpenIndiana Mate on OpenIndiana](https://opensource.com/sites/default/files/uploads/advent-mate-openindiana_675px.jpg) Mate's layout consists of three menus in the top-left corner: Applications, Places, and System. The Applications menu provides quick access to all application launchers installed on the system. The Places menu provides quick access to common locations, such as your home directory, a network folder, and so on. The System menu contains global options, such as shutdown and suspend. In the upper-right corner is a system tray, and there's a taskbar and a virtual desktop pager at the bottom of the screen. It's a slightly peculiar configuration, as far as desktop design goes. It borrows equal parts from earlier Linux desktops, the Mac Finder, and Windows, but creates a unique configuration that's intuitive and somehow familiar. Mate intentionally resists deviation from this model, and that's exactly the way its users prefer it. ## Mate and open source Mate is one of the most direct examples of how open source empowers developers to fight against a project's end of life. On paper, GNOME 2 was superseded by GNOME 3, yet it lives on because one developer forked the code and carried on. Momentum grew, more developers joined, and the desktop that users love is healthier than ever. Not all software gets a second chance at life, but the option is always there with open source, and it's always absent otherwise. Using and supporting open source means supporting user and developer freedom. And the Mate desktop is a powerful example of what happens when it works. ## 2 Comments
11,705
全球化思考:怎样克服交流中的文化差异
https://opensource.com/article/18/10/think-global-communication-challenges
2019-12-23T06:24:15
[ "交流" ]
https://linux.cn/article-11705-1.html
> > 这有一些建议帮助你的全球化开发团队能够更好地理解你们的讨论并能参与其中。 > > > ![](/data/attachment/album/201912/23/062419wzzet2u2jj56c5e5.png) 几周前,我见证了两位同事之间一次有趣的互动,他们分别是 Jason,我们的一位美国员工,和 Raj,一位来自印度的访问工作人员。 Raj 在印度时,他一般会通过电话参加美国中部时间上午 9 点的每日立会,现在他到美国工作了,就可以和组员们坐在同一间会议室里开会了。Jason 拦下了 Raj,说:“Raj 你要去哪?你不是一直和我们开电话会议吗?你突然出现在会议室里我还不太适应。” Raj 听了说,“是这样吗?没问题。”就回到自己工位前准备和以前一样参加电话会议了。 我去找 Raj,问他为什么不去参加每日立会,Raj 说 Jason 让自己给组员们打电话参会,而与此同时,Jason 也在会议室等着 Raj 来参加立会。 到底是哪里出的问题?Jason 明显只是调侃 Raj 终于能来一起开会了,为什么 Raj 没能听懂呢? Jason 明显是在开玩笑,但 Raj 把它当真了。这就是在两人互相不了解对方文化语境时发生的一个典型误会。 我经常会遇到有人在电子邮件的末尾写“请复原”,最开始我很迷惑,“这有什么需要我复原的内容?”后来我才搞懂,“请复原”其实是“请回复”的意思。 在 Ricardo Fernandez 的TED 演讲“[如何管理跨文化团队](https://www.youtube.com/watch?v=QIoAkFpN8wQ)” 中,他提到了自己与一位南非同事发生的小故事。那位同事用一句“我一会给你打电话。”结束了两人的 IM 会话,Ricardo 回到办公室后就开始等这位同事的电话,十五分钟后他忍不住主动给这位同事打了电话,问他:“你不是说要给我打电话吗?”,这位同事答到:“是啊,我是说以后有机会给你打电话。”这时 Ricardo 才理解那位同事说的“一会”是“以后”的意思。 现在是全球化时代,我们的同事很可能不跟我们面对面接触,甚至不在同一座城市,来自不同的国家。越来越多的技术公司拥有全球化的工作场所,和来自世界各地的员工,他们有着不同的背景和经历。这种多样性使得技术公司能够在这个快速发展的科技大环境下拥有更强的竞争力。 但是这种地域的多样性也会给团队带来挑战。管理和维持高性能的团队发展对于同地协作的团队来说就有着很大难度,对于有着多样背景成员的全球化团队来说,无疑更加困难。成员之间的交流会发生延迟,误解时有发生,成员之间甚至会互相怀疑,这些都会影响着公司的成功。 到底是什么因素让全球化交流间发生误解呢?我们可以参照 Erin Meyer 的书《[文化地图](https://www.amazon.com/The-Culture-Map-Invisible-Boundaries/dp/1610392507)》,她在书中将全球文化分为八个类型,其中美国文化被分为低语境文化,与之相对的,日本为高语境文化。 看到这里你可能会问,高、低语境文化到底是什么意思?美国人从小就教育孩子们简洁表达,“直言不讳”是他们的表达准则;另一边,日本人从小学习在高效处理社交线索的同时进行交流,“察言观色”是他们的交流习惯。 大部分亚洲国家的文化都属于高语境文化。作为一个年轻的移民国家,美国毫不意外地拥有着低语境文化。移民来自于世界各地,拥有着不同的文化背景,他们不得不选择简洁而直接的交流方式,这或许就是其拥有低语境文化的原因。 ### 从文化语境的角度与异国同事交流的三个步骤: 怎样面临跨文化交流中遇到的挑战?比如说一位美国人与他的日本同事交流,他更应该注重日本同事的非语言线索,同样的日本同事应当更关注美国人直接表达出的信息。如果你也面临类似的挑战,按照下面这三个步骤做,可以帮助你更有效地和异国同事交流,增进与他们的感情。 #### 认识到文化语境的差异 跨文化交流的第一步是认识到文化差异,跨文化交流从认识其他文化开始。 #### 尊重文化语境的差异 一旦你意识到了文化语境的差异会影响跨文化交流,你要做的就是尊重这些差异。在你遇到一种不同的交流方式时,学会接受差异,学会积极听取他人意见。 #### 调和文化语境的差异 只是认识和尊重差异还远远不够,你还需要学会如何调和这些差异。互相理解和换位思考可以增进差异的调和,你还要学着用它们去提高同事间的交流效率,推动生产力。 ### 五种促进不同文化语境间交流的方法 为了加强组员们之间关系,这么多年来我一直在收集各种各样的方法和建议。这些方法帮助我解决了与外国组员间产生的很多交流问题,下面有其中一些例子: #### 与外国组员交流时尽量使用视频会议的形式 研究表明,交流中约 55% 的内容不是靠语言传递的。肢体语言传达着一种十分微妙的信息,你可以根据它们理解对方的意思,而视频会议中处于异地的组员们能够看到对方的肢体语言。因此,组织远程会议时我一般都会采用视频会议的形式。 #### 确保每位成员都有机会分享他们的想法 我虽然喜欢开视频会议,但不是每次都能开的成。如果视频会议对你的团队来说并不常用,大家可能要一些时间去适应,你需要积极鼓励大家参与到其中,先从进行语音会议开始。 我们有一个外地的组员,每次都和我们进行语音会议,和我们提到她经常会有些想法想要分享,或者想做些贡献,但是我们互相看不到,她不知道该怎样开口。如果你一直在进行语音会议,注意要给组员们足够的时间和机会分享他们的想法。 #### 互相学习 通过你身边一两名外国朋友来学习他们的文化,你可以把从一位同事身上学到的应用于所有来自这个国家的同事。我有几位南亚和南美的同事,他们帮助我理解他们的文化,而这些也使得我更加专业。 对编程人员来说,我建议请你全世界的同行们检查你的代码,这个过程能让你观察到其他文化中人们怎样进行反馈、劝说他人,和最终进行技术决策。 #### 学会感同身受 同理心是一段牢固关系的核心。你越能换位思考,就越容易获得信任,来建立长久的关系。你可以在每次会议开始之前和大家闲聊几句,这样大家更容易处于一个放松的状态,如果团队中有很多外国人,要确保大家都能参与进来。 #### 和你的外国同事们单独见面 保持长久关系最好的方法是和你的组员们单独见面。如果你的公司可以报销这些费用,那么努力去和组员们见面吧。和一起工作了很长时间的组员们见面能够使你们的关系更加坚固。我所在的公司就有着周期性交换员工的传统,每隔一段时间,世界各地的员工就会来到美国工作,美国员工再到其他分部工作。 另一种聚齐组员们的机会是研讨会。研讨会创造的不仅是学习和培训的机会,你还可以挤出一些时间和组员们培养感情。 在如今,全球化经济不断发展,拥有来自不同国家和地区的员工对维持一个公司的竞争力来说越来越重要。即使组员们来自世界各地,团队中会出现一些交流问题,但拥有一支国际化的高绩效团队不是问题。如果你在工作中有什么促进团队交流的小窍门,请在评论中告诉我们吧。 --- via: <https://opensource.com/article/18/10/think-global-communication-challenges> 作者:[Avindra Fernando](https://opensource.com/users/avindrafernando) 选题:[lujun9972](https://github.com/lujun9972) 译者:[Valoniakim](https://github.com/Valoniakim) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
A few weeks ago, I witnessed an interesting interaction between two work colleagues—Jason, who is from the United States; and Raj, who was visiting from India. Raj typically calls into a daily standup meeting at 9:00am US Central Time from India, but since he was in the US, he and his teammates headed toward the scrum area for the meeting. Jason stopped Raj and said, “Raj, where are you going? Don’t you always call into the stand-up? It would feel strange if you don’t call in.” Raj responded, “Oh, is that so? No worries,” and headed back to his desk to call into the meeting. I went to Raj’s desk. “Hey, Raj, why aren’t you going to the daily standup?” Raj replied, “Jason asked me to call in.” Meanwhile, Jason was waiting for Raj to come to the standup. What happened here? Jason was obviously joking when he made the remark about Raj calling into the meeting. But how did Raj miss this? Jason’s statement was meant as a joke, but Raj took it literally. This was a clear example of a misunderstanding that occurred due to unfamiliarity with each other’s cultural context. I often encounter emails that end with “Please revert back to me.” At first, this phrase left me puzzled. I thought, "What changes do they want me to revert?" Finally, I figured out that “please revert” means “Please reply.” In his TED talk, “[Managing Cross Cultural Remote Teams,](https://www.youtube.com/watch?v=QIoAkFpN8wQ)” Ricardo Fernandez describes an interaction with a South African colleague who ended an IM conversation with “I’ll call you just now.” Ricardo went back to his office and waited for the call. After fifteen minutes, he called his colleague: “Weren’t you going to call me just now?” The colleague responded, “Yes, I was going to call you just now.” That's when Ricardo realized that to his South African colleague, the phrase “just now” meant “sometime in the future.” In today's workplace, our colleagues may not be located in the same office, city, or even country. A growing number of tech companies have a global workforce comprised of employees with varied experiences and perspectives. This diversity allows companies to compete in the rapidly evolving technological environment. But geographically dispersed teams can face challenges. Managing and maintaining high-performing development teams is difficult even when the members are co-located; when team members come from different backgrounds and locations, that makes it even harder. Communication can deteriorate, misunderstandings can happen, and teams may stop trusting each other—all of which can affect the success of the company. What factors can cause confusion in global communication? In her book, “[The Culture Map](https://www.amazon.com/The-Culture-Map-Invisible-Boundaries/dp/1610392507),” Erin Meyer presents eight scales into which all global cultures fit. We can use these scales to improve our relationships with international colleagues. She identifies the United States as a very low-context culture in the communication scale. In contrast, Japan is identified as a high-context culture. What does it mean to be a high- or low-context culture? In the United States, children learn to communicate explicitly: “Say what you mean; mean what you say” is a common principle of communication. On the other hand, Japanese children learn to communicate effectively by mastering the ability to “read the air.” That means they are able to read between the lines and pick up on social cues when communicating. Most Asian cultures follow the high-context style of communication. Not surprisingly, the United States, a young country composed of immigrants, follows a low-context culture: Since the people who immigrated to the United States came from different cultural backgrounds, they had no choice but to communicate explicitly and directly. ## The three R’s How can we overcome challenges in cross-cultural communication? Americans communicating with Japanese colleagues, for example, should pay attention to the non-verbal cues, while Japanese communicating with Americans should prepare for more direct language. If you are facing a similar challenge, follow these three steps to communicate more effectively and improve relationships with your international colleagues. ### Recognize the differences in cultural context The first step toward effective cross-cultural communication is to recognize that there are differences. Start by increasing your awareness of other cultures. ### Respect the differences in cultural context Once you become aware that differences in cultural context can affect cross-cultural communication, the next step is to respect these differences. When you notice a different style of communication, learn to embrace the difference and actively listen to the other person’s point of view. ### Reconcile the differences in cultural context Merely recognizing and respecting cultural differences is not enough; you must also learn how to reconcile the cultural differences. Understanding and being empathetic towards the other culture will help you reconcile the differences and learn how to use them to better advance productivity. ## 5 ways to improve communications for cultural context Over the years, I have incorporated various approaches, tips, and tricks to strengthen relationships among team members across the globe. These approaches have helped me overcome communication challenges with global colleagues. Here are a few examples: ### Always use video conferencing when communicating with global teammates Studies show that about 55% of communication is non-verbal. Body language offers many subtle cues that can help you decipher messages, and video conferencing enables geographically dispersed team members to see each other. Videoconferencing is my default choice when conducting remote meetings. ### Ensure that every team member gets an opportunity to share their thoughts and ideas Although I prefer to conduct meetings using video conferencing, this is not always possible. If video conferencing is not a common practice at your workplace, it might take some effort to get everyone comfortable with the concept. Start by encouraging everyone to participate in audio meetings. One of our remote team members, who frequently met with us in audio conferences, mentioned that she often wanted to share ideas and contribute to the meeting but since we couldn’t see her and she couldn’t see us, she had no idea when to start speaking. If you are using audio conferencing, one way to mitigate this is to ensure that every team member gets an opportunity to share their ideas. ### Learn from one another Leverage your international friends to learn about their cultural context. This will help you interact more effectively with colleagues from these countries. I have friends from South Asia and South America who have helped me better understand their cultures, and this knowledge has helped me professionally. For programmers, I recommend conducting code reviews with your global peers. This will help you understand how those from different cultures give and receive feedback, persuade others, and make technical decisions. ### Be empathetic Empathy is the key to strong relationships. The more you are able to put yourself in someone else's shoes, the better able you will be to gain trust and build long-lasting connections. Encourage “water-cooler” conversations among your global colleagues by allocating the first few minutes of each meeting for small talk. This offers the additional benefit of putting everyone in a more relaxed mindset. If you manage a global team, make sure every member feels included in the discussion. ### Meet your global colleagues in person The best way to build long-lasting relationships is to meet your team members in person. If your company can afford it, arrange for this to happen. Meeting colleagues with whom you have been working will likely strengthen your relationship with them. The companies I have worked for have a strong record of periodically sending US team members to other countries and global colleagues to the US office. Another way to bring teams together is to attend conferences. This not only creates educational and training opportunities, but you can also carve out some in-person team time. In today's increasingly global economy, it is becoming more important for companies to maintain a geographically diverse workforce to remain competitive. Although global teams can face communication challenges, it is possible to maintain a high-performing development team despite geographical and cultural differences. Share some of the techniques you use in the comments. ## Comments are closed.
11,706
在 Linux 桌面中开始使用 Lumina
https://opensource.com/article/19/12/linux-lumina-desktop
2019-12-23T07:07:20
[ "Lumina" ]
https://linux.cn/article-11706-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。Lumina 桌面是让你使用快速、合理的基于 Fluxbox 桌面的捷径,它具有你无法缺少的所有功能。 > > > ![](/data/attachment/album/201912/23/070658vtgg3wkrpg5g36rs.jpg) 多年来,有一个名为 PC-BSD 的基于 FreeBSD 的桌面操作系统(OS)。它旨在作为一个常规使用的系统,因此值得注意,因为 BSD 主要用于服务器。大多数时候,PC-BSD 默认带 KDE 桌面,但是 KDE 越来越依赖于 Linux 特定的技术,因此 PC-BSD 越来越从 KDE 迁离。PC-BSD 变成了 [Trident](https://project-trident.org/),它的默认桌面是 [Lumina](https://lumina-desktop.org/),它是一组小部件,它们使用与 KDE 相同的基于 Qt 的工具包,运行在 Fluxbox 窗口管理器上。 你可以在 Linux 发行版的软件仓库或 BSD 的 ports 树中找到 Lumina 桌面。如果你安装了 Lumina 并且已经在运行另一个桌面,那么你可能会发现有冗余的应用(两个 PDF 阅读器、两个文件管理器,等等),因为 Lumina 包含一些集成的应用。如果你只想尝试 Lumina 桌面,那么可以在虚拟机如 [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization) 中安装基于 Lumina 的 BSD 发行版。 如果在当前的操作系统上安装 Lumina,那么必须注销当前的桌面会话,才能登录到新的会话。默认情况下,会话管理器(SDDM、GDM、LightDM 或 XDM,取决于你的设置)将继续登录到以前的桌面,因此你必须在登录之前覆盖该桌面。 在 GDM 中: ![Selecting your desktop in GDM](/data/attachment/album/201912/23/070722llb9m1xm2lsguunx.jpg "Selecting your desktop in GDM") 在 SDDM 中: ![Selecting your desktop in KDM](/data/attachment/album/201912/23/070722rtp4riotq4ktwokn.jpg "Selecting your desktop in KDM") ### Lumina 桌面 Lumina 提供了一个简单而轻巧的桌面环境。屏幕底部有一个面板,它的左侧是应用菜单,中间是任务栏,右边是系统托盘。桌面上有图标,可以快速访问常见的应用和路径。 除了这个基本的桌面结构外,Lumina 还有自定义文件管理器、PDF 查看器,截图工具、媒体播放器、文本编辑器和存档工具。还有一个配置程序可以帮助你自定义 Lumina 桌面,并且右键单击桌面可以找到更多配置选项。 ![Lumina desktop running on Project Trident](/data/attachment/album/201912/23/070723x5nzvn4tnffu4ub7.jpg "Lumina desktop running on Project Trident") Lumina 与几个 Linux 轻量级桌面非常相似,尤其是 LXQT,不同之处在于 Lumina 完全不依赖于基于 Linux 的桌面框架(例如 ConsoleKit、PolicyKit、D-Bus 或 systemd)。对于你而言,这是否具有优势取决于所运行的操作系统。毕竟,如果你运行的是可以访问这些功能的 Linux,那么使用不使用这些特性的桌面可能就没有多大意义,还会减少功能。如果你运行的是 BSD,那么在 Fluxbox 中运行 Lumina 部件意味着你不必从 ports 安装 Linux 兼容库。 ### 为什么要使用 Lumina Lumina 设计简单,它没有很多功能,但是你可以安装 Fluxbox 你喜欢的组件(用于文件管理的 [PCManFM](https://wiki.lxde.org/en/PCManFM)、各种 [LXQt 应用](http://lxqt.org)、[Tint2](https://opensource.com/article/19/1/productivity-tool-tint2) 面板等)。在开源中,开源用户喜欢寻找不要重复发明轮子的方法(几乎与我们喜欢重新发明轮子一样多)。 Lumina 桌面是让你使用快速、合理的基于 Fluxbox 桌面的捷径,它具有你无法缺少的所有功能,并且你很少需要调整细节。试一试 Lumina 桌面,看看它是否适合你。 --- via: <https://opensource.com/article/19/12/linux-lumina-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
For a good number of years, there was a desktop operating system (OS) based on FreeBSD called PC-BSD. It was intended as an OS for general use, which was noteworthy because BSD development mostly focuses on servers. For most of its life, PC-BSD shipped with the KDE desktop by default, but the more KDE came to depend on Linux-specific technology, the more PC-BSD migrated away from it. PC-BSD became [Trident](https://project-trident.org/), and its default desktop is [Lumina](https://lumina-desktop.org/), a collection of widgets written to use the same Qt toolkit that KDE is based upon, running on the Fluxbox window manager. You may find the Lumina desktop in your Linux distribution's software repository or in BSD's ports tree. If you install Lumina and you're already running another desktop, you may find yourself with redundant applications (two PDF readers, two file managers, and so on) because Lumina includes a few integrated applications. If you just want to try the Lumina desktop, you can install a Lumina-based BSD distribution in a virtual machine, such as [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization). If you install Lumina on your current OS, you must log out of your current desktop session so you can log into your new one. By default, your session manager (SDDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. With GDM: ![Selecting your desktop in GDM Selecting your desktop in GDM](https://opensource.com/sites/default/files/uploads/advent-gdm_400x400_1.jpg) With SDDM: ![Selecting your desktop in KDM Selecting your desktop in KDM](https://opensource.com/sites/default/files/uploads/advent-kdm_400x400_1.jpg) ## Lumina desktop Lumina delivers a simple and lightweight desktop environment. There's a panel at the bottom of the screen containing an application menu on the left, a taskbar in the middle, and a system tray on the right. There are icons on the desktop providing quick access to common applications and locations. In addition to this basic desktop structure, Lumina features a custom file manager, PDF viewer, screenshot tool, media player, text editor, and archive tool. There's also a configuration utility to help you customize your Lumina desktop, and you can find further configuration options by right-clicking on the desktop. ![Lumina desktop running on Project Trident Lumina desktop running on Project Trident](https://opensource.com/sites/default/files/uploads/advent-lumina.jpg) Lumina is very similar to several Linux lightweight desktops, especially LXQT, except without any reliance upon Linux-based desktop frameworks like ConsoleKit, PolicyKit, D-Bus, or systemd. Whether or not that holds any advantage for you depends on the OS you're running. After all, if you're already running Linux with access to those features, using a desktop that doesn't utilize them may not make much sense and cost you features. If you're running BSD, then running Fluxbox with Lumina widgets could mean not having to install the Linux-compatible libraries from ports. ## Why you should use Lumina Lumina is simple enough in design that it doesn't have many features you can't implement on your own by installing Fluxbox along with your favorite components ([PCManFM](https://wiki.lxde.org/en/PCManFM) for file management, a variety of [LXQt apps](http://lxqt.org), [Tint2](https://opensource.com/article/19/1/productivity-tool-tint2) for a panel, and so on). But this is open source, and users of open source love to find ways to avoid reinventing the wheel (almost as much as we love reinventing the wheel). The Lumina desktop is a shortcut to a quick and sensible Fluxbox-based desktop with all the things you can't live without and very few of the finer details you'll want to configure yourself. Give the Lumina desktop a try to see if it's the desktop for you. ## Comments are closed.
11,708
网络启动一个 Fedora Live CD
https://fedoramagazine.org/netboot-a-fedora-live-cd/
2019-12-23T22:48:43
[ "iPXE", "远程启动" ]
https://linux.cn/article-11708-1.html
![](/data/attachment/album/201912/23/224848yaa09am9i3svmxxs.jpg) [Live CD](https://en.wikipedia.org/wiki/Live_CD) 对于很多任务是很有用的,例如: * 将操作系统安装到一个硬盘驱动器 * 修复一个启动加载程序或执行其它救援模式操作 * 为 Web 浏览提供一个相适应的最小环境 * …以及[更多的东西](https://en.wikipedia.org/wiki/Live_CD#Uses)。 作为使用 DVD 和 USB 驱动器来存储你的 Live CD 镜像是一个替代方案,你可以上传它们到一个不太可能丢失或损坏的 [iSCSI](https://en.wikipedia.org/wiki/ISCSI) 服务器中。这个指南向你展示如何加载你的 Live CD 镜像到一个 ISCSI 服务器上,并使用 [iPXE](https://ipxe.org/) 启动加载程序来访问它们。 ### 下载一个 Live CD 镜像 ``` $ MY_RLSE=27 $ MY_LIVE=$(wget -q -O - https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/$MY_RLSE/Workstation/x86_64/iso | perl -ne '/(Fedora[^ ]*?-Live-[^ ]*?\.iso)(?{print $^N})/;') $ MY_NAME=fc$MY_RLSE $ wget -O $MY_NAME.iso https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/$MY_RLSE/Workstation/x86_64/iso/$MY_LIVE ``` 上面的命令下载 `Fedora-Workstation-Live-x86_64-27-1.6.iso` Fedora Live 镜像,并保存为 `fc27.iso`。更改 `MY_RLSE` 的值来下载其它档案版本。或者,你可以浏览 <https://getfedora.org/> 来下载最新的 Fedora live 镜像。在 21 之前的版本使用不同的命名约定,必需[在这里手动下载](https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/)。如果你手动下载一个 Live CD 镜像,设置 `MY_NAME` 变量为不带有扩展名的文件的基本名称。用此方法,下面部分中命令将引用正确的文件。 ### 转换 Live CD 镜像 使用 `livecd-iso-to-disk` 工具来转换 ISO 文件为一个磁盘镜像,并添加 `netroot` 参数到嵌入的内核命令行: ``` $ sudo dnf install -y livecd-tools $ MY_SIZE=$(du -ms $MY_NAME.iso | cut -f 1) $ dd if=/dev/zero of=$MY_NAME.img bs=1MiB count=0 seek=$(($MY_SIZE+512)) $ MY_SRVR=server-01.example.edu $ MY_RVRS=$(echo $MY_SRVR | tr '.' "\n" | tac | tr "\n" '.' | cut -b -${#MY_SRVR}) $ MY_LOOP=$(sudo losetup --show --nooverlap --find $MY_NAME.img) $ sudo livecd-iso-to-disk --format --extra-kernel-args netroot=iscsi:$MY_SRVR:::1:iqn.$MY_RVRS:$MY_NAME $MY_NAME.iso $MY_LOOP $ sudo losetup -d $MY_LOOP ``` ### 上传 Live 镜像到你的服务器 在你的 ISCSI 服务器上创建一个目录来存储你的 live 镜像,随后上传你修改的镜像到其中。 对于 21 及更高发布版本: ``` $ MY_FLDR=/images $ scp $MY_NAME.img $MY_SRVR:$MY_FLDR/ ``` 对于 21 以前发布版本: ``` $ MY_FLDR=/images $ MY_LOOP=$(sudo losetup --show --nooverlap --find --partscan $MY_NAME.img) $ sudo tune2fs -O ^has_journal ${MY_LOOP}p1 $ sudo e2fsck ${MY_LOOP}p1 $ sudo dd status=none if=${MY_LOOP}p1 | ssh $MY_SRVR "dd of=$MY_FLDR/$MY_NAME.img" $ sudo losetup -d $MY_LOOP ``` ### 定义 iSCSI 目标 在你的 iSCSI 服务器上运行下面的命令: ``` $ sudo -i # MY_NAME=fc27 # MY_FLDR=/images # MY_SRVR=`hostname` # MY_RVRS=$(echo $MY_SRVR | tr '.' "\n" | tac | tr "\n" '.' | cut -b -${#MY_SRVR}) # cat << END > /etc/tgt/conf.d/$MY_NAME.conf <target iqn.$MY_RVRS:$MY_NAME> backing-store $MY_FLDR/$MY_NAME.img readonly 1 allow-in-use yes </target> END # tgt-admin --update ALL ``` ### 创建一个可启动 USB 驱动器 [iPXE](https://ipxe.org/) 启动加载程序有一个 [sanboot](http://ipxe.org/cmd/sanboot/) 命令,你可以使用它来连接并启动托管于你 ISCSI 服务器上运行的 live 镜像。它可以以很多不同的[格式](https://ipxe.org/appnote/buildtargets#boot_type)编译。最好的工作格式依赖于你正在运行的硬件。例如,下面的说明向你展示如何在一个 USB 驱动器上从 [syslinux](https://www.syslinux.org/wiki/index.php?title=SYSLINUX) 中 [链式加载](https://en.wikipedia.org/wiki/Chain_loading) iPXE。 首先,下载 iPXE,并以它的 lkrn 格式构建。这应该作为一个工作站上的普通用户完成: ``` $ sudo dnf install -y git $ git clone http://git.ipxe.org/ipxe.git $HOME/ipxe $ sudo dnf groupinstall -y "C Development Tools and Libraries" $ cd $HOME/ipxe/src $ make clean $ make bin/ipxe.lkrn $ cp bin/ipxe.lkrn /tmp ``` 接下来,准备一个带有一个 MSDOS 分区表和一个 FAT32 文件系统的 USB 驱动器。下面的命令假设你已经连接将要格式化的 USB 驱动器。**注意:你要格式正确的驱动器!** ``` $ sudo -i # dnf install -y parted util-linux dosfstools # echo; find /dev/disk/by-id ! -regex '.*-part.*' -name 'usb-*' -exec readlink -f {} \; | xargs -i bash -c "parted -s {} unit MiB print | perl -0 -ne '/^Model: ([^(]*).*\n.*?([0-9]*MiB)/i && print \"Found: {} = \$2 \$1\n\"'"; echo; read -e -i "$(find /dev/disk/by-id ! -regex '.*-part.*' -name 'usb-*' -exec readlink -f {} \; -quit)" -p "Drive to format: " MY_USB # umount $MY_USB? # wipefs -a $MY_USB # parted -s $MY_USB mklabel msdos mkpart primary fat32 1MiB 100% set 1 boot on # mkfs -t vfat -F 32 ${MY_USB}1 ``` 最后,在 USB 驱动器上安装并配置 syslinux ,来链式加载 iPXE: ``` # dnf install -y syslinux-nonlinux # syslinux -i ${MY_USB}1 # dd if=/usr/share/syslinux/mbr.bin of=${MY_USB} # MY_MNT=$(mktemp -d) # mount ${MY_USB}1 $MY_MNT # MY_NAME=fc27 # MY_SRVR=server-01.example.edu # MY_RVRS=$(echo $MY_SRVR | tr '.' "\n" | tac | tr "\n" '.' | cut -b -${#MY_SRVR}) # cat << END > $MY_MNT/syslinux.cfg ui menu.c32 default $MY_NAME timeout 100 menu title SYSLINUX label $MY_NAME menu label ${MY_NAME^^} kernel ipxe.lkrn append dhcp && sanboot iscsi:$MY_SRVR:::1:iqn.$MY_RVRS:$MY_NAME END # cp /usr/share/syslinux/menu.c32 $MY_MNT # cp /usr/share/syslinux/libutil.c32 $MY_MNT # cp /tmp/ipxe.lkrn $MY_MNT # umount ${MY_USB}1 ``` 通过简单地编辑 `syslinux.cfg` 文件,并添加附加的菜单项,你应该能够使用这同一个 USB 驱动器来网络启动附加的 ISCSI 目标。 这仅是加载 IPXE 的一种方法。你可以直接在你的工作站上安装 syslinux 。再一种选项是编译 iPXE 为一个 EFI 可执行文件,并直接放置它到你的 [ESP](https://en.wikipedia.org/wiki/EFI_system_partition) 中。又一种选项是编译 iPXE 为一个 PXE 加载器,并放置它到你的能够被 DHCP 引用的 TFTP 服务器。最佳的选项依赖于的环境 ### 最后说明 * 如果你以 IPXE 的 EFI 格式编译 IPXE ,你可能想添加 `–filename \EFI\BOOT\grubx64.efi` 参数到 `sanboot` 命令。 * 能够创建自定义 live 镜像。更多信息参考[创建和使用 live CD](https://docs.fedoraproject.org/en-US/quick-docs/creating-and-using-a-live-installation-image/#proc_creating-and-using-live-cd)。 * 可以添加 `–overlay-size-mb` 和 `–home-size-mb` 参数到 `livecd-iso-to-disk` 命令来创建永久存储的 live 镜像。然而,如果你有多个并发用户,你将需要设置你的 ISCSI 服务器来管理独立的每个用户的可写覆盖。这与 “[如何构建一个网络启动服务器,部分 4](https://fedoramagazine.org/how-to-build-a-netboot-server-part-4/)” 一文所示类似。 * Live 镜像在它们的内核命令行中支持一个 `persistenthome` 选项(例如, `persistenthome=LABEL=HOME`)。与经过 CHAP 身份验证的 iSCSI 目标一起使用,对于中心控制主目录,`persistenthome` 选项为 NFS 提供一个有趣的替代方案。 --- via: <https://fedoramagazine.org/netboot-a-fedora-live-cd/> 作者:[Gregory Bartholomew](https://fedoramagazine.org/author/glb/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxys) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
[Live CDs](https://en.wikipedia.org/wiki/Live_CD) are useful for many tasks such as: - installing the operating system to a hard drive - repairing a boot loader or performing other rescue-mode operations - providing a consistent and minimal environment for web browsing - …and [much more](https://en.wikipedia.org/wiki/Live_CD#Uses). As an alternative to using DVDs and USB drives to store your Live CD images, you can upload them to an [iSCSI](https://en.wikipedia.org/wiki/ISCSI) server where they will be less likely to get lost or damaged. This guide shows you how to load your Live CD images onto an iSCSI server and access them with the [iPXE](https://ipxe.org/) boot loader. ## Download a Live CD Image $ MY_RLSE=27 $ MY_LIVE=$(wget -q -O - https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/$MY_RLSE/Workstation/x86_64/iso | perl -ne '/(Fedora[^ ]*?-Live-[^ ]*?\.iso)(?{print $^N})/;') $ MY_NAME=fc$MY_RLSE $ wget -O $MY_NAME.iso https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/$MY_RLSE/Workstation/x86_64/iso/$MY_LIVE The above commands download the *Fedora-Workstation-Live-x86_64-27-1.6.iso* Fedora Live image and save it as *fc27.iso*. Change the value of *MY_RLSE* to download other archived versions. Or you can browse to [https://getfedora.org/](https://getfedora.org/) to download the latest Fedora live image. Versions prior to 21 used different naming conventions, and must be [downloaded manually here](https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/https://dl.fedoraproject.org/pub/archive/fedora/linux/releases/). If you download a Live CD image manually, set the *MY_NAME* variable to the basename of the file without the extension. That way the commands in the following sections will reference the correct file. ## Convert the Live CD Image Use the *livecd-iso-to-disk* tool to convert the ISO file to a disk image and add the *netroot* parameter to the embedded kernel command line: $ sudo dnf install -y livecd-tools $ MY_SIZE=$(du -ms $MY_NAME.iso | cut -f 1) $ dd if=/dev/zero of=$MY_NAME.img bs=1MiB count=0 seek=$(($MY_SIZE+512)) $ MY_SRVR=server-01.example.edu $ MY_RVRS=$(echo $MY_SRVR | tr '.' "\n" | tac | tr "\n" '.' | cut -b -${#MY_SRVR}) $ MY_LOOP=$(sudo losetup --show --nooverlap --find $MY_NAME.img) $ sudo livecd-iso-to-disk --format --extra-kernel-args netroot=iscsi:$MY_SRVR:::1:iqn.$MY_RVRS:$MY_NAME $MY_NAME.iso $MY_LOOP $ sudo losetup -d $MY_LOOP ## Upload the Live Image to your Server Create a directory on your iSCSI server to store your live images and then upload your modified image to it. **For releases 21 and greater:** $ MY_FLDR=/images $ scp $MY_NAME.img $MY_SRVR:$MY_FLDR/ **For releases prior to 21:** $ MY_FLDR=/images $ MY_LOOP=$(sudo losetup --show --nooverlap --find --partscan $MY_NAME.img) $ sudo tune2fs -O ^has_journal ${MY_LOOP}p1 $ sudo e2fsck ${MY_LOOP}p1 $ sudo dd status=none if=${MY_LOOP}p1 | ssh $MY_SRVR "dd of=$MY_FLDR/$MY_NAME.img" $ sudo losetup -d $MY_LOOP ## Define the iSCSI Target Run the following commands on your iSCSI server: $ sudo -i # MY_NAME=fc27 # MY_FLDR=/images # MY_SRVR=`hostname` # MY_RVRS=$(echo $MY_SRVR | tr '.' "\n" | tac | tr "\n" '.' | cut -b -${#MY_SRVR}) # cat << END > /etc/tgt/conf.d/$MY_NAME.conf <target iqn.$MY_RVRS:$MY_NAME> backing-store $MY_FLDR/$MY_NAME.img readonly 1 allow-in-use yes </target> END # tgt-admin --update ALL ## Create a Bootable USB Drive The [iPXE](https://ipxe.org/) boot loader has a [sanboot](http://ipxe.org/cmd/sanboot/) command you can use to connect to and start the live images hosted on your iSCSI server. It can be compiled in many different [formats](https://ipxe.org/appnote/buildtargets#boot_type). The format that works best depends on the type of hardware you’re running. As an example, the following instructions show how to [chain load](https://en.wikipedia.org/wiki/Chain_loading) iPXE from [syslinux](https://www.syslinux.org/wiki/index.php?title=SYSLINUX) on a USB drive. First, download iPXE and build it in its *lkrn* format. This should be done as a normal user on a workstation: $ sudo dnf install -y git $ git clone http://git.ipxe.org/ipxe.git $HOME/ipxe $ sudo dnf groupinstall -y "C Development Tools and Libraries" $ cd $HOME/ipxe/src $ make clean $ make bin/ipxe.lkrn $ cp bin/ipxe.lkrn /tmp Next, prepare a USB drive with a MSDOS partition table and a FAT32 file system. The below commands assume that you have already connected the USB drive to be formatted. **Be careful that you do not format the wrong drive!** $ sudo -i # dnf install -y parted util-linux dosfstools # echo; find /dev/disk/by-id ! -regex '.*-part.*' -name 'usb-*' -exec readlink -f {} \; | xargs -i bash -c "parted -s {} unit MiB print | perl -0 -ne '/^Model: ([^(]*).*\n.*?([0-9]*MiB)/i && print \"Found: {} = \$2 \$1\n\"'"; echo; read -e -i "$(find /dev/disk/by-id ! -regex '.*-part.*' -name 'usb-*' -exec readlink -f {} \; -quit)" -p "Drive to format: " MY_USB # umount $MY_USB? # wipefs -a $MY_USB # parted -s $MY_USB mklabel msdos mkpart primary fat32 1MiB 100% set 1 boot on # mkfs -t vfat -F 32 ${MY_USB}1 Finally, install syslinux on the USB drive and configure it to chain load iPXE: # dnf install -y syslinux-nonlinux # syslinux -i ${MY_USB}1 # dd if=/usr/share/syslinux/mbr.bin of=${MY_USB} # MY_MNT=$(mktemp -d) # mount ${MY_USB}1 $MY_MNT # MY_NAME=fc27 # MY_SRVR=server-01.example.edu # MY_RVRS=$(echo $MY_SRVR | tr '.' "\n" | tac | tr "\n" '.' | cut -b -${#MY_SRVR}) # cat << END > $MY_MNT/syslinux.cfg ui menu.c32 default $MY_NAME timeout 100 menu title SYSLINUX label $MY_NAME menu label ${MY_NAME^^} kernel ipxe.lkrn append dhcp && sanboot iscsi:$MY_SRVR:::1:iqn.$MY_RVRS:$MY_NAME END # cp /usr/share/syslinux/menu.c32 $MY_MNT # cp /usr/share/syslinux/libutil.c32 $MY_MNT # cp /tmp/ipxe.lkrn $MY_MNT # umount ${MY_USB}1 You should be able to use this same USB drive to netboot additional iSCSI targets simply by editing the *syslinux.cfg* file and adding additional menu entries. This is just one method of loading iPXE. You could install syslinux directly on your workstation. Another option is to compile iPXE as an EFI executable and place it directly in your [ESP](https://en.wikipedia.org/wiki/EFI_system_partition). Yet another is to compile iPXE as a PXE loader and place it on your TFTP server to be referenced by DHCP. The best option depends on your environment. ## Final Notes - You may want to add the *–filename \EFI\BOOT\grubx64.efi*parameter to the*sanboot*command if you compile iPXE in its EFI format. - It is possible to create custom live images. Refer to [Creating and using live CD](https://docs.fedoraproject.org/en-US/quick-docs/creating-and-using-a-live-installation-image/#proc_creating-and-using-live-cd)for more information. - It is possible to add the *–overlay-size-mb*and*–home-size-mb*parameters to the*livecd-iso-to-disk*command to create live images with persistent storage. However, if you have multiple concurrent users, you’ll need to set up your iSCSI server to manage separate per-user writeable overlays. This is similar to what was shown in the “[How to Build a Netboot Server, Part 4](https://fedoramagazine.org/how-to-build-a-netboot-server-part-4/)” article. - The live images support a *persistenthome*option on their kernel command line (e.g.*persistenthome=LABEL=HOME*). Used together with CHAP-authenticated iSCSI targets, the*persistenthome*option provides an interesting alternative to NFS for centralized home directories. *Photo by **Chris Yates** on **Unsplash**.* ## svsv sarma I don’t see any advantage of the Net-boot with so much technical struggle, when a full fledged Fedora live DVD is handy. Perhaps I am a lay man or it is just for fun! ## Gregory Bartholomew It’s not for everyone. But I hear you. Next time I’ll try to write something more useful to the typical end user. ## Leslie Satenstein I have external backup drives. I copy the ISO’s to the external drive. I also have internal drives a through f. I often want to install a Linux ISO on one of the b through f drives. What would interest me as a topic woule be a demonstration of being able, while in my installed Fedora system, to: mount the Linux ISO, do a chroot or some other action to the ISO run the ISO’s boot and installation software. In otherwords, using a “xyz.sh” script or a “xyz” application program, do the above avoid installing the ISO copy to a flashdrive and then booting that flashdrive to perform the evaluation or installation of the desired Linux ISO I want to avoid copying the ISO to a USB flash drive and booting from that flashdrive. ## Gregory Bartholomew Hi Leslie, Thank you for your article suggestion! We are always looking for new ideas. The 3 steps that you describe are essentially what happens “behind the scenes” when the following command is run: $ qemu-system-x86_64 -machine accel=kvm -m 1024M -drive format=raw,file=,cache=none,if=virtio -cdrom .iso -boot once=d Does that command satisfy your criteria? If so, it may be a bit too brief to do an article for. However, we might be able to make an article out of it if we provided more examples and variations of the command or made the article about QEMU and provided the above command as one example of its usage. Alternatively, if you wanted to replacethe currently running OS with the one from the ISO, that might be doable with the kexec command.I’m not sure how reliable it would be to run anaconda from the installation disk without running (booting) the provided kernel if that is what you are wanting to do. I once had a situation where I wanted to keep an installation ISO on a secondary drive of a server and be able to reboot the server and do a full (re)installation of the OS on the primary drive remotely through the command line (the “command line” was routed to a separate server using a serial cable). That wasn’t too difficult. All I had to do was to copy the contents of the installation CD to a partition on the secondary drive and tweak the syslinux.cfg file by adding the line: serial 0 115200 at the top and append “console=ttyS0,115200n8 nomodeset inst.text” to the kernel command line (I also made a few aesthetic tweaks to the syslinux.cfg file — numer of rows, helpmsgrow, etc.). I could then access (“chain load”) syslinux on the secondary drive by pressing “c” when grub came up and entering something like: root=(hd1) chainloader +1 boot I’m not sure if there would be much interest in a how to for something like that, but if several people reply requesting it, I could do a detailed write up about it. Anyway, I’ll write a “pitch” for a QEMU article if there isn’t already one in the magazine archives. Suggestions are welcome. Thanks! ## Gregory Bartholomew Whoops, the editor butchered by reply. I always forget that things between angle brackets need to be escaped or they will get removed when I click “post comment”. That example command line should have been: $ qemu-system-x86_64 -machine accel=kvm -m 1024M -drive format=raw,file=<device node>,cache=none,if=virtio -cdrom <isoname>.iso -boot once=d ## Gregory Bartholomew One caveat that I should note about using qemu to install an OS to a secondary drive is that if you subsequently try to boot your physical machine directly off of that drive, the hardware might not be detected properly because the initramfs will have been build against the “virtualized” hardware at installtion time. You should be able to work around that problem by selecting the “rescue” initramfs (it includes ALL drivers), and then running “dracut -f –regenerate-all” to rebuild the initramfs against the correct hardware.
11,709
Linux 如何设置密码复杂度?
https://www.2daygeek.com/how-to-set-password-complexity-policy-on-linux/
2019-12-23T23:19:05
[ "密码" ]
https://linux.cn/article-11709-1.html
![](/data/attachment/album/201912/23/231829jr5huwjufjhxxwrz.jpg) 对于 Linux 系统管理员来说,用户管理是最重要的事之一。这涉及到很多因素,实现强密码策略是用户管理的其中一个方面。移步后面的 URL 查看如何 [在 Linux 上生成一个强密码](https://www.2daygeek.com/5-ways-to-generate-a-random-strong-password-in-linux-terminal/)。它会限制系统未授权的用户的访问。 所有人都知道 Linux 的默认策略很安全,然而我们还是要做一些微调,这样才更安全。弱密码有安全隐患,因此,请特别注意。移步后面的 URL 查看生成的强密码的[密码长度和分值](https://www.2daygeek.com/how-to-check-password-complexity-strength-and-score-in-linux/)。本文将教你在 Linux 中如何实现最安全的策略。 在大多数 Linux 系统中,我们可以用 PAM(<ruby> 可插拔认证模块 <rt> pluggable authentication module </rt></ruby>)来加强密码策略。在下面的路径可以找到这个文件。 * 在红帽系列的系统中,路径:`/etc/pam.d/system-auth`。 * Debian 系列的系统中,路径:`/etc/pam.d/common-password`。 关于默认的密码过期时间,可以在 `/etc/login.defs` 文件中查看详细信息。 为了更好理解,我摘取了文件的部分内容: ``` # vi /etc/login.defs PASS_MAX_DAYS 99999 PASS_MIN_DAYS 0 PASS_MIN_LEN 5 PASS_WARN_AGE 7 ``` 详细解释: * `PASS_MAX_DAYS`:一个密码可使用的最大天数。 * `PASS_MIN_DAYS`:两次密码修改之间最小的间隔天数。 * `PASS_MIN_LEN`:密码最小长度。 * `PASS_WARN_AGE`:密码过期前给出警告的天数。 我们将会展示在 Linux 中如何实现下面的 11 个密码策略。 * 一个密码可使用的最大天数 * 两次密码修改之间最小的间隔天数 * 密码过期前给出警告的天数 * 密码历史记录/拒绝重复使用密码 * 密码最小长度 * 最少的大写字母个数 * 最少的小写字母个数 * 最少的数字个数 * 最少的其他字符(符号)个数 * 账号锁定 — 重试 * 账号解锁时间 ### 密码可使用的最大天数是什么? 这一参数限制一个密码可使用的最大天数。它强制用户在过期前修改他/她的密码。如果他们忘记修改,那么他们会登录不了系统。他们需要联系管理员才能正常登录。这个参数可以在 `/etc/login.defs` 文件中设置。我把这个参数设置为 90 天。 ``` # vi /etc/login.defs PASS_MAX_DAYS 90 ``` ### 密码最小天数是什么? 这个参数限制两次修改之间的最少天数。举例来说,如果这个参数被设置为 15 天,用户今天修改了密码,那么在 15 天之内他都不能修改密码。这个参数可以在 `/etc/login.defs` 文件中设置。我设置为 15 天。 ``` # vi /etc/login.defs PASS_MIN_DAYS 15 ``` ### 密码警告天数是什么? 这个参数控制密码警告的前置天数,在密码即将过期时会给用户警告提示。在警告天数结束前,用户会收到日常警告提示。这可以提醒用户在密码过期前修改他们的密码,否则我们就需要联系管理员来解锁密码。这个参数可以在 `/etc/login.defs` 文件中设置。我设置为 10 天。 ``` # vi /etc/login.defs PASS_WARN_AGE 10 ``` **注意:** 上面的所有参数仅对新账号有效,对已存在的账号无效。 ### 密码历史或拒绝重复使用密码是什么? 这个参数控制密码历史。它记录曾经使用过的密码(禁止使用的曾用密码的个数)。当用户设置新的密码时,它会检查密码历史,如果他们要设置的密码是一个曾经使用过的旧密码,将会发出警告提示。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。我设置密码历史为 5。 ``` # vi /etc/pam.d/system-auth password sufficient pam_unix.so md5 shadow nullok try_first_pass use_authtok remember=5 ``` ### 密码最小长度是什么? 这个参数表示密码的最小长度。当用户设置新密码时,系统会检查这个参数,如果新设的密码长度小于这个参数设置的值,会收到警告提示。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。我设置最小密码长度为 12。 ``` # vi /etc/pam.d/system-auth password requisite pam_cracklib.so try_first_pass retry=3 minlen=12 ``` `try_first_pass retry=3`:在密码设置交互界面,用户有 3 次机会重设密码。 ### 设置最少的大写字母个数? 这个参数表示密码中至少需要的大写字母的个数。这些是密码强度参数,可以让密码更健壮。当用户设置新密码时,系统会检查这个参数,如果密码中没有大写字母,会收到警告提示。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。我设置密码(中的大写字母)的最小长度为 1 个字母。 ``` # vi /etc/pam.d/system-auth password requisite pam_cracklib.so try_first_pass retry=3 minlen=12 ucredit=-1 ``` ### 设置最少的小写字母个数? 这个参数表示密码中至少需要的小写字母的个数。这些是密码强度参数,可以让密码更健壮。当用户设置新密码时,系统会检查这个参数,如果密码中没有小写字母,会收到警告提示。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。我设置为 1 个字母。 ``` # vi /etc/pam.d/system-auth password requisite pam_cracklib.so try_first_pass retry=3 minlen=12 lcredit=-1 ``` ### 设置密码中最少的数字个数? 这个参数表示密码中至少需要的数字的个数。这些是密码强度参数,可以让密码更健壮。当用户设置新密码时,系统会检查这个参数,如果密码中没有数字,会收到警告提示。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。我设置为 1 个数字。 ``` # vi /etc/pam.d/system-auth password requisite pam_cracklib.so try_first_pass retry=3 minlen=12 dcredit=-1 ``` ### 设置密码中最少的其他字符(符号)个数? 这个参数表示密码中至少需要的特殊符号的个数。这些是密码强度参数,可以让密码更健壮。当用户设置新密码时,系统会检查这个参数,如果密码中没有特殊符号,会收到警告提示。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。我设置为 1 个字符。 ``` # vi /etc/pam.d/system-auth password requisite pam_cracklib.so try_first_pass retry=3 minlen=12 ocredit=-1 ``` ### 设置账号锁定? 这个参数控制用户连续登录失败的最大次数。当达到设定的连续失败登录次数阈值时,锁定账号。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。 ``` # vi /etc/pam.d/system-auth auth required pam_tally2.so onerr=fail audit silent deny=5 account required pam_tally2.so ``` ### 设定账号解锁时间? 这个参数表示用户解锁时间。如果一个用户账号在连续认证失败后被锁定了,当过了设定的解锁时间后,才会解锁。设置被锁定中的账号的解锁时间(900 秒 = 15分钟)。这个参数可以在 `/etc/pam.d/system-auth` 文件中设置。 ``` # vi /etc/pam.d/system-auth auth required pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900 account required pam_tally2.so ``` --- via: <https://www.2daygeek.com/how-to-set-password-complexity-policy-on-linux/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
11,711
在 Linux 上安装安卓 8.1 Oreo 来运行应用程序和游戏
https://fosspost.org/tutorials/install-android-8-1-oreo-on-linux
2019-12-24T23:34:03
[ "安卓", "Android" ]
https://linux.cn/article-11711-1.html
![](/data/attachment/album/201912/24/233410f2qbd1070f1n8mgc.png) [android x86](http://www.android-x86.org/) 是一个自由而开源的项目,将谷歌制作的安卓系统从 ARM 架构移植到了 x86 架构,可以让用户在他们的桌面电脑上运行安卓系统来享受所有的安卓功能和应用程序及游戏。 在前一段时间,android x86 项目完成了安卓 8.1 Oreo 系统的 x86 架构移植。在这篇文章中,我们将解释如何在你的 Linux 系统上安装它,以便你能够随时使用你的安卓 用程序和游戏。 ### 在 Linux 上安装安卓 x86 8.1 Oreo #### 准备环境 首先,让我们下载 android x86 8.1 Oreo 系统镜像。你可以从[这个页面](http://www.android-x86.org/download)下载它,只需单击 “android-x86\_64-8.1-r1.iso” 文件下的 “View” 按钮。 我们将在我们的 Linux 系统上使用 QEMU 来运行 android x86。QEMU 是一个非常好的模拟器软件,它也是自由而开源的,并且在所有主要的 Linux 发行版存储库中都是可用的。 在 Ubuntu/Linux Mint/Debian 上安装 QEMU: ``` sudo apt-get install qemu qemu-kvm libvirt-bin ``` 在 Fedora 上安装 QEMU: ``` sudo dnf install qemu qemu-kvm ``` 对于其它发行版,只需要搜索 “qemu” 和 “qemu-kvm” 软件包,并安装它们。 在你安装 QEMU 后,我们将需要运行下面的命令来创建 `android.img` 文件,它就像某种分配给安卓系统的磁盘空间。所有安卓文件和系统都将位于该镜像文件中: ``` qemu-img create -f qcow2 android.img 15G ``` 我们在这里的意思是,我们想为该安卓系统分配一个最大 15GB 的磁盘空间,但是,你可以更改它到你想要的任意大小(确保它至少大于 5GB)。 现在,首次启动运行该安卓系统,运行: ``` sudo qemu-system-x86_64 -m 2048 -boot d -enable-kvm -smp 3 -net nic -net user -hda android.img -cdrom /home/mhsabbagh/android-x86_64-8.1-r1.iso ``` 将 `/home/mhsabbagh/android-x86_64-8.1-r1.iso` 替换为你从 android x86 网站下载的文件的路径。关于我们在这里正在使用的其它选项的解释,你可以参考[这篇文章](https://fosspost.org/tutorials/use-qemu-test-operating-systems-distributions)。 在你运行上面的命令后,该安卓系统将启动: ![](/data/attachment/album/201912/24/233413je8p76xppd9fxx67.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 40 android 8.1 oreo on linux") #### 安装系统 从这个窗口中,选择 “Advanced options”, 它将引导到下面的菜单,你应如下在其中选择 “Auto\_installation” : ![](/data/attachment/album/201912/24/233416e8bbjsgwy67l06w8.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 42 android 8.1 oreo on linux") 在这以后,安装器将告知你是否想要继续,选择 “Yes”: ![](/data/attachment/album/201912/24/233420g3wcgjddcj7ejegq.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 44 android 8.1 oreo on linux") 接下来,安装器将无需你的指示而继续进行: ![](/data/attachment/album/201912/24/233421biuqii2zunaj0nny.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 46 android 8.1 oreo on linux") 最后,你将收到这个信息,它表示你已经成功安装安卓 8.1 : ![](/data/attachment/album/201912/24/233423vnazontn138bzdof.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 48 android 8.1 oreo on linux") 现在,关闭 QEMU 窗口即可。 #### 启动和使用 安卓 8.1 Oreo 现在,安卓系统已经完全安装在你的 `android.img` 文件中,你应该使用下面的 QEMU 命令来启动它,而不是前面的命令: ``` sudo qemu-system-x86_64 -m 2048 -boot d -enable-kvm -smp 3 -net nic -net user -hda android.img ``` 注意,我们所做的只是移除 `-cdrom` 选项及其参数。这是告诉 QEMU,我们不再想从我们下载的 ISO 文件启动,相反,从这个安装的安卓系统启动。 你现在能够看到安卓的启动菜单: ![](/data/attachment/album/201912/24/233425ftf9g7ztagpl4rfx.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 50 android 8.1 oreo on linux") 然后,你将进入第一个准备向导,选择你的语言并继续: ![](/data/attachment/album/201912/24/233426syetz7zyeeveqmat.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 52 android 8.1 oreo on linux") 从这里,选择 “Set up as new” 选项: ![](/data/attachment/album/201912/24/233428slmbizq1k29bbbmn.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 54 android 8.1 oreo on linux") 然后,安卓将询问你是否想登录到你当前的谷歌账号。这步骤是可选的,但是这很重要,以便你随后可以使用谷歌 Play 商店: ![](/data/attachment/album/201912/24/233430lszsxsg27lsicc9l.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 56 android 8.1 oreo on linux") 然后,你将需要接受条款: ![](/data/attachment/album/201912/24/233433eoqzu1koyny1boqt.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 58 android 8.1 oreo on linux") 现在,你可以选择你当前的时区: ![](/data/attachment/album/201912/24/233434mmdsb5dkbjm9jb5n.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 60 android 8.1 oreo on linux") 系统将询问你是否想启动一些数据收集功能。如果我是你的话,我将简单地全部关闭它们,像这样: ![](/data/attachment/album/201912/24/233439ly30xn3pyjz6n6m8.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 62 android 8.1 oreo on linux") 最后,你将有两种启动类型可供选择,我建议你选择 Launcher3 选项,并使其成为默认项: ![](/data/attachment/album/201912/24/233441tn799n7j8bxnb9nz.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 64 android 8.1 oreo on linux") 然后,你将看到完整工作的安卓系统主屏幕: ![](/data/attachment/album/201912/24/233445ro8yxox0avhyh8oh.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 66 android 8.1 oreo on linux") 从现在起,你可以做你想做的任何事情;你可以使用内置的安卓应用程序,或者你可以浏览你的系统设置来根据你的喜好进行调整。你可以更改你的系统的外观和体验,或者你可以像示例一样运行 Chrome : ![](/data/attachment/album/201912/24/233448z511gt1ot1yig7jy.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 68 android 8.1 oreo on linux") 你可以开始从谷歌 Play 商店安装一些应用程序程序,像 WhatsApp 和其它的应用程序,以供你自己使用: ![](/data/attachment/album/201912/24/233451d4ffc4cnwf42jbcf.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 70 android 8.1 oreo on linux") 你现在可以用你的系统做任何你想做的事。恭喜! ### 以后如何轻松地运行安卓 8.1 Oreo 我们不想总是不得不打开终端窗口,并写那些长长的 QEMU 命令来运行安卓系统,相反,我们想在我们需要时一次单击就运行它。 为此,我们将使用下面的命令在 `/usr/share/applications` 下创建一个名为 `android.desktop` 的新文件: ``` sudo nano /usr/share/applications/android.desktop ``` 并在其中粘贴下面的内容(右键单击然后粘贴): ``` [Desktop Entry] Name=Android 8.1 Comment=Run Android 8.1 Oreo on Linux using QEMU Icon=phone Exec=bash -c 'pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY qemu-system-x86_64 -m 2048 -boot d -enable-kvm -smp 3 -net nic -net user -hda /home/mhsabbagh/android.img' Terminal=false Type=Application StartupNotify=true Categories=GTK; ``` 再强调一次,你必需使用你系统上的本地镜像路径来替换 `/home/mhsabbagh/android.img` 。然后保存文件(`Ctrl+X`,然后按 `Y`,然后按回车)。 注意,我们需要使用 `pkexec` 来使用 root 权限运行 QEMU ,因为从较新的版本开始,普通用户不允许通过 libvirt 访问 KVM 技术;这就是为什么它将每次要求你输入 root 密码的原因。 现在,你将在应用程序菜单中看到安卓图标,你可以在你想使用安卓的任何时间来简单地单击该图标,QEMU 程序将启动: ![](/data/attachment/album/201912/24/233453rj81hq1myjfyd19f.png "Install Android 8.1 Oreo on Linux To Run Apps & Games 72 android 8.1 oreo on linux") ### 总结 我们向你展示如何在你的 Linux 系统上安装和运行安卓 8.1 Oreo 。从现在起,在没有其它一些软件的(像 Blutsticks 和类似的方法)的情况下,你可以更容易地完成基于安卓的任务。在这里,你有一个完整工作和功能的安卓系统,你可以随心所欲地操作它,如果一些东西出错,你可以简单地干掉该镜像文件,然后随时再一次重新运行安装程序。 你之前尝试过 android x86 吗?你的体验如何? --- via: <https://fosspost.org/tutorials/install-android-8-1-oreo-on-linux> 作者:[M.Hanny Sabbagh](https://fosspost.org/author/mhsabbagh) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,712
使用 FVWM 自定义 Linux 桌面
https://opensource.com/article/19/12/fvwm-linux-desktop
2019-12-25T06:28:18
[ "FVWM" ]
https://linux.cn/article-11712-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。如果你正在寻找轻巧、快速且简单的 Linux 窗口管理器,那么 FVWM 可以胜任。但是,如果你正在寻找可以深入、探索和魔改的窗口管理器,那么 FVWM 是必须的。 > > > ![](/data/attachment/album/201912/25/062800dwh3yhfcpx3ggjxp.jpg) [FVWM](http://www.fvwm.org/) 窗口管理器最早脱胎于对 1993 年的 [TWM](https://en.wikipedia.org/wiki/Twm) 的修改。经过几年的迭代,诞生了一个可高度自定义的环境,它可以配置任何行为、动作或事件。它支持自定义键绑定、鼠标手势、主题、脚本等。 尽管 FVWM 在安装后即可投入使用,但默认分发版本仅提供了极其少的配置。这是开始自定义桌面环境的良好基础,但是,如果你只想将其用作桌面,那么可能要安装由其它用户发布的完整配置版本。FVWM 有几种不同的分发版,包括模仿 Windows 95 的 FVWM95(至少在外观和布局上)。我尝试了 [FVWM-Crystal](https://www.box-look.org/p/1018270/),这是一个具有一些现代 Linux 桌面约定的现代主题。 可以从 Linux 发行版的软件仓库中安装要尝试的 FVWM 分发版。如果找不到特定的 FVWM 分发版,那么可以安装基础的 FVWM2 包,然后进入 [Box-Look.org](http://box-look.org) 手动下载主题包。这样就需要更多的工作,但比从头开始构建要少。 安装后,请注销当前的桌面会话,以便你可以登录 FVWM。默认情况下,会话管理器(KDM、GDM、LightDM 或 XDM,取决于你的设置)将继续登录到以前的桌面,因此你必须在登录之前覆盖该桌面。 对于 GDM: ![Select your desktop session in GDM](/data/attachment/album/201912/25/062821v99x5n5f9nx6zi65.jpg "Select your desktop session in GDM") 对于 KDM: ![Select your desktop session with KDM](/data/attachment/album/201912/25/062821jcgqctsgpumkptui.jpg "Select your desktop session with KDM") ### FVWM 桌面 无论你使用什么主题和配置,当你在桌面上单击鼠标左键时,FVWM 至少会显示一个菜单。菜单的内容取决于你所安装的内容。FVWM-Crystal 分发版中的菜单包含对常用首选项的快速访问,例如屏幕分辨率、壁纸设置、窗口装饰等。 同 FVWM 中的几乎所有东西一样,你可以编辑菜单中你要想的内容,但 FVWM-Crystal 的特色在于其应用菜单栏。应用菜单位于屏幕的左上角,每个图标都包含了相关的应用启动器的菜单。例如,GIMP 图标表示图像编辑器,KDevelop 图标表示集成开发环境(IDE),GNU 图标表示文本编辑器,等等,具体取决于你在系统上安装的程序。 ![FVWM-crystal running on Slackware 14.2](/data/attachment/album/201912/25/062822w1hjba0mymlzzxbm.jpg "FVWM-crystal running on Slackware 14.2") FVWM-Crystal 还提供了虚拟桌面、任务栏、时钟和应用栏。 关于背景,你可以使用与 FVWM-Crystal 捆绑在一起的壁纸,也可以使用 `feh` 命令设置自己的壁纸(你可能需要从仓库中安装它)。此命令有一些设置背景的选项,包括 `--bg-scale` 使用你选择的图片缩放填充屏幕,`--bg-fill` 直接填充而不缩放图片,等等。 ``` $ feh --bg-scale ~/Pictures/wallpapers/mybackground.jpg ``` 大多数配置文件都包含在 `$HOME/.fvwm-crystal` 中,某些系统范围的默认文件位于 `/usr/share/fvwm-crystal`。 ### 自己尝试一下 FVWM 是大多作为一个桌面构建平台,它也是窗口管理器。它不会为你做到面面俱到,它期望你来配置尽可能的一切。 如果你正在寻找轻巧、快速且简单的窗口管理器,那么 FVWM 可以胜任。但是,如果你正在寻找可以深入、探索和魔改的窗口管理器,那么 FVWM 是必须的。 --- via: <https://opensource.com/article/19/12/fvwm-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The [FVWM](http://www.fvwm.org/) window manager started out as modifications to [TWM](https://en.wikipedia.org/wiki/Twm), back in 1993. After several years of iteration, what emerged is an extremely customizable environment where any behavior, action, or event is configurable. It has support for custom key bindings, mouse gestures, theming, scripting, and much more. While FVWM is usable immediately after installation, its default distribution provides only the absolute minimum configuration. It's a great foundation to start your own custom desktop environment, but if you just want to use it as a desktop, then you probably want to install a full configuration distributed by another user. There are a few different distributions of FVWM, including FVWM95, which mimics Windows 95 (at least in appearance and layout). I tried [FVWM-Crystal](https://www.box-look.org/p/1018270/), a modern-looking theme with some common Linux desktop conventions. Install the FVWM distribution you want to try from your Linux distribution's software repository. If you can't find a specific FVWM distribution, it's safe to install the base FVWM2 package and then go to [Box-Look.org](http://box-look.org) to download a theme package manually. It's a little more work that way, but not nearly as much as building your own workspace from scratch. After installing, log out of your current desktop session so you can log into FVWM. By default, your session manager (KDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. To do so with GDM: ![Select your desktop session in GDM Select your desktop session in GDM](https://opensource.com/sites/default/files/advent-gdm_0.jpg) And with SDDM: ![Select your desktop session with KDM Select your desktop session with KDM](https://opensource.com/sites/default/files/advent-kdm.jpg) ## FVWM desktop Regardless of what theme and configuration you're using, FVWM, at minimum, provides a menu when you left-click on the desktop. The contents of this menu vary depending on what you've installed. The menu in the FVWM-Crystal distribution contains quick access to common preferences, such as screen resolution, wallpaper settings, window decorations, and so on. As with pretty much everything in FVWM, the menu can be edited to include whatever you want, but FVWM-Crystal favors the application menu bar. The application menu is located at the top-left of the screen, and each icon contains a menu of related application launchers. For example, the GIMP icon reveals image editors, the KDevelop icon reveals integrated development environments (IDEs), the GNU icon reveals text editors, and so on, depending on what you have installed on your system. ![FVWM-crystal running on Slackware 14.2 FVWM-crystal running on Slackware 14.2](https://opensource.com/sites/default/files/advent-fvwm-crystal.jpg) FVWM-Crystal also provides virtual desktops, a taskbar, a clock, and an application bar. For your background, you can use the wallpapers bundled with FVWM-Crystal or set your own with the **feh** command (you may need to install it from your repository). This command has a few options for setting the background, including **--bg-scale** to fill the screen with a scaled version of your wallpaper of choice, **--bg-fill** to fill the screen without adjusting the size of the image, and so on. `$ feh --bg-scale ~/Pictures/wallpapers/mybackground.jpg` Most configuration files are contained in **$HOME/.fvwm-crystal**, with some systemwide defaults located in **/usr/share/fvwm-crystal**. ## Do it yourself FVWM is as much a desktop-building platform as it is a window manager. It doesn't do anything for you, and it expects you to configure anything—and possibly everything. If you're looking for a lightweight, fast, and simple window manager, FVWM qualifies. But if you're looking for something to dig into, explore, and hack, then FVWM is a must. ## Comments are closed.
11,714
怎样用 Bash 编程:循环
https://opensource.com/article/19/10/programming-bash-loops
2019-12-26T11:15:19
[ "Bash" ]
https://linux.cn/article-11714-1.html
> > 本文是 Bash 编程系列三篇中的最后一篇,来学习使用循环执行迭代的操作。 > > > ![](/data/attachment/album/201912/26/111437f9pa3zqqwcc9wwg1.jpg) Bash 是一种强大的用于命令行和 shell 脚本的编程语言。本系列的三部分都是基于我的三集 [Linux 自学课程](http://www.both.org/?page_id=1183) 写的,探索怎么用 CLI 进行 bash 编程。 本系列的 [第一篇文章](/article-11552-1.html) 讨论了 bash 编程的一些简单命令行操作,如使用变量和控制操作符。[第二篇文章](/article-11687-1.html) 探讨了文件、字符串、数字等类型和各种各样在执行流中提供控制逻辑的的逻辑运算符,还有 bash 中不同种类的扩展。本文是第三篇(也是最后一篇),意在考察在各种迭代的操作中使用循环以及怎么合理控制循环。 ### 循环 我使用过的所有编程语言都至少有两种循环结构来用来执行重复的操作。我经常使用 `for` 循环,然而我发现 `while` 和 `until` 循环也很有用处。 #### for 循环 我的理解是,在 bash 中实现的 `for` 命令比大部分语言灵活,因为它可以处理非数字的值;与之形成对比的是,诸如标准 C 语言的 `for` 循环只能处理数字类型的值。 Bash 版的 `for` 命令基本的结构很简单: ``` for Var in list1 ; do list2 ; done ``` 解释一下:“对于 `list1` 中的每一个值,把 `$Var` 设置为那个值,使用该值执行 `list2` 中的程序语句;`list1` 中的值都执行完后,整个循环结束,退出循环。” `list1` 中的值可以是一个简单的显式字符串值,也可以是一个命令执行后的结果(`` 包含其内的命令执行的结果,本系列第二篇文章中有描述)。我经常使用这种结构。 要测试它,确认 `~/testdir` 仍然是当前的工作目录(PWD)。删除目录下所有东西,来看下这个显式写出值列表的 `for` 循环的简单的示例。这个列表混合了字母和数字 — 但是不要忘了,在 bash 中所有的变量都是字符串或者可以被当成字符串来处理。 ``` [student@studentvm1 testdir]$ rm * [student@studentvm1 testdir]$ for I in a b c d 1 2 3 4 ; do echo $I ; done a b c d 1 2 3 4 ``` 给变量赋予更有意义的名字,变成前面版本的进阶版: ``` [student@studentvm1 testdir]$ for Dept in "Human Resources" Sales Finance "Information Technology" Engineering Administration Research ; do echo "Department $Dept" ; done Department Human Resources Department Sales Department Finance Department Information Technology Department Engineering Department Administration Department Research ``` 创建几个目录(创建时显示一些处理信息): ``` [student@studentvm1 testdir]$ for Dept in "Human Resources" Sales Finance "Information Technology" Engineering Administration Research ; do echo "Working on Department $Dept" ; mkdir "$Dept" ; done Working on Department Human Resources Working on Department Sales Working on Department Finance Working on Department Information Technology Working on Department Engineering Working on Department Administration Working on Department Research [student@studentvm1 testdir]$ ll total 28 drwxrwxr-x 2 student student 4096 Apr 8 15:45 Administration drwxrwxr-x 2 student student 4096 Apr 8 15:45 Engineering drwxrwxr-x 2 student student 4096 Apr 8 15:45 Finance drwxrwxr-x 2 student student 4096 Apr 8 15:45 'Human Resources' drwxrwxr-x 2 student student 4096 Apr 8 15:45 'Information Technology' drwxrwxr-x 2 student student 4096 Apr 8 15:45 Research drwxrwxr-x 2 student student 4096 Apr 8 15:45 Sales ``` 在 `mkdir` 语句中 `$Dept` 变量必须用引号包裹起来;否则名字中间有空格(如 `Information Technology`)会被当做两个独立的目录处理。我一直信奉的一条实践规则:所有的文件和目录都应该为一个单词(中间没有空格)。虽然大部分现代的操作系统可以处理名字中间有空格的情况,但是系统管理员需要花费额外的精力去确保脚本和 CLI 程序能正确处理这些特例。(即使它们很烦人,也务必考虑它们,因为你永远不知道将拥有哪些文件。) 再次删除 `~/testdir` 下的所有东西 — 再运行一次下面的命令: ``` [student@studentvm1 testdir]$ rm -rf * ; ll total 0 [student@studentvm1 testdir]$ for Dept in Human-Resources Sales Finance Information-Technology Engineering Administration Research ; do echo "Working on Department $Dept" ; mkdir "$Dept" ; done Working on Department Human-Resources Working on Department Sales Working on Department Finance Working on Department Information-Technology Working on Department Engineering Working on Department Administration Working on Department Research [student@studentvm1 testdir]$ ll total 28 drwxrwxr-x 2 student student 4096 Apr 8 15:52 Administration drwxrwxr-x 2 student student 4096 Apr 8 15:52 Engineering drwxrwxr-x 2 student student 4096 Apr 8 15:52 Finance drwxrwxr-x 2 student student 4096 Apr 8 15:52 Human-Resources drwxrwxr-x 2 student student 4096 Apr 8 15:52 Information-Technology drwxrwxr-x 2 student student 4096 Apr 8 15:52 Research drwxrwxr-x 2 student student 4096 Apr 8 15:52 Sales ``` 假设现在有个需求,需要列出一台 Linux 机器上所有的 RPM 包并对每个包附上简短的描述。我为北卡罗来纳州工作的时候,曾经遇到过这种需求。由于当时开源尚未得到州政府的“批准”,而且我只在台式机上使用 Linux,对技术一窍不通的老板(PHB)需要我列出我计算机上安装的所有软件,以便他们可以“批准”一个特例。 你怎么实现它?有一种方法是,已知 `rpm –qa` 命令提供了 RPM 包的完整描述,包括了白痴老板想要的东西:软件名称和概要描述。 让我们一步步执行出最后的结果。首先,列出所有的 RPM 包: ``` [student@studentvm1 testdir]$ rpm -qa perl-HTTP-Message-6.18-3.fc29.noarch perl-IO-1.39-427.fc29.x86_64 perl-Math-Complex-1.59-429.fc29.noarch lua-5.3.5-2.fc29.x86_64 java-11-openjdk-headless-11.0.ea.28-2.fc29.x86_64 util-linux-2.32.1-1.fc29.x86_64 libreport-fedora-2.9.7-1.fc29.x86_64 rpcbind-1.2.5-0.fc29.x86_64 libsss_sudo-2.0.0-5.fc29.x86_64 libfontenc-1.1.3-9.fc29.x86_64 &lt;snip&gt; ``` 用 `sort` 和 `uniq` 命令对列表进行排序和打印去重后的结果(有些已安装的 RPM 包具有相同的名字): ``` [student@studentvm1 testdir]$ rpm -qa | sort | uniq a2ps-4.14-39.fc29.x86_64 aajohan-comfortaa-fonts-3.001-3.fc29.noarch abattis-cantarell-fonts-0.111-1.fc29.noarch abiword-3.0.2-13.fc29.x86_64 abrt-2.11.0-1.fc29.x86_64 abrt-addon-ccpp-2.11.0-1.fc29.x86_64 abrt-addon-coredump-helper-2.11.0-1.fc29.x86_64 abrt-addon-kerneloops-2.11.0-1.fc29.x86_64 abrt-addon-pstoreoops-2.11.0-1.fc29.x86_64 abrt-addon-vmcore-2.11.0-1.fc29.x86_64 &lt;snip&gt; ``` 以上命令得到了想要的 RPM 列表,因此你可以把这个列表作为一个循环的输入信息,循环最终会打印每个 RPM 包的详细信息: ``` [student@studentvm1 testdir]$ for RPM in `rpm -qa | sort | uniq` ; do rpm -qi $RPM ; done ``` 这段代码产出了多余的信息。当循环结束后,下一步就是提取出白痴老板需要的信息。因此,添加一个 `egrep` 命令用来搜索匹配 `^Name` 或 `^Summary` 的行。脱字符(`^`)表示行首,整个命令表示显示所有以 Name 或 Summary 开头的行。 ``` [student@studentvm1 testdir]$ for RPM in `rpm -qa | sort | uniq` ; do rpm -qi $RPM ; done | egrep -i "^Name|^Summary" Name : a2ps Summary : Converts text and other types of files to PostScript Name : aajohan-comfortaa-fonts Summary : Modern style true type font Name : abattis-cantarell-fonts Summary : Humanist sans serif font Name : abiword Summary : Word processing program Name : abrt Summary : Automatic bug detection and reporting tool &lt;snip&gt; ``` 在上面的命令中你可以试试用 `grep` 代替 `egrep` ,你会发现用 `grep` 不能得到正确的结果。你也可以通过管道把命令结果用 `less` 过滤器来查看。最终命令像这样: ``` [student@studentvm1 testdir]$ for RPM in `rpm -qa | sort | uniq` ; do rpm -qi $RPM ; done | egrep -i "^Name|^Summary" > RPM-summary.txt ``` 这个命令行程序用到了管道、重定向和 `for` 循环,这些全都在一行中。它把你的 CLI 程序的结果重定向到了一个文件,这个文件可以在邮件中使用或在其他地方作为输入使用。 这个一次一步构建程序的过程让你能看到每步的结果,以此来确保整个程序以你期望的流程进行且输出你想要的结果。 白痴老板最终收到了超过 1900 个不同的 RPM 包的清单,我严重怀疑根本就没人读过这个列表。我给了他们想要的东西,没有从他们嘴里听到过任何关于 RPM 包的信息。 ### 其他循环 Bash 中还有两种其他类型的循环结构:`while` 和 `until` 结构,两者在语法和功能上都类似。这些循环结构的基础语法很简单: ``` while [ expression ] ; do list ; done ``` 逻辑解释:表达式(`expression`)结果为 true 时,执行程序语句 `list`。表达式结果为 false 时,退出循环。 ``` until [ expression ] ; do list ; done ``` 逻辑解释:执行程序语句 `list`,直到表达式的结果为 true。当表达式结果为 true 时,退出循环。 #### While 循环 `while` 循环用于当逻辑表达式结果为 true 时执行一系列程序语句。假设你的 PWD 仍是 `~/testdir`。 最简单的 `while` 循环形式是这个会一直运行下去的循环。下面格式的条件语句永远以 `true` 作为返回。你也可以用简单的 `1` 代替 `true`,结果一样,但是这解释了 true 表达式的用法。 ``` [student@studentvm1 testdir]$ X=0 ; while [ true ] ; do echo $X ; X=$((X+1)) ; done | head 0 1 2 3 4 5 6 7 8 9 [student@studentvm1 testdir]$ ``` 既然你已经学了 CLI 的各部分知识,那就让它变得更有用处。首先,为了防止变量 `$X` 在前面的程序或 CLI 命令执行后有遗留的值,设置 `$X` 的值为 0。然后,因为逻辑表达式 `[ true ]` 的结果永远是 1,即 true,在 `do` 和 `done` 中间的程序指令列表会一直执行 — 或者直到你按下 `Ctrl+C` 抑或发送一个 2 号信号给程序。那些程序指令是算数扩展,用来打印变量 `$X` 当前的值并加 1. 《[系统管理员的 Linux 哲学](https://www.apress.com/us/book/9781484237298)》的信条之一是追求优雅,实现优雅的一种方式就是简化。你可以用操作符 `++` 来简化这个程序。在第一个例子中,变量当前的值被打印出来,然后变量的值增加了。可以在变量后加一个 `++` 来表示这个逻辑: ``` [student@studentvm1 ~]$ X=0 ; while [ true ] ; do echo $((X++)) ; done | head 0 1 2 3 4 5 6 7 8 9 ``` 现在删掉程序最后的 `| head` 再运行一次。 在下面这个版本中,变量在值被打印之前就自增了。这是通过在变量之前添加 `++` 操作符实现的。你能看出区别吗? ``` [student@studentvm1 ~]$ X=0 ; while [ true ] ; do echo $((++X)) ; done | head 1 2 3 4 5 6 7 8 9 ``` 你已经把打印变量的值和自增简化到了一条语句。类似 `++` 操作符,也有 `--` 操作符。 你需要一个在循环到某个特定数字时终止循环的方法。把 true 表达式换成一个数字比较表达式来实现它。这里有一个循环到 5 终止的程序。在下面的示例代码中,你可以看到 `-le` 是 “小于或等于” 的数字逻辑操作符。整个语句的意思:只要 `$X` 的值小于或等于 5,循环就一直运行。当 `$X` 增加到 6 时,循环终止。 ``` [student@studentvm1 ~]$ X=0 ; while [ $X -le 5 ] ; do echo $((X++)) ; done 0 1 2 3 4 5 [student@studentvm1 ~]$ ``` #### Until 循环 `until` 命令非常像 `while` 命令。不同之处是,它直到逻辑表达式的值是 `true` 之前,会一直循环。看一下这种结构最简单的格式: ``` [student@studentvm1 ~]$ X=0 ; until false ; do echo $((X++)) ; done | head 0 1 2 3 4 5 6 7 8 9 [student@studentvm1 ~]$ ``` 它用一个逻辑比较表达式来计数到一个特定的值: ``` [student@studentvm1 ~]$ X=0 ; until [ $X -eq 5 ] ; do echo $((X++)) ; done 0 1 2 3 4 [student@studentvm1 ~]$ X=0 ; until [ $X -eq 5 ] ; do echo $((++X)) ; done 1 2 3 4 5 [student@studentvm1 ~]$ ``` ### 总结 本系列探讨了构建 Bash 命令行程序和 shell 脚本的很多强大的工具。但是这仅仅是你能用 Bash 做的很多有意思的事中的冰山一角,接下来就看你的了。 我发现学习 Bash 编程最好的方法就是实践。找一个需要多个 Bash 命令的简单项目然后写一个 CLI 程序。系统管理员们要做很多适合 CLI 编程的工作,因此我确信你很容易能找到自动化的任务。 很多年前,尽管我对其他的 Shell 语言和 Perl 很熟悉,但还是决定用 Bash 做所有系统管理员的自动化任务。我发现,有时稍微搜索一下,我可以用 Bash 实现我需要的所有事情。 --- via: <https://opensource.com/article/19/10/programming-bash-loops> 作者:[David Both](https://opensource.com/users/dboth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Bash is a powerful programming language, one perfectly designed for use on the command line and in shell scripts. This three-part series, based on my [three-volume Linux self-study course](http://www.both.org/?page_id=1183), explores using Bash as a programming language on the command-line interface (CLI). The [first article](https://opensource.com/article/19/10/programming-bash-part-1) in this series explored some simple command-line programming with Bash, including using variables and control operators. The [second article](https://opensource.com/article/19/10/programming-bash-part-2) looked into the types of file, string, numeric, and miscellaneous logical operators that provide execution-flow control logic and different types of shell expansions in Bash. This third (and final) article examines the use of loops for performing various types of iterative operations and ways to control those loops. ## Loops Every programming language I have ever used has at least a couple types of loop structures that provide various capabilities to perform repetitive operations. I use the for loop quite often but I also find the while and until loops useful. ### for loops Bash's implementation of the **for** command is, in my opinion, a bit more flexible than most because it can handle non-numeric values; in contrast, for example, the standard C language **for** loop can deal only with numeric values. The basic structure of the Bash version of the **for** command is simple: `for Var in list1 ; do list2 ; done` This translates to: "For each value in list1, set the **$Var** to that value and then perform the program statements in list2 using that value; when all of the values in list1 have been used, it is finished, so exit the loop." The values in list1 can be a simple, explicit string of values, or they can be the result of a command substitution (described in the second article in the series). I use this construct frequently. To try it, ensure that **~/testdir** is still the present working directory (PWD). Clean up the directory, then look at a trivial example of the **for** loop starting with an explicit list of values. This list is a mix of alphanumeric values—but do not forget that all variables are strings and can be treated as such. ``` [student@studentvm1 testdir]$ rm * [student@studentvm1 testdir]$ for I in a b c d 1 2 3 4 ; do echo $I ; done a b c d 1 2 3 4 ``` Here is a bit more useful version with a more meaningful variable name: ``` [student@studentvm1 testdir]$ for Dept in "Human Resources" Sales Finance "Information Technology" Engineering Administration Research ; do echo "Department $Dept" ; done Department Human Resources Department Sales Department Finance Department Information Technology Department Engineering Department Administration Department Research ``` Make some directories (and show some progress information while doing so): ``` [student@studentvm1 testdir]$ for Dept in "Human Resources" Sales Finance "Information Technology" Engineering Administration Research ; do echo "Working on Department $Dept" ; mkdir "$Dept" ; done Working on Department Human Resources Working on Department Sales Working on Department Finance Working on Department Information Technology Working on Department Engineering Working on Department Administration Working on Department Research [student@studentvm1 testdir]$ ll total 28 drwxrwxr-x 2 student student 4096 Apr 8 15:45 Administration drwxrwxr-x 2 student student 4096 Apr 8 15:45 Engineering drwxrwxr-x 2 student student 4096 Apr 8 15:45 Finance drwxrwxr-x 2 student student 4096 Apr 8 15:45 'Human Resources' drwxrwxr-x 2 student student 4096 Apr 8 15:45 'Information Technology' drwxrwxr-x 2 student student 4096 Apr 8 15:45 Research drwxrwxr-x 2 student student 4096 Apr 8 15:45 Sales ``` The **$Dept** variable must be enclosed in quotes in the **mkdir** statement; otherwise, two-part department names (such as "Information Technology") will be treated as two separate departments. That highlights a best practice I like to follow: all file and directory names should be a single word. Although most modern operating systems can deal with spaces in names, it takes extra work for sysadmins to ensure that those special cases are considered in scripts and CLI programs. (They almost certainly should be considered, even if they're annoying because you never know what files you will have.) So, delete everything in **~/testdir**—again—and do this one more time: ``` [student@studentvm1 testdir]$ rm -rf * ; ll total 0 [student@studentvm1 testdir]$ for Dept in Human-Resources Sales Finance Information-Technology Engineering Administration Research ; do echo "Working on Department $Dept" ; mkdir "$Dept" ; done Working on Department Human-Resources Working on Department Sales Working on Department Finance Working on Department Information-Technology Working on Department Engineering Working on Department Administration Working on Department Research [student@studentvm1 testdir]$ ll total 28 drwxrwxr-x 2 student student 4096 Apr 8 15:52 Administration drwxrwxr-x 2 student student 4096 Apr 8 15:52 Engineering drwxrwxr-x 2 student student 4096 Apr 8 15:52 Finance drwxrwxr-x 2 student student 4096 Apr 8 15:52 Human-Resources drwxrwxr-x 2 student student 4096 Apr 8 15:52 Information-Technology drwxrwxr-x 2 student student 4096 Apr 8 15:52 Research drwxrwxr-x 2 student student 4096 Apr 8 15:52 Sales ``` Suppose someone asks for a list of all RPMs on a particular Linux computer and a short description of each. This happened to me when I worked for the State of North Carolina. Since open source was not "approved" for use by state agencies at that time, and I only used Linux on my desktop computer, the pointy-haired bosses (PHBs) needed a list of each piece of software that was installed on my computer so that they could "approve" an exception. How would you approach that? Here is one way, starting with the knowledge that the **rpm –qa** command provides a complete description of an RPM, including the two items the PHBs want: the software name and a brief summary. Build up to the final result one step at a time. First, list all RPMs: ``` [student@studentvm1 testdir]$ rpm -qa perl-HTTP-Message-6.18-3.fc29.noarch perl-IO-1.39-427.fc29.x86_64 perl-Math-Complex-1.59-429.fc29.noarch lua-5.3.5-2.fc29.x86_64 java-11-openjdk-headless-11.0.ea.28-2.fc29.x86_64 util-linux-2.32.1-1.fc29.x86_64 libreport-fedora-2.9.7-1.fc29.x86_64 rpcbind-1.2.5-0.fc29.x86_64 libsss_sudo-2.0.0-5.fc29.x86_64 libfontenc-1.1.3-9.fc29.x86_64 <snip> ``` Add the **sort** and **uniq** commands to sort the list and print the unique ones (since it's possible that some RPMs with identical names are installed): ``` [student@studentvm1 testdir]$ rpm -qa | sort | uniq a2ps-4.14-39.fc29.x86_64 aajohan-comfortaa-fonts-3.001-3.fc29.noarch abattis-cantarell-fonts-0.111-1.fc29.noarch abiword-3.0.2-13.fc29.x86_64 abrt-2.11.0-1.fc29.x86_64 abrt-addon-ccpp-2.11.0-1.fc29.x86_64 abrt-addon-coredump-helper-2.11.0-1.fc29.x86_64 abrt-addon-kerneloops-2.11.0-1.fc29.x86_64 abrt-addon-pstoreoops-2.11.0-1.fc29.x86_64 abrt-addon-vmcore-2.11.0-1.fc29.x86_64 <snip> ``` Since this gives the correct list of RPMs you want to look at, you can use this as the input list to a loop that will print all the details of each RPM: `[student@studentvm1 testdir]$ for RPM in `rpm -qa | sort | uniq` ; do rpm -qi $RPM ; done` This code produces way more data than you want. Note that the loop is complete. The next step is to extract only the information the PHBs requested. So, add an **egrep** command, which is used to select **^Name** or **^Summary**. The carat (**^**) specifies the beginning of the line; thus, any line with Name or Summary at the beginning of the line is displayed. ``` [student@studentvm1 testdir]$ for RPM in `rpm -qa | sort | uniq` ; do rpm -qi $RPM ; done | egrep -i "^Name|^Summary" Name : a2ps Summary : Converts text and other types of files to PostScript Name : aajohan-comfortaa-fonts Summary : Modern style true type font Name : abattis-cantarell-fonts Summary : Humanist sans serif font Name : abiword Summary : Word processing program Name : abrt Summary : Automatic bug detection and reporting tool <snip> ``` You can try **grep** instead of **egrep** in the command above, but it will not work. You could also pipe the output of this command through the **less** filter to explore the results. The final command sequence looks like this: `[student@studentvm1 testdir]$ for RPM in `rpm -qa | sort | uniq` ; do rpm -qi $RPM ; done | egrep -i "^Name|^Summary" > RPM-summary.txt` This command-line program uses pipelines, redirection, and a **for** loop—all on a single line. It redirects the output of your little CLI program to a file that can be used in an email or as input for other purposes. This process of building up the program one step at a time allows you to see the results of each step and ensure that it is working as you expect and provides the desired results. From this exercise, the PHBs received a list of over 1,900 separate RPM packages. I seriously doubt that anyone read that list. But I gave them exactly what they asked for, and I never heard another word from them about it. ## Other loops There are two more types of loop structures available in Bash: the **while** and **until** structures, which are very similar to each other in both syntax and function. The basic syntax of these loop structures is simple: `while [ expression ] ; do list ; done` and `until [ expression ] ; do list ; done` The logic of the first reads: "While the expression evaluates as true, execute the list of program statements. When the expression evaluates as false, exit from the loop." And the second: "Until the expression evaluates as true, execute the list of program statements. When the expression evaluates as true, exit from the loop." ### While loop The **while** loop is used to execute a series of program statements while (so long as) the logical expression evaluates as true. Your PWD should still be **~/testdir**. The simplest form of the **while** loop is one that runs forever. The following form uses the true statement to always generate a "true" return code. You could also use a simple "1"—and that would work just the same—but this illustrates the use of the true statement: ``` [student@studentvm1 testdir]$ X=0 ; while [ true ] ; do echo $X ; X=$((X+1)) ; done | head 0 1 2 3 4 5 6 7 8 9 [student@studentvm1 testdir]$ ``` This CLI program should make more sense now that you have studied its parts. First, it sets **$X** to zero in case it has a value left over from a previous program or CLI command. Then, since the logical expression **[ true ]** always evaluates to 1, which is true, the list of program instructions between **do** and **done** is executed forever—or until you press **Ctrl+C** or otherwise send a signal 2 to the program. Those instructions are an arithmetic expansion that prints the current value of **$X** and then increments it by one. One of the tenets of [ The Linux Philosophy for Sysadmins](https://www.apress.com/us/book/9781484237298) is to strive for elegance, and one way to achieve elegance is simplicity. You can simplify this program by using the variable increment operator, **++**. In the first instance, the current value of the variable is printed, and then the variable is incremented. This is indicated by placing the **++**operator after the variable: ``` [student@studentvm1 ~]$ X=0 ; while [ true ] ; do echo $((X++)) ; done | head 0 1 2 3 4 5 6 7 8 9 ``` Now delete **| head** from the end of the program and run it again. In this version, the variable is incremented before its value is printed. This is specified by placing the **++** operator before the variable. Can you see the difference? ``` [student@studentvm1 ~]$ X=0 ; while [ true ] ; do echo $((++X)) ; done | head 1 2 3 4 5 6 7 8 9 ``` You have reduced two statements into a single one that prints the value of the variable and increments that value. There is also a decrement operator, **--**. You need a method for stopping the loop at a specific number. To accomplish that, change the true expression to an actual numeric evaluation expression. Have the program loop to 5 and stop. In the example code below, you can see that **-le** is the logical numeric operator for "less than or equal to." This means: "So long as **$X** is less than or equal to 5, the loop will continue. When **$X** increments to 6, the loop terminates." ``` [student@studentvm1 ~]$ X=0 ; while [ $X -le 5 ] ; do echo $((X++)) ; done 0 1 2 3 4 5 [student@studentvm1 ~]$ ``` ### Until loop The **until** command is very much like the **while** command. The difference is that it will continue to loop until the logical expression evaluates to "true." Look at the simplest form of this construct: ``` [student@studentvm1 ~]$ X=0 ; until false ; do echo $((X++)) ; done | head 0 1 2 3 4 5 6 7 8 9 [student@studentvm1 ~]$ ``` It uses a logical comparison to count to a specific value: ``` [student@studentvm1 ~]$ X=0 ; until [ $X -eq 5 ] ; do echo $((X++)) ; done 0 1 2 3 4 [student@studentvm1 ~]$ X=0 ; until [ $X -eq 5 ] ; do echo $((++X)) ; done 1 2 3 4 5 [student@studentvm1 ~]$ ``` ## Summary This series has explored many powerful tools for building Bash command-line programs and shell scripts. But it has barely scratched the surface on the many interesting things you can do with Bash; the rest is up to you. I have discovered that the best way to learn Bash programming is to do it. Find a simple project that requires multiple Bash commands and make a CLI program out of them. Sysadmins do many tasks that lend themselves to CLI programming, so I am sure that you will easily find tasks to automate. Many years ago, despite being familiar with other shell languages and Perl, I made the decision to use Bash for all of my sysadmin automation tasks. I have discovered that—sometimes with a bit of searching—I have been able to use Bash to accomplish everything I need. ## 4 Comments
11,716
在 Fedora 中使用 Cockpit 创建虚拟机
https://fedoramagazine.org/create-virtual-machines-with-cockpit-in-fedora/
2019-12-26T11:39:22
[ "Cockpit", "虚拟机" ]
https://linux.cn/article-11716-1.html
![](/data/attachment/album/201912/26/113924y1f69u9zl1kzwnjk.jpg) 本文向你展示如何在 Fedora 31 上使用安装 Cockpit 所需软件来创建和管理虚拟机。Cockpit 是一个[交互式管理界面](https://cockpit-project.org/),可让你在任何受支持的 Web 浏览器上访问和管理系统。随着 [virt-manager 逐渐被废弃](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/8.0_release_notes/rhel-8_0_0_release#virtualization_4),鼓励用户使用 Cockpit 来替换它。 Cockpit 是一个正在活跃开发的项目,它有许多扩展其工作的插件。例如,其中一个是 “Machines”,它与 libvirtd 交互并允许用户创建和管理虚拟机。 ### 安装软件 先决所需软件是 `libvirt`、`cockpit` 和 `cockpit-machines`。要将它们安装在 Fedora 31 上,请在终端[使用 sudo](https://fedoramagazine.org/howto-use-sudo/) 运行以下命令: ``` $ sudo dnf install libvirt cockpit cockpit-machines ``` Cockpit 也在 “Headless Management” 软件包组中。该软件组对于仅通过网络访问的基于 Fedora 的服务器很有用。在这里,请使用以下命令进行安装: ``` $ sudo dnf groupinstall "Headless Management" ``` ### 设置 Cockpit 服务 安装了必要的软件包后,就该启用服务了。`libvirtd` 服务运行虚拟机,而 Cockpit 有一个激活的套接字服务,可让你访问 Web GUI: ``` $ sudo systemctl enable libvirtd --now $ sudo systemctl enable cockpit.socket --now ``` 这应该足以运行虚拟机并通过 Cockpit 对其进行管理。(可选)如果要从网络上的另一台设备访问并管理计算机,那么需要将该服务开放给网络。为此,请在防火墙配置中添加新规则: ``` $ sudo firewall-cmd --zone=public --add-service=cockpit --permanent $ sudo firewall-cmd --reload ``` 要确认服务正在运行并且没有发生任何问题,请检查服务的状态: ``` $ sudo systemctl status libvirtd $ sudo systemctl status cockpit.socket ``` 此时一切都应该正常工作。Cockpit Web GUI 应该可通过 <https://localhost:9090> 或 <https://127.0.0.1:9090> 访问。或者,在连接到同一网络的任何其他设备上的 Web 浏览器中输入本地网络 IP。(如果未设置 SSL 证书,那么可能需要允许来自浏览器的连接。) ### 创建和安装机器 使用系统的用户名和密码登录界面。你还可以选择是否允许在此会话中将密码用于管理任务。 选择 “Virtual Machines”,然后选择 “Create VM” 来创建一台新的虚拟机。控制台为你提供几个选项: * 使用 Cockpit 的内置库下载操作系统 * 使用系统上已下载的安装媒体 * 指向系统安装树的 URL * 通过 [PXE](https://en.wikipedia.org/wiki/Preboot_Execution_Environment) 协议通过网络引导媒体 输入所有必要的参数。然后选择 “Create” 启动新虚拟机。 此时,将出现一个图形控制台。大多数现代 Web 浏览器都允许你使用键盘和鼠标与 VM 控制台进行交互。现在,你可以完成安装并使用新的 VM,就像[过去通过 virt-manager](https://fedoramagazine.org/full-virtualization-system-on-fedora-workstation-30/) 一样。 *照片由 [Miguel Teixeira](https://flickr.com/photos/miguelteixeira/) 发布于 [Flickr](https://flickr.com/photos/miguelteixeira/2964851828/)(CC BY-SA 2.0)* --- via: <https://fedoramagazine.org/create-virtual-machines-with-cockpit-in-fedora/> 作者:[Karlis Kavacis](https://fedoramagazine.org/author/karlisk/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
This article shows you how to install the software you need to use Cockpit to create and manage virtual machines on Fedora 31. Cockpit is [an interactive admin interface](https://cockpit-project.org/) that lets you access and manage systems from any supported web browser. With [virt-manager being deprecated](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/8.0_release_notes/rhel-8_0_0_release#virtualization_4) users are encouraged to use Cockpit instead, which is meant to replace it. Cockpit is an actively developed project, with many plugins available that extend how it works. For example, one such plugin is “Machines,” which interacts with libvirtd and lets users create and manage virtual machines. ## Installing software The required software prerequisites are *libvirt*, *cockpit* and *cockpit-machines*. To install them on Fedora 31, run the following command from a terminal [using sudo](https://fedoramagazine.org/howto-use-sudo/): $ sudo dnf install libvirt cockpit cockpit-machines Cockpit is also included as part of the “Headless Management” package group. This group is useful for a Fedora based server that you only access through a network. In that case, to install it, use this command: $ sudo dnf groupinstall "Headless Management" ## Setting up Cockpit services After installing the necessary packages it’s time to enable the services. The *libvirtd* service runs the virtual machines, while Cockpit has a socket activated service to let you access the Web GUI: $ sudo systemctl enable libvirtd --now $ sudo systemctl enable cockpit.socket --now This should be enough to run virtual machines and manage them through Cockpit. Optionally, if you want to access and manage your machine from another device on your network, you need to expose the service to the network. To do this, add a new rule in your firewall configuration: $ sudo firewall-cmd --zone=public --add-service=cockpit --permanent $ sudo firewall-cmd --reload To confirm the services are running and no issues occurred, check the status of the services: $ sudo systemctl status libvirtd $ sudo systemctl status cockpit.socket At this point everything should be working. The Cockpit web GUI should be available at [https://localhost:9090](https://localhost:9090) or [https://127.0.0.1:9090](https://127.0.0.1:9090). Or, enter the local network IP in a web browser on any other device connected to the same network. (Without SSL certificates setup, you may need to allow a connection from your browser.) ## Creating and installing a machine Log into the interface using the user name and password for that system. You can also choose whether to allow your password to be used for administrative tasks in this session. Select *Virtual Machines* and then select *Create VM* to build a new box. The console gives you several options: - Download an OS using Cockpit’s built in library - Use install media already downloaded on the system you’re managing - Point to a URL for an OS installation tree - Boot media over the network via the [PXE](https://en.wikipedia.org/wiki/Preboot_Execution_Environment)protocol Enter all the necessary parameters. Then select *Create* to power up the new virtual machine. At this point, a graphical console appears. Most modern web browsers let you use your keyboard and mouse to interact with the VM console. Now you can complete your installation and use your new VM, just as you would [via virt-manager in the past](https://fedoramagazine.org/full-virtualization-system-on-fedora-workstation-30/). *Photo by Miguel Teixeira on Flickr (CC BY-SA 2.0).* ## Lucas The software is great and is very easy to use. What if my computer does not support virtualization technology at all ? because i tried to install and setting up new machine in my fedora 30 and it gave me an error. ## Karlis Kavacis It is possible that your computer simply does not permit running Virtual Machines, you can check the BIOS settings to see if virtualization is simply disabled and enable it. If you have an Intel based system the configuration related to Virtualization will be called something like “Intel VT-d” or “Enable Intel Virtualization”. On AMD systems it will be called something like “AMD-V” or just “Enable Virtualization”. In either case the configuration to enable/disable virtualization usually can be found under CPU settings or under Advanced settings in BIOS – the exact procedure to access BIOS settings or how Virtualization settings are named in BIOS differs between different manufacturers, so it’s best to consult the user manual. Additionally, if you’re sure Virtualization is enabled in BIOS, you can check if the system meets the requirements by running: “virt-host-validate” (comes with libvirt and should already be available). ## RaphGro You should also take a look into Ravada VDI. We’ve it as a package in Fedora called ravada. https://ravada.readthedocs.io/en/latest/ ## OppaErich Well, that failed fast. I’ve tried to setup a VM for FreeDOS but it does not start. There’s a red ‘OOPS’ and no VM. No VM is running or defined on this host ## OppaErich Hi, I can’t edit so I add another. Another try discovered a permission denied on the ISO. [oppa@oppa-labor ~]$ ls -l ~/Downloads/FD12CD.iso -rw-rw-r–. 1 root root 438777856 28. Nov 16:43 /home/oppa/Downloads/FD12CD.iso WTH? Why is this owned by root? Do I become root in Chrome by using this Cockpit thing? This is scary, I’ll stop using Cockpit. ## Karlis Kavacis Normally, no – Chrome doesn’t run as root when accessing Cockpit, however, tasks executed while authenticated in Cockpit and with the checkbox “Reuse my password for privileged tasks” will be run as elevated. You can try setting the ownership of the ISO media to “qemu:qemu” (“sudo chown qemu:qemu INSTALLATION.iso”) and see if that resolves the issue. If that wasn’t enough, SE Linux might have restricted Libvirt to access the installation ISO – you can set the context with “sudo chcon system_u:object_r:virt_content_t:s0 INSTALLATION.iso”. ## Stephen Gallagher SELinux requires that the ISO have the context virt_image_t set on it or it won’t read it. So try ## David I don’t understand why virt-manager is being deprecated. Cockpit seems to be very limited in functionality compared to virt-manager. In Cockpit, I cannot even select UEFI instead of BIOS for the virtual machine, virtio-scsi controller, enable discard unmap feature etc. ## Karlis Kavacis Personally, I agree – at this moment virt-manager does offer more configuration available in GUI than Cockpit. At the same time, you still have access to virsh – the commandline interface that allows for more complex configurations than either in Cockpit or virt-manager. Switching over to Cockpit was a change that was made by Red Hat, I’m sure there was a good reason for it. In the meantime, Cockpit is a constantly evolving project – new features are added all the time. And I’m sure virt-manager won’t stop functioning or disappear from the repositories anytime soon or before the same functionality has been introduced in Cockpit. You can head over to GitHub and follow the progress of development and take part in improving it – https://github.com/cockpit-project/cockpit ## Stephen Gallagher First, I’ll note that “deprecated” is not the same as “removed”. virt-manager is still available as part of the libvirt upstream. The main reason I expect it’s being replaced by Cockpit is so that users are not required to have a Linux workstation system around just to manage their VMs. The virt-manager tool requires a full graphical environment in which to run, whereas Cockpit can run in any modern web browser. ## Bryce Hardy I get an error message saying: “ERROR authentication failed: access denied by policy” ## Rudolph Might have to add your user to the libvirt group? ## dtw I just tried cockpit and I can see how it replaces virt-manager for creating, starting and stopping VMs. What I don’t understand is how I access the VM itself from cockpit? Is the assumption that we only run headless VMs? ## Eddie Jennings I know I’ve had Cockpit work in the past (and it was a pretty slick interface). I’m currently working on trying to figure why my Fedora 31 server’s resetting TCP connections when I try to connect to Cockpit using Firefox. ## Eddie Jennings Update: Looks like what I’m not alone with what I experienced with Fedora 31. Here’s a bug report that describes the exact problem. https://bugzilla.redhat.com/show_bug.cgi?id=1775489 ## Severo Acevedo How to work it on Fedora SilverBlue?
11,717
使用 Java 持久化 API
https://opensource.com/article/19/10/using-java-persistence-api
2019-12-27T00:07:34
[ "Java" ]
https://linux.cn/article-11717-1.html
> > 我们通过为自行车商店构建示例应用程序来学习如何使用 JPA。 > > > ![](/data/attachment/album/201912/27/000705dymv92hnba2a2322.jpg) 对应用开发者来说,<ruby> Java 持久化 API <rt> Java Persistence API </rt></ruby>(JPA)是一项重要的 java 功能,需要透彻理解。它为 Java 开发人员定义了如何将对象的方法调用转换为访问、持久化及管理存储在 NoSQL 和关系型数据库中的数据的方案。 本文通过构建自行车借贷服务的教程示例来详细研究 JPA。此示例会使用 Spring Boot 框架、MongoDB 数据库([已经不开源](https://www.techrepublic.com/article/mongodb-ceo-tells-hard-truths-about-commercial-open-source/))和 Maven 包管理来构建一个大型应用程序,并且构建一个创建、读取、更新和删除(CRUD)层。这儿我选择 NetBeans 11 作为我的 IDE。 此教程仅从开源的角度来介绍 Java 持久化 API 的工作原理,不涉及其作为工具的使用说明。这全是关于编写应用程序模式的学习,但对于理解具体的软件实现也很益处。可以从我的 [GitHub 仓库](https://github.com/StephonBrown/SpringMongoJava)来获取相关代码。 ### Java: 不仅仅是“豆子” Java 是一门面向对象的编程语言,自 1996 年发布第一版 Java 开发工具(JDK)起,已经变化了很多很多。要了解其各种发展及其虚拟机本身就是一堂历史课。简而言之,和 Linux 内核很相似,自发布以来,该语言已经向多个方向分支发展。有对社区免费的标准版本、有针对企业的企业版本及由多家供应商提供的开源替代品。主要版本每六个月发布一次,其功能往往差异很大,所以确认选用版本前得先做些研究。 总而言之,Java 的历史很悠久。本教程重点介绍 Java 11 的开源实现 [JDK 11](https://openjdk.java.net/projects/jdk/11/)。因其是仍然有效的长期支持版本之一。 * **Spring Boot** 是由 Pivotal 公司开发的大型 Spring 框架的一个模块。Spring 是 Java 开发中一个非常流行的框架。它支持各种框架和配置,也为 WEB 应用程序及安全提供了保障。Spring Boot 为快速构建各种类型的 Java 项目提供了基本的配置。本教程使用 Spring Boot 来快速编写控制台应用程序并针对数据库编写测试用例。 * **Maven** 是由 Apache 开发的项目/包管理工具。Maven 通过 `POM.xml` 文件来管理包及其依赖项。如果你使用过 NPM 的话,可能会非常熟悉包管理器的功能。此外 Maven 也用来进行项目构建及生成功能报告。 * **Lombok** 是一个库,它通过在对象文件里面添加注解来自动创建 getters/setters 方法。像 C# 这些语言已经实现了此功能,Lombok 只是把此功能引入 Java 语言而已。 * **NetBeans** 是一款很流行的开源 IDE,专门用于 Java 开发。它的许多工具都随着 Java SE 和 EE 的版本更新而更新。 我们会用这组工具为一个虚构自行车商店创建一个简单的应用程序。会实现对 `Customer` 和 `Bike` 对象集合的的插入操作。 ### 酿造完美 导航到 [Spring Initializr](https://start.spring.io/) 页面。该网站可以生成基于 Spring Boot 和其依赖项的基本项目。选择以下选项: 1. **项目:** Maven 工程 2. **语言:** Java 3. **Spring Boot:** 2.1.8(或最稳定版本) 4. **项目元数据:** 无论你使用什么名字,其命名约定都是像 `com.stephb` 这样的。 * 你可以保留 Artifact 名字为 “Demo”。 5. **依赖项:** 添加: * Spring Data MongoDB * Lombok 点击 **下载**,然后用你的 IDE(例如 NetBeans) 打开此新项目。 #### 模型层概要 在项目里面,<ruby> 模型 <rt> model </rt></ruby>代表从数据库里取出的信息的具体对象。我们关注两个对象:`Customer` 和 `Bike`。首先,在 `src` 目录创建 `dto` 目录;然后,创建两个名为 `Customer.java` 和 `Bike.java` 的 Java 类对象文件。其结构如下示: ``` package com.stephb.JavaMongo.dto; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.Id; /** * * @author stephon */ @Getter @Setter public class Customer { private @Id String id; private String emailAddress; private String firstName; private String lastName; private String address; } ``` *Customer.Java* ``` package com.stephb.JavaMongo.dto; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.Id; /** * * @author stephon */ @Getter @Setter public class Bike { private @Id String id; private String modelNumber; private String color; private String description; @Override public String toString() { return "This bike model is " + this.modelNumber + " is the color " + this.color + " and is " + description; } } ``` *Bike.java* 如你所见,对象中使用 Lombok 注解来为定义的<ruby> 属性 <rt> properties </rt></ruby>/<ruby> 特性 <rt> attributes </rt></ruby>生成 getters/setters 方法。如果你不想对该类的所有特性都生成 getters/setters 方法,可以在属性上专门定义这些注解。这两个类会变成容器,里面携带有数据,无论在何处想显示信息都可以使用。 #### 配置数据库 我使用 [Mongo Docker](https://hub.docker.com/_/mongo) 容器来进行此次测试。如果你的系统上已经安装了 MongoDB,则不必运行 Docker 实例。你也可以登录其官网,选择系统信息,然后按照安装说明来安装 MongoDB。 安装后,就可以使用命令行、GUI(例如 MongoDB Compass)或用于连接数据源的 IDE 驱动程序来与新的 MongoDB 服务器进行交互。到目前为止,可以开始定义数据层了,用来拉取、转换和持久化数据。需要设置数据库访问属性,请导航到程序中的 `applications.properties` 文件,然后添加如下内容: ``` spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=BikeStore ``` #### 定义数据访问对象/数据访问层 <ruby> 数据访问层 <rt> data access layer </rt></ruby>(DAL)中的<ruby> 数据访问对象 <rt> data access objects </rt></ruby>(DAO)定义了与数据库中的数据的交互过程。令人惊叹的就是在使用 `spring-boot-starter` 后,查询数据库的大部分工作已经完成。 让我们从 `Customer` DAO 开始。在 `src` 下的新目录 `dao` 中创建一个接口文件,然后再创建一个名为 `CustomerRepository.java` 的 Java 类文件,其内容如下示: ``` package com.stephb.JavaMongo.dao; import com.stephb.JavaMongo.dto.Customer; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; /** * * @author stephon */ public interface CustomerRepository extends MongoRepository<Customer, String>{ @Override public List<Customer> findAll(); public List<Customer> findByFirstName(String firstName); public List<Customer> findByLastName(String lastName); } ``` 这个类是一个接口,扩展或继承于 `MongoRepository` 类,而 `MongoRepository` 类依赖于 DTO (`Customer.java`)和一个字符串,它们用来实现自定义函数查询功能。因为你已继承自此类,所以你可以访问许多方法函数,这些函数允许持久化和查询对象,而无需实现或引用自己定义的方法函数。例如,在实例化 `CustomerRepository` 对象后,你就可以直接使用 `Save` 函数。如果你需要扩展更多的功能,也可以重写这些函数。我创建了一些自定义查询来搜索我的集合,这些集合对象是我自定义的元素。 `Bike` 对象也有一个存储源负责与数据库交互。与 `CustomerRepository` 的实现非常类似。其实现如下所示: ``` package com.stephb.JavaMongo.dao; import com.stephb.JavaMongo.dto.Bike; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; /** * * @author stephon */ public interface BikeRepository extends MongoRepository<Bike,String>{ public Bike findByModelNumber(String modelNumber); @Override public List<Bike> findAll(); public List<Bike> findByColor(String color); } ``` #### 运行程序 现在,你已经有了一种结构化数据的方式,可以对数据进行提取、转换和持久化,然后运行这个程序。 找到 `Application.java` 文件(有可能不是此名称,具体取决于你的应用程序名称,但都会包含有 “application” )。在定义此类的地方,在后面加上 `implements CommandLineRunner`。这将允许你实现 `run` 方法来创建命令行应用程序。重写 `CommandLineRunner` 接口提供的 `run` 方法,并包含如下内容用来测试 `BikeRepository` : ``` package com.stephb.JavaMongo; import com.stephb.JavaMongo.dao.BikeRepository; import com.stephb.JavaMongo.dao.CustomerRepository; import com.stephb.JavaMongo.dto.Bike; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JavaMongoApplication implements CommandLineRunner { @Autowired private BikeRepository bikeRepo; private CustomerRepository custRepo; public static void main(String[] args) { SpringApplication.run(JavaMongoApplication.class, args); } @Override public void run(String... args) throws Exception { Scanner scan = new Scanner(System.in); String response = ""; boolean running = true; while(running){ System.out.println("What would you like to create? \n C: The Customer \n B: Bike? \n X:Close"); response = scan.nextLine(); if ("B".equals(response.toUpperCase())) { String[] bikeInformation = new String[3]; System.out.println("Enter the information for the Bike"); System.out.println("Model Number"); bikeInformation[0] = scan.nextLine(); System.out.println("Color"); bikeInformation[1] = scan.nextLine(); System.out.println("Description"); bikeInformation[2] = scan.nextLine(); Bike bike = new Bike(); bike.setModelNumber(bikeInformation[0]); bike.setColor(bikeInformation[1]); bike.setDescription(bikeInformation[2]); bike = bikeRepo.save(bike); System.out.println(bike.toString()); } else if ("X".equals(response.toUpperCase())) { System.out.println("Bye"); running = false; } else { System.out.println("Sorry nothing else works right now!"); } } } } ``` 其中的 `@Autowired` 注解会自动依赖注入 `BikeRepository` 和 `CustomerRepository` Bean。我们将使用这些类来从数据库持久化和采集数据。 已经好了。你已经创建了一个命令行应用程序。该应用程序连接到数据库,并且能够以最少的代码执行 CRUD 操作 ### 结论 从诸如对象和类之类的编程语言概念转换为用于在数据库中存储、检索或更改数据的调用对于构建应用程序至关重要。Java 持久化 API(JPA)正是为 Java 开发人员解决这一难题的重要工具。你正在使用 Java 操纵哪些数据库呢?请在评论中分享。 --- via: <https://opensource.com/article/19/10/using-java-persistence-api> 作者:[Stephon Brown](https://opensource.com/users/stephb) 选题:[lujun9972](https://github.com/lujun9972) 译者:[runningwater](https://github.com/runningwater) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The Java Persistence API (JPA) is an important Java functionality for application developers to understand. It translates exactly how Java developers turn method calls on objects into accessing, persisting, and managing data stored in NoSQL and relational databases. This article examines the JPA in detail through a tutorial example of building a bicycle loaning service. This example will create a create, read, update, and delete (CRUD) layer for a larger application using the Spring Boot framework, the MongoDB database (which is [no longer open source](https://www.techrepublic.com/article/mongodb-ceo-tells-hard-truths-about-commercial-open-source/)), and the Maven package manager. I also use NetBeans 11 as my IDE of choice. This tutorial focuses on the open source angle of the Java Persistence API, rather than the tools, to show how it works. This is all about learning the pattern of programming applications, but it's still smart to understand the software. You can access the full code in my [GitHub repository](https://github.com/StephonBrown/SpringMongoJava). ## Java: More than 'beans' Java is an object-oriented language that has gone through many changes since the Java Development Kit (JDK) was released in 1996. Understanding the language's various pathways and its virtual machine is a history lesson in itself; in brief, the language has forked in many directions, similar to the Linux kernel, since its release. There are standard editions that are free to the community, enterprise editions for business, and an open source alternatives contributed to by multiple vendors. Major versions are released at six-month intervals; since there are often major differences in features, you may want to do some research before choosing a version. All and all, Java is steeped in history. This tutorial focuses on [JDK 11](https://openjdk.java.net/projects/jdk/11/), which is the open source implementation of Java 11, because it is one of the long-term-support versions that is still active. **Spring Boot:**Spring Boot is a module from the larger Spring framework developed by Pivotal. Spring is a very popular framework for working with Java. It allows for a variety of architectures and configurations. Spring also offers support for web applications and security. Spring Boot offers basic configurations for bootstrapping various types of Java projects quickly. This tutorial uses Spring Boot to quickly write a console application and test functionality against the database.**Maven:**Maven is a project/package manager developed by Apache. Maven allows for the management of packages and various dependencies within its POM.xml file. If you have used NPM, you may be familiar with how package managers function. Maven also manages build and reporting functionality.**Lombok:**Lombok is a library that allows the creation of object getters/setters through annotation within the object file. This is already present in languages like C#, and Lombok introduces this functionality into Java.**NetBeans:**NetBeans is a popular open source IDE that focuses specifically on Java development. Many of its tools provide an implementation for the latest Java SE and EE updates. This group of tools will be used to create a simple application for a fictional bike store. It will implement functionality for inserting collections for "Customer" and "Bike" objects. ## Brewed to perfection Navigate to the [Spring Initializr](https://start.spring.io/). This website enables you to generate basic project needs for Spring Boot and the dependencies you will need for the project. Select the following options: **Project:**Maven Project**Language:**Java**Spring Boot:**2.1.8 (or the most stable release)**Project Metadata:**Whatever your naming conventions are (e.g.,**com.stephb**)- You can keep Artifact as "Demo" **Dependencies:**Add:- Spring Data MongoDB - Lombok Click **Download** and open the new project in your chosen IDE (e.g., NetBeans). ### Model outline The models represent information collected about specific objects in the program that will be persisted in your database. Focus on two objects: **Customer** and **Bike**. First, create a **dto** folder within the **src** folder. Then, create the two Java class objects named **Customer.java** and **Bike.java**. They will be structured in the program as follows: **Customer. Java** ``` 1 package com.stephb.JavaMongo.dto; 2 3 import lombok.Getter; 4 import lombok.Setter; 5 import org.springframework.data.annotation.Id; 6 7 /** 8 * 9 * @author stephon 10 */ 11 @Getter @Setter 12 public class Customer { 13 14 private @Id String id; 15 private String emailAddress; 16 private String firstName; 17 private String lastName; 18 private String address; 19 20 } ``` **Bike.java** ``` 1 package com.stephb.JavaMongo.dto; 2 3 import lombok.Getter; 4 import lombok.Setter; 5 import org.springframework.data.annotation.Id; 6 7 /** 8 * 9 * @author stephon 10 */ 11 @Getter @Setter 12 public class Bike { 13 private @Id String id; 14 private String modelNumber; 15 private String color; 16 private String description; 17 18 @Override 19 public String toString() { 20 return "This bike model is " + this.modelNumber + " is the color " + this.color + " and is " + description; 21 } 22 } ``` As you can see, Lombok annotation is used within the object to generate the getters/setters for the properties/attributes. Properties can specifically receive the annotations if you do not want all of the attributes to have getters/setters within that class. These two classes will form the container carrying your data to wherever you want to display information. ### Set up a database I used a [Mongo Docker](https://hub.docker.com/_/mongo) container for testing. If you have MongoDB installed on your system, you do not have to run an instance in Docker. You can install MongoDB from its website by selecting your system information and following the installation instructions. After installing, you can interact with your new MongoDB server through the command line, a GUI such as MongoDB Compass, or IDE drivers for connecting to data sources. Now you can define your data layer to pull, transform, and persist your data. To set your database access properties, navigate to the **applications.properties** file in your application and provide the following: ``` 1 spring.data.mongodb.host=localhost 2 spring.data.mongodb.port=27017 3 spring.data.mongodb.database=BikeStore ``` ### Define the data access object/data access layer The data access objects (DAO) in the data access layer (DAL) will define how you will interact with data in the database. The awesome thing about using a **spring-boot-starter** is that most of the work for querying the database is already done. Start with the **Customer** DAO. Create an interface in a new **dao** folder within the **src** folder, then create another Java class name called **CustomerRepository.java**. The class should look like: ``` 1 package com.stephb.JavaMongo.dao; 2 3 import com.stephb.JavaMongo.dto.Customer; 4 import java.util.List; 5 import org.springframework.data.mongodb.repository.MongoRepository; 6 7 /** 8 * 9 * @author stephon 10 */ 11 public interface CustomerRepository extends MongoRepository<Customer, String>{ 12 @Override 13 public List<Customer> findAll(); 14 public List<Customer> findByFirstName(String firstName); 15 public List<Customer> findByLastName(String lastName); 16 } ``` This class is an interface that extends or inherits from the **MongoRepository** class with your DTO (**Customer.java**) and a string because they will be used for querying with your custom functions. Because you have inherited from this class, you have access to many functions that allow persistence and querying of your object without having to implement or reference your own functions. For example, after you instantiate the **CustomerRepository** object, you can use the **Save** function immediately. You can also override these functions if you need more extended functionality. I created a few custom queries to search my collection, given specific elements of my object. The **Bike** object also has a repository for interacting with the database. Implement it very similarly to the **CustomerRepository**. It should look like: ``` 1 package com.stephb.JavaMongo.dao; 2 3 import com.stephb.JavaMongo.dto.Bike; 4 import java.util.List; 5 import org.springframework.data.mongodb.repository.MongoRepository; 6 7 /** 8 * 9 * @author stephon 10 */ 11 public interface BikeRepository extends MongoRepository<Bike,String>{ 12 public Bike findByModelNumber(String modelNumber); 13 @Override 14 public List<Bike> findAll(); 15 public List<Bike> findByColor(String color); 16 } ``` ### Run your program Now that you have a way to structure your data and a way to pull, transform, and persist it, run your program! Navigate to your **Application.java** file (it may have a different name, depending on what you named your application, but it should include "application"). Where the class is defined, include an **implements CommandLineRunner** afterward. This will allow you to implement a **run** method to create a command-line application. Override the **run** method provided by the **CommandLineRunner** interface and include the following to test the **BikeRepository**: ``` 1 package com.stephb.JavaMongo; 2 3 import com.stephb.JavaMongo.dao.BikeRepository; 4 import com.stephb.JavaMongo.dao.CustomerRepository; 5 import com.stephb.JavaMongo.dto.Bike; 6 import java.util.Scanner; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.boot.CommandLineRunner; 9 import org.springframework.boot.SpringApplication; 10 import org.springframework.boot.autoconfigure.SpringBootApplication; 11 12 13 @SpringBootApplication 14 public class JavaMongoApplication implements CommandLineRunner { 15 @Autowired 16 private BikeRepository bikeRepo; 17 private CustomerRepository custRepo; 18 19 public static void main(String[] args) { 20 SpringApplication.run(JavaMongoApplication.class, args); 21 } 22 @Override 23 public void run(String... args) throws Exception { 24 Scanner scan = new Scanner(System.in); 25 String response = ""; 26 boolean running = true; 27 while(running){ 28 System.out.println("What would you like to create? \n C: The Customer \n B: Bike? \n X:Close"); 29 response = scan.nextLine(); 30 if ("B".equals(response.toUpperCase())) { 31 String[] bikeInformation = new String[3]; 32 System.out.println("Enter the information for the Bike"); 33 System.out.println("Model Number"); 34 bikeInformation[0] = scan.nextLine(); 35 System.out.println("Color"); 36 bikeInformation[1] = scan.nextLine(); 37 System.out.println("Description"); 38 bikeInformation[2] = scan.nextLine(); 39 40 Bike bike = new Bike(); 41 bike.setModelNumber(bikeInformation[0]); 42 bike.setColor(bikeInformation[1]); 43 bike.setDescription(bikeInformation[2]); 44 45 bike = bikeRepo.save(bike); 46 System.out.println(bike.toString()); 47 48 49 } else if ("X".equals(response.toUpperCase())) { 50 System.out.println("Bye"); 51 running = false; 52 } else { 53 System.out.println("Sorry nothing else works right now!"); 54 } 55 } 56 57 } 58 } ``` The **@Autowired** annotation allows automatic dependency injection of the **BikeRepository** and **CustomerRepository** beans. You will use these classes to persist and gather data from the database. There you have it! You have created a command-line application that connects to a database and is able to perform CRUD operations with minimal code on your part. ## Conclusion Translating from programming language concepts like objects and classes into calls to store, retrieve, or change data in a database is essential to building an application. The Java Persistence API (JPA) is an important tool in the Java developer's toolkit to solve that challenge. What databases are you exploring in Java? Please share in the comments. ## Comments are closed.
11,718
为什么 Python 代码要写得美观而明确
https://opensource.com/article/19/12/zen-python-beauty-clarity
2019-12-27T09:17:00
[ "Python" ]
https://linux.cn/article-11718-1.html
> > 欢迎阅读“Python 光明节(Pythonukkah)”系列文章,这个系列文章将会讨论《Python 之禅》。我们首先来看《Python 之禅》里的前两个原则:美观与明确。 > > > ![](/data/attachment/album/201912/27/091634drq96c2fojzp6okr.png) 早在 1999 年,Python 的贡献者之一,Tim Peters 就提出了《[Python 之禅](https://www.python.org/dev/peps/pep-0020/)》,直到二十年后的今天,《Python 之禅》中的 19 条原则仍然对整个社区都产生着深远的影响。为此,就像庆典光明的<ruby> 光明节 <rt> Hanukkah </rt></ruby>一样,我们举行了这一次的“<ruby> Python 光明节 <rt> Pythonukkah </rt></ruby>”。首先,我们会讨论《Python 之禅》中的前两个原则:美观和明确。 > > “Hanukkah is the Festival of Lights, > > > Instead of one day of presents, we get eight crazy nights.” > > > —亚当·桑德勒,[光明节之歌](https://en.wikipedia.org/wiki/The_Chanukah_Song) > > > ### <ruby> 美观胜于丑陋 <rp> ( </rp> <rt> Beautiful is better than ugly </rt> <rp> ) </rp></ruby> 著名的《[<ruby> 计算机程序的构造和解释 <rt> Structure and Interpretation of Computer Programs </rt></ruby>](https://en.wikipedia.org/wiki/Structure_and_Interpretation_of_Computer_Programs)》中有这么一句话:<ruby> 代码是写给人看的,只是恰好能让机器运行。 <rt> Programs must be written for people to read and only incidentally for machines to execute. </rt></ruby>机器并不在乎代码的美观性,但人类在乎。 阅读美观的代码对人们来说是一种享受,这就要求在整套代码中保持一致的风格。使用诸如 [Black](https://opensource.com/article/19/5/python-black)、[flake8](https://opensource.com/article/19/5/python-flake8)、[Pylint](https://opensource.com/article/19/10/python-pylint-introduction) 这一类工具能够有效地接近这一个目标。 但实际上,只有人类自己才知道什么才是真正的美观。因此,代码审查和协同开发是其中的不二法门,同时,在开发过程中倾听别人的意见也是必不可少的。 最后,个人的主观能动性也很重要,否则一切工具和流程都会变得毫无意义。只有意识到美观的重要性,才能主动编写出美观的代码。 这就是为什么美观在众多原则当中排到了首位,它让“美”成为了 Python 社区的一种价值。如果有人要问,”我们*真的*在乎美吗?“社区会以代码给出肯定的答案。 ### <ruby> 明确胜于隐晦 <rp> ( </rp> <rt> Explicit is better than implicit </rt> <rp> ) </rp></ruby> 人类会欢庆光明、惧怕黑暗,那是因为光能够让我们看到难以看清的事物。同样地,尽管有些时候我们会不自觉地把代码写得含糊不清,但明确地编写代码确实能够让我们理解很多抽象的概念。 “为什么类方法中要将 `self` 显式指定为第一个参数?” 这个问题已经是老生常谈了,但网络上很多流传已久的回答都是不准确的。在编写<ruby> 元类 <rt> metaclass </rt></ruby>时,显式指定 `self` 参数就显得毫无意义。如果你没有编写过元类,希望你可以尝试一下,这是很多 Python 程序员的必经之路。 显式指定 `self` 参数的原因并不是 Python 的设计者不想将这样的元类视为“默认”元类,而是因为第一个参数必须是*显式*的。 即使 Python 中确实允许非显式的情况存在(例如上下文变量),但我们还是应该提出疑问:某个东西是不是有存在的必要呢?如果非显式地传递参数会不会出现问题呢?有些时候,由于种种原因,这是会有问题的。总之,在写代码时一旦能够优先考虑到明确性,至少意味着能对不明确的地方提出疑问并对结果作出有效的估计。 --- via: <https://opensource.com/article/19/12/zen-python-beauty-clarity> 作者:[Moshe Zadka](https://opensource.com/users/moshez) 选题:[lujun9972](https://github.com/lujun9972) 译者:[HankChow](https://github.com/HankChow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Python contributor Tim Peters introduced us to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/) in 1999. Twenty years later, its 19 guiding principles continue to be relevant within the community. We start our Pythonukkah celebration—like Hanukkah, a festival of lights—with the first two principles in the Zen of Python: on beauty and explicitness. "Hanukkah is the Festival of Lights, Instead of one day of presents, we get eight crazy nights." —Adam Sandler,The Hanukkah Song ## Beautiful is better than ugly. It was in * Structure and Interpretation of Computer Programs* ( *SICP*) that the point was made: "Programs must be written for people to read and only incidentally for machines to execute." Machines do not care about beauty, but people do. A beautiful program is one that is enjoyable to read. This means first that it is consistent. Tools like [Black](https://opensource.com/article/19/5/python-black), [flake8](https://opensource.com/article/19/5/python-flake8), and [Pylint](https://opensource.com/article/19/10/python-pylint-introduction) are great for making sure things are reasonable on a surface layer. But even more important, only humans can judge what humans find beautiful. Code reviews and a collaborative approach to writing code are the only realistic way to build beautiful code. Listening to other people is an important skill in software development. Finally, all the tools and processes are moot if the *will* is not there. Without an appreciation for the importance of beauty, there will never be an emphasis on writing beautiful code. This is why this is the first principle: it is a way of making "beauty" a value in the Python community. It immediately answers: "Do we *really* care about beauty?" We do. ## Explicit is better than implicit. We humans celebrate light and fear the dark. Light helps us make sense of vague images. In the same way, programming with more explicitness helps us make sense of abstract ideas. It is often tempting to make things implicit. "Why is **self** explicitly there as the first parameter of methods?" There are many technical explanations, but all of them are wrong. It is almost a Python programmer's rite of passage to write a metaclass that makes explicitly listing **self** unnecessary. (If you have never done this before, do so; it makes a great metaclass learning exercise!) The reason **self** is explicit is not because the Python core developers did not want to make a metaclass like that the "default" metaclass. The reason it is explicit is because there is one less special case to teach: the first argument is *explicit*. Even when Python does allow non-explicit things, such as context variables, we must always ask: Are we sure we need them? Could we not just pass arguments explicitly? Sometimes, for many reasons, this is not feasible. But prioritizing explicitness means, at the least, asking the question and estimating the effort. ## Comments are closed.
11,720
使用 Linux MLVWM 打造复古苹果桌面
https://opensource.com/article/19/12/linux-mlvwm-desktop
2019-12-27T20:49:15
[ "Macintosh" ]
https://linux.cn/article-11720-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。如果老式的苹果电脑是用开源 POSIX 构建的呢?你可以通过构建 Macintosh 式的虚拟窗口管理器来实现。 > > > ![MLVWM running on Slackware 14.2](/data/attachment/album/201912/27/204924i1htr017siaxnfss.jpg "MLVWM running on Slackware 14.2") 想象一下穿越到另一段平行历史,Apple II GS 和 MacOS 7 是基于开源 [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) 构建的,它使用了与现代 Linux 相同的所有惯例,例如纯文本配置文件和模块化系统设计。这样的操作系统将为其用户带来什么?你可以使用 [Macintosh 式的虚拟窗口管理器(MLVWM)](http://www2u.biglobe.ne.jp/%7Ey-miyata/mlvwm.html)来回答这些问题(甚至更多!)。 ### 安装 MLVWM MLVWM 安装并不容易,并且可能不在你的发行版软件仓库中。如果你有时间理解翻译不佳的 README 文件,编辑一些配置文件,收集并调整一些旧的 .xpm 图片,编辑一两个 Xorg 选项,那么你就可以体验 MLVWM。不管怎么说,这是一个新奇的窗口管理器,其最新版本可以追溯到 2000 年。 要编译 MLVWM,你必须安装 imake,它提供了 `xmkmf` 命令。你可以从发行版的软件仓库中安装 imake,也可以直接从 [Freedesktop.org](http://cgit.freedesktop.org/xorg/util/imake) 获得。假设你已经有 `xmkmf` 命令,请进入包含 MLVWM 源码的目录,然后运行以下命令进行构建: ``` $ xmkmf -a $ make ``` 构建后,编译后的 `mlvwm` 二进制文件位于 `mlvwm` 目录中。将其移动到[你的 PATH](https://opensource.com/article/17/6/set-path-linux) 的任何位置: ``` $ mv mlvwm/mlvwm /usr/local/bin/ ``` #### 编辑配置文件 现在已经安装好 MLVWM,但是如果不调整几个配置文件并仔细放好所需的图像文件,它将无法正确启动。示例配置文件位于你下载的源代码的 `sample_rc` 目录中。将文件 `Mlvwm-Netscape` 和 `Mlvwm-Xterm` 复制到你的主目录: ``` $ cp sample_rc/Mlvwm-{Netscape,Xterm} $HOME ``` 将 `Mlvwmrc` 改名为 `$HOME/.mlvwmrc`(是的,即使示例文件的名称看似是大写字母,但你也必须使用小写的 “m”): ``` $ cp sample_rc/Mlvwmrc $HOME/.mlvwmrc ``` 打开 `.mlwmrc` 并找到第 54-55 行,它们定义了 MLVWM 在菜单和 UI 中使用的像素图的路径(`IconPath`): ``` # Set icon search path. It needs before "Style". IconPath /usr/local/include/X11/pixmaps:/home2/tak/bin/pixmap ``` 调整路径以匹配你填充图像的路径(我建议使用 `$HOME/.local/share/pixmaps`)。MLVWM 不提供像素图,因此需要你提供构建桌面所需图标。 即使你有位于系统其他位置的像素图(例如 `/usr/share/pixmaps`),也要这样做,因为你需要调整像素图的大小,你可能也不想在系统范围内执行此操作。 ``` # Set icon search path. It needs before "Style". IconPath /home/seth/.local/share/pixmaps ``` #### 选择像素图 你已将 `.local/share/pixmaps` 目录定义为像素图源路径,但是该目录和图像均不存在。创建目录: ``` $ mkdir -p $HOME/.local/share/pixmaps ``` 现在,配置文件将图像分配给菜单项和 UI 元素,但是系统中不存在这些图像。要解决此问题,请通读配置文件并找到每个 .xpm 图像。对于配置中列出的每个图像,将具有相同文件名的图像(或更改配置文件中的文件名)添加到你的 IconPath 目录。 `.mlvwmrc` 文件的注释很好,因此你可以大致了解要编辑的内容。无论如何,这只是第一步。你可以随时回来更改桌面外观。 这有些例子。 此代码块设置屏幕左上角的图标: ``` # Register the menu Menu Apple, Icon label1.xpm, Stick ``` `label1.xpm` 图像实际上在源代码的 `pixmap` 目录中,但我更喜欢使用来自 `/usr/share/pixmaps` 的 `Penguin.xpm`(在 Slackware 上)。无论使用什么,都必须将自定义像素图放在 `~/.local/share/pixmaps` 中,并在配置中更改像素图的名称,或者重命名像素图以匹配配置文件中当前的名称。 此代码块定义了左侧菜单中列出的应用: ``` "About this Workstation..." NonSelect, Gray, Action About "" NonSelect "Terminal" Icon mini-display.xpm, Action Exec "kterm" exec kterm -ls "Editor" Action Exec "mule" exec mule, Icon mini-edit.xpm "calculator" Action Exec "xcal" exec xcalc, Icon mini-calc.xpm END ``` 通过遵循与配置文件中相同的语法,你可以自定义像素图并将自己的应用添加到菜单中(例如,我将 `mule` 更改为 `emacs`)。这是你在 MLVWM GUI 中打开应用的入口,因此请列出你要快速访问的所有内容。你可能还希望包括指向 `/usr/share/applications` 文件夹的快捷方式。 ``` "Applications" Icon Penguin.xpm, Action Exec "thunar /usr/share/applications" exec thunar /usr/share/applications ``` 完成编辑配置文件并将自己的图像添加到 IconPath 目录后,必须将所有像素图的大小都调整为大约 16x16 像素。(MLVWM 的默认设置不一致,因此存在变化空间。)你可以使用 ImageMagick 进行批量操作: ``` $ for i in ~/.local/share/mlvwm-pixmaps/*xpm ; do convert -resize '16x16^' $i; done ``` ### 启动 MLVWM 最简单的运行 MLVWM 的方式是让 Xorg 完成大部分工作。首先,你必须创建一个 `$HOME/.xinitrc` 文件。我从 Slackware 复制了这个,它也是从 Xorg 拿来的: ``` #!/bin/sh # $XConsortium: xinitrc.cpp,v 1.4 91/08/22 11:41:34 rws Exp $ userresources=$HOME/.Xresources usermodmap=$HOME/.Xmodmap sysresources=/etc/X11/xinit/.Xresources sysmodmap=/etc/X11/xinit/.Xmodmap # merge in defaults and keymaps if [ -f $sysresources ]; then xrdb -merge $sysresources fi if [ -f $sysmodmap ]; then xmodmap $sysmodmap fi if [ -f $userresources ]; then xrdb -merge $userresources fi if [ -f $usermodmap ]; then xmodmap $usermodmap fi # Start the window manager: if [ -z "$DESKTOP_SESSION" -a -x /usr/bin/ck-launch-session ]; then exec ck-launch-session /usr/local/bin/mlvwm else exec /usr/local/bin/mlvwm fi ``` 根据此文件,`startx` 命令的默认操作是启动 MLVWM。但是,你的发行版可能对于图形服务器启动(或被终止以重新启动)时会发生的情况有其他做法,因此此文件可能对你没有什么帮助。在许多发行版上,你可以添加 .desktop 文件到 `/usr/share/xsessions` 中,以将其列在 GDM 或 KDM 菜单中,因此创建名为 `mlvwm.desktop` 的文件并输入: ``` [Desktop Entry] Name=Mlvwm Comment=Macintosh-like virtual window manager Exec=/usr/local/bin/mlvwm TryExec=ck-launch-session /usr/local/bin/mlvwm Type=Application ``` 从桌面会话注销并重新登录到 MLVWM。默认情况下,会话管理器(KDM、GDM 或 LightDM,具体取决于你的设置)将继续登录到以前的桌面,因此在登录之前必须覆盖它。 对于 GDM: ![](/data/attachment/album/201912/27/204934n8zvrkxqxbly6k88.jpg) 对于 SDDM: ![](/data/attachment/album/201912/27/204937f8q4p3p48pqt5u47.jpg) #### 强制启动 如果 MLVWM 无法启动,请尝试安装 XDM,这是一个轻量级会话管理器,它不会查询 `/usr/share/xsessions` 的内容,而是执行经过身份验证用户的所有 `.xinitrc` 操作。 ![MLVWM](/data/attachment/album/201912/27/204945bap879hdshhefzmh.jpg "MLVWM") ### 打造自己的复古苹果 MLVWM 桌面未经打磨、不完美、模仿到位且充满乐趣。你看到的许多菜单项都是未实现的,但你可以使它们变得活跃且有意义。 这是一次让你时光倒流、改变历史,让老式苹果系列电脑成为开源堡垒的机会。成为一名修正主义者,设计你自己的复古苹果桌面,最重要的是,它有乐趣。 --- via: <https://opensource.com/article/19/12/linux-mlvwm-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Imagine traveling into an alternate history where the Apple II GS and MacOS 7 were built upon open source [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains), using all the same conventions as modern Linux, like plain-text configuration files and modular system design. What would such an OS have enabled for its users? You can answer these questions (and more!) with the [Macintosh-like Virtual Window Manager (MLVWM)](http://www2u.biglobe.ne.jp/~y-miyata/mlvwm.html). ![MLVWM running on Slackware 14.2 MLVWM running on Slackware 14.2](https://opensource.com/sites/default/files/uploads/advent-mlvwm-file.jpg) ## Installing MLVWM MLVWM is not an easy installation, and it's probably not in your distribution's software repository. If you have the time to decipher a poorly translated README file, edit some configuration files, gather and resize some old **.xpm** images, and edit an Xorg preference or two, then you can experience MLVWM. Otherwise, this is a novelty window manager with its latest release back in 2000. To compile MLVWM, you must have **imake** installed, which provides the **xmkmf** command. You can install imake from your distribution's software repository, or get it directly from [Freedesktop.org](http://cgit.freedesktop.org/xorg/util/imake). Assuming you have the **xmkmf** command, change into the directory containing the MLVWM source code, and run these commands to build it: ``` $ xmkmf -a $ make ``` After building, the compiled **mlvwm** binary is located in the **mlvwm** directory. Move it to any location [in your path](https://opensource.com/article/17/6/set-path-linux) to install it: `$ mv mlvwm/mlvwm /usr/local/bin/` ### Editing the config files MLVWM is now installed, but it won't launch correctly without adjusting several configuration files and carefully arranging required image files. Sample config files are located in the **sample_rc** directory of the source code you downloaded. Copy the files **Mlvwm-Netscape** and **Mlvwm-Xterm** to your home directory: `$ cp sample_rc/Mlvwm-{Netscape,Xterm} $HOME` Move the **Mlvwmrc** file to **$HOME/.mlvwmrc** (yes, you must use a lower-case "m" even though the sample file deceptively begins with a capital letter): `$ cp sample_rc/Mlvwmrc $HOME/.mlvwmrc` Open **.mlwmrc** and find lines 54–55, which define the path (the "IconPath") for the pixmap images that MLVWM uses in its menus and UI: ``` # Set icon search path. It needs before "Style". IconPath /usr/local/include/X11/pixmaps:/home2/tak/bin/pixmap ``` Adjust the path to match a directory you will fill with your own images (I suggest using **$HOME/.local/share/pixmaps**). MLVWM doesn't provide pixmaps, so it's up to you to provide pixmap icons for the desktop you're building. Do this even if you have pixmaps located elsewhere on your system (such as **/usr/share/pixmaps**), because you're going to have to adjust the size of the pixmaps, and you probably don't want to do that on a system-wide level. ``` # Set icon search path. It needs before "Style". IconPath /home/seth/.local/share/pixmaps ``` ### Choosing the pixmaps You've defined the **.local/share/pixmaps** directory as the source of pixmaps, but neither the directory nor the images exist yet. Create the directory: `$ mkdir -p $HOME/.local/share/pixmaps` Right now, the config file assigns images to menu entries and UI elements, but none of those images exist on your system. To fix this, read through the configuration file and locate every **.xpm** image. For each image listed in the config, add an image with the same file name (or change the file name in the config file) to your IconPath directory. The **.mlvwmrc** file is well commented, so you can get a general idea of what you're editing. This is just a first pass, anyway. You can always come back and change the look of your desktop later. Here are some examples. This code block sets the icon in the upper-left corner of the screen: ``` # Register the menu Menu Apple, Icon label1.xpm, Stick ``` The **label1.xpm** image is actually provided in the source code download's **pixmap **directory, but I prefer to use **Penguin.xpm** from **/usr/share/pixmaps** (on Slackware). Whatever you use, you must place your custom pixmap in **~/.local/share/pixmaps** and either change the pixmap's name in the configuration or rename the pixmap file to match what's currently in the config file. This code block defines the applications listed in the left menu: ``` "About this Workstation..." NonSelect, Gray, Action About "" NonSelect "Terminal" Icon mini-display.xpm, Action Exec "kterm" exec kterm -ls "Editor" Action Exec "mule" exec mule, Icon mini-edit.xpm "calculator" Action Exec "xcal" exec xcalc, Icon mini-calc.xpm END ``` By following the same syntax as what you see in the configuration file, you can customize the pixmaps and add your own applications to the menu (for instance, I changed **mule** to **emacs**). This is your gateway to your applications in the MLVWM GUI, so list everything you want quick access to. You may also wish to include a shortcut to your **/usr/share/applications** folder. `"Applications" Icon Penguin.xpm, Action Exec "thunar /usr/share/applications" exec thunar /usr/share/applications ` Once you're finished editing the configuration file and adding your own images to your IconPath directory, your pixmaps must all be resized to roughly 16x16 pixels. (MLVWM isn't consistent in its defaults, so there's room for variation.) You can do this as a bulk action using ImageMagick: `$ for i in ~/.local/share/mlvwm-pixmaps/*xpm ; do convert -resize '16x16^' $i; done` ## Starting MLVWM The easiest way to get up and running with MLVWM is to let Xorg do the bulk of the work. First, you must create a **$HOME/.xinitrc** file. I borrowed this one from Slackware, which borrowed it from Xorg: ``` #!/bin/sh # $XConsortium: xinitrc.cpp,v 1.4 91/08/22 11:41:34 rws Exp $ userresources=$HOME/.Xresources usermodmap=$HOME/.Xmodmap sysresources=/etc/X11/xinit/.Xresources sysmodmap=/etc/X11/xinit/.Xmodmap # merge in defaults and keymaps if [ -f $sysresources ]; then xrdb -merge $sysresources fi if [ -f $sysmodmap ]; then xmodmap $sysmodmap fi if [ -f $userresources ]; then xrdb -merge $userresources fi if [ -f $usermodmap ]; then xmodmap $usermodmap fi # Start the window manager: if [ -z "$DESKTOP_SESSION" -a -x /usr/bin/ck-launch-session ]; then exec ck-launch-session /usr/local/bin/mlvwm else exec /usr/local/bin/mlvwm fi ``` According to this file, the default action for the **startx** command is to launch MLVWM. However, your distribution may have other ideas about what happens when your graphic server launches (or is killed to be restarted), so this file may do you little good. On many distributions, you can add a **.desktop** file to **/usr/share/xsessions** to have it listed in the GDM or KDM menu, so create a file called **mlvwm.desktop** and enter this text: ``` [Desktop Entry] Name=Mlvwm Comment=Macintosh-like virtual window manager Exec=/usr/local/bin/mlvwm TryExec=ck-launch-session /usr/local/bin/mlvwm Type=Application ``` Log out from your desktop session and log back into MLVWM. By default, your session manager (KDM, GDM, or LightDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. With GDM: ![](https://opensource.com/sites/default/files/advent-gdm_2.jpg) With SDDM: ![](https://opensource.com/sites/default/files/advent-kdm_1.jpg) ### Launching with brute force If MLVWM fails to start, try installing XDM, a lightweight session manager that doesn't look at **/usr/share/xsessions** and instead just does whatever the authenticated user's **.xinitrc** proscribes. ![MLVWM MLVWM](https://opensource.com/sites/default/files/uploads/advent-mlvwm-chess.jpg) ## Build your own retro Apple The MLVWM desktop is unpolished, imperfect, accurate, and loads of fun. Many of the menu options you see are unimplemented, but you can make them active and meaningful. This is your chance to step back in time, change history, and make the old-school Apple line of computers a bastion of open source. Be a revisionist, design your own retro Apple desktop, and, most importantly, have fun. ## Comments are closed.
11,721
网络广告商的像素追踪是如何工作的?
https://jvns.ca/blog/how-tracking-pixels-work/
2019-12-29T06:00:00
[ "广告", "像素追踪" ]
https://linux.cn/article-11721-1.html
![](/data/attachment/album/201912/27/214125hvpv4e5ijepa0aqj.jpg) 昨天,我和一名记者谈到了一个问题:广告商是如何在互联网上对人们进行追踪的?我们津津有味地查看了 Firefox 的开发者工具(虽然我不是一个互联网隐私专家,但至少还会使用开发者工具中的“network”标签页),从中我终于弄明白<ruby> 像素追踪 <rt> tracking pixels </rt></ruby>在实际中是如何工作的了。 ### 问题:Facebook 怎么知道你逛了 Old Navy? 我时常听人们说起这种有些诡异的上网经历:你在线上浏览了一个商品,一天之后,竟然看到了同一款靴子(或者是别的什么你当时浏览的商品)的广告。这就是所谓的“再营销”,但它到底是如何实现的呢? 在本文中,我们来进行一个小实验,看看 Facebook 究竟是怎么知道你在线上浏览了什么商品的。这里使用 Facebook 作为示例,只是因为很容易找到使用了 Facebook 像素追踪技术的网站;其实,几乎所有互联网广告公司都会使用类似的追踪技术。 ### 准备:允许第三方追踪器,同时关闭广告拦截器 我使用的浏览器是 Firefox,但是 Firefox 默认拦截了很多这种类型的追踪,所以需要修改 Firefox 的隐私设置,才能让这种追踪生效。 首先,我将隐私设置从默认设置([截图](https://jvns.ca/images/trackers.png))修改为允许第三方追踪器的个性化设置([截图](https://jvns.ca/images/firefox-insecure-settings.png)),然后禁用了一些平时运行的隐私保护扩展。 ![截图](/data/attachment/album/201912/29/084152xnzxj7sz02ofjujz.png) ![截图](/data/attachment/album/201912/27/214259d0au8h8ujsabahuo.png) ### 像素追踪:关键不在于 gif,而在于请求参数 像素追踪是网站用来追踪你的一个 1x1 大小的 gif。就其本身而言,一个小小的 1x1 gif 显然起不到什么作用。那么,像素追踪到底是如何进行追踪的?其中涉及两个方面: 1. 通过使用像素追踪上的**请求参数**,网站可以添加额外的信息,比如你正在访问的页面。这样一来,请求的就不是 `https://www.facebook.com/tr/`(这个链接是一个 44 字节大小的 1x1 gif),而是 `https://www.facebook.com/tr/?the_website_you're_on`。(邮件营销人员会使用类似的技巧,通过为像素追踪指定一个独特的 URL,弄清楚你是否打开了某一封邮件。) 2. 在发送该请求的同时,还发送了相应的 cookie。这样一来广告商就可以知道,访问 oldnavy.com 的这个人和在同一台电脑上使用 Facebook 的是同一个人。 ### Old Navy 网站上的 Facebook 像素追踪 为了对此进行验证,我在 Old Navy(GAP 旗下的一个服装品牌)网站上浏览了一个商品,相应的 URL 是 `https://oldnavy.gap.com/browse/product.do?pid=504753002&cid=1125694&pcid=1135640&vid=1&grid=pds_0_109_1`(这是一件“男款短绒格子花呢大衣”)。 在我浏览这个商品的同时,页面上运行的 Javascript(用的应该是[这段代码](https://developers.facebook.com/docs/facebook-pixel/implementation/))向 facebook.com 发送了一个请求。在开发者工具中,该请求看上去是这样的:(我屏蔽了大部分 cookie 值,因为其中有一些是我的登录 cookie) ![](/data/attachment/album/201912/27/214301d2dv02d7av0za7j8.png) 下面对其进行拆解分析: 1. 我的浏览器向如下 URL 发送了一个请求; ``` https://www.facebook.com/tr/?id=937725046402747&ev=PageView&dl=https%3A%2F%2Foldnavy.gap.com%2Fbrowse%2Fproduct.do%3Fpid%3D504753002%26cid%3D1125694%26pcid%3Dxxxxxx0%26vid%3D1%26grid%3Dpds_0_109_1%23pdp-page-content&rl=https%3A%2F%2Foldnavy.gap.com%2Fbrowse%2Fcategory.do%3Fcid%3D1135640%26mlink%3D5155%2Cm_mts_a&if=false&ts=1576684838096&sw=1920&sh=1080&v=2.9.15&r=stable&a=tmtealium&ec=0&o=30&fbp=fb.1.1576684798512.1946041422&it=15xxxxxxxxxx4&coo=false&rqm=GET ``` 2. 与该请求同时发送的,还有一个名为 `fr` 的 cookie,取值为 ``` 10oGXEcKfGekg67iy.AWVdJq5MG3VLYaNjz4MTNRaU1zg.Bd-kxt.KU.F36.0.0.Bd-kx6. ``` (估计是我的 Facebook 广告追踪 ID) 在所发送的像素追踪查询字符串里,有三个值得注意的地方: * 我当前访问的页面:`https://oldnavy.gap.com/browse/product.do?pid=504753002&cid=1125694&pcid=1135640&vid=1&grid=pds_0_109_1#pdp-page-content` * 引导我来到当前页面的上一级页面:`https://oldnavy.gap.com/browse/category.do?cid=1135640&mlink=5155,m_mts_a`; * 作为我的身份标识的 cookie:`10oGXEcKfGekg67iy.AWVdJq5MG3VLYaNjz4MTNRaU1zg.Bd-kxt.KU.F36.0.0.Bd-kx6.` ### 下面来逛逛 Facebook! 下面来逛逛 Facebook 吧。我之前已经登入了 Facebook,猜猜看,我的浏览器发送给 Facebook 的 cookie 是什么? 不出所料,正是之前见过的 `fr` cookie:`10oGXEcKfGekg67iy.AWVdJq5MG3VLYaNjz4MTNRaU1zg.Bd-kxt.KU.F36.0.0.Bd-kx6.`。Facebook 现在一定知道我(Julia Evans,这个 Facebook 账号所关联的人)在几分钟之前访问了 Old Navy 网站,并且浏览了“男款短绒格子花呢大衣”,因为他们可以使用这个 cookie 将数据串联起来。 ### 这里涉及到的是第三方 cookie Facebook 用来追踪我访问了哪些网站的 cookie,属于所谓的“第三方 cookie”,因为 Old Navy 的网站使用它为一个第三方(即 facebook.com)确认我的身份。这和用来维持登录状态的“第一方 cookie”有所不同。 Safari 和 Firefox 默认都会拦截许多第三方 cookie(所以需要更改 Firefox 的隐私设置,才能够进行这个实验),而 Chrome 目前并不进行拦截(很可能是因为 Chrome 的所有者正是一个广告公司)。(LCTT 译注:Chrome 可以设置阻拦) ### 网站上的像素追踪有很多 如我所料,网站上的像素追踪有 **很多**。比如,wrangler.com 在我的浏览器里加载了来自不同域的 19 个不同的像素追踪。wrangler.com 上的像素追踪分别来自:`ct.pinterest.com`、`af.monetate.net`、`csm.va.us.criteo.net`、`google-analytics.com`、`dpm.demdex.net`、`google.ca`、`a.tribalfusion.com`、`data.photorank.me`、`stats.g.doubleclick.net`、`vfcorp.dl.sc.omtrdc.net`、`ib.adnxs.com`、`idsync.rlcdn.com`、`p.brsrvr.com`,以及 `adservice.google.com`。 Firefox 贴心地指出,如果使用 Firefox 的标准隐私设置,其中的大部分追踪器都会被拦截: ![](/data/attachment/album/201912/27/214301u097bgg0f8k5wl8j.png) ### 浏览器的重要性 浏览器之所以如此重要,是因为你的浏览器最终决定了发送你的什么信息、发送到哪些网站。Old Navy 网站上的 Javascript 可以请求你的浏览器向 Facebook 发送关于你的追踪信息,但浏览器可以拒绝执行。浏览器的决定可以是:“哈,我知道 facebook.com/tr/ 是一个像素追踪,我不想让我的用户被追踪,所以我不会发送这个请求”。 浏览器还可以允许用户对上述行为进行配置,方法包括更改浏览器设置,以及安装浏览器扩展(所以才会有如此多的隐私保护扩展)。 ### 摸清其中原理,实为一件趣事 在我看来,弄清楚 cookie/像素追踪是怎么用于对你进行追踪的,实在是一件趣事(尽管有点吓人)。我之前大概明白其中的道理,但是并没有亲自查看过像素追踪上的 cookie,也没有看过发送的查询参数上究竟包含什么样的信息。 当然,明白了其中的原理,也就更容易降低被追踪的概率了。 ### 可以采取的措施 为了尽量避免在互联网上被追踪,我采取了几种简单的措施: * 安装一个广告拦截器(比如 ublock origin 之类)。广告拦截器可以针对许多追踪器的域进行拦截。 * 使用目前默认隐私保护强度更高的 Firefox/Safari,而不是 Chrome。 * 使用 [Facebook Container](https://addons.mozilla.org/en-CA/firefox/addon/facebook-container/) 这个 Firefox 扩展。该扩展针对 Facebook 进一步采取了防止追踪的措施。 虽然在互联网上被追踪的方式还有很多(尤其是在使用手机应用的时候,因为在这种情况下,你没有和像对浏览器一样的控制程度),但是能够理解这种追踪方法的工作原理,稍微减少一些被追踪的可能性,也总归是一件好事。 --- via: <https://jvns.ca/blog/how-tracking-pixels-work/> 作者:[Julia Evans](https://jvns.ca/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[chen-ni](https://github.com/chen-ni) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
null
11,722
如何在 Ubuntu 和其他 Linux 发行版中启动、停止和重启服务
https://itsfoss.com/start-stop-restart-services-linux/
2019-12-28T08:17:06
[ "服务" ]
https://linux.cn/article-11722-1.html
![](/data/attachment/album/201912/28/081645vee5lkult55kituu.jpg) 服务是必不可少的后台进程,它通常随系统启动,并在关机时关闭。如果你是系统管理员,那么你会定期处理服务。如果你是普通桌面用户,你可能会遇到需要重启服务的情况,例如[安装 Barrier 来用于在计算机之间共享鼠标和键盘](https://itsfoss.com/keyboard-mouse-sharing-between-computers/)。或[在使用 ufw 设置防火墙](https://itsfoss.com/set-up-firewall-gufw/)时。 今天,我将向你展示两种管理服务的方式。你将学习在 Ubuntu 或任何其他 Linux 发行版中启动、停止和重启服务。 > > systemd 与 init > > > 如今,Ubuntu 和许多其他发行版都使用 systemd 而不是旧的 init。 > > > 在 systemd 中,可以使用 `systemctl` 命令管理服务。 > > > 在 init 中,你可以使用 `service` 命令管理服务。 > > > 你会注意到,即使你的 Linux 系统使用 systemd,它仍然可以使用 `service` 命令(与 init 系统一起使用的)。这是因为 `service` 命令实际上已重定向到 `systemctl`。systemd 引入了向后兼容性,因为系统管理员们习惯使用 `service` 命令。 > > > 在本教程中,我将同时展示 `systemctl` 和 `service` 命令。 > > > 我用的是 Ubuntu 18.04,但其他版本的过程也一样。 ### 方法 1:使用 systemd 在 Linux 中管理服务 我从 systemd 开始,因为它被广泛接受。 #### 1、列出所有服务 为了管理服务,你首先需要知道系统上有哪些服务可用。你可以使用 systemd 的命令列出 Linux 系统上的所有服务: ``` systemctl list-unit-files --type service -all ``` ![systemctl list-unit-files](/data/attachment/album/201912/28/081710jtozi0gb00j9cxob.png) 此命令将输出所有服务的状态。服务状态有<ruby> 启用 <rt> enabled </rt></ruby>、<ruby> 禁用 <rt> disabled </rt></ruby>、<ruby> 屏蔽 <rt> masked </rt></ruby>(在取消屏蔽之前处于非活动状态)、<ruby> 静态 <rt> static </rt></ruby>和<ruby> 已生成 <rt> generated </rt></ruby>。 与 [grep 命令](https://linuxhandbook.com/grep-command-examples/) 结合,你可以仅显示正在运行的服务: ``` sudo systemctl | grep running ``` ![Display running services systemctl](/data/attachment/album/201912/28/081711eoog3bt2z333348o.jpg) 现在,你知道了如何引用所有不同的服务,你可以开始主动管理它们。 **注意:** 下列命令中的 `<service-name>` 应该用你想管理的服务名代替。(比如:network-manager、ufw 等) #### 2、启动服务 要在 Linux 中启动服务,你只需使用它的名字: ``` systemctl start <service-name> ``` #### 3、停止服务 要停止 systemd 服务,可以使用 `systemctl` 命令的 `stop` 选项: ``` systemctl stop <service-name> ``` #### 4、重启服务 要重启 systemd 服务,可以使用: ``` systemctl restart <service-name> ``` #### 5、检查服务状态 你可以通过打印服务状态来确认你已经成功执行特定操作: ``` systemctl status <service-name> ``` 这将以以下方式输出: ![systemctl status](/data/attachment/album/201912/28/081715rgx1maxpramgox4g.jpg) 这是 systemd 的内容。现在切换到 init。 ### 方法 2:使用 init 在 Linux 中管理服务 init 的命令和 systemd 的一样简单。 #### 1、列出所有服务 要列出所有 Linux 服务,使用: ``` service --status-all ``` ![service –status-all](/data/attachment/album/201912/28/081716p629oqhw59isg629.png) 前面的 `[ – ]` 代表**禁用**,`[ + ]` 代表**启用**。 #### 2、启动服务 要在 Ubuntu 和其他发行版中启动服务,使用命令: ``` service <service-name> start ``` #### 3、停止服务 停止服务同样简单。 ``` service <service-name> stop ``` #### 4、重启服务 如果你想重启服务,命令是: ``` service <service-name> restart ``` #### 5、检查服务状态 此外,要检查是否达到了预期的结果,你可以输出服务状态: ``` service <service-name> status ``` 这将以以下方式输出: ![service status](/data/attachment/album/201912/28/081717w0j0v0rdbvby0hgy.jpg) 最重要的是,这将告诉你某项服务是否处于活跃状态(正在运行)。 ### 总结 今天,我详细介绍了两种在 Ubuntu 或任何其他 Linux 系统上管理服务的非常简单的方法。 希望本文对你有所帮助。 你更喜欢哪种方法? 让我在下面的评论中知道! --- via: <https://itsfoss.com/start-stop-restart-services-linux/> 作者:[Sergiu](https://itsfoss.com/author/sergiu/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) Services are essential background processes that are usually run while booting up and shut down with the OS. If you are a sysadmin, you’ll deal with the service regularly. If you are a normal desktop user, you may come across the need to restart a service like [setting up Barrier for sharing mouse and keyboard between computers](https://itsfoss.com/keyboard-mouse-sharing-between-computers/) or when you are [using ufw to setup firewall](https://itsfoss.com/set-up-firewall-gufw/). Today I will show you two different ways you can manage services. You’ll learn to start, stop and restart services in Ubuntu or any other Linux distribution. - Method 1 uses systemd and you manage sevices with `systemctl` command - Method 2 uses init and you manage services with `service` command [Check if You Are Using Systemd or Not in LinuxIs your Linux system using systemd or sysv or some other init system? Here’s how to find out.](https://linuxhandbook.com/check-if-systemd/)![](https://linuxhandbook.com/content/images/2022/09/check-if-systemd-or-init.png) ![](https://linuxhandbook.com/content/images/2022/09/check-if-systemd-or-init.png) ## Method 1: Managing services in Linux with systemd I am starting with systemd because of the obvious reason of its widespread adoption. ### 1. List all services In order to manage the services, you first need to know what services are available on your system. You can use the systemd command to list all the services on your Linux system: `systemctl list-unit-files --type service -all` ![systemctl list-unit-files](https://itsfoss.com/content/images/wordpress/2019/12/systemctl_list_services.png) This command will output the state of all services. The value of a service’s state can be enabled, disabled, masked (inactive until mask is unset), static and generated. Combine it with the [grep command](https://linuxhandbook.com/grep-command-examples/?ref=itsfoss.com) and you can** display just the running services**: `sudo systemctl | grep running` ![Display running services systemctl](https://itsfoss.com/content/images/wordpress/2019/12/systemctl_grep_running.jpg) Now that you know how to reference all different services, you can start actively managing them. **Note:** **<service-***name>** in the commands should be replaced by the name of the service you wish to manage (e.g. network-manager, ufw etc.).* **2. Start a** service To start a service in Linux, you just need to use its name like this: `systemctl start <service-name>` ### 3. **Stop** a service To stop a systemd service, you can use the stop option of systemctl command: `systemctl stop <service-name>` ### 4. Re**start** a service To restart a service in Linux with systemd, you can use: `systemctl restart <service-name>` ### 5. Check the status of a service You can confirm that you have successfully executed a certain action by printing the service status: `systemctl status <service-name>` This will output information in the following manner: ![systemctl status](https://itsfoss.com/content/images/wordpress/2019/12/systemctl_status.jpg) That was systemd. Let’s switch to init now. [systemd vs init Controversy [A Layman’s Guide]Still confused about what is systemd and why it is often at the center of controversy in the Linux world? I try to answer in simpler words.](https://itsfoss.com/systemd-init/)![](https://itsfoss.com/content/images/2023/07/understanding-systemd.png) ![](https://itsfoss.com/content/images/2023/07/understanding-systemd.png) ## Method 2: Managing services in Linux with init The commands in init are also as simple as system. `service` command is actually redirected to systemctl. It’s sort of backward compatibility introduced by systemd because sysadmins were habitual of using the service command.### 1. List all services To list all the Linux services, use `service --status-all` ![service --status-all](https://itsfoss.com/content/images/wordpress/2019/12/service_status_all.png) The services preceded by **[ – ]** are **disabled** and those with **[ + ]** are **enabled**. **2. Start** a service To start a service in Ubuntu and other distributions, use this command: `service <service-name> start` **3. Stop** a service Stopping a service is equally easy. `service <service-name> stop` ### 4. Re**start** a service If you want to restart a service, the command is: `service <service-name> restart` ### 5. Check the status of a service Furthermore, to check if your intended result was achieved, you can output the service** **status**:** `service <service-name> status` This will output information in the following manner: ![service status](https://itsfoss.com/content/images/wordpress/2019/12/service_status.jpg) This will, most importantly, tell you if a certain service is active** (**running**)** or not. **Wrapping Up** Today I detailed two very simple methods of managing services on Ubuntu or any other Linux system. I hope this article was helpful to you. Which method do you prefer? Let us know in the comment section below!
11,724
Unix 即将迎来 50 岁
https://www.networkworld.com/article/3511428/unix-is-turning-50-what-does-that-mean.html
2019-12-30T07:00:00
[ "Epoch", "Unix" ]
https://linux.cn/article-11724-1.html
Unix 时间(又称为“<ruby> 纪元时间 <rt> epoch time </rt></ruby>”)是自 1970 年 1 月 1 日以来经过的秒数。当 Unix 即将 50 岁时,让我们看一下让内核开发人员担心的地方。 ![](/data/attachment/album/201912/28/120311hzghpxux1hp5t4xo.jpg) 对于 Unix 而言,2020 年是重要的一年。在这一年年初,Unix 进入 50 岁。 尽管 Unix 的某些早期开发早于其“纪元”的正式开始,但 1970 年 1 月 1 日仍然是 POSIX 时间的零点,也是公认的 Unix 的万物之始。自那一刻算起,2020 年 1 月 1 日将是其 50 周年。(LCTT 译注:实际上,在 1971/11/3 出版的第一版《Unix 程序员手册》中,将 1971/1/1 作为 Unix 纪元的开始,并且一秒钟记录 60 个数,但是后来发现这样 32 位整型数字只能记录两年多,后来这个纪元被一再重新定义,改为从 1970/1/1 开始,每秒 1 个数。) ### Unix 时间与人类时间 就人类时间而言,50 年是很重要的。就 Unix 时间而言,50 年没有什么特别的。48.7 年同样重要。 Unix(包括 Linux)系统将日期/时间值存储为自 1970-01-01 00:00:00 UTC 以来经过的秒数(32 位整型)。要确定自该时间以来经过了多少秒钟,看看 Unix 时间值是什么样子,你可以发出如下命令: ``` $ date +%s 1576883876 ``` `%s` 参数告诉 `date` 命令将当前日期/时间显示为自 1970-01-01 开始以来的秒数。 ### Unix 系统可以管理多少时间? 要了解 Unix 系统可以容纳多少时间,我们需要查看 32 位字段的容量。可以这样计算: ``` $ echo '2^32' | bc 4294967296 ``` 但是,由于 Unix 需要容纳负数,因此它会为数字的符号保留一位,从而将其减少为: ``` $ echo '2^31' | bc 2147483648 ``` 并且,由于 Unix 计数以 0 开头,这意味着我们有 2,147,483,648 个值,但最大的可能值为 2,147,483,647 个。Unix 日期/时间值不能超过该数字——就像汽车上的里程表可能不能超过 999,999 英里一样。加 1 该值就变为了 -2147483648。(LCTT 译注:此处原文描述有误,已修改。在达到最大值之后,即 2038/1/19 03:14:07,下 1 秒导致符号位变为 1,其余 31 位为 0,即 -2147483648,时间变为 1901/12/13 20:45:52,这就是 Y2K38 问题。) ### 一年有多少秒? 大多数年份的秒数可以这样计算:每天的小时数乘以每小时的分钟数乘以每分钟的秒数乘以一年中的天数: ``` $ expr 24 \* 60 \* 60 \* 365 31536000 ``` 在闰年,我们再增加一天: ``` $ expr 24 \* 60 \* 60 \* 366 31622400 ``` (LCTT 译注:Unix 时间将一天精确定义为 24 \* 60 \* 60 = 86400 秒,忽略闰秒。) ### Unix 将如何庆祝其 50 岁生日? 2020 年 1 月 1 日中午 12:00 是纪元时间的 1577836800。这个计算有些棘手,但主要是因为我们必须适应闰年。自该纪元开始以来,我们经历了 12 个闰年,从 1972 年开始,到上一个闰年是 2016 年。而且,当我们达到 2020 年时,我们将有 38 个常规年份。 这是使用 `expr` 命令进行的计算,以计算这 50 年的秒数: ``` $ expr 24 \* 60 \* 60 \* 365 \* 38 + 24 \* 60 \* 60 \* 366 \* 12 1577836800 ``` 前半部分是计算 38 个非闰年的秒数。然后,我们加上闰年的 366 天的类似计算。或者,你可以使用前面介绍的每年秒数,然后执行以下操作: ``` $ expr 31536000 \* 38 + 31622400 \* 12 1577836800 ``` 这种跟踪日期和时间的方式使 Unix 系统完全不受 Y2K 恐慌的影响,1999 年末人们开始担心进入 2000 年会对计算机系统造成严重破坏,但是实际遇到的问题比人们担心的少得多。实际上,只有以两位数格式存储年份的应用程序才会将年份变为 00,以表示时间倒退。尽管如此,许多应用程序开发人员还是做了很多额外的繁琐工作,以确保 2000 年到来时,他们的系统不会出现严重问题。 ### Unix 时间何时会遇到问题? 在 2038 年之前,Unix 系统不会遇到 Y2K 类型的问题,直到如上所述存储的日期将超过其 32 位空间分配。但这距离现在已经只有 18 年了,内核开发人员已经在研究如何避免灾难。但现在开始恐慌还为时过早。 2038 年的问题有时称为 Y2K38 问题。我们必须在 2038 年 1 月 19 日星期二之前解决这个问题。如果问题到时候仍未解决,则该日期之后的系统可能会认为是 1901 年。解决该问题的一种方法是切换为日期/时间信息的 64 位表示形式。有些人认为,即使那样,也会有比听起来更复杂的问题。无论如何,恐慌还为时过早。并且,与此同时,也许在新年前夜演唱了《Auld Lang Syne》之后,你可以向 Unix 唱《生日快乐》歌了。Unix 50 岁了,这仍然是大事。 (LCTT 译注:建议阅读一下 Unix 时间的[维基百科](https://en.wikipedia.org/wiki/Unix_time)页面,有更多有趣和不为人知的信息。) --- via: <https://www.networkworld.com/article/3511428/unix-is-turning-50-what-does-that-mean.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,725
内向者的 DevOps
https://opensource.com/article/19/7/devops-introverted-people
2019-12-29T10:36:54
[ "外向", "内向" ]
https://linux.cn/article-11725-1.html
> > 我们邀请 Opensource.com 的 DevOps 团队,希望他们能够谈一谈作为 DevOps 内向者的休验,同时给 DevOps 外向者一些建议。下面是他们的回答。 > > > ![](/data/attachment/album/201912/29/103642jmzt6t6mggjjx5yt.jpg) 我们邀请我们的 [DevOps 团队](https://opensource.com/devops-team) 谈一谈他们作为一个内向者的体验,并给外向者们一些建议。但是在我们开始了解他们的回答之前,让我们先来定义一下这些词汇。 ### “内向者”是什么意思? 内向者通常指的是一部分人群,当他们和别人相处的时候,会使他们的能量耗尽,而不是激发他们更多的能量。当我们思考我们是如何恢复能量时,这是一个非常有用的词汇:内向者通常需要更多的独处时间来恢复能量,特别是和一群人在一起很长时间后。关于内向者的一个非常大的误解就是他们一定是“害羞的”,但是科学表明,那不过是另一种不同的性格特征。 内向性与外向性是通过 [Myers Briggs 类型指标](https://www.myersbriggs.org/my-mbti-personality-type/mbti-basics/extraversion-or-introversion.htm?bhcp=1) 而为人所知的,现在也常常被称作一个 [光谱](https://lifehacker.com/lets-quit-it-with-the-introvert-extrovert-nonsense-1713772952) 的两端。虽然这个世界看起来好像外向者比内向者要多,但是心理学者则倾向于认为大部分人在光谱上的位置是落在 [中间性格或偏内向性格的](https://www.psychologytoday.com/us/blog/the-gen-y-guide/201710/the-majority-people-are-not-introverts-or-extroverts)。 现在,我们来看看问答。 ### DevOps 技术主管可以通过哪些方式来让内向者感觉他们是团队的一部分并且愿意分享他们的想法? “每个人都会不大一样,所以观察敏锐就很重要了。从 GitLab 过来的一个人告诉我,他们的哲学就是如果他们没有提供任何意见,那么他们就是被排除在外的。如果有人在一个会议上没有提供任何的意见,那就想办法让他们加入进来。**当我知道一个内向者对我们将要讨论的会议论题感兴趣的时候,我会提前请他写一些书面文本。有非常多的会议其实是可以避免的,只要通过把讨论放到 Slack 或者 GitLab 上就行了,内向者会更愿意参与进来**。在站立会议中,每个人都会交代最新的进展,在这个环境下,内向者表现得很好。有时候我们在其实会议上会重复做一些事情,仅仅是为了保证每个人都有时间发言。我同时也会鼓励内向者在工作小组或者社区小组面前发言,以此来锻炼他们的这些技能。”—— 丹·巴克 “**我觉得别人对我做的最好的事情,就是他们保证了当重大问题来临的时候,我拥有必要的技能去回答它**。彼时,我作为一名非常年轻的入伍空军的一员,我需要给我们部队的高级领导做状态简报的汇报。我必须在任何时候都有一些可用的数据点,以及在实现我们确立的目标的过程中,产生延误以及偏差的背后的原因。那样的经历推动着我从一个‘幕后人员’逐渐变得更加愿意和别人分享自己的观点和想法。”—— 克里斯·肖特 “**通过文化去领导。为你的同僚一起设计和尝试仪式。**你可以为给你的小组或团队设计一个小的每周仪式,甚至给你的部门或组织设计一个年度的大仪式。它的意义在于去尝试一些事物,并观察你在其中的领导角色。去找到你们文化当中的代沟以及对立。回顾团队的信仰和行为。你能从哪里观察到对立?你们的文化中缺失了什么?从一个小陈述开始‘我从 X 和 Y 之间看到了对立’,或者‘我的团队缺少了 Z’。接着,将代沟与对立转换为问题:写下三个‘我们如何能……(How might we’s, HMWs)’。”—— 凯瑟琳·路易斯 “内向者不是一个不同的群体,他们要么是在分享他们的想法之前想得太多或等得太久的一些人,要么就是一些根本不知道发生了什么的人。我就是第一种,我想太多了,有时候还担心我的意见会被其他人嘲笑,或者没有什么意思,或者想偏了。形成那样的思维方式很难,但它同时也在吞噬着我学习更好事物的机会。有一次,我们团队在讨论一个实现问题。我当时的老大一次又一次地问我,为什么我没有作为团队中更具经验的人参与进来,然后我就(集齐了全宇宙的力量之后)开口说我想说的大家都已经说过了。他说,有时候我可以重复说一次,事情纷繁,如果你能够重复一遍你的想法,即使它已经被讨论过了,也会大有裨益。好吧,虽然它不是一种特别信服的方式,但是我知道了至少有人想听听我怎么说,它给了我一点信心。 “现在,我所使用的让团队中的人发言的方法是**我经常向内向的人求助,即使我知道解决方法,并且在团队会议和讨论中感谢他们来建立他们的自信心,通过给他们时间让他们一点一点的从他们寡言的本性中走出来,从而跟团队分享很多的知识**。他们在外面的世界中可能仍然会有一点点孤立,但是在团队里面,有些会成为我们可以信赖的人。”—— 阿布希什克·塔姆拉卡尔 “我给参加会议的内向者的建议是,找一个同样要参加会议的朋友或者同事,这样到时你就会有人可以跟你一起舒服地交谈,在会议开始之前,提前跟其他的与会者(朋友、行业联系人、前同事等等)约着见个面或者吃顿饭,**要注意你的疲劳程度,并且照顾好自己**:如果你需要重新恢复能量,就跳过那些社交或者夜晚的活动,在事后回顾中记录一下自己的感受。”—— 伊丽莎白·约瑟夫 ### 和一个内向者倾向的同事一起工作时,有什么提高生产效率的小建议? “在保证质量时,生产效率会越来越具备挑战性。在大多数时候,工作中的一个小憩或者轻松随意的交谈,可能正是我们的创造性活动中需要的一个火花。再说一次,我发现当你的团队中有内向者时, Slack 和 Github 会是一个非常有用的用于交换想法以及和其他人互动的媒介。**我同时也发现,结对编程对于大部分的内向者也非常有用,虽然一对一的交流对于他们来说,并不像交税那么频繁,但是生产质量和效率的提升却是重大的**。但是,当一个内向者在独自工作的时间,团队中的所有人都不应该去打断他们。最好是发个邮件,或者使用没有那么强的侵入性的媒介。”—— 丹·巴克 “给他们趁手的工具,让他们工作并归档他们的工作。**让他们能够在他们的工作上做到最好**。要足够经常地去检查一下,保证他们没有走偏路,但是要记住,相比外向者而言,这样做是更大的一种让人分心的困扰。”—— 克里斯·肖特 “**当我低着头的时候,不要打断我。真的,别打断我!**当我沉浸在某件事物中时,这样做会造成我至少需要花费两个小时,才能让我的大脑重新回到之前的状态。感觉很痛苦。真的。你可以发个邮件让我去有白板的地方。然后从客户的角度而不是你的角度——通过画图的方式——分享下有什么问题。要知道,可能同时会有十几个客户问题缠绕在我的脑海中,如果你的问题听起来就是‘这样子做会让我在我的领导面前显得很好’的那一类问题,那么相比我脑袋中已经有的真正的客户问题而言,它不会得到更多的关注的。画个图,给我点时间思考。当我准备分享我的看法的时候,保证有多支马克笔可以使用。准备好接受你对问题的假设有可能完全是错误的。”—— 凯瑟琳·路易斯 “感谢和鼓励就是解决的方法,感谢可能不是一份工作评估,但是感谢能让人舒服地感受到自己并不仅仅是一个活着的独立实体,**因而每个人都能够感觉到自己是被倾听的,而不是被嘲笑或者低估的**。”—— 阿布希什克·塔姆拉卡尔 ### 结语 在与内向的 DevOps 爱好者的这次交谈中,我们最大的启迪就是平等:其他人需要被怎样对待,就怎样对待他们,同时你想被怎样对待,就去要求别人怎样对待你。无论你是内向还是外向,我们都需要承认我们并非全以相同的一种方式体验这个世界。我们的同事应当被给予足够的空间以完成他们的工作,通过讨论他们的需求作为了解如何支持他们的开始。我们的差异正是我们的社区如此特别的原因,它让我们的工作对更多的人更加的有用。与别人沟通最有效的方式,就是对于你们两者而言都可行的方式。 --- via: <https://opensource.com/article/19/7/devops-introverted-people> 作者:[Matthew Broberg](https://opensource.com/users/mbbroberg) 选题:[lujun9972](https://github.com/lujun9972) 译者:[XLCYun](https://github.com/XLCYun) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
We asked members of our [DevOps team](https://opensource.com/devops-team) to talk about their experience as introverts and to give extroverts some advice. Before we get into their responses, though, let’s first define the term. ## What does being introverted mean? Being an introvert is commonly defined as someone who finds it more energy depleting, as opposed to energizing, to be around people. It can be a helpful term when we think about how we recharge: introverted people may require more alone time to recharge, especially after spending a lot of time around groups of people. A big myth about introverts is that they are necessarily shy, but [science suggests](https://www.inc.com/melanie-curtin/are-you-shy-or-introverted-science-says-this-is-1-primary-difference.html) that is a separate personality trait. Introversion and extraversion were popularized by the [Myers Briggs Type Indicators](https://www.myersbriggs.org/my-mbti-personality-type/mbti-basics/extraversion-or-introversion.htm?bhcp=1) and are now more commonly referred to as two ends of the same [spectrum](https://lifehacker.com/lets-quit-it-with-the-introvert-extrovert-nonsense-1713772952). Even though it may seem that there are more extroverted people in the world than introverts, psychologists tend to believe that a majority of us fall along the spectrum closer to [ambiverts or introverts](https://www.psychologytoday.com/us/blog/the-gen-y-guide/201710/the-majority-people-are-not-introverts-or-extroverts). Now, on to the questions and answers. ## What are some techniques DevOps leaders can use to make sure introverts feel like part of the team and increase their willingness to share ideas? "Everyone is a little different, so it’s important to be observant. Someone from GitLab once told me their philosophy is that if you aren’t offering your opinion, then they’re being exclusionary. If someone isn’t offering an opinion in a meeting, then find ways to include them. **When I know an introvert is interested in a topic we’re meeting about, I’ll ask in advance for written input. A lot of meetings can be avoided by moving the discussion to slack or GitLab where introverts are more willing to engage.** In stand-up, everyone gives an update, and introverts seem to do fine in this context. So we sometimes do the same thing in other meetings just to make sure everyone has time to speak. I also encourage introverts to speak in front of small groups either at work or in the community in order to build those skills." —Dan Barker "**I think the best thing that anyone ever did for me was to make sure I had the skills necessary to answer the big questions when they came.** As a very young enlisted Air Force member I was giving status briefings to my units’ senior leadership. That required that I have a number of data points available at any given moment as well as the why behind any delays or deviations on the way towards established objectives. That propelled me from a behind the scenes person into being willing to share my opinion and thoughts with others." —Chris Short "**Lead through culture. Design and try out a ritual for your co-workers.** You can design a smaller weekly ritual for groups or teams or a bigger yearly event for your department or organization. The point is to try something and observe your leadership role in it. Identify gaps or tensions in your culture. Look back at the beliefs and behaviors of teams. Where do you observe tension? What’s missing from your culture? Start with a simple statement 'I see a tension between X and Y'. Or 'My team is missing Z'. Next, flip the gap or tension into a question: write down 3 'How might we’s (HMWs)'." —Catherine Louis "Introverts are not a different class of people, they are either people who think or wait too much before they share their mind or people who have no idea what's going on. I was one among the first category, I thought too much and sometimes worried about what if my opinion is laughed upon or not entertained or thought otherwise. It was hard coming up of that kind of mindset but it was also eating my chances of learning better things. Once, we were discussing in the team about an implementation issue. My then manager asked me one on one, why I am not participating as I am one of the more experienced people on the team, and I opened up (after I gathered all the power in the universe to say something) saying everything I wanted to say was already shared. He suggested 'I could use a repetition sometimes, as there are many things going on, it would be helpful if you just repeat your thought even if it is discussed'. Well, that was not a very persuasive way but that gave me a bit of confidence that someone at-least wants to hear me. "Now, the way I used to make people speak in my team, is **I often ask the introvert person for help, even if I know the resolution, and appreciate them in team meetings and discussions to boost up their confidence encouraging them to share more knowledge with the team, by slowly giving them time to come out of their reserved nature**. They may still remain a bit isolated in the outer world but within a team, some emerge a player we can count on." —Abhishek Tamrakar "My advice to introverts when participating in conferences is to find friends/colleagues who are also attending so you have people to talk to comfortably, reach out prior to the event to schedule some smaller meetings/meals with other attendees (friends, industry contacts, former colleagues, etc.), **be mindful of your exhaustion level and take care of yourself**: skip the social/evening events if you need to recharge, write about your experience in a post-event retrospective." —Elizabeth Joseph ## What are some tips for increasing productivity when working with a teammate who tends to be more of an introvert? "Productivity is increasingly challenging to really qualify. In many cases, a break from work or a casual conversation can be the spark needed in our creative endeavors. Again, I find slack and GitLab to be very helpful mediums for exchanging ideas and interacting with others when you have introverts on your team. **I also find pair programming to be very useful for most introverts as one on one interactions aren’t usually as taxing but the product quality and efficiency gains are substantial.** However, when an introvert is working alone, everyone on the team should be discouraged from interrupting them. It’s best to send them an email or some non-intrusive medium." —Dan Barker "Give them great tools for doing and documenting their work. **Enable them to be the best they can be at their job.** Check in with them frequently enough to make sure they’re on the right track but also be mindful it’s a bigger distraction to them than it is more extroverted people." —Chris Short "**Don’t interrupt me when I am heads down.** Really, don’t. It could take me 2 hours minimally to get my brain back to where I was when I was knee deep in something. It feels painful. Really. Instead, email me and ask me to come to a place where there is a whiteboard. Share the problem from the customer's point of view—draw it—not from your point of view. I may have dozens of customer issues niggling in the back of my brain. If your issues sound like 'make me look good to my upper management', it will get less attention from me than the true customer's issues I already have. Draw a picture. Give me time to think. Make sure there is more than one marker in case I am ready to share. Be prepared that your hypothesis about the problem is completely wrong." —Catherine Louis "Appreciation and encouragement is the way out, appreciation may not be an appraisal, but an appreciation that encourages people to feel comfortable in presence of more than one living entities, **so that everyone feels heard and not laughed or underrated**." —Abhishek Tamrakar ## Final thoughts The biggest takeaway from our conversations on introverted DevOps enthusiasts is one of equity: Treat people as they need to be treated, and ask people to treat you as you want to be treated. Whether you are extroverted or introverted, we all need to respect the fact that we do not all experience the world in the same way. Our colleagues deserve the space they need to get the work done, and knowing how to support them starts with a discussion on their needs. Our differences are what make our communities so special and it makes our work more useful for more people. The most effective way to communicate with others is to communicate in a style that works well for both of you. ## 5 Comments
11,726
如何在 Ubuntu 和其它 Linux 发行版上更新 grub
https://itsfoss.com/update-grub/
2019-12-29T11:02:11
[ "grub" ]
https://linux.cn/article-11726-1.html
![](/data/attachment/album/201912/29/110155d51bhogs5ezp5p71.png) 在这篇文章中,你将学习在 Ubuntu 或任何其它 Linux 发行版上更新 grub 。你也将学习一个或两个关于更新这个 grub 过程如何工作的事情。 ### 如何更新 grub Ubuntu 和很多其它的 Linux 发行版提供一个易使用的称为 `update-grub` 命令行实用程序。 为更新 grub ,你所要的全部工作就是使用 `sudo` 在终端中运行这个命令。 ``` sudo update-grub ``` 你应该看到一个像这样的输出: ``` [email protected]:~$ sudo update-grub [sudo] password for abhishek: Sourcing file `/etc/default/grub' Generating grub configuration file ... Found linux image: /boot/vmlinuz-5.0.0-37-generic Found initrd image: /boot/initrd.img-5.0.0-37-generic Found linux image: /boot/vmlinuz-5.0.0-36-generic Found initrd image: /boot/initrd.img-5.0.0-36-generic Found linux image: /boot/vmlinuz-5.0.0-31-generic Found initrd image: /boot/initrd.img-5.0.0-31-generic Found Ubuntu 19.10 (19.10) on /dev/sda4 Found MX 19 patito feo (19) on /dev/sdb1 Adding boot menu entry for EFI firmware configuration done ``` 你可能看到一个类似的称为 `update-grub2` 的命令。不需要在 `update-grub` 和 `update-grub2` 之间感到害怕或不知所措。这两个命令执行相同的动作。 大约在 10 年前,当 grub2 刚刚被引进时,`update-grub2` 命令也被引进。现在,`update-grub2` 只是一个链接到 `update-grub` 的符号,它们都更新 grub2 配置(因为 grub2 是默认的)。 #### 不能找到 update-grub 命令?这里是在这种情况下该做什么 它可能是,你的 Linux 发行版可能没有可用的 `update-grub` 命令。 在这种情况下你该做什么?你如何在这样一个 Linux 发行版上更新 grub ? 在这里不需要惊慌。`update-grub` 命令只是一个入口,用于运行 `grub-mkconfig -o /boot/grub/grub.cfg` 来生成 grub2 配置文件。 这意味着你可以在任意 Linux 发行版上使用下面的命令更新 grub : ``` sudo grub-mkconfig -o /boot/grub/grub.cfg ``` 当然,记住 `update-grub` 命令比上面的命令容易很多,这是为什么它在一开始被创建的原因。 ### update-grub 是如何工作的? 当你安装一个 Linux 发行版时,它(通常)要求你安装 [grub 启动引导程序](https://en.wikipedia.org/wiki/GNU_GRUB)。 grub 的一部分安装在 MBR/ESP 分区上。grub 的剩余部分保留在 Linux 发行版的 `/boot/grub` 目录中。 依据它的 [man 页面](https://manpages.debian.org/testing/grub-legacy/update-grub.8.en.html),`update-grub` 通过查找 `/boot` 目录来工作。所有以 [vmlinuz-](https://www.ibm.com/developerworks/community/blogs/mhhaque/entry/anatomy_of_the_initrd_and_vmlinuz?lang=en) 开头的文件将被作为内核来对待,并且它们将得到一个 grub 菜单项。它也将为与所找到内核版本相同的 [ramdisk](https://en.wikipedia.org/wiki/Initial_ramdisk) 镜像添加 initrd 行。 它也使用 [os-prober](https://packages.debian.org/sid/utils/os-prober) 为其它操作系统查找所有磁盘分区。如果找到其它操作系统,它添加它们到 grub 菜单。 ![Representational image of Grub Menu](/data/attachment/album/201912/29/110215yzk01gtzmt6rn1nz.png) ### 为什么你需要更新 grub ? 在有很多场景下你需要更新 grub。 假设你修改 grub 配置文件(`/etc/default/grub`)以 [更改默认启动顺序](https://itsfoss.com/grub-customizer-ubuntu/) 或减少默认启动时间。除非你更新 grub ,否则你的修改将不会生效。 另一种情况是,你在同一个电脑系统上安装多个 Linux 发行版。 例如,在我的 Intel NUC 上,我有两个磁盘。第一个磁盘有 Ubuntu 19.10 ,并且我在其上面安装了 Ubuntu 18.04 。第二个操作系统(Ubuntu 18.04)安装了其自己的 grub ,现在 grub 启动屏幕由 Ubuntu 18.04 grub 控制。 在第二个磁盘上,我安装了 MX Linux ,但是这次我没有安装 grub。我希望现有的 grub(由 Ubuntu 18.04 控制)来处理所有的操作系统项目。 现在,在这种情况中,在 Ubuntu 18.04 上的 grub 需要更新,以便它能够看到 [MX Linux](https://mxlinux.org/) 。 ![](/data/attachment/album/201912/29/110215pp3pajbpn9ea3999.png) 如上图所示,当我更新 grub 时,它在 18.04 上找到很多安装的 Linux 内核, 以及在不同的分区上 Ubntu 19.10 和 MX Linux 。 如果你想让 MX Linux 控制 grub ,我可以使用 [grub-install](https://www.gnu.org/software/grub/manual/grub/html_node/Installing-GRUB-using-grub_002dinstall.html) 命令来在 MX Linux 上安装 grub,然后在 MX Linux 上的 grub 将开始控制 grub 启动屏幕。你已经明白这点,对吧? 使用一个像 [Grub Customizer](https://itsfoss.com/customize-grub-linux/) 的 GUI 工具是在 grub 中进行更改的一种简单的方法。 ### 最后… 最初,我打算保持它为一篇短文作为一种快速提示。但是后来我想解释一些与之相关的东西,以便(相对)新的 Linux 用户能够学到更多,而不仅仅是一个简单命令。 你喜欢它吗?你有一些问题或建议吗?请随意发表评论。 --- via: <https://itsfoss.com/update-grub/> 作者:[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) This tutorial teaches you to update grub on Ubuntu or any other Linux distribution. You’ll also learn a thing or two about how this grub update process works. ## How to update grub Ubuntu and many other Linux distributions provide a handy command line utility called update-grub. To update grub, all you have to do is to run this command in the terminal with sudo. `sudo update-grub` You should see an output like this: ``` abhishek@nuc:~$ sudo update-grub [sudo] password for abhishek: Sourcing file `/etc/default/grub' Generating grub configuration file ... Found linux image: /boot/vmlinuz-5.0.0-37-generic Found initrd image: /boot/initrd.img-5.0.0-37-generic Found linux image: /boot/vmlinuz-5.0.0-36-generic Found initrd image: /boot/initrd.img-5.0.0-36-generic Found linux image: /boot/vmlinuz-5.0.0-31-generic Found initrd image: /boot/initrd.img-5.0.0-31-generic Found Ubuntu 19.10 (19.10) on /dev/sda4 Found MX 19 patito feo (19) on /dev/sdb1 Adding boot menu entry for EFI firmware configuration done ``` You may see a similar command called update-grub2. No need to be alarmed or confused between update-grub and update-grub2. Both of these commands do the same action. Around ten years ago, when grub2 was just introduced, update-grub2 command was also introduced. Today, update-grub2 is just a symbolic link to update-grub and both update grub2 configuration (because grub2 is the default). ### Can’t find update-grub command? Here’s what to do in that case It’s possible that your Linux distribution might not have update-grub command available. What do you do in that case? How do you update grub on such a Linux distribution? There is no need to panic. The update-grub command is simply a stub for running ‘grub-mkconfig -o /boot/grub/grub.cfg’ to generate grub2 config file. Which means that you can update grub with the following command on any Linux distribution: `sudo grub-mkconfig -o /boot/grub/grub.cfg` Of course, remembering update-grub command is a lot easier than the above command and this is the reason why it was created in the first place. ## How does update-grub work? When you install a Linux distribution, it (usually) asks you to install the [grub boot loader](https://en.wikipedia.org/wiki/GNU_GRUB). Part of grub is installed on the MBR/ESP partition. Rest of the grub lies in /boot/grub directory of the Linux distributions. As per its [man page](https://manpages.debian.org/testing/grub-legacy/update-grub.8.en.html), update-grub works by looking into the /boot directory. All the files starting with [vmlinuz-](https://www.ibm.com/developerworks/community/blogs/mhhaque/entry/anatomy_of_the_initrd_and_vmlinuz?lang=en) will be treated as kernels and they will get a grub menu entry. It will also add initrd lines for [ramdisk](https://en.wikipedia.org/wiki/Initial_ramdisk) images found with the same version as kernels found. It also looks into all disk partitions for other operating systems with [os-prober](https://packages.debian.org/sid/utils/os-prober). If it finds other operating systems, it adds them to the grub menu. ![Grub Screen](https://itsfoss.com/content/images/wordpress/2019/12/grub_screen.png) ## Why would you need to update grub? There could be a number of scenarios when you need to update grub. Suppose you changed the grub config file (/etc/default/grub) to [change the default boot order](https://itsfoss.com/grub-customizer-ubuntu/) or reduce the default boot time. Your changes won’t take into effect unless you update the grub. Another scenario is when you have multiple Linux distributions installed on the same system. For example, on my Intel NUC, I have two disks. The first disk had Ubuntu 19.10 and then I installed Ubuntu 18.04 on it. The second OS (Ubuntu 18.04) also installed its own grub and now the grub screen is controlled by Ubuntu 18.04 grub. On the second disk, I installed MX Linux but I didn’t install grub this time. I want the existing grub (controlled by Ubuntu 18.04) to handle all the OS entries. Now, in this scenario, the grub on Ubuntu 18.04 needs to be updated so that it can see [MX Linux](https://mxlinux.org/). ![Update Grub](https://itsfoss.com/content/images/wordpress/2019/12/update_grub.png) As you can see in the image above, when I update the grub, it finds various Linux kernels installed on 18.04 along with Ubuntu 19.10 and MX Linux on different partitions. If I want MX Linux to control the grub, I can install grub on MX Linux with [grub-install](https://www.gnu.org/software/grub/manual/grub/html_node/Installing-GRUB-using-grub_002dinstall.html) command and then the grub on MX Linux will start controlling the grub screen. You get the gist, right? Using a GUI tool like [Grub Customizer](https://itsfoss.com/customize-grub-linux/) is a simpler way to make changes in grub. [Customize Grub to Get a Better Experience With LinuxYou know what Grub bootloader is, right? You see the Grub screen when you start your Linux powered system. It generally shows the installed operating systems on your computer along with the option to access the UEFI settings and recovery menu. Not many people know that several aspects of Gru…](https://itsfoss.com/customize-grub-linux/)![](https://itsfoss.com/content/images/wordpress/2016/02/customize-grub.png) ![](https://itsfoss.com/content/images/wordpress/2016/02/customize-grub.png) **In the end…** Initially, I had intended to keep it a short article as a quick tip. But then I thought of explaining a few things associated with it so that (relatively) new Linux users could learn more than just a simple command. Did you like it? Do you have some questions or suggestions? Please feel free to leave a comment.
11,728
使用 KDE Plasma 定制 Linux 桌面
https://opensource.com/article/19/12/linux-kde-plasma
2019-12-30T09:35:39
[ "KDE" ]
https://linux.cn/article-11728-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。如果你认为没有太多自定义桌面的需要,KDE Plasma 可能适合你。 > > > ![KDE Plasma desktop](/data/attachment/album/201912/30/093544uff51mc7557av14d.jpg "KDE Plasma desktop") KDE 社区的 Plasma 桌面是开源桌面环境中的巅峰之作。KDE 很早就进入了 Linux 桌面环境市场,但是由于它的基础 Qt 工具包当时没有完全开放的许可证,因此才有 [GNOME](https://opensource.com/article/19/12/gnome-linux-desktop) 桌面。在此之后,Qt 开源了,并且 KDE(及其衍生产品,例如 [Trinity 桌面](https://opensource.com/article/19/12/linux-trinity-desktop-environment-tde))开始蓬勃发展。 你可能会在发行版的软件仓库中找到 KDE 桌面,或者可以下载并安装将 KDE 作为默认桌面的发行版。在安装之前,请注意,KDE 提供了完整、集成且强大的桌面体验,因此会同时安装几个 KDE 应用。如果你已经在运行其他桌面,那么将发现有几个冗余的应用(两个 PDF 阅读器、多个媒体播放器、两个或多个文件管理器,等等)。如果你只想尝试而不是一直使用 KDE 桌面,那么可以在虚拟机,如 [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization) 中安装基于 KDE 的发行版,也可以尝试使用可引导的操作系统,例如 [Porteus](https://opensource.com/article/19/6/linux-distros-to-try)。 ### KDE 桌面之旅 乍一看,[KDE Plasma](https://kde.org/plasma-desktop) 桌面相对无聊,但让人感到舒适。它有行业标准的布局:左下角弹出应用菜单,中间是任务栏,右边是系统托盘。这正是你对标准家用或商用计算机的期望。 但是,使 KDE 与众不同的是,你几乎可以更改任何想要的东西。Qt 工具包可以以令人惊讶的方式分割和重新排列,这意味着你实质上可以使用 KDE 的部件作为基础来设计自己的桌面。桌面行为的可用设置也很多。KDE 可以充当标准桌面、平铺窗口管理器以及两者之间的任意形式。你可以通过窗口类、角色、类型、标题或它们的任意组合来创建自己的窗口规则,因此,如果希望特定应用的行为不同于其他行为,那么可以创建全局设置的例外。 此外,它还有丰富的小部件集合,使你可以自定义与桌面交互的方式。它有一个类似 GNOME 的全屏应用启动器,一个类似 Unity 的 dock 启动器和仅有图标的任务栏,以及一个传统的任务栏。你可以在屏幕的任何边缘上创建和放置面板。 ![A slightly customized KDE desktop](/data/attachment/album/201912/30/093547mcxoexxt2u5exc32.jpg "A slightly customized KDE desktop") 实际上,它有太多的自定义项了,因此 KDE 最常见的批评之一是它的*太过可定制化*,所以请记住,自定义项是可选的。你可以在默认配置下使用 Plasma 桌面,并仅在你认为必要时逐步进行更改。Plasma 桌面配置选项最重要的不是它们的数目,而是它们容易发现和直观,它们都在系统设置应用或者右键单击中。 事实是,在 KDE 上,几乎绝不会只有一种方法可以完成任何给定的任务,并且它的用户将这个视为其最大的优势。KDE 中没有隐含的工作流,只有默认的。并且可以更改所有默认设置,直到你需要桌面做的成为你的习惯。 ### 一致性和集成 KDE 社区以一致性和集成为荣,出色的开发人员、社区管理以及 KDE 库使其成为可能。KDE 的开发人员不只是桌面开发人员。它们提供了[惊人的应用集合](https://kde.org/applications/),每个应用都使用 KDE 库创建,这些库扩展并标准化了常见的 Qt 小部件。使用 KDE 几个月后,无论是打开 [DigiKam](https://opensource.com/life/16/5/how-use-digikam-photo-management) 进行照片管理,还是打开 Kmail 来检查电子邮件,还是打开 KTorrent 来获取最新的 ISO 或者使用 Dolphin 管理文件,你的肌肉记忆会在你思考之前直接带你进入对应 UI。 ![KDE on Porteus](/data/attachment/album/201912/30/093549yeyp9rye4lx9zevu.jpg "KDE on Porteus") ### 尝试 KDE KDE 适合所有人。使用其默认设置可获得流畅、原始的桌面体验,或对其进行自定义以使其成为自己专属。它是一个稳定、有吸引力且强大的桌面环境,可能有你想要在 Linux 完成要做的事的一切。 --- via: <https://opensource.com/article/19/12/linux-kde-plasma> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The Plasma desktop by the KDE community is a pinnacle among open source desktops. KDE got into the Linux desktop market early, but since its foundational Qt toolkit did not have a fully open license at the time, the [GNOME](https://opensource.com/article/19/12/gnome-linux-desktop) desktop was created. Since then, Qt has become open source, and KDE (and its derivatives, like the [Trinity desktop](https://opensource.com/article/19/12/linux-trinity-desktop-environment-tde)) has thrived. You may find the KDE desktop in your distribution's software repository, or you can download and install a distribution that ships KDE as its default. Before you install, be aware that KDE provides a full, integrated, and robust desktop experience, so several KDE applications are installed along with it. If you're already running a different desktop, you will find yourself with redundant applications (two PDF readers, several media players, two or more file managers, and so on). If you just want to try the KDE desktop without committing to it, you can install a KDE-based distribution in a virtual machine, such as [GNOME Boxes](https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization), or you can try a bootable OS like [Porteus](https://opensource.com/article/19/6/linux-distros-to-try). ## KDE desktop tour The [KDE Plasma](https://kde.org/plasma-desktop) desktop is relatively boring at first glance—but in a comforting way. It's got the industry-standard layout: pop-up application menu in the bottom-left corner, taskbar in the middle, system tray on the right. It's exactly what you'd expect from a standard household or business computer. ![KDE Plasma desktop KDE Plasma desktop](https://opensource.com/sites/default/files/uploads/advent-kde-presskit.jpg) What sets KDE apart, though, is that you can change nearly anything you want. The Qt toolkit can be taken apart and rearranged in some surprising ways, meaning you can essentially design your own desktop using KDE's parts as your foundation. The settings available for how your desktop behaves are vast, too. KDE can act as a standard desktop, a tiling window manager, and anything in between. You can create your own window rules by window class, role, type, title, or any combination thereof, so if you want specific applications to behave differently than everything else, you can create an exception to global settings. Furthermore, there's a rich collection of widgets to enable you to customize the way you interface with your desktop. There's a GNOME-like full-screen application launcher, a Unity-like dock launcher and icons-only taskbar, and a traditional taskbar. You can create and place panels on any edge of the screen you want. ![A slightly customized KDE desktop A slightly customized KDE desktop](https://opensource.com/sites/default/files/uploads/advent-kde-dock.jpg) There's so much customization, in fact, that one of the most common critiques of KDE is that it's *too customizable*, so keep in mind that customization is optional. You can use the Plasma desktop in its default configuration, and change things gradually and only as you feel necessary. What matters most about Plasma desktop configuration options isn't their number, but that they're discoverable and intuitive, either in the System Settings application or with a right-click. The fact is, on KDE, there's almost never just one way to accomplish any given task, and its users see that as its greatest strength. There's no implied workflow in KDE, only a default. And all defaults can be changed, until everything you need to do with your desktop is second-nature. ## Consistency and integration The KDE community prides itself on consistency and integration, made possible through great developer and community management and the KDE libraries. The developers of KDE aren't just developers of a desktop. They provide a [stunning collection of applications](https://kde.org/applications/), each of them created with KDE libs that extend and standardize common Qt widgets. It's no accident that after using KDE for a few months, whether you open [DigiKam](https://opensource.com/life/16/5/how-use-digikam-photo-management) for photo management or Kmail to check email or KTorrent to grab the latest ISO or Dolphin to manage files, your muscle memory takes you where you need to go in the UI before you consciously think about it. ![KDE on Porteus KDE on Porteus](https://opensource.com/sites/default/files/uploads/advent-kde.jpg) ## Try KDE KDE has something for everyone. Use its default settings for a smooth, plain-vanilla desktop experience, or customize it to make it your own. It's a stable, attractive, and robust desktop environment that probably has everything you need for whatever you want to do on Linux. ## Comments are closed.
11,730
每个 Kubernetes 应聘者应该知道的 5 个面试题
https://opensource.com/article/19/12/kubernetes-interview-questions
2019-12-31T10:12:53
[ "Kubernetes", "面试" ]
/article-11730-1.html
> > 如果你是要面试 Kubernetes 相关职位的应聘者,这里给出了要提问的问题以及这些问题的重要性。 > > > ![](/data/attachment/album/201912/31/101229mmjumsesrzhh6rhk.jpg) 面试对面试官及候选人来说都很不容易。最近,我发现面试 Kubernetes 相关工作的候选人似乎尤其困难。为什么呢?一方面,很难找到可以回答他们问题的人。而且,不管回答者回答的怎样,都很难确定他们是否有正确的经验。 跳过这个问题,让我们来看看面试 [Kubernetes](https://kubernetes.io/) 求职者时应该提问的一些问题。 ### Kubernetes 是什么? 我发现这个问题是面试中最好的问题之一。我经常听到有人说“我用 Kubernetes 工作”,但是当我问道“Kubernetes 是什么”时,从来都没有得到过一个满意答案。 我最喜欢 [Chris Short](https://twitter.com/ChrisShort) 给出的答案:“Kubernetes 就是带有一些 YAML 文件的 API 。” 虽然他的回答没有错,但我会给你更详细的解释。 Kubernetes 是一个可移植容器的编排工具,用于自动执行管理、监控、扩展和部署容器化应用程序。 我认为“用于部署容器化应用程序的编排工具”这个回答可能与你期望的答案差不多了。能回答出这个,我觉得已经很不错了。尽管许多人认为 Kubernetes 做了更多更棒的工作,但总的来说,它为其核心功能——容器编排——添加了许多 API。 我认为,这是你在面试中可以提问的最好的问题之一,因为它至少证明了候选人是否知道 Kubernetes 是什么。 ### Kubernetes 的节点和 Pod 有什么区别? 该问题揭示了候选人对 Kubernetes 复杂性的初步了解。它将面试对话转换为对体系结构的概述,并可能导向许多有趣的后续细节问题。我已经听到了无数次关于该问题的错误解释了。 [节点](https://kubernetes.io/docs/concepts/architecture/nodes/) 是工作计算机。该计算机可以是虚拟机(VM)或物理计算机,具体取决于你是在虚拟机监控程序上运行还是在裸机上运行。该节点包含用于运行容器的服务,包括 kubelet、kube-proxy 和容器运行时。 [Pod](https://kubernetes.io/docs/concepts/workloads/pods/pod/) 包括:一个或多个**容器**、具有共享**网络**和**存储**,以及有关如何运行一起部署的容器的**规范**。这四个细节都很重要。更进一步,职位申请人应从技术层面解释,Pod 是 Kubernetes 可以创建和管理的最小可部署单元,而不是容器。 对于这个问题,我听到的最好的简答是:“节点是计算机,而 Pod 是容器运行于其中的东西。”这个区别很重要。Kubernetes 管理员的大部分工作是知道什么时间要部署什么,而节点的部署成本可能非常非常高,具体取决于它们的运行位置。我不希望有人一遍又一遍地部署节点,他们需要做的就是部署一堆 Pod。 ### kubectl 是什么?(你怎么发音?) 这个问题是我优先级较高的问题之一,但可能与你和你的团队无关。在我的团队中,我们不会使用图形化界面来管理 Kubernetes 环境,我们使用命令行操作。 那么什么是 [kubectl](https://kubernetes.io/docs/reference/kubectl/kubectl/)?它是 Kubernetes 的命令行界面。你可以从该界面获取并设置任何内容,从收集日志和事件到编辑部署环境和机密文件。随机提问候选人关于如何使用此工具对测试候选人对 kubectl 的熟悉度是很有帮助的。 你是怎么读的?好吧,你随便吧(对此有很大的分歧),但是我很高兴向你介绍我朋友 [Waldo](https://opensource.com/article/18/12/kubectl-definitive-pronunciation-guide) 的精彩视频演示。 ### 命名空间是什么? 在多次面试中,我都没有得到关于这个问题的答案。我不确定在其他环境中使用的命名空间是否会在我所在的团队经常使用。我在这里给出一个简短的答案:命名空间是 Pod 中的虚拟集群。这种抽象可以使你将多个虚拟集保留在多个环境中以此来进行隔离。 ### 容器是什么? 了解 Pod 中正在部署的内容总是有帮助的,因为如果都不知道其中部署的是什么,何谈部署?容器是打包代码及其所有依赖项的软件的标准单元。我收到了两个可以接受的答案,其中包括:a)精简的操作系统镜像,以及 b)在受限的操作系统环境中运行的应用程序。如果你可以叫得出使用 [Docker](https://opensource.com/resources/what-docker) 以外的其他容器的编排软件(例如你最喜欢的公共云的容器服务),则可以得到加分。 ### 其他问题 如果你想知道为什么我没有在此问题列表中添加更多问题,那么我可以给出一个简单的答案:我所列出的这些问题是在面试候选人时应了解的最基本的问题。接下来的问题应该是基于具体的团队、环境及组织。当你仔细研究这些内容时,尝试寻找有关技术如何相互作用的有趣问题,以了解人们如何应对基础架构挑战。考虑一下你的团队最近遇到的挑战(中断),要求逐步进行部署,或者考虑改善团队积极想要改进的策略(例如减少部署时间)。问题越不抽象,对面试后真正重要的技能的询问就越多。 没有两个环境是完全相同的。这也适用于面试中。我在每次面试中都会混合提问。我也有一个测试面试者的小环境。我经常发现回答问题是最容易的部分,而你所做的工作才是对你的真正的考验。 我给面试官的最后一点建议是:如果你遇到一个很有潜力但没有经验的候选人时,请给他们一个证明自己的机会。如果当初没有人看到我的潜力,没有给我机会的话,我不会拥有今天的知识和经验。 还有哪些重要的问题?请留言告诉我们。 --- via: <https://opensource.com/article/19/12/kubernetes-interview-questions> 作者:[Jessica Repka](https://opensource.com/users/jrepka) 选题:[lujun9972](https://github.com/lujun9972) 译者:[Morisun029](https://github.com/Morisun029) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,732
应用推荐:来自 KDE 的 Falkon 开源 Web 浏览器
https://itsfoss.com/falkon-browser/
2019-12-31T10:47:00
[ "浏览器", "Falkon" ]
https://linux.cn/article-11732-1.html
> > Falkon 是基于 QtWebEngine 的 Web 浏览器,它以前称为 Qupzilla。在本周的“应用推荐”中,我们来看看这个开源软件。 > > > ![](/data/attachment/album/201912/31/105027tblfjlzn9xx8keud.png) ### Falkon:适用于 Linux(和 Windows)的开源 Web 浏览器 ![](/data/attachment/album/201912/31/104800t18mzzoqwoipibgp.jpg) 首先,[Falkon](https://www.falkon.org/) 并不是一款新的 Web 浏览器。它自 2010 年以来一直在开发中,但被称为 Qupzilla。2017 年,QupZilla 移到 KDE 旗下,并更名为 Falkon。处于 KDE 旗下意味着项目会按照 KDE 标准积极维护。 它使用 [QtWebEngine](https://wiki.qt.io/QtWebEngine) 渲染引擎,这是 Chromium 核心的简化版本。 在本文中,我将仔细研究它提供的功能以及与 Linux 上其他主流 Web 浏览器的不同之处。 ### Falkon 浏览器的功能 我认为它可能不是流行的浏览器,但我发现它足以浏览现代 Web 服务。让我重点介绍 Falkon 的主要功能,如果你觉得它很有趣,请尝试一下。 #### 简单的用户界面 ![](/data/attachment/album/201912/31/104805t24z4wjuo42z21gr.png) 我知道这不完全是一项“功能”,但是用户体验(UX)至关重要。尽管是轻量级的浏览器,但你会拥有一个不错的界面。你不会觉得使用的是一款源自 2000 年早期的浏览器。 #### AdBlock 扩展 ![](/data/attachment/album/201912/31/104812pllzmh6hsth6s6ds.jpg) 它附带了 AdBlock 扩展程序,如果你想在浏览网站时摆脱广告,它的效果很好。你还可以自定义 AdBlock 扩展的行为。 #### DuckDuckGo 作为默认搜索引擎 如果你不喜欢使用 Google,那么这是一件好事,它将这个[主打隐私的搜索引擎](https://itsfoss.com/privacy-search-engines/)设为默认搜索引擎。 #### 会话管理器 ![](/data/attachment/album/201912/31/104812hss4c7410iqf6t6i.jpg) Falkon 在浏览器菜单的可用选项中包含了一个有用的会话管理器。你可以用它还原特定的近期会话,这应该能派上用场。 #### 扩展支持 ![](/data/attachment/album/201912/31/104814lyzzadpqj49hyldj.png) 它确实支持添加扩展,但你不能从 Chrome/Firefox 插件市场添加扩展。你只能选择有限的一组扩展。 #### 主题支持 Falkon 还允许你在某种程度上自定义外观。如果要更改浏览器的外观,可以尝试一下。 ![](/data/attachment/album/201912/31/104816homd1ue6zoz11mm7.png) #### 其他基本设置 ![](/data/attachment/album/201912/31/104818t7ljpqy3fmjm7jml.png) 我还尝试了其他设置/功能,例如添加书签或管理密码。或者,管理网页的通知。我还试了 YouTube,没有任何问题。 当然,这不是一个详尽的评测。但是,Falkon 确实拥有浏览器中需要的所有基本功能(除非你有特定要求)。 ### 安装 Falkon 浏览器 你可以在软件中心轻松找到 Falkon 浏览器。如果没有,你可以从它的[官方下载页面](https://www.falkon.org/download/)中找到 Flatpak/Snap 包。你还可以在下载页面上找到 Windows 的安装程序。 [Download Falkon Browser](https://www.falkon.org/download/) ### 总结 作为 KDE 产品,Falkon 是为 KDE 桌面环境量身定制的。一些 KDE 发行版(例如 OpenMandriva)使用 Falkon 作为默认的 Web 浏览器。 Falkon 浏览器适合那些正在寻求轻巧且功能丰富的 Web 浏览器的人。值得尝试的另一个替代是 [Midori](https://itsfoss.com/midori-browser/)。 我认为,除非你需要大量的扩展、跨平台同步并且需要访问某些特定于浏览器的网站,不然它是一个很好的替代浏览器。 你如何看待 Falkon 浏览器?请在下面的评论中让我知道你的想法。 --- via: <https://itsfoss.com/falkon-browser/> 作者:[Ankush Das](https://itsfoss.com/author/ankush/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
*Formerly known as Qupzilla, Falkon is a web browser based on QtWebEngine. In this week’s App Highlight, we take a look at this open source software.* ## Falkon: Open Source Web Browser for Linux (and Windows) ![Falkon Browser Screenshot](https://itsfoss.com/content/images/wordpress/2019/12/falkon-browser-screenshot.jpg) First thing first, [Falkon](https://www.falkon.org/) is not a new web browser. It has been in development since 2010 but it was known as Qupzilla. In 2017, QupZilla moved under KDE umbrella and changed its name to Falkon. Being under KDE umbrella means that project is actively maintained following KDE standards. It uses the [QtWebEngine](https://wiki.qt.io/QtWebEngine) rendering engine – which is a striped down version of Chromium core. In this article, I shall take a closer look at what it offers and how it’s different than other dominant web browsers on Linux out there. ## Features of Falkon Browser Thought it may not be a [popular browser for Linux](https://itsfoss.com/best-browsers-ubuntu-linux/) yet, I did find it capable enough to browse modern web services. Let me highlight the key features of Falkon and if you find it interesting enough, give it a try. ### Simple User Interface ![Falkon Browser](https://itsfoss.com/content/images/wordpress/2019/12/falkon-browser.png) I know it’s not exactly a “feature” but the user experience (UX) matters a lot. Despite being a lightweight browser, you have a decent looking interface here. You won’t feel like you are using a browser from the early 2000’s. ### AdBlock Extension ![Falkon Adblock](https://itsfoss.com/content/images/wordpress/2019/12/falkon-adblock.jpg) It comes packed in with the AdBlock extension that works pretty well if you want to get rid of the advertisements while browsing a website. You can also customize the behavior of the AdBlock extension. ### DuckDuckGo Default Search Engine It’s a good thing to have one of the [privacy-oriented search engines](https://itsfoss.com/privacy-search-engines/) as the default search engine if you do not like using Google. ### Session Manager ![Session Manager Falkon](https://itsfoss.com/content/images/wordpress/2019/12/session-manager-falkon.jpg) Falkon includes a useful session manager from the available options in the browser menu. You can restore a specific recent session using this – which should come in handy. ### Extension Support ![Falkon Browser Extensions](https://itsfoss.com/content/images/wordpress/2019/12/falkon-browser-extensions.png) It does support adding extensions but you cannot add extensions from Chrome/Firefox add-on marketplace. You have a limited set of extensions to choose from. ### Theme Support Falkon also lets you customize the appearance to some extent. You can try them out if you want to change the appearance of the browser. ![Falkon Browser Theme](https://itsfoss.com/content/images/wordpress/2019/12/falkon-browser-theme.png) ### Other Essential Settings ![Falkon Browser Preference](https://itsfoss.com/content/images/wordpress/2019/12/falkon-browser-preference.png) I also explored other settings/functionalities like adding a bookmark or being able to manage the passwords. Or, maybe manage the notification access of a webpage. Oh, I also tried using YouTube – with no problems whatsoever. Of course, this isn’t an extensive review – but yes, Falkon does have all the essential options that you will need in a browser (unless you have a specific requirements). ## Installing Falkon Browser You can easily find Falkon browser available in your Software Center. In case you don’t, you can find Flatpak/Snap packages available from its [official download page](https://www.falkon.org/download/). You’ll also find Windows installer files on the download page. **Wrapping Up** As a KDE product, Falkon is tailored for KDE desktop environment. Some KDE distributions like OpenMandriva use Falkon as the default web browser. Falkon browser is for the ones looking for a lightweight and feature-rich web browser. An alternative worth taking a look is [Midori](https://itsfoss.com/midori-browser/). In my opinion, it is a good alternative browser – unless you need tons of extensions, cross-platform synchronization and require to access some browser-specific websites. [interaction id=”5e00aa147cf62bac52e4174d”] What do you think about the Falkon browser? Let me know your thoughts in the comments below.
11,733
Fedora 上的桌面环境内存占用测试
https://fedoramagazine.org/fedora-desktops-memory-footprints/
2019-12-31T11:00:00
[ "桌面环境", "Fedora" ]
https://linux.cn/article-11733-1.html
![](/data/attachment/album/201912/31/110051vfaepxfs4dd4cays.jpg) Fedora 中有 40 多种桌面环境(DE)。每种桌面环境都有自己的优点和缺点。通常,根据功能、外观和其它品质,选择桌面是一件非常个人的偏好。但有时,你选择的桌面环境还会受到硬件限制。 本文旨在帮助人们根据桌面环境占用的基准内存来比较 Fedora 桌面环境。为了缩小范围,我们仅查看具有正式 Fedora Live 镜像的桌面环境。 ### 安装与系统配置 每个桌面环境都安装在自己的 KVM 虚拟机上。每个虚拟机都有 1 个 CPU、4GB 内存、15GB virtio 固态磁盘,以及 RHEL 8.0 kvm 上所有其他标准配置。 用于安装的镜像是标准的 Fedora 31 Live 镜像。对于 GNOME,该镜像是 “Fedora 工作站”。对于其它桌面,使用了相应的 Spin 版本。未对“<ruby> 糖葫芦 <rt> Sugar On A Stick </rt></ruby>”(SOAS)进行测试,因为它不容易安装到本地驱动器上。 用 Live CD 启动虚拟机,然后选择“安装到硬盘”。在安装过程中,仅使用默认值。创建了一个 root 用户和一个普通用户。安装并重新启动后,live 镜像已确认不在虚拟 CDROM 中。 每个桌面环境的设置都没有改动。它们每个都以 Live CD 环境中默认的设置运行。每个桌面环境都是通过普通用户登录的。打开了一个终端,在每台虚拟机中都使用 `sudo` 运行了 `dnf -y update`。在更新后,在该 sudo 终端中,每台虚拟机都运行 `/sbin/shutdown -h now` 以关闭。 ### 测试方式 每台机器都已启动。桌面环境已通过普通用户登录。打开了三个桌面终端。xterm 从未使用过,始终用的是该桌面环境的终端,例如 konsole。 在一个终端中,启动 `top` 并按下 `M`,以显示按内存排序的进程。在另一个终端中,一个简单的 `while` 循环每 30 秒显示一次 `free -m`。第三个终端闲置。 然后,我等待了 5 分钟。这样就可以让所有启动的服务都启动完成。我记录了最终的 `free` 结果,以及 `top` 中最终的前三名内存使用者。 ### 结果 * Cinnamon + 使用了624 MB + cinnamon 4.8% / Xorg 2.2% / dnfdragora 1.8% * GNOME + 使用了 612 MB + gnome-shell 6.9% / gnome-software 1.8% / ibus-x11 1.5% * KDE + 使用了 733 MB + plasmashell 6.2% / kwin\_x11 3.6% / akonadi\_mailfil 2.9% * LXDE + 使用了 318 MB + Xorg 1.9% / nm-applet 1.8% / dnfdragora 1.8% * LXQt + 使用了 391 MB + lxqt-panel 2.2% / pcmanfm-qt 2.1% / Xorg 2.1% * MATE + 使用了 465 MB + Xorg 2.5% / dnfdragora 1.8% / caja 1.5% * XFCE + 使用了 448 MB + Xorg 2.3% / xfwm4 2.0% / dnfdragora 1.8% ### 结论 我会让数字说明一切。 请记住,这些数字来自默认的 Live 安装环境。如果删除或添加服务和功能,则内存使用量将发生变化。但是,如果要根据内存消耗确定桌面环境,这是一个很好的基准。 --- via: <https://fedoramagazine.org/fedora-desktops-memory-footprints/> 作者:[Troy Dawson](https://fedoramagazine.org/author/tdawson/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
There are over 40 desktops in Fedora. Each desktop has it’s own strengths and weaknesses. Usually picking a desktop is a very personal preference based on features, looks, and other qualities. Sometimes, what you pick for a desktop is limited by hardware constraints. This article is to help people compare Fedora desktops based on the desktop baseline memory. To narrow the scope, we are only looking at the desktops that have an official Fedora Live image. ### Installation and Setup Each of the desktops was installed on it’s own KVM virtual machine. Each virtual machine had 1 CPU, 4GB of memory, 15 GB virtio solid state disk, and everything else that comes standard on RHEL 8.0 kvm. The images for installation were the standard Fedora 31 Live images. For GNOME, that image was the Fedora Workstation. For the other desktops, the corresponding Spin was used. Sugar On A Stick (SOAS) was not tested because it does not install easily onto a local drive. The virtual machine booted into the Live CD. “Install to Hard Disk” was selected. During the install, only the defaults were used. A root user, and a regular users were created. After installation and reboot, the Live image was verified to not be in the virtual CDROM. The settings for each desktop was not touched. They each ran whatever settings came default from the Live CD installation. Each desktop was logged into via the regular user. A terminal was opened. Using sudo each machine ran “dnf -y update”. After update, in that sudo terminal, each machine ran “/sbin/shutdown -h now” to shut down. ### Testing Each machine was started up. The desktop was logged into via the regular user. Three of the desktop terminals were opened. xterm was never used, it was always the terminal for that desktop, such as konsole. In one terminal, top was started and M pressed, showing the processes sorted by memory. In another terminal, a simple while loop showed “free -m” every 30 seconds. The third terminal was idle. I then waited 5 minutes. This allowed any startup services to finish. I recorded the final free result, as well as the final top three memory consumers from top. ### Results - Cinnamon - 624 MB Memory used - cinnamon 4.8% / Xorg 2.2% / dnfdragora 1.8% - GNOME - 612 MB Memory used - gnome-shell 6.9% / gnome-software 1.8% / ibus-x11 1.5% - KDE - 733 MB Memory used - plasmashell 6.2% / kwin_x11 3.6% / akonadi_mailfil 2.9% - LXDE - 318 MB Memory used - Xorg 1.9% / nm-applet 1.8% / dnfdragora 1.8% - LXQt - 391 MB Memory used - lxqt-panel 2.2% / pcmanfm-qt 2.1% / Xorg 2.1% - MATE - 465 MB Memory used - Xorg 2.5% / dnfdragora 1.8% / caja 1.5% - XFCE - 448 MB Memory used - Xorg 2.3% / xfwm4 2.0% / dnfdragora 1.8% ### Conclusion I will let the numbers speak for themselves. Remember that these numbers are from a default Live install. If you remove, or add services and features, your memory usage will change. But this is a good baseline to look at if you are determining your desktop based on memory consumption. ## ANATOLIY KOTOV “KDE 733 MB Memory used” I usually have 450-500mb ram at startup ## ANATOLIY KOTOV did not notice the “Testing” section then the results from other DE are not clear I got the same results on a bare system without tests ## Norbert J. Very helpful article, especially for users of VMs or older hardware. Many thanks for the effort put into this comparison. In my case also firewalld and sssd_nss are listed as top memory consuming processes on an idle system, but I guess those services are not mentioned because they are common to all Spins. I also wonder what some of the many enabled services on current Fedora installations are good for and which of them can be safely disabled without breaking essential functions. If by chance any documentation exists about this topic a reference would be greatly appreciated. ## Troy Dawson I started testing all the desktops, starting with a minimal install and layering up. With the smaller desktops (awesome, ratpoison, etc..) firewalld and sssd_nss were always in the top three memory consumers. So yes, I have seen that. ## Frederik The only big surprise here is that Cinnamon is heavier than GNOME. Have you done any comparison between running DEs in X versus Wayland? ## Troy Dawson I have. I started testing all the desktops, starting with a minimal install and layering up. With the smaller X desktops (awesome, ratpoison, etc..) X11 was in the top 4 memory consumers. With the smaller wayland desktops, the wayland specific processes were much farther down. ## Edwin Buck I don’t think Cinnamon was ever meant to be an optimization of GNOME, but rather a Windows 95 compatible user interface for those who just couldn’t use their computers without that “start bar”. What is interesting is that all of those “heavy” desktops I keep hearing about are only 30% to 80% heavier than their “lightweight” counterparts. ## Paul M Edwin Buck wrote; I think that the lightweight desktops have become steadily more bloated. ## netnaut Its very interesting test. In time when i had to decide which of desktop enviroments i will use, i decided to use XFCE but when i see your results i think my next enviroment will be LXDE version. Nice test. ## Darlha Thanks for your article. One think I don’t understand is that you menintion that there are 40 desktops but you only list 7. Are the other 33 desktops listed somewhere else? ## Troy Dawson As far as I know, there isn’t a full official list. I got my list started by using dnf search. Searching for “window manager” and “desktop” showed quite a few. But you have to weed through that list to figure out which one’s are real desktops and which ones aren’t. I was originally going to write this article with the smallest memory footprint of all 40 desktops that I found. But that proved too complicated. For the small desktops, having pkgconf or xorg-x11-font-utils installed, changed the memory footprint by 10 Meg. I would put the list here, but I still haven’t tested if each of those 40 are real desktops. Perhaps that would be a good next article for me. The list of desktops in Fedora, along with some minor things about the desktop. ## John I know i3wm is not desktop but a window manager but only takes 230MB ## Troy Dawson This depends on the definition of a desktop. Sometimes the definitions of “window manger” and “desktop” can be blurry. In the past, you were able to setup KDE to use the icewm as it’s window manager. But you can also run IceWM by itself. My definition of a desktop is if you can run it by itself. It may or may not have certain features, but if it run’s by itself, I consider it a desktop. That being said, yes, i3 was one of the “desktops” that I tested when I was trying to test all 40 desktops, and it certainly had a smaller memory footprint. ## hammerhead corvette If i3wm is not a desktop, neither is Gnome. In my humble opinion that is… Simply because neither have a traditional “desktop” ## icywind Many people think Gnome uses much more memory than other desktops because Gnome system monitor shows cashed memory as used. ## Pat Kelly This is Great! Knowing everything you can about the choices before choosing is a very good thing. When I first starting using Fedora, Gnome was and still is sort of the “flagship” desktop. I stuck with it because of that. At the time I wasn’t used to this type of desktop, but in the spirit of trying new things I got to like it. That status sort of assures that it gets lots of care in the form of updates and bug fixes. I think it’s great that the spins exist. Flagships usually evolve slowly so they don’t disturb the environment for the users too much. The spins can evolve faster as I think is demonstrated by the fact that there are so many of them. They can also provide indicators of directions that might be good for the flagship to go. ## Shadilay Cinnamon became buffy 🙁 KDE looking and feeling better than ever. ## Ivan All of these (except for KDE) seem like underestimates. Maybe it’s my hardware, maybe it’s because I’m not waiting on startup processes, but I get memory usage of about 1.1 GB idle on Fedora’s live USB ## Troy Dawson I only used the live usb as a means to install on a hard drive. After it was installed on the hard drive I made sure the live usb wasn’t on the system. If you are running just the live usb, it is going to use more memory. The live usb, running as a live usb, does alot more memory caching. I’m not sure of all the settings, but it is running read-only, and I believe tuned for slower disks. ## Mark Memory used is a good start in comparing them, thanks for the post and the effort involved in testing them all. I would be interested in the number of running processes each desktop environment spawns as well should you ever feel tempted to redo the tests one day. On a F31 ‘server’ without Gnome or any desktop packages installed running 3 KVM systems, a webserver, bacula and lots of other stuff. 4 core + 8Gb mem ory, 2 external encrypted disks and an encypted internal one. [mark@vmhost1 snort]# ps -ef | wc -l 190 [mark@vmhost1 ~]$ ps -ef | grep ‘[’ | wc -l 119 On a F31 desktop with Gnome intsalled logged onto the GUI desktop with no applications other than one terminal window open, plus a bacula, synergy and puppet client. All other prcesses are default services. 8 core + 32Gb memory. 1 external encrypted disk and an encypted internal one. [mark@vmhost3 ~]$ ps -ef | wc -l 349 [mark@vmhost3 ~]$ ps -ef | grep ‘[’ | wc -l 160 I assume processes within [ ] in a ps display are system processes (lots of kworker etc) and should be subtracted to get around 71 processes I have probably had a hand in starting on the server and on the desktop 189 extra processes some of which I may have had a hand in starting. While Gnome alone starts more processes than just those with gdm in the name a quick count of those alone gives me [mark@vmhost3 ~]$ ps -ef | grep gdm | wc -l 49 Plus there will be all the sockets and udp pipes etc the GUI components chat to each other across, so desktop resource usage cannot be measured just by memory, although none have as great an impact as memory. Without a GUI desktop on a KVM instance ‘server’ I have running no major apps other than nagios and a puppet client the total memory usage is just 172Mb, always seems strange to me that a GUI user interface needs more memory at idle than the entire working operating system does. Having said that I have found any attempt to run ‘dnf update’ in a kvm with less than 500mb assigned is eventually killed by the out of memory handler. Does anyone other than me remember the old days when fedora would run the Linux OS plus a full GUI desktop and all the tools flawlessly on a machine with 256Mb of memory. ## Chicken Try repeating the test with at least two cores and 8 Gb or Ram. (A more likely set up). Who uses one core and 4Gb of Ram? You do realise that most OS’s will grab as much memory as they can to run smoother. ## Paul M And then install and run Google Chrome and watch it soak up another four gigabytes of RAM ## anon ” Each virtual machine had 1 CPU, 4GB of memory” Yeah, cause that’s a standard set up. What is this 2000? You know full well that if you did the same test with 8Gb of memory that Gnome would grab more. ## Troy Dawson Don’t I wish I could have afforded a desktop with those specs back in 2000. 🙂 But more seriously, the reason I started looking at desktop memory footprints was because I wanted a desktop running on a raspberry pi, and similar machines. For those machines, 4GB is huge. There have been many reading this article that have thought the same thing as what you stated. So, for GNOME, I have re-ran the test in various configurations. NOTE1: It has been a month since I originally ran my test. After updates, gsd-xsettings is now in the top 3 memory users. gnome-shell usage is also higher. You will notice that none of these runs got down to the original gnome memory usage. NOTE2: gnome-software memory usage has been all over the place. From 40M to 180M. It also doesn’t drop off after 5 or 10 minutes either. Because these tests were testing the differences between amount of memory, and number of CPU’s, I would reboot the virtual machine until gnome-software memory usage was the same. GNOME: 1 CPU, 4Gig memory — 634 MB Memory used — gnome-shell 7.2% / gnome-software 1.8% / gsd-xsetting 1.5% / ibus-x11 1.5% GNOME: 2 CPU, 4Gig memory — 645 MB Memory used — gnome-shell 7.2% / gnome-software 1.8% / gsd-xsetting 1.5% / ibus-x11 1.5% GNOME: 1 CPU, 8Gig memory — 632 MB Memory used — gnome-shell 3.6% / gnome-software 0.9% / gsd-xsetting 0.7% / ibus-x11 0.7% GNOME: 2 CPU, 8Gig memory — 647 MB Memory used — gnome-shell 3.6% / gnome-software 0.9% / gsd-xsetting 0.7% / ibus-x11 0.7% So, it looks like the amount of memory used, does not increase with amount of memory available. It also looks like the number of CPU’s might increase the amount of memory used, but it’s so close, that I couldn’t definitely say that, without more and better tests. ## Gareth Jones Okay, at the opposite end of the spectrum, here’s Gnome/Wayland running on a 64 GiB Threadripper 2950X (16 cores with SMT), 5 minutes idle after log-in: $ free -h total used free shared buff/cache available Mem: 62Gi 1.6Gi 58Gi 50Mi 2.9Gi 60Gi Swap: 8.0Gi 0B 8.0Gi Top processes: 0.4 % gnome-shell 0.3 % gnome-software 0.2 % epiphany-search (???) This is a net-install F30, dnf upgraded to F31, with some customizations (btrfs on LUKS, extra software installed, mostly dev tools), so not very scientific. I guess the 5K monitor bumps up gnome-shell memory usage more than anything else. ## james sparks LXDE is a vital element to acheive maximum performance with minimal use of resources. Thank you Fedora for the LXDE spin! ## KDE Fan Akonadi is inflating KDE’s usage – not many distros install/start akonadi by default so it’s not really fair to include that. IIRC it uses full mysql DB install. ## Troy Dawson I too am a KDE fan. I also never run akonadi on my desktop. So it was really hard for me to put those numbers up there. But, the Fedora 31 KDE live image installs, and turns on, akonadi. Maybe in Fedora 32 things will change, but with what I tested, those were the results. ## svsv sarma Please don’t go by memory usage alone. Memory is not a big thing at all in today’s systems. A desktop should be pleasing and easy to work on also. ## Cornel Panceac I think not only the memory footprint is important but also the I/O and of course CPU should be counted in. Probably this is why, on a slow Pentium D525 computer with 2 GB of RAM, the LXQT feels faster than LXDE, XFCE or (god forbid) GNOME. Unfortunately, the request for adding I/O data to the GNOME system monitor was just ignored at the time of request. It would have provided interesting insights on how much packagekit and tracker impacts the rotational disks performance in Gnome (or how much of SSD data is used for these two performance hitters). And yes, to answer indirectly to a question above, i still remember starting my first desktops in slackware 1.0 on 4 MB of RAM, or running Starcraft in Wine in Gnome on a system with Pentium 200 MMX and 64 MB of RAM. And also i still see new releases claiming they are faster then the previous ones … ## El Venas gruesas Están pero si bien pendejos como KDE 733 megas? Díganle a Federico Mena que mejor se ponga las pilas el cabrón y vean la forma de que gnome no se la como doblada, La Memoria ram ## noots Interesting, looks like GNOME has been optimized! My desktop benchmarks (with all my customizations installed) when idle are as follows: Gnome – ~1.8GB Cinnamon – ~1.1GB XFCE (Debian) – ~700MB LXQT (Ubuntu) – ~700MB Each includes nm-applet, firewalld, avahi, ntp, CUPS etc running. ## Andy What gtk+ version is the current LXDe using? gtk+2 or gtk+ 3? ## eeee w3m ? simple x-windows and twm ? ## JCjr I’ve been looking at SwayWM on Wayland for a simpler desktop than GNOME. I just wish setup was easier. There’s some docs on the the Github page that detail some of the ways to make it a usable desktop (adding a launcher and utilities, etc.) as well as some [conflicting/outdated] documentation from the Arch docs, but it still looks like a lot of manual work to make it functional. Anybody using it as their daily-driver? ## Paul M can you try this as a desktop: https://www.nongnu.org/ratpoison/ and reports its memory usage? I know it’s not strictly a desktop, but it gives you a substitute for a window manager. ## Mohamed I’m using i3wm and polybar, I would like to know the memory footprint of it, how can I do that? Thank you ## Esteban Wilson good article! Appreciate the reported metrics for the respective desktops. Comes in handy to know the footprints when trying to virtualize GUI applications. Been using xvfb+joe+x11vnc. Another small footprint is xvfb+icewm++x11vnc. LXDE works also. Always good to see article like this. ## Tom Kidd I don’t like the part about “KDE” as it is I think incorrect. First of all desktop is Plasma 5 and not KDE… KDE is just a brand for community which makes software, so KDE is people, and piece of software is Plasma 5. Brand re-positioning happen over 10 years ago: https://dot.kde.org/2009/11/24/repositioning-kde-brand And having “KDE – 733 MB Memory used” clearly states that some kind of bloatware was in the system. On fresh install KDE Plasma consumes on my system no more than 400MB of RAM. ## Troy Dawson You are correct. The Fedora Spins page clearly says “KDE Plasma Desktop”. I should have used that full name. Just using KDE was lazy of me. As for the bloatware, it’s akonadi. When you install the Fedora 31 KDE Plasma Live Spin to your machine, the entire akonadi suite is turned on. In the article, I only show the first akonadi component, but there was over 10 components running, and 4 of them were using as much memory as akonadi_mailfil.
11,734
为什么 Vim 爱好者喜欢 Herbstluftwm Linux 窗口管理器
https://opensource.com/article/19/12/herbstluftwm-linux-desktop
2020-01-01T07:30:00
[ "Herbstluftwm", "Vim" ]
https://linux.cn/article-11734-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。如果你是 Vim 爱好者,请试试 Herbstluftwm,这是一个受到 “Vim 方式”启发的平铺式 Linux 窗口管理器。 > > > ![](/data/attachment/album/201912/31/215943pisvzwkm8mvsefhm.jpg) 每个人都喜欢 Vim(除了 Dvorak 和 Emacs 用户)。Vim 非常流行,它不仅仅是个编辑器,还有整个都使用 Vim 键绑定来浏览网页的 Web 浏览器,在非常流行的 [Zsh](https://opensource.com/article/19/9/getting-started-zsh) 终端仿真器中也有 Vim 模式。此外,还有一个名为 [herbstluftwm](https://herbstluftwm.org) 的窗口管理器,它部分模仿了 “Vim 方式”。Herbstluftwm 取消了窗口,而是在程序载入和使用时使用平铺的贴片或者象限代替。你可以使用键盘(`Alt+h`、`Alt+j`、`Alt+k` 和 `Alt+l`)从一个平铺贴片移动到另一个平铺贴片。 可以从发行版软件仓库安装 Herbstluftwm。安装后,请退出当前桌面会话,以便可以登录到新会话。默认情况下,会话管理器(KDM、GDM、LightDM 或 XDM,具体取决于你的设置)将继续登录到以前的桌面,因此在登录之前必须覆盖它。 在 GDM 中: ![](/data/attachment/album/201912/31/220406m2qcbhyx1sxqty1g.jpg) 在 SDDM 中: ![](/data/attachment/album/201912/31/220408i828z7acu4r6czgw.jpg) ### Herbstluftwm 桌面之旅 第一次登录 Herbstluftwm 时,你只会看到一个绿屏,边缘有深绿色边框。你所看到的是初始的平铺贴片,其中没有加载任何应用程序。要启动默认应用,请按 `Alt+Enter`。 ![](/data/attachment/album/201912/31/220408onnsddtdc9td9dk4.png "Herbstluftwm") 文档中强调使用 `$HOME/.config/herbstluftwm/autostart` 作为登录时启动重要应用的配置文件。对于不必在每次登录时启动的应用,可以使用 xterm 作为启动守护进程。与往常一样,在命令后加一个 `&` 符号会将 shell 的控制权返回给你。例如,要启动 Emacs: ``` % emacs & ``` 这将在新的平铺贴片中启动 Emacs 窗口,然后返回命令行。 ![Emacs running in Herbstluftwm](/data/attachment/album/201912/31/220412ctgt6opwgi8g0zg1.jpg "Emacs running in Herbstluftwm") #### 切换平铺贴片 要从一个平铺贴片移动到另一个平铺贴片,请使用经典的 `h`、`j`、`k` 或 `l` 与 `Alt` 的 Vim 导航组合键。例如,要从终端切换到其下方的平铺贴片中的应用(即屏幕底部),请按 `Alt+j`。要返回,请按 `Alt+k`。左移和右移分别为 `Alt+h` 和 `Alt+l`。 #### 分割屏幕 你可以使用 `Alt+o` 垂直分割屏幕,使用 `Alt+u` 水平分割屏幕。 要删除空白平铺贴片,请移动到该平铺贴片,然后按 `Alt+r`。 ### 配置 herbstluftwm 除了 `Alt` 键绑定外,你还可通过 `herbstclient` 命令与 Herbstluftwm 进行通信。此命令可以在 shell 中交互,或者你可在配置文件中保留你的首选项。 你可以查看 Herbstluftwm 中的所有可用属性: ``` $ herbstclient attr ``` Herbstluftwm 的默认行为定义在其默认配置文件中,你可以将其复制到你的家目录并进行修改。启动后,Herbstluftwm 执行配置文件中包含的命令。例如,你觉得使用以 `Alt` 为中心的键绑定很笨拙(它传统上是应用内保留快捷键),那你可以在配置文件中更改触发 Herbstluftwm 操作的键: ``` % mkdir ~/.config/herbstluftwm % cp /usr/xdg/herbstluftwm/autostart ~/.config/herbstluftwm % sed -i 's/Mod=Mod1/Mod=Mod4/' ~/.config/herbstluftwm % herbstclient reload ``` 这将使 Herbstluftwm 的修饰键更改为 `Super` 键(“Windows” 或 “Tux” 键,具体取决于你的键盘)。 使用 `autostart` 文件,你可以设置自定义键绑定,为特定类型的应用创建标签,以便以一致的方式平铺应用,并执行更多操作。 ### 为何你要尝试 herbstluftwm Herbstluftwm 是一个平铺窗口管理器的很好例子。它默认平铺窗口,并允许用户定义全局规则的例外。它使用类似 Vim 的导航方式,但可以快速简单地覆盖它。它可能是你一直在寻找的平铺管理器,所以请马上尝试一下。 --- via: <https://opensource.com/article/19/12/herbstluftwm-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Everybody loves Vim (aside from Dvorak and Emacs users). Vim is so popular that there are entire web browsers dedicated to navigating the web with Vim keybindings, a Vim mode in the wildly popular [Zsh](https://opensource.com/article/19/9/getting-started-zsh) terminal emulator, and even a text editor. There's also a window manager called [herbstluftwm](https://herbstluftwm.org) that models itself partly after the "Vim way." Herbstluftwm does away with windows, as such, and replaces them with tiles, or quadrants, into which applications are loaded and used. You use the keyboard (**Alt+h**, **Alt+j**, **Alt+k**, and **Alt+l**) to navigate from one tile to another. ![Herbstluftwm Herbstluftwm](https://opensource.com/sites/default/files/uploads/advent-herbsluftwm.png) Install herbstluftwm from your distribution's software repository. After installing it, log out of your current desktop session so you can log into your new one. By default, your session manager (KDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. With GDM: ![](https://opensource.com/sites/default/files/advent-gdm_1.jpg) With SDDM: ![](https://opensource.com/sites/default/files/advent-kdm_0.jpg) ## Herbstluftwm desktop tour The first time you log into herbstluftwm, you are greeted with nothing but a green screen with a darker green border around the edges. What you're seeing is the initial tile with no application loaded into it. To start the default application, xterm, press **Alt+Return**. The documentation emphasizes the **$HOME/.config/herbstluftwm/autostart** configuration file as a way to start important applications when you log in. For applications you don't necessarily want to start every time you log in, you can use xterm as your launch daemon. As usual, placing an ampersand (**&**) symbol after the command returns control of the shell to you. To start Emacs, for instance: `% emacs &` This launches an Emacs window in a new tile and returns you to a prompt. ![Emacs running in Herbstluftwm Emacs running in Herbstluftwm](https://opensource.com/sites/default/files/uploads/advent-herbsluftwm-emacs.jpg) ### Switching tiles To move from one tile to another, use the classic Vim navigation combination of **h**, **j**, **k**, or **l**, along with the **Alt** key. For example, to switch from the terminal to an application in a tile below it (i.e., at the bottom of the screen), press **Alt+j**. To navigate back up, **Alt+k**. Left and right navigations are **Alt+h** and **Alt+l**, respectively. ### Split screen You can manually split a screen vertically with **Alt+o** and horizontally with **Alt+u**. To remove an empty tile, navigate into it and press **Alt+r**. ## Configuring herbstluftwm Aside from the **Alt** keybindings, you communicate with herbstluftwm through the **herbstclient** command. This command can be used interactively from a shell, or you can preserve your preferences in a configuration file. You can view all attributes available in Herbstluftwm with: `$ herbstclient attr` Herbstluftwm's default behavior is defined in the default config file, which you can copy to your home directory and modify. Upon launch, herbstluftwm executes the commands contained in the config file. For instance, if you find it awkward to use keybindings centered around the **Alt** key, which is traditionally a key reserved for in-application shortcuts, you can change the key used to trigger herbstluftwm actions in the config file: ``` % mkdir ~/.config/herbstluftwm % cp /usr/xdg/herbstluftwm/autostart \ ~/.config/herbstluftwm % sed -i 's/Mod=Mod1/Mod=Mod4/' ~/.config/herbstluftwm % herbstclient reload ``` This changes the herbstluftwm modifier to the Super key (the "Windows" or "Tux" key, depending on your keyboard). Using the autostart file, you can set custom keybindings, create tags for applications of a specific type so you can tile applications in a consistent way, and do much more. ## Why you need to try herbstluftwm Herbstluftwm is a fine example of a tiling window manager. It tiles windows by default and lets the user define exceptions to global rules. It uses Vim-like navigation but allows for quick and easy overrides. It's very likely the tiling manager you've been looking for, so try it soon. ## 2 Comments
11,735
如何使用 Ansible 同步 GitHub 和 GitLab
https://opensource.com/article/19/11/how-host-github-gitlab-ansible
2020-01-01T10:40:59
[ "GitHub", "GitLab" ]
https://linux.cn/article-11735-1.html
> > 通过使用 Ansible 镜像 Git 存储库,保护对重要项目的访问。 > > > ![](/data/attachment/album/202001/01/104040fbdu68wosg8o99wg.jpg) 开源无处不在。它在家里的计算机上、在工作场所的计算机上、在互联网上,并且很多都由 [Git](https://opensource.com/resources/what-is-git) 管理。由于 Git 是分布式的,因此许多人也将其视为一种众包的备份解决方案。从理论上讲,每当有人将 Git 存储库克隆到其本地计算机时,他们就创建了该项目源代码的备份。如果有 100 个人这样做,则存储库就有 100 个备份副本。 从理论上讲,这可以缓解“灾难”的影响,例如当项目维护者[突然决定删除存储库](https://github.com/AntiMicro/antimicro/issues/3)或[莫名其妙地阻止所有流量](https://opensource.com/article/19/10/how-community-saved-artwork-creative-commons),导致开发人员们无头苍蝇般地寻找谁拥有主分支的最新版本。类似的,整个代码托管站点也会消失。没有人会想到 Google Code、Microsoft CodePlex 或 Gitorious 会在鼎盛时期将被关闭。 简而言之,如果在过去的几十年中互联网教给了我们一些东西,那就是依靠互联网神奇地创建备份并不是冗余的最可靠途径。 此外,对于许多人来说,很多开源项目都托管在 GitHub 上是个问题 —— GitHub 并不是开放平台。许多开发人员和用户都希望支持诸如 GitLab 之类的堆栈并与之交互,它具有开源社区版本。 ### 使用 Ansible 管理 Git Git 的去中心方式对于解决这个问题很有用。使用纯 Git,你可以使用一个 `push` 命令轻松地将其推到两个或多个存储库。但是,为了使其在发生意外故障时有用,你必须经常与 Git 存储库进行交互(特别是推送)。此外,即使你可能永远不会自己推送或拉出代码,也可能有一些要备份的存储库。 但是,使用 Ansible,你可以自动执行项目主分支(或其他任何分支)的 Git 拉取,然后自动进行存储库到“异地”镜像的 Git 推送。换句话说,你可以让你的计算机定期从 GitHub 拉取并推送到 GitLab 或 [Gitolite](https://opensource.com/article/19/4/server-administration-git) 或 Gitea(或你喜欢的任何 Git 托管主机)。 ### Ansible 模块 如果不是因其出色的模块集合,那么 Ansible 就没那么出色。像 Python 的第三方库或 Linux 的应用程序一样,这个技术引擎的一个有用而令人惊讶的简单技巧是,Ansible 以其他人贡献的组件而闻名。因为本文正在研究如何有效和可靠地备份 Git 存储库,所以这里使用的模块是 [Git 模块](https://docs.ansible.com/ansible/latest/modules/git_module.html)和 [ini\_file](https://docs.ansible.com/ansible/latest/modules/ini_file_module.html) 模块。 首先,创建一个名为 `mirror.yaml` 的文件作为<ruby> 剧本 <rt> playbook </rt></ruby>。你可以像通常使用 Ansible 一样,从 `name` 和 `task` 条目开始。本示例将 `localhost` 添加到 `hosts` 列表中,以便在控制器计算机(你现在坐在前面的计算机)上运行<ruby> 动作 <rt> play </rt></ruby>,但是在现实生活中,你可能会在特定的主机或一组网络上的主机上运行它。 ``` --- - name: "Mirror a Git repo with Ansible" hosts: localhost tasks: ``` ### Git 拉取和克隆 如果要进行备份,则需要最新代码的副本。明显,在 Git 仓库中实现这一目标的方法是执行 `git pull`。 但是,`pull` 会假定克隆已经存在,而写得很好的 Ansible 动作(Ansible 脚本)则尽可能少的假定。最好告诉 Ansible 先克隆存储库。 将你的第一个任务添加到剧本: ``` --- - name: "Mirror a Git repo with Ansible" hosts: localhost vars: git_dir: /tmp/soso.git tasks: - name: "Clone the git repo" git: repo: 'https://github.com/ozkl/soso.git' dest: '{{ git_dir }}' clone: yes update: yes ``` 这个例子使用了开源的、类似于 Unix 的操作系统 soso 作为我要镜像的存储库。这是一个完全任意的选择,绝不意味着我对该存储库的未来缺乏信心。它还使用变量来引用目标文件夹 `/tmp/soso.git`,这很方便,并且如果以后你希望将它扩展为一个通用的镜像脚本也会受益。在现实生活中,你的工作机上可能会比 `/tmp` 具有更永久的位置,例如 `/home/gitmirrors/soso.git` 或 `/opt/gitmirrors/soso.git`。 运行你的剧本: ``` $ ansible-playbook mirror.yaml ``` 首次运行该剧本时,Ansible 会正确检测到 Git 存储库在本地尚不存在,因此将其克隆。 ``` PLAY [Ansible Git mirror] ******** TASK [Gathering Facts] *********** ok: [localhost] TASK [Clone git repo] ************ changed: [localhost] PLAY RECAP *********************** localhost: ok=2 changed=1 failed=0 [...] ``` 如果你再次运行该剧本,Ansible 会正确检测到自上次运行以来没有任何更改,并且会报告未执行任何操作: ``` localhost: ok=2 changed=0 failed=0 [...] ``` 接下来,必须指示 Ansible 将存储库推送到另一个 Git 服务器。 ### Git 推送 Ansible 中的 Git 模块不提供 `push` 功能,因此该过程的一部分是手动的。但是,在将存储库推送到备用镜像之前,你必须具有一个镜像,并且必须将镜像配置为备用<ruby> 远程服务器 <rt> remote </rt></ruby>。 首先,必须将备用的远程服务器添加到 Git 配置。因为 Git 配置文件是 INI 样式的配置,所以你可以使用 `ini_file` Ansible 模块轻松地添加所需的信息。将此添加到你的剧本: ``` - name: "Add alternate remote" ini_file: dest={{ git_dir }}/.git/config section='remote \"mirrored\"' option=url value='[email protected]:example/soso-mirror.git' tags: configuration ``` 为此,你必须在目标服务器上有一个空的存储库(在本例中为 [GitLab.com](http://GitLab.com))。如果需要在剧本中创建目标存储库,可以按照 Steve Ovens 的出色文章《[如何使用 Ansible 通过 SSH 设置 Git 服务器](https://opensource.com/article/17/8/ansible-environment-management)》来完成。 最后,直接使用 Git 将 HEAD 推送到备用远程服务器: ``` - name: "Push the repo to alternate remote" shell: 'git --verbose --git-dir={{ git_dir }}/.git push mirrored HEAD' ``` 像往常一样运行该剧本,然后使该过程自动化,这样你就不必再次直接运行它了。你可以使用变量和特定的 Git 命令来调整脚本以适应你的需求,但是通过常规的拉取和推送操作,可以确保驻留在一台服务器上的重要项目可以安全地镜像到另一台服务器上。 这是完整的剧本,供参考: ``` --- - name: "Mirror a Git repository with Ansible" hosts: localhost vars: git_dir: /tmp/soso.git tasks: - name: "Clone the Git repo" git: repo: 'https://github.com/ozkl/soso.git' dest: '{{ git_dir }}' clone: yes update: yes - name: "Add alternate remote" ini_file: dest={{ git_dir }}/.git/config section='remote \"mirrored\"' option=url value='[email protected]:example/soso-mirror.git' tags: configuration - name: "Push the repo to alternate remote" shell: 'git --verbose --git-dir={{ git_dir }}/.git push mirrored HEAD' ``` --- via: <https://opensource.com/article/19/11/how-host-github-gitlab-ansible> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Open source is everywhere. It's in your computer at home, it's in your computer at work, it's on the internet, and a lot of it is managed with [Git](https://opensource.com/resources/what-is-git). Because Git is decentralized, many people also think of it as a kind of crowdsourced backup solution. The theory is that each time someone clones a Git repository to their local computer, they are creating a backup of the project's source code. If 100 people do that, then there are 100 backup copies of a repository. This, in theory, mitigates "disasters" such as a project maintainer [suddenly deciding to remove a repository](https://github.com/AntiMicro/antimicro/issues/3) or [inexplicably blocking all traffic](https://opensource.com/article/19/10/how-community-saved-artwork-creative-commons) and leaving developers scrambling to figure out who has the latest version of the master branch. Similarly, entire code-hosting sites have disappeared in the past. Nobody anticipated the closure of Google Code, Microsoft CodePlex, or Gitorious when they were at their peak. In short, if the internet has taught us anything over the past few decades, it's that relying on the internet to magically create backups isn't the most reliable road to redundancy. Besides, it's a problem for a lot of people that many open source projects are hosted on GitHub, which is not an open platform. Many developers and users would prefer to support and interact with a stack such as GitLab, which has an open source community edition. ## Using Ansible for Git Git's decentralization is useful in solving this problem. Using pure Git, you can easily push to two or more repositories with a single **push** command. However, for that to be useful against unexpected failure, you must be interacting (and pushing, specifically) with a Git repository frequently. Furthermore, there may be repositories out there that you want to back up, even though you may never push or pull the code yourself. But using Ansible, you can automate Git pulls of a project's master branch (or any other branch, for that matter) and then automate Git pushes of the repository to an "offsite" mirror. In other words, you can have your computer regularly pull from GitHub and push to GitLab or [Gitolite](https://opensource.com/article/19/4/server-administration-git) or Gitea (or whatever Git host you prefer). ## Ansible modules There wouldn't be much to Ansible if it weren't for its excellent collection of modules. Like third-party libraries for Python or applications for Linux, the technical *driver* of the useful and surprisingly easy tricks Ansible is famous for are the parts that other people have already figured out for you. Because this article is tackling how to effectively and reliably backup a Git repository, the modules used here are the [Git module](https://docs.ansible.com/ansible/latest/modules/git_module.html) and the [ini_file](https://docs.ansible.com/ansible/latest/modules/ini_file_module.html) module. To begin, create a file called **mirror.yaml** to serve as the playbook. You can start mostly as you usually do with Ansible, with **name** and **task** entries. This example adds **localhost** to the **hosts** list so that the play runs on the controller machine (the computer you're sitting at right now), but in real life, you would probably run this on a specific host or group of hosts on your network. ``` --- - name: "Mirror a Git repo with Ansible" hosts: localhost tasks: ``` ## Git pull and clone If you're going to make a backup, then you need a copy of the latest code. The obvious way to make that happen with a Git repository is to perform a **git pull**. However, **pull** assumes that a clone already exists, and a well-written Ansible *play* (an Ansible script) assumes as little as possible. It's better to tell Ansible to **clone** a repository first. Add your first task to your playbook: ``` --- - name: "Mirror a Git repo with Ansible" hosts: localhost vars: git_dir: /tmp/soso.git tasks: - name: "Clone the git repo" git: repo: 'https://github.com/ozkl/soso.git' dest: '{{ git_dir }}' clone: yes update: yes ``` This example uses the open source, Unix-like operating system **soso** as the repository I want to mirror. This is a completely arbitrary choice and in no way implies a lack of confidence in this repository's future. It also uses a variable to refer to the destination folder, **/tmp/soso.git**, which is convenient now and also beneficial later should you want to scale this out to be a generic mirroring script. In real life, you would probably have a more permanent location than **/tmp**, such as **/home/gitmirrors/soso.git** or **/opt/gitmirrors/soso.git**, on your worker machine. Run your playbook: `$ ansible-playbook mirror.yaml` The first time you run the playbook, Ansible correctly detects that the Git repository does not yet exist locally, so it clones it. ``` PLAY [Ansible Git mirror] ******** TASK [Gathering Facts] *********** ok: [localhost] TASK [Clone git repo] ************ changed: [localhost] PLAY RECAP *********************** localhost: ok=2 changed=1 failed=0 [...] ``` Should you run the playbook again, Ansible correctly detects that there have been no changes since the last time it was run and it reports that no actions were performed: `localhost: ok=2 changed=0 failed=0 [...]` Next, Ansible must be instructed to push the repository to another Git server. ## Git push The Git module in Ansible doesn't provide a **push** function, so that part of the process is manual. However, before you can push the repo to an alternate mirror, you have to have a mirror, and you have to configure the mirror as an alternate remote. First, you must add an alternate remote to your Git configuration. Because the Git config file is an INI-style configuration, you can use the **ini_file** Ansible module to append the required information easily. Add this to your playbook: ``` - name: "Add alternate remote" ini_file: dest={{ git_dir }}/.git/config section='remote \"mirrored\"' option=url value='[email protected]:example/soso-mirror.git' tags: configuration ``` For this to work, you must have an empty repository on your destination server (in this case, [GitLab.com](http://GitLab.com)). If you need to create destination repositories in your playbook, you can do that by following Steve Ovens' excellent article "[How to use Ansible to set up a Git server over SSH](https://opensource.com/article/17/8/ansible-environment-management)." Finally, use Git directly to push HEAD to your alternate remote: ``` - name: "Push the repo to alternate remote" shell: 'git --verbose --git-dir={{ git_dir }}/.git push mirrored HEAD' ``` Run the playbook as usual, and then automate the process so that you never have to run it directly again. You can adjust the script with variables and specific Git commands to suit your needs, but with regular pulls and pushes, you can be sure that an important project that lives on one server is safely mirrored on another. Here is the full playbook for reference: ``` --- - name: "Mirror a Git repository with Ansible" hosts: localhost vars: git_dir: /tmp/soso.git tasks: - name: "Clone the Git repo" git: repo: 'https://github.com/ozkl/soso.git' dest: '{{ git_dir }}' clone: yes update: yes - name: "Add alternate remote" ini_file: dest={{ git_dir }}/.git/config section='remote \"mirrored\"' option=url value='[email protected]:example/soso-mirror.git' tags: configuration - name: "Push the repo to alternate remote" shell: 'git --verbose --git-dir={{ git_dir }}/.git push mirrored HEAD' ``` ## 5 Comments
11,737
10 个提高 Git 技能的资源
https://opensource.com/article/19/12/git-resources
2020-01-02T09:40:16
[ "Git" ]
https://linux.cn/article-11737-1.html
> > 年末总结一下 Git 的最佳表现。以下是告诉你可以在新的一年中以新奇的方式使用 Git 的十篇文章。 > > > ![](/data/attachment/album/202001/02/093934q5ifu46u4nuq4lgi.jpg) 2019 年过去了,是时候回顾一下我们(opensource.com)今年发表的有关 Git 的前 10 篇文章了。 这些文章包括从用例和教程到一些非常有趣的(甚至有些非常规的)使用 Git 的方法。所有这些文章都可以帮助你提高 Git 技能,但是,如果你确实需要 Git 入门介绍,请务必查看我们的《[Git 入门:术语入门](https://opensource.com/article/19/2/git-terminology)》文章,并下载我们的 [Git 备忘单](https://opensource.com/downloads/cheat-sheet-git)。 1. Molly de Blanc 写的《[GNOME 项目如何使用 Git](https://opensource.com/article/19/10/how-gnome-uses-git)》考察了 GNOME 项目采用的自托管 GitLab 实例的做法,该实例作为 GNOME 项目集中保存对 GNOME 做出的贡献的位置。De Blanc 从事于非编码职位,因此她的文章还探讨了切换到 GitLab 如何使主要角色不是编写代码的贡献者受益。 2. Ahmad Awais 写的《[Emoji-Log:编写 Git 提交信息的新方法](/article-10627-1.html)》解释了如何使用 Emoji-Log(一种直白的、开源的 Git 提交日志标准)来编写更好、更用户友好的 Git 提交消息。本文概述了 Emoji-Log 背后的理论以及可添加到 `.bashrc`、`.zshrc` 或 `.gitconfig` 中的配置示例,以便你快速开始使用 Emoji-Log。 3. 在《[用 Git 管理你的每日行程](/article-11320-1.html)》中,Seth Kenlon 解释了如何使用 Git 来管理日历。通过结合 Org 模式、Git 和其他一些工具,Kenlon 描述了如何创建可在设备之间同步的基于 Git 的日历工作流。 4. 《[用 Git 作为聊天应用的后端](/article-11342-1.html)》,Seth Kenlon 探索了另一种使用 Git 的非常规方式。在本文中,他探讨了 GIC,这是一个用 Node.js 编写的聊天客户端,其中 Git 用作后端数据库。GIC 是一个概念验证模型,不是供产品环境使用的东西,但是它提供了一个有趣的示例,说明了使用 Git 的真正独特方法。 5. Alan Formy-Duval 的《[Git 学习实用练习](https://opensource.com/article/19/5/practical-learning-exercise-git)》是一份他为提高 Git 技能而努力的编年史。他分享了自己的经验,以使其他人受益于他所学,而 Git 新手将从这篇对 Git 核心功能的出色概述中受益匪浅。 6. 《[用 Git 帮助写作者更好地完成工作](/article-11499-1.html)》的作者 Seth Kenlon 着眼于写作者如何从基于 Git 的工作流中受益。本文介绍了如何使用 Git 和 Atom 利用 Markdown 进行书写。通过遵循本文中的示例,写作者可以轻松地将复杂的版本控制系统添加到其编写工作流中。 7. Sachin Patil 在《[如何使用 Magit 管理 Git 项目](https://opensource.com/article/19/1/how-use-magit)》中,解释了如何使用 Emacs 的 Magit 扩展来管理 Git 存储库。本文提供了有关如何在 Emacs 中执行一系列关键 Git 任务的清晰示例。这些示例带有说明各种任务的屏幕截图。 8. 《[把“点文件”放到版本控制中](/article-11419-1.html)》的作者 Matthew Broberg 演示了如何使用 Git 存储放在主目录中的点文件。将你的点文件存储在 Git 存储库中,可以更轻松地在计算机之间共享系统配置,并且,如果你愿意的话,也可以与其他人共享配置。这篇文章也有不要共享哪些文件的警告,因为共享错误的点文件会将其暴露给其他人。 9. Austin Dewey 的《[4 种用于 Git 加密的机密管理工具](https://opensource.com/article/19/2/secrets-management-tools-git)》在本文中比较了 Git-crypt、BlackBox、SOPS 和 Transcrypt,研究了在 Git 中存储机密的工具。本文涵盖四个主要领域:支持的加密类型、每个项目的目标、项目的工作流和差异以及其他功能。 10. Seth Kenlon 的《[使用 Git 管理 Git 服务器](https://opensource.com/article/19/4/server-administration-git)》解释了如何使用 Gitolite 管理 Git 服务器。Gitolite 是使用 Git 来管理 Git 服务器的“管理杂项的后端应用程序”。本文演示了如何安装、配置和使用 Gitolite,并提供了清晰的示例详细说明了该过程的每个步骤。 --- via: <https://opensource.com/article/19/12/git-resources> 作者:[Joshua Allen Holm](https://opensource.com/users/holmja) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
As we near the end of 2019, it is time to look back at the top 10 articles we published about Git this year. These articles range from use cases and tutorials to some very interesting, if somewhat unconventional, ways to use Git. All of these articles can help you improve your Git skills, but if you really need a Git 101 introduction, be sure to check out our * Getting started with Git: Terminology 101* article and download our [Git cheat sheet](https://opensource.com/downloads/cheat-sheet-git). - by Molly de Blanc looks at the GNOME project’s adoption of a self-hosted GitLab instance as the GNOME project’s centralized location for contributing to GNOME. De Blanc works in a non-coding position, so her article also explores how the switch to GitLab benefits contributors whose primary role is not writing code.[How GNOME uses Git](https://opensource.com/article/19/10/how-gnome-uses-git) - Ahmad Awais’ explains how to use Emoji-Log, "a straightforward, open source Git commit log standard," to write better, more user-friendly, Git commit messages. The article contains an overview of the theory behind Emoji-Log and configuration examples that can be added to[Emoji-Log: A new way to write Git commit messages](https://opensource.com/article/19/2/emoji-log-git-commit-messages)**.bashrc, .zshrc, or .gitconfig**to quickly start using Emoji-Log. - In , Seth Kenlon explains how to use Git to manage your calendar. By combining Org mode, Git, and a few other tools, Kenlon describes how to create a Git-based calendar workflow that can be synced across devices.[Manage your daily schedule with Git](https://opensource.com/article/19/4/calendar-git) - by Seth Kenlon explores another unconventional way to use Git. In this article, he explores GIC, which is a chat client written in Node.js with Git functioning as the backend database. GIC is proof of concept, not something intended for production use, but it provides an interesting example of a really unique way to use Git.*Use Git as the backend for chat* - Alan Formy-Duval’s is a chronicle of his effort to improve his Git skills. He shares his experience for others to benefit from what he learned, and Git novices will gain a lot from this excellent overview of Git’s core functionality.[A practical learning exercise for Git](https://opensource.com/article/19/5/practical-learning-exercise-git) - by Seth Kenlon looks at how writers can benefit from a Git-based workflow. The article explains how to use Git and Atom to write using Markdown. By following the examples in this article, writers can easily add a complex revision control system to their writing workflow.[How writers can get work done better with Git](https://opensource.com/article/19/4/write-git) - In , Sachin Patil explains how to use Emacs’ Magit extension to manage Git repositories. The article provides clear examples of how to perform a selection of key Git tasks inside Emacs. The examples are supported by screenshots illustrating the various tasks.[How to use Magit to manage Git projects](https://opensource.com/article/19/1/how-use-magit) - by Matthew Broberg shows how to use Git to store the dotfiles in your home directory. Storing your dotfiles in a Git repository makes it easier to share your system configuration between computers and, if you so choose, share your configurations with others. The article does come with a warning about what not to share because sharing the wrong dotfiles can expose others.[Move your dotfiles to version control](https://opensource.com/article/19/3/move-your-dotfiles-version-control) - Austin Dewey’s compares Git-crypt, BlackBox, SOPS, and Transcrypt in this article examining tools for storing secrets in Git. The article covers four major areas: encryption types supported, the goals of each project, the projects’ workflows and differences, and other features.[4 secrets management tools for Git encryption](https://opensource.com/article/19/2/secrets-management-tools-git) - by Seth Kenlon explains how Gitolite can be used to manage a Git server. Gitolite is "a backend application managing the fiddly bits" involved in using Git to manage a Git server. The article demonstrates how to install, configure, and use Gitolite, with clear examples detailing each step the process.[Run a server with Git](https://opensource.com/article/19/4/server-administration-git) ## Comments are closed.
11,738
如何在 LibreOffice Writer 中创建一个电子书章节模板
https://opensource.com/article/17/10/creating-ebook-chapter-template-libreoffice-writer
2020-01-02T10:29:40
[ "电子书" ]
https://linux.cn/article-11738-1.html
> > 将电子书分成几章,创建电子书会更容易。这是设置模板的分步指南。 > > > ![](/data/attachment/album/202001/02/102817vmflleeemehetblt.jpg) 对于很多人来说,使用 word 程序来撰写和发布一本电子书是一种最好的、最容易的、最熟悉的方法。但是,启动你的 word 程序和打字是不够的 —— 你需要遵循一种格式。 这就是模板的来源。一个模板确保你的电子书有一个一致的外观和体验。幸运的是,创建模板是快速和容易的,并你在其上花费的时间和努力将带给你一本更好感观的书。 在这篇文章中,我将陪伴你走过如何使用 LibreOffice Writer 创建一个简单的模板,可以用于一本电子书的各个章节。你可以将这个模板用于 PDF 和 EPUB 书籍,并加以修改来满足你的需要。 ### 我的方法 为什么我着重于为一个章节创建一个模板,而不是为一整本书创建一个模板?因为编写和管理单独的章节比编写和管理单个庞大而僵化的文档更容易。 通过关注于单独的章节,你可以专心于你需要编写的东西。你可以很容易地四处移动这些章节,给审阅者发单独一章节比发送你的完整原稿更简单而高效。当你写完一章后,你可以简单地把你的章节拼凑在一起来出版这本书(我将在下面讨论如何做到这一点)。但是不要觉得你被这种方法所束缚 —— 如果你更喜欢在单个文件中编写,简单地调整在这篇文章中描述的步骤就行。 让我们开始吧。 ### 设置页面 仅当你计划发布你的电子书为一本 PDF 书时,这是很重要的。设置页面意味着你的书将不包含大量的跨越屏幕的让眼睛疲劳的文本。 选择 **格式 > 页面** 来打开 **页面样式** 窗口。我的 PDF 电子书通常是 5x8 英寸高(大约 13x20cm ,对于我们这些生活在米制世界的人来说)。我也设置页边距为半英寸(约 1.25 cm)。这些是我较喜欢的尺寸;你可以使用任何适合你的尺寸。 ![LibreOffice Page Style window](/data/attachment/album/202001/02/102943sfzufzwoumskwojo.png "LibreOffice Page Style window") *在 LibreOffice Writer 中的页面样式窗口让你设置页边距和页格式。* 接下来,添加页脚以显示页码。保持页面样式窗口打开着,并单击 **页脚** 选项卡。选择 **在页脚上** 并单击 **确定** 。 在该页面上,在页脚中单击,然后选择 **插入 > 字段 > 页码**。不要担心页码的位置和外观;我们接下来会处理。 ### 设置你的样式 像模板本身一样,样式为你的文档提供一种一致的外观和体验。如果你想更改一个标题的字体或大小,例如,你只需要在一个地方完成它,而不是手动应用格式化到每个标题。 标准化的 LibreOffice 模板带有许多样式,你可以调整它们以适应你的需要。为此,按 `F11` 来打开 **样式和格式** 窗口。 ![LibreOffice styles and formatting](/data/attachment/album/202001/02/102945qt38x00x3ghgsc5h.png "LibreOffice styles and formatting window") *使用样式和格式窗口更改字体和其它细节。* 在一个样式上右键单击,并选择 **修改** 来编辑它。 这里是我在每本中使用的主要样式: | 样式 | 字体 | 间距 / 对齐方式 | | --- | --- | --- | | 标题 1 | Liberation Sans, 36 pt | 上面 36 pt ,下面 48 pt ,左对齐 | | 标题 2 | Liberation Sans, 18 pt | 上面 12 pt ,下面 12 pt ,左对齐 | | 标题 3 | Liberation Sans, 14 pt | 上面 12 pt ,下面 12 pt ,左对齐 | | 正文 | Liberation Sans, 12 pt | 上面 12 pt ,下面 12 pt ,左对齐 | | 页脚 | Liberation Sans, 10 pt | 居中对齐 | ![LibreOffice styles in action](/data/attachment/album/202001/02/102946q28l5z9lt921to1q.png "Example of LibreOffice styles") *这是当我们应用到电子书内容时的一个选择的样式外观。* 对于大多数书来说,这通常是最小要求。可以随便更改字体和空格来适应你的要求。 根据你正在编写书的类型,你可能也想创建或修改项目符合样式,以及数字列表、引号、代码示例、数字符号等等。只需要记住始终如一地使用字体以及其大小。 ### 保存你的模板 选择 **文件 > 另存为** 。在保持对话框中,从格式列表中选择 “ODF 文本文档模板 (.ott)” 。这将保存模板为一个模板,以后你可以快速调用该模板。 保存模板的最佳位置是 LibreOffice 模板文件夹。例如,在 Linux 中,那是在你的家目录下,在 `.config/libreoffice/4/user/template` 下。 ### 编写你的书 在你开始编写前,在你的计算机上创建一个文件夹,它将为你的书保存所有的文件 —— 章节、图像、笔记等等。 当你准备编写时,启动 LibreOffice Writer 并选择 **文件 > 新建 > 模板** 。然后从列表中选择你的模板,并单击 **打开**。 ![LibreOffice Writer template list](/data/attachment/album/202001/02/102948j7sh75vavvmf56o5.png "Template list - LibreOffice Writer") *从你在 LibreOffice Writer 中设置的列表中选择你的模板,并开始编写。* 然后用一个描述性名称保存文档。 建议使用像 “第 1 章” 和 “第 2 章” 这样的惯例 —— 在某些时候,你可能决定重新编排你的章节,当你尝试管理这些章节时,它可能会变得混乱。然而,你可以在文件名称中放置章节数字,像 “第 1 章” 或 “一” 。如果你最后要重新排列全书的章节,像这样重命名更容易。 无需赘言,开始编写吧。记住在模板中使用样式来格式化文本 —— 这就是为什么你要创建模板,对吧? ### 发布你的电子书 在完成编写一堆章节后,并准备发布它们时,创建一个主控文档。把一个主控文档作为你所编写章节的一个容器。使用一个主控文档,你可以快速地组装你的书,并任意重新排序你的章节。LibreOffice 的帮助提供了使用[主控文档](https://help.libreoffice.org/Writer/Working_with_Master_Documents_and_Subdocuments)的详细信息。 假设你想生成一个 PDF ,不要只是单击**直接导出到 PDF** 按钮。这将创建一个相当不错的 PDF ,但是你可能想优化它。为此,选择 **文件 > 导出为 PDF** ,并在 PDF 选项窗口中轻微调整。你可以在这篇 [LibreOffice Writer 文档](https://help.libreoffice.org/Common/Export_as_PDF) 中学到更多东西。 如果你想创建一个 EPUB 而不是一个 PDF,或者除了一个 PDF 以外,另外创建一个 EPUB,请安装 [Writer2EPUB](http://writer2epub.it/en/) 扩展。Opensource.com 的 Bryan Behrenshausen 为这个扩展[分享了一些有用的说明](https://opensource.com/life/13/8/how-create-ebook-open-source-way) 。 ### 结束语 我们在这里创建的模板是极简单的,但是你可以将其用于一本简单的书,或者作为构建一个复杂模板的起点。不管怎样,这个模板都会让你快速地开始编写和发布你的电子书。 --- via: <https://opensource.com/article/17/10/creating-ebook-chapter-template-libreoffice-writer> 作者:[Scott Nesbitt](https://opensource.com/users/scottnesbitt) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
For many people, using a word processor is the fastest, easiest, and most familiar way to write and publish an e-book. But firing up your word processor and typing away isn't enough—you need to follow a format. That's where a template comes in. A template ensures that your book has a consistent look and feel. Luckily, creating a template is quick and easy, and the time and effort you spend on it will give you a better-looking book. In this article, I'll walk you through how to create a simple template for writing individual chapters of an e-book using LibreOffice Writer. You can use this template for both PDF and EPUB books and modify it to suit your needs. ## My approach Why am I focusing on creating a template for a chapter rather than one for an entire book? Because it's easier to write and manage individual chapters than it is to work on a single monolithic document. By focusing on individual chapters, you can focus on what you need to write. You can easily move those chapters around, and it's less cumbersome to send a reviewer a single chapter rather than your full manuscript. When you've finished writing a chapter, you can simply stitch your chapters together to publish the book (I'll discuss how to do that below). But don't feel that you're stuck with this approach—if you prefer to write in single file, simply adapt the steps described in this article to doing so. Let's get started. ## Setting up the page This is important only if you plan to publish your e-book as a PDF. Setting up the page means your book won't comprise a mass of eye-straining text running across the screen. Select **Format > Page** to open the **Page Style** window. My PDF e-books are usually 5x8 inches tall (about 13x20cm, for those of us in the metric world). I also set the margins to half an inch (around 1.25 cm). These are my preferred dimensions; use whatever size suits you. ![LibreOffice Page Style window LibreOffice Page Style window](https://opensource.com/sites/default/files/images/life-uploads/lo-page-style.png) The Page Style window in LibreOffice Writer lets you set margins and format the page. Next, add a footer to display a page number. Keep the Page Style window open and click the **Footer** tab. Select **Footer on** and click **OK**. On the page, click in the footer, then select **Insert > Field > Page Number**. Don't worry about the position and appearance of the page number; we'll take care of that next. ## Setting up your styles Like the template itself, styles provide a consistent look and feel for your documents. If you want to change the font or the size of a heading, for example, you need do it in only one place rather than manually applying formatting to each heading. The standard LibreOffice template comes with a number of styles that you can fiddle with to suit your needs. To do that, press **F11** to open the **Styles and Formatting** window. ![LibreOffice styles and formatting window LibreOffice styles and formatting](https://opensource.com/sites/default/files/images/life-uploads/lo-paragraph-style.png) Change fonts and other details using the Styles and Formatting window. Right-click on a style and select **Modify** to edit it. Here are the main styles that I use in every book I write: Style | Font | Spacing/Alignment | ---|---|---| Heading 1 | Liberation Sans, 36 pt | 36 pt above, 48 pt below, aligned left | Heading 2 | Liberation Sans, 18 pt | 12 pt above, 12 pt below, aligned left | Heading 3 | Liberation Sans, 14 pt | 12 pt above, 12 pt below, aligned left | Text Body | Liberation Sans, 12 pt | 12 pt above, 12 pt below, aligned left | Footer | Liberation Sans, 10 pt | Aligned center | ![Example of LibreOffice styles LibreOffice styles in action](https://opensource.com/sites/default/files/images/life-uploads/lo-styles-in-action.png) Here's what a selected style looks like when applied to ebook content. That's usually the bare minimum you need for most books. Feel free to change the fonts and spacing to suit your needs. Depending on the type of book you're writing, you might also want to create or modify styles for bullet and number lists, quotes, code samples, figures, etc. Just remember to use fonts and their sizes consistently. ## Saving your template Select **File > Save As**. In the Save dialog box, select *ODF Text Document Template (.ott)* from the formats list. This saves the document as a template, which you'll be able to quickly call up later. The best place to save it is in your LibreOffice templates folder. In Linux, for example, that's in your** /home** directory, under .**config/libreoffice/4/user/template**. ## Writing your book Before you start writing, create a folder on your computer that will hold all the files—chapters, images, notes, etc.—for your book. When you're ready to write, fire up LibreOffice Writer and select **File > New > Templates**. Then select your template from the list and click **Open**. ![Template list - LibreOffice Writer LibreOffice Writer template list](https://opensource.com/sites/default/files/images/life-uploads/lo-template-list.png) Select your template from the list you set up in LibreOffice Writer and begin writing. Then save the document with a descriptive name. Avoid using conventions like *Chapter 1* and *Chapter 2*—at some point, you might decide to shuffle your chapters around, and it can get confusing when you're trying to manage those chapters. You could, however, put chapter numbers, like *Chapter 1* or *Ch1,* in the file name. It's easier to rename a file like that if you do wind up rearranging the chapters of your book. With that out of the way, start writing. Remember to use the styles in the template to format the text—that's why you created the template, right? ## Publishing your e-book Once you've finished writing a bunch of chapters and are ready to publish them, create a master document. Think of a master document as a container for the chapters you've written. Using a master document, you can quickly assemble your book and rearrange your chapters at will. The LibreOffice help offers detailed instructions for working with [master documents](https://help.libreoffice.org/Writer/Working_with_Master_Documents_and_Subdocuments). Assuming you want to generate a PDF, don't just click the **Export Directly to PDF** button. That will create a decent PDF, but you might want to optimize it. To do that, select **File > Export as PDF** and tweak the settings in the PDF options window. You can learn more about that in the [LibreOffice Writer documentation](https://help.libreoffice.org/Common/Export_as_PDF). If you want to create an EPUB instead of, or in addition to, a PDF, install the [Writer2EPUB](http://writer2epub.it/en/) extension. Opensource.com's Bryan Behrenshausen [shares some useful instructions](https://opensource.com/life/13/8/how-create-ebook-open-source-way) for the extension. ## Final thoughts The template we've created here is bare-bones, but you can use it for a simple book, or as the starting point for building a more complex template. Either way, this template will quickly get you started writing and publishing your e-book. ## 1 Comment
11,741
Darktable 3 发布,带来重新打造的 UI 及新的功能
https://itsfoss.com/darktable-3-release/
2020-01-02T22:23:00
[ "Darktable" ]
https://linux.cn/article-11741-1.html
> > 这是给摄影爱好者的圣诞节礼物。Darktable 3.0 刚刚发布了。 > > > [Darktable](https://www.darktable.org/) 是[在 Linux 上编辑 RAW 图像的最佳应用之一](https://itsfoss.com/raw-image-tools-linux/)。你可以将其视为 [Adobe Lightroom 的自由开源替代品](https://itsfoss.com/open-source-photoshop-alternatives/)。 Darktable 3 是一个主版本更新,它带来了大量的功能改进和重新打造的用户界面。现在,GUI 完全由 GTK+ CSS 规则所控制,这使得整个 GUI 都可定制主题。它默认有八个主题。 借助 3000 多个提交和 553 个拉取请求,新版本修复了 66 个 bug 并添加了许多新功能。 让我们看看这个新版本带来了什么功能。 ### Darktable 3.0 的新功能 ![Darktable 3.0 Screenshot](/data/attachment/album/202001/02/222428zjvnqq13ztlj3qz6.jpg) 以下是重要的新功能: * 重新打造的 UI * 用于处理 3D RGB Lut 变换的新模块 * 对“降噪(轮廓化)”模块进行了许多改进 * 添加了新的“剔除”模式和时间轴视图 * 对“降噪(轮廓化)”模块进行了许多改进 * 新色调均衡器的基本和电影 RGB 模块 * 更好的 4K/5K 显示支持 * 撤消/重做支持更多操作 * 针对 CPU 和 SSE 路径的许多代码优化 * 支持导出到 Google 相册 * 支持更多的相机,白平衡预设和噪点配置 * 大量的 bug 修复和功能改进 你可以在 [GitHub 发行说明](https://github.com/darktable-org/darktable/releases/tag/release-3.0.0)中了解所有更改。 ### 在 Linux 上安装 Darktable 3.0 让我们看看如何获​​取最新的 Darktable 版本。 #### 在基于 Ubuntu 的发行版上安装 Darktable 3.0 Ubuntu 仓库中有 Darktable,但你不能得到马上最新的版本。对于 LTS 版本,它的更新可能需要几个月的时间。 不用担心!Darktable 提供了[自己的 PPA](https://launchpad.net/%7Epmjdebruijn/+archive/ubuntu/darktable-release) 来在基于 Ubuntu 的发行版上安装最新版本。 不幸的是,此 Darktable PPA 尚未随新版本更新。 不用担心了!多亏了我们的朋友 [Ubuntu Handbook 的 Ji M](http://ubuntuhandbook.org/index.php/2019/12/install-darktable-3-0-0-ubuntu-18-04-19-10/),我们有一个非正式的 PPA,可以轻松地在 Ubuntu 和其他基于 Ubuntu 的发行版上安装 Darktable 3.0。 打开终端,并使用这些命令: ``` sudo add-apt-repository ppa:ubuntuhandbook1/darktable sudo apt update sudo apt install darktable ``` #### 卸载 Darktable 3 要删除通过此 PPA 安装的 Darktable,你可以先卸载该应用: ``` sudo apt remove darktable ``` 接着[删除 PPA](https://itsfoss.com/how-to-remove-or-delete-ppas-quick-tip/): ``` sudo add-apt-repository -r ppa:ubuntuhandbook1/darktable ``` #### 在其他 Linux 发行版上安装 Darktable 你可以等待到你的发行版的软件管理器提供新版本。 你也可以从 GitHub 发布页面(位于页面底部)下载 tarball 或所有源代码。 * [下载 Darktable 3.0](https://github.com/darktable-org/darktable/releases/tag/release-3.0.0) 使用 Darktable 3,你可以更好地编辑自己的假期照片:) --- via: <https://itsfoss.com/darktable-3-release/> 作者:[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
11,742
10 篇强化你的安全能力的文章
https://opensource.com/article/19/12/security-resources
2020-01-03T00:44:43
[ "安全" ]
https://linux.cn/article-11742-1.html
> > 无论你是新手还是想要增加技能,这十篇安全文章中都有适合你的内容。 > > > ![](/data/attachment/album/202001/03/004344rco51cnc153ns1zz.jpg) 如果安全是一个过程(确实如此),那么理所当然的,不同的项目(及其贡献者)的情况各有不同。有些应用程序经历了多年的安全测试,由在信息安全领域工作了几十年的人员所设计。而另外一些则是由开发人员在他们的第一个开源项目中开发的全新项目。毫不奇怪,这十大安全文章囊括了代表这一范围的经验。我们有介绍基本安全实践的文章,也有深入探讨更高级主题的文章。 无论你是新手还是想要增加你在传奇职业生涯中获得的技能,2019 年十大安全文章中都有适合你的内容。 ### 《安全强化你的 Linux 服务器的七个步骤》 安全如舍,地基不牢,房屋不稳。Patrick H. Mullins 的杰作《[安全强化你的 Linux 服务器的七个步骤](/article-11444-1.html)》让你从 Linux 服务器的基本安全步骤开始。即使你有很多管理服务器的经验,本文也提供了一个很好的清单以确保你掌握了基础知识。在此基础上,你可以开始添加额外的安全层。 ### 《使用防火墙让你的 Linux 更加强大》 七步捍卫你的 Linux 服务器中的一步即是启用防火墙。但什么**是**防火墙,它是如何工作的呢? Seth Kenlon 在《[使用防火墙让你的 Linux 更加强大](/article-11093-1.html)》一文中回答了这些问题,然后详细描述了为了更好的安全性应如何配置你的防火墙。使用 firewalld 与 Network Manager,你可以为不同的网络设置不同的防火墙配置。例如,这允许你在家庭网络上进行信任配置,并在你最喜欢的咖啡店的 WiFi 网络上进行更多疑的配置。 ### 《用集中日志减少安全风险》 保护系统安全,只有开始,没有结束:安全是一个过程而不是状态。**保持**系统安全工作的一部分即是密切关注所发生的事情。集中化日志是实现这一点的一种方法,尤其是在管理多系统时。在《[减少集中日志的安全风险](https://opensource.com/article/19/2/reducing-security-risks-centralized-logging)》中 Hannah Suarez 分享了要如何开始(她这篇文章基于她在 FOSDEM'19 [自由及开源软件开发者欧洲会议] 中的闪电演讲)。 ### 《在 SSH 中使用 GPG 密钥》 大多数人都会为 SSH 的密钥认证使用 SSH 密钥。为什么不呢?毕竟 SSH 就在名字里。从安全的角度来看,这些方法非常好。但若想简化某些形式的密钥分发与备份还有另一种方法,Brian Exelbierd 的三部曲系列介绍了《[如何启用使用 GPG 子钥的 SSH 访问](https://opensource.com/article/19/4/gpg-subkeys-ssh)》、《[如何导入现有 SSH 密钥](https://opensource.com/article/19/4/gpg-subkeys-ssh-multiples)》、《[如何将备份量减少到单个密钥文件](https://opensource.com/article/19/4/gpg-subkeys-ssh-manage)》 ### 《使用 Seahorse 图形化管理 SSH 密钥》 并不是所有人都喜欢用 GPG 作为 SSH 密钥,但这并不意味着你在密钥管理上会不顺利。Seahorse 是一个在 GNOME 桌面中用于管理 SSH 密钥及其他身份验证方法的图形化工具。Alan Formy-Duval 的《[使用 Seahorse 图形化管理 SSH 密钥》对新手用户特别有帮助。 ### 《安全扫描你的 DevOps 流程》 如今到处都是容器。但它们容纳着什么?了解容器满足你的安全策略是保持安全性的重要部分。幸运的是,你可以使用开源工具来帮助自动化合规检查。Jessica Cherry(原名: Repka)的《[安全扫描你的 DevOps 流程](https://opensource.com/article/19/7/security-scanning-your-devops-pipeline)》是一个循序渐进的教程,向你展示了如何使用 Jenkins 构建系统和 Anchore 检查服务为容器镜像和注册库创建扫描流程。 ### 《4 种开源云安全工具》 云服务的一大优点是你的数据可以从任何地方访问。云服务的一个缺点是你的数据可以从任何地方访问。如果你使用的是 “-as-a-Service”(LCTT 译注: 某某即服务,如 IaaS、PaaS、Saa)产品,那么你需要确保它们是经过安全配置的。Anderson Silva、Alison Naylor、Travis McPeak 和 Rich Monk 联合推出《[4 种开源云安全工具](/article-11432-1.html)》以帮助在使用 GitHub 和 AWS 时提高安全性。如果你正在寻找被不小心提交的机密信息,或尝试从一开始就阻止这些机密信息被提交,这篇文章提供了工具。 ### 《如何使用 OpenSSL:哈希、数字签名等》 许多信息安全是基于数学的:特别是用于加密数据和验证用户或文件内容的加密函数。在《[开始使用 OpenSSL:密码学基础](https://opensource.com/article/19/6/cryptography-basics-openssl-part-1)》中进行介绍后,Marty Kalin 深入讨论了《[如何使用 OpenSSL:哈希、数字签名等](https://opensource.com/article/19/6/cryptography-basics-openssl-part-2)》的细节,解释了如何使用 OpenSSL 实用程序来探索这些常用但不常被理解的概念。 ### 《使用树莓派和 Kali Linux 学习计算机安全》 廉价硬件与开源软件构成了一个很好的组合,特别是对于那些希望边做边学的人来说。在《[使用树莓派和 Kali Linux 学习计算机安全](https://opensource.com/article/19/3/computer-security-raspberry-pi)》这篇文章中,Anderson Silva 介绍了面向安全的 Kali Linux 发行版。这是一篇短文,但它满是关于文档和安全相关项目的有用的链接,你可以在自己的树莓派上使用它们。 ### 《量子计算会打破现有的安全体系吗?》 这篇文章的余下部分是浪费吗?量子计算会让我们对安全的所知变得过时吗?好消息是:回答是否定的,但是量子计算仍然可以在更广泛的范围内对安全和计算世界产生深远的影响。在《[量子计算会打破现有的安全体系吗?](/article-10566-1.html)》一文中,Mike Bursell 剖析了它好坏两方面的影响,当然,量子计算可能会让加密的破解变得更容易,但如果坏人一开始就无法获得你的数据,那也没有关系。 ### 展望 2020 安全永远是重要的,(正如那篇量子计算文章所建议的)未来几年将是该领域的一个有趣时期。在 2020 年,我们的文章将着眼于开源安全的前沿,并帮助向不断增长的开源社区解释基础知识。如果你有一个你想要我们报导的主题,请在评论中分享它,或者更进一步 —— 如果你想写一篇文章,就写给我们吧。 --- via: <https://opensource.com/article/19/12/security-resources> 作者:[Ben Cotton](https://opensource.com/users/bcotton) 选题:[lujun9972](https://github.com/lujun9972) 译者:[nacyro](https://github.com/nacyro) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
If security is a process (and it is), then it stands to reason that different projects (and contributors) are in different places. Some applications have years of security testing, with design done by people who have worked in information security for decades. Others are brand new projects by developers working on their first open source project. It comes as no surprise that Opensource.com's top security articles of 2019 represent this range of experience. We have articles that introduce basic security practices as well as deep dives into more advanced topics. Whether you're learning the first steps or looking to add to your skills acquired over a storied career, there's something for you in the top 10 security articles of 2019. ## 7 steps to securing your Linux server Security is like a house: if the foundation is bad, the rest is at risk. Patrick H. Mullins' excellent * 7 steps to securing your Linux server* gets you started with basic security steps for Linux servers. Even if you have a lot of experience administering servers, this article provides a good checklist to make sure you have the basics covered. From there, you can begin adding additional layers of security. ## Make Linux stronger with firewalls One of the seven steps to securing your server is enabling a firewall. But what *is* a firewall, and how does it work? Seth Kenlon answers these questions and then describes in detail how to configure your firewall for better security in * Make Linux stronger with firewalls*. Using firewalld and Network Manager, you can set different firewall configurations for different networks. This allows you to have a trusting configuration on your home network, for example, and a more paranoid configuration on your favorite coffee shop's WiFi network. ## Reducing security risks with centralized logging Once you've secured your system, you're not done: security is a process, not a state. Part of *keeping* systems secure is keeping an eye on what goes on. One way to do that, especially with multiple systems, is to centralize your logging. In * Reducing security risks with centralized logging*, Hannah Suarez shares how to get started (she based this article on her lightning talk at FOSDEM '19). ## Using GPG keys for SSH Most people who use key-based authentication for SSH use SSH keys. And why wouldn't you? It's right there in the name. These are perfectly fine from a security standpoint, but if you want to make some forms of key distribution and backup easier, there's another way. Brian Exelbierd's three-part series walks through * How to enable SSH access with a GPG subkey*, *, and* [How to import existing SSH keys](https://opensource.com/article/19/4/gpg-subkeys-ssh-multiples)*.* [How to reduce your backup needs to a single key file](https://opensource.com/article/19/4/gpg-subkeys-ssh-manage)## Graphically manage SSH keys with Seahorse Using GPG for SSH keys isn't everyone's cup of tea, but that doesn't mean you're out of luck when it comes to key management. Seahorse is a graphical tool for managing SSH keys (and other authentication methods) that is included in the GNOME desktop. Alan Formy-Duval's [ Graphically manage SSH keys with Seahorse](https://opensource.com/article/19/4/ssh-keys-seahorse), is particularly helpful to the novice user. ## Security scanning your DevOps pipeline Containers are everywhere these days. But what's in them? Knowing that containers meet your security policies is an important part of staying secure. Fortunately, you can use open source tools to help automate compliance checking. Jessica Cherry's (formly Repka) [ Security scanning your DevOps pipeline](https://opensource.com/article/19/7/security-scanning-your-devops-pipeline) is a step-by-step tutorial that shows you how to use the Jenkins build system and the Anchore inspection service to create a scanning pipeline for container images and registries. ## 4 open source cloud security tools One of the great things about cloud services is that your data can be accessed from anywhere. One of the downsides to cloud services is that your data can be accessed from anywhere. If you're using "-as-a-Service" offerings, you want to make sure they're securely configured. Anderson Silva, Alison Naylor, Travis McPeak, and Rich Monk join forces to introduce [ 4 open source cloud security tools](https://opensource.com/article/19/9/open-source-cloud-security) to help improve security when using GitHub and AWS. If you're looking for accidentally committed secrets—or trying to prevent them from being committed in the first place—this article has tools you can use. ## How to use OpenSSL: hashes, digital signatures, and more Much of information security is based on math: specifically, the cryptographic functions used to encrypt data and authenticate users or file contents. After providing an introduction in [ Getting started with OpenSSL: Cryptography basics](https://opensource.com/article/19/6/cryptography-basics-openssl-part-1), Marty Kalin digs deeper into the details of *, explaining how to use the OpenSSL utility to explore these commonly used but uncommonly understood concepts.* [How to use OpenSSL: Hashes, digital signatures, and more](https://opensource.com/article/19/6/cryptography-basics-openssl-part-2)## Learn about computer security with the Raspberry Pi and Kali Linux Cheap hardware and open source software make a great combination, especially for people looking to learn by doing. In this article, Anderson Silva introduces the security-oriented Kali Linux distribution in * Learn about computer security with the Raspberry Pi and Kali Linux*. It's a short article, but it's full of useful links to documentation and security-related projects that you can use with your own Raspberry Pi. ## Will quantum computing break security? Has the rest of this article been a waste? Will quantum computing render everything we know about security obsolete? The good news is that the answer is "no," but quantum computing can still have a profound impact on security and the computing world more broadly. In * Will quantum computing break security?* Mike Bursell examines its potential impacts—both the good news and the bad. And of course, quantum computing may make it easier to break encryption, but that doesn't matter if the baddies can't get your data in the first place. ## Looking to 2020 Security will always be important, and (as the quantum computing article suggests) the next few years will be an interesting time in the field. In 2020, Opensource.com articles will look at the leading edge of open source security and help explain the basics to the ever-growing open source community. If you have a topic you want us to cover, please share it in the comments, or—better yet— if you have an article in mind, [write for us](https://opensource.com/how-submit-article). ## 2 Comments
11,744
Pop!_OS 与 Ubuntu:哪个更棒?
https://itsfoss.com/pop-os-vs-ubuntu/
2020-01-03T08:53:04
[ "Ubuntu" ]
https://linux.cn/article-11744-1.html
好吧,你可能会发现从[最佳 Linux 发行版](https://itsfoss.com/best-linux-distributions/)列表中选择一个发行版很容易,但是,将两个类似的 Linux 发行版进行比较通常会令人困惑,就像 Pop!\_OS 与 Ubuntu 一样。 有趣的是,Pop!\_OS 是基于 [Ubuntu](https://ubuntu.com/) 的。那么,Pop!\_OS 和 Ubuntu 之间有什么区别呢?为什么要从中选择一个呢? 在本文中,我将比较 Pop!\_OS 和 Ubuntu(两者都是我的最爱)。 **注意:**你可能会发现一些武断的观点,而本文只是一份比较的参考。随着 Linux 发行版的不断开发和更新,随着时间的流逝,很多事情都会改变。 ### 比较 Ubuntu 和 Pop!\_OS ![Pop!_OS Vs Ubuntu](/data/attachment/album/202001/03/085307q17bbb7tnn8fd7bb.png) 发现相似之处可帮助你区分其他差异之处。因此,让我们从一些明显的相似之处开始。 就像我提到的,Pop!\_OS 是基于 Ubuntu 之上的 Linux 发行版。因此,当你使用 Pop!\_OS 时,你将获得使用 Ubuntu 的所有好处(从技术上说,其核心是一样的)。 它们都默认带有 [GNOME 桌面环境](https://www.gnome.org/),因此它们具有相似的用户界面(UI)。 在不讨论所有底层差异的情况下,我将在这里重点介绍一些重要的差异。 #### 用户体验及主题 ![Pop!_OS](/data/attachment/album/202001/03/085310zjlcwmgzc7lgyxsx.jpg) 许多用户认为 Pop!\_OS 只是具有不同外观的 Ubuntu。 根据我的经验,我觉得这并非完全正确。 是的,它们俩都很喜欢 [GNOME 桌面环境](https://www.gnome.org/) —— 但是,Pop!\_OS 让人感觉更加优美。 除了外观之外,[Ubuntu 还通过添加程序坞和其他一些小花巧来定制了 GNOME 的体验](https://itsfoss.com/gnome-tricks-ubuntu/)。如果你喜欢定制的 GNOME 体验,可能会发现它更好。 但是,如果你更喜欢纯粹的 GNOME 体验,Pop!\_OS 默认情况下为你提供的就是这样。 在你亲自尝试之前,我无法说服你。但是,Pop!\_OS 中的总体配色方案、图标和主题可以说是令人愉悦的高级用户体验。 这可能是一个主观的事情,但这是我所观察到的。你还可以查看 Ubuntu 19.10 的视频教程,亲自感受一下。 #### 易于安装第三方应用 ![Pop Os PPA](/data/attachment/album/202001/03/085311yzexzprhhxr3ezjy.jpg) Ubuntu 非常重视 Snap 软件包。这增加了它提供的应用程序的数量。 但是 Snap 软件包存在一些重要的问题。它们占用了过多的磁盘空间,并且启动要花费大量的时间。 这就是为什么我更喜欢使用应用程序的 APT 版本的原因。 我为什么要说这个呢? 因为 Pop!\_OS 具有其[自己的官方 PPA](https://launchpad.net/%7Esystem76/+archive/ubuntu/pop/),并已默认启用。你会在此处找到一些有用的应用程序,例如 Android Studio、TensorFlow。无需下载 Android Studio 的 1GB 大的 Snap 程序包。只需使用 [apt-get install](https://itsfoss.com/apt-get-linux-guide/)就可以了。 #### 预装应用 ![Ubuntu installation slideshow](/data/attachment/album/202001/03/085313ozap7jurabzk15h1.jpg) 对于某些人来说,它可能不是最大的问题,但是拥有大量预安装的应用程序可能会影响体验和性能。即使不影响性能,某些用户也只喜欢较少的预装应用程序。 与 Ubuntu 相比,Pop!\_OS 捆绑了更少的默认应用程序(潜在地减少了胖软件)。 再一次提醒,这是主观的看法。如果你希望预安装更多应用程序,则可以考虑使用 Ubuntu 而不是 Pop!\_OS。 #### Snap 软件包支持 ![](/data/attachment/album/202001/03/085313vrqdts8jhjxrrxax.jpg) 对于熟悉 Snap 程序包的用户来说,Ubuntu 的软件中心是比 Pop!\_OS 商店更好的解决方案,因为你可以在软件中心中列出 Snap 程序包。 你无法在软件中心中过滤 Snap 软件包,但是当你在软件中心中发现一个 Snap 软件包(查看应用程序来源的详细信息为 “Snap store”/“Snapcraft”)时安装它就更容易了。 可能你会感到困惑,Pop!\_OS 也确实支持 Snap 软件包。但是,你不会在 Pop!\_OS 商店中找到它们,这是唯一的区别。 如果不确定什么是 Snap 软件包及其功能,可以查看我们的文章《[在 Linux 上安装 Snap 应用](https://itsfoss.com/install-snap-linux/)》。 #### 单独的 NVIDIA/AMD ISO 文件 ![ISOs](/data/attachment/album/202001/03/085314h50wyyzz630xmew0.jpg) 从技术上讲,它不是内部比较的一部分,而是某些用户关心的一个因素。 因此,值得强调的是 Pop!\_OS 提供了单独的 ISO。一个用于带 NVIDIA 显卡的系统,另一个用于带/不带 AMD 显卡的系统。 使用 Ubuntu 19.10,你可以在 Ubuntu ISO 上获得 NVIDIA 驱动程序,但 AMD 显卡没有这个。 #### 可靠性与问题 毫无疑问,这两个[发行版都适合初学者](https://itsfoss.com/best-linux-beginners/),并且相当可靠。如果你想要更好的可靠性和更少的问题,则可能希望一直使用长期支持(LTS)版本。 当出现新版本的 Ubuntu 时,Pop!\_OS 将在其上开发,并有可能解决用户在 Ubuntu 原始发行版上遇到的问题,然后再进行新的升级。这给它们带来了一点优势,但这没什么实质性的不同,因为这些修复最终都可以运用于 Ubuntu。 #### 性能 性能将高度取决于你所安装的内容以及所安装的硬件配置。 除非你有一个超级旧的系统,否则这两个发行版似乎都表现良好。 我的机器是 i5-7400 处理器和 16GB 的 RAM(带有 GTX 1050ti 显卡),我发现两种发行版上的体验都足够好。 当然,你可以手动进行一些优化调整以满足要求——无论它们中的哪个不满足你的硬件配置。 但是,如果你想使用 System76 笔记本电脑,那么 Pop!\_OS 将可以证明自己是 [Linux 领域的苹果](https://www.phoronix.com/scan.php?page=news_item&px=System76-Integrated-Vision),因为 Pop!\_OS 是针对其硬件量身定制的,与 Ubuntu 有所不同。 #### 硬件兼容性 在比较其他 Linux 发行版时,这绝对是要考虑的事情。但是,在这种情况下,实际上并没有太大的区别。 你可能会考虑 Pop!\_OS 一直在使用较新的硬件配置,因为他们主要是为他们的笔记本电脑量身定制具有各种配置的 OS。而且,这只是一个观察,而不是事实。 ### 结语 我知道在不亲自尝试的情况下从两个流行的 Linux 发行版中选择一个并不容易。如果可能的话,我建议你在进行比较的同时尝试两者,以供参考。 你在这两者之间有何选择?我在比较中错过了什么吗?在下面的评论中让我知道。 --- via: <https://itsfoss.com/pop-os-vs-ubuntu/> 作者:[Ankush Das](https://itsfoss.com/author/ankush/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Well, you might find it easy to pick one from the list of [best Linux distributions](https://itsfoss.com/best-linux-distributions/). However, it is often confusing to compare two similar Linux distros, just like Pop!_OS vs Ubuntu. Interestingly, Pop!_OS is based on [Ubuntu](https://ubuntu.com/). So, what is the difference between Pop!_OS and Ubuntu? Why should you choose one over other? In this article, I’m going to compare Pop!_OS and Ubuntu (both of which happen to be my favorites). **Note:** *You might find some of the points opinionated, this article is just a reference for the comparison. With constant developments and updates to Linux distros, a lot can change over time.* ## Comparing Ubuntu and Pop!_OS ![Pop Os Vs Ubuntu](https://itsfoss.com/content/images/wordpress/2019/12/pop_os_vs_ubuntu.png) Spotting the similarity helps you distinguish other differences. So, let me start noting down some of the obvious similarities. Like I mentioned, Pop!_OS is a Linux distribution on top of Ubuntu. So, you get all the benefits of using Ubuntu (technically the same thing at its core) when you use Pop!_OS. They both ship with the [GNOME desktop environment](https://www.gnome.org/) by default and hence they feature a similar user interface (UI). Without going into all the under-the-hood differences, I will be highlighting some important ones here. ### User Experience & Theming ![Pop Os Ui](https://itsfoss.com/content/images/wordpress/2019/11/pop-os-UI.jpg) A lot of users think that Pop!_OS is just Ubuntu with a different skin. From my experience, I’ll mention that it is not entirely true. Yes, they both rock [GNOME desktop environment](https://www.gnome.org/) – however, Pop!_OS just feels more polished. In addition to the look and feel, [Ubuntu customizes the GNOME experience](https://itsfoss.com/gnome-tricks-ubuntu/) by adding a dock and a few more tricks. You might find it better if you like a customized GNOME experience. But, if you prefer a pure GNOME experience, Pop!_OS gives you that by default. I cannot convince you enough until you try it out for yourself. But, the overall color scheme, icons, and the theme that goes on in Pop!_OS is arguably more pleasing as a superior user experience. It can be a subjective thing – but it is what I observed. You can also check out the video tour for Ubuntu 19.10 to check it out for yourself: ### Ease of Installing Third-Party Apps ![Pop Os Ppa](https://itsfoss.com/content/images/wordpress/2019/11/pop-os-ppa.jpg) Ubuntu puts a lot of emphasis on Snap packages. This greatly increases the number of application it offers. But there are some issues with Snap packages. They take too much of disk space and they take a lot of time to start. This is why I prefer using the APT version of any application. Why am I telling you this? Because Pop!_OS has its [own official PPA](https://launchpad.net/~system76/+archive/ubuntu/pop/) which is enabled by default. You’ll find some useful applications like Android Studio, TensorFlow in here. You can use [apt-get install](https://itsfoss.com/apt-get-linux-guide/) and get these tools. Do note that they might not be packages well. Android Studio PPA downloads the entire tarball and then extracts it on the system. Of course, you can [use the same PPA](https://itsfoss.com/ppa-guide/) on a regular Ubuntu as well and take advantage of it. ### Pre-installed Applications ![Install Ubuntu Linux On Intel Nuc 14 Tutorial](https://itsfoss.com/content/images/wordpress/2019/08/install-ubuntu-linux-on-intel-nuc-14_tutorial-800x516.jpg) It may not be the biggest deal-breaker for some but having a lot of pre-installed apps could affect the experience and performance. Even if it does not affect the performance – some users just prefer fewer pre-installed apps. Pop!_OS comes bundled with fewer default apps (potentially less bloatware, if I may call it that) when compared to Ubuntu. Yet again, this is something subjective because if you want no bloatware, Ubuntu has the Ubuntu Minimal options that comes with only the bare essentials so that you can choose which application to install. ### Snap Package Support ![Snapcraft](https://itsfoss.com/content/images/wordpress/2019/11/snapcraft.jpg) For users comfortable with the snap packages, Ubuntu’s software center is a slightly better solution to Pop!_OS shop because you can have snap packages listed right in your software center. You cannot filter the snap packages in the software center but it will be easier to install a snap package when you notice one (look at the details for the source of the app as ‘*Snap store*‘ / ‘*Snapcraft*‘) in the Software Center. Pop!_OS does support snap packages as well – if you’re confused. But, you won’t find them through the Pop!_OS shop, that’s the only difference here. If you are not sure what a snap package is and what it does, you can check out our article on [installing snap apps on Linux](https://itsfoss.com/install-snap-linux/). ### Separate NVIDIA/AMD ISO File ![Iso Amd Nvidia Pop Os](https://itsfoss.com/content/images/wordpress/2019/11/iso-amd-nvidia-pop-os.jpg) Technically, it isn’t a part of the comparison internally but it is a factor that some users care for. So, it is worth highlighting that Pop!_OS provides separate ISOs. One for the systems with NVIDIA graphics card and another for systems with/without AMD graphics. With Ubuntu 19.10, you get NVIDIA drivers on the Ubuntu ISO but there is no such thing for AMD graphics. ### Reliability & Issues Unquestionably, both the [distributions are beginner-friendly](https://itsfoss.com/best-linux-beginners/) and quite reliable. You might want to hold on to a Long Term Support (LTS) release if you want better reliability and fewer issues. When a new version of Ubuntu comes up, Pop!_OS works on it and potentially fixes the issues that users encounter on Ubuntu’s original release before making the new upgrade available. This gives them a slight edge but that’s nothing substantial because those fixes eventually reach Ubuntu. ### Performance The performance will highly depend on what you have installed and the hardware configuration you install it on. Unless you have a super old system, both distributions seem to perform very well. I’m rocking an i5-7400 processor coupled with 16 Gigs of RAM (with a GTX 1050ti Graphics Card) and I find the experience good enough on both the distros. Of course, you could manually do a few optimization tweaks to fit your requirements – if either of them does not work out for your hardware configuration. But, if you want to get your hands on a System76 laptop, Pop!_OS will prove to be [the Apple of Linux space](https://www.phoronix.com/scan.php?page=news_item&px=System76-Integrated-Vision) because Pop!_OS has been tailored for their hardware, unlike Ubuntu. ### Hardware Compatibility This is definitely something to consider when comparing other Linux distributions. However, in this case, there’s really no significant difference. Pop!_OS has custom tweaks to suit their own range of [Linux laptops and desktops](https://itsfoss.com/get-linux-laptops/). If you have got a System76 machine, Pop!_OS should definitely be your choice. **Wrapping Up** Ubuntu is an evergreen distribution that is not hardware centric. Pop!_OS on the other hand is a distribution tailored for System76 hardware. I know it’s not easy to choose one among the two popular Linux distro without trying them out. If it’s a possibility, I’ll recommend you to give them both a try while keeping this comparison for reference. What’s your choice between these two? Did I miss something in the comparison? Let me know in the comments below.
11,745
轻松使用 Linux Equinox 桌面环境
https://opensource.com/article/19/12/ede-linux-desktop
2020-01-03T17:43:53
[ "Equinox" ]
https://linux.cn/article-11745-1.html
> > 本文是 24 天 Linux 桌面特别系列的一部分。EDE 不是最迷人、最小或效率最高的桌面。但它的柔和、安宁让人平静,它让人感到熟悉舒缓,它的图标主题也很有趣。 > > > 我还没有认真用过 Fast Light Toolkit([FLTK](https://www.fltk.org/)),但我是 C++ GUI 工具箱的粉丝,它非常易于学习,并且即使进行更新也很可靠。当我发现有一个用 FLTK 构建的桌面环境时,我很想尝试一下,并且我很快为我的决定感到高兴。[Equinox 桌面环境(EDE)](https://sourceforge.net/projects/ede/) 是用 C++ 和 FLTK 为 Unix 桌面编写的快速、简单的桌面环境。它使用通用的桌面约定,因此外观和感觉都非常熟悉,并且在使用几天后,我发现它的简单性提供了我所喜欢的最低限度的优雅。 ![EDE desktop](/data/attachment/album/202001/03/174400p89hyv66jh6zq6sn.jpg "EDE desktop") ### 安装 EDE 你可能会发现 EDE 包含在发行版的软件仓库中,但你也可以在它的 [SourceForge 仓库](http://ede.sf.net)中找到它。如果你已经在运行其他桌面环境,你可以安全地在同一系统上安装 EDE,因为它仅带来了一些额外的应用,这些应用程序特定于 EDE,因此它们不会妨碍你的其他桌面。 EDE 只是桌面环境,它使用 [Pekwm](https://opensource.com/article/19/12/pekwm-linux-desktop) 窗口管理器来处理布局。 安装 EDE 之后,注销当前的桌面会话,以便你可以登录到新的会话。默认情况下,会话管理器(KDM、GDM、LightDM 或 XDM,取决于你的设置)将继续登录到以前的桌面环境,因此你必须在登录之前覆盖该桌面环境。 在 GDM 中: ![](/data/attachment/album/202001/03/174402uo5lx3mooz633tmx.jpg) 在 SDDM 中: ![](/data/attachment/album/202001/03/174403xhzim8n8z0ugmuhn.jpg) 首次启动 EDE 时,可能会提示你确认一些启动任务。在我的 Slackware 工作站上,KDE 将某些服务标记为启动任务(例如 HPLIP 打印监视器和蓝牙守护程序),并且 EDE 在一个确认框中显示了它们。 ![Importing desktop services in EDE](/data/attachment/album/202001/03/174404lm6tt9h6mva9hzfz.jpg "Importing desktop services in EDE") 设置一次后,你无需再次进行设置。 ### EDE 桌面之旅 EDE 的布局恰恰是大多数人在桌面上所期望的布局:左侧的应用菜单、中间的任务栏、右侧的系统托盘。这是标准的现成布局,不会让任何人感到困惑。这是一个可以安全地装在 Linux 上并且可以自信地给任何没有使用过 Linux 的人使用的桌面。他们将以舒适的方式很快地适应这个桌面。 你可以单击鼠标右键打开一个小型桌面菜单。这可以让你在桌面上创建应用启动器、创建文件夹并设置一些主题选项。 屏幕底部的面板是可伸缩的,因此你可以根据需要在全屏模式下工作。单击屏幕右下角的时钟来调出日历和时区设置。 EDE 有一个小的配置应用,可用于设置一些简单的选项: * 背景和图标设置 * 屏幕保护程序设置 * 时间和时钟 * 系统铃声 * 键盘 * 偏好应用 ![EDE Configuration Place](/data/attachment/album/202001/03/174406mxvi3sgj45neg5x4.jpg "EDE Configuration Place") EDE 的功能不多。没有文件管理器、文本编辑器、绘画程序或纸牌游戏。你必须安装你想在桌面运行的程序。这意味着你可以从各种各样的 Linux 应用中进行选择,并使用你最喜欢的。 ### EDE 总结 我发现 EDE 至少作为一种“假日”桌面而言,它的简单性令人舒适。它值得一看。它不是最迷人的桌面,也不是最精简的、也不是最高效的。但它的柔和、安宁让人平静,它让人感到熟悉舒缓,并且它的图标主题充满乐趣和生气。EDE 是一个以其缓慢而稳定的步调而自豪的桌面。 如果你想放松心情使用一个干净和令人愉悦的界面,请试试 EDE。 --- via: <https://opensource.com/article/19/12/ede-linux-desktop> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
I haven't used the Fast Light Toolkit ([FLTK](https://www.fltk.org/)) for anything serious yet, but I'm a fan of the C++ GUI toolkit that's pretty simple to learn and (in my experience) reliable even across updates. When I found out that there was a desktop environment built with FLTK, I was eager to try it—and I was quickly glad I did. The [Equinox Desktop Environment (EDE)](https://sourceforge.net/projects/ede/) is a fast and simple desktop written in C++ and FLTK for Unix desktops. It uses common desktop conventions, so it looks and feels familiar right away, and after only a few days of using it, I found its simplicity provides a minimal elegance that I enjoy. ![EDE desktop EDE desktop](https://opensource.com/sites/default/files/uploads/advent-ede.jpg) ## Installing EDE You are likely to find EDE included in your distribution's software repository, but you can also find it in its [SourceForge repository](http://ede.sf.net). If you're already running a different desktop, it's safe to install EDE on the same system because it brings along just a few extra applications, which are specific to EDE so they won't get in your way on other desktops. EDE is only the desktop, and it uses the [Pekwm](https://opensource.com/article/19/12/pekwm-linux-desktop) window manager to handle layout. After installing EDE, log out of your current desktop session so you can log into your new one. By default, your session manager (KDM, GDM, LightDM, or XDM, depending on your setup) will continue to log you into your previous desktop, so you must override that before logging in. With GDM: ![](https://opensource.com/sites/default/files/advent-gdm_2.jpg) With SDDM: ![](https://opensource.com/sites/default/files/advent-kdm_1.jpg) When EDE first boots, you might be prompted to confirm some startup tasks. On my Slackware workstation, KDE had marked some services as startup tasks (such as the HPLIP print monitor and a Bluetooth daemon), and EDE imported them with just one confirmation box. ![Importing desktop services in EDE Importing desktop services in EDE](https://opensource.com/sites/default/files/uploads/advent-ede-init.jpg) After setting it up once, you won't need to do it again. ## EDE desktop tour EDE's layout is exactly what most people expect from a desktop: application menu on the left, taskbar in the middle, system tray on the right. It's the standard off-the-shelf layout that confuses nobody; this is a desktop that's safe to install on a Linux computer and hand over, with confidence, to someone who's never used Linux in their life. They'll fall right into this desktop with a soft and gentle landing. You can bring up a small desktop menu with a right-click. This allows you to make an application launcher on the desktop, create a folder, and set some theme options. The panel at the bottom of the screen is retractable, so you can work full-screen if you prefer. Click the clock in the bottom-right of the screen to bring up a calendar and time-zone settings. EDE has a small Configuration Place application that provides access to a few simple preferences: - Background and icon settings - Screensaver settings - Time and clock - System bell - Keyboard - Preferred applications ![EDE Configuration Place EDE Configuration Place](https://opensource.com/sites/default/files/uploads/advent-ede-conf.jpg) There's not much more to EDE. There's no file manager, no text editor, or paint program, or game of solitaire. You must bring anything you want to run on your desktop. That means you get to pick and choose from the wide array of Linux applications and use whatever you love the most. ## EDE as a statement I found the simplicity of EDE oddly comforting, at least as a kind of "holiday" desktop; it's a nice place to visit. It's not the most glamorous desktop available, nor the most minimal, nor the most efficient. But its soft, muted tones are calming, its familiarity soothing, and its icon theme fun and exuberant. EDE is a desktop that's proud of its slow and steady pace. If you're in the mood to put your feet up and enjoy a clean and pleasant interface, try EDE. ## 3 Comments
11,746
如何把你的老爷机重新利用起来
https://opensource.com/article/19/7/how-make-old-computer-useful-again
2020-01-04T06:41:20
[ "旧计算机" ]
https://linux.cn/article-11746-1.html
> > 按照下面各个步骤,让你的老爷机焕然一新。 > > > ![](/data/attachment/album/202001/04/064017ztl28cn6jjhnjnaj.jpg) 你的地下室里是不是有一台用来落灰的旧电脑?为什么不把它利用起来呢?如果你常用的电脑坏了,又想用一个比手机更大的屏幕上网,这时候一台备用电脑可能就派上用场了。或者,它也可以充当一台全家人共用的廉价备用电脑,甚至还可以改造为一台复古游戏机。 哪怕是一台有十余年历史的老爷机,只要选对了软件,也可以胜任很多新电脑能够完成的任务。其中的关键在于,要使用开源软件。 我进行电脑翻新已经有二十年了。在这篇文章里,我会分享一下电脑翻新的技巧。此处讨论的范围包括双核笔记本,以及机龄在 5 到 12 年之间的台式机。 ### 检查硬件 第一步是检查硬件是否运转正常。如果在这个环节忽略了一个问题,后面可能会让你非常头疼。 灰尘是电子器件的天敌,所以第一件事应该是打开机箱,清除灰尘。[压缩空气设备](https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=compressed+air+for+computers&rh=i%3Aaps%2Ck%3Acompressed+air+for+computers)这时候可能会派上用场。请注意,进行任何接触电脑的操作时,都应该确保[接地](https://www.wikihow.com/Ground-Yourself-to-Avoid-Destroying-a-Computer-with-Electrostatic-Discharge)。此外,**不要**用清洁布擦拭任何东西。即使是一次小到你无法察觉的静电放电,也可能会导致电路损毁。 清洁工作完成之后,关闭机箱,检查是否所有硬件都可以正常工作。需要测试的项目包括: * 内存 * 硬盘 * 主板 * 外围设备(DVD 驱动器、USB 接口、声卡,等等) 首先,将计算机启动界面([UEFI](https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface) 或者是 [BIOS](http://en.wikipedia.org/wiki/BIOS) 界面)上的诊断测试依次运行一遍。如果不知道按哪个功能键进入你电脑的启动界面,可以参考 [这份列表](http://www.disk-image.com/faq-bootmenu.htm)。 此外,也可以使用诸如 [Hirens BootCD](http://www.hirensbootcd.org/download/) 和 [Ultimate Boot CD](http://www.ultimatebootcd.com/) 之类的免费资源工具包,进行启动界面覆盖不到的测试。这些资源工具包涵盖了数百个测试程序,并且都是免费的,尽管不都开源。运行这些工具包无需安装任何软件,因为它们都是从 U 盘或者 DVD 驱动器启动的。 测试一定要彻底!对于内存和硬盘来说,基础测试还不够,应该运行深度测试,哪怕是运行一整夜也无妨。只有这样,才能够查出那些不易发现的瞬时故障。 如果发现了问题,可以参考我的[硬件故障排除快速指南](http://www.rexxinfo.org/Quick_Guide/Quick_Guide_To_Fixing_Computer_Hardware),可以帮你解决最常见的硬件问题。 ### 选择软件 电脑翻新的关键在于,根据手头的硬件资源,恰如其分地安装软件。最核心的三种硬件资源分别是: 1. 处理器(内核数、速度) 2. 内存 3. 显存 可以在启动时的 UEFI/BIOS 界面上,弄清楚你电脑的硬件资源。记得抄下数据,以免遗忘。接下来,可以在 [CPU Benchmark](http://www.cpubenchmark.net/) 网站上查看你的处理器,该网站除了提供 CPU 的背景资料,还提供一个 CPU 的性能分数。 了解了硬件性能之后,就可以选择能够在硬件上高效运行的软件了。软件的选择涉及四个重要的层面: 1. 操作系统(OS) 2. 桌面环境(DE) 3. 浏览器 4. 应用 一个优秀的 Linux 发行版可以满足上述全部四个层面。不要试图使用已经停止维护的 Windows 版本,例如 Windows 8、Vista 或者 XP,哪怕已经安装在电脑上了。恶意软件的[风险](https://askleo.com/unsupported-software-really-mean/)你是承受不起的。明智的做法是,使用一个更抗病毒的最新版本操作系统。 那 Windows 7 呢?[维护宽限期](http://home.bt.com/tech-gadgets/computing/windows-7/windows-7-support-end-11364081315419)至 2020 年 1 月 14 日结束,也就是说,在此日期之前你还可以获得安全补丁,之后就想都别想了。现在正是迁出 Windows 7 的绝佳时机。 Linux 的巨大优势在于,有许多专门为过时硬件设计的[发行版](https://fossbytes.com/best-lightweight-linux-distros/)。此外,[桌面环境](http://en.wikipedia.org/wiki/Desktop_environment)和操作系统在 Linux 的设计中是分开的,你可以自行选择搭配。这一点非常重要,因为桌面环境对低端系统的性能有很大影响。(对于 Windows 和 MacOS 来说,你选择的操作系统版本决定了桌面环境,没得可选。) Linux 的另一个好处是,拥有数以千计自由且开源的应用,不需要担心激活或者许可的问题。此外,Linux 是可移植的,可以在不同的分区、硬盘、设备或计算机之间,对操作系统和应用进行复制、移动或克隆。(Windows 则不然,使用注册表将系统捆绑在了所安装的计算机上。) ### 翻新后的电脑能够做什么? 这里讨论的是大约在 2006 年到 2013 年之间生产的双核计算机,尤其是装载了 [Intel 酷睿 2](https://en.wikipedia.org/wiki/Intel_Core_2) CPU 或 [AMD 速龙 64 X2](https://en.wikipedia.org/wiki/Athlon_64_X2) 系列处理器的计算机。它们的 [CPU 分数](http://www.cpubenchmark.net/) 大多在 1000 到 4000 分之间。这种电脑卖不了几个钱,但用在运行轻量级 Linux 软件上,性能还是足够的。 有一点需要注意:你的电脑应该至少拥有 2 GB 内存,如果不够就进行升级。就我翻新过的电脑来说,使用者用到的内存(不包括数据缓存)一般在 0.5 到 2 GB 之间,很少超过 2 GB。如果将内存升级到 2GB,系统就不至于进行**内存交换**,即将硬盘当做内存使用。如果想要获得良好性能,这一点十分关键。 以我自己为例,我用来写作这篇文章的是一台有十年机龄的翻新电脑。取下 1 GB 内存条之后,它只剩下了 1 GB 内存,然后就慢得像一只乌龟。用它浏览网页,或者是做类似的事情,都让人感到灰心,甚至痛苦。一旦把内存条重新装回去,有了 2 GB 内存,它就立马回到了可以使用的状态。 一台 2 GB 的双核计算机可以满足大多数人的需求,只要安装的是轻量级发行版和浏览器。你可以用它浏览网页、发送电子邮件、编辑文档和电子表格、观看 YouTube 视频、参与 eBay 拍卖竞标、在社交网络上发帖、听播客、查看相簿、管理家庭收支和个人日程、玩游戏,等等。 ### 翻新电脑的局限 那么,这些老爷机又有什么局限呢?由于它们的并发性能比不上最先进的计算机,所以应该使用轻量级浏览器,同时拦截广告(广告正是让网页加载变慢的罪魁祸首)。如果可以使用虚拟专用网络(VPN)拦截广告,为处理器免除加载广告的负荷,那就再好不过。此外,还需要禁用视频自动播放、Flash 以及网页动画效果;将浏览器上的标签页控制在少数几个,不要同时打开 20 个;以及下载可以开启/禁用 JavaScript 的浏览器扩展。 让处理器专注于你目前正在做的事情吧,不要同时打开一堆应用,也不要在后台运行很多程序。图像编辑和视频编辑的高级工具可能会很慢;至于运行虚拟机,还是别想了吧。 那游戏呢?开源软件仓库提供了数以千计的游戏。这就是我为什么将显存列为三种核心硬件资源之一。如果你的电脑没有独立显卡,那很可能只有 32 或者 64 MB 的显存。可以增加一张显卡,将显存提升到 256 或者 512 MB,这样一来,处理器密集型的游戏就会顺畅很多了。如果不确定你的电脑有多少显存,可以参考[这里](http://www.cyberciti.biz/faq/howto-find-linux-vga-video-card-ram/)。请注意,需要确保显卡与电脑的[显卡插槽](https://www.onlinecomputertips.com/support-categories/hardware/493-pci-vs-agp-vs-pci-express-video-cards/)(AGP、PCI-Express 或者 PCI)相匹配,同时使用正确的[连接线](https://silentpc.com/articles/video-connectors)(VGA、DVI 或者 HDMI)。 #### 与 Windows 系统的兼容性如何? 许多人关心 Linux 与 Windows 系统的兼容性如何。首先,对于任何一个 Windows 程序,都有一个 [Linux 版本的替代品](http://wiki.linuxquestions.org/wiki/Linux_software_equivalent_to_Windows_software)。 退一步说,即使你真的必须要运行某个特定的 Windows 程序,通常也可以借助 [Wine](https://en.wikipedia.org/wiki/Wine_%28software%29) 在 Linux 上运行。可以在 [Wine 数据库](https://appdb.winehq.org/) 里查找一下你的应用,看看是否可以在 Wine 上运行,顺便学一些特殊安装技巧。[Winetricks](https://en.wikipedia.org/wiki/Winetricks) 和 [PlayOnLinux](https://en.wikipedia.org/wiki/PlayOnLinux) 这两个辅助工具可以帮助你进行安装和配置。 Wine 的另一个优势是可以运行旧版本 Windows(例如 Vista、XP、ME/98/95 和 3.1)上的程序。我认识一个家伙,搭建了一台特别赞的游戏电脑,然后用来玩 XP 上的老游戏。借助 [DOSBox](https://en.wikipedia.org/wiki/DOSBox),你甚至还可以运行数以千计的[免费 DOS 程序](https://archive.org/details/softwarelibrary_msdos)。但是有一点需要注意,如果 Windows 程序可以运行,那么 Windows [病毒](https://wiki.winehq.org/FAQ#Is_Wine_malware-compatible.3F)也同样可以。你需要保护 Linux 上的 Wine 环境,正如保护任何其他 Windows 环境一样。 对了,与 Microsoft Office 的兼容性又如何呢?我使用的是 LibreOffice,经常编辑并交换 Word 和 Excel 文件,完全没有问题。不过,你应该避免使用隐晦或者过于专业的功能。 ### 如何选择发行版? 假设选择了 Linux 作为操作系统,那么你还需要选择桌面环境、浏览器和各种应用。最简单的方法是,安装一个包含了你所需要的一切的发行版。 通过从 [live USB](https://www.howtogeek.com/howto/linux/create-a-bootable-ubuntu-usb-flash-drive-the-easy-way/) U 盘或者 DVD 启动,你无需安装任何程序,就可以尝试不同的发行版。关于在 Linux 或 Windows 上创建可启动的 Linux 的方法,可以参考[这里](https://unetbootin.github.io/)。 我进行电脑翻新的目的是做慈善,所以无法指望电脑使用者具备任何相应知识。我需要的发行版应该具有以下特性: * 用户友好 * 具有轻量级界面 * 自带各种轻量级应用 * 拥有足够大的软件仓库 * 历史表现良好 * 拥有庞大的用户社区和活跃的论坛 * 通过长期维护版本(而不是滚动发布版本)确保稳定性 * 更重视可靠性,而不是尖端功能 * 可以通过图形化用户界面进行设置,而不是只能通过文本文件进行设置 许多发行版都能够满足上面的要求。我曾经尝试成功的有 [Mint/Xfce](https://linuxmint.com/)、[Xubuntu](https://xubuntu.org/) 和 [Lubuntu](https://lubuntu.me/)。前两个发行版使用 Xfce 桌面环境,第三个使用 LXQt。相比 GNOME、Unity、KDE、MATE 和 Cinnamon 这些桌面环境,运行上面这两种桌面环境只需要[更少](https://www.makeuseof.com/tag/best-lean-linux-desktop-environment-lxde-vs-xfce-vs-mate/)的处理器和内存资源。 Xfce 和 LXQt 用起来非常简单,我的客户们之前从未见过 Linux,但是都可以自如使用这些简单的、菜单驱动的用户界面。 对于旧电脑来说,运行最快速、最高效的浏览器是一件非常重要的事情。[很多人觉得](https://www.zdnet.com/article/chrome-is-the-most-popular-web-browser-of-all/) Chromium 是最好的浏览器;此外,我还安装了 Firefox Quantum,因为大家比较熟悉它,并且[它的性能](https://www.laptopmag.com/articles/firefox-quantum-vs-chrome)可以和 [Chromium 的性能](https://www.zdnet.com/article/just-how-fast-is-firefox-quantum/)媲美。我还加上了 Opera,因为它速度快,而且有一些独特功能,比如内置的广告拦截,以及免费的[虚拟专用网络](http://en.wikipedia.org/wiki/Virtual_private_network)。Opera 是免费的,但并非开源。 无论你使用什么浏览器,一定要拦截广告和追踪器,尽量降低浏览器的负荷。此外,除非得到你的明确批准,否则视频和 Flash 都不应该被允许运行。 至于应用,我使用的是 Mint/Xfce、Xubuntu 和 Lubuntu 自带的轻量级应用。它们足以满足一切需求了。 ### 行动起来吧 你是否会对翻新后的电脑感到满意呢?就我来说,我所使用的两台电脑的机龄都已经超过十年了,其中一个装载的是 Intel 双核处理器([eMachines T5274a](https://www.cnet.com/products/emachines-t5274/specs/)),另一个装载的是 AMD 速龙 64 x2 处理器([HP dc5750](https://community.spiceworks.com/products/7727-hewlett-packard-dc5750-microtower)),两台电脑都有 2 GB 内存。它们和我的另一台具备四核 i5 处理器和 16 GB 内存的电脑一样,完全能够胜任我的办公工作。如果说有什么功能是这两台电脑缺失的,那就是运行虚拟机了。 我们生活在一个非常神奇的年代。只需要付出一点努力,就可以将一台机龄在 5 到 12 年之间的旧电脑,翻新为一台具备实用价值的机器。还有什么比这更有趣吗? --- via: <https://opensource.com/article/19/7/how-make-old-computer-useful-again> 作者:[Howard Fosdick](https://opensource.com/users/howtech) 选题:[lujun9972](https://github.com/lujun9972) 译者:[chen-ni](https://github.com/chen-ni) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Have an old computer gathering dust in your basement? Why not put it to use? A backup machine could come in handy if your primary computer fails and you want to be online with a larger screen than your smartphone. Or it could act as a cheap secondary computer shared by the family. You could even make it into a retro gaming box. You can take any computer up to a dozen years old and—with the right software—perform many of the same tasks you can with new machines. Open source software is the key. I've refurbished computers for two decades, and in this article, I'll share how I do it. We're talking about dual-core laptops and desktops between five and 12 years old. ## Verify the hardware Step one is to verify that your hardware all works. Overlooking a problem here could cause you big headaches later. Dust kills electronics, so open up the box and clean out the dirt. [Compressed air](https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=compressed+air+for+computers&rh=i%3Aaps%2Ck%3Acompressed+air+for+computers) comes in handy. Be careful that you're [grounded](https://www.wikihow.com/Ground-Yourself-to-Avoid-Destroying-a-Computer-with-Electrostatic-Discharge) whenever you touch the machine. And *don't* rub anything with a cleaning cloth. Even a static shock so small you won't feel it can destroy circuitry. Then close the clean computer and verify that all the hardware works. Test: - Memory - Disk - Motherboard - Peripherals (DVD drive, USB ports, sound, etc.) Run any diagnostic tests in the computer's boot panels (the [UEFI](https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface) or [BIOS](http://en.wikipedia.org/wiki/BIOS) panels). [This list](http://www.disk-image.com/faq-bootmenu.htm) tells you which program function (PF) key to press to access those panels for your computer. Free resource kits like [Hirens BootCD](http://www.hirensbootcd.org/download/) or [Ultimate Boot CD](http://www.ultimatebootcd.com/) enable you to test what your boot panels don't. They contain hundreds of testing programs; all are free, but not all are open source. You don't have to install anything to run these kits because they'll boot from a USB thumb drive or DVD drive. Be thorough! Run the extended tests for memory and disk—not just the short tests. Let them run overnight. That's the only way to catch transient (sporadic) errors. If you find problems, my [Quick guide to fixing hardware](http://www.rexxinfo.org/Quick_Guide/Quick_Guide_To_Fixing_Computer_Hardware) will help you solve the most common hardware issues. ## Select the software The key to refurbishing is to install software appropriate for the hardware resources you have. The three essential hardware resources are: - Processor (number of cores and speed) - Memory - Video memory You can identify your computer's resources in its boot-time UEFI/BIOS panels. Write down your findings so that you don't forget them. Then, look up your processor at [CPU Benchmark](http://www.cpubenchmark.net/). That website gives you background on your CPU plus a CPU Mark that indicates its performance. Now that you know your hardware's power, you're ready to select software that it can efficiently run. Your software choices are divided into four critical areas: - Operating system (OS) - Desktop environment (DE) - Browser - Applications A good Linux distribution covers all four. Don't be tempted to run an unsupported version of Windows like 8, Vista, or XP just because it's already on the computer! The [risk](https://askleo.com/unsupported-software-really-mean/) of malware is too great. You're much better off with a more virus-resistant, up-to-date operating system. How about Windows 7? [Extended support](http://home.bt.com/tech-gadgets/computing/windows-7/windows-7-support-end-11364081315419) ends January 14, 2020, meaning you get security fixes only until that date. After that, zilch. Now is the perfect time to migrate off Windows 7. Linux's big benefit is that it offers [many distros](https://fossbytes.com/best-lightweight-linux-distros/) specifically designed for older hardware. Plus, its design decouples [DEs](http://en.wikipedia.org/wiki/Desktop_environment) from the OS, so you can mix and match the two. This is important because DEs heavily impact low-end system performance. (With Windows and MacOS, the OS version you run dictates the DE.) Other Linux advantages: Its thousands of apps are free and open source, so you don't have to worry about activation and licensing. And Linux is portable. You can copy, move, or clone the OS and applications across partitions, disks, devices, or computers. (Windows binds itself to the computer it's installed on via its Registry.) ## What can your refurbished computer do? We're talking dual-core machines dating from about 2006 to 2013, especially [Intel Core 2](https://en.wikipedia.org/wiki/Intel_Core_2) CPUs and [AMD Athlon 64 X2](https://en.wikipedia.org/wiki/Athlon_64_X2) family processors. Most have a [CPU Mark](http://www.cpubenchmark.net/) of between 1,000 and 4,000. You can often pick up these machines for a song, yet they're still powerful enough to run lightweight Linux software. One caution: be sure your computer has at least 2GB of memory. Upgrade the RAM if you have to. End users on my refurbished machines typically use between 0.5 and 2GB of RAM (exclusive of data buffering); rarely do they go over 2 gig. So if you can bump memory to 2GB, your system won't be forced to *swap*, or substitute disk for memory. That's critical for good performance. For example, I removed 1GB RAM from the decade-old rebuild I'm writing this article on, which dropped memory down to 1GB. The machine slowed to a crawl. Web surfing and other tasks became frustrating, even painful. I popped the memory stick back in and, with 2GB RAM, the desktop instantly reverted to its usable self. With a 2 gig dual-core computer, most people can do whatever they want, so long as they run a lightweight distro and browser. You can web surf, email, edit documents, do spreadsheets, watch YouTube videos, bid on eBay auctions, post on social media, listen to podcasts, view photo collections, manage home finance and personal scheduling, play games, and more. ## Limitations What can't these older computers do? Their concurrency is less than state-of-the-art machines. So run a fast browser and block ads, because that's what slows down web surfing. If your virtual private network (VPN) can block ads for you and offload that work from your processor, that's ideal. Disable autoplay of videos, Flash, and animation. Surf with a couple of tabs open rather than 20. Install a browser extension so you can toggle JavaScript. Direct the processors to what you're working on; don't keep a ton of apps open or run lots of stuff in the background. High-end graphics and video editing may be slow. Virtual machine hosting is out. How about games? The open source software repositories offer literally thousands of games. That's why I listed video memory as one of the three essential hardware resources. If your box doesn't have a video card, it likely has only 32 or 64MB of VRAM. Bump that to 256 or 512MB by adding a video card, and you'll find that processor-intensive games run much better. [Here's how](http://www.cyberciti.biz/faq/howto-find-linux-vga-video-card-ram/) to see how much VRAM your computer has. Be sure to get a card that fits your computer's [video slot](https://www.onlinecomputertips.com/support-categories/hardware/493-pci-vs-agp-vs-pci-express-video-cards/) (AGP, PCI-Express, or PCI) and has the right [cable connector](https://silentpc.com/articles/video-connectors) (VGA, DVI, or HDMI). ### What about Windows compatibility? People often ask about Windows compatibility. First, there's a [Linux equivalent](http://wiki.linuxquestions.org/wiki/Linux_software_equivalent_to_Windows_software) for every Windows program. Second, if you really must run a specific Windows program, you can usually do that on Linux using [Wine](https://en.wikipedia.org/wiki/Wine_%28software%29). Look up your application in the [Wine database](https://appdb.winehq.org/) to verify it runs under Wine and learn any special install tricks. Then the auxiliary tools [Winetricks](https://en.wikipedia.org/wiki/Winetricks) or [PlayOnLinux](https://en.wikipedia.org/wiki/PlayOnLinux) will help you with installation and setup. Wine's other benefit is that it runs programs from old Windows versions like Vista, XP, ME/98/95, and 3.1. I know a guy who set up a fantastic game box running his old XP games. You can even run thousands of [free DOS programs](https://archive.org/details/softwarelibrary_msdos) using [DOSBox.](https://en.wikipedia.org/wiki/DOSBox) One caution: if Windows programs can run, so can Windows [viruses](https://wiki.winehq.org/FAQ#Is_Wine_malware-compatible.3F). You must protect your Wine environment inside Linux just as you would any other Windows environment. How about compatibility with Microsoft Office? I use LibreOffice and routinely edit and exchange Word and Excel files without problems. You must, however, avoid using obscure or specialized features. ## Which distro? Assuming Linux is the OS, you need to select a DE, browser, and applications. The easy way to do this is to install a distribution that bundles everything you need. Remember that you can try out different distros without installing anything by booting from a [live USB](https://www.howtogeek.com/howto/linux/create-a-bootable-ubuntu-usb-flash-drive-the-easy-way/) thumb drive or DVD. [Here's how to create a bootable Linux](https://unetbootin.github.io/) from within Linux or Windows. I rebuild computers for charity, so I can't assume any knowledge on the part of my users. I need a distro with these traits: - User-friendly - Lightweight interface - Bundles lightweight apps - Big repository - Solid track record - Large user community with an active forum - Stability through long-term support releases (not rolling releases) - Prioritizes reliability over cutting-edge features - Configurable by a GUI rather than by text files Many distros fulfill these criteria. The three I've successfully deployed are [Mint/Xfce](https://linuxmint.com/), [Xubuntu,](https://xubuntu.org/) and [Lubuntu](https://lubuntu.me/). The first two use the Xfce desktop environment, while the latter runs LXQt. These DEs [use less](https://www.makeuseof.com/tag/best-lean-linux-desktop-environment-lxde-vs-xfce-vs-mate/) processor and memory resources than alternatives like GNOME, Unity, KDE, MATE, and Cinnamon. Xfce and LXQt are very easy to use. My clients have never seen Linux before, yet they have no trouble using these simple, menu-driven interfaces. It's vital to run the fastest, most efficient browser on older equipment. [Many feel](https://www.zdnet.com/article/chrome-is-the-most-popular-web-browser-of-all/) Chromium wins the browser race. I also install Firefox Quantum because people are familiar with it and [its performance](https://www.laptopmag.com/articles/firefox-quantum-vs-chrome) rivals [that of Chromium](https://www.zdnet.com/article/just-how-fast-is-firefox-quantum/). I toss in Opera because it's speedy and has some unique features, like integrated ad-blocking and a free [virtual private network](http://en.wikipedia.org/wiki/Virtual_private_network). Opera is free but not open source. Whatever browser you use, block ads and trackers! Minimize browser overhead. And don't allow videos or Flash to run without your explicit say-so. For applications, I rely on the lightweight apps bundled with Mint/Xfce, Xubuntu, and Lubuntu. They address every possible need. ## Go for it Will you be happy with your rebuild? The computers I've been using lately are both over a decade old. One has an Intel dual-core processor ([eMachines T5274a](https://www.cnet.com/products/emachines-t5274/specs/)) while the other features an AMD Athlon 64 x2 processor ([HP dc5750](https://community.spiceworks.com/products/7727-hewlett-packard-dc5750-microtower)). Both have 2 gig memory. They're as effective for my office workload as my quad-core i5 with 16GB RAM. The only function I miss when using them is the ability to host virtual machines. We live in an amazing era. You can take a five- to 12-year-old computer and, with a little effort, restore it to practical use. What could be more fun? ## 9 Comments
11,748
修复 “VLC is Unable to Open the MRL” 错误
https://itsfoss.com/vlc-is-unable-to-open-the-mrl/
2020-01-05T08:42:00
[ "VLC" ]
https://linux.cn/article-11748-1.html
![](/data/attachment/album/202001/05/084139mzlt1lfivilnnbkl.jpg) 一个使用 [VLC 的技巧](https://itsfoss.com/simple-vlc-tips/)是使用 [VLC](https://www.videolan.org/index.html) 播放 YouTube 和其他在线视频。这可以帮助你[观看带有字幕的在线视频](https://itsfoss.com/penguin-subtitle-player/)。 但是事情并不总是这么简单,因为有时使用 VLC 打开 YouTube 视频时会遇到此错误: > > Your input can’t be opened: VLC is unable to open the MRL 'https://youtubeurl.com'. Check the log for details. > > > ![VLC error while playing YouTube videos](/data/attachment/album/202001/05/084212d3b1t43ug0uhg40s.png) 这是因为 Google 不想让你使用任何第三方应用观看 YouTube,因为这样他们就无法正常收集数据。 因此,他们不断修改服务端,以使第三发开发更难与 Youtube 集成。 以 [youtube-dl](https://itsfoss.com/download-youtube-linux/) 为例。你会发现自己无法突然[下载 YouTube 视频](https://itsfoss.com/download-youtube-videos-ubuntu/),最简单的方案是安装最新版本的 youtube-dl。 对于 VLC 也是如此。如果你[在 Ubuntu 或任何你用的系统中安装了最新的 VLC](https://itsfoss.com/install-latest-vlc/),那么可能不会看到此错误。 ### 修复 “VLC is unable to open the MRL” 错误 让我向你展示对于 YouTube 的修复步骤。 进入 VLC 媒体播放器的官方 Github 仓库页面的[这个页面](https://raw.githubusercontent.com/videolan/vlc/master/share/lua/playlist/youtube.lua),并使用 `Ctrl+S` 保存文件: 现在,你需要做的是用此下载文件替换 `lib/vlc/lua/playlist` 目录中的 `youtube.luac`(注意 luac 中的 “c”)。 #### Linux 中的步骤 如果你使用的是 Linux,请打开终端并使用 [locate 命令](https://linuxhandbook.com/locate-command/)查找 `youtube.luac` 文件的确切位置: ``` locate youtube.luac ``` 当你得到文件的路径时,只需将该文件替换为下载的文件即可。我相信你可以完成这项简单的任务。 对我而言,以下是文件路径: ``` abhishek@itsfoss:~$ locate youtube.lua /usr/lib/x86_64-linux-gnu/vlc/lua/playlist/youtube.luac ``` 因此,我要做的就是将下载的文件移到该位置并替换它的内容: ``` sudo cp ~/Downloads/youtube.lua /usr/lib/x86_64-linux-gnu/vlc/lua/playlist/youtube.luac ``` 你现在应该可以在 VLC 中播放 YouTube 视频了。 #### Windows 中的步骤 如果你使用的是 Windows,那么应遵循以下步骤: * 将下载的 `youtube.lua` 文件重命名为 `youtube.luac` * 复制此文件并将其粘贴到 `C:\Program Files (x86)\VideoLAN\VLC\lua\playlist\` 就是这些了。 如果你在 Dailymotion 或其他视频流网站上遇到问题,那么可以从 VLC 仓库的[此处](https://github.com/videolan/vlc/tree/master/share/lua/playlist)下载它们各自的 lua 文件,并替换 VLC 安装中的现有 lua 文件。 我希望这个快速提示可以解决 VLC 无法为你播放 YouTube 视频的问题。 --- via: <https://itsfoss.com/vlc-is-unable-to-open-the-mrl/> 作者:[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) One of the [VLC tips](https://itsfoss.com/simple-vlc-tips/) is to play YouTube and other online videos with [VLC](https://www.videolan.org/index.html). This could help you [watch online videos with subtitles](https://itsfoss.com/penguin-subtitle-player/). But things may not always be simple because at times you’ll encounter this error when trying to open YouTube video with VLC: **Your input can’t be opened:****VLC is unable to open the MRL ‘https://youtubeurl.com’. Check the log for details.** ![Vlc Error Input Cant Be Played](https://itsfoss.com/content/images/wordpress/2019/12/vlc_error_input_cant_be_played.png) The thing here is that Google doesn’t want you to use any third party application for watching YouTube because then they cannot collect data properly. So, they keep changing stuff from their side to make it harder for third party devs to work with YouTube. Take [youtube-dl](https://itsfoss.com/download-youtube-linux/) for example. You’ll notice that you cannot [download YouTube videos](https://itsfoss.com/download-youtube-videos-ubuntu/) with it all of a sudden and the simplest solution is to have the latest version of youtube-dl installed. Same goes for VLC. If you [install the latest VLC in Ubuntu](https://itsfoss.com/install-latest-vlc/) or whichever operating system you are using, you probably won’t see this error. ## Fixing “VLC is unable to open the MRL” error At least let me show you the steps to fix this problem for YouTube. Go to this page and use Ctrl+S to save the file from the official GitHub repository of the VLC media player: Now, what you need to do is to replace the youtube.luac (mind the ‘c’ in luac) in lib/vlc/lua/playlist directory with this downloaded file. ### Steps for Linux If you are using Linux, open the terminal and use the [locate command](https://linuxhandbook.com/locate-command/) to find the exact location of youtube.luac file: `locate youtube.luac` When you get the path of the file, you just replace that file with your downloaded file. I trust you to handle this simple task. For me, it showed the path of the file here: ``` abhishek@itsfoss:~$ locate youtube.lua /usr/lib/x86_64-linux-gnu/vlc/lua/playlist/youtube.luac ``` So all I did was to move the downloaded file to this location and replace the content of the file: `sudo cp ~/Downloads/youtube.lua /usr/lib/x86_64-linux-gnu/vlc/lua/playlist/youtube.luac` You should be able to play the YouTube videos in VLC now. ### Steps for Windows If you are using Windows, you should follow these steps: - Rename the downloaded youtube.lua file to youtube.luac - Now copy this file and paste it to C:\Program Files (x86)\VideoLAN\VLC\lua\playlist\ That’s it. If you have trouble with Dailymotion or other video streaming websites, you can download their respective lua files from the VLC repository [here](https://github.com/videolan/vlc/tree/master/share/lua/playlist) and replace the existing one in your VLC install. I hope this quick tip fixed the problem with VLC being unable to play YouTube videos for you.
11,749
Kubernetes 命名空间入门
https://opensource.com/article/19/12/kubernetes-namespaces
2020-01-05T09:45:57
[ "kubernetes", "命名空间" ]
https://linux.cn/article-11749-1.html
> > 命名空间是什么?你为什么需要它? > > > ![](/data/attachment/album/202001/05/094542qnq3qc3nrkkrjanh.jpg) kubernetes <ruby> 命名空间 <rt> namespace </rt></ruby>是什么?正如 Shakespeare 以前写过的,我们所谓的命名空间,或者任何其他名字,就是虚拟集群。通过虚拟集群,意味着 kubernetes 可以在单个集群上提供多个 kubernetes 的集群,类似一个在其主机抽象出来的虚拟机。[kubernetes 文档](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) 中的解释: > > kubernetes 在一个物理集群上提供了多个虚拟集群。这些虚拟集群被称为命名空间。 > > > 你为什么需要命名空间?一言以蔽之:隔离。 隔离有很多优点,如它提供了安全和干净的环境。如果你是基础设施的所属者,并且要为开发者提供环境,隔离就相当重要。你最不需要的就是,一个不熟悉你集群是如何搭建的人去修改系统配置 —— 这可能导致所有人都无法登录。 ### 初始命名空间 一个集群的三个初始命名空间:`default`、`kube-system` 和 `kube-public`。虽然技术上你可以用这三个命名空间作部署,但我还是推荐你把这三个命名空间留作系统配置用,而不是你的项目。 * `Default` 用于某些没有指明命名空间的部署,这是一种快速创建混乱的做法,如果你在没有正确信息的情况下做了很多部署,将很难清理。我不会去动它,因为它只有这一个用途,而且在不止一种情况下误导过我。 * `Kube-system` 是 Kubernetes 系统相关的所有对象组成的命名空间。任何对此命名空间的部署都可能是危险的操作,可能对系统本身造成不可挽回的破坏。没错,我试过;所以我不推荐。 * `Kube-public` 所有人可读,但是这个命名空间是为系统保留的。 ### 用命名空间来实现隔离 我用了多种方式通过命名空间来实现隔离。我经常用命名空间来把多个用户项目分割到不同的环境。这种方式可以有效防止跨项目的污染,因为命名空间提供了独立的环境。例如,用户可以安装不同版本的 Jenkins,如果它们的环境变量是在不同的命名空间,就不会冲突。 这种隔离对于清理也很有帮助。如果开发小组的多个项目突然被废弃,你可以用命令 `kubectl delete ns <$NAMESPACENAME>` 一键删除命名空间,清理命名空间内的所有东西。(请确认被删除的是正确的命名空间。我曾经在生产环境删除了错误的命名空间,这很不好。) 如果你是基础设施所有者,请谨慎操作,因为这可能会引发其他团队的的故障或引发其他问题。例如,如果你创建了一个特定的命名空间,里面有特殊的额外安全的 DNS 功能,但是其他人删除了它,那么命名空间内的所有 pod 和它们运行的应用都会被清空。所有的**删除**操作在真正实施之前都应该由同事(通过 [GitOps](https://www.weave.works/blog/gitops-operations-by-pull-request))评审一下。 虽然官方文档不建议 [10 人以下团队](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) 使用多个命名空间,但出于架构需要,在我自己的集群上还是用了多个命名空间。集群越干净越好。 ### 关于命名空间管理员应该知道的 首先,命名空间不能嵌套。部署只能在一个命名空间中进行。对于版本化项目,你不一定要用命名空间,你可以使用标签来区分有相同名字的版本化应用。命名空间使用配额来为不同的用户划分资源;例如,*某个命名空间最多能有 x 个节点*。最后,所有的命名空间对于该资源类型只能使用一个独一无二的名字。 ### 命名空间命令操作 你需要安装 [Minikube](https://kubernetes.io/docs/tasks/tools/install-minikube/)、[Helm](https://helm.sh/) 和 [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) 命令行,才能使用下面的命名空间命令。我的文章《[安全扫描你的 DevOps 流水线](https://opensource.com/article/19/7/security-scanning-your-devops-pipeline)》中有它们的安装教程,你也可以去每个项目的官方主页去找安装教程。我使用的是最新的 Minikube。手动安装很快,第一次就能成功运行。 获取你的第一组命名空间: ``` jess@Athena:~$ kubectl get namespace NAME STATUS AGE default Active 5m23s kube-public Active 5m24s kube-system Active 5m24s ``` 创建一个命名空间: ``` jess@Athena:~$ kubectl create namespace athena namespace/athena created ``` 现在开发者可以部署到你创建的命名空间了;例如,这里是一个简短的 Helm chart: ``` jess@Athena:~$ helm install teset-deploy stable/redis --namespace athena NAME: teset-deploy LAST DEPLOYED: Sat Nov 23 13:47:43 2019 NAMESPACE: athena STATUS: deployed REVISION: 1 TEST SUITE: None NOTES: ` Please be patient while the chart is being deployed ` Redis can be accessed via port 6379 on the following DNS names from within your cluster: teset-deploy-redis-master.athena.svc.cluster.local for read/write operations teset-deploy-redis-slave.athena.svc.cluster.local for read-only operations ``` 获取你的密码: ``` export REDIS_PASSWORD=$(kubectl get secret --namespace athena teset-deploy-redis -o jsonpath="{.data.redis-password}" | base64 --decode) ``` 连接你的 redis 服务: 1. 运行一个你可以作为客户端用的 Redis pod: ``` kubectl run --namespace athena teset-deploy-redis-client --rm --tty -i --restart='Never' \ --env REDIS_PASSWORD=$REDIS_PASSWORD \ --image docker.io/bitnami/redis:5.0.7-debian-9-r0 -- bash ``` 2. 使用 Redis CLI 连接: ``` redis-cli -h teset-deploy-redis-master -a $REDIS_PASSWORD redis-cli -h teset-deploy-redis-slave -a $REDIS_PASSWORD ``` 从集群外连接你的数据库: ``` kubectl port-forward --namespace athena svc/teset-deploy-redis-master 6379:6379 & redis-cli -h 127.0.0.1 -p 6379 -a $REDIS_PASSWORD ``` 现在这一套部署已经完成了,你有一个在命名空间 `test-deploy` 中部署的 chart。 查看你的命名空间中有哪些 pod: ``` jess@Athena:~$ kubectl get pods --namespace athena NAME READY STATUS RESTARTS AGE teset-deploy-redis-master-0 1/1 Running 0 2m38s teset-deploy-redis-slave-0 1/1 Running 0 2m38s teset-deploy-redis-slave-1 1/1 Running 0 90s ``` 现在,你已经正式把你的应用隔离到了一个命名空间,创建了一个只在内部通信的虚拟集群。 一键删除所有东西: ``` jess@Athena:~$ kubectl delete namespace athena namespace "athena" deleted ``` 因为这会删除应用的所有内部配置,所以这个删除操作可能会持续一段时间,持续时间取决于你的部署到底有多大。 再次检查一下所有东西是否被删除了: ``` jess@Athena:~$ kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE kube-system coredns-5644d7b6d9-4vxv6 1/1 Running 0 32m kube-system coredns-5644d7b6d9-t5wn7 1/1 Running 0 32m kube-system etcd-minikube 1/1 Running 0 31m kube-system kube-addon-manager-minikube 1/1 Running 0 32m kube-system kube-apiserver-minikube 1/1 Running 0 31m kube-system kube-controller-manager-minikube 1/1 Running 0 31m kube-system kube-proxy-5tdmh 1/1 Running 0 32m kube-system kube-scheduler-minikube 1/1 Running 0 31m kube-system storage-provisioner 1/1 Running 0 27m ``` 这是一个所有 pod 及它们存在于的已知命名空间的列表。你可以看到,之前创建的应用和命名空间现在已经不在了。 ### 命名空间实践 当前我是出于安全考虑才使用命名空间,如限制用户的权限。你可以限制所有的东西 —— 从哪些角色可以访问命名空间,到命名空间可使用的集群资源(CPU 等)的配额等级。例如,我通过资源配额和<ruby> 基于角色的访问控制 <rt> role-based access control </rt></ruby>(RBAC)配置来确保只有允许的服务账号可以访问命名空间。 对于隔离方面的安全,我不希望我的私人 Jenkins 应用可以通过一个信任的本地网络被当做一个有公共 IP 地址的安全镜像来访问(我不得不假定,可能会被侵袭)。 如果你很难提前计算出到底要在你的云平台上部署多少节点(或者,就我而言,是在[搞崩](https://en.wikipedia.org/wiki/Segmentation_fault)我的家庭服务器之前我能部署多少个),那么命名空间在预算方面也很有用。虽然这超出了本文的讨论范围,而且很复杂,但值得你去调研和使用来防止你的集群过分扩展。 ### 总结 命名空间是一个很好的隔离项目和应用的方法。本文仅是一个关于命名空间的简短介绍,所以我建议你更深入地研究下命名空间,在你的实践中更多地去使用它们。 --- via: <https://opensource.com/article/19/12/kubernetes-namespaces> 作者:[Jessica Cherry](https://opensource.com/users/jrepka) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
What is in a Kubernetes namespace? As Shakespeare once wrote, which we call a namespace, by any other name, would still be a virtual cluster. By virtual cluster, I mean Kubernetes can offer multiple Kubernetes clusters on a single cluster, much like a virtual machine is an abstraction of its host. According to the [Kubernetes docs](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/): Kubernetes supports multiple virtual clusters backed by the same physical cluster. These virtual clusters are called namespaces. Why do you need to use namespaces? In one word: isolation. Isolation has many advantages, including that it supports secure and clean environments. If you are the owner of the infrastructure and are supporting developers, isolation is fairly important. The last thing you need is someone who is unfamiliar with how your cluster is built going and changing the system configuration—and possibly disabling everyone's ability to log in. ## The namespaces that start it all The first three namespaces created in a cluster are always **default**, **kube-system**, and **kube-public**. While you can technically deploy within these namespaces, I recommend leaving these for system configuration and not for your projects. **Default**is for deployments that are not given a namespace, which is a quick way to create a mess that will be hard to clean up if you do too many deployments without the proper information. I leave this alone because it serves that one purpose and has confused me on more than one occasion.**Kube-system**is for all things relating to, you guessed it, the Kubernetes system. Any deployments to this namespace are playing a dangerous game and can accidentally cause irreparable damage to the system itself. Yes, I have done it; I do not recommend it.**Kube-public**is readable by everyone, but the namespace is reserved for system usage. ## Using namespaces for isolation I have used namespaces for isolation in a couple of ways. I use them most often to split many users' projects into separate environments. This is useful in preventing cross-project contamination since namespaces provide independent environments. Users can install multiple versions of Jenkins, for example, and their environmental variables won't collide if they are in different namespaces. This separation also helps with cleanup. If development groups are working on various projects that suddenly become obsolete, you can delete the namespace and remove everything in one swift movement with **kubectl delete ns <$NAMESPACENAME>**. (Please make sure it's the right namespace. I deleted the wrong one in production once, and it's not pretty.) Be aware that this can cause damage across teams and problems for you if you are the infrastructure owner. For example, if you create a namespace with some special, extra-secure DNS functions and the wrong person deletes it, all of your pods and their running applications will be removed with the namespace. Any use of **delete** should be reviewed by a peer (through [GitOps](https://www.weave.works/blog/gitops-operations-by-pull-request)) before hitting the cluster. While the official documentation suggests not using multiple namespaces [with 10 or fewer users](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/), I still use them in my own cluster for architectural purposes. The cleaner the cluster, the better. ## What admins need to know about namespaces For starters, namespaces cannot be nested in other namespaces. There can be only one namespace with deployments in it. You don't have to use namespaces for versioned projects, but you can always use the labels to separate versioned apps with the same name. Namespaces divide resources between users using resource quotas; for example, *this namespace can only have x* *number* *of nodes*. Finally, all namespaces scope down to a unique name for the resource type. ## Namespace commands in action To try out the following namespace commands, you need to have [Minikube](https://kubernetes.io/docs/tasks/tools/install-minikube/), [Helm](https://helm.sh/), and the [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) command line installed. For information about installing them, see my article [ Security scanning your DevOps pipeline](https://opensource.com/article/19/7/security-scanning-your-devops-pipeline) or each project's homepage. I am using the most recent release of Minikube. The manual installation is fast and has consistently worked correctly the first time. To get your first set of namespaces: ``` jess@Athena:~$ kubectl get namespace NAME STATUS AGE default Active 5m23s kube-public Active 5m24s kube-system Active 5m24s ``` To create a namespace: ``` jess@Athena:~$ kubectl create namespace athena namespace/athena created ``` Now developers can deploy to the namespace you created; for example, here's a small and easy Helm chart: ``` jess@Athena:~$ helm install teset-deploy stable/redis --namespace athena NAME: teset-deploy LAST DEPLOYED: Sat Nov 23 13:47:43 2019 NAMESPACE: athena STATUS: deployed REVISION: 1 TEST SUITE: None NOTES: ** Please be patient while the chart is being deployed ** Redis can be accessed via port 6379 on the following DNS names from within your cluster: teset-deploy-redis-master.athena.svc.cluster.local for read/write operations teset-deploy-redis-slave.athena.svc.cluster.local for read-only operations ``` To get your password: `export REDIS_PASSWORD=$(kubectl get secret --namespace athena teset-deploy-redis -o jsonpath="{.data.redis-password}" | base64 --decode)` To connect to your Redis server: - Run a Redis pod that you can use as a client: `kubectl run --namespace athena teset-deploy-redis-client --rm --tty -i --restart='Never' \ --env REDIS_PASSWORD=$REDIS_PASSWORD \ --image docker.io/bitnami/redis:5.0.7-debian-9-r0 -- bash` - Connect using the Redis CLI: `redis-cli -h teset-deploy-redis-master -a $REDIS_PASSWORD redis-cli -h teset-deploy-redis-slave -a $REDIS_PASSWORD` To connect to your database from outside the cluster: ``` kubectl port-forward --namespace athena svc/teset-deploy-redis-master 6379:6379 & redis-cli -h 127.0.0.1 -p 6379 -a $REDIS_PASSWORD ``` Now that this deployment is out, you have a chart deployed in your namespace named **test-deploy**. To look at what pods are in your namespace: ``` jess@Athena:~$ kubectl get pods --namespace athena NAME READY STATUS RESTARTS AGE teset-deploy-redis-master-0 1/1 Running 0 2m38s teset-deploy-redis-slave-0 1/1 Running 0 2m38s teset-deploy-redis-slave-1 1/1 Running 0 90s ``` At this point, you have officially isolated your application to a single namespace and created one virtual cluster that talks internally only to itself. Delete everything with a single command: ``` jess@Athena:~$ kubectl delete namespace athena namespace "athena" deleted ``` Because this deletes the application's entire internal configuration, the delete may take some time, depending on how large your deployment is. Double-check that everything has been removed: ``` jess@Athena:~$ kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE kube-system coredns-5644d7b6d9-4vxv6 1/1 Running 0 32m kube-system coredns-5644d7b6d9-t5wn7 1/1 Running 0 32m kube-system etcd-minikube 1/1 Running 0 31m kube-system kube-addon-manager-minikube 1/1 Running 0 32m kube-system kube-apiserver-minikube 1/1 Running 0 31m kube-system kube-controller-manager-minikube 1/1 Running 0 31m kube-system kube-proxy-5tdmh 1/1 Running 0 32m kube-system kube-scheduler-minikube 1/1 Running 0 31m kube-system storage-provisioner 1/1 Running 0 27m ``` This is a list of all the pods and all the known namespaces where they live. As you can see, the application and namespace you previously made are now gone. ## Namespaces in practice I currently use namespaces for security purposes, including reducing the privileges of users with limitations. You can limit everything—from which roles can access a namespace to their quota levels for cluster resources, like CPUs. For example, I use resource quotas and role-based access control (RBAC) configurations to confirm that a namespace is accessible only by the appropriate service accounts. On the isolation side of security, I don't want my home Jenkins application to be accessible over a trusted local network as secure images that have public IP addresses (and thus, I have to assume, could be compromised). Namespaces can also be helpful for budgeting purposes if you have a hard budget on how much you can use in your cloud platform for nodes (or, in my case, how much I can deploy before [segfaulting](https://en.wikipedia.org/wiki/Segmentation_fault) my home server). Although this is out of scope for this article, and it's complicated, it is worth researching and taking advantage of to prevent overextending your cluster. ## Conclusion Namespaces are a great way to isolate projects and applications. This is just a quick introduction to the topic, so I encourage you to do more advanced research on namespaces and use them more in your work. ## Comments are closed.
11,751
12 个给全等级码农们的编程资源
https://opensource.com/article/19/12/programming-resources
2020-01-05T10:20:40
[ "程序员" ]
https://linux.cn/article-11751-1.html
> > 无论你身处编程旅程中的何处,这 12 篇编程文章都有你需要学习一些东西。 > > > ![](/data/attachment/album/202001/05/102002cdjy66jucbcfs6dg.jpg) > > “学习计算机编程的最佳时间是 20 年前,其次是现在。” — 计算机科学的谚语(也许是) > > > 无论你是新程序员、经验丰富的 Web 开发人员、后端大师、头发花白的系统程序员,还是其他神秘物种的计算机极客?无论你身处广阔的软件开发人员生态系统中的何处,在我们领域中唯一不变的就是需要了解新技术及其应用方法。这是过去一年来阅读量最大的 Opensource.com 文章的集合,我很高兴在这里与你分享它们。 ### 好好学习 无论你的技能或兴趣是什么,学习如何编写计算机程序都可以将特定领域的知识变成一种超能力。不幸的是,至少从现在开始,还不可能通过坐在计算机前面接受电磁辐射就能学会如何编程。在这之前,我推荐这些出色的文章来帮助激发你的编程技能。它们解决了一些重要的问题,例如考虑学习哪种语言以及不同的入门方式。 * [你应该学习哪种编程语言?](/article-10769-1.html)(译文) * [学习 Python 的 12 个方式](/article-11280-1.html)(译文) * [你可以使用树莓派学习的三种流行编程语言](/article-10661-1.html)(译文) * [利用 Python 引导孩子的计算机思维](/article-11116-1.html)(译文) ### 天天向上 经验丰富的程序员知道,与学习编程相比,唯一更难的就是使你的技能和知识保持最新。但是我们是[自学成才](https://en.wikipedia.org/wiki/Autodidacticism)的一族,总是希望提高我们的专业知识和理解力。即使我们不期望使用新技术,我们也知道总会有人问起它们。这些有关 Rust、WebAssembly 和 Podman 的文章是开始学习软件技术一些即将出现的趋势的好地方。 * [为什么要在 WebAssembly 中使用 Rust?](https://opensource.com/article/19/2/why-use-rust-webassembly) * [使用 WebAssembly 扩展命令行领域](https://opensource.com/article/19/4/command-line-playgrounds-webassembly) * [免 root 的 Podman 如何工作?](https://opensource.com/article/19/2/how-does-rootless-podman-work) * [为什么选择 Rust 作为你的下一种编程语言](https://opensource.com/article/19/10/choose-rust-programming-language) ### 老兵不死 尽管新技术层出不穷,但回顾过去可以帮助你前进。当今惊人的技术是建立在昨天的工具之上的,即使我们从未使用这些传奇语言编写过代码,它也将使我们很好地理解这些工具的功能和局限性。这一系列文章集中于 C 语言、用 AWK 编写的实际应用程序,以及对流行度下降但也许还没有消亡的计算机语言的有趣讨论。 * [C 的巨大影响](https://opensource.com/article/19/10/command-line-heroes-c) * [如何写好 C main 函数](/article-10949-1.html)(译文) * [用 AWK 喝咖啡](/article-10555-1.html)(译文) * [你最喜欢的“死”语言是什么?](https://opensource.com/article/19/6/favorite-dead-language) ### 学习不止 无论你在编程过程中处于何处,总有更多东西需要学习。我希望这些来自 2019 年的顶级资源能帮助你为 2020 年做好准备。感谢作者们和你——读者。 --- via: <https://opensource.com/article/19/12/programming-resources> 作者:[Erik O'Shaughnessy](https://opensource.com/users/jnyjny) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
"The best time to learn computer programming was 20 years ago. The second best time is now." — A computer science proverb, maybe. Are you a new programmer, an experienced web dev, a backend wizard, a grizzled system programmer, or some other yet-to-be-discovered species of computer geek? Wherever you land in the vast ecosystem of software developers, the only constant in our field is the need to learn about new technologies and how to apply them. Here is an ensemble of the most-read Opensource.com articles from the past year that inform and entertain, and I'm excited to share them with you here. ## For the noble newbie Whatever your skillset or interests, learning how to write computer programs turns that domain-specific knowledge into a superpower. Unfortunately, it isn't possible to learn how to program from the bite of a radioactive computer, at least not yet. Until that's a thing, I recommend these excellent articles to help bootstrap your programming skills. They address important questions like which languages to consider learning and different ways to get started. [Which programming languages should you learn?](https://opensource.com/article/19/2/which-programming-languages-should-you-learn)[A dozen ways to learn Python](https://opensource.com/article/19/8/dozen-ways-learn-python)[Three popular programming languages you can learn with Raspberry Pi](https://opensource.com/article/19/3/programming-languages-raspberry-pi)[Introducing kids to computational thinking with Python](https://opensource.com/article/19/2/break-down-stereotypes-python) ## Keeping up with emerging technologies Experienced programmers know that the only thing harder than learning to program is keeping your skills and knowledge up to date. But we are an [autodidactic](https://en.wikipedia.org/wiki/Autodidacticism) breed, always looking to level up our expertise and understanding. Even if we don't anticipate using a new technology, we know that eventually, someone will ask about it. These articles on Rust, WebAssembly, and Podman are great places to start learning about just a few of the upcoming trends in software technology. [Why should you use Rust in WebAssembly?](https://opensource.com/article/19/2/why-use-rust-webassembly)[Level up command-line playgrounds with WebAssembly](https://opensource.com/article/19/4/command-line-playgrounds-webassembly)[How does rootless Podman work?](https://opensource.com/article/19/2/how-does-rootless-podman-work)[Why to choose Rust as your next programming language](https://opensource.com/article/19/10/choose-rust-programming-language) ## Old programs never die Despite the never-ending cascade of new technologies, it never hurts to look back to help you look forward. Today's amazing technologies are built on top of yesterday's tools, and it will serve us well to understand the abilities and limitations of those tools, even if we never write a line of code in these languages of legend. This collection of articles focuses on the C language, a practical application written in AWK, and an interesting discussion of computer languages that are declining in popularity, but perhaps not dead yet. [The monumental impact of C](https://opensource.com/article/19/10/command-line-heroes-c)[How to write a good C main function](https://opensource.com/article/19/5/how-write-good-c-main-function)[Drinking coffee with AWK](https://opensource.com/article/19/2/drinking-coffee-awk)[What's your favorite "dead" language?](https://opensource.com/article/19/6/favorite-dead-language) ## Keep on learning No matter where you are in your programming journey, there will always be more to learn. I hope these top resources from 2019 will get you ready for 2020. Thanks to the authors and you, the reader. ## 2 Comments
11,752
借助 zope.interface 深入了解 Python 接口
https://opensource.com/article/19/9/zopeinterface-python-package
2020-01-05T22:46:46
[ "Python" ]
https://linux.cn/article-11752-1.html
> > Zope.interface 可以帮助声明存在哪些接口,是由哪些对象提供的,以及如何查询这些信息。 > > > ![Snake charmer cartoon with a yellow snake and a blue snake](/data/attachment/album/202001/05/224701yp24pci9zz7i2mqn.png "Snake charmer cartoon with a yellow snake and a blue snake") `zope.interface` 库可以克服 Python 接口设计中的歧义性。让我们来研究一下。 ### 隐式接口不是 Python 之禅 [Python 之禅](https://en.wikipedia.org/wiki/Zen_of_Python) 很宽松,但是有点自相矛盾,以至于你可以用它来例证任何东西。让我们来思考其中最著名的原则之一:“显示胜于隐式”。 传统上,在 Python 中会隐含的一件事是预期的接口。比如函数已经记录了它期望一个“类文件对象”或“序列”。但是什么是类文件对象呢?它支持 `.writelines`吗?`.seek` 呢?什么是一个“序列”?是否支持步进切片,例如 `a[1:10:2]`? 最初,Python 的答案是所谓的“鸭子类型”,取自短语“如果它像鸭子一样行走,像鸭子一样嘎嘎叫,那么它可能就是鸭子”。换句话说,“试试看”,这可能是你能得到的最具隐式的表达。 为了使这些内容显式地表达出来,你需要一种方法来表达期望的接口。[Zope](http://zope.org) Web 框架是最早用 Python 编写的大型系统之一,它迫切需要这些东西来使代码明确呈现出来,例如,期望从“类似用户的对象”获得什么。 `zope.interface` 由 Zope 开发,但作为单独的 Python 包发布。`Zope.interface` 可以帮助声明存在哪些接口,是由哪些对象提供的,以及如何查询这些信息。 想象编写一个简单的 2D 游戏,它需要各种东西来支持精灵界面(LCTT 译注:“<ruby> 精灵 <rt> Sprite </rt></ruby>”是指游戏面板中各个组件)。例如,表示一个边界框,但也要表示对象何时与一个框相交。与一些其他语言不同,在 Python 中,将属性访问作为公共接口一部分是一种常见的做法,而不是实现 getter 和 setter。边界框应该是一个属性,而不是一个方法。 呈现精灵列表的方法可能类似于: ``` def render_sprites(render_surface, sprites): """ sprites 应该是符合 Sprite 接口的对象列表: * 一个名为 "bounding_box" 的属性,包含了边界框 * 一个名为 "intersects" 的方法,它接受一个边界框并返回 True 或 False """ pass # 一些做实际渲染的代码 ``` 该游戏将具有许多处理精灵的函数。在每个函数中,你都必须在随附文档中指定预期。 此外,某些函数可能期望使用更复杂的精灵对象,例如具有 Z 序的对象。我们必须跟踪哪些方法需要 Sprite 对象,哪些方法需要 SpriteWithZ 对象。 如果能够使精灵是显式而直观的,这样方法就可以声明“我需要一个精灵”,并有个严格定义的接口,这不是很好吗?来看看 `zope.interface`。 ``` from zope import interface class ISprite(interface.Interface): bounding_box = interface.Attribute( "边界框" ) def intersects(box): "它和一个框相交吗?" ``` 乍看起来,这段代码有点奇怪。这些方法不包括 `self`,而包含 `self` 是一种常见的做法,并且它有一个**属性**。这是在 `zope.interface` 中声明接口的方法。这看起来很奇怪,因为大多数人不习惯严格声明接口。 这样做的原因是接口显示了如何调用方法,而不是如何定义方法。因为接口不是超类,所以它们可以用来声明数据属性。 下面是一个能带有圆形精灵的接口的一个实现: ``` @implementer(ISprite) @attr.s(auto_attribs=True) class CircleSprite: x: float y: float radius: float @property def bounding_box(self): return ( self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius, ) def intersects(self, box): # 当且仅当至少一个角在圆内时,方框与圆相交 top_left, bottom_right = box[:2], box[2:] for choose_x_from (top_left, bottom_right): for choose_y_from (top_left, bottom_right): x = choose_x_from[0] y = choose_y_from[1] if (((x - self.x) ` 2 + (y - self.y) ` 2) &lt;= self.radius ` 2): return True return False ``` 这**显式**声明了实现了该接口的 `CircleSprite` 类。它甚至能让我们验证该类是否正确实现了接口: ``` from zope.interface import verify def test_implementation(): sprite = CircleSprite(x=0, y=0, radius=1) verify.verifyObject(ISprite, sprite) ``` 这可以由 pytest、nose 或其他测试框架运行,它将验证创建的精灵是否符合接口。测试通常是局部的:它不会测试仅在文档中提及的内容,甚至不会测试方法是否可以在没有异常的情况下被调用!但是,它会检查是否存在正确的方法和属性。这是对单元测试套件一个很好的补充,至少可以防止简单的拼写错误通过测试。 --- via: <https://opensource.com/article/19/9/zopeinterface-python-package> 作者:[Moshe Zadka](https://opensource.com/users/moshezhttps://opensource.com/users/lauren-pritchetthttps://opensource.com/users/sethhttps://opensource.com/users/drmjg) 选题:[lujun9972](https://github.com/lujun9972) 译者:[MjSeven](https://github.com/MjSeven) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The **zope.interface** library is a way to overcome ambiguity in Python interface design. Let's take a look at it. ## Implicit interfaces are not zen The [Zen of Python](https://en.wikipedia.org/wiki/Zen_of_Python) is loose enough and contradicts itself enough that you can prove anything from it. Let's meditate upon one of its most famous principles: "Explicit is better than implicit." One thing that traditionally has been implicit in Python is the expected interface. Functions have been documented to expect a "file-like object" or a "sequence." But what is a file-like object? Does it support **.writelines**? What about **.seek**? What is a "sequence"? Does it support step-slicing, such as **a[1:10:2]**? Originally, Python's answer was the so-called "duck-typing," taken from the phrase "if it walks like a duck and quacks like a duck, it's probably a duck." In other words, "try it and see," which is possibly the most implicit you could possibly get. In order to make those things explicit, you need a way to express expected interfaces. One of the first big systems written in Python was the [Zope](http://zope.org) web framework, and it needed those things desperately to make it obvious what rendering code, for example, expected from a "user-like object." Enter **zope.interface**, which is developed by Zope but published as a separate Python package. **Zope.interface** helps declare what interfaces exist, which objects provide them, and how to query for that information. Imagine writing a simple 2D game that needs various things to support a "sprite" interface; e.g., indicate a bounding box, but also indicate when the object intersects with a box. Unlike some other languages, in Python, attribute access as part of the public interface is a common practice, instead of implementing getters and setters. The bounding box should be an attribute, not a method. A method that renders the list of sprites might look like: ``` def render_sprites(render_surface, sprites): """ sprites should be a list of objects complying with the Sprite interface: * An attribute "bounding_box", containing the bounding box. * A method called "intersects", that accepts a box and returns True or False """ pass # some code that would actually render ``` The game will have many functions that deal with sprites. In each of them, you would have to specify the expected contract in a docstring. Additionally, some functions might expect a more sophisticated sprite object, maybe one that has a Z-order. We would have to keep track of which methods expect a Sprite object, and which expect a SpriteWithZ object. Wouldn't it be nice to be able to make what a sprite is explicit and obvious so that methods could declare "I need a sprite" and have that interface strictly defined? Enter **zope.interface**. ``` from zope import interface class ISprite(interface.Interface): bounding_box = interface.Attribute( "The bounding box" ) def intersects(box): "Does this intersect with a box" ``` This code looks a bit strange at first glance. The methods do not include a **self**, which is a common practice, and it has an **Attribute** thing. This is the way to declare interfaces in **zope.interface**. It looks strange because most people are not used to strictly declaring interfaces. The reason for this practice is that the interface shows how the method will be called, not how it is defined. Because interfaces are not superclasses, they can be used to declare data attributes. One possible implementation of the interface can be with a circular sprite: ``` @implementer(ISprite) @attr.s(auto_attribs=True) class CircleSprite: x: float y: float radius: float @property def bounding_box(self): return ( self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius, ) def intersects(self, box): # A box intersects a circle if and only if # at least one corner is inside the circle. top_left, bottom_right = box[:2], box[2:] for choose_x_from (top_left, bottom_right): for choose_y_from (top_left, bottom_right): x = choose_x_from[0] y = choose_y_from[1] if (((x - self.x) ** 2 + (y - self.y) ** 2) <= self.radius ** 2): return True return False ``` This *explicitly* declares that the **CircleSprite** class implements the interface. It even enables us to verify that the class implements it properly: ``` from zope.interface import verify def test_implementation(): sprite = CircleSprite(x=0, y=0, radius=1) verify.verifyObject(ISprite, sprite) ``` This is something that can be run by **pytest**, **nose**, or another test runner, and it will verify that the sprite created complies with the interface. The test is often partial: it will not test anything only mentioned in the documentation, and it will not even test that the methods can be called without exceptions! However, it does check that the right methods and attributes exist. This is a nice addition to the unit test suite and—at a minimum—prevents simple misspellings from passing the tests. ## Comments are closed.
11,753
九个提升程序员技术技能的备忘单和指南
https://opensource.com/article/20/1/cheat-sheets-guides
2020-01-05T23:31:58
[ "备忘单" ]
/article-11753-1.html
> > 用我们最新的编程备忘单和指南来为新年开局,它适合所有技能水平的人。 > > > ![](/data/attachment/album/202001/05/233115etzm6hv4a3z5yvhg.jpg) 对刚接触命令行的新程序员来说备忘单是完美的。然而,即便是最有经验的程序员也需要时不时地依靠参考资料。假如你刚好敲不出那个讨厌的快捷键,那么手边有个备忘单就很赞了。这是一份我们可供下载指南的综述,它将助你在 2020 年取得成功。 ### 备忘单 #### Markdown [Markdown](https://opensource.com/downloads/cheat-sheet-markdown) 不仅针对程序员,任何人都可以借助它为纯文本文档增添语法和结构。此备忘单提供了使用 CommonMark 规范的 Markdown 基础要点。它还包括 GitHub 和 GitLab 的语法。 #### Linux 权限和用户 用这个 Linux 备忘单把[用户管理](https://opensource.com/downloads/linux-permissions-cheat-sheet)命令放在手边。快速学习如何增删用户、查看历史以及设置权限。 #### Bash 一旦你了解了 [Bash](https://opensource.com/downloads/bash-cheat-sheet),在命令行中就蕴含了无限可能。我们的 Bash 备忘单可以帮助你更有效地使用键盘快捷键。不知不觉间,你就能在睡眠中(字面意义上)运行脚本。 #### Linux 常用命令 毫不奇怪,我们的 [Linux 常用命令备忘单](https://opensource.com/downloads/linux-common-commands-cheat-sheet)是如此受欢迎。这个备忘单包含了开始安装软件和导览文件系统的要点。为自己和你的同事打印出来吧。 #### 微服务 似乎每个人都在谈论[微服务](https://opensource.com/downloads/microservices-cheat-sheet),而且理由很充分。微服务使应用程序模块化,因此更容易构建和维护。它不再只是这个备忘单上的流行语。在[微服务开源指南](https://opensource.com/article/19/11/microservices-cheat-sheet)中了解重要的术语并学习更多关于微服务的基础知识。 #### Java 此备忘单非常适合初级和中级 [Java](https://opensource.com/downloads/java-cheat-sheet) 程序员。它包括重要的上下文以及处理导入、变量、类等的代码。 #### pip 程序员爱用 [pip](https://opensource.com/downloads/pip-cheat-sheet) 命令来帮助安装、管理和使用 Python 软件包。然而,pip 可以做的远不止这些。这个备忘单将教你如何构建 wheels 和 record 包。 ### 指南 #### 七个不可或缺的 PyPI 库 [这组 Python 教程](https://opensource.com/downloads/7-essential-pypi-libraries)将帮助你学习如何更快地编写扩展、格式化代码、自动化测试、确保代码一致性,以及更多使用 PyPI 库的方法。 #### 开始学习 Kubernetes 在这份平易近人的[指南](https://opensource.com/downloads/getting-started-kubernetes-ebook)中,作者 Scott McCarty 用了一个出人意料的类比来解释 Kubernetes 的价值和上手步骤。 --- via: <https://opensource.com/article/20/1/cheat-sheets-guides> 作者:[Lauren Pritchett](https://opensource.com/users/lauren-pritchett) 选题:[lujun9972](https://github.com/lujun9972) 译者:[nacyro](https://github.com/nacyro) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,756
Linux useradd 命令介绍
https://opensource.com/article/19/10/linux-useradd-command
2020-01-06T22:58:00
[ "useradd" ]
https://linux.cn/article-11756-1.html
> > 使用 useradd 命令来添加用户(并且根据需要修改账号)。 > > > ![](/data/attachment/album/202001/06/225733hv1u7f4z4vbt8u5x.jpg) 任何计算机系统中,添加用户都是最重要的事之一;本文着重介绍如何在 Linux 系统中添加用户。 正式开始之前,我先提三个概念。首先,跟大多数操作系统一样,Linux 用户也需要一个账号才能登录。本文只介绍本地账号,不涉及网络账号,如 LDAP。其次,每个账号都有一个名字(username)和一个对应的数字(用户 ID)。最后,每个用户通常都在一个组内,每个组都有一个名字和一个组 ID。 你可能已经想到了,Linux 提供了添加用户的命令行工具,就是 `useradd` 命令。有些版本也叫 `adduser`。为了方便使用,很多发行版上这个命令是一个指向 `useradd` 命令的符号链接。 ``` $ file `which adduser` /usr/sbin/adduser: symbolic link to useradd ``` 来看一下 `useradd`。 > > 注意:本文描述的默认环境是 Red Hat Enterprise Linux 8.0。你可能会发现本文描述的这些文件和某些默认值与某些 Linux 发行版或其他 Unix 操作系统(FreeBSD 或 Solaris)偶尔会有差异。 > > > ### 默认处理 `useradd` 的基本用法相当简单:提供一个用户名就可以添加一个用户。 ``` $ sudo useradd sonny ``` 在本例中,`useradd` 命令创建了一个名为 `sonny` 的账号。此命令同时创建了一个同名的组,`sonny` 被放进了这个组,这个组也是 `sonny` 账号的主组。命令执行时,根据配置文件 `/etc/default/useradd` 和 `/etc/login.defs` 中的不同设置,也会有其他的参数,如语言和 shell。对于一个私人系统或微小的单服务商业环境,这些参数已经足够了。 上面两个文件控制 `useradd` 的处理,用户的信息保存在 `/etc` 目录下的一些其他文件中,关于这些信息的讲解会贯穿全文。 | 文件 | 描述 | 域 (加粗的表示由 useradd 命令设置) | | --- | --- | --- | | `passwd` | 存储用户账号信息 | **用户名**:未使用:**UID**:**GID**:**备注**:**家目录**:**shell** | | `shadow` | 存储用户账号的安全信息 | **用户名**:加密密码:上次修改时间:最短使用天数:最长使用天数间:**修改前警示天数**:**过期后宽限时间**:未使用 | | `group` | 存储组信息 | **组名**:未使用:**GID**:**成员列表** | ### 自定义处理 当管理员需要更好地控制账号时,可以使用命令行来自定义,如指定一个用户的 ID。 #### 用户和组 ID 默认情况下,`useradd` 试图使用相同的用户 ID(UID)和主组 ID(GID),但也不完全是。虽然 UID 与 GID 相同不是必须的,但如果相同,会更方便管理员管理。 下面的场景就是一个 GID 与 UID 不同的例子。现在我添加另一账号,名为 Timmy。通过使用 `getent` 命令来比较 `sonny` 和 `timmy` 两个账号,显示两个用户和对应的主组。 ``` $ getent passwd sonny timmy sonny:x:1001:1002:Sonny:/home/sonny:/bin/bash timmy:x:1002:1003::/home/timmy:/bin/bash $ getent group sonny timmy sonny:x:1002: timmy:x:1003: ``` 不幸的是,两者的 UID 和 GID 都不相同。因为默认的处理是,创建用户时,把下一个可用的 UID 赋给用户,然后把同一个数字作为主组 ID 赋给它。然而,当要使用的组 ID 已经被使用时,就再把下一个可用的 GID 赋给它。为了弄清细节,我猜想 1001 这个 GID 已经被使用了,用一个命令确认了一下。 ``` $ getent group 1001 book:x:1001:alan ``` `book` 的 ID 是 `1001`,因此新创建的用户的 GID 都有偏移量 1。这就是为什么系统管理员在用户创建过程中需要多设置一些值的一个实例。为了解决这个问题,我必须先确定下一个可用的 UID 和 GID 是否相同。确定下一个可用值时,可以使用 `getent group` 和 `getent passwd` 命令,通过 `-u` 参数传递要确认的值。 ``` $ sudo useradd -u 1004 bobby $ getent passwd bobby; getent group bobby bobby:x:1004:1004::/home/bobby:/bin/bash bobby:x:1004: ``` 另一个需要指定 ID 的场景是,通过 NFS 访问远程系统上的文件时。对于一个给定的用户,当 NFS 所有客户端和服务系统的 ID 都一样时,管理员更容易控制。在我的文章 [使用 autofs 挂载 NFS](https://opensource.com/article/18/6/using-autofs-mount-nfs-shares) 中有详细介绍。 ### 更多自定义 一些其他的指定用户信息的参数也用得比较频繁。这里是一些你会经常用到的参数的概括例子。 #### 注释 注释选项是通过 `-c` 参数指定的一个解释文本字段,可以提供一段简短的描述或其他信息。 ``` $ sudo useradd -c "Bailey is cool" bailey $ getent passwd bailey bailey:x:1011:1011:Bailey is cool:/home/bailey:/bin/bash ``` #### 组 一个用户可以被指定一个主组和多个次组。`-g` 参数指定主组名称或 GID。如果不指定,`useradd` 会以用户名创建一个主组(前面演示过)。`-G`(大写)参数用一个逗号分隔的组列表来指定此用户所属的组,这些组就是次组。 ``` $ sudo useradd -G tgroup,fgroup,libvirt milly $ id milly uid=1012(milly) gid=1012(milly) groups=1012(milly),981(libvirt),4000(fgroup),3000(tgroup) ``` #### 家目录 `useradd` 的默认处理是,在 `/home` 目录下创建用户的家目录。然而,下面的参数可以改写家目录的基础目录。`-b` 设置另一个可以创建家目录的基础目录。例如指定 `/home2` 而不是 `/home`。 ``` $ sudo useradd -b /home2 vicky $ getent passwd vicky vicky:x:1013:1013::/home2/vicky:/bin/bash ``` `-d` 参数可以指定一个与用户名不同的家目录。 ``` $ sudo useradd -d /home/ben jerry $ getent passwd jerry jerry:x:1014:1014::/home/ben:/bin/bash ``` #### 目录模板 指定 `-k` 参数会在创建新用户时,复制 `/etc/skel` 目录下的所有文件到用户的家目录中。这些文件通常是 shell 配置文件,当然也可以是系统管理员想在新建用户时使用的任何文件。 #### Shell `-s` 参数可以指定 shell。如果不指定,则使用默认的 shell。例如,下面的例子中 ,配置文件中定义的 shell 是 `bash`,但 `wally` 这个用户指定的是 `zsh`。 ``` SHELL=/bin/bash $ sudo useradd -s /usr/bin/zsh wally $ getent passwd wally wally:x:1004:1004::/home/wally:/usr/bin/zsh ``` #### 安全 安全是用户管理的重中之重,因此 `useradd` 命令也提供了很多关于安全的选项。可以使用 `-e` 参数,以 YYYY-MM-DD 的格式指定一个用户的过期时间。 ``` $ sudo useradd -e 20191231 sammy $ sudo getent shadow sammy sammy:!!:18171:0:99999:7::20191231: ``` 当密码过期时,账号也会自动失效。`-f` 参数指定密码过期后经过几天账号失效。如果设为 0,则立即失效。 ``` $ sudo useradd -f 30 willy $ sudo getent shadow willy willy:!!:18171:0:99999:7:30:: ``` ### 实例 生产环境中,创建一个用户账号时会用到多个参数。例如,我要创建一个 Perry 账号,可能会用下面的命令: ``` $ sudo useradd -u 1020 -c "Perry Example" \ -G tgroup -b /home2 \ -s /usr/bin/zsh \ -e 20201201 -f 5 perry ``` 查看前面的内容来理解每个选项。用下面的命令确认结果: ``` $ getent passwd perry; getent group perry; getent shadow perry; id perry perry:x:1020:1020:Perry Example:/home2/perry:/usr/bin/zsh perry:x:1020: perry:!!:18171:0:99999:7:5:20201201: uid=1020(perry) gid=1020(perry) groups=1020(perry),3000(tgroup) ``` ### 一点小建议 `useradd` 命令是所有 Unix(不仅仅是 Linux)系统管理员都必知必会的命令。由于用户创建不能出错,需要第一次就正确,所以理解它的每一个选项很重要。这意味着你需要有一套深思熟虑的命名约定,包括为整个企业环境而不仅仅是一个单系统预留一个专用的 UID/GID 范围,尤其是你为一个成长中的组织工作时。 --- via: <https://opensource.com/article/19/10/linux-useradd-command> 作者:[Alan Formy-Duval](https://opensource.com/users/alanfdoss) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Adding a user is one of the most fundamental exercises on any computer system; this article focuses on how to do it on a Linux system. Before getting started, I want to mention three fundamentals to keep in mind. First, like with most operating systems, Linux users need an account to be able to log in. This article specifically covers local accounts, not network accounts such as LDAP. Second, accounts have both a name (called a username) and a number (called a user ID). Third, users are typically placed into a group. Groups also have a name and group ID. As you'd expect, Linux includes a command-line utility for adding users; it's called **useradd**. You may also find the command **adduser**. Many distributions have added this symbolic link to the **useradd** command as a matter of convenience. ``` $ file `which adduser` /usr/sbin/adduser: symbolic link to useradd ``` Let's take a look at **useradd**. Note: The defaults described in this article reflect those in Red Hat Enterprise Linux 8.0. You may find subtle differences in these files and certain defaults on other Linux distributions or other Unix operating systems such as FreeBSD or Solaris. ## Default behavior The basic usage of **useradd** is quite simple: A user can be added just by providing their username. `$ sudo useradd sonny` In this example, the **useradd** command creates an account called *sonny*. A group with the same name is also created, and *sonny* is placed in it to be used as the primary group. There are other parameters, such as language and shell, that are applied according to defaults and values set in the configuration files **/etc/default/useradd** and **/etc/login.defs**. This is generally sufficient for a single, personal system or a small, one-server business environment. While the two files above govern the behavior of **useradd**, user information is stored in other files found in the **/etc** directory, which I will refer to throughout this article. File | Description | Fields (bold—set by useradd) | ---|---|---| passwd | Stores user account details | username:unused:uid:gid:comment:homedir:shell | shadow | Stores user account security details | username:password:lastchange:minimum:maximum:warn:inactive:expire:unused | group | Stores group details | groupname:unused:gid:members | ## Customizable behavior The command line allows customization for times when an administrator needs finer control, such as to specify a user's ID number. ### User and group ID numbers By default, **useradd** tries to use the same number for the user ID (UID) and primary group ID (GID), but there are no guarantees. Although it's not necessary for the UID and GID to match, it's easier for administrators to manage them when they do. I have just the scenario to explain. Suppose I add another account, this time for Timmy. Comparing the two users, *sonny* and *timmy*, shows that both users and their respective primary groups were created by using the **getent** command. ``` $ getent passwd sonny timmy sonny:x:1001:1002:Sonny:/home/sonny:/bin/bash timmy:x:1002:1003::/home/timmy:/bin/bash $ getent group sonny timmy sonny:x:1002: timmy:x:1003: ``` Unfortunately, neither users' UID nor primary GID match. This is because the default behavior is to assign the next available UID to the user and then attempt to assign the same number to the primary group. However, if that number is already used, the next available GID is assigned to the group. To explain what happened, I hypothesize that a group with GID 1001 already exists and enter a command to confirm. ``` $ getent group 1001 book:x:1001:alan ``` The group *book* with the ID *1001* has caused the GIDs to be off by one. This is an example where a system administrator would need to take more control of the user-creation process. To resolve this issue, I must first determine the next available user and group ID that will match. The commands **getent group** and **getent passwd** will be helpful in determining the next available number. This number can be passed with the **-u** argument. ``` $ sudo useradd -u 1004 bobby $ getent passwd bobby; getent group bobby bobby:x:1004:1004::/home/bobby:/bin/bash bobby:x:1004: ``` Another good reason to specify the ID is for users that will be accessing files on a remote system using the Network File System (NFS). NFS is easier to administer when all client and server systems have the same ID configured for a given user. I cover this in a bit more detail in my article on [using autofs to mount NFS shares](https://opensource.com/article/18/6/using-autofs-mount-nfs-shares). ## More customization Very often though, other account parameters need to be specified for a user. Here are brief examples of the most common customizations you may need to use. ### Comment The comment option is a plain-text field for providing a short description or other information using the **-c** argument. ``` $ sudo useradd -c "Bailey is cool" bailey $ getent passwd bailey bailey:x:1011:1011:Bailey is cool:/home/bailey:/bin/bash ``` ### Groups A user can be assigned one primary group and multiple secondary groups. The **-g** argument specifies the name or GID of the primary group. If it's not specified, **useradd** creates a primary group with the user's same name (as demonstrated above). The **-G** (uppercase) argument is used to pass a comma-separated list of groups that the user will be placed into; these are known as secondary groups. ``` $ sudo useradd -G tgroup,fgroup,libvirt milly $ id milly uid=1012(milly) gid=1012(milly) groups=1012(milly),981(libvirt),4000(fgroup),3000(tgroup) ``` ### Home directory The default behavior of **useradd** is to create the user's home directory in **/home**. However, different aspects of the home directory can be overridden with the following arguments. The **-b** sets another directory where user homes can be placed. For example, **/home2** instead of the default **/home**. ``` $ sudo useradd -b /home2 vicky $ getent passwd vicky vicky:x:1013:1013::/home2/vicky:/bin/bash ``` The **-d** lets you specify a home directory with a different name from the user. ``` $ sudo useradd -d /home/ben jerry $ getent passwd jerry jerry:x:1014:1014::/home/ben:/bin/bash ``` ### The skeleton directory The **-k** instructs the new user's new home directory to be populated with any files in the **/etc/skel** directory. These are usually shell configuration files, but they can be anything that a system administrator would like to make available to all new users. ### Shell The **-s** argument can be used to specify the shell. The default is used if nothing else is specified. For example, in the following, shell **bash** is defined in the default configuration file, but Wally has requested **zsh**. ``` $ grep SHELL /etc/default/useradd SHELL=/bin/bash $ sudo useradd -s /usr/bin/zsh wally $ getent passwd wally wally:x:1004:1004::/home/wally:/usr/bin/zsh ``` ### Security Security is an essential part of user management, so there are several options available with the **useradd** command. A user account can be given an expiration date, in the form YYYY-MM-DD, using the **-e** argument. ``` $ sudo useradd -e 20191231 sammy $ sudo getent shadow sammy sammy:!!:18171:0:99999:7::20191231: ``` An account can also be disabled automatically if the password expires. The **-f** argument will set the number of days after the password expires before the account is disabled. Zero is immediate. ``` $ sudo useradd -f 30 willy $ sudo getent shadow willy willy:!!:18171:0:99999:7:30:: ``` ## A real-world example In practice, several of these arguments may be used when creating a new user account. For example, if I need to create an account for Perry, I might use the following command: ``` $ sudo useradd -u 1020 -c "Perry Example" \ -G tgroup -b /home2 \ -s /usr/bin/zsh \ -e 20201201 -f 5 perry ``` Refer to the sections above to understand each option. Verify the results with: ``` $ getent passwd perry; getent group perry; getent shadow perry; id perry perry:x:1020:1020:Perry Example:/home2/perry:/usr/bin/zsh perry:x:1020: perry:!!:18171:0:99999:7:5:20201201: uid=1020(perry) gid=1020(perry) groups=1020(perry),3000(tgroup) ``` ## Some final advice The **useradd** command is a "must-know" for any Unix (not just Linux) administrator. It is important to understand all of its options since user creation is something that you want to get right the first time. This means having a well-thought-out naming convention that includes a dedicated UID/GID range reserved for your users across your enterprise, not just on a single system—particularly when you're working in a growing organization. ## Comments are closed.
11,758
2020 年对 Kubernetes 的 5 个预测
https://opensource.com/article/20/1/kubernetes-2020
2020-01-07T09:44:27
[ "Kubernetes" ]
/article-11758-1.html
> > 以及,对 2019 年最受欢迎的 Kubernetes 文章的回顾。 > > > ![](/data/attachment/album/202001/07/094358qucr5o2lu2lo23od.jpg) 你是怎么追踪一个广受欢迎的项目(如 Kubernetes)的发展轨迹?你是怎么了解它发展到什么程度了?如果你在为这个项目作贡献或加入了特殊兴趣组(SIG),可能你会在潜移默化中了解到它的发展轨迹,但如果你的全日工作不涉及到为 Kubernetes 作贡献,那么你可能需要一点关于未来的预测来帮助你了解。对于一个诸如 Kubernetes 的快速发展的项目,年末是回顾过去的一年和展望新的一年的最好时机。 今年,Kubernetes 取得了很大的进展。除了去查看源码、文档、会议笔记,你也可以去浏览博客。为了深入了解,我在 Opensource.com 上找到了 Kubernetes 排名前十的文章。通过这些文章,我们能了解开发者们更喜欢读和写哪些话题的文章。我们开始吧! * [为什么数据科学家喜欢Kubernetes](https://opensource.com/article/19/1/why-data-scientists-love-kubernetes) * [Kubernetes 机密信息和 ConfigMap 简介](https://opensource.com/article/19/6/introduction-kubernetes-secrets-and-configmaps) * [怎样在 Kubernetes 上运行 PostgreSQL](/article-10762-1.html)(译文) * [为什么说 Kubernetes 是一辆翻斗车](/article-11011-1.html)(译文) * [安全扫描你的 DevOps 流程](https://opensource.com/article/19/7/security-scanning-your-devops-pipeline) * [在 Kubernetes 上部署 InfluxDB 和 Grafana 以收集 Twitter 统计信息](https://opensource.com/article/19/2/deploy-influxdb-grafana-kubernetes) * [使用 Kubernetes 操作器扩展 PostgreSQL](https://opensource.com/article/19/2/scaling-postgresql-kubernetes-operators) * [使用 Kubernetes 控制器减少系统管理员的工作量](https://opensource.com/article/19/3/reducing-sysadmin-toil-kubernetes-controllers) * [将 Kubernetes 带到裸金属边缘计算](https://opensource.com/article/19/3/bringing-kubernetes-bare-metal-edge) * [为什么你不必担心 Kubernetes](https://opensource.com/article/19/10/kubernetes-complex-business-problem) 首先,我要指明这些文章中有 5 篇是关于 Kubernetes 工作负载的扩展以及它们可以运行在什么场景。这些工作负载涵盖数据科学、PostgreSQL、InfluxDB、Grafana(不仅仅监控集群本身)和边缘计算。从历史角度看,Kubernetes 和容器都是在虚拟机上运行的,尤其是运行在由云提供的基础设施上时。抛开对于 Kubernetes 的兴趣因素,这也表明了终端用户们极度希望在裸机上安装 Kubernetes(参照 [用 OpenShift 在裸机环境运行 Kubernetes](https://blog.openshift.com/kubernetes-on-metal-with-openshift/))。 其次,也有很多开发者希望了解操作相关的知识以及 Kubernetes 的最佳实践。从 [Kubernetes 操作器](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) 到 [Kubernetes 控制器](https://kubernetes.io/docs/concepts/architecture/controller/),从 [机密信息](https://kubernetes.io/docs/concepts/configuration/secret/) 到 [ConfigMaps](https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/),开发者和运维人员都希望能找到简化部署和管理工作的最佳实践。我们经常纠结在怎么去修改配置文件或别人会怎么配置,而不去回头想想这些配置是怎么让应用部署运转的(不是怎么安装,也不是怎么运行 Kubernetes)。 最后,人们似乎对入门教程真的感兴趣。事实上,构建 Kubernetes 所需了解的信息太多了,以至于让人们望而却步,也使他们走了错误的路。流行度高的文章中有几篇讲述了为什么你需要了解用 Kubernetes 运行应用程序,而不仅仅是安装它。就像最佳实践类的文章一样,人们也通常不会回头分析在入门时他们应该在什么地方花费时间。我一直秉持的理念是,把有限的时间和金钱投入到如何使用某项技术上,而不是如何构建它。 ### 2020 年对 Kubernetes 的 5 个预测 回顾了 2019 年的相关主题,这些主题告诉我们 2020 年将如何发展?结合这些文章中的观点,加上我自己的看法,我来分享下我对于 2020 年以及未来发展趋势的想法: 1. 工作负载扩展。我会关注高性能计算、AI/ML 以及使用操作器的有状态工作负载。 2. 更多的生产中的最佳实践,尤其是跟一些成熟的标准相关的,像 PCI、HIPAA、NIST 等等。 3. 提升免 root 和更安全的[运行时类](https://kubernetes.io/docs/concepts/containers/runtime-class/)(如 [gVisor](https://gvisor.dev/)、[Kata Containers](https://katacontainers.io/) 等等)的安全性。 4. 在部署和开发者们共享应用时,把 Kubernetes 清单的更好的规范标准作为部署的核心要素。如 [podman 生成 kube](https://developers.redhat.com/blog/2019/01/29/podman-kubernetes-yaml/)、[podman 运行 kube](https://www.redhat.com/en/blog/rhel-81-minor-release-major-new-container-capabilities),还有多合一 Kubernetes 环境,如 [CodeReady Containers (CRC)](https://developers.redhat.com/products/codeready-containers/overview) 5. 一个前所未有的网络、存储和专业硬件(如 GPU 等等)供应商的生态系统,为 Kubernetes 提供 BoB(LCTT 译注:best of breed,单项最佳品牌)解决方案(在自由软件中,我们相信开放的生态系统好过垂直整合的解决方案)。 期待 Kubernetes 在新的一年里再创辉煌! --- via: <https://opensource.com/article/20/1/kubernetes-2020> 作者:[Scott McCarty](https://opensource.com/users/fatherlinux) 选题:[lujun9972](https://github.com/lujun9972) 译者:[lxbwolf](https://github.com/lxbwolf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
11,760
提升自动化技巧的 10 篇 Ansible 文章
https://opensource.com/article/19/12/ansible-resources
2020-01-07T23:11:22
[ "Ansible" ]
https://linux.cn/article-11760-1.html
> > 今年,准备好,用出色的 Ansible 自动化技能装备自己的技能包吧。 > > > ![](/data/attachment/album/202001/07/231057fbtfjwrn29ficxj0.jpg) 今年我关注了大量关于 Ansible 的文章,以下这些内容都值得每个人学习,无论是否是 Ansible 的新手。 这些文章值得大家标记为书签,或者设置个计划任务(亦或者是设置一个 Tower/AWX 任务),用来提醒自己常读常新。 如果你是 Ansible 的新手,那么就从这些文章开始着手吧: * 《[Ansible 快速入门指南](https://opensource.com/article/19/2/quickstart-guide-ansible)》拥有一些对新手非常有用的信息,同时还介绍了一些更高级的话题。 * 《[你需要知道的 10 个 Ansible 模块](https://opensource.com/article/19/9/must-know-ansible-modules)》和《[5 个 Ansible 运维任务](/article-11312-1.html)》(译文)这两篇文章有每一位 Ansible 管理员都应该熟悉并认真研习的一些最基础的 Ansible 功能。 * 《[如何使用 Ansible 记录流程](https://opensource.com/article/19/4/ansible-procedures)》这篇文章是对一些额外话题的纵览,我猜你一定会感到很有趣。 剩余的这些文章包含了更多高级的话题,比如 Windows 管理、测试、硬件、云和容器,甚至包括了一个案例研究,如何管理那些对技术有兴趣的孩子的需求。 我希望你能像我一样好好享受 Ansible 带来的乐趣。不要停止学习哦! 1. 《[Ansible 如何为我的家庭带来和平](https://opensource.com/article/19/9/ansible-documentation-kids-laptops)》这个异想天开的案例,你能看到如何利用 Ansible 为孩子们快速部署一个新的笔记本(或者重装旧笔记本) 2. Taz Brown 和 Abner Malivert 的《[适用于 Windows 管理员的 Ansible](https://opensource.com/article/19/2/ansible-windows-admin)》:你知道 Ansible 也可以管理 Windows 的节点吗?这篇文章以部署一个 IIS 为案例,阐述了基础的 Ansible 服务器和 Windows 客户端的安装。 3. Shashank Hegde 的《[你需要知道的 10 个 Ansible 模块](https://opensource.com/article/19/9/must-know-ansible-modules)》是个学习你最应该知道的那些最常见、最基础的 Ansible 模块的好文章。运行命令、安装软件包和操作文件是许多有用的自动化工作的基础。 4. Marco Bravo 的《[如何使用 Ansible 记录流程](https://opensource.com/article/19/4/ansible-procedures)》:Ansible 的 YAML 文件易于阅读,因此它们可以被用于记录完成任务所需的手动步骤。这一特性可以帮助你调试与扩展,这令工作变得异常轻松。同时,这篇文章还包含关于测试和分析等 Ansible 相关主题的指导。 5. Clement Verna 的《[使用 Testinfra 和 Ansible 验证服务器状态](/article-10943-1.html)》(译文):测试环节是任何一个 CI/CD DevOps 流程不可或缺的一部分。所以为什么不把测试 Ansible 的运行结果也纳入其中呢?这个测试架构 Testinfra 的入门级文章可以帮助你检查配置结果。 6. Mark Phillips 的《[Ansible 硬件起步](https://opensource.com/article/19/5/hardware-bootstrapping-ansible)》:这个世界并不是完全已经被容器和虚拟机所占据。许多系统管理员仍然需要管理众多硬件资源。通过 Ansible 与一点 PXE、DHCP 以及其他技巧的结合,你可以创建一个方便的管理框架使硬件易于启动和运行。 7. Jairo da Silva Junior 的《[你需要了解的关于 Ansible 模块的知识](https://opensource.com/article/19/3/developing-ansible-modules)》:模块给 Ansible 带来了巨大的潜力,已经有许多模块可以拿来利用。但如果没有你所需的模块,那你可以尝试给自己打造一个。看看这篇文章吧,它能让你了解如何从零开始打造自己所需的模块。 8. Mark Phillips 的《[5 个 Ansible 运维任务](/article-11312-1.html)》(译文):这是另一个有关于如何使用 Ansible 来管理常见的系统操作任务的文章。这里描述了一系列可以取代命令行操作的 Tower(或 AWX)的案例。 9. Chris Short 的《[Ansible 快速入门指南](https://opensource.com/article/19/2/quickstart-guide-ansible)》是个可以下载的 PDF 文档。它可以作为一本随时拿来翻阅的手册。这篇文章的开头有助于初学者入门。同时,还包括了一些其他的研究领域,比如模块测试、系统管理任务和针对 K8S 对象的管理。 10. Mark Phillips 的《[Ansible 参考指南,带有 Ansible Tower 和 GitHub 的 CI/CD,等等](https://opensource.com/article/19/7/ansible-news-edition-one)》:这是一篇每月进行总结更新的文章,充满了有趣的链接。话题包括了 Ansible 的基础内容、管理 Netapp 的 E 系列存储产品、调试、打补丁包和其他一些相关内容。文章中还包括了一些视频以及一些聚会的链接。请查看详情。 如果你也有一些你喜爱的 Ansible 文章,那请留言告诉我们吧。 --- via: <https://opensource.com/article/19/12/ansible-resources> 作者:[James Farrell](https://opensource.com/users/jamesf) 选题:[lujun9972](https://github.com/lujun9972) 译者:[BrunoJu](https://github.com/BrunoJu) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
This year saw a wide range of really helpful Ansible articles. Whether you are just starting out with Ansible or a seasoned pro, there is something for everyone here to learn from. A good number of these articles are worthy of your bookmarking and perhaps a cron (or maybe a Tower/AWX job) reminder to reread them periodically. If you are new to Ansible, start with the following articles: has some good starter information as well as deeper dives into more advanced topics*A quickstart guide to Ansible*and*10 Ansible modules you need to know*review some of the more fundamental functions that every Ansible admin should be familiar with*5 ops tasks to do with Ansible*also presents a survey of additional topics you might find it interesting to follow up on*How to use Ansible to document procedures* The remainder of these articles cover more advanced topics like Windows management, testing, hardware, cloud, and containers—and even a case study in managing the demands of tech-curious children. I hope you enjoyed this Ansible year as much as I did. Never stop learning! is a whimsical case study in applying Ansible skills to quickly provision new (or rather old) laptops for my children.[How Ansible brought peace to my home](https://opensource.com/article/19/9/ansible-documentation-kids-laptops)by Taz Brown and Abner Malivert: Did you know Ansible can manage Windows nodes as well? This piece reviews basic Ansible server and Windows client setups with an example on how to deploy an IIS server.[Ansible for the Windows admin](https://opensource.com/article/19/2/ansible-windows-admin)by Shashank Hegde is a great place to start for some of the most common and basic Ansible modules all admins should know. Running commands, installing packages, and handling files are the basis for many useful automation plays.[10 Ansible modules you need to know](https://opensource.com/article/19/9/must-know-ansible-modules)by Marco Bravo: Ansible’s YAML files make for easy reading, so much so that they can be used to document the manual steps needed to accomplish a task. This makes your work easier to debug and extend later on. Also contained in this article are pointers on related topics like testing and analysis.[How to use Ansible to document procedures](https://opensource.com/article/19/4/ansible-procedures)by Clement Verna: Testing is an integral part of any CI/CD DevOps pipeline, so why not test Ansible’s results as well? This primer on Testinfra can be used to help check the configuration results you need.[Using Testinfra with Ansible to verify server state](https://opensource.com/article/19/5/using-testinfra-ansible-verify-server-state)by Mark Phillips: Not all the world is containers and virtual machines. Many of us sysadmins still have significant hardware deployments to manage. With a little PXE dust and DHCP magic (among other tidbits), you can create a convenient framework using Ansible to get real hardware up and running easily.[Hardware bootstrapping with Ansible](https://opensource.com/article/19/5/hardware-bootstrapping-ansible)by Jairo da Silva Junior: Modules bring real power to Ansible. Many modules are already available, but when there is none, you may need to roll your own. Read this article to look a bit deeper into how modules are made.[What you need to know about Ansible modules](https://opensource.com/article/19/3/developing-ansible-modules)by Mark Phillips: This is another more basic review of Ansible use to manage common system operations tasks. The draw here is the list of examples given in Tower (or AWX) instead of the old familiar command line.[5 ops tasks to do with Ansible](https://opensource.com/article/19/8/ops-tasks-ansible)by Chris Short is a great PDF download that you should keep on hand and reread from time to time. It begins with a great primer to get started in Ansible. It also covers other areas of interest including Molecule testing, sysadmin tasks, and Kubernetes object management, to name a few.[A quickstart guide to Ansible](https://opensource.com/article/19/2/quickstart-guide-ansible)by Mark Phillips: This is a monthly round-up article full of interesting links to follow. Topics span Ansible basics, managing Netapp E-Series storage, debugging, patching, and more. Videos are included here as well as some pointers to Ansible meetup groups. Check it out![An Ansible reference guide, CI/CD with Ansible Tower and GitHub, and more news](https://opensource.com/article/19/7/ansible-news-edition-one) Let us know if you had a favorite Ansible article this year and why in the comments. ## 2 Comments
11,762
给儿童和青少年的 7 件创客礼物
https://opensource.com/article/19/11/maker-gifts-kids
2020-01-08T14:06:49
[ "礼物", "创客" ]
https://linux.cn/article-11762-1.html
> > 这份礼物指南使你轻松完成节日礼物的采购,它们可给婴儿、儿童、青少年及年龄更大的人们带来创造和创新能力。 > > > ![](/data/attachment/album/202001/08/140516t4ewey9ryu24tpz5.jpg) 还在纠结这个假期给年轻人买什么礼物?这是我精选的开源礼物,这些礼物将激发未来的创意和灵感。 ### 蜂鸟机器人套件 ![Hummingbird Robotics Kit](/data/attachment/album/202001/08/140700n89lttz019kssds1.png "Hummingbird Robotics Kit") **年龄:**8 岁 - 成人 **这是什么:**[蜂鸟机器人套件](https://www.birdbraintechnologies.com/hummingbirdbit/)是一套完整的机器人套件,带有微控制器、电机、LED 和传感器。机器人的大脑具有特殊的端口,小手可以轻松地将其连接到机器人的组件上。蜂鸟套件并没有身体,而是鼓励用户自己创建一个。 **为什么我喜欢它:**蜂鸟可以使用多种编程语言 —— 从可视化编程(BirdBlox、MakeCode、Snap)到代码编程(Python 和 Java)—— 可以随着用户编码技能的提高而可扩展。所有组件均与你在电子商店中找到的组件完全相同,没有像其他机器人套件那样被塑料所遮盖。这使机器人的内部工作不再神秘,并在你需要时易于采购更多零件。 由于没有固定组装项目,因此蜂鸟是发挥创造力的完美机器人。 蜂鸟具有开源的软件和固件。它适用于 Linux、Windows、Mac、Chromebook、Android 和 iOS。 **费用:**起价为 99 美元。 ### Makey Makey 经典版 ![Makey Makey Classic](/data/attachment/album/202001/08/140710lknwcis2k232ri82.jpg "Makey Makey Classic") **年龄:** 6岁 - 成人 **这是什么:** [Makey Makey 经典版](https://makeymakey.com/)可将任何导电物体(从棉花糖到你的朋友)变成计算机钥匙。 你可以使用鳄鱼夹将 Makey Makey 连接到你选择的导电物体上。然后,通过同时触摸两个导电物体来闭合接地和任何触发键之间的电路。Makey Makey 是一种安全的方法,可以安全地在家中探索电力,同时创造与计算机进行交互的有趣方式。 **为什么我喜欢它:** Makey Makey 可以与 Scratch 开发的视频游戏搭配使用,以创建独特的控制器,使用户进一步沉浸在游戏中。从用卫生纸卷和铝箔制成的工具到互动艺术和故事,可能性是无限的。它可以在具有 USB 端口的 Linux、Windows 和 Mac 计算机上使用。 **费用:** 49.95 美金 ### Arduino Uno ![Arduino Uno](/data/attachment/album/202001/08/140717hc79mzgpsj3cr0cg.jpg "Arduino Uno") **年龄:** 10 岁 - 成人 **这是什么:** Arduino 是随同电子套件购买的微控制器,也可以单独购买,它们具有多种版本,而我最喜欢 [Arduino Uno](https://www.arduino.cc/)。你可以根据需要从任何电子商店购买其他组件,例如 LED、电机和传感器。 **为什么我喜欢它:** Arduino Uno 的文档很完善,因此创客们很容易在线上找到教程。Arduino 可以实现从简单到复杂的各种电子项目。Arduino 具有开源的固件和硬件。它适用于 Linux、Mac 和 Windows。 **费用:** 主板的起价为 22.00 美元。总成本取决于项目和技能水平。 ### DIY 创客套件 ![A maker kit assembled in a quick trip to the hardware store](/data/attachment/album/202001/08/140728xqy5qao5aifftmf5.jpg "A maker kit assembled in a quick trip to the hardware store") **年龄**:8 岁 - 成人 **这是什么:**当今许多创客、发明家和程序员都是从鼓捣碰巧出现在身边东西开始的。你可以快速前往最近的电子产品商店,为家里的年轻人创建一套出色的创客工具包。这是我的创客工具包中的内容: * 护目镜 * 锤子 * 钉子和螺丝 * 碎木 * 螺丝起子 * 电线 * LED * 压电蜂鸣器 * 马达 * 带引线的 AA 电池组 * 剪线钳 * 纸板 * 美纹纸胶带 * 废布 * 纽扣 * 线程 * 针 * 拉链 * 钩子 * 一个很酷的工具盒,用来存放所有东西 **我为什么喜欢它:**还记得小时候,你把父母带回家的空纸箱变成了宇宙飞船、房屋或超级计算机吗?这就是为大孩子们准备的 DIY 创客工具包。 原始的组件使孩子们可以尝试并运用他们的想象力。DIY 创客工具包可以完全针对接收者定制。可以放入一些接受这份礼品的人可能从未想到过用之发挥创意的某些组件,例如为下水道提供一些 LED 或木工结构。 **费用:**不等 ### 启发式游戏篮 ![Heuristic play kit](/data/attachment/album/202001/08/140735p5bf9zdvvrd9f859.jpg "Heuristic play kit") **年龄:** 8 个月至 5 岁 **这是什么:**启发式游戏篮充满了由天然、无毒材料制成的有趣物品,可供婴幼儿使用其五种感官进行探索。这是一种开放式、自娱自乐的游戏。其想法是,成年人将监督(但不指导)儿童使用篮子及其物品半小时,然后将篮子拿走,等下一次再玩。 创建带有常见家用物品的可爱游戏篮很容易。尝试包括质地、声音、气味、形状和重量各不相同的物品。这里有一些想法可以帮助您入门。 * 漏勺或脊状柳条篮可容纳所有物品 * 木勺子 * 金属打蛋器和汤匙 * 板刷 * 海绵 * 小型鸡蛋纸箱 * 纸板管 * 小擀面杖 * 带纹理的毛巾 * 岩石 * 手铃 * 钩针桌巾 * 带盖的小铁罐 游戏篮中不应包括任何容易破碎的东西或足够小到可以装入纸巾卷的东西,因为它们有窒息危险,应将所有物品彻底清洁后再交给孩子。 **我为什么喜欢它:**游戏篮非常适合感官发育,并可以帮助幼儿提出问题和探索周围的世界。这是培养创客思维方式的重要组成部分! 很容易获得适合这个游戏篮的物品。你可能已经在家中或附近的二手商店里找到了很多有趣的物品。幼儿使用游戏篮的方式与婴儿不同。随着孩子们开始模仿成人生活并通过他们的游戏讲故事,这些物品将随孩子一起成长。 **费用:**不等 ### 《Hello Ruby》 ![Hello Ruby book cover](/data/attachment/album/202001/08/140745pxlty5fetnl5ze8q.jpg "Hello Ruby book cover") **年龄**:5-8 岁 **这是什么:** 《[Hello Ruby](https://www.helloruby.com/):编码历险记》是 Linda Liukas 的插图书,通过有趣的故事讲述了一个遇到各种问题和朋友(每个都用一个码代表)的女孩,向孩子们介绍了编程概念。Liukas 还有其他副标题为《互联网探险》和《计算机内的旅程》的《Hello Ruby》系列书籍,而《编码历险记》已以 20 多种语言出版。 **为什么我喜欢它:**作者在书中附带了许多免费、有趣和无障碍的活动,可以从 Hello Ruby 网站下载和打印这些活动。这些活动教授编码概念、还涉及艺术表达、沟通、甚至时间安排。 **费用:**精装书的标价为 17.99 美元,但你可以通过本地或在线书店以较低的价格买到这本书。 ### 《编程少女:学会编程和改变世界》 ![Girls Who Code book cover](/data/attachment/album/202001/08/140750nn1wiaf1i1i6xaf7.jpg "Girls Who Code book cover") **年龄**:10 岁 - 成人 **内容是什么:**由《编程少女》的创始人 Reshma Saujani 撰写,《[编程少女:学会编程和改变世界](https://girlswhocode.com/book/girls-code-learn-code-change-world/)》为年轻女孩(以及男孩)提供了科技领域的实用信息。它涵盖了广泛的主题,包括编程语言、用例、术语和词汇、职业选择以及技术行业人士的个人简介和访谈。 **为什么我喜欢它:**本书以讲述了大多数面向成年人的网站都没有的技术故事。这些技术涉及许多学科,对于年轻人来说,重要的是要了解他们可以使用它来解决现实世界中的问题并有所作为。 **成本:**精装书的标价为 17.99 美元,平装书的标价为 10.99 美元,但你可以通过本地或在线书店以更低的价格找到。 --- via: <https://opensource.com/article/19/11/maker-gifts-kids> 作者:[Jess Weichler](https://opensource.com/users/cyanide-cupcake) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Struggling with what gifts to give the young person in your life this holiday season? Here are my top picks for open source presents that will spark creativity and inspire for years to come. ## Hummingbird Robotics Kit ![Hummingbird Robotics Kit Hummingbird Robotics Kit](https://opensource.com/sites/default/files/uploads/hummingbird.png) **Ages**: 8 to adult **What it is: **The [Hummingbird Robotics Kit](https://www.birdbraintechnologies.com/hummingbirdbit/) is a complete robotics kit with a microcontroller, motors, LEDs, and sensors. The robot brain has special ports that little hands can easily attach robot components to. The Hummingbird kits don't come with a body, empowering users to create their own. **Why I love it: **The Hummingbird works with multiple programming languages—from visual (BirdBlox, MakeCode, Snap) to text (Python and Java)— making it scalable as users' coding skills increase. All the components are exactly as you'd find them at an electronics store, not obscured by plastic like other robot kits. This demystifies the inner workings of robots and makes it easy to source more parts if needed. Because there is no set project, the Hummingbird is the perfect robot for creativity. The Hummingbird Bit has open source software and firmware. It works on Linux, Windows, Mac, Chromebook, Android, and iOS. **Cost:** Starts at US$ 99. ## Makey Makey Classic ![Makey Makey Classic Makey Makey Classic](https://opensource.com/sites/default/files/uploads/makeymakey2.jpg) **Ages:** 6 to adult **What it is: **[Makey Makey Classic](https://makeymakey.com/) turns any conductive object, from marshmallows to a friend, into a computer key. You use alligator clips to connect the Makey Makey to the conductive object of your choice. Then, you close the circuit between the ground connection and any trigger key by touching both conductive objects at the same time. The Makey Makey is a good way to safely explore electricity at home while creating interesting ways to interact with your computer. **Why I love it: **Makey Makey can be paired with video games made in Scratch to create unique controllers that further immerse users in the game. The possibilities are endless, from instruments made of toilet rolls and foil to interactive art and stories. It works on Linux, Windows, and Mac computers with a USB port. **Cost:** US$ 49.95 ## Arduino Uno ![Arduino Uno Arduino Uno](https://opensource.com/sites/default/files/uploads/arduinouno.jpg) **Ages**: 10 to adult **What it is: **Arduinos are microcontrollers that can be purchased with or without an electronics kit, and they come in many different flavors, though I like the [Arduino Uno](https://www.arduino.cc/) the best. Additional components, such as LEDs, motors, and sensors can be purchased as needed from any electronics shop. **Why I love it: **The Arduino Uno is well-documented, so it's easy for makers to find tutorials online. The Arduino can bring a wide variety of electronic projects to life, from simple to complex. The Arduino features open source firmware and hardware. It works on Linux, Mac, and Windows. **Cost:** Starts at US$ 22.00 for the board. The overall cost varies depending on projects and skill level. ## DIY maker kit ![A maker kit assembled in a quick trip to the hardware store A maker kit assembled in a quick trip to the hardware store](https://opensource.com/sites/default/files/makerbox-makerkit.jpg) Image by Jess Weichler, CC-BY-SA **Ages**: 8 to adult **What it is: **Many of today's makers, creators, and programmers started out tinkering with objects that happened to be lying around. You can create an awesome maker kit for the young person in your life with a quick trip to the nearest electronics store. Here's what's in my maker kit: - Eye goggles - Hammer - Nails and screws - Scraps of wood - Screwdrivers - Wire - LEDs - Piezo buzzer - Motors - AA battery pack with leads - Wire cutters - Cardboard - Masking tape - Scrap fabric - Buttons - Thread - Needles - Zippers - Hooks - A cool tackle box to store everything in **Why I love it: **Remember when you were a kid and your parents brought home an empty cardboard box that you turned into a spaceship or a house or a supercomputer? That's what a DIY maker kit can be for older kids. Raw components empower kids to experiment and use their imaginations. A DIY maker kit can be completely customized for the recipient. Be sure to throw in some components the giftee may have never thought to create with, like giving an avid sewer some LEDs or a woodworker fabric. **Cost:** Variable ## Heuristic play basket ![Heuristic play kit Heuristic play kit](https://opensource.com/sites/default/files/makerbox-sensorykit.jpg) opensource.com **Ages:** 8 months to 5 years **What it is: **Heuristic play baskets are filled with interesting objects made from natural, non-toxic materials for infants and toddlers to explore using their five senses. It's open-ended, self-directed play at its best. The idea is that an adult will supervise (but not direct) a child's use of the basket and its items for a half-hour, then put the basket away until the next time. It's easy to create a lovely play basket with common household objects. Try to include items with varying textures, sounds, smells, shapes, and weights. Here are some ideas to get you started. - Colander or ridged wicker basket to hold everything - Wooden spoon - Metal whisks and spoons - Scrubbing brush - Sponge - Small egg carton - Cardboard tubes - Small rolling pin - Textured washcloth - Rocks - Handbells - Crochet doily - Small tin with a lid Play baskets should not include anything easily breakable or small enough to fit inside a paper towel roll, as these are choking hazards, and all objects should be cleaned thoroughly before being given to a child. **Why I love it: **Play baskets are fantastic for sensory development and helping young children ask questions and explore the world around them. This is an important part of developing a maker mindset! It's easy to obtain suitable items for a play basket; you probably already have many interesting objects in your home or at your nearest second-hand store. Toddlers will use their play baskets differently than infants. These objects will grow with children as they begin to mimic adult life and tell stories through their play. **Cost:** Variable ## Hello Ruby ![Hello Ruby book cover Hello Ruby book cover](https://opensource.com/sites/default/files/uploads/helloruby2.jpg) **Ages**: 5–8 **What it is: *** Hello Ruby: Adventures in Coding* is an illustrated book by Linda Liukas that introduces children to programming concepts through a fun narrative about a girl who encounters problems and friends, each of which represents code. Liukas' other *Hello Ruby*books are subtitled *Expedition to the Internet*and *Journey Inside the Computer*, and *Adventures in Coding*has been published in more than 20 languages. **Why I love it: **The author accompanies the book with a number of free, fun, and unplugged activities that can be downloaded and printed out from the Hello Ruby website. These activities teach coding concepts and also touch on artistic expression, communication, and even time management. **Cost:** List price for the hardcover book is US$ 17.99, but you may find it at a lower price through local or online booksellers. ## Girls Who Code: Learn to Code and Change the World ![Girls Who Code book cover Girls Who Code book cover](https://opensource.com/sites/default/files/uploads/girlswhocodebook.jpg) **Ages**: 10 to adult **What it is: **Written by Reshma Saujani, the founder of Girls Who Code, * Girls Who Code: Learn to Code and Change the World* gives practical information about the tech world for young girls (and boys). It covers a wide variety of topics, including coding languages, use-cases, terminology and vocabulary, career options, and profiles and interviews with people in the tech industry. **Why I love it: **This book tells the story of tech in ways even most websites meant for adults miss out on. Technology encompasses so many disciplines, and it's important for young people to understand they can use it to solve real-world problems and make a difference. **Cost:** List price for the hardcover book is US$ 17.99 and US$ 10.99 for the paperback, but you may find it at a lower price through local or online booksellers. ## Comments are closed.
11,764
Signal:安全、开源的聊天应用
https://itsfoss.com/signal-messaging-app/
2020-01-09T07:56:42
[ "聊天", "隐私" ]
https://linux.cn/article-11764-1.html
> > Signal 是一款智能手机上的安全开源聊天应用。它还提供了适用于 Linux、Windows 和 macOS 的独立桌面应用。在本文中,我们来看看它的功能和可用性。 > > > ### 对于关注隐私的人来说,Signal 是 WhatsApp(和 Telegram)的绝佳替代品 ![Signal App On Linux](/data/attachment/album/202001/09/075645lq16t81tllwc8zil.jpg) Signal 是一款关注隐私的开源应用。像[爱德华·斯诺登](https://en.wikipedia.org/wiki/Edward_Snowden)这样的隐私权倡导者建议使用它。 它可能没有 Telegram 或 WhatsApp 这么多的功能。但是,如果你想在交流时增强隐私,这是一个可靠的开源方案。 你可以在智能手机([iOS](https://apps.apple.com/us/app/signal-private-messenger/id874139669)/[Android](https://play.google.com/store/apps/details?id=org.thoughtcrime.securesms&hl=en_IN))上安装,也可以在 Linux、Windows 和 macOS 上安装。 ### Signal 的功能 **注意:** 某些功能是智能手机特有的。你可能无法在桌面应用上看到所有功能。 另请注意,目前,Signal 需要电话号码才能注册。如果你不想公开自己的私人电话号码,则可以使用 Google 语音或类似服务。 正如我已经提到的,这是为增强你的隐私而量身定制的。因此,用户体验可能不是你见过“最佳”的。但是,从隐私/安全角度考虑,我认为这是一个不错的选择。 ![Signal Features](/data/attachment/album/202001/09/075648tv4lls4pbqxtcg4p.jpg) #### 消失的消息 你可以为对话中的消息设置一个计时器,以便根据它自动删除消息。 本质上,对话中的任何人都可以激活此功能。因此,你可以控制对话中的消息时保留还是消失。 #### 用作默认短信应用 如果你想在短信中使用开源应用,那么只需进入 Signal 的设置,并将其设置为短信和彩信的默认设置。 #### 屏幕安全 有一个巧妙的功能可以阻止应用内截图,它就是“屏幕安全”。 如果你开启它,那么你将无法为应用中的任何对话截图。你可以从应用设置中找到启用或禁用它的选项。 它可能并不是对所有人有用,但你可以尝试一下。 #### 安全数字 如果你想与朋友一起验证加密的安全性,只需点击个人资料并向下滚动找到“查看安全数字”。 你可以扫描验证或者看一眼并标记为已验证。 #### 锁定消息 如果你使用了锁(密码/指纹)来保护应用,那么即使你的设备已解锁,你也无法在通知中看到消息。 因此,当 Signal 处于锁定状态收到通知时,你会注意到通知的内容为 “**Locked Message**”,这对于注重隐私的用户来说是一个加分项。 #### 其它功能 ![](/data/attachment/album/202001/09/075652uoe2mdt1dk2rfiim.jpg) 如你所期待的聊天应用,你可以使用几个标签,并且可以根据需要创建一个组。但是,你无法管理你的组,你只能添加成员和更改群头像。 此外,Signal 还为其应用支持生物识别。 ### 在 Ubuntu/Linux 上安装 Signal 不幸的是,你无法在你的 Linux 发行版上找到 .deb 或者 .AppImage。因此,你需要根据[官方安装说明](https://signal.org/download/)在终端上安装。 在终端中输入以下内容: ``` curl -s https://updates.signal.org/desktop/apt/keys.asc | sudo apt-key add - echo "deb [arch=amd64] https://updates.signal.org/desktop/apt xenial main" | sudo tee -a /etc/apt/sources.list.d/signal-xenial.list sudo apt update && sudo apt install signal-desktop ``` 只需在终端中一个接一个地复制并粘贴命令。 [Download Signal for Other Devices](https://signal.org/download/) ### 我对 Signal 的想法 我已经使用 Signal 有几年了,它的功能已经得到了改善。但是,我仍然认为可以改善用户体验。 在隐私方面,(在我看来)这绝对是我们已有软件的一个很好的替代方案。你可以尝试一下,看看它的使用效果如何。 如果你想尝试一下它,也可以看看它的 [GitHub 页面](https://github.com/signalapp)以获取最新的开发和 beta 版本。 与 WhatsApp 甚至 [Linux 上的 Telegram](https://itsfoss.com/install-telegram-desktop-linux/) 相比,Signal 可能不是流行的聊天应用。但是,你可以自己尝试一下,并鼓励你的朋友使用它。 你尝试过了吗?在下面的评论中,让我知道你对 “Signal” 的看法。 --- via: <https://itsfoss.com/signal-messaging-app/> 作者:[Ankush Das](https://itsfoss.com/author/ankush/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
*Brief: Signal is a secure open-source messaging app for smartphones. It also offers a standalone desktop app for Linux, Windows, and macOS*.* Here, we take a look at its features and usability.* ## Signal is an Excellent Alternative to WhatsApp (and Telegram) for Privacy Concerned People ![Signal Shot](https://itsfoss.com/content/images/wordpress/2019/12/signal-shot.jpg) Signal is an open source application with a keen focus on privacy. It is recommended by privacy advocates like [Edward Snowden](https://en.wikipedia.org/wiki/Edward_Snowden). It may not have as many features as Telegram or WhatsApp – but if you want to enhance your privacy while having a conversation, this is a solid open-source solution. You can install it on your smartphone ([iOS](https://apps.apple.com/us/app/signal-private-messenger/id874139669)/[Android](https://play.google.com/store/apps/details?id=org.thoughtcrime.securesms&hl=en_IN)) and it is also available for Linux, Windows, and macOS. ## Features of Signal Messenger **Note:** *Some of the features are specific/exclusive to smartphones. You may not observe all the features mentioned in the desktop app.* **Also note that, for now, Signal requires a phone number to register. If you do not want to expose your private phone number, you can use Google Voice or similar services.** As I already mentioned, this is tailored to enhance your privacy. So, the user experience may not be the “best” you’ve ever seen. But, privacy/security-wise, I think it is a good option to have. ![Signal Phone](https://itsfoss.com/content/images/wordpress/2019/12/signal-phone.jpg) ### Disappearing Messages You can set a timer for messages in a conversation – so that it will be automatically deleted as per the timer. Essentially, anyone in the conversation can activate this feature. So, you control if the messages should stay in a conversation or disappear. ### Use it As Default SMS App If you want to utilize an open-source app for all your SMSs, you can simply go to Signal’s app settings and set it as the default for SMS and MMS. ### Screen Security There’s a neat feature to block screenshots in-app, “Screen Security”. If you enable it, you won’t be able to take a screenshot of any conversation in the app. You can find the option to enable or disable it from the app settings. It may not be useful to everyone – but you can try it out. ### Safety Number If you want to verify the security of your encryption with a friend, you can simply tap on the profile and scroll down to find “View Safety Number”. You can either scan it to verify or simply take a look at it to mark it verified. ### Locked Messages If you protect the app with a lock (pin/fingerprint), even if your device has been unlocked, you won’t be able to see the messages on your notifications. So, when you get a notification while Signal is locked, you will notice the content of the notification as “**Locked Message**” – which is a plus for privacy-oriented users. ### Other Features ![Signal Shot 1](https://itsfoss.com/content/images/wordpress/2019/12/signal-shot-1.jpg) As you would expect in a messaging app – you get a couple of stickers to utilize and you can also create a group if you want. However, you won’t have the ability to moderate your group – you can just add members and change the profile picture. In addition to this, Signal also supports biometric security for its app. ## Installing Signal on Ubuntu/Linux Unfortunately, you don’t get a .**deb** or .**AppImage** to install it on your Linux distro. But you can still [install Signal on Ubuntu](https://itsfoss.com/install-signal-ubuntu/) using their repository. Here’s what you have to type in the terminal: ``` curl -s https://updates.signal.org/desktop/apt/keys.asc | sudo apt-key add - echo "deb [arch=amd64] https://updates.signal.org/desktop/apt xenial main" | sudo tee -a /etc/apt/sources.list.d/signal-xenial.list sudo apt update && sudo apt install signal-desktop ``` Simply copy-paste the commands one by one in the terminal and you should be good to go. ## My Thoughts On Signal I’ve been using Signal for a few years now and it has improved with what it offers. However, I still feel that the user experience can be improved. Privacy-wise, it is definitely a good alternative to what we already have (in my opinion). You can give it a try and see how well it works for your usage. You can also take a look at their [GitHub page](https://github.com/signalapp) for the latest developments and beta releases if you want to try them out. Signal app may not be a popular messaging app when compared to WhatsApp or even [Telegram on Linux](https://itsfoss.com/install-telegram-desktop-linux/). But, you can try it for yourself and encourage your friends to use an open-source messaging app. Have you tried it yet? Let me know what you think about the ‘Signal’ app in the comments below.
11,766
GNOME 有一个“隐藏”的屏幕录像机
https://itsfoss.com/gnome-screen-recorder/
2020-01-10T10:36:17
[ "GNOME" ]
https://linux.cn/article-11766-1.html
![](/data/attachment/album/202001/10/103524bx2wpxee2aefcgww.png) [GNOME](https://gnome.org/) 是[最受欢迎的桌面环境](https://itsfoss.com/best-linux-desktop-environments/)之一。它有现代的 UI,并且带有许多特定于 GNOME 的应用,这些应用与桌面整体外观完美融合。 你可以根据自己的喜好来[调整 GNOME](https://itsfoss.com/gnome-tweak-tool/),但我不在这里讨论。GNOME 桌面有一些你可能不知道的隐藏功能。 这种不太显眼的功能之一是内置的屏幕录像机。 是的,你没有看错。如果你使用的是 GNOME 桌面,那么不必安装其他的 [Linux 屏幕录像机](https://itsfoss.com/best-linux-screen-recorders/)。你只需要知道正确的快捷键即可。 ### 立即使用 GNOME 屏幕录像机录制屏幕 要快速打开 GNOME 屏幕录像机,你需要[在 Ubuntu 或其他带有 GNOME 桌面的发行版中按下此快捷键](https://itsfoss.com/ubuntu-shortcuts/): ``` Ctrl + Alt + Shift + R ``` 这将会立即开始录制你的桌面。你可以通过顶部的系统托盘区域的红点了解到正在录制: ![The red dot in the system tray area indicates that screen recording is in progress](/data/attachment/album/202001/10/103621nrhgxkhwecx5pnr2.jpg) #### 增加录制时间 默认的最大录制时间仅为 30 秒。但是可以增加。 打开终端并使用以下命令: ``` gsettings set org.gnome.settings-daemon.plugins.media-keys max-screencast-length 300 ``` 在上面的命令中,我将录音的最大长度增加到 300 秒(即 5 分钟)。你可以将其更改为任何其它值,但应以秒为单位。 如果你**不希望最长录音时间有任何限制,请将其设置为 `0`**,之后它会在你手动停止或者磁盘空间不足才会停止。 #### 停止屏幕录制 如前所述,你的桌面录制将在达到最大时间限制后自动停止。 要在此之前停止录制,你可以按下相同的组合键: ``` Ctrl + Alt + Shift + R ``` 你的录制内容将以 [webm](https://www.webmproject.org/about/) 格式保存在家目录的 `Videos` 文件夹中。 #### 局限性 尽管使用这个小工具可以方便地快速录制桌面,但是与功能强大的 [Simple Screen Recorder](https://itsfoss.com/record-screen-ubuntu-simplescreenrecorder/) 这样的屏幕录制工具相比,它有一些局限性。 * 录制开始之前没有时间延迟选项 * 没有暂停和播放选项 * 它录制整个屏幕。无法仅录制应用窗口、特定区域或特定屏幕(如果你有多个屏幕)。 * 视频以 webm 格式保存在用户的 `Videos` 目录中。你无法更改。你必须使用 [HandBrake 之类的工具将视频转换为其他格式](https://itsfoss.com/handbrake/)。 如你所见,这个秘密的 GNOME 屏幕录像机与 [Kazam](https://itsfoss.com/kazam-screen-recorder/) 之类的工具或其他此类工具所提供的功能相差很远。但是,它并不会尝试成为全功能的屏幕录像机。它只是为你提供录制屏幕的快速方法。 GNOME 是一个多功能的现代桌面环境。你可以大量地[调整 GNOME](https://itsfoss.com/gnome-tweak-tool/)。[GNOME 扩展](https://itsfoss.com/best-gnome-extensions/)为桌面自定义提供了另一个维度。 该屏幕录像机是 GNOME 的隐藏功能之一,就像你自己很难轻易找到的挂起选项。 你喜欢它吗?你是否还想与我们分享其他隐藏的 GNOME 功能?请在评论区留言。 --- via: <https://itsfoss.com/gnome-screen-recorder/> 作者:[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) GNOME is one of the [most popular desktop environments](https://itsfoss.com/best-linux-desktop-environments/) and for good reasons. It has a modern UI and it comes with a number of GNOME-specific applications that blend well with the overall desktop appearance. One such application is GNOME's built-in screen recorder! It is a simple screen recorder with limited features. It works on Wayland and Xorg both. Mind you, there are not many [screen recorders on Linux](https://itsfoss.com/best-linux-screen-recorders/) that support Wayland. But you won't get fancy features like delaying the recording or saving the output to a different path and format. Heck! You cannot even pause the recording. However, GNOME's recorder is simple, easy, and efficient to capture the screen for a certain amount of time. Let's see how to use it. ## Using the GNOME Screen recorder The screen recorder is actually combined with GNOME's screenshot tool. To start the screen recorder, you can use the Print Screen button to open the screenshot tool. You'll find a switch to toggle between screenshot (camera icon) and screencast (video camera icon). Toggle it to select the screen recording. ![GNOME Screen recorder](https://itsfoss.com/content/images/2023/03/gnome-screen-recorder.jpg) **Alternatively**, execute the key combination of `Alt + Ctrl + Shift + R` and it will get you the controls for recording immediately: ![GNOME screen recorder](https://itsfoss.com/content/images/2023/03/Selection_005.png) And as you can see, here, you have two options to choose from: - Select a portion of the screen to record - Use the entire screen to record The option to record a specific application window is not available while writing. ### Start the recording Now, let's look at **how you can record a specific portion of the screen** using a GNOME screen recorder. First, select the `Selection option` and set the size of the desired portion you want to record and start recording by pressing the 🔴 button: ![](https://itsfoss.com/content/images/2023/03/how-to-record-screen-using-GNOME-s-built-in-recorder-2.png) Yes, that's all it takes to record the desired portion of the screen. The process remains similar when you want to record the entire screen. **To record the entire screen**, select the `Screen` option and start recording by pressing the red button: ![](https://itsfoss.com/content/images/2023/03/record-the-entire-screen-using-GNOME-s-built-in-recorder.png) But how are you supposed to stop the recording? ### Stop the recording Once you start recording, you will see a timer on your top bar suggesting the length of the video. Which also acts as a stop button! So all you have to do is press that button to stop the video: ![stop recording in GNOME's in-built recorder](https://itsfoss.com/content/images/2023/03/stop-recording-in-GNOME-s-in-built-recorder.png) And your video will be saved under `/home/user/Videos/Screencasts` . `/home/user/Videos/Screencasts` with `.webm` extension.As I mentioned earlier, the GNOME Screen Recorder offers few features. You cannot pause the recording, select output file formats, show mouse clicks etc. If you want such fancy features, you can try the powerful OBS. It offers a lot of features but comes with a complex interface. [Screen Recording in Linux With OBS and WaylandThere are tons of screen recorders available for Linux. But when it comes to supporting Wayland, almost all of them do not work. This is problematic because many new distribution releases are switching to Wayland display manager by default once again. And if something as basic as a screen recor…](https://itsfoss.com/screen-record-obs-wayland/)![](https://itsfoss.com/content/images/wordpress/2021/09/obs-screen-record-wayland.webp) ![](https://itsfoss.com/content/images/wordpress/2021/09/obs-screen-record-wayland.webp) ## Want to convert the screen-recorded videos? The files will be saved with the `.webm` extension, which may not be the preferred video file for everyone. But worry not! **You can use FFmpeg** CLI utility that allows users to modify video file properties, including the media format: [The Complete Guide for Using ffmpeg in LinuxBrief: This detailed guide shows how to install ffmpeg in Ubuntu and other Linux distributions. It also demonstrates some useful ffmpeg commands for practical usage. ffmpeg is a CLI (command line based) utility for processing media files. It is a framework with a multitude of features and, beca…](https://itsfoss.com/ffmpeg/)![](https://itsfoss.com/content/images/wordpress/2019/03/ffmpeg-tutorial.png) ![](https://itsfoss.com/content/images/wordpress/2019/03/ffmpeg-tutorial.png) Sure, FFmpeg is great utility but new users won't be able to make the most out of it as it bombards you with tonnes of options at once. And for that purpose, you can use the Handbrake utility, which not just allows you to convert video files to different formats but has other useful features for you: [App Highlight: Open Source Video Transcoder HandbrakeBrief: HandBrake is a free and open-source video conversion tool that is quite useful. Let’s see what are its main features and how to use them for converting videos from one format to another. HandBrake: An Open Source Video Transcoder HandBrake is a quite useful tool which helps yo…](https://itsfoss.com/handbrake/)![](https://itsfoss.com/content/images/wordpress/2019/12/handbrake.jpg) ![](https://itsfoss.com/content/images/wordpress/2019/12/handbrake.jpg) Happy recording! And if you have some queries, feel free to ask me in the comments.
11,768
用 Git 来共享文件
https://opensource.com/article/19/4/file-sharing-git
2020-01-10T11:38:16
[ "Git" ]
https://linux.cn/article-11768-1.html
> > SparkleShare 是一个开源的基于 Git 的 Dropbox 风格的文件共享应用程序。在我们的系列文章中了解有关 Git 鲜为人知的用法。 > > > ![](/data/attachment/album/202001/10/113645qb2ufvuu2ttimugv.png) [Git](https://git-scm.com/) 是一个少有的能将如此多的现代计算封装到一个程序之中的应用程序,它可以用作许多其他应用程序的计算引擎。虽然它以跟踪软件开发中的源代码更改而闻名,但它还有许多其他用途,可以让你的生活更轻松、更有条理。在这个 Git 系列中,我们将分享七种鲜为人知的使用 Git 的方法。 今天,我们将看看 SparkleShare,它使用 Git 作为文件共享的基础。 ### 用于文件共享的 Git Git 的优点之一是它具有固有的分发能力。它可用来建立共享。即使你只是与自己网络上的其他计算机共享资源库,Git 也会为从共享位置获取文件的行为带来透明性。 随着其界面的发展,Git 变得非常简单。虽然因用户而异,他们坐下来完成一些工作时的共同点仅仅是 `git pull` 或稍微复杂一点的 `git pull && git checkout -b my-branch`。但是,对于某些人来说,将*命令输入*到他们的计算机中的做法完全是令人困惑或烦恼的。计算机旨在使生活变得轻松,它擅长于重复性工作,因此有更简便的方法可以与 Git 共享文件。 ### SparkleShare [SparkleShare](http://www.sparkleshare.org/) 项目是一个基于 Git 的跨平台的、开源的 Dropbox 式的文件共享应用程序。它通过将文件拖放到专门指定的 SparkleShare 目录中的简单操作,自动执行所有 Git 命令,触发添加、提交、推送和拉取过程。因为它基于 Git,所以你可以获得基于差异(diff)的快速推送和拉取,并且继承了 Git 版本控制和后端基础设施(如 Git 挂钩)的所有优点。它可以完全自托管,也可以将其与 [GitLab](http://gitlab.com)、GitHub、Bitbucket 等 Git 托管服务一起使用。此外,由于它基本上只是一个 Git 的前端,因此你可以在可能没有 SparkleShare 客户端但有 Git 客户端的设备上访问 SparkleShare 中的文件。 正如你获得 Git 的所有好处一样,你也会受到所有常见的 Git 限制:使用 SparkleShare 存储数百张照片、音乐和视频是不切实际的,因为 Git 是为文本而设计和优化的。Git 当然可以存储二进制文件的大文件,但是因为它可以跟踪历史记录,因此一旦将文件添加到其中,几乎就不可能完全删除它。这在某种程度上限制了 SparkleShare 对某些人的实用性,但使其非常适合许多工作流程,包括[日程安排](https://opensource.com/article/19/4/calendar-git)。 #### 安装 SparkleShare SparkleShare 是跨平台的,可从[网站](http://sparkleshare.org)获得适用于 Windows 和 Mac 的安装程序。对于 Linux,有一个 [Flatpak](/business/16/8/flatpak) 安装包,或者你可以在终端中运行以下命令: ``` $ sudo flatpak remote-add flathub https://flathub.org/repo/flathub.flatpakrepo $ sudo flatpak install flathub org.sparkleshare.SparkleShare ``` ### 创建一个 Git 存储库 SparkleShare 并不是软件即服务(SaaS)。你在计算机上运行 SparkleShare 与 Git 存储库进行通信,而 SparkleShare 并不存储你的数据。如果你还没有与文件夹同步的 Git 存储库,则必须在启动 SparkleShare 之前创建一个文件夹。你有三个选择:托管的 Git、自托管 Git 或自托管 SparkleShare。 #### 托管的 Git SparkleShare 可以使用你能访问的任何 Git 存储库进行存储,因此,如果你拥有 GitLab 或任何其他托管服务的帐户(或创建一个),则它可以成为 SparkleShare 的后端。例如,开源 [Notabug.org](http://notabug.org) 服务是一个类似于 GitHub 和 GitLab 的 Git 托管服务,但其独特性足以证明 SparkleShare 的灵活性。根据用户界面的不同,不同的托管服务创建新存储库的方法也有所不同,但是所有主要存储库都遵循相同的通用模型。 首先,在托管服务中找到创建新项目或存储库的按钮,单击它以开始。然后逐步完成存储库的创建过程,为存储库提供名称、隐私级别(存储库通常默认为公共),以及是否使用 `README` 文件初始化存储库。无论你是否需要个 `README` 文件,请初始化建立一个。使用一个文件来创建存储库不是绝对必要的,但是它会强制 Git 主机实例化存储库中的 `master` 分支,这有助于确保前端应用程序(例如 SparkleShare)具有要提交并推送的分支。即使文件是几乎空的 `README` 文件,也可以用来查看该文件以确认你已连接成功。 ![Creating a Git repository](/data/attachment/album/202001/10/113823cmb5wm5z871fjdoe.jpg "Creating a Git repository") 创建存储库后,获取其用于 SSH 克隆的 URL。就像从 Git 项目获得其 URL 一样,你也可以获取此 URL:导航至存储库页面并查找 “Clone” 按钮或字段。 ![Cloning a URL on GitHub](/data/attachment/album/202001/10/113825pwdydttne70rjruy.jpg "Cloning a URL on GitHub") *GitHub 的克隆 URL。* ![Cloning a URL on GitLab](/data/attachment/album/202001/10/113826a9ue0ee8csbebkar.jpg "Cloning a URL on GitLab") *GitLab 的克隆 URL。* 这是 SparkleShare 用于获取数据的地址,因此请记下它。你的 Git 存储库现已配置好。 #### 自托管的 Git 你可以使用 SparkleShare 访问你有权访问的任何计算机上的 Git 存储库。除了一个 Git 裸存储库外,无需任何特殊设置。但是,如果你想将对 Git 存储库的访问权授予其他任何人,则应运行 [Gitolite](http://gitolite.org) 之类的 Git 管理器或 SparkleShare 自己的 Dazzle 服务器来帮助你管理 SSH 密钥和帐户。至少,创建一个特定于 Git 的用户,以便有权访问你的 Git 存储库的用户不会自动获得对服务器其余部分的访问权限。 以 Git 用户身份登录服务器(如果你非常擅长管理用户和组权限,则可以以自己的用户登录)并创建存储库: ``` $ mkdir ~/sparkly.git $ cd ~/sparkly.git $ git init --bare . ``` 你的 Git 存储库现已配置好。 #### Dazzle SparkleShare 的开发人员提供了一个名为 [Dazzle](https://github.com/hbons/Dazzle) 的 Git 管理系统,以帮助你自托管 Git 存储库。 在你的服务器上,将 Dazzle 应用程序下载到你的路径中的某个位置: ``` $ curl https://raw.githubusercontent.com/hbons/Dazzle/master/dazzle.sh --output ~/bin/dazzle $ chmod +x ~/bin/dazzle ``` Dazzle 设置了一个特定于 Git 和 SparkleShare 的用户,并且还基于 SparkleShare 应用程序生成的密钥实现了访问权限。现在,只需设置一个项目: ``` $ dazzle create sparkly ``` 你的服务器现在已经配置好,可以用作 SparkleShare 托管了。 ### 配置 SparkleShare 首次启动 SparkleShare 时,系统会提示你配置 SparkleShare 用于存储的服务器。这个过程可能看起来像一个首次运行的安装向导,但实际上是在 SparkleShare 中设置新共享位置的通常过程。与许多共享驱动器应用程序不同,使用 SparkleShare 可以一次配置多个位置。你配置的第一个共享位置并不比你以后可以配置的任何共享位置更重要,并且你也不用注册 SparkleShare 或任何其他服务。你只是将 SparkleShare 指向 Git 存储库,以便它知道如何使第一个 SparkleShare 文件夹保持同步。 在第一个屏幕上,给出一个身份信息,SparkleShare 将在代表你进行的 Git 提交记录中使用这些信息。你可以使用任何内容,甚至可以使用不代表任何意义的伪造信息。它仅用于提交消息,如果你对审查 Git 后端进程没有兴趣,你可能甚至看不到它们。 下一个屏幕提示你选择主机类型。如果你使用的是 GitLab、GitHub、Planio 或 Bitbucket,则可以选择一个适当的。否则,请选择“自己的服务器”。 ![Choosing a Sparkleshare host](/data/attachment/album/202001/10/113828t1yvjjgsqg126uju.jpg "Choosing a Sparkleshare host") 在此屏幕底部,你必须输入 SSH 的克隆 URL。如果你是自托管的 Git,则地址类似于 `<ssh://[email protected]>`,而远程路径是为此目的而创建的 Git 存储库的绝对路径。 根据上面的自托管示例,我虚构的服务器的地址为 `ssh://[email protected]:22122`(`:22122` 表示一个非标准的 SSH 端口),远程路径为 `/home/git/sparkly.git`。 如果我改用 Notabug.org 帐户,则上例中的地址为 `ssh://[email protected]`,路径为 `seth/sparkly.git`。 SparkleShare 首次尝试连接到主机时会失败,因为你尚未将 SparkleShare 客户端 ID(特定于 SparkleShare 应用程序的 SSH 密钥)复制到 Git 主机。这是预料之中的,所以不要取消该过程。将 SparkleShare 设置窗口保持打开状态,并从系统任务栏中的 SparkleShare 图标处获取客户端 ID。然后将客户端 ID 复制到剪贴板,以便可以将其添加到 Git 主机。 ![Getting the client ID from Sparkleshare](/data/attachment/album/202001/10/113829b6sfd5bxnlfre1fx.jpg "Getting the client ID from Sparkleshare") #### 将你的客户端 ID 添加到托管的 Git 帐户 除了较小的 UI 差异外,在任何托管服务上添加 SSH 密钥(所有客户端 ID 都是这样)的过程基本上是相同的。在你的 Git 主机的 Web 仪表板中,导航到你的用户设置,然后找到 “SSH 密钥”类别。单击“添加新密钥”按钮(或类似按钮),然后粘贴你的 SparkleShare 客户端 ID 的内容。 ![Adding an SSH key](/data/attachment/album/202001/10/113832skvkcyjgz11gklcc.jpg "Adding an SSH key") 保存密钥。如果你希望其他人(例如协作者或家庭成员)能够访问同一存储库,则他们必须向你提供其 SparkleShare 客户端 ID,以便你可以将其添加到帐户中。 #### 将你的客户端 ID 添加到自托管的 Git 帐户 SparkleShare 客户端 ID 只是一个 SSH 密钥,因此将其复制并粘贴到 Git 用户的 `~/.ssh/authorized_keys` 文件中。 #### 使用 Dazzle 添加你的客户 ID 如果你使用 Dazzle 管理 SparkleShare 项目,请使用以下命令添加客户端 ID: ``` $ dazzle link ``` 当 Dazzle 提示你输入该 ID 时,请粘贴在 SparkleShare 菜单中找到的客户端 ID。 ### 使用 SparkleShare 将客户端 ID 添加到 Git 主机后,在 SparkleShare 窗口中单击“重试”按钮以完成设置。克隆存储库完成后,你可以关闭 SparkleShare 设置窗口,并在你的家目录中找到一个新的 `SparkleShare` 文件夹。如果你设置了带有托管服务的 Git 存储库,并选择包括 `README` 文件或许可证文件,则可以在 SparkleShare 目录中看到它们。 ![Sparkleshare file manager](/data/attachment/album/202001/10/113834wdjmljld2cd2djl0.jpg "Sparkleshare file manager") 此外,有一些隐藏目录,你可以通过在文件管理器中显示隐藏目录来查看。 ![Showing hidden files in GNOME](/data/attachment/album/202001/10/113837xnvay9nyzy4wwyi4.jpg "Showing hidden files in GNOME") 使用 SparkleShare 的方式与使用计算机上任何目录的方式相同:将文件放入其中。每当将文件或目录放入 SparkleShare 文件夹时,它都会在后台复制到你的 Git 存储库。 #### 排除某些文件 由于 Git 从设计上就是要记住*一切*,因此你可能希望从记录中排除特定的文件类型。排除一些文件是有原因的。通过定义摆脱 SparkleShare 管理的文件,可以避免意外复制大文件。你还可以为自己设计一种方案,使你可以将存储在一个目录中的逻辑上属于同一个文件(例如,MIDI 文件及其 .flac 导出文件),但是可以自己手动备份大文件,而同时让 SparkleShare 备份基于文本的文件。 如果在系统的文件管理器中看不到隐藏的文件,请显示它们。导航到你的 SparkleShare 文件夹,然后到代表你的存储库的目录,找到一个名为 `.gitignore` 的文件,然后在文本编辑器中将其打开。你可以在 `.gitignore` 中输入文件扩展名或文件名(每行一个),任何与你列出的文件匹配的文件都会被忽略(如文件名所示)。 ``` Thumbs.db $RECYCLE.BIN/ .DS_Store ._* .fseventsd .Spotlight-V100 .Trashes .directory .Trash-* *.wav *.ogg *.flac *.mp3 *.m4a *.opus *.jpg *.png *.mp4 *.mov *.mkv *.avi *.pdf *.djvu *.epub *.od{s,t} *.cbz ``` 你知道最经常遇到哪些文件类型,因此请集中精力处理最有可能潜入你的 SparkleShare 目录的文件。如果你想稍微矫枉过正一些,可以在 Notabug.org 以及整个网上找到 `.gitignore` 文件的好集合。 通过将这些条目保存在 `.gitignore` 文件中,你可以将不需要发送到 Git 主机的大文件放在 SparkleShare 目录中,SparkleShare 将完全忽略它们。当然,这意味着你需要确保它们可以备份或通过其他方式分发给你的 SparkleShare 协作者。 ### 自动化 [自动化](/downloads/ansible-quickstart) 是我们与计算机达成的默契之一:计算机执行重复的、无聊的工作,而我们人类要么不擅长做这些,要么不擅长记忆这些。SparkleShare 是一种很好的、简单的自动执行例行数据分发的方法。但不管怎么说,这并不适合每个 Git 存储库。它没有用于高级 Git 功能的接口,它没有暂停按钮或手动管理的操作。没关系,因为它的使用范围是有意限制的。SparkleShare 可以完成它计划要做的事情,它做得很好,而且它是你无需关心的一个 Git 存储库。 如果你想使用这种稳定的、看不见的自动化,请尝试一下 SparkleShare。 --- via: <https://opensource.com/article/19/4/file-sharing-git> 作者:[Seth Kenlon](https://opensource.com/users/seth) 选题:[lujun9972](https://github.com/lujun9972) 译者:[wxy](https://github.com/wxy) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
[Git](https://git-scm.com/) is one of those rare applications that has managed to encapsulate so much of modern computing into one program that it ends up serving as the computational engine for many other applications. While it's best-known for tracking source code changes in software development, it has many other uses that can make your life easier and more organized. In this series leading up to Git's 14th anniversary on April 7, we'll share seven little-known ways to use Git. Today, we'll look at SparkleShare, which uses Git as the backbone for file sharing. ## Git for file sharing One of the nice things about Git is that it's inherently distributed. It's built to share. Even if you're sharing a repository just with other computers on your own network, Git brings transparency to the act of getting files from a shared location. As interfaces go, Git is pretty simple. It varies from user to user, but the common incantation when sitting down to get some work done is just **git pull** or maybe the slightly more complex **git pull && git checkout -b my-branch**. Still, for some people, the idea of *entering a command* into their computer at all is confusing or bothersome. Computers are meant to make life easy, and computers are good at repetitious tasks, and so there are easier ways to share files with Git. ## SparkleShare The [SparkleShare](http://www.sparkleshare.org/) project is a cross-platform, open source, Dropbox-style file sharing application based on Git. It automates all Git commands, triggering the add, commit, push, and pull processes with the simple act of dragging-and-dropping a file into a specially designated SparkleShare directory. Because it is based on Git, you get fast, diff-based pushes and pulls, and you inherit all the benefits of Git version control and backend infrastructure (like Git hooks). It can be entirely self-hosted, or you can use it with Git hosting services like [GitLab](http://gitlab.com), GitHub, Bitbucket, and others. Furthermore, because it's basically just a frontend to Git, you can access your SparkleShare files on devices that may not have a SparkleShare client but do have Git clients. Just as you get all the benefits of Git, you also get all the usual Git restrictions: It's impractical to use SparkleShare to store hundreds of photos and music and videos because Git is designed and optimized for text. Git certainly has the capability to store large files of binary data but it is designed to track history, so once a file is added to it, it's nearly impossible to completely remove it. This somewhat limits the usefulness of SparkleShare for some people, but it makes it ideal for many workflows, including [calendaring](https://opensource.com/article/19/4/calendar-git). ### Installing SparkleShare SparkleShare is cross-platform, with installers for Windows and Mac available from its [website](http://sparkleshare.org). For Linux, there's a [Flatpak](https://opensource.com/business/16/8/flatpak) in your software installer, or you can run these commands in a terminal: ``` $ sudo flatpak remote-add flathub https://flathub.org/repo/flathub.flatpakrepo $ sudo flatpak install flathub org.sparkleshare.SparkleShare ``` ## Creating a Git repository SparkleShare isn't software-as-a-service (SaaS). You run SparkleShare on your computer to communicate with a Git repository—SparkleShare doesn't store your data. If you don't have a Git repository to sync a folder with yet, you must create one before launching SparkleShare. You have three options: hosted Git, self-hosted Git, or self-hosted SparkleShare. ### Git hosting SparkleShare can use any Git repository you can access for storage, so if you have or create an account with GitLab or any other hosting service, it can become the backend for your SparkleShare. For example, the open source [Notabug.org](http://notabug.org) service is a Git hosting service like GitHub and GitLab, but unique enough to prove SparkleShare's flexibility. Creating a new repository differs from host to host depending on the user interface, but all of the major ones follow the same general model. First, locate the button in your hosting service to create a new project or repository and click on it to begin. Then step through the repository creation process, providing a name for your repository, privacy level (repositories often default to being public), and whether or not to initialize the repository with a README file. Whether you need a README or not, enable an initial README file. Starting a repository with a file isn't strictly necessary, but it forces the Git host to instantiate a **master** branch in the repository, which helps ensure that frontend applications like SparkleShare have a branch to commit and push to. It's also useful for you to see a file, even if it's an almost empty README file, to confirm that you have connected. ![Creating a Git repository Creating a Git repository](https://opensource.com/sites/default/files/uploads/git-new-repo.jpg) Once you've created a repository, obtain the URL it uses for SSH clones. You can get this URL the same way anyone gets any URL for a Git project: navigate to the page of the repository and look for the **Clone** button or field. ![Cloning a URL on GitHub Cloning a URL on GitHub](https://opensource.com/sites/default/files/uploads/github-clone-url.jpg) ![Cloning a URL on GitLab Cloning a URL on GitLab](https://opensource.com/sites/default/files/uploads/gitlab-clone-url.jpg) This is the address SparkleShare uses to reach your data, so make note of it. Your Git repository is now configured. ### Self-hosted Git You can use SparkleShare to access a Git repository on any computer you have access to. No special setup is required, aside from a bare Git repository. However, if you want to give access to your Git repository to anyone else, then you should run a Git manager like [Gitolite](http://gitolite.org) or SparkleShare's own Dazzle server to help you manage SSH keys and accounts. At the very least, create a user specific to Git so that users with access to your Git repository don't also automatically gain access to the rest of your server. Log into your server as the Git user (or yourself, if you're very good at managing user and group permissions) and create a repository: ``` $ mkdir ~/sparkly.git $ cd ~/sparkly.git $ git init --bare . ``` Your Git repository is now configured. ### Dazzle SparkleShare's developers provide a Git management system called [Dazzle](https://github.com/hbons/Dazzle) to help you self-host Git repositories. On your server, download the Dazzle application to some location in your path: ``` $ curl https://raw.githubusercontent.com/hbons/Dazzle/master/dazzle.sh \ --output ~/bin/dazzle $ chmod +x ~/bin/dazzle ``` Dazzle sets up a user specific to Git and SparkleShare and also implements access rights based on keys generated by the SparkleShare application. For now, just set up a project: `$ dazzle create sparkly` Your server is now configured as a SparkleShare host. ## Configuring SparkleShare When you launch SparkleShare for the first time, you are prompted to configure what server you want SparkleShare to use for storage. This process may feel like a first-run setup wizard, but it's actually the usual process for setting up a new shared location within SparkleShare. Unlike many shared drive applications, with SparkleShare you can have several locations configured at once. The first shared location you configure isn't any more significant than any shared location you may set up later, and you're not signing up with SparkleShare or any other service. You're just pointing SparkleShare at a Git repository so that it knows what to keep your first SparkleShare folder in sync with. On the first screen, identify yourself by whatever means you want on record in the Git commits that SparkleShare makes on your behalf. You can use anything, even fake information that resolves to nothing. It's purely for the commit messages, which you may never even see if you have no interest in reviewing the Git backend processes. The next screen prompts you to choose your hosting type. If you are using GitLab, GitHub, Planio, or Bitbucket, then select the appropriate one. For anything else, select **Own server**. ![Choosing a Sparkleshare host Choosing a Sparkleshare host](https://opensource.com/sites/default/files/uploads/sparkleshare-host.jpg) At the bottom of this screen, you must enter the SSH clone URL. If you're self-hosting, the address is something like ** ssh://[email protected]** and the remote path is the absolute path to the Git repository you created for this purpose. Based on my self-hosted examples above, the address to my imaginary server is ** ssh://[email protected]:22122** (the **:22122**indicates a nonstandard SSH port) and the remote path is **/home/git/sparkly.git**. If I use my Notabug.org account instead, the address from the example above is ** [email protected]** and the path is **seth/sparkly.git**. SparkleShare will fail the first time it attempts to connect to the host because you have not yet copied the SparkleShare client ID (an SSH key specific to the SparkleShare application) to the Git host. This is expected, so don't cancel the process. Leave the SparkleShare setup window open and obtain the client ID from the SparkleShare icon in your system tray. Then copy the client ID to your clipboard so you can add it to your Git host. ![Getting the client ID from Sparkleshare Getting the client ID from Sparkleshare](https://opensource.com/sites/default/files/uploads/sparkleshare-clientid.jpg) ### Adding your client ID to a hosted Git account Minor UI differences aside, adding an SSH key (which is all the client ID is) is basically the same process on any hosting service. In your Git host's web dashboard, navigate to your user settings and find the **SSH Keys** category. Click the **Add New Key** button (or similar) and paste the contents of your SparkleShare client ID. ![Adding an SSH key Adding an SSH key](https://opensource.com/sites/default/files/uploads/git-ssh-key.jpg) Save the key. If you want someone else, such as collaborators or family members, to be able to access this same repository, they must provide you with their SparkleShare client ID so you can add it to your account. ### Adding your client ID to a self-hosted Git account A SparkleShare client ID is just an SSH key, so copy and paste it into your Git user's **~/.ssh/authorized_keys** file. ### Adding your client ID with Dazzle If you are using Dazzle to manage your SparkleShare projects, add a client ID with this command: `$ dazzle link` When Dazzle prompts you for the ID, paste in the client ID found in the SparkleShare menu. ## Using SparkleShare Once you've added your client ID to your Git host, click the **Retry** button in the SparkleShare window to finish setup. When it's finished cloning your repository, you can close the SparkleShare setup window, and you'll find a new **SparkleShare** folder in your home directory. If you set up a Git repository with a hosting service and chose to include a README or license file, you can see them in your SparkleShare directory. ![Sparkleshare file manager Sparkleshare file manager](https://opensource.com/sites/default/files/uploads/sparkleshare-file-manager.jpg) Otherwise, there are some hidden directories, which you can see by revealing hidden directories in your file manager. ![Showing hidden files in GNOME Showing hidden files in GNOME](https://opensource.com/sites/default/files/uploads/gnome-show-hidden-files.jpg) You use SparkleShare the same way you use any directory on your computer: you put files into it. Anytime a file or directory is placed into a SparkleShare folder, it's copied in the background to your Git repository. ### Excluding certain files Since Git is designed to remember *everything*, you may want to exclude specific file types from ever being recorded. There are a few reasons to manage excluded files. By defining files that are off limits for SparkleShare, you can avoid accidental copying of large files. You can also design a scheme for yourself that enables you to store files that logically belong together (MIDI files with their **.flac** exports, for instance) in one directory, but manually back up the large files yourself while letting SparkleShare back up the text-based files. If you can't see hidden files in your system's file manager, then reveal them. Navigate to your SparkleShare folder, then to the directory representing your repository, locate a file called **.gitignore**, and open it in a text editor. You can enter file extensions or file names, one per line, into **.gitignore**, and any file matching what you list will be (as the file name suggests) ignored. ``` Thumbs.db $RECYCLE.BIN/ .DS_Store ._* .fseventsd .Spotlight-V100 .Trashes .directory .Trash-* *.wav *.ogg *.flac *.mp3 *.m4a *.opus *.jpg *.png *.mp4 *.mov *.mkv *.avi *.pdf *.djvu *.epub *.od{s,t} *.cbz ``` You know the types of files you encounter most often, so concentrate on the ones most likely to sneak their way into your SparkleShare directory. If you want to exercise a little overkill, you can find good collections of **.gitignore** files on Notabug.org and also on the internet at large. With those entries in your **.gitignore** file, you can place large files that you don't want sent to your Git host in your SparkleShare directory, and SparkleShare will ignore them entirely. Of course, that means it's up to you to make sure they get onto a backup or distributed to your SparkleShare collaborators through some other means. ## Automation [Automation](https://opensource.com/downloads/ansible-quickstart) is part of the silent agreement we have with computers: they do the repetitious, boring stuff that we humans either aren't very good at doing or aren't very good at remembering. SparkleShare is a nice, simple way to automate the routine distribution of data. It isn't right for every Git repository, by any means. It doesn't have an interface for advanced Git functions; it doesn't have a pause button or a manual override. And that's OK because its scope is intentionally limited. SparkleShare does what SparkleShare sets out to do, it does it well, and it's one Git repository you won't have to think about. If you have a use for that kind of steady, invisible automation, give SparkleShare a try. ## 2 Comments
11,770
应用推荐:开源磁盘分区工具 GParted
https://itsfoss.com/gparted/
2020-01-10T22:00:31
[ "分区", "GParted" ]
https://linux.cn/article-11770-1.html
![](/data/attachment/album/202001/10/220015lp58jjjt22xfppjj.jpg) > > GParted 是一个可用于 Linux 发行版的非常受欢迎且免费的分区编辑器。在这里,我们简要地介绍一下它提供的功能。 > > > ### GParted:一个自由开源的图形化分区管理器 ![](/data/attachment/album/202001/10/220035waqj77qngqnk733b.png) GParted 无疑是 [Linux 下的最好的分区管理器](https://itsfoss.com/partition-managers-linux/)之一。用户界面非常简单而可以完成任务。 在某些情况下,你最终还是会使用 [GParted](https://gparted.org/) 来修复或格式化你的 USB 驱动器。我有一个[在 Ubuntu 中使用“磁盘”应用程序不能格式化的 USB 磁盘](https://itsfoss.com/format-usb-drive-sd-card-ubuntu/),而这是 GParted 用来救援的地方。 所以,它是一个非常有用的工具,有很多出色的功能。让我为你们重点介绍一下。 > > 警告! > > > 进行磁盘分区是一件危险的工作。除非绝对必要,否则不要做。否则,你可能最终擦除了整个磁盘。 > > > ### GParted 的功能 从简单地格式化任务到重要的分区任务,你可以使用 GParted 做很多事。我将使用一些屏幕截图突出关键功能,以帮助你在安装它前进一步了解它。 #### 创建分区表 你可以为新磁盘创建一个新的分区表,也可以擦除你现存的磁盘内容来修改分区表。 ![](/data/attachment/album/202001/10/220043vf2itgigff7fgi1f.png) 你能够选择 msdos、gpt、atari,以及更多类型的分区表。 #### 创建、移动、标记、删除和修改分区表 你可以使用 GParted 中一系列选项来轻松地创建、标记、删除或修改分区表。 ![](/data/attachment/album/202001/10/220046j3fi2h5ql225ix5p.png) 当然,你必须要谨慎你要做的事情。 好的是,GParted 可以确保你不能直接应用任何更改 —— 在你点击应用更改之前,它将排队你选择的操作/任务,并在你执行前最后再要求确认一次。 顶部的对号标记符号 `✓` 可以让你确认更改,然后你的更改才会生效。 这是分区可用选项的另一个屏幕截图: ![](/data/attachment/album/202001/10/220049fvvvjx4s1yftj4py.png) #### 尝试数据救援 除了编辑分区以外,你也可以试着使用“尝试数据救援”功能以[在 Linux 中恢复丢失的数据](https://itsfoss.com/recover-deleted-files-linux/),如下面的屏幕截图所示。 ![](/data/attachment/album/202001/10/220051bnntqckdcc9nn2ke.png) 值得注意的是,默认情况下你没有安装此功能 —— 你只是能看到这个选项。因此,要使这个数据恢复功能可以正常工作,你必须使用下面的命令来单独地安装 gpart (在基于 Ubuntu/Debian 的发行版上): ``` sudo apt install gpart ``` 除了所有这些关键功能以外,它支持各种存储设备和文件系统。你可以从其官方网站的[功能列表](https://gparted.org/features.php)中了解到更多信息。 ### 在 Ubuntu 和其它 Linux 发行版上安装 GParted 你可能已经预安装了 GParted 。所以,务必核实一下。如果你尚未安装它,则可以进入软件中心安装它。 如果你想使用终端,简单地键入下面的命令: ``` sudo apt install gparted ``` 如上所述,如果你想要使用数据恢复选项,除了安装 gparted 软件包外,还应该安装 gpart 软件包。 如果你使用的是其它 Linux 发行版,你可以在各自的软件管理器中找到它,或者直接查看[官方下载操作说明](https://gparted.org/download.php)。 * [下载 GParted](https://gparted.org/download.php) ### 总结 当涉及处理磁盘管理和分区时,GParted 是一个非常有用且重要的工具。但是,因为显而易见的原因,当你使用它时,你必须要小心。 你尝试过 GParted 吗?你在 Linux 上使用的其它哪个分区工具?请在下面的评论中分享你的经验。 --- via: <https://itsfoss.com/gparted/> 作者:[Ankush Das](https://itsfoss.com/author/ankush/) 选题:[lujun9972](https://github.com/lujun9972) 译者:[robsean](https://github.com/robsean) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) [GParted](https://gparted.org/?ref=itsfoss.com) is undoubtedly one of the [best partition managers for Linux](https://itsfoss.com/partition-managers-linux/) out there. The user interface is very simple and gets the job done. In some cases, you end up using GParted to fix or [format your USB drive](https://itsfoss.com/format-usb-drive-sd-card-ubuntu/) as well. I had a USB disk which I couldn’t format in Ubuntu~~ ~~using the “Disks” app – this is where GParted came to the rescue. So, it is a quite useful tool with plenty of good features. Let me highlight them for you. ## Installing GParted on Ubuntu and other Linux distributions ![a screenshot of gparted](https://itsfoss.com/content/images/2023/11/GParted_1.png) Before installing GParted, let's take a look at some of its **key features**: **Set Partition Flags****Resize/Move Partitions****Create/Remove Partitions****Ability to Set UUIDs** So, moving on to the installation. You might have GParted pre-installed, therefore, make sure to verify that before proceeding to install it. If you do not have it installed, you can head into the **software center** on your Linux distro and search for 'GParted' to get it installed. In case you want to **use the terminal**, simply type in the following command (Ubuntu/Debian): `sudo apt install gparted` If you’re using any other Linux distribution, you can either find GParted in their respective software managers, or you could head over to the [official download page](https://gparted.org/download.php?ref=itsfoss.com) for further install instructions. ## Using the features of GParted You can do many things with GParted, ranging from a simple format task to important partitioning tasks. I’ll highlight the key features with some screenshots to help you know more about it before installing it. ### Create partition tables ![a screenshot of gparted create partion table feature](https://itsfoss.com/content/images/2023/11/GParted_2.png) You can create a new partition table for your disks, or erase the content of your existing disk to modify the partition table. GParted lets you choose from different types of partition tables like *msdos*, *bsd*, *gpt*, *atari*, and more. ### Create, Move, Label, Delete & Modify Partitions You can easily create, label, delete or modify the partitions with a bunch of options available within GParted. Below, you can see how **creating a new partition** looks like. Of course, you will have to be careful about what you want to do. ![a screenshot of gparted create new partition feature](https://itsfoss.com/content/images/2023/11/GParted_3a.png) After creating a new partition, you can also **Resize/Move** it according to your preference. ![a screenshot of gparted resize move partition feature](https://itsfoss.com/content/images/2023/11/GParted_3b.png) The good thing is that **GParted makes sure that you do not directly apply any changes** – it queues up your selected operations/tasks and asks for another final confirmation before you hit it. ![a screenshot of gparted apply operations to device confirmation window](https://itsfoss.com/content/images/2023/11/GParted_4.png) The tick mark symbol ✓ on the top allows you to confirm the changes and then only your changes take into effect. Here’s another screenshot for the **format options** you have available for the partitions: ![a screenshot of gparted format options for partitions](https://itsfoss.com/content/images/2023/11/GParted_5.png) ### Attempt Data Rescue Apart from editing partitions, you can also try to [recover your lost data in Linux](https://itsfoss.com/recover-deleted-files-linux/) using the “**Attempt Data Rescue**” feature, as shown in the screenshot below. ![a screenshot of gparted attempt data rescue feature](https://itsfoss.com/content/images/2023/11/GParted_6.png) It is worth noting that **you do not have this feature installed by default** – you only see the option visible. So, for the data recovery feature to work, you have to install '*gpart*' separately using the following command (on Ubuntu/Debian-based distributions): `sudo apt install gpart` In addition to all the key features listed above, **GParted supports a wide range of storage devices and file systems**. You can learn more about it from the [list of features](https://gparted.org/features.php?ref=itsfoss.com) on their official website. **Wrapping Up** GParted is **a very useful and important tool** when it comes to dealing with disk management and partitions. However, you will have to be careful while using it for obvious reasons. 💬 Have you tried GParted? Prefer other partitioning tools for Linux? Don't hesitate to share your experiences in the comments below!