Merge remote-tracking branch 'LCTT/master'

This commit is contained in:
wxy 2018-02-24 22:04:07 +08:00
commit 43776d03fb
24 changed files with 2687 additions and 1412 deletions

View File

@ -0,0 +1,89 @@
如何使用 lftp 来加速 Linux/UNIX 上的 ftp/https 下载速度
======
`lftp` 是一个文件传输程序。它可以用于复杂的 FTP、 HTTP/HTTPS 和其他连接。如果指定了站点 URL那么 `lftp` 将连接到该站点,否则会使用 `open` 命令建立连接。它是所有 Linux/Unix 命令行用户的必备工具。我目前写了一些关于 [Linux 下超快命令行下载加速器][1],比如 Axel 和 prozilla。`lftp` 是另一个能做相同的事,但有更多功能的工具。`lftp` 可以处理七种文件访问方式:
1. ftp
2. ftps
3. http
4. https
5. hftp
6. fish
7. sftp
8. file
### 那么 lftp 的独特之处是什么?
* `lftp` 中的每个操作都是可靠的,即任何非致命错误都被忽略,并且重复进行操作。所以如果下载中断,它会自动重新启动。即使 FTP 服务器不支持 `REST` 命令lftp 也会尝试从开头检索文件,直到文件传输完成。
* `lftp` 具有类似 shell 的命令语法,允许你在后台并行启动多个命令。
* `lftp` 有一个内置的镜像功能,可以下载或更新整个目录树。还有一个反向镜像功能(`mirror -R`),它可以上传或更新服务器上的目录树。镜像也可以在两个远程服务器之间同步目录,如果可用的话会使用 FXP。
### 如何使用 lftp 作为下载加速器
`lftp``pget` 命令。它能让你并行下载。语法是:
```
lftp -e 'pget -n NUM -c url; exit'
```
例如,使用 `pget` 分 5个部分下载 <http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.22.2.tar.bz2>
```
$ cd /tmp
$ lftp -e 'pget -n 5 -c http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.22.2.tar.bz2'
```
示例输出:
```
45108964 bytes transferred in 57 seconds (775.3K/s)
lftp :~>quit
```
这里:
1. `pget` - 并行下载文件
2. `-n 5` - 将最大连接数设置为 5
3. `-c` - 如果当前目录存在 `lfile.lftp-pget-status`,则继续中断的传输
### 如何在 Linux/Unix 中使用 lftp 来加速 ftp/https下载
再尝试添加 `exit` 命令:
```
$ lftp -e 'pget -n 10 -c https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.15.tar.xz; exit'
```
[Linux-lftp-command-demo](https://www.cyberciti.biz/tips/wp-content/uploads/2007/08/Linux-lftp-command-demo.mp4)
### 关于并行下载的说明
请注意,通过使用下载加速器,你将增加远程服务器负载。另请注意,`lftp` 可能无法在不支持多点下载的站点上工作,或者防火墙阻止了此类请求。
其它的命令提供了更多功能。有关更多信息,请参考 [lftp][2] 的 man 页面:
```
man lftp
```
### 关于作者
作者是 nixCraft 的创建者,经验丰富的系统管理员,也是 Linux 操作系统/Unix shell 脚本的培训师。他曾与全球客户以及IT、教育、国防和太空研究以及非营利部门等多个行业合作。在 [Twitter][9]、[Facebook][10]、[Google +][11] 上关注他。通过 [RSS/XML 订阅][5]获取最新的系统管理、Linux/Unix 以及开源主题教程。
--------------------------------------------------------------------------------
via: https://www.cyberciti.biz/tips/linux-unix-download-accelerator.html
作者:[Vivek Gite][a]
译者:[geekpi](https://github.com/geekpi)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.cyberciti.biz
[1]:https://www.cyberciti.biz/tips/download-accelerator-for-linux-command-line-tools.html
[2]:https://lftp.yar.ru/
[3]:https://twitter.com/nixcraft
[4]:https://facebook.com/nixcraft
[5]:https://plus.google.com/+CybercitiBiz
[6]:https://www.cyberciti.biz/atom/atom.xml

View File

@ -1,12 +1,13 @@
# Liunx 平台 6 个最好的替代 Microsoft Office 的开源办公软件
6 个 Liunx 平台下最好的替代 Microsoft Office 的开源办公软件
===========
**概要:还在 Linux 中寻找 Microsoft Office ? 这里有一些最好的在 Linux 平台替代 Microsoft Office 的开源软件。**
> 概要:还在 Linux 中寻找 Microsoft Office 吗? 这里有一些最好的在 Linux 平台下替代 Microsoft Office 的开源软件。
办公套件是任何操作系统的必备品。很难想象没有Office 软件的桌面操作系统。虽然 Windows 有 MS Office 套件Mac OS X 也有它自己的 iWork但其他很多办公套件都是专门针对这些操作系统的Linux 也有自己的办公套件。
办公套件是任何操作系统的必备品。很难想象没有 Office 软件的桌面操作系统。虽然 Windows 有 MS Office 套件Mac OS X 也有它自己的 iWork但其他很多办公套件都是专门针对这些操作系统的Linux 也有自己的办公套件。
在本文中,我会列举一些在 Linux 平台替代 Microsoft Office 的办公软件。
## Linux 最好的 MS Office 开源替代软件
### Linux 最好的 MS Office 开源替代软件
![Best Microsoft office alternatives for Linux][1]
@ -16,62 +17,61 @@
* 电子表格
* 演示功能
我知道 Microsoft Office 提供了比上述三种工具更多的工具,但事实上, 您主要使用这三个工具。 开源办公套件并不限于只有这三种产品。 其中有一些套件提供了一些额外的工具,但我们的重点将放在上述工具上。
我知道 Microsoft Office 提供了比上述三种工具更多的工具,但事实上,您主要使用这三个工具。开源办公套件并不限于只有这三种产品。其中有一些套件提供了一些额外的工具,但我们的重点将放在上述工具上。
让我们看看在 Linux 上有什么办公套件:
### 6. Apache OpenOffice
#### 6. Apache OpenOffice
![OpenOffice Logo][2]
[Apache OpenOffice][3] 或简单的称为 OpenOffice 有一段名称/所有者变更的历史。 它于1999年由 Sun Microsystems 公司开发,后来改名为 OpenOffice ,将它作为一个与 MS Office 对抗的免费的开源替代软件。 当Oracle 在 2010 年收购 Sun 公司后,一年之后便停止开发 OpenOffice。 最后是 Apache 支持它现在被称为Apache OpenOffice。
[Apache OpenOffice][3] 或简单的称为 OpenOffice 有一段名称/所有者变更的历史。 它于 1999 年由 Sun Microsystems 公司开发,后来改名为 OpenOffice,将它作为一个与 MS Office 对抗的自由开源的替代软件。 当 Oracle 在 2010 年收购 Sun 公司后,一年之后便停止开发 OpenOffice。 最后是 Apache 支持它,现在被称为 Apache OpenOffice。
Apache OpenOffice 可用于多种平台,包括 LinuxWindowsMac OS XUnixBSD。 除了 OpenDocument 格式外,它还支持 MS Office 文件。 办公套件包含以下应用程序WriterCalcImpressBaseDrawMath。
Apache OpenOffice 可用于多种平台,包括 Linux、Windows、Mac OS X、Unix、BSD。 除了 OpenDocument 格式外,它还支持 MS Office 文件。 办公套件包含以下应用程序Writer、Calc、Impress、Base、Draw、Math。
安装 OpenOffice 是一件痛苦的事,因为它没有提供一个友好的安装程序。 另外,有传言说 OpenOffice 开发可能已经停滞。 这两个是我不推荐的主要原因。 为了历史目的,我在这里列出它。
安装 OpenOffice 是一件痛苦的事,因为它没有提供一个友好的安装程序。另外,有传言说 OpenOffice 开发可能已经停滞。 这是我不推荐的两个主要原因。 出于历史目的,我在这里列出它。
### 5. Feng Office
#### 5. Feng Office
![Feng Office logo][6]
[Feng Office][7] 以前被称为 OpenGoo。 这不是一个常规的办公套件。 它完全专注于在线办公,如 Google 文档。 换句话说,这是一个开源[协作平台][8]。
[Feng Office][7] 以前被称为 OpenGoo。 这不是一个常规的办公套件。 它完全专注于在线办公,如 Google 文档一样。 换句话说,这是一个开源[协作平台][8]。
Feng Office 不支持桌面使用因此如果您想在单个Linux 桌面上使用它,这个可能无法实现。 另一方面,如果你有一个小企业一个机构或其他组织,你可以尝试将其部署在本地服务器上。
Feng Office 不支持桌面使用,因此如果您想在单个 Linux 桌面上使用它,这个可能无法实现。 另一方面,如果你有一个小企业一个机构或其他组织,你可以尝试将其部署在本地服务器上。
### 4. Siag Office
#### 4. Siag Office
![SIAG Office logo][9]
[Siag][10] 是一个非常轻量级的办公套件,适用于类 Unix 系统,可以在 16 MB 系统上运行。 由于它非常轻便,因此缺少标准办公套件中的许多功能。 但小即是,不是吗? 它具有办公套件的所有必要功能,可以在[轻量级 Linux 发行版][11]上“正常工作”。它是 [Damn Small Linux][12] 默认安装软件。(译者注: 根据官网,现已不是默认安装软件)
[Siag][10] 是一个非常轻量级的办公套件,适用于类 Unix 系统,可以在 16MB 系统上运行。 由于它非常轻便,因此缺少标准办公套件中的许多功能。 但小即是丽,不是吗? 它具有办公套件的所有必要功能,可以在[轻量级 Linux 发行版][11]上“正常工作”。它是 [Damn Small Linux][12] 默认安装软件。LCTT 译注:根据官网,现已不是默认安装软件)
### 3. Calligra Suite
#### 3. Calligra Suite
![Calligra free and Open Source office logo][13]
[Calligra][14],以前被称为 KOffice是 KDE 中默认的 Office 套件。 它支持 Mac OS XWindowsLinuxFreeBSD系统。 它也曾经推出 Android 版本。 但不幸的是,后续没有继续支持 Android。 它拥有办公套件所需的必要应用程序以及一些额外的应用程序,如用于绘制流程图的 Flow 和用于项目管理的 Plane。
[Calligra][14],以前被称为 KOffice是 KDE 中默认的 Office 套件。 它支持 Mac OS X、Windows、Linux、FreeBSD 系统。 它也曾经推出 Android 版本。 但不幸的是,后续没有继续支持 Android。 它拥有办公套件所需的必要应用程序以及一些额外的应用程序,如用于绘制流程图的 Flow 和用于项目管理的 Plane。
Calligra 最近的发展产生了相当大的影响,很有可能成为 [LibreOffice 的替代品][16]。
### 2. ONLYOFFICE
#### 2. ONLYOFFICE
![ONLYOFFICE is Linux alternative to Microsoft Office][17]
[ONLYOFFICE][18] 是办公套件市场上的新玩家,它更专注于协作部分。 企业(甚至个人)可以将其部署到自己的服务器上,以获得类似 Google Docs 之类的协作办公套件。
别担心。 您不必必须将其安装在服务器上。 有一个免费的开源[桌面版本][19] ONLYOFFICE。 您甚至可以获取 .deb 和 .rpm 二进制文件,以便将其安装在 Linux 桌面系统上。
别担心,您不是必须将其安装在服务器上。有一个免费的开源[桌面版本][19] ONLYOFFICE。 您甚至可以获取 .deb 和 .rpm 二进制文件,以便将其安装在 Linux 桌面系统上。
### 1. LibreOffice
#### 1. LibreOffice
![LibreOffice logo][20]
当 Oracle 决定停止 OpenOffice 的开发时,是[文档基金会][21]将其复制分发,这就是我们所熟知的 [Libre-Office][22] 。从那时起,许多 Linux 发行版都将 OpenOffice 替换为 LibreOffice 作为它们的默认办公应用程序。
当 Oracle 决定停止 OpenOffice 的开发时,是[文档基金会][21]将其复制分发,这就是我们所熟知的 [Libre-Office][22]。从那时起,许多 Linux 发行版都将 OpenOffice 替换为 LibreOffice 作为它们的默认办公应用程序。
它适用于 LinuxWindows 和 Mac OS X这使得在跨平台环境中易于使用。 和 Apache OpenOffice 一样,这也包括了除了 OpenDocument 格式以外的对 MS Office 文件的支持。 它还包含与 Apache OpenOffice 相同的应用程序。
您还可以使用 LibreOffice 作为 [Collabora Online][23] 的协作平台。 基本上LibreOffice 是一个完整的软件包,无疑是 LinuxWindows 和 MacOS 的**最佳 Microsoft Office 替代品**。
您还可以使用 LibreOffice 作为 [Collabora Online][23] 的协作平台。 基本上LibreOffice 是一个完整的软件包,无疑是 LinuxWindows 和 MacOS 的**最佳 Microsoft Office 替代品**。
## 你认为呢?
### 你认为呢?
我希望 Microsoft Office 的这些开源替代软件可以节省您的资金。 您会使用哪种开源生产力办公套件?
@ -81,7 +81,7 @@ via: https://itsfoss.com/best-free-open-source-alternatives-microsoft-office/
作者:[Abhishek Prakash][a]
译者:[amwps290](https://github.com/amwps290)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

View File

@ -1,12 +1,15 @@
如何使用cloud-init来预配置LXD容器
如何使用 cloud-init 来预配置 LXD 容器
======
当你正在创建LXD容器的时候你希望它们能被预先配置好。例如在容器一启动就自动执行 **apt update**来安装一些软件包,或者运行一些命令。
这篇文章将讲述如何用[**cloud-init**][1]来对[LXD容器进行进行早期初始化][2]。
当你正在创建 LXD 容器的时候,你希望它们能被预先配置好。例如在容器一启动就自动执行 `apt update`来安装一些软件包,或者运行一些命令。
这篇文章将讲述如何用 [cloud-init][1] 来对 [LXD 容器进行进行早期初始化][2]。
接下来我们将创建一个包含cloud-init指令的LXD profile然后启动一个新的容器来使用这个profile。
### 如何创建一个新的LXD profile
### 如何创建一个新的 LXD profile
查看已经存在的profile
查看已经存在的 profile
```shell
$ lxc profile list
@ -17,7 +20,7 @@ $ lxc profile list
+---------|---------+
```
我们把名叫default的profile复制一份然后在其内添加新的指令
我们把名叫 `default` profile 复制一份,然后在其内添加新的指令:
```shell
$ lxc profile copy default devprofile
@ -32,7 +35,7 @@ $ lxc profile list
+------------|---------+
```
我们就得到了一个新的profile **devprofile**。下面是它的详情:
我们就得到了一个新的 profile `devprofile`。下面是它的详情:
```yaml
$ lxc profile show devprofile
@ -52,11 +55,12 @@ name: devprofile
used_by: []
```
注意这几个部分: **config:** **description:** **devices:** **name:****used_by:**,当你修改这些内容的时候注意不要搞错缩进。(译因为这些内容是YAML格式的缩进是语法的一部分
注意这几个部分: `config:``description:``devices:``name:``used_by:`,当你修改这些内容的时候注意不要搞错缩进。(LCTT 译注:因为这些内容是 YAML 格式的,缩进是语法的一部分)
### 如何把cloud-init添加到LXD profile里
### 如何把 cloud-init 添加到 LXD profile 里
[cloud-init][1] 可以添加到 LXD profile 的 `config` 里。当这些指令将被传递给容器后,会在容器第一次启动的时候执行。
[cloud-init][1]可以添加到LXD profile的 **config** 里。当这些指令将被传递给容器后,会在容器第一次启动的时候执行。
下面是用在示例中的指令:
```yaml
@ -69,11 +73,9 @@ used_by: []
- [touch, /tmp/simos_was_here]
```
**package_upgrade: true** 是指当容器第一次被启动时,我们想要**cloud-init** 运行 **sudo apt upgrade**
**packages:** 列出了我们想要自动安装的软件。然后我们设置了**locale** and **timezone**。在Ubuntu容器的镜像里root用户默认的 locale 是**C.UTF-8**,而**ubuntu** 用户则是 **en_US.UTF-8**。此外,我们把时区设置为**Etc/UTC**。
最后,我们展示了[如何使用**runcmd**来运行一个Unix命令][3]。
`package_upgrade: true` 是指当容器第一次被启动时,我们想要 `cloud-init` 运行 `sudo apt upgrade`。`packages:` 列出了我们想要自动安装的软件。然后我们设置了 `locale``timezone`。在 Ubuntu 容器的镜像里root 用户默认的 `locale``C.UTF-8`,而 `ubuntu` 用户则是 `en_US.UTF-8`。此外,我们把时区设置为 `Etc/UTC`。最后,我们展示了[如何使用 runcmd 来运行一个 Unix 命令][3]。
我们需要关注如何将**cloud-init**指令插入LXD profile。
我们需要关注如何将 `cloud-init` 指令插入 LXD profile。
我首选的方法是:
@ -110,15 +112,15 @@ name: devprofile
used_by: []
```
### 如何使用LXD profile启动一个容器
### 如何使用 LXD profile 启动一个容器
使用profile **devprofile**来启动一个新容器:
使用 profile `devprofile` 来启动一个新容器:
```
$ lxc launch --profile devprofile ubuntu:x mydev
```
然后访问该容器来查看我们的指令是否生效:
然后访问该容器来查看我们的指令是否生效:
```shell
$ lxc exec mydev bash
@ -139,7 +141,7 @@ root@mydev:~# ps ax
root@mydev:~#
```
如果我们连接得够快,通过**ps ax**将能够看到系统正在更新软件。我们可以从/var/log/cloud-init-output.log看到完整的日志
如果我们连接得够快,通过 `ps ax` 将能够看到系统正在更新软件。我们可以从 `/var/log/cloud-init-output.log` 看到完整的日志:
```
Generating locales (this might take a while)...
@ -147,7 +149,7 @@ Generating locales (this might take a while)...
Generation complete.
```
以上可以看出locale已经被更改了。root 用户还是保持默认的**C.UTF-8**只有非root用户**ubuntu**使用了新的locale
以上可以看出 `locale` 已经被更改了。root 用户还是保持默认的 `C.UTF-8`,只有非 root 用户 `ubuntu` 使用了新的`locale` 设置
```
Hit:1 http://archive.ubuntu.com/ubuntu xenial InRelease
@ -155,7 +157,7 @@ Get:2 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Get:3 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
```
以上是安装软件包之前执行的**apt update**
以上是安装软件包之前执行的 `apt update`
```
The following packages will be upgraded:
@ -163,16 +165,18 @@ The following packages will be upgraded:
4 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 211 kB of archives.
```
以上是在执行**package_upgrade: true**和安装软件包。
以上是在执行 `package_upgrade: true` 和安装软件包。
```
The following NEW packages will be installed:
binutils build-essential cpp cpp-5 dpkg-dev fakeroot g++ g++-5 gcc gcc-5
libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl
```
以上是我们安装**build-essential**软件包的指令。
**runcmd** 执行的结果如何?
以上是我们安装 `build-essential` 软件包的指令。
`runcmd` 执行的结果如何?
```
root@mydev:~# ls -l /tmp/
@ -185,7 +189,7 @@ root@mydev:~#
### 结论
当我们启动LXD容器的时候我们常常需要默认启用一些配置并且希望能够避免重复工作。通常解决这个问题的方法是创建LXD profile然后把需要的配置添加进去。最后当我们启动新的容器时只需要应用该LXD profile即可。
当我们启动 LXD 容器的时候,我们常常需要默认启用一些配置,并且希望能够避免重复工作。通常解决这个问题的方法是创建 LXD profile然后把需要的配置添加进去。最后当我们启动新的容器时只需要应用该 LXD profile 即可。
--------------------------------------------------------------------------------
@ -193,7 +197,7 @@ via: https://blog.simos.info/how-to-preconfigure-lxd-containers-with-cloud-init/
作者:[Simos Xenitellis][a]
译者:[kaneg](https://github.com/kaneg)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

View File

@ -0,0 +1,310 @@
通过 ncurses 在终端创建一个冒险游戏
======
怎样使用 curses 函数读取键盘并操作屏幕。
我[之前的文章][1]介绍了 ncurses 库,并提供了一个简单的程序展示了一些将文本放到屏幕上的 curses 函数。在接下来的文章中,我将介绍如何使用其它的 curses 函数。
### 探险
当我逐渐长大,家里有了一台苹果 II 电脑。我和我兄弟正是在这台电脑上自学了如何用 AppleSoft BASIC 写程序。我在写了一些数学智力游戏之后,继续创造游戏。作为 80 年代的人,我已经是龙与地下城桌游的粉丝,在游戏中角色扮演一个追求打败怪物并在陌生土地上抢掠的战士或者男巫,所以我创建一个基本的冒险游戏也在情理之中。
AppleSoft BASIC 支持一种简洁的特性在标准分辨率图形模式GR 模式)下,你可以检测屏幕上特定点的颜色。这为创建一个冒险游戏提供了捷径。比起创建并更新周期性传送到屏幕的内存地图,我现在可以依赖 GR 模式为我维护地图我的程序还可以在玩家的角色LCTT 译注:此处 character 双关一个代表玩家的角色,同时也是一个字符)在屏幕四处移动的时候查询屏幕。通过这种方式,我让电脑完成了大部分艰难的工作。因此,我的自顶向下的冒险游戏使用了块状的 GR 模式图形来展示我的游戏地图。
我的冒险游戏使用了一张简单的地图,上面有一大片绿地伴着山脉从中间蔓延向下和一个在左上方的大湖。我要粗略地为桌游战役绘制这个地图,其中包含一个允许玩家穿过到远处的狭窄通道。
![](http://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1000009/quest-map.jpg)
*图 1. 一个有湖和山的简单桌游地图*
你可以用 curses 绘制这个地图,并用字符代表草地、山脉和水。接下来,我描述怎样使用 curses 那样做,以及如何在 Linux 终端创建和进行类似的一个冒险游戏。
### 构建程序
在我的上一篇文章,我提到了大多数 curses 程序以相同的一组指令获取终端类型和设置 curses 环境:
```
initscr();
cbreak();
noecho();
```
在这个程序,我添加了另外的语句:
```
keypad(stdscr, TRUE);
```
这里的 `TRUE` 标志允许 curses 从用户终端读取小键盘和功能键。如果你想要在你的程序中使用上下左右方向键,你需要使用这里的 `keypad(stdscr, TRUE)`
这样做了之后你现在可以开始在终端屏幕上绘图了。curses 函数包括了一系列在屏幕上绘制文本的方法。在我之前的文章中,我展示了 `addch()``addstr()` 函数以及在添加文本之前先移动到指定屏幕位置的对应函数 `mvaddch()``mvaddstr()`。为了在终端上创建这个冒险游戏的地图,你可以使用另外一组函数:`vline()` 和 `hline()`,以及它们对应的函数 `mvvline()``mvhline()`。这些 mv 函数接受屏幕坐标、一个要绘制的字符和要重复此字符的次数的参数。例如,`mvhline(1, 2, '-', 20)` 将会绘制一条开始于第一行第二列并由 20 个横线组成的线段。
为了以编程方式绘制地图到终端屏幕上,让我们先定义这个 `draw_map()` 函数:
```
#define GRASS ' '
#define EMPTY '.'
#define WATER '~'
#define MOUNTAIN '^'
#define PLAYER '*'
void draw_map(void)
{
int y, x;
/* 绘制探索地图 */
/* 背景 */
for (y = 0; y < LINES; y++) {
mvhline(y, 0, GRASS, COLS);
}
/* 山和山道 */
for (x = COLS / 2; x < COLS * 3 / 4; x++) {
mvvline(0, x, MOUNTAIN, LINES);
}
mvhline(LINES / 4, 0, GRASS, COLS);
/* 湖 */
for (y = 1; y < LINES / 2; y++) {
mvhline(y, 1, WATER, COLS / 3);
}
}
```
在绘制这副地图时,记住填充大块字符到屏幕所使用的 `mvvline()``mvhline()` 函数。我绘制从 0 列开始的字符水平线(`mvhline`)以创建草地区域,直到占满整个屏幕的高度和宽度。我绘制从 0 行开始的多条垂直线(`mvvline`)在此上添加了山脉,绘制单行水平线添加了一条山道(`mvhline`)。并且,我通过绘制一系列短水平线(`mvhline`)创建了湖。这种绘制重叠方块的方式看起来似乎并没有效率,但是记住在我们调用 `refresh()` 函数之前 curses 并不会真正更新屏幕。
绘制完地图,创建游戏就还剩下进入循环让程序等待用户按下上下左右方向键中的一个然后让玩家图标正确移动了。如果玩家想要移动的地方是空的,就应该允许玩家到那里。
你可以把 curses 当做捷径使用。比起在程序中实例化一个版本的地图并复制到屏幕这么复杂,你可以让屏幕为你跟踪所有东西。`inch()` 函数和相关联的 `mvinch()` 函数允许你探测屏幕的内容。这让你可以查询 curses 以了解玩家想要移动到的位置是否被水填满或者被山阻挡。这样做你需要一个之后会用到的一个帮助函数:
```
int is_move_okay(int y, int x)
{
int testch;
/* 如果要进入的位置可以进入,返回 true */
testch = mvinch(y, x);
return ((testch == GRASS) || (testch == EMPTY));
}
```
如你所见,这个函数探测行 `x`、列 `y` 并在空间未被占据的时候返回 `true`,否则返回 `false`
这样我们写移动循环就很容易了:从键盘获取一个键值然后根据是上下左右键移动用户字符。这里是一个这种循环的简单版本:
```
do {
ch = getch();
/* 测试输入的值并获取方向 */
switch (ch) {
case KEY_UP:
if ((y > 0) && is_move_okay(y - 1, x)) {
y = y - 1;
}
break;
case KEY_DOWN:
if ((y < LINES - 1) && is_move_okay(y + 1, x)) {
y = y + 1;
}
break;
case KEY_LEFT:
if ((x > 0) && is_move_okay(y, x - 1)) {
x = x - 1;
}
break;
case KEY_RIGHT
if ((x < COLS - 1) && is_move_okay(y, x + 1)) {
x = x + 1;
}
break;
}
}
while (1);
```
为了在游戏中使用这个循环,你需要在循环里添加一些代码来启用其它的键(例如传统的移动键 WASD以提供让用户退出游戏和在屏幕上四处移动的方法。这里是完整的程序
```
/* quest.c */
#include
#include
#define GRASS ' '
#define EMPTY '.'
#define WATER '~'
#define MOUNTAIN '^'
#define PLAYER '*'
int is_move_okay(int y, int x);
void draw_map(void);
int main(void)
{
int y, x;
int ch;
/* 初始化curses */
initscr();
keypad(stdscr, TRUE);
cbreak();
noecho();
clear();
/* 初始化探索地图 */
draw_map();
/* 在左下角初始化玩家 */
y = LINES - 1;
x = 0;
do {
/* 默认获得一个闪烁的光标--表示玩家字符 */
mvaddch(y, x, PLAYER);
move(y, x);
refresh();
ch = getch();
/* 测试输入的键并获取方向 */
switch (ch) {
case KEY_UP:
case 'w':
case 'W':
if ((y > 0) && is_move_okay(y - 1, x)) {
mvaddch(y, x, EMPTY);
y = y - 1;
}
break;
case KEY_DOWN:
case 's':
case 'S':
if ((y < LINES - 1) && is_move_okay(y + 1, x)) {
mvaddch(y, x, EMPTY);
y = y + 1;
}
break;
case KEY_LEFT:
case 'a':
case 'A':
if ((x > 0) && is_move_okay(y, x - 1)) {
mvaddch(y, x, EMPTY);
x = x - 1;
}
break;
case KEY_RIGHT:
case 'd':
case 'D':
if ((x < COLS - 1) && is_move_okay(y, x + 1)) {
mvaddch(y, x, EMPTY);
x = x + 1;
}
break;
}
}
while ((ch != 'q') && (ch != 'Q'));
endwin();
exit(0);
}
int is_move_okay(int y, int x)
{
int testch;
/* 当空间可以进入时返回true */
testch = mvinch(y, x);
return ((testch == GRASS) || (testch == EMPTY));
}
void draw_map(void)
{
int y, x;
/* 绘制探索地图 */
/* 背景 */
for (y = 0; y < LINES; y++) {
mvhline(y, 0, GRASS, COLS);
}
/* 山脉和山道 */
for (x = COLS / 2; x < COLS * 3 / 4; x++) {
mvvline(0, x, MOUNTAIN, LINES);
}
mvhline(LINES / 4, 0, GRASS, COLS);
/* 湖 */
for (y = 1; y < LINES / 2; y++) {
mvhline(y, 1, WATER, COLS / 3);
}
}
```
在完整的程序清单中,你可以看见使用 curses 函数创建游戏的完整布置:
1. 初始化 curses 环境。
2. 绘制地图。
3. 初始化玩家坐标(左下角)
4. 循环:
* 绘制玩家的角色。
* 从键盘获取键值。
* 对应地上下左右调整玩家坐标。
* 重复。
5. 完成时关闭curses环境并退出。
### 开始玩
当你运行游戏时,玩家的字符在左下角初始化。当玩家在游戏区域四处移动的时候,程序创建了“一串”点。这样可以展示玩家经过了的点,让玩家避免经过不必要的路径。
![](http://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1000009/quest-start.png)
*图 2. 初始化在左下角的玩家*
![](http://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1000009/quest-1.png)
*图 3. 玩家可以在游戏区域四处移动,例如湖周围和山的通道*
为了创建上面这样的完整冒险游戏,你可能需要在他/她的角色在游戏区域四处移动的时候随机创建不同的怪物。你也可以创建玩家可以发现在打败敌人后可以掠夺的特殊道具,这些道具应能提高玩家的能力。
但是作为起点,这是一个展示如何使用 curses 函数读取键盘和操纵屏幕的好程序。
### 下一步
这是一个如何使用 curses 函数更新和读取屏幕和键盘的简单例子。按照你的程序需要做什么curses 可以做得更多。在下一篇文章中,我计划展示如何更新这个简单程序以使用颜色。同时,如果你想要学习更多 curses我鼓励你去读位于 Linux 文档计划的 Pradeep Padala 写的[如何使用 NCURSES 编程][2]。
--------------------------------------------------------------------------------
via: http://www.linuxjournal.com/content/creating-adventure-game-terminal-ncurses
作者:[Jim Hall][a]
译者:[Leemeans](https://github.com/leemeans)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.linuxjournal.com/users/jim-hall
[1]:https://linux.cn/article-9348-1.html
[2]:http://tldp.org/HOWTO/NCURSES-Programming-HOWTO

View File

@ -0,0 +1,160 @@
Python 中最快解压 zip 文件的方法
======
假设现在的上下文LCTT 译注context计算机术语此处意为业务情景是这样的一个 zip 文件被上传到一个[Web 服务][1]中,然后 Python 需要解压这个 zip 文件然后分析和处理其中的每个文件。这个特殊的应用查看每个文件各自的名称和大小,并和已经上传到 AWS S3 上的文件进行比较,如果文件(和 AWS S3 上的相比)有所不同或者文件本身更新,那么就将它上传到 AWS S3。
[![Uploads today][2]][3]
挑战在于这些 zip 文件太大了。它们的平均大小是 560MB 但是其中一些大于 1GB。这些文件中大多数是文本文件但是其中同样也有一些巨大的二进制文件。不同寻常的是每个 zip 文件包含 100 个文件但是其中 1-3 个文件却占据了多达 95% 的 zip 文件大小。
最开始我尝试在内存中解压文件,并且每次只处理一个文件。在各种内存爆炸和 EC2 耗尽内存的情况下,这个方法壮烈失败了。我觉得这个原因是这样的。最开始你有 1GB 文件在内存中,然后你现在解压每个文件,在内存中大约就要占用 2-3GB。所以在很多次测试之后解决方案是将这些 zip 文件复制到磁盘上(在临时目录 `/tmp` 中),然后遍历这些文件。这次情况好多了但是我仍然注意到了整个解压过程花费了巨量的时间。**是否可能有方法优化呢?**
### 原始函数
首先是下面这些模拟对 zip 文件中文件实际操作的普通函数:
```
def _count_file(fn):
with open(fn, 'rb') as f:
return _count_file_object(f)
def _count_file_object(f):
# Note that this iterates on 'f'.
# You *could* do 'return len(f.read())'
# which would be faster but potentially memory
# inefficient and unrealistic in terms of this
# benchmark experiment.
total = 0
for line in f:
total += len(line)
return total
```
这里是可能最简单的另一个函数:
```
def f1(fn, dest):
with open(fn, 'rb') as f:
zf = zipfile.ZipFile(f)
zf.extractall(dest)
total = 0
for root, dirs, files in os.walk(dest):
for file_ in files:
fn = os.path.join(root, file_)
total += _count_file(fn)
return total
```
如果我更仔细地分析一下,我将会发现这个函数花费时间 40% 运行 `extractall`60% 的时间在遍历各个文件并读取其长度。
### 第一步尝试
我的第一步尝试是使用线程。先创建一个 `zipfile.ZipFile` 的实例,展开其中的每个文件名,然后为每一个文件开始一个线程。每个线程都给它一个函数来做“实质工作”(在这个基准测试中,就是遍历每个文件然后获取它的名称)。实际业务中的函数进行的工作是复杂的 S3、Redis 和 PostgreSQL 操作,但是在我的基准测试中我只需要制作一个可以找出文件长度的函数就好了。线程池函数:
```
def f2(fn, dest):
def unzip_member(zf, member, dest):
zf.extract(member, dest)
fn = os.path.join(dest, member.filename)
return _count_file(fn)
with open(fn, 'rb') as f:
zf = zipfile.ZipFile(f)
futures = []
with concurrent.futures.ThreadPoolExecutor() as executor:
for member in zf.infolist():
futures.append(
executor.submit(
unzip_member,
zf,
member,
dest,
)
)
total = 0
for future in concurrent.futures.as_completed(futures):
total += future.result()
return total
```
**结果:加速 ~10%**
### 第二步尝试
所以可能是 GILLCTT 译注Global Interpreter Lock一种全局锁CPython 中的一个概念)阻碍了我。最自然的想法是尝试使用多线程在多个 CPU 上分配工作。但是这样做有缺点,那就是你不能传递一个非可 pickle 序列化的对象LCTT 译注:意为只有可 pickle 序列化的对象可以被传递),所以你只能发送文件名到之后的函数中:
```
def unzip_member_f3(zip_filepath, filename, dest):
with open(zip_filepath, 'rb') as f:
zf = zipfile.ZipFile(f)
zf.extract(filename, dest)
fn = os.path.join(dest, filename)
return _count_file(fn)
def f3(fn, dest):
with open(fn, 'rb') as f:
zf = zipfile.ZipFile(f)
futures = []
with concurrent.futures.ProcessPoolExecutor() as executor:
for member in zf.infolist():
futures.append(
executor.submit(
unzip_member_f3,
fn,
member.filename,
dest,
)
)
total = 0
for future in concurrent.futures.as_completed(futures):
total += future.result()
return total
```
**结果: 加速 ~300%**
### 这是作弊
使用处理器池的问题是这样需要存储在磁盘上的原始 `.zip` 文件。所以为了在我的 web 服务器上使用这个解决方案,我首先得要将内存中的 zip 文件保存到磁盘,然后调用这个函数。这样做的代价我不是很清楚但是应该不低。
好吧,再翻翻看又没有损失。可能,解压过程加速到足以弥补这样做的损失了吧。
但是一定记住!这个优化取决于使用所有可用的 CPU。如果一些其它的 CPU 需要执行在 `gunicorn` 中的其它事务呢?这时,这些其它进程必须等待,直到有 CPU 可用。由于在这个服务器上有其他的事务正在进行,我不是很确定我想要在进程中接管所有其他 CPU。
### 结论
一步一步地做这个任务的这个过程感觉挺好的。你被限制在一个 CPU 上但是表现仍然特别好。同样地,一定要看看在`f1` 和 `f2` 两段代码之间的不同之处!利用 `concurrent.futures` 池类你可以获取到允许使用的 CPU 的个数,但是这样做同样给人感觉不是很好。如果你在虚拟环境中获取的个数是错的呢?或者可用的个数太低以致无法从负载分配获取好处并且现在你仅仅是为了移动负载而支付营运开支呢?
我将会继续使用 `zipfile.ZipFile(file_buffer).extractall(temp_dir)`。这个工作这样做已经足够好了。
### 想试试手吗?
我使用一个 `c5.4xlarge` EC2 服务器来进行我的基准测试。文件可以从此处下载:
```
wget https://www.peterbe.com/unzip-in-parallel/hack.unzip-in-parallel.py
wget https://www.peterbe.com/unzip-in-parallel/symbols-2017-11-27T14_15_30.zip
```
这里的 `.zip` 文件有 34MB。和在服务器上的相比已经小了很多。
`hack.unzip-in-parallel.py` 文件里是一团糟。它包含了大量可怕的修正和丑陋的代码,但是这只是一个开始。
--------------------------------------------------------------------------------
via: https://www.peterbe.com/plog/fastest-way-to-unzip-a-zip-file-in-python
作者:[Peterbe][a]
译者:[Leemeans](https://github.com/leemeans)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.peterbe.com/
[1]:https://symbols.mozilla.org
[2]:https://cdn-2916.kxcdn.com/cache/b7/bb/b7bbcf60347a5fa91420f71bbeed6d37.png
[3]:https://cdn-2916.kxcdn.com/cache/e6/dc/e6dc20acd37d94239edbbc0727721e4a.png

View File

@ -0,0 +1,69 @@
How Linux became my job
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/linux_penguin_green.png?itok=ENdVzW22)
I've been using open source since what seems like prehistoric times. Back then, there was nothing called social media. There was no Firefox, no Google Chrome (not even a Google), no Amazon, barely an internet. In fact, the hot topic of the day was the new Linux 2.0 kernel. The big technical challenges in those days? Well, the [ELF format][1] was replacing the old [a.out][2] format in binary [Linux][3] distributions, and the upgrade could be tricky on some installs of Linux.
How I transformed a personal interest in this fledgling young operating system to a [career][4] in open source is an interesting story.
### Linux for fun, not profit
I graduated from college in 1994 when computer labs were small networks of UNIX systems; if you were lucky they connected to this new thing called the internet. Hard to believe, I know! The "web" (as we knew it) was mostly handwritten HTML, and the `cgi-bin` directory was a new playground for enabling dynamic web interactions. Many of us were excited about these new technologies, and we taught ourselves shell scripting, [Perl][5], HTML, and all the terse UNIX commands that we had never seen on our parents' Windows 3.1 PCs.
`vi` and `ls` and reading my email via
After graduation, I joined IBM, working on a PC operating system with no access to UNIX systems, and soon my university cut off my remote access to the engineering lab. How was I going to keep usingandand reading my email via [Pine][6] ? I kept hearing about open source Linux, but I hadn't had time to look into it.
In 1996, I was about to begin a master's degree program at the University of Texas at Austin. I knew it would involve programming and writing papers, and who knows what else, and I didn't want to use proprietary editors or compilers or word processors. I wanted my UNIX experience!
So I took an old PC, found a Linux distribution—Slackware 3.0—and downloaded it, diskette after diskette, in my IBM office. Let's just say I've never looked back after that first install of Linux. In those early days, I learned a lot about makefiles and the `make` system, about building software, and about patches and source code control. Even though I started working with Linux for fun and personal knowledge, it ended up transforming my career.
While I was a happy Linux user, I thought open source development was still other people's work; I imagined an online mailing list of mystical [UNIX][7] geeks. I appreciated things like the Linux HOWTO project for helping with the bumps and bruises I acquired trying to add packages, upgrade my Linux distribution, or install device drivers for new hardware or a new PC. But working with source code and making modifications or submitting them upstream … that was for other people, not me.
### How Linux became my job
In 1999, I finally had a reason to combine my personal interest in Linux with my day job at IBM. I took on a skunkworks project to port the IBM Java Virtual Machine (JVM) to Linux. To ensure we were legally safe, IBM purchased a shrink-wrapped, boxed copy of Red Hat Linux 6.1 to do this work. Working with the IBM Tokyo Research lab, which wrote our JVM just-in-time (JIT) compiler, and both the AIX JVM source code and the Windows & OS/2 JVM source code reference, we had a working JVM on Linux within a few weeks, beating the announcement of Sun's official Java on Linux port by several months. Now that I had done development on the Linux platform, I was sold on it.
By 2000, IBM's use of Linux was growing rapidly. Due to the vision and persistence of [Dan Frye][8], IBM made a "[billion dollar bet][9]" on Linux, creating the Linux Technology Center (LTC) in 1999. Inside the LTC were kernel developers, open source contributors, device driver authors for IBM hardware, and all manner of Linux-focused open source work. Instead of remaining tangentially connected to the LTC, I wanted to be part of this exciting new area at IBM.
From 2003 to 2013 I was deeply involved in IBM's Linux strategy and use of Linux distributions, culminating with having a team that became the clearinghouse for about 60 different product uses of Linux across every division of IBM. I was involved in acquisitions where it was an expectation that every appliance, management system, and virtual or physical appliance-based middleware ran Linux. I became well-versed in the construction of Linux distributions, including packaging, selecting upstream sources, developing distro-maintained patch sets, doing customizations, and offering support through our distro partners.
Due to our downstream providers, I rarely got to submit patches upstream, but I got to contribute by interacting with [Ulrich Drepper][10] (including getting a small patch into glibc) and working on changes to the [timezone database][11], which Arthur David Olson accepted while he was maintaining it on the NIH FTP site. But I still hadn't worked as a regular contributor on an open source project as part of my work. It was time for that to change.
In late 2013, I joined IBM's cloud organization in the open source group and was looking for an upstream community in which to get involved. Would it be our work on Cloud Foundry, or would I join IBM's large group of contributors to OpenStack? It was neither, because in 2014 Docker took the world by storm, and IBM asked a few of us to get involved with this hot new technology. I experienced many firsts in the next few months: using GitHub, [learning a lot more about Git][12] than just `git clone`, having pull requests reviewed, writing in Go, and more. Over the next year, I became a maintainer in the Docker engine project, working with Docker on creating the next version of the image specification (to support multiple architectures), and attending and speaking at conferences about container technology.
### Where I am today
Fast forward a few years, and I've become a maintainer of open source projects, including the Cloud Native Computing Foundation (CNCF) [containerd][13] project. I've also created projects (such as [manifest-tool][14] and [bucketbench][15]). I've gotten involved in open source governance via the Open Containers Initiative (OCI), where I'm now a member of the Technical Oversight Board, and the Moby Project, where I'm a member of the Technical Steering Committee. And I've had the pleasure of speaking about open source at conferences around the world, to meetup groups, and internally at IBM.
Open source is now part of the fiber of my career at IBM. The connections I've made to engineers, developers, and leaders across the industry may rival the number of people I know and work with inside IBM. While open source has many of the same challenges as proprietary development teams and vendor partnerships have, in my experience the relationships and connections with people around the globe in open source far outweigh the difficulties. The sharpening that occurs with differing opinions, perspectives, and experiences can generate a culture of learning and improvement for both the software and the people involved.
This journey—from my first use of Linux to becoming a leader, contributor, and maintainer in today's cloud-native open source world—has been extremely rewarding. I'm looking forward to many more years of open source collaboration and interactions with people around the globe.
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/2/my-open-source-story-phil-estes
作者:[Phil Estes][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/estesp
[1]:https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
[2]:https://en.wikipedia.org/wiki/A.out
[3]:https://opensource.com/node/19796
[4]:https://opensource.com/node/25456
[5]:https://opensource.com/node/35141
[6]:https://opensource.com/article/17/10/alpine-email-client
[7]:https://opensource.com/node/22781
[8]:https://www.linkedin.com/in/danieldfrye/
[9]:http://www-03.ibm.com/ibm/history/ibm100/us/en/icons/linux/
[10]:https://www.linkedin.com/in/ulrichdrepper/
[11]:https://en.wikipedia.org/wiki/Tz_database
[12]:https://opensource.com/article/18/1/step-step-guide-git
[13]:https://github.com/containerd/containerd
[14]:https://github.com/estesp/manifest-tool
[15]:https://github.com/estesp/bucketbench

View File

@ -0,0 +1,91 @@
4 considerations when naming software development projects
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/hello-name-sticker-badge-tag.png?itok=fAgbMgBb)
Working on a new open source project, you're focused on the code—getting that great new idea released so you can share it with the world. And you'll want to attract new contributors, so you need a terrific **name** for your project.
We've all read guides for creating names, but how do you go about choosing the right one? Keeping that cool science fiction reference you're using internally might feel fun, but it won't mean much to new users you're trying to attract. A better approach is to choose a name that's memorable to new users and developers searching for your project.
Names set expectations. Your project's name should showcase its functionality in the ecosystem and explain to users what your story is. In the crowded open source software world, it's important not to get entangled with other projects out there. Taking a little extra time now, before sending out that big announcement, will pay off later.
Here are four factors to keep in mind when choosing a name for your project.
### What does your project's code do?
Start with your project: What does it do? You know the code intimately—but can you explain what it does to a new developer? Can you explain it to a CTO or non-developer at another company? What kinds of problems does your project solve for users?
Your project's name needs to reflect what it does in a way that makes sense to newcomers who want to use or contribute to your project. That means considering the ecosystem for your technology and understanding if there are any naming styles or conventions used for similar kinds of projects. Imagine that you're trying to evaluate someone else's project: Would the name be appealing to you?
Any distribution channels you push to are also part of the ecosystem. If your code will be in a Linux distribution, [npm][1], [CPAN][2], [Maven][3], or in a Ruby Gem, you need to review any naming standards or common practices for that package manager. Review any similar existing names in that distribution channel, and get a feel for naming styles of other programs there.
### Who are the users and developers you want to attract?
The hardest aspect of choosing a new name is putting yourself in the shoes of new users. You built this project; you already know how powerful it is, so while your cool name may sound great, it might not draw in new people. You need a name that is interesting to someone new, and that tells the world what problems your project solves.
Great names depend on what kind of users you want to attract. Are you building an [Eclipse][4] plugin or npm module that's focused on developers? Or an analytics toolkit that brings visualizations to the average user? Understanding your user base and the kinds of open source contributors you want to attract is critical.
Great names depend on what kind of users you want to attract.
Take the time to think this through. Who does your project most appeal to, and how can it help them do their job? What kinds of problems does your code solve for end users? Understanding the target user helps you focus on what users need, and what kind of names or brands they respond to.
Take the time to think this through. Who does your project most appeal to, and how can it help them do their job? What kinds of problems does your code solve for end users? Understanding the target user helps you focus on what users need, and what kind of names or brands they respond to.
When you're open source, this equation changes a bit—your target is not just users; it's also developers who will want to contribute code back to your project. You're probably a developer, too: What kinds of names and brands excite you, and what images would entice you to try out someone else's new project?
Once you have a better feel of what users and potential contributors expect, use that knowledge to refine your names. Remember, you need to step outside your project and think about how the name would appeal to someone who doesn't know how amazing your code is—yet. Once someone gets to your website, does the name synchronize with what your product does? If so, move to the next step.
### Who else is using similar names for software?
Now that you've tried on a user's shoes to evaluate potential names, what's next? Figuring out if anyone else is already using a similar name. It sometimes feels like all the best names are taken—but if you search carefully, you'll find that's not true.
The first step is to do a few web searches using your proposed name. Search for the name, plus "software", "open source", and a few keywords for the functionality that your code provides. Look through several pages of results for each search to see what's out there in the software world.
The first step is to do a few web searches using your proposed name.
Unless you're using a completely made-up word, you'll likely get a lot of hits. The trick is understanding which search results might be a problem. Again, put on the shoes of a new user to your project. If you were searching for this great new product and saw the other search results along with your project's homepage, would you confuse them? Are the other search results even software products? If your product solves a similar problem to other search results, that's a problem: Users may gravitate to an existing product instead of a new one.
Unless you're using a completely made-up word, you'll likely get a lot of hits. The trick is understanding which search results might be a problem. Again, put on the shoes of a new user to your project. If you were searching for this great new product and saw the other search results along with your project's homepage, would you confuse them? Are the other search results even software products? If your product solves a similar problem to other search results, that's a problem: Users may gravitate to an existing product instead of a new one.
Similar non-software product names are rarely an issue unless they are famous trademarks—like Nike or Red Bull, for example—where the companies behind them won't look kindly on anyone using a similar name. Using the same name as a less famous non-software product might be OK, depending on how big your project gets.
### How big do you plan to grow your project?
Are you building a new node module or command-line utility, but not planning a career around it? Is your new project a million-dollar business idea, and you're thinking startup? Or is it something in between?
If your project is a basic developer utility—something useful that developers will integrate into their workflow—then you have enough data to choose a name. Think through the ecosystem and how a new user would see your potential names, and pick one. You don't need perfection, just a name you're happy with that seems right for your project.
If you're planning to build a business around your project, use these tips to develop a shortlist of names, but do more vetting before announcing the winner. Use for a business or major project requires some level of registered trademark search, which is usually performed by a law firm.
### Common pitfalls
Finally, when choosing a name, avoid these common pitfalls:
* Using an esoteric acronym. If new users don't understand the name, they'll have a hard time finding you.
* Using current pop-culture references. If you want your project's appeal to last, pick a name that will last.
* Failing to consider non-English speakers. Does the name have a specific meaning in another language that might be confusing?
* Using off-color jokes or potentially unsavory references. Even if it seems funny to developers, it may fall flat for newcomers and turn away contributors.
Good luck—and remember to take the time to step out of your shoes and consider how a newcomer to your project will think of the name.
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/2/choosing-project-names-four-key-considerations
作者:[Shane Curcuru][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/shane-curcuru
[1]:https://www.npmjs.com/
[2]:https://www.cpan.org/
[3]:https://maven.apache.org/
[4]:https://www.eclipse.org/

View File

@ -0,0 +1,55 @@
Translating by MjSeven
How slowing down made me a better leader
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/BUSINESS_leadership_brand.png?itok=YW1Syk4S)
Early in my career, I thought the most important thing I could do was act. If my boss said jump, my reply was "how high?"
But as I've grown as a leader and manager, I've realized that the most important traits I can offer are [patience][1] and listening. This patience and listening means I'm focusing on what's really important. I'm decisive, so I do not hesitate to act. Yet I've learned that my actions are more impactful when I consider input from multiple sources and offer advice on what we should be doing—not simply reacting to an immediate request.
Practicing open leadership involves cultivating the patience and listening skills I need to collaborate on the [best plan of action, not just the quickest one][2]. It also gives me the tools I need to explain [why I'm saying "no"][3] (or, perhaps, "not now") to someone, so I can lead with transparency and confidence.
If you're in software development and practice scrum, then the following argument might resonate with you: The patience and listening a manager displays are as important as her skills in sprint planning and running the sprint demo. Forget about them, and you'll lessen the impact you're able to have.
### A focus on patience
Focus and patience do not always come easily. Often, I find myself sitting in meetings and filling my notebook with action items. My default action can be to think: "We can simply do x and y will improve!" Then I remember that things are not so linear.
I need to think about the other factors that can influence a situation. Pausing to take in data from multiple people and resources helps me flesh out a strategy that our organization needs for long-term success. It also helps me identify those shorter-term milestones that should lead us to deliver the business results I'm responsible for producing.
Here's a great example from a time when patience wasn't something I valued as I should have—and how that hurt my performance. When I was based on North Carolina, I worked with someone based in Arizona. We didn't use video conferencing technologies, so I didn't get to observe her body language when we talked. While I was responsible for delivering the results for the project I led, she was one of the two people tasked with making sure I had adequate support.
For whatever reason, when I talked with this person, when she asked me to do something, I did it. She would be providing input on my performance evaluation, so I wanted to make sure she was happy. At the time, I didn't possess the maturity to know I didn't need to make her happy; my focus should have been on other performance indicators. I should have spent more time listening and collaborating with her instead of picking up the first "action item" and working on it while she was still talking.
After six months on the job, this person gave me some tough feedback. I was angry and sad. Didn't I do everything she'd asked? I had worked long hours, nearly seven days a week for six months. How dare she criticize my performance?
Then, after I had my moment of anger followed by sadness, I thought about what she said. Her feedback was on point.
The patience and listening a manager displays are as important as her skills in sprint planning and running the sprint demo.
She had concerns about the project, and she held me accountable because I was responsible. We worked through the issues, and I learned that vital lesson about how to lead: Leadership does not mean "get it done right now." Leadership means putting together a strategy, then communicating and implementing plans in support of the strategy. It also means making mistakes and learning from these hiccups.
### Lesson learned
In hindsight, I realize I could have asked more questions to better understand the intent of her feedback. I also could have pushed back if the guidance from her did not align with other input I was receiving. By having the patience to listen to the various sources giving me input about the project, synthesizing what I learned, and creating a coherent plan for action, I would have been a better leader. I also would have had more purpose driving the work I was doing. Instead of reacting to a single data point, I would have been implementing a strategic plan. I also would have had a better performance evaluation.
I eventually had some feedback for her. Next time we worked together, I didn't want to hear the feedback after six months. I wanted to hear the feedback earlier and more often so I could learn from the mistakes sooner. An ongoing discussion about the work is what should happen on any team.
As I mature as a manager and leader, I hold myself to the same standards I ask my team to meet: Plan, work the plan, and reflect. Repeat. Don't let a fire drill created by an external force distract you from the plan you need to implement. Breaking work into small increments builds in space for reflections and adjustments to the plan. As Daniel Goleman writes, "Directing attention toward where it needs to go is a primal task of leadership." Don't be afraid of meeting this challenge.
--------------------------------------------------------------------------------
via: https://opensource.com/open-organization/18/2/open-leadership-patience-listening
作者:[Angela Robertson][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/arobertson98
[1]:https://opensource.com/open-organization/16/3/my-most-difficult-leadership-lesson
[2]:https://opensource.com/open-organization/16/3/fastest-result-isnt-always-best-result
[3]:https://opensource.com/open-organization/17/5/saying-no-open-organization

View File

@ -1,478 +0,0 @@
Translating by shipsw
Top 20 OpenSSH Server Best Security Practices
======
![OpenSSH Security Tips][1]
OpenSSH is the implementation of the SSH protocol. OpenSSH is recommended for remote login, making backups, remote file transfer via scp or sftp, and much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two networks and systems. However, the main advantage is server authentication, through the use of public key cryptography. From time to time there are [rumors][2] about OpenSSH zero day exploit. This **page shows how to secure your OpenSSH server running on a Linux or Unix-like system to improve sshd security**.
#### OpenSSH defaults
* TCP port - 22
* OpenSSH server config file - sshd_config (located in /etc/ssh/)
#### 1. Use SSH public key based login
OpenSSH server supports various authentication. It is recommended that you use public key based authentication. First, create the key pair using following ssh-keygen command on your local desktop/laptop:
DSA and RSA 1024 bit or lower ssh keys are considered weak. Avoid them. RSA keys are chosen over ECDSA keys when backward compatibility is a concern with ssh clients. All ssh keys are either ED25519 or RSA. Do not use any other type.
```
$ ssh-keygen -t key_type -b bits -C "comment"
$ ssh-keygen -t ed25519 -C "Login to production cluster at xyz corp"
$ ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_aws_$(date +%Y-%m-%d) -C "AWS key for abc corp clients"
```
Next, install the public key using ssh-copy-id command:
```
$ ssh-copy-id -i /path/to/public-key-file user@host
$ ssh-copy-id user@remote-server-ip-or-dns-name
$ ssh-copy-id vivek@rhel7-aws-server
```
When promoted supply user password. Verify that ssh key based login working for you:
`$ ssh vivek@rhel7-aws-server`
[![OpenSSH server security best practices][3]][3]
For more info on ssh public key auth see:
* [keychain: Set Up Secure Passwordless SSH Access For Backup Scripts][48]
* [sshpass: Login To SSH Server / Provide SSH Password Using A Shell Script][49]
* [How To Setup SSH Keys on a Linux / Unix System][50]
* [How to upload ssh public key to as authorized_key using Ansible DevOPS tool][51]
#### 2. Disable root user login
Before we disable root user login, make sure regular user can log in as root. For example, allow vivek user to login as root using the sudo command.
##### How to add vivek user to sudo group on a Debian/Ubuntu
Allow members of group sudo to execute any command. [Add user vivek to sudo group][4]:
`$ sudo adduser vivek sudo`
Verify group membership with [id command][5]
`$ id vivek`
##### How to add vivek user to sudo group on a CentOS/RHEL server
Allows people in group wheel to run all commands on a CentOS/RHEL and Fedora Linux server. Use the usermod command to add the user named vivek to the wheel group:
```
$ sudo usermod -aG wheel vivek
$ id vivek
```
##### Test sudo access and disable root login for ssh
Test it and make sure user vivek can log in as root or run the command as root:
```
$ sudo -i
$ sudo /etc/init.d/sshd status
$ sudo systemctl status httpd
```
Once confirmed disable root login by adding the following line to sshd_config:
```
PermitRootLogin no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
```
See "[How to disable ssh password login on Linux to increase security][6]" for more info.
#### 3. Disable password based login
All password-based logins must be disabled. Only public key based logins are allowed. Add the following in your sshd_config file:
```
AuthenticationMethods publickey
PubkeyAuthentication yes
```
Older version of SSHD on CentOS 6.x/RHEL 6.x user should use the following setting:
```
PubkeyAuthentication yes
```
#### 4. Limit Users' ssh access
By default, all systems user can login via SSH using their password or public key. Sometimes you create UNIX / Linux user account for FTP or email purpose. However, those users can log in to the system using ssh. They will have full access to system tools including compilers and scripting languages such as Perl, Python which can open network ports and do many other fancy things. Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:
`AllowUsers vivek jerry`
Alternatively, you can allow all users to login via SSH but deny only a few users, with the following line in sshd_config:
`DenyUsers root saroj anjali foo`
You can also [configure Linux PAM][7] allows or deny login via the sshd server. You can allow [list of group name][8] to access or deny access to the ssh.
#### 5. Disable Empty Passwords
You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:
`PermitEmptyPasswords no`
#### 6. Use strong passwords and passphrase for ssh users/keys
It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because user goes to dictionary based passwords. You can force users to avoid [passwords against a dictionary][9] attack and use [john the ripper tool][10] to find out existing weak passwords. Here is a sample random password generator (put in your ~/.bashrc):
```
genpasswd() {
local l=$1
[ "$l" == "" ] && l=20
tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
```
Run it:
`genpasswd 16`
Output:
```
uw8CnDVMwC6vOKgW
```
* [Generating Random Password With mkpasswd / makepasswd / pwgen][52]
* [Linux / UNIX: Generate Passwords][53]
* [Linux Random Password Generator Command][54]
--------------------------------------------------------------------------------
#### 7. Firewall SSH TCP port # 22
You need to firewall ssh TCP port # 22 by updating iptables/ufw/firewall-cmd or pf firewall configurations. Usually, OpenSSH server must only accept connections from your LAN or other remote WAN sites only.
##### Netfilter (Iptables) Configuration
Update [/etc/sysconfig/iptables (Redhat and friends specific file) to accept connection][11] only from 192.168.1.0/24 and 202.54.1.5/29, enter:
```
-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -s 202.54.1.5/29 -m state --state NEW -p tcp --dport 22 -j ACCEPT
```
If you've dual stacked sshd with IPv6, edit /etc/sysconfig/ip6tables (Redhat and friends specific file), enter:
```
-A RH-Firewall-1-INPUT -s ipv6network::/ipv6mask -m tcp -p tcp --dport 22 -j ACCEPT
```
Replace ipv6network::/ipv6mask with actual IPv6 ranges.
##### UFW for Debian/Ubuntu Linux
[UFW is an acronym for uncomplicated firewall. It is used for managing a Linux firewall][12] and aims to provide an easy to use interface for the user. Use the [following command to accept port 22 from 202.54.1.5/29][13] only:
`$ sudo ufw allow from 202.54.1.5/29 to any port 22`
Read "[Linux: 25 Iptables Netfilter Firewall Examples For New SysAdmins][14]" for more info.
##### *BSD PF Firewall Configuration
If you are using PF firewall update [/etc/pf.conf][15] as follows:
```
pass in on $ext_if inet proto tcp from {192.168.1.0/24, 202.54.1.5/29} to $ssh_server_ip port ssh flags S/SA synproxy state
```
#### 8. Change SSH Port and limit IP binding
By default, SSH listens to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (many brutes forcing scripts only try to connect to TCP port # 22). To bind to 192.168.1.5 and 202.54.1.5 IPs and port 300, add or correct the following line in sshd_config:
```
Port 300
ListenAddress 192.168.1.5
ListenAddress 202.54.1.5
```
Port 300 ListenAddress 192.168.1.5 ListenAddress 202.54.1.5
A better approach to use proactive approaches scripts such as fail2ban or denyhosts when you want to accept connection from dynamic WAN IP address.
#### 9. Use TCP wrappers (optional)
TCP Wrapper is a host-based Networking ACL system, used to filter network access to the Internet. OpenSSH does support TCP wrappers. Just update your /etc/hosts.allow file as follows to allow SSH only from 192.168.1.2 and 172.16.23.12 IP address:
```
sshd : 192.168.1.2 172.16.23.12
```
See this [FAQ about setting and using TCP wrappers][16] under Linux / Mac OS X and UNIX like operating systems.
#### 10. Thwart SSH crackers/brute force attacks
Brute force is a method of defeating a cryptographic scheme by trying a large number of possibilities (combination of users and passwords) using a single or distributed computer network. To prevents brute force attacks against SSH, use the following software:
* [DenyHosts][17] is a Python based security tool for SSH servers. It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.
* Explains how to setup [DenyHosts][18] under RHEL / Fedora and CentOS Linux.
* [Fail2ban][19] is a similar program that prevents brute force attacks against SSH.
* [sshguard][20] protect hosts from brute force attacks against ssh and other services using pf.
* [security/sshblock][21] block abusive SSH login attempts.
* [ IPQ BDB filter][22] May be considered as a fail2ban lite.
#### 11. Rate-limit incoming traffic at TCP port # 22 (optional)
Both netfilter and pf provides rate-limit option to perform simple throttling on incoming connections on port # 22.
##### Iptables Example
The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:
```
#!/bin/bash
inet_if=eth1
ssh_port=22
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --set
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --update --seconds 60 --hitcount 5
```
Call above script from your iptables scripts. Another config option:
```
$IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT
$IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
# another one line example
# $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT
```
See iptables man page for more details.
##### *BSD PF Example
The following will limits the maximum number of connections per source to 20 and rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.
```
sshd_server_ip = "202.54.1.5"
table <abusive_ips> persist
block in quick from <abusive_ips>
pass in on $ext_if proto tcp to $sshd_server_ip port ssh flags S/SA keep state (max-src-conn 20, max-src-conn-rate 15/5, overload <abusive_ips> flush)
```
#### 12. Use port knocking (optional)
[Port knocking][23] is a method of externally opening ports on a firewall by generating a connection attempt on a set of prespecified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect to the specific port(s). A sample port Knocking example for ssh using iptables:
```
$IPT -N stage1
$IPT -A stage1 -m recent --remove --name knock
$IPT -A stage1 -p tcp --dport 3456 -m recent --set --name knock2
$IPT -N stage2
$IPT -A stage2 -m recent --remove --name knock2
$IPT -A stage2 -p tcp --dport 2345 -m recent --set --name heaven
$IPT -N door
$IPT -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2
$IPT -A door -m recent --rcheck --seconds 5 --name knock -j stage1
$IPT -A door -p tcp --dport 1234 -m recent --set --name knock
$IPT -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT
$IPT -A INPUT -p tcp --syn -j door
```
For more info see:
[Debian / Ubuntu: Set Port Knocking With Knockd and Iptables][55]
#### 13. Configure idle log out timeout interval
A user can log in to the server via ssh, and you can set an idle timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:
```
ClientAliveInterval 300
ClientAliveCountMax 0
```
You are setting an idle timeout interval in seconds (300 secs == 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out). See [how to automatically log BASH / TCSH / SSH users][24] out after a period of inactivity for more details.
#### 14. Enable a warning banner for ssh users
Set a warning banner by updating sshd_config with the following line:
`Banner /etc/issue`
Sample /etc/issue file:
```
----------------------------------------------------------------------------------------------
You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only.
By using this IS (which includes any device attached to this IS), you consent to the following conditions:
+ The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to,
penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM),
law enforcement (LE), and counterintelligence (CI) investigations.
+ At any time, the XYZG may inspect and seize data stored on this IS.
+ Communications using, or data stored on, this IS are not private, are subject to routine monitoring,
interception, and search, and may be disclosed or used for any XYZG authorized purpose.
+ This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not
for your personal benefit or privacy.
+ Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching
or monitoring of the content of privileged communications, or work product, related to personal representation
or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work
product are private and confidential. See User Agreement for details.
----------------------------------------------------------------------------------------------
```
Above is a standard sample, consult your legal team for specific user agreement and legal notice details.
#### 15. Disable .rhosts files (verification)
Don't read the user's ~/.rhosts and ~/.shosts files. Update sshd_config with the following settings:
`IgnoreRhosts yes`
SSH can emulate the behavior of the obsolete rsh command, just disable insecure access via RSH.
#### 16. Disable host-based authentication (verification)
To disable host-based authentication, update sshd_config with the following option:
`HostbasedAuthentication no`
#### 17. Patch OpenSSH and operating systems
It is recommended that you use tools such as [yum][25], [apt-get][26], [freebsd-update][27] and others to keep systems up to date with the latest security patches:
#### 18. Chroot OpenSSH (Lock down users to their home directories)
By default users are allowed to browse the server directories such as /etc/, /bin and so on. You can protect ssh, using os based chroot or use [special tools such as rssh][28]. With the release of OpenSSH 4.8p1 or 4.9p1, you no longer have to rely on third-party hacks such as rssh or complicated chroot(1) setups to lock users to their home directories. See [this blog post][29] about new ChrootDirectory directive to lock down users to their home directories.
#### 19. Disable OpenSSH server on client computer
Workstations and laptop can work without OpenSSH server. If you do not provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL users can disable and remove openssh-server with the [yum command][30]:
`$ sudo yum erase openssh-server`
Debian / Ubuntu Linux user can disable and remove the same with the [apt command][31]/[apt-get command][32]:
`$ sudo apt-get remove openssh-server`
You may need to update your iptables script to remove ssh exception rule. Under CentOS / RHEL / Fedora edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Once done [restart iptables][33] service:
```
# service iptables restart
# service ip6tables restart
```
#### 20. Bonus tips from Mozilla
If you are using OpenSSH version 6.7+ or newer try [following][34] settings:
```
#################[ WARNING ]########################
# Do not use any setting blindly. Read sshd_config #
# man page. You must understand cryptography to #
# tweak following settings. Otherwise use defaults #
####################################################
# Supported HostKey algorithms by order of preference.
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
# Specifies the available KEX (Key Exchange) algorithms.
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
# Specifies the ciphers allowed
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
#Specifies the available MAC (message authentication code) algorithms
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com
# LogLevel VERBOSE logs user's key fingerprint on login. Needed to have a clear audit track of which key was using to log in.
LogLevel VERBOSE
# Log sftp level file access (read/write/etc.) that would not be easily logged otherwise.
Subsystem sftp /usr/lib/ssh/sftp-server -f AUTHPRIV -l INFO
```
You can grab list of cipher and alog supported by your OpenSSH server using the following commands:
```
$ ssh -Q cipher
$ ssh -Q cipher-auth
$ ssh -Q mac
$ ssh -Q kex
$ ssh -Q key
```
[![OpenSSH Security Tutorial Query Ciphers and algorithms choice][35]][35]
#### How do I test sshd_config file and restart/reload my SSH server?
To [check the validity of the configuration file and sanity of the keys][36] for any errors before restarting sshd, run:
`$ sudo sshd -t`
Extended test mode:
`$ sudo sshd -T`
Finally [restart sshd on a Linux or Unix like systems][37] as per your distro version:
```
$ [sudo systemctl start ssh][38] ## Debian/Ubunt Linux##
$ [sudo systemctl restart sshd.service][39] ## CentOS/RHEL/Fedora Linux##
$ doas /etc/rc.d/sshd restart ## OpenBSD##
$ sudo service sshd restart ## FreeBSD##
```
#### Other susggesions
1. [Tighter SSH security with 2FA][40] - Multi-Factor authentication can be enabled with [OATH Toolkit][41] or [DuoSecurity][42].
2. [Use keychain based authentication][43] - keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys
#### See also:
* The [official OpenSSH][44] project.
* Man pages: sshd(8),ssh(1),ssh-add(1),ssh-agent(1)
If you have a technique or handy software not mentioned here, please share in the comments below to help your fellow readers keep their OpenSSH based server secure.
#### About the author
The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on [Twitter][45], [Facebook][46], [Google+][47].
--------------------------------------------------------------------------------
via: https://www.cyberciti.biz/tips/linux-unix-bsd-openssh-server-best-practices.html
作者:[Vivek Gite][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.cyberciti.biz
[1]:https://www.cyberciti.biz/media/new/tips/2009/07/openSSH_logo.png
[2]:https://isc.sans.edu/diary/OpenSSH+Rumors/6742
[3]:https://www.cyberciti.biz/tips/wp-content/uploads/2009/07/OpenSSH-server-security-best-practices.png
[4]:https://www.cyberciti.biz/faq/how-to-create-a-sudo-user-on-ubuntu-linux-server/
[5]:https://www.cyberciti.biz/faq/unix-linux-id-command-examples-usage-syntax/ (See Linux/Unix id command examples for more info)
[6]:https://www.cyberciti.biz/faq/how-to-disable-ssh-password-login-on-linux/
[7]:https://www.cyberciti.biz/tips/linux-pam-configuration-that-allows-or-deny-login-via-the-sshd-server.html
[8]:https://www.cyberciti.biz/tips/openssh-deny-or-restrict-access-to-users-and-groups.html
[9]:https://www.cyberciti.biz/tips/linux-check-passwords-against-a-dictionary-attack.html
[10]:https://www.cyberciti.biz/faq/unix-linux-password-cracking-john-the-ripper/
[11]:https://www.cyberciti.biz/faq/rhel-fedorta-linux-iptables-firewall-configuration-tutorial/
[12]:https://www.cyberciti.biz/faq/howto-configure-setup-firewall-with-ufw-on-ubuntu-linux/
[13]:https://www.cyberciti.biz/faq/ufw-allow-incoming-ssh-connections-from-a-specific-ip-address-subnet-on-ubuntu-debian/
[14]:https://www.cyberciti.biz/tips/linux-iptables-examples.html
[15]:https://bash.cyberciti.biz/firewall/pf-firewall-script/
[16]:https://www.cyberciti.biz/faq/tcp-wrappers-hosts-allow-deny-tutorial/
[17]:https://www.cyberciti.biz/faq/block-ssh-attacks-with-denyhosts/
[18]:https://www.cyberciti.biz/faq/rhel-linux-block-ssh-dictionary-brute-force-attacks/
[19]:https://www.fail2ban.org
[20]:https://sshguard.sourceforge.net/
[21]:http://www.bsdconsulting.no/tools/
[22]:https://savannah.nongnu.org/projects/ipqbdb/
[23]:https://en.wikipedia.org/wiki/Port_knocking
[24]:https://www.cyberciti.biz/faq/linux-unix-login-bash-shell-force-time-outs/
[25]:https://www.cyberciti.biz/faq/rhel-centos-fedora-linux-yum-command-howto/
[26]:https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html
[27]:https://www.cyberciti.biz/tips/howto-keep-freebsd-system-upto-date.html
[28]:https://www.cyberciti.biz/tips/rhel-centos-linux-install-configure-rssh-shell.html
[29]:https://www.debian-administration.org/articles/590
[30]:https://www.cyberciti.biz/faq/rhel-centos-fedora-linux-yum-command-howto/ (See Linux/Unix yum command examples for more info)
[31]:https://www.cyberciti.biz/faq/ubuntu-lts-debian-linux-apt-command-examples/ (See Linux/Unix apt command examples for more info)
[32]:https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html (See Linux/Unix apt-get command examples for more info)
[33]:https://www.cyberciti.biz/faq/howto-rhel-linux-open-port-using-iptables/
[34]:https://wiki.mozilla.org/Security/Guidelines/OpenSSH
[35]:https://www.cyberciti.biz/tips/wp-content/uploads/2009/07/OpenSSH-Security-Tutorial-Query-Ciphers-and-algorithms-choice.jpg
[36]:https://www.cyberciti.biz/tips/checking-openssh-sshd-configuration-syntax-errors.html
[37]:https://www.cyberciti.biz/faq/howto-restart-ssh/
[38]:https://www.cyberciti.biz/faq/howto-start-stop-ssh-server/ (Restart sshd on a Debian/Ubuntu Linux)
[39]:https://www.cyberciti.biz/faq/centos-stop-start-restart-sshd-command/ (Restart sshd on a CentOS/RHEL/Fedora Linux)
[40]:https://www.cyberciti.biz/open-source/howto-protect-linux-ssh-login-with-google-authenticator/
[41]:http://www.nongnu.org/oath-toolkit/
[42]:https://duo.com
[43]:https://www.cyberciti.biz/faq/ssh-passwordless-login-with-keychain-for-scripts/
[44]:https://www.openssh.com/
[45]:https://twitter.com/nixcraft
[46]:https://facebook.com/nixcraft
[47]:https://plus.google.com/+CybercitiBiz
[48]:https://www.cyberciti.biz/faq/ssh-passwordless-login-with-keychain-for-scripts/
[49]:https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/
[50]:https://www.cyberciti.biz/faq/how-to-set-up-ssh-keys-on-linux-unix/
[51]:https://www.cyberciti.biz/faq/how-to-upload-ssh-public-key-to-as-authorized_key-using-ansible/
[52]:https://www.cyberciti.biz/faq/generating-random-password/
[53]:https://www.cyberciti.biz/faq/linux-unix-generating-passwords-command/
[54]:https://www.cyberciti.biz/faq/linux-random-password-generator/
[55]:https://www.cyberciti.biz/faq/debian-ubuntu-linux-iptables-knockd-port-knocking-tutorial/

View File

@ -1,193 +0,0 @@
Translating by qhwdw
Choosing a Linux Tracer (2015)
======
[![][1]][2]
_Linux Tracing is Magic!_
A tracer is an advanced performance analysis and troubleshooting tool, but don't let that intimidate you... If you've used strace(1) or tcpdump(8) - you've used a tracer. System tracers can see much more than just syscalls or packets, as they can typically trace any kernel or application software.
There are so many Linux tracers that the choice is overwhelming. As each has an official (or unofficial) pony-corn mascot, we have enough for a kids' show.
Which tracer should you use?
I've answered this question for two audiences: for most people, and, for performance/kernel engineers. This will also change over time, so I'll need to post follow-ups, maybe once a year or so.
## For Most People
Most people (developers, sysadmins, devops, SREs, ...) are not going to learn a system tracer in gory detail. Here's what you most likely need to know and do about tracers:
### 1. Use perf_events for CPU profiling
Use perf_events to do CPU profiling. The profile can be visualized as a [flame graph][3]. Eg:
```
git clone --depth 1 https://github.com/brendangregg/FlameGraph
perf record -F 99 -a -g -- sleep 30
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > perf.svg
```
Linux perf_events (aka "perf", after its command) is the official tracer/profiler for Linux users. It is in the kernel source, and is well maintained (and currently rapidly being enhanced). It's usually added via a linux-tools-common package.
perf can do many things, but if I had to recommend you learn just one, it would be CPU profiling. Even though this is not technically "tracing" of events, as it's sampling. The hardest part is getting full stacks and symbols to work, which I covered in my [Linux Profiling at Netflix][4] talk for Java and Node.js.
### 2. Know what else is possible
As a friend once said: "You don't need to know how to operate an X-ray machine, but you _do_ need to know that if you swallow a penny, an X-ray is an option!" You need to know what is possible with tracers, so that if your business really needs it, you can either learn how to do it later, or hire someone who does.
In a nutshell: performance of virtually anything can be understood with tracing. File system internals, TCP/IP processing, device drivers, application internals. Read my lwn.net [article on ftrace][5], and browse my [perf_events page][6], as examples of some tracing (and profiling) capabilities.
### 3. Ask for front ends
If you are paying for performance analysis tools (and there are many companies that sell them), ask for Linux tracing support. Imagine an intuitive point-and-click interface that can expose kernel internals, including latency heatmaps at different stack locations. I described such an interface in my [Monitorama talk][7].
I've created and open sourced some front ends myself, although for the CLI (not GUIs). These also allow people to benefit from the tracers more quickly and easily. Eg, from my [perf-tools][8], tracing new processes:
```
# ./execsnoop
Tracing exec()s. Ctrl-C to end.
PID PPID ARGS
22898 22004 man ls
22905 22898 preconv -e UTF-8
22908 22898 pager -s
22907 22898 nroff -mandoc -rLL=164n -rLT=164n -Tutf8
[...]
```
At Netflix, we're creating [Vector][9], an instance analysis tool that should also eventually front Linux tracers.
## For Performance or Kernel Engineers
Our job is much harder, since most people may be asking us to figure out how to trace something, and therefore which tracer to use. To properly understand a tracer, you usually need to spend at least one hundred hours with it. Understanding all the Linux tracers to make a rational decision between them a huge undertaking. (I may be the only person who has come close to doing this.)
Here's what I'd recommend. Either:
A) Pick one all-powerful tracer, and standardize on that. This will involve a lot of time figuring out its nuances and safety in a test environment. I'd currently recommend the latest version of SystemTap (ie, build from [source][10]). I know of companies that have picked LTTng, and are happy with it, although it's not quite as powerful (although, it is safer). If sysdig adds tracepoints or kprobes, it could be another candidate.
B) Follow the above flow chart from my [Velocity tutorial][11]. It will mean using ftrace or perf_events as much as possible, eBPF as it gets integrated, and then other tracers like SystemTap/LTTng to fill in the gaps. This is what I do in my current job at Netflix.
Comments by tracer:
### 1. ftrace
I love [Ftrace][12], it's a kernel hacker's best friend. It's built into the kernel, and can consume tracepoints, kprobes, and uprobes, and provides a few capabilities: event tracing, with optional filters and arguments; event counting and timing, summarized in-kernel; and function-flow walking. See [ftrace.txt][13] from the kernel source for examples. It's controlled via /sys, and is intended for a single root user (although you could hack multi-user support using buffer instances). Its interface can be fiddly at times, but it's quite hackable, and there are front ends: Steven Rostedt, the main ftrace author, has created trace-cmd, and I've created the perf-tools collection. My biggest gripe is that it isn't programmable, so you can't, for example, save and fetch timestamps, calculate latency, and then store it as a histogram. You'll need to dump events to user-level, and post-process, at some cost. It may become programmable via eBPF.
### 2. perf_events
[perf_events][14] is the main tracing tool for Linux users, its source is in the Linux kernel, and is usually added via a linux-tools-common package. Aka "perf", after its front end, which is typically used to trace & dump to a file (perf.data), which it does relatively efficiently (dynamic buffering), and then post-processeses that later. It can do most of what ftrace can. It can't do function-flow walking, and is a bit less hackable (as it has better safety/error checking). But it can do profiling (sampling), CPU performance counters, user-level stack translation, and can consume debuginfo for line tracing with local variables. It also supports multiple concurrent users. As with ftrace, it isn't kernel programmable yet, until perhaps eBPF support (patches have been proposed). If there's one tracer I'd recommend people learn, it'd be perf, as it can solve a ton of issues, and is relatively safe.
### 3. eBPF
The extended Berkeley Packet Filter is an in-kernel virtual machine that can run programs on events, efficiently (JIT). It's likely to eventually provide in-kernel programming for ftrace and perf_events, and to enhance other tracers. It's currently being developed by Alexei Starovoitov, and isn't fully integrated yet, but there's enough in-kernel (as of 4.1) for some impressive tools: eg, latency heat maps of block device I/O. For reference, see the [BPF slides][15] from Alexei, and his [eBPF samples][16].
### 4. SystemTap
[SystemTap][17] is the most powerful tracer. It can do everything: profiling, tracepoints, kprobes, uprobes (which came from SystemTap), USDT, in-kernel programming, etc. It compiles programs into kernel modules and loads them - an approach which is tricky to get safe. It is also developed out of tree, and has had issues in the past (panics or freezes). Many are not SystemTap's fault - it's often the first to use certain tracing capabilities with the kernel, and the first to run into bugs. The latest version of SystemTap is much better (you must compile from source), but many people are still spooked from earlier versions. If you want to use it, spend time in a test environment, and chat to the developers in #systemtap on irc.freenode.net. (Netflix has a fault-tolerant architecture, and we have used SystemTap, but we may be less concerned about safety than you.) My biggest gripe is that it seems to assume you'll have kernel debuginfo, which I don't usually have. It actually can do a lot without it, but documentation and examples are lacking (I've begun to help with that myself).
### 5. LTTng
[LTTng][18] has optimized event collection, which outperforms other tracers, and also supports numerous event types, including USDT. It is developed out of tree. The core of it is very simple: write events to a tracing buffer, via a small and fixed set of instructions. This helps make it safe and fast. The downside is that there's no easy way to do in-kernel programming. I keep hearing that this is not a big problem, since it's so optimized that it can scale sufficiently despite needing post processing. It also has been pioneering a different analysis technique, more of a black box recording of all interesting events that can be studied in GUIs later. I'm concerned about such a recording missing events I didn't have the foresight to record, but I really need to spend more time with it to see how well it works in practice. It's the tracer I've spent the least time with (no particular reason).
### 6. ktap
[ktap][19] was a really promising tracer, which used an in-kernel lua virtual machine for processing, and worked fine without debuginfo and on embedded devices. It made it into staging, and for a moment looked like it would win the trace race on Linux. Then eBPF began kernel integration, and ktap integration was postponed until it could use eBPF instead of its own VM. Since eBPF is still integrating many months later, the ktap developers have been waiting a long time. I hope it restarts development later this year.
### 7. dtrace4linux
[dtrace4linux][20] is mostly one man's part-time effort (Paul Fox) to port Sun DTrace to Linux. It's impressive, and some providers work, but it's some ways from complete, and is more of an experimental tool (unsafe). I think concern over licensing has left people wary of contributing: it will likely never make it into the Linux kernel, as Sun released DTrace under the CDDL license; Paul's approach to this is to make it an add-on. I'd love to see DTrace on Linux and this project finished, and thought I'd spend time helping it finish when I joined Netflix. However, I've been spending time using the built-in tracers, ftrace and perf_events, instead.
### 8. OL DTrace
[Oracle Linux DTrace][21] is a serious effort to bring DTrace to Linux, specifically Oracle Linux. Various releases over the years have shown steady progress. The developers have even spoken about improving the DTrace test suite, which shows a promising attitude to the project. Many useful providers have already been completed: syscall, profile, sdt, proc, sched, and USDT. I'm still waiting for fbt (function boundary tracing, for kernel dynamic tracing), which will be awesome on the Linux kernel. Its ultimate success will hinge on whether it's enough to tempt people to run Oracle Linux (and pay for support). Another catch is that it may not be entirely open source: the kernel components are, but I've yet to see the user-level code.
### 9. sysdig
[sysdig][22] is a new tracer that can operate on syscall events with tcpdump-like syntax, and lua post processing. It's impressive, and it's great to see innovation in the system tracing space. Its limitations are that it is syscalls only at the moment, and, that it dumps all events to user-level for post processing. You can do a lot with syscalls, although I'd like to see it support tracepoints, kprobes, and uprobes. I'd also like to see it support eBPF, for in-kernel summaries. The sysdig developers are currently adding container support. Watch this space.
## Further Reading
My own work with the tracers includes:
**ftrace** : My [perf-tools][8] collection (see the examples directory); my lwn.net [article on ftrace][5]; a [LISA14][8] talk; and the posts: [function counting][23], [iosnoop][24], [opensnoop][25], [execsnoop][26], [TCP retransmits][27], [uprobes][28], and [USDT][29].
**perf_events** : My [perf_events Examples][6] page; a [Linux Profiling at Netflix][4] talk for SCALE; and the posts [CPU Sampling][30], [Static Tracepoints][31], [Heat Maps][32], [Counting][33], [Kernel Line Tracing][34], [off-CPU Time Flame Graphs][35].
**eBPF** : The post [eBPF: One Small Step][36], and some [BPF-tools][37] (I need to publish more).
**SystemTap** : I wrote a [Using SystemTap][38] post a long time ago, which is somewhat out of date. More recently I published some [systemtap-lwtools][39], showing how SystemTap can be used without kernel debuginfo.
**LTTng** : I've used it a little, but not enough yet to publish anything.
**ktap** : My [ktap Examples][40] page includes one-liners and scripts, although these were for an earlier version.
**dtrace4linux** : I included some examples in my [Systems Performance book][41], and I've developed some small fixes for things in the past, eg, [timestamps][42].
**OL DTrace** : As this is a straight port of DTrace, much of my earlier DTrace work should be relevant (too many links to list here; search on [my homepage][43]). I may develop some specific tools once this is more complete.
**sysdig** : I contributed the [fileslower][44] and [subsecond offset spectrogram][45] chisels.
**others** : I did write a warning post about [strace][46].
Please, no more tracers! ... If you're wondering why Linux doesn't just have one, or DTrace itself, I answered these in my [From DTrace to Linux][47] talk, starting on [slide 28][48].
Thanks to [Deirdre Straughan][49] for edits, and for creating the tracing ponies (with General Zoi's pony creator).
--------------------------------------------------------------------------------
via: http://www.brendangregg.com/blog/2015-07-08/choosing-a-linux-tracer.html
作者:[Brendan Gregg.][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.brendangregg.com
[1]:http://www.brendangregg.com/blog/images/2015/tracing_ponies.png
[2]:http://www.slideshare.net/brendangregg/velocity-2015-linux-perf-tools/105
[3]:http://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html
[4]:http://www.brendangregg.com/blog/2015-02-27/linux-profiling-at-netflix.html
[5]:http://lwn.net/Articles/608497/
[6]:http://www.brendangregg.com/perf.html
[7]:http://www.brendangregg.com/blog/2015-06-23/netflix-instance-analysis-requirements.html
[8]:http://www.brendangregg.com/blog/2015-03-17/linux-performance-analysis-perf-tools.html
[9]:http://techblog.netflix.com/2015/04/introducing-vector-netflixs-on-host.html
[10]:https://sourceware.org/git/?p=systemtap.git;a=blob_plain;f=README;hb=HEAD
[11]:http://www.slideshare.net/brendangregg/velocity-2015-linux-perf-tools
[12]:http://lwn.net/Articles/370423/
[13]:https://www.kernel.org/doc/Documentation/trace/ftrace.txt
[14]:https://perf.wiki.kernel.org/index.php/Main_Page
[15]:http://www.phoronix.com/scan.php?page=news_item&px=BPF-Understanding-Kernel-VM
[16]:https://github.com/torvalds/linux/tree/master/samples/bpf
[17]:https://sourceware.org/systemtap/wiki
[18]:http://lttng.org/
[19]:http://ktap.org/
[20]:https://github.com/dtrace4linux/linux
[21]:http://docs.oracle.com/cd/E37670_01/E38608/html/index.html
[22]:http://www.sysdig.org/
[23]:http://www.brendangregg.com/blog/2014-07-13/linux-ftrace-function-counting.html
[24]:http://www.brendangregg.com/blog/2014-07-16/iosnoop-for-linux.html
[25]:http://www.brendangregg.com/blog/2014-07-25/opensnoop-for-linux.html
[26]:http://www.brendangregg.com/blog/2014-07-28/execsnoop-for-linux.html
[27]:http://www.brendangregg.com/blog/2014-09-06/linux-ftrace-tcp-retransmit-tracing.html
[28]:http://www.brendangregg.com/blog/2015-06-28/linux-ftrace-uprobe.html
[29]:http://www.brendangregg.com/blog/2015-07-03/hacking-linux-usdt-ftrace.html
[30]:http://www.brendangregg.com/blog/2014-06-22/perf-cpu-sample.html
[31]:http://www.brendangregg.com/blog/2014-06-29/perf-static-tracepoints.html
[32]:http://www.brendangregg.com/blog/2014-07-01/perf-heat-maps.html
[33]:http://www.brendangregg.com/blog/2014-07-03/perf-counting.html
[34]:http://www.brendangregg.com/blog/2014-09-11/perf-kernel-line-tracing.html
[35]:http://www.brendangregg.com/blog/2015-02-26/linux-perf-off-cpu-flame-graph.html
[36]:http://www.brendangregg.com/blog/2015-05-15/ebpf-one-small-step.html
[37]:https://github.com/brendangregg/BPF-tools
[38]:http://dtrace.org/blogs/brendan/2011/10/15/using-systemtap/
[39]:https://github.com/brendangregg/systemtap-lwtools
[40]:http://www.brendangregg.com/ktap.html
[41]:http://www.brendangregg.com/sysperfbook.html
[42]:https://github.com/dtrace4linux/linux/issues/55
[43]:http://www.brendangregg.com
[44]:https://github.com/brendangregg/sysdig/commit/d0eeac1a32d6749dab24d1dc3fffb2ef0f9d7151
[45]:https://github.com/brendangregg/sysdig/commit/2f21604dce0b561407accb9dba869aa19c365952
[46]:http://www.brendangregg.com/blog/2014-05-11/strace-wow-much-syscall.html
[47]:http://www.brendangregg.com/blog/2015-02-28/from-dtrace-to-linux.html
[48]:http://www.slideshare.net/brendangregg/from-dtrace-to-linux/28
[49]:http://www.beginningwithi.com/

View File

@ -1,4 +1,5 @@
Make “rm” Command To Move The Files To “Trash Can” Instead Of Removing Them Completely
amwps290 translating
Make “rm” Command To Move The Files To “Trash Can” Instead Of Removing Them Completely
======
Human makes mistake because we are not a programmed devices so, take additional care while using `rm` command and don't use `rm -rf *` at any point of time. When you use rm command it will delete the files permanently and doesn't move those files to `Trash Can` like how file manger does.

View File

@ -1,3 +1,5 @@
translating by yizhuoyan
5 Tips to Improve Technical Writing for an International Audience
============================================================

View File

@ -1,128 +0,0 @@
10 things I love about Vue
============================================================
![](https://cdn-images-1.medium.com/max/1600/1*X4ipeKVYzmY2M3UPYgUYuA.png)
I love Vue. When I first looked at it in 2016, perhaps I was coming from a perspective of JavaScript framework fatigue. Id already had experience with Backbone, Angular, React, among others and I wasnt overly enthusiastic to try a new framework. It wasnt until I read a comment on hacker news describing Vue as the new jquery of JavaScript, that my curiosity was piqued. Until that point, I had been relatively content with Reactit is a good framework based on solid design principles centred around view templates, virtual DOM and reacting to state, and Vue also provides these great things. In this blog post, I aim to explore why Vue is the framework for me. I choose it above any other that I have tried. Perhaps you will agree with some of my points, but at the very least I hope to give you some insight into what it is like to develop modern JavaScript applications with Vue.
1\. Minimal Template Syntax
The template syntax which you are given by default from Vue is minimal, succinct and extendable. Like many parts of Vue, its easy to not use the standard template syntax and instead use something like JSX (there is even an official page of documentation about how to do this), but I dont know why you would want to do that to be honest. For all that is good about JSX, there are some valid criticisms: by blurring the line between JavaScript and HTML, it makes it a bit too easy to start writing complex code in your template which should instead be separated out and written elsewhere in your JavaScript view code.
Vue instead uses standard HTML to write your templates, with a minimal template syntax for simple things such as iteratively creating elements based on the view data.
```
<template>
<div id="app">
<ul>
<li v-for='number in numbers' :key='number'>{{ number }}</li>
</ul>
<form @submit.prevent='addNumber'>
<input type='text' v-model='newNumber'>
<button type='submit'>Add another number</button>
</form>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
addNumber() {
const num = +this.newNumber;
if (typeof num === 'number' && !isNaN(num)) {
this.numbers.push(num);
}
}
},
data() {
return {
newNumber: null,
numbers: [1, 23, 52, 46]
};
}
}
</script>
<style lang="scss">
ul {
padding: 0;
li {
list-style-type: none;
color: blue;
}
}
</style>
```
I also like the short-bindings provided by Vue, : for binding data variables into your template and @ for binding to events. Its a small thing, but it feels nice to type and keeps your components succinct.
2\. Single File Components
When most people write Vue, they do so using single file components. Essentially it is a file with the suffix .vue containing up to 3 parts (the css, html and javascript) for each component.
This coupling of technologies feels right. It makes it easy to understand each component in a single place. It also has the nice side effect of encouraging you to keep your code short for each component. If the JavaScript, CSS and HTML for your component is taking up too many lines then it might be time to modularise further.
When it comes to the <style> tag of a Vue component, we can add the scoped attribute. This will fully encapsulate the styling to this component. Meaning if we had a .name CSS selector defined in this component, it wont apply that style in any other component. I much prefer this approach of styling view components to the approaches of writing CSS in JS which seems popular in other leading frameworks.
Another very nice thing about single file components is that they are actually valid HTML5 files. <template>, <script>, <style> are all part of the official w3c specification. This means that many tools you use as part of your development process (such as linters) can work out of the box or with minimal adaptation.
3\. Vue as the new jQuery
Really these two libraries are not similar and are doing different things. Let me provide you with a terrible analogy that I am actually quite fond of to describe the relationship of Vue and jQuery: The Beatles and Led Zeppelin. The Beatles need no introduction, they were the biggest group of the 1960s and were supremely influential. It gets harder to pin the accolade of biggest group of the 1970s but sometimes that goes to Led Zeppelin. You could say that the musical relationship between the Beatles and Led Zeppelin is tenuous and their music is distinctively different, but there is some prior art and influence to accept. Maybe 2010s JavaScript world is like the 1970s music world and as Vue gets more radio plays, it will only attract more fans.
Some of the philosophy that made jQuery so great is also present in Vue: a really easy learning curve but with all the power you need to build great web applications based on modern web standards. At its core, Vue is really just a wrapper around JavaScript objects.
4\. Easily extensible
As mentioned, Vue uses standard HTML, JS and CSS to build its components as a default, but it is really easy to plug in other technologies. If we want to use pug instead of HTML or typescript instead of JS or sass instead of CSS, its just a matter of installing the relevant node modules and adding an attribute to the relevant section of our single file component. You could even mix and match components within a projecte.g. some components using HTML and others using pugalthough Im not sure doing this is the best practice.
5\. Virtual DOM
The virtual DOM is used in many frameworks these days and it is great. It means the framework can work out what has changed in our state and then efficiently apply DOM updates, minimizing re-rendering and optimising the performance of our application. Everyone and their mother has a Virtual DOM these days, so whilst its not something unique, its still very cool.
6\. Vuex is great
For most applications, managing state becomes a tricky issue which using a view library alone can not solve. Vues solution to this is the vuex library. Its easy to setup and integrates very well with vue. Those familiar with redux will be at home here, but I find that the integration between vue and vuex is neater and more minimal than that of react and redux. Soon-to-be-standard JavaScript provides the object spread operator which allows us to merge in state or functions to manipulate state from vuex into the components that need it.
7\. Vue CLI
The CLI provided by Vue is really great and makes it easy to get started with a webpack project with Vue. Single file components support, babel, linting, testing and a sensible project structure can all be created with a single command in your terminal.
There is one thing, however I miss from the CLI and that is the vue build.
```
try this: `echo '<template><h1>Hello World!</h1></template>' > Hello.vue && vue build Hello.vue -o`
```
It looked so simple to build and run components and test them in the browser. Unfortunately this command was later removed from vue, instead the recommendation is to now use poi. Poi is basically a wrapper around webpack, but I dont think it quite gets to the same point of simplicity as the quoted tweet.
8\. Re-rendering optimizations worked out for you
In Vue, you dont have to manually state which parts of the DOM should be re-rendered. I never was a fan of the management on react components, such as shouldComponentUpdate in order to stop the whole DOM tree re-rendering. Vue is smart about this.
9\. Easy to get help
Vue has reached a critical mass of developers using the framework to build a wide variety of applications. The documentation is very good. Should you need further help, there are multiple channels available with many active users: stackoverflow, discord, twitter etc.this should give you some more confidence in building an application over some other frameworks with less users.
10\. Not maintained by a single corporation
I think its a good thing for an open source library to not have the voting rights of its direction steered too much by a single corporation. Issues such as the react licensing issue (now resolved) are not something Vue has had to deal with.
In summary, I think Vue is an excellent choice for whatever JavaScript project you might be starting next. The available ecosystem is larger than I covered in this blog post. For a more full-stack offering you could look at Nuxt.js. And if you want some re-usable styled components you could look at something like Vuetify. Vue has been one of the fastest growing frameworks of 2017 and I predict the growth is not going to slow down for 2018\. If you have a spare 30 minutes, why not dip your toes in and see what Vue has to offer for yourself?
P.S.The documentation gives you a great comparison to other frameworks here: [https://vuejs.org/v2/guide/comparison.html][1]
--------------------------------------------------------------------------------
via: https://medium.com/@dalaidunc/10-things-i-love-about-vue-505886ddaff2
作者:[Duncan Grant ][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://medium.com/@dalaidunc
[1]:https://vuejs.org/v2/guide/comparison.html

View File

@ -0,0 +1,161 @@
The List Of Useful Bash Keyboard Shortcuts
======
![](https://www.ostechnix.com/wp-content/uploads/2018/02/Bash-720x340.jpg)
Nowadays, I spend more time in Terminal, trying to accomplish more in CLI than GUI. I learned many BASH tricks over time. And, here is the list of useful of BASH shortcuts that every Linux users should know to get things done faster in their BASH shell. I wont claim that this list is a complete list of BASH shortcuts, but just enough to move around your BASH shell faster than before. Learning how to navigate faster in BASH Shell not only saves some time, but also makes you proud of yourself for learning something worth. Well, lets get started.
### List Of Useful Bash Keyboard Shortcuts
#### ALT key shortcuts
1\. **ALT+A** Go to the beginning of a line.
2\. **ALT+B** Move one character before the cursor.
3\. **ALT+C** Suspends the running command/process. Same as CTRL+C
4\. **ALT+D** Closes the empty Terminal (I.e it closes the Terminal when there is nothing typed). Also deletes all chracters after the cursor.
5\. **ALT+F** Move forward one character.
6\. **ALT+T** Swaps the last two words.
7\. **ALT+U** Capitalize all characters in a word after the cursor.
8\. **ALT+L** Uncaptalize all characters in a word after the cursor.
9\. **ALT+R** Undo any changes to a command that you have brought from the history if youve edited it.
As you see in the above output, I have pulled a command using reverse search and changed the last characters in that command and revert the changes using **ALT+R**.
10\. **ALT+.** (note the dot at the end) Use the last word of the previous command.
If you want to use the same options for multiple commands, you can use this shortcut to bring back the last word of previous command. For instance, I need to short the contents of a directory using “ls -r” command. Also, I want to view my Kernel version using “uname -r”. In both commands, the common word is “-r”. This is where ALT+. shortcut comes in handy. First run, ls -r command to do reverse shorting and use the last word “-r” in the nex command i.e uname.
#### CTRL key shortcuts
1\. **CTRL+A** Quickly move to the beginning of line.
Let us say youre typing a command something like below. While youre at the Nth line, you noticed there is a typo in the first character
```
$ gind . -mtime -1 -type
```
Did you notice? I typed “gind” instead of “find” in the above command. You can correct this error by pressing the left arrow all the way to the first letter and replace “g” with “f”. Alternatively, just hit the **CTRL+A** or **Home** key to instantly go to the beginning of the line and replace the misspelled character. This will save you a few seconds.
2\. **CTRL+B** To move backward one character.
This shortcut key can move the cursor backward one character i.e one character before the cursor. Alternatively, you can use LEFT arrow to move backward one character.
3\. **CTRL+C** Stop the currently running command
If a command takes too long to complete or if you mistakenly run it, you can forcibly stop or quit the command by using **CTRL+C**.
4\. **CTRL+D** Delete one character backward.
If you have a system where the BACKSPACE key isnt working, you can use **CTRL+D** to delete one character backward. This shortcut also lets you logs out of the current session, similar to exit.
5\. **CTRL+E** Move to the end of line
After you corrected any misspelled word in the start of a command or line, just hit **CTRL+E** to quickly move to the end of the line. Alternatively, you can use END key in your keyboard.
6\. **CTRL+F** Move forward one character
If you want to move the cursor forward one character after another, just press **CTRL+F** instead of RIGHT arrow key.
7\. **CTRL+G** Leave the history searching mode without running the command.
As you see in the above screenshot, I did the reverse search, but didnt execute the command and left the history searching mode.
8\. **CTRL+H** Delete the characters before the cursor, same as BASKSPACE.
9\. **CTRL+J** Same as ENTER/RETURN key.
ENTER key is not working? No problem! **CTRL+J** or **CTRL+M** can be used as an alternative to ENTER key.
10\. **CTRL+K** Delete all characters after the cursor.
You dont have to keep hitting the DELETE key to delete the characters after the cursor. Just press **CTRL+K** to delete all characters after the cursor.
11\. **CTRL+L** Clears the screen and redisplay the line.
Dont type “clear” to clear the screen. Just press CTRL+L to clear and redisplay the currently typed line.
12\. **CTRL+M** Same as CTRL+J or RETURN.
13\. **CTRL+N** Display next line in command history.
You can also use DOWN arrow.
14\. **CTRL+O** Run the command that you found using reverse search i.e CTRL+R.
15\. **CTRL+P** Displays the previous line in command history.
You can also use UP arrow.
16\. **CTRL+R** Searches the history backward (Reverse search).
17\. **CTRL+S** Searches the history forward.
18\. **CTRL+T** Swaps the last two characters.
This is one of my favorite shortcut. Let us say you typed “sl” instead of “ls”. No problem! This shortcut will transposes the characters as in the below screenshot.
![][2]
19\. **CTRL+U** Delete all characters before the cursor (Kills backward from point to the beginning of line).
This shortcut will delete all typed characters backward at once.
20\. **CTRL+V** Makes the next character typed verbatim
21\. **CTRL+W** Delete the words before the cursor.
Dont confuse it with CTRL+U. CTRL+W wont delete everything behind a cursor, but a single word.
![][3]
22\. **CTRL+X** Lists the possible filename completions of the current word.
23\. **CTRL+XX** Move between start of command line and current cursor position (and back again).
24\. **CTRL+Y** Retrieves last item that you deleted or cut.
Remember, we deleted a word “-al” using CTRL+W in the 21st command. You can retrieve that word instantly using CTRL+Y.
![][4]
See? I didnt type “-al”. Instead, I pressed CTRL+Y to retrieve it.
25\. **CTRL+Z** Stops the current command.
You may very well know this shortcut. It kills the currently running command. You can resume it with **fg** in the foreground or **bg** in the background.
26\. **CTRL+[** Equivalent to ESC key.
#### Miscellaneous
1\. **!!** Repeats the last command.
2\. **ESC+t** Swaps the last tow words.
Thats all I have in mind now. I will keep adding more if I came across any Bash shortcut keys in future. If you think there is a mistake in this article, please do notify me in the comments section below. I will update it asap.
Cheers!
--------------------------------------------------------------------------------
via: https://www.ostechnix.com/list-useful-bash-keyboard-shortcuts/
作者:[SK][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.ostechnix.com/author/sk/
[2]:http://www.ostechnix.com/wp-content/uploads/2018/02/CTRLT-1.gif
[3]:http://www.ostechnix.com/wp-content/uploads/2018/02/CTRLW-1.gif
[4]:http://www.ostechnix.com/wp-content/uploads/2018/02/CTRLY-1.gif

View File

@ -1,3 +1,5 @@
translated by cyleft
How to Get Started Using WSL in Windows 10
======

View File

@ -0,0 +1,217 @@
How to enable repository using subscription-manager in RHEL
======
Learn how to enable repository using subscription-manager in RHEL. Article also includes steps to register system with Red Hat, attach subscription and errors along with resolutions.
![Enable repository using subscription-manager][1]
In this article we will walk you through step by step process to enable Red Hat repository in RHEL fresh installed server.
Repository can be enabled using `subscription-manager` command like below
```
root@kerneltalks # subscription-manager repos --enable rhel-6-server-rhv-4-agent-beta-debug-rpms
Error: 'rhel-6-server-rhv-4-agent-beta-debug-rpms' does not match a valid repository ID. Use "subscription-manager repos --list" to see valid repositories.
```
You will see above error when your subscription is not in place. Lets go through step by step procedure to enable repositories via `subscription-manager`
##### Step 1 : Register your system with Red Hat
We are considering you have freshly installed system and its not yet registered with Red Hat. If you have registered system already then you can ignore this step.
You can check if your system is registered with Red Hat for subscription using below command
```
# subscription-manager version
server type: This system is currently not registered.
subscription management server: Unknown
subscription management rules: Unknown
subscription-manager: 1.18.10-1.el6
python-rhsm: 1.18.6-1.el6
```
Here, in first line of output you can see system is not registered. So, lets start with registering system. You need to use `subscription-manager` command with `register` switch. You need to use your Red Hat account credentials here.
```
root@kerneltalks # subscription-manager register
Registering to: subscription.rhsm.redhat.com:443/subscription
Username: admin@kerneltalks.com
Password:
Network error, unable to connect to server. Please see /var/log/rhsm/rhsm.log for more information.
```
If you are getting above error then your server is not able to reach RedHat. Check internet connection & if you are able to [resolve site name][2]s. Sometimes even if you are able to ping subscription server, you will see this error. This might be because of you have proxy server in your environment. In such case, you need to add its details in file `/etc/rhsm/rhsm.conf`. Below proxy details should be populated :
```
# an http proxy server to use
proxy_hostname =
# port for http proxy server
proxy_port =
# user name for authenticating to an http proxy, if needed
proxy_user =
# password for basic http proxy auth, if needed
proxy_password =
```
Once you are done, recheck if `subscription-manager` taken up new proxy details by using below command
```
root@kerneltalks # subscription-manager config
[server]
hostname = [subscription.rhsm.redhat.com]
insecure = [0]
port = [443]
prefix = [/subscription]
proxy_hostname = [kerneltalksproxy.abc.com]
proxy_password = [asdf]
proxy_port = [3456]
proxy_user = [user2]
server_timeout = [180]
ssl_verify_depth = [3]
[rhsm]
baseurl = [https://cdn.redhat.com]
ca_cert_dir = [/etc/rhsm/ca/]
consumercertdir = [/etc/pki/consumer]
entitlementcertdir = [/etc/pki/entitlement]
full_refresh_on_yum = [0]
manage_repos = [1]
pluginconfdir = [/etc/rhsm/pluginconf.d]
plugindir = [/usr/share/rhsm-plugins]
productcertdir = [/etc/pki/product]
repo_ca_cert = /etc/rhsm/ca/redhat-uep.pem
report_package_profile = [1]
[rhsmcertd]
autoattachinterval = [1440]
certcheckinterval = [240]
[logging]
default_log_level = [INFO]
[] - Default value in use
```
Now, try registering your system again.
```
root@kerneltalks # subscription-manager register
Registering to: subscription.rhsm.redhat.com:443/subscription
Username: admin@kerneltalks.com
Password:
You must first accept Red Hat's Terms and conditions. Please visit https://www.redhat.com/wapps/tnc/termsack?event[]=signIn . You may have to log out of and back into the Customer Portal in order to see the terms.
```
You will see above error if you are adding server to your Red Hat account for the first time. Go to the [URL ][3]and accept the terms. Come back to terminal and try again.
```
oot@kerneltalks # subscription-manager register
Registering to: subscription.rhsm.redhat.com:443/subscription
Username: admin@kerneltalks.com
Password:
The system has been registered with ID: xxxxb2-xxxx-xxxx-xxxx-xx8e199xxx
```
Bingo! System is registered with Red Hat now. You can again verify it with `version` switch.
```
#subscription-managerversionservertype:RedHatSubscriptionManagementsubscriptionmanagementserver:2.0.43-1subscriptionmanagementrules:5.26subscription-manager:1.18.10-1.el6python-rhsm:1.18.6-1.el6" decode="true" ]root@kerneltalks # subscription-manager version
server type: Red Hat Subscription Management
subscription management server: 2.0.43-1
subscription management rules: 5.26
subscription-manager: 1.18.10-1.el6
python-rhsm: 1.18.6-1.el6
```
##### Step 2 : Attach subscription to your server
First try to list repositories. You wont be able to list any since we havent attached any subscription to our server yet.
```
root@kerneltalks # subscription-manager repos --list
This system has no repositories available through subscriptions.
```
As you can see `subscription-manager` couldnt found any repositories, you need to attach subscriptions to your server. Once subscription is attached, `subscription-manager` will be able to list repositories under it.
To attach subscription, first check all available subscriptions for your server with below command
```
root@kerneltalks # subscription-manager list --available
+-------------------------------------------+
Available Subscriptions
+-------------------------------------------+
Subscription Name: Red Hat Enterprise Linux for Virtual Datacenters, Standard
Provides: Red Hat Beta
Red Hat Software Collections (for RHEL Server)
Red Hat Enterprise Linux Atomic Host Beta
Oracle Java (for RHEL Server)
Red Hat Enterprise Linux Server
dotNET on RHEL (for RHEL Server)
Red Hat Enterprise Linux Atomic Host
Red Hat Software Collections Beta (for RHEL Server)
Red Hat Developer Tools Beta (for RHEL Server)
Red Hat Developer Toolset (for RHEL Server)
Red Hat Developer Tools (for RHEL Server)
SKU: RH00050
Contract: xxxxxxxx
Pool ID: 8a85f98c6011059f0160110a2ae6000f
Provides Management: Yes
Available: Unlimited
Suggested: 0
Service Level: Standard
Service Type: L1-L3
Subscription Type: Stackable (Temporary)
Ends: 12/01/2018
System Type: Virtual
```
You will get list of such subscriptions available for your server. You need to read through what it provides and note down `Pool ID` of subscriptions which are useful/required for you.
Now, attach subscriptions to your server by using pool ID.
```
# subscription-manager attach --pool=8a85f98c6011059f0160110a2ae6000f
Successfully attached a subscription for: Red Hat Enterprise Linux for Virtual Datacenters, Standard
```
If you are not sure which one to pick, you can simple attach subscriptions automatically which are best suited for your server with below command
```
root@kerneltalks # subscription-manager attach --auto
Installed Product Current Status:
Product Name: Red Hat Enterprise Linux Server
Status: Subscribed
```
Move on to final step to enable repository.
##### Step 3 : Enable repository
Now you will be enable repository which is available under your attached subscription.
```
root@kerneltalks # subscription-manager repos --enable rhel-6-server-rhv-4-agent-beta-debug-rpms
Repository 'rhel-6-server-rhv-4-agent-beta-debug-rpms' is enabled for this system.
```
Thats it. You are done. You can [list repositories with yum command][4] and confirm.
--------------------------------------------------------------------------------
via: https://kerneltalks.com/howto/how-to-enable-repository-using-subscription-manager-in-rhel/
作者:[kerneltalks][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://kerneltalks.com
[1]:https://a2.kerneltalks.com/wp-content/uploads/2018/02/enable-repository-in-rhel.png
[2]:https://kerneltalks.com/howto/how-to-configure-nameserver-in-linux/
[3]:https://www.redhat.com/wapps/tnc/termsack?event%5B%5D=signIn
[4]:https://kerneltalks.com/howto/how-to-list-yum-repositories-in-rhel-centos/

View File

@ -0,0 +1,265 @@
How to format academic papers on Linux with groff -me
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/life_paperclips.png?itok=j48op49T)
I was an undergraduate student when I discovered Linux in 1993. I was so excited to have the power of a Unix system right in my dorm room, but despite its many capabilities, Linux lacked applications. Word processors like LibreOffice and OpenOffice were years away. If you wanted to use a word processor, you likely booted your system into MS-DOS and used WordPerfect, the shareware GalaxyWrite, or a similar program.
`nroff` and `troff`. They are different interfaces to the same system: `nroff` generates plaintext output, suitable for screens or line printers, and `troff` generates very pretty output, usually for printing on a laser printer.
That was my method, since I needed to write papers for my classes, but I preferred staying in Linux. I knew from our "big Unix" campus computer lab that Unix systems provided a set of text-formatting programs calledand. They are different interfaces to the same system:generates plaintext output, suitable for screens or line printers, andgenerates very pretty output, usually for printing on a laser printer.
On Linux, `nroff` and `troff` are combined as GNU troff, more commonly known as [groff][1]. I was happy to see a version of groff included in my early Linux distribution, so I set out to learn how to use it to write class papers. The first macro set I learned was the `-me` macro package, a straightforward, easy to learn macro set.
The first thing to know about `groff` is that it processes and formats text according to a set of macros. A macro is usually a two-character command, set on a line by itself, with a leading dot. A macro might carry one or more options. When `groff` encounters one of these macros while processing a document, it will automatically format the text appropriately.
Below, I'll share the basics of using `groff -me` to write simple documents like class papers. I won't go deep into the details, like how to create nested lists, keeps and displays, tables, and figures.
### Paragraphs
Let's start with an easy example you see in almost every type of document: paragraphs. Paragraphs can be formatted with the first line either indented or not (i.e., flush against the left margin). Many printed documents, including academic papers, magazines, journals, and books, use a combination of the two types, with the first (leading) paragraph in a document or chapter flush left and all other (regular) paragraphs indented. In `groff -me`, you can use both paragraph types: leading paragraphs (`.lp`) and regular paragraphs (`.pp`).
```
.lp
This is the first paragraph.
.pp
This is a standard paragraph.
```
### Text formatting
The macro to format text in bold is `.b` and to format in italics is `.i`. If you put `.b` or `.i` on a line by itself, then all text that comes after it will be in bold or italics. But it's more likely you just want to put one or a few words in bold or italics. To make one word bold or italics, put that word on the same line as `.b` or `.i`, as an option. To format multiple words in **bold** or italics, enclose your text in quotes.
```
.pp
You can do basic formatting such as
.i italics
or
.b "bold text."
```
In the above example, the period at the end of **bold text** will also be in bold type. In most cases, that's not what you want. It's more correct to only have the words **bold text** in bold, but not the trailing period. To get the effect you want, you can add a second argument to `.b` or `.i` to indicate any text that should trail the bolded or italicized text, but in normal type. For example, you might do this to ensure that the trailing period doesn't show up in bold type.
```
.pp
You can do basic formatting such as
.i italics
or
.b "bold text" .
```
### Lists
With `groff -me`, you can create two types of lists: bullet lists (`.bu`) and numbered lists (`.np`).
```
.pp
Bullet lists are easy to make:
.bu
Apple
.bu
Banana
.bu
Pineapple
.pp
Numbered lists are as easy as:
.np
One
.np
Two
.np
Three
.pp
Note that numbered lists will reset at the next pp or lp.
```
### Subheads
If you're writing a long paper, you might want to divide your content into sections. With `groff -me`, you can create numbered headings (`.sh`) and unnumbered headings (`.uh`). In either, enclose the section title in quotes as an argument. For numbered headings, you also need to provide the heading level: `1` will give a first-level heading (e.g., 1.). Similarly, `2` and `3` will give second and third level headings, such as 2.1 or 3.1.1.
```
.uh Introduction
.pp
Provide one or two paragraphs to describe the work
and why it is important.
.sh 1 "Method and Tools"
.pp
Provide a few paragraphs to describe how you
did the research, including what equipment you used
```
### Smart quotes and block quotes
It's standard in any academic paper to cite other people's work as evidence. If you're citing a brief quote to highlight a key message, you can just type quotes around your text. But groff won't automatically convert your quotes into the "smart" or "curly" quotes used by modern word processing systems. To create them in `groff -me`, insert an inline macro to create the left quote (`\*(lq`) and right quote mark (`\*(rq`).
```
.pp
Christine Peterson coined the phrase \*(lqopen source.\*(rq
```
There's also a shortcut in `groff -me` to create these quotes (`.q`) that I find easier to use.
```
.pp
Christine Peterson coined the phrase
.q "open source."
```
If you're citing a longer quote that spans several lines, you'll want to use a block quote. To do this, insert the blockquote macro (`.(q`) at the beginning and end of the quote.
```
.pp
Christine Peterson recently wrote about open source:
.(q
On April 7, 1998, Tim O'Reilly held a meeting of key
leaders in the field. Announced in advance as the first
.q "Freeware Summit,"
by April 14 it was referred to as the first
.q "Open Source Summit."
.)q
```
### Footnotes
To insert a footnote, include the footnote macro (`.(f`) before and after the footnote text, and use an inline macro (`\**`) to add the footnote mark. The footnote mark should appear both in the text and in the footnote itself.
```
.pp
Christine Peterson recently wrote about open source:\**
.(f
\**Christine Peterson.
.q "How I coined the term open source."
.i "OpenSource.com."
1 Feb 2018.
.)f
.(q
On April 7, 1998, Tim O'Reilly held a meeting of key
leaders in the field. Announced in advance as the first
.q "Freeware Summit,"
by April 14 it was referred to as the first
.q "Open Source Summit."
.)q
```
### Cover page
Most class papers require a cover page containing the paper's title, your name, and the date. Creating a cover page in `groff -me` requires some assembly. I find the easiest way is to use centered blocks of text and add extra lines between the title, name, and date. (I prefer to use two blank lines between each.) At the top of your paper, start with the title page (`.tp`) macro, insert five blank lines (`.sp 5` ), then add the centered text (`.(c`), and extra blank lines (`.sp 2`).
```
.tp
.sp 5
.(c
.b "Writing Class Papers with groff -me"
.)c
.sp 2
.(c
Jim Hall
.)c
.sp 2
.(c
February XX, 2018
.)c
.bp
```
The last macro (`.bp`) tells groff to add a page break after the title page.
### Learning more
Those are the essentials of writing professional-looking a paper in `groff -me` with leading and indented paragraphs, bold and italics text, bullet and numbered lists, numbered and unnumbered section headings, block quotes, and footnotes.
I've included a sample groff file to demonstrate all of this formatting. Save the `lorem-ipsum.me` file to your system and run it through groff. The `-Tps` option sets the output type to PostScript so you can send the document to a printer or convert it to a PDF file using the `ps2pdf` program.
```
groff -Tps -me lorem-ipsum.me > lorem-ipsum.me.ps
ps2pdf lorem-ipsum.me.ps lorem-ipsum.me.pdf
```
If you'd like to use more advanced functions in `groff -me`, refer to Eric Allman's "Writing Papers with Groff using `me`," which you should find on your system as `meintro.me` in groff's `doc` directory. It's a great reference document that explains other ways to format papers using the `groff -me` macros.
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/2/how-format-academic-papers-linux-groff-me
作者:[Jim Hall][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/jim-hall
[1]:https://www.gnu.org/software/groff/

View File

@ -1,324 +0,0 @@
通过ncurses在终端创建一个冒险游戏
======
怎样使用curses函数读取键盘并操作屏幕。
我[之前的文章][1]介绍了ncurses库并提供了一个简单的程序展示一些将文本放到屏幕上的一些curses函数。
### 探险
当我逐渐长大家里有了一台苹果2电脑。我和我兄弟正是在这台电脑上自学了如何用AppleSoft BASIC写程序。我在写了一些数学智力游戏之后继续创造游戏。作为80年代的人我已经是龙与地下城桌游的粉丝在游戏中角色扮演一个追求打败怪物并在陌生土地上抢掠的战士或者男巫。所以我创建一个基本的冒险游戏也在情理之中。
AppleSoft BASIC支持一种简洁的特性在标准分辨率图形模式(GR模式)下你可以检测屏幕上特定点的颜色。这为创建一个冒险游戏提供了捷径。比起创建并更新周期性传送到屏幕的内存地图我现在可以依赖GR模式为我维护地图我的程序还可以当玩家字符在屏幕四处移动的时候查询屏幕。通过这种方式我让电脑完成了大部分艰难的工作。因此我的自顶向下的冒险游戏使用了块状的GR模式图形来展示我的游戏地图。
我的冒险游戏使用了一张简单的地图,上面有一大片绿地伴着山脉从中间蔓延向下和一个在左上方的大湖。我要粗略地为桌游战役绘制这个地图,其中包含一个允许玩家穿过到远处的狭窄通道。
![](http://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1000009/quest-map.jpg)
图1.一个有湖和山的简单桌游地图
你可以用curses绘制这个地图并用字符代表草地、山脉和水。接下来我描述怎样使用curses那样做以及如何在Linux终端创建和进行类似的一个冒险游戏
### 构建程序
在我的上一篇文章我提到了大多数curses程序以相同的一组指令获取终端类型和设置curses环境:
```
initscr();
cbreak();
noecho();
```
在这个程序,我添加了另外的语句:
```
keypad(stdscr, TRUE);
```
这里的TRUE标志允许curses从用户终端读取小键盘和功能键。如果你想要在你的程序中使用上下左右方向键你需要使用这里的keypad(stdscr, TRUE)。
这样做了之后你可以你可以开始在终端屏幕上绘图了。curses函数包括了一系列方法在屏幕上绘制文本。在我之前的文章中我展示了addch()和addstr()函数以及他们对应的在添加文本之前先移动到指定屏幕位置的副本mvaddch()和mvaddstr()函数。为了创建这个冒险游戏,你可以使用另外一组函数:vline()和hline()以及它们对应的函数mvvline()和mvhline()。这些mv函数接收屏幕坐标一个要绘制的字符和要重复此字符的次数。例如mvhline(1, 2, '-', 20)将会绘制一条开始于第一行第二列并由20个横线组成的线段。
为了以编程方式绘制地图到终端让我们先定义这个draw_map()函数:
```
#define GRASS ' '
#define EMPTY '.'
#define WATER '~'
#define MOUNTAIN '^'
#define PLAYER '*'
void draw_map(void)
{
int y, x;
/* 绘制探索地图 */
/* 背景 */
for (y = 0; y < LINES; y++) {
mvhline(y, 0, GRASS, COLS);
}
/* 山和山道 */
for (x = COLS / 2; x < COLS * 3 / 4; x++) {
mvvline(0, x, MOUNTAIN, LINES);
}
mvhline(LINES / 4, 0, GRASS, COLS);
/* 湖 */
for (y = 1; y < LINES / 2; y++) {
mvhline(y, 1, WATER, COLS / 3);
}
}
```
在绘制这副地图时记住填充大块字符到屏幕使用的mvvline()和mvhline()函数。我绘制从0列开始的字符水平线(mvhline)以创建草地区域直到整个屏幕的高度和宽度。我绘制从0行开始的多条垂直线(mvvline)在此上添加了山脉,绘制单行水平线添加了一条山道(mvhline)。并且,我通过绘制一系列短水平线(mvhline)创建了湖。这种绘制重叠方块的方式看起来似乎并没有效率但是记住在我们调用refresh()函数之前curses并不会真正更新屏幕。
绘制完地图,创建游戏就还剩下进入循环让程序等待用户按下上下左右方向键中的一个然后让玩家图标正确移动了。如果玩家想要移动的地方是空的,就应该允许玩家到那里。
你可以把curses当做捷径使用。比起在程序中实例化一个版本的地图并复制到屏幕(这么复杂)你可以让屏幕为你跟踪所有东西。inch()函数和相关联的mvinch()函数允许你探测屏幕的内容。这让你可以查询curses以了解玩家想要移动到的位置是否被水填满或者被山阻挡。这样做你需要一个之后会用到的一个帮助函数:
```
int is_move_okay(int y, int x)
{
int testch;
/* 如果要进入的位置可以进入返回true */
testch = mvinch(y, x);
return ((testch == GRASS) || (testch == EMPTY));
}
```
如你所见这个函数探测行x、列y并在空间未被占据的时候返回true否则返回false。
这样我们写移动循环就很容易了:从键盘获取一个键值然后根据是上下左右键移动用户字符。这里是一个简单版本的这种循环:
```
do {
ch = getch();
/* 测试输入的值并获取方向 */
switch (ch) {
case KEY_UP:
if ((y > 0) && is_move_okay(y - 1, x)) {
y = y - 1;
}
break;
case KEY_DOWN:
if ((y < LINES - 1) && is_move_okay(y + 1, x)) {
y = y + 1;
}
break;
case KEY_LEFT:
if ((x > 0) && is_move_okay(y, x - 1)) {
x = x - 1;
}
break;
case KEY_RIGHT
if ((x < COLS - 1) && is_move_okay(y, x + 1)) {
x = x + 1;
}
break;
}
}
while (1);
```
为了在游戏中使用(这个循环),你需要在循环里添加一些代码来启用其它的键(例如传统的移动键WASD)以提供方法供用户退出游戏和在屏幕上四处移动。这里是完整的程序:
```
/* quest.c */
#include
#include
#define GRASS ' '
#define EMPTY '.'
#define WATER '~'
#define MOUNTAIN '^'
#define PLAYER '*'
int is_move_okay(int y, int x);
void draw_map(void);
int main(void)
{
int y, x;
int ch;
/* 初始化curses */
initscr();
keypad(stdscr, TRUE);
cbreak();
noecho();
clear();
/* 初始化探索地图 */
draw_map();
/* 在左下角初始化玩家 */
y = LINES - 1;
x = 0;
do {
/* 默认获得一个闪烁的光标--表示玩家字符 */
mvaddch(y, x, PLAYER);
move(y, x);
refresh();
ch = getch();
/* 测试输入的键并获取方向 */
switch (ch) {
case KEY_UP:
case 'w':
case 'W':
if ((y > 0) && is_move_okay(y - 1, x)) {
mvaddch(y, x, EMPTY);
y = y - 1;
}
break;
case KEY_DOWN:
case 's':
case 'S':
if ((y < LINES - 1) && is_move_okay(y + 1, x)) {
mvaddch(y, x, EMPTY);
y = y + 1;
}
break;
case KEY_LEFT:
case 'a':
case 'A':
if ((x > 0) && is_move_okay(y, x - 1)) {
mvaddch(y, x, EMPTY);
x = x - 1;
}
break;
case KEY_RIGHT:
case 'd':
case 'D':
if ((x < COLS - 1) && is_move_okay(y, x + 1)) {
mvaddch(y, x, EMPTY);
x = x + 1;
}
break;
}
}
while ((ch != 'q') && (ch != 'Q'));
endwin();
exit(0);
}
int is_move_okay(int y, int x)
{
int testch;
/* 当空间可以进入时返回true */
testch = mvinch(y, x);
return ((testch == GRASS) || (testch == EMPTY));
}
void draw_map(void)
{
int y, x;
/* 绘制探索地图 */
/* 背景 */
for (y = 0; y < LINES; y++) {
mvhline(y, 0, GRASS, COLS);
}
/* 山脉和山道 */
for (x = COLS / 2; x < COLS * 3 / 4; x++) {
mvvline(0, x, MOUNTAIN, LINES);
}
mvhline(LINES / 4, 0, GRASS, COLS);
/* 湖 */
for (y = 1; y < LINES / 2; y++) {
mvhline(y, 1, WATER, COLS / 3);
}
}
```
在完整的程序清单中你可以看见使用curses函数创建游戏的完整布置:
1) 初始化curses环境。
2) 绘制地图。
3) 初始化玩家坐标(左下角)
4) 循环:
* 绘制玩家字符。
* 从键盘获取键值。
* 对应地上下左右调整玩家坐标。
* 重复。
5) 完成时关闭curses环境并退出。
### 开始玩
当你运行游戏时,玩家的字符在左下角初始化。当玩家在游戏区域四处移动的时候,程序创建了“一串”点。这样可以展示玩家经过了的点,让玩家避免经过不必要的路径。
![](http://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1000009/quest-start.png)
图2\. 初始化在左下角的玩家
![](http://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1000009/quest-1.png)
图3\. 玩家可以在游戏区域四处移动,例如湖周围和山的通道
为了创建上面这样的完整冒险游戏,你可能需要在他/她的字符在游戏区域四处移动的时候随机创建不同的怪物。你也可以创建玩家可以发现在打败敌人后可以掠夺的特殊道具,这些道具应能提高玩家的能力。
但是作为起点这是一个展示如何使用curses函数读取键盘和操纵屏幕的好程序。
### 下一步
这是一个如何使用curses函数更新和读取屏幕和键盘的简单例子。按照你的程序需要做什么curses可以做得更多。在下一篇文章中我计划展示如何更新这个简单程序以使用颜色。同时如果你想要学习更多curses我鼓励你去读位于Linux文档计划的Pradeep Padala之[如何使用NCURSES编程][2]。
--------------------------------------------------------------------------------
via: http://www.linuxjournal.com/content/creating-adventure-game-terminal-ncurses
作者:[Jim Hall][a]
译者:[Leemeans](https://github.com/leemeans)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.linuxjournal.com/users/jim-hall
[1]:http://www.linuxjournal.com/content/getting-started-ncurses
[2]:http://tldp.org/HOWTO/NCURSES-Programming-HOWTO

View File

@ -1,81 +0,0 @@
如何使用 lftp 来加速 Linux/UNIX 上的 ftp/https 下载速度
======
lftp 是一个文件传输程序。它可以用复杂的 FTP, HTTP/HTTPS 和其他连接。如果指定了站点 URL那么 lftp 将连接到该站点,否则会使用 open 命令建立连接。它是所有 Linux/Unix 命令行用户的必备工具。我目前写了一些关于[ Linux 下超快命令行下载加速器][1],比如 Axel 和 prozilla。lftp 是另一个能做相同的事但有更多功能的工具。lftp 可以处理七种文件访问方式:
1. ftp
2. ftps
3. http
4. https
5. hftp
6. fish
7. sftp
8. file
### 那么 lftp 的独特之处是什么?
* lftp 中的每个操作都是可靠的,即任何非致命错误都被忽略,并且重复操作。所以如果下载中断,它会自动重新启动。即使 FTP 服务器不支持 REST 命令lftp 也会尝试从开头检索文件,直到文件传输完成。
  * lftp 具有类似 shell 的命令语法,允许你在后台并行启动多个命令。
  * lftp 有一个内置镜像可以下载或更新整个目录树。还有一个反向镜像mittor -R它可以上传或更新服务器上的目录树。镜像也可以在两个远程服务器之间同步目录如果可用的话会使用 FXP。
### 如何使用 lftp 作为下载加速器
lftp 有 pget 命令。它能让你并行下载。语法是:
`lftp -e 'pget -n NUM -c url; exit'`
例如,使用 pget 分 5个部分下载 <http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.22.2.tar.bz2>
```
$ cd /tmp
$ lftp -e 'pget -n 5 -c http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.22.2.tar.bz2'
```
示例输出:
```
45108964 bytes transferred in 57 seconds (775.3K/s)
lftp :~>quit
```
这里:
1. pget - 并行下载文件
  2. -n 5 - 将最大连接数设置为 5
  3. -c - 如果当前目录存在 lfile.lftp-pget-status则继续中断的传输
### 如何在 Linux/Unix 中使用 lftp 来加速 ftp/https下载
再尝试添加退出命令:
`$ lftp -e 'pget -n 10 -c https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.15.tar.xz; exit'`
[Linux-lftp-command-demo][https://www.cyberciti.biz/tips/wp-content/uploads/2007/08/Linux-lftp-command-demo.mp4]
### 关于并行下载的说明
请注意通过使用下载加速器你将增加远程服务器负载。另请注意lftp 可能无法在不支持多点下载的站点上工作,或者防火墙阻止了此类请求。
NA 命令提供了许多其他功能。有关更多信息,请参考 [lftp][2] 的 man 页面:
`man lftp`
### 关于作者
作者是 nixCraft 的创建者,经验丰富的系统管理员,也是 Linux 操作系统/Unix shell 脚本的培训师。他曾与全球客户以及IT、教育、国防和太空研究以及非营利部门等多个行业合作。在 [Twitter][9]、[Facebook][10]、[Google +][11] 上关注他。通过[我的 RSS/XML 订阅][5]获取**最新的系统管理、Linux/Unix 以及开源主题教程**。
--------------------------------------------------------------------------------
via: https://www.cyberciti.biz/tips/linux-unix-download-accelerator.html
作者:[Vivek Gite][a]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.cyberciti.biz
[1]:https://www.cyberciti.biz/tips/download-accelerator-for-linux-command-line-tools.html
[2]:https://lftp.yar.ru/
[3]:https://twitter.com/nixcraft
[4]:https://facebook.com/nixcraft
[5]:https://plus.google.com/+CybercitiBiz
[6]:https://www.cyberciti.biz/atom/atom.xml

View File

@ -0,0 +1,476 @@
Translated by shipsw
20 个 OpenSSH 安全实践
======
![OpenSSH 安全提示][1]
OpenSSH 是 SSH 协议的一个实现。一般被 scp 或 sftp 用在远程登录、备份、远程文件传输等功能上。SSH能够完美保障两个网络或系统间数据传输的保密性和完整性。尽管如此他主要用在使用公匙加密的服务器验证上。不时出现关于 OpenSSH 零日漏洞的[谣言][2]。本文描述**如何设置你的 Linux 或类 Unix 系统以提高 sshd 的安全性**。
#### OpenSSH 默认设置
* TCP 端口 - 22
* OpenSSH 服务配置文件 - sshd_config (位于 /etc/ssh/)
#### 1. 基于公匙的登录
OpenSSH 服务支持各种验证方式。推荐使用公匙加密验证。首先,使用以下 ssh-keygen 命令在本地电脑上创建密匙对:
低于 1024 位的 DSA 和 RSA 加密是很弱的请不要使用。RSA 密匙主要是在考虑 ssh 客户端兼容性的时候代替 ECDSA 密匙使用的。
```
$ ssh-keygen -t key_type -b bits -C "comment"
$ ssh-keygen -t ed25519 -C "Login to production cluster at xyz corp"
$ ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_aws_$(date +%Y-%m-%d) -C "AWS key for abc corp clients"
```
下一步,使用 ssh-copy-id 命令安装公匙:
```
$ ssh-copy-id -i /path/to/public-key-file user@host
$ ssh-copy-id user@remote-server-ip-or-dns-name
$ ssh-copy-id vivek@rhel7-aws-server
```
提示输入用户名和密码的时候,使用你自己的 ssh 公匙:
`$ ssh vivek@rhel7-aws-server`
[![OpenSSH 服务安全最佳实践][3]][3]
更多有关 ssh 公匙的信息,参照以下文章:
* [为备份脚本设置无密码安全登录][48]
* [sshpass: 使用脚本密码登录SSH服务器][49]
* [如何为一个 Linux/类Unix 系统设置 SSH 登录密匙][50]
* [如何使用 Ansible 工具上传 ssh 登录授权公匙][51]
#### 2. 禁用 root 用户登录
禁用 root 用户登录前,确认普通用户可以以 root 身份登录。例如,允许用户 vivek 使用 sudo 命令以 root 身份登录。
##### 在 Debian/Ubuntu 系统中如何将用户 vivek 添加到 sudo 组中
允许 sudo 组中的用户执行任何命令。 [将用户 vivek 添加到 sudo 组中][4]:
`$ sudo adduser vivek sudo`
使用 [id 命令][5] 验证用户组。
`$ id vivek`
##### 在 CentOS/RHEL 系统中如何将用户 vivek 添加到 sudo 组中
在 CentOS/RHEL 和 Fedora 系统中允许 wheel 组中的用户执行所有的命令。使用 uermod 命令将用户 vivek 添加到 wheel 组中:
```
$ sudo usermod -aG wheel vivek
$ id vivek
```
##### 测试 sudo 权限并禁用 ssh root 登录
测试并确保用户 vivek 可以以 root 身份登录执行以下命令:
```
$ sudo -i
$ sudo /etc/init.d/sshd status
$ sudo systemctl status httpd
```
添加以下内容到 sshd_config 文件中来禁用 root 登录。
```
PermitRootLogin no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
```
更多信息参见“[如何通过禁用 Linux 的 ssh 密码登录来增强系统安全][6]” 。
#### 3. 禁用密码登录
所有的密码登录都应该禁用,仅留下公匙登录。添加以下内容到 sshd_config 文件中:
```
AuthenticationMethods publickey
PubkeyAuthentication yes
```
CentOS 6.x/RHEL 6.x 系统中老版本的 SSHD 用户可以使用以下设置:
```
PubkeyAuthentication yes
```
#### 4. 限制用户的 ssh 权限
默认状态下,所有的系统用户都可以使用密码或公匙登录。但是有些时候需要为 FTP 或者 email 服务创建 UNIX/Linux 用户。所以,这些用户也可以使用 ssh 登录系统。他们将获得访问系统工具的完整权限,包括编译器和诸如 Perl、Python(可以打开网络端口干很多疯狂的事情) 等的脚本语言。通过添加以下内容到 sshd_config 文件中来仅允许用户 root、vivek 和 jerry 通过 SSH 登录系统:
`AllowUsers vivek jerry`
当然,你也可以添加以下内容到 sshd_config 文件中来达到仅拒绝一部分用户通过 SSH 登录系统的效果。
`DenyUsers root saroj anjali foo`
你也可以通过[配置 Linux PAM][7] 来禁用或允许用户通过 sshd 登录。也可以允许或禁止一个[用户组列表][8]通过 ssh 登录系统。
#### 5. 禁用空密码
你需要明确禁止空密码账户远程登录系统,更新 sshd_config 文件的以下内容:
`PermitEmptyPasswords no`
#### 6. 为 ssh 用户或者密匙使用强密码
为密匙使用强密码和短语的重要性再怎么强调都不过分。暴力破解可以起作用就是因为用户使用了基于字典的密码。你可以强制用户避开字典密码并使用[约翰的开膛手工具][10]来检测弱密码。以下是一个随机密码生成器(放到你的 ~/.bashrc 下)
```
genpasswd() {
local l=$1
[ "$l" == "" ] && l=20
tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
```
运行:
`genpasswd 16`
输出:
```
uw8CnDVMwC6vOKgW
```
* [使用 mkpasswd / makepasswd / pwgen 生成随机密码][52]
* [Linux / UNIX: 生成密码][53]
* [Linux 随机密码生成命令][54]
--------------------------------------------------------------------------------
#### 7. 为 SSH 端口 # 22 配置防火墙
你需要更新 iptables/ufw/firewall-cmd 或 pf firewall 来为 ssh TCP 端口 # 22 配置防火墙。一般来说OpenSSH 服务应该仅允许本地或者其他的远端地址访问。
##### Netfilter (Iptables) 配置
更新 [/etc/sysconfig/iptables (Redhat和其派生系统特有文件) ][11] 实现仅接受来自于 192.168.1.0/24 和 202.54.1.5/29 的连接, 输入:
```
-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -s 202.54.1.5/29 -m state --state NEW -p tcp --dport 22 -j ACCEPT
```
如果同时使用 IPv6 的话,可以编辑/etc/sysconfig/ip6tables(Redhat 和其派生系统特有文件),输入:
```
-A RH-Firewall-1-INPUT -s ipv6network::/ipv6mask -m tcp -p tcp --dport 22 -j ACCEPT
```
将 ipv6network::/ipv6mask 替换为实际的 IPv6 网段。
##### Debian/Ubuntu Linux 下的 UFW
[UFW 是 uncomplicated firewall 的首字母缩写,主要用来管理 Linux 防火墙][12],目的是提供一种用户友好的界面。输入[以下命令使得系统进允许网段 202.54.1.5/29 接入端口 22][13]
`$ sudo ufw allow from 202.54.1.5/29 to any port 22`
更多信息请参见 "[Linux: 菜鸟管理员的 25 个 Iptables Netfilter 命令][14]"。
##### *BSD PF 防火墙配置
如果使用 PF 防火墙 [/etc/pf.conf][15] 配置如下:
```
pass in on $ext_if inet proto tcp from {192.168.1.0/24, 202.54.1.5/29} to $ssh_server_ip port ssh flags S/SA synproxy state
```
#### 8. 修改 SSH 端口和绑定 IP
SSH 默认监听系统中所有可用的网卡。修改并绑定 ssh 端口有助于避免暴力脚本的连接(许多暴力脚本只尝试端口 22)。更新文件 sshd_config 的以下内容来绑定端口 300 到 IP 192.168.1.5 和 202.54.1.5
```
Port 300
ListenAddress 192.168.1.5
ListenAddress 202.54.1.5
```
端口 300 监听地址 192.168.1.5 监听地址 202.54.1.5
当需要接受动态广域网地址的连接时,使用主动脚本是个不错的选择,比如 fail2ban 或 denyhosts。
#### 9. 使用 TCP wrappers (可选的)
TCP wrapper 是一个基于主机的访问控制系统用来过滤来自互联网的网络访问。OpenSSH 支持 TCP wrappers。只需要更新文件 /etc/hosts.allow 中的以下内容就可以使得 SSH 只接受来自于 192.168.1.2 和 172.16.23.12 的连接:
```
sshd : 192.168.1.2 172.16.23.12
```
在 Linux/Mac OS X 和类 UNIX 系统中参见 [TCP wrappers 设置和使用的常见问题][16]。
#### 10. 阻止 SSH 破解或暴力攻击
暴力破解是一种在单一或者分布式网络中使用大量组合(用户名和密码的组合)来尝试连接一个加密系统的方法。可以使用以下软件来应对暴力攻击:
* [DenyHosts][17] 是一个基于 Python SSH 安全工具。该工具通过监控授权日志中的非法登录日志并封禁原始IP的方式来应对暴力攻击。
* RHEL / Fedora 和 CentOS Linux 下如何设置 [DenyHosts][18]。
* [Fail2ban][19] 是另一个类似的用来预防针对 SSH 攻击的工具。
* [sshguard][20] 是一个使用 pf 来预防针对 SSH 和其他服务攻击的工具。
* [security/sshblock][21] 阻止滥用 SSH 尝试登录。
* [IPQ BDB filter][22] 可以看做是 fail2ban 的一个简化版。
#### 11. 限制 TCP 端口 # 22 的传入速率 (可选的)
netfilter 和 pf 都提供速率限制选项可以对端口 # 22 的传入速率进行简单的限制。
##### Iptables 示例
以下脚本将会阻止 60 秒内尝试登录 5 次以上的客户端的连入。
```
#!/bin/bash
inet_if=eth1
ssh_port=22
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --set
$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --update --seconds 60 --hitcount 5
```
在你的 iptables 脚本中调用以上脚本。其他配置选项:
```
$IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT
$IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT
# another one line example
# $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT
```
其他细节参见 iptables 用户手册。
##### *BSD PF 示例
以下脚本将限制每个客户端的连入数量为 20并且 5 秒范围的连接不超过 15 个。如果客户端触发此规则则将其加入 abusive_ips 表并限制该客户端连入。最后 flush 关键词杀死所有触发规则的客户端的状态。
```
sshd_server_ip = "202.54.1.5"
table <abusive_ips> persist
block in quick from <abusive_ips>
pass in on $ext_if proto tcp to $sshd_server_ip port ssh flags S/SA keep state (max-src-conn 20, max-src-conn-rate 15/5, overload <abusive_ips> flush)
```
#### 12. 使用端口敲门 (可选的)
[端口敲门][23]是通过在一组预先指定的封闭端口上生成连接尝试来从外部打开防火墙上的端口的方法。一旦指定的端口连接顺序被触发,防火墙规则就被动态修改以允许发送连接的主机连入指定的端口。以下是一个使用 iptables 实现的端口敲门的示例:
```
$IPT -N stage1
$IPT -A stage1 -m recent --remove --name knock
$IPT -A stage1 -p tcp --dport 3456 -m recent --set --name knock2
$IPT -N stage2
$IPT -A stage2 -m recent --remove --name knock2
$IPT -A stage2 -p tcp --dport 2345 -m recent --set --name heaven
$IPT -N door
$IPT -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2
$IPT -A door -m recent --rcheck --seconds 5 --name knock -j stage1
$IPT -A door -p tcp --dport 1234 -m recent --set --name knock
$IPT -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT
$IPT -A INPUT -p tcp --syn -j door
```
更多信息请参见:
[Debian / Ubuntu: 使用 Knockd and Iptables 设置端口敲门][55]
#### 13. 配置空闲超时注销时长
用户可以通过 ssh 连入服务器,可以配置一个超时时间间隔来避免无人值守的 ssh 会话。 打开 sshd_config 并确保配置以下值:
```
ClientAliveInterval 300
ClientAliveCountMax 0
```
以秒为单位设置一个空闲超时时间(300秒 = 5分钟)。一旦空闲时间超过这个值,空闲用户就会被踢出会话。更多细节参见[如何自动注销空闲超时的 BASH / TCSH / SSH 用户][24]。
#### 14. 为 ssh 用户启用警示标语
更新 sshd_config 文件如下来设置用户的警示标语
`Banner /etc/issue`
/etc/issue 示例文件:
```
----------------------------------------------------------------------------------------------
You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only.
By using this IS (which includes any device attached to this IS), you consent to the following conditions:
+ The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to,
penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM),
law enforcement (LE), and counterintelligence (CI) investigations.
+ At any time, the XYZG may inspect and seize data stored on this IS.
+ Communications using, or data stored on, this IS are not private, are subject to routine monitoring,
interception, and search, and may be disclosed or used for any XYZG authorized purpose.
+ This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not
for your personal benefit or privacy.
+ Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching
or monitoring of the content of privileged communications, or work product, related to personal representation
or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work
product are private and confidential. See User Agreement for details.
----------------------------------------------------------------------------------------------
```
以上是一个标准的示例,更多的用户协议和法律细节请咨询你的律师团队。
#### 15. 禁用 .rhosts 文件 (核实)
禁止读取用户的 ~/.rhosts 和 ~/.shosts 文件。更新 sshd_config 文件中的以下内容:
`IgnoreRhosts yes`
SSH 可以模拟过时的 rsh 命令,所以应该禁用不安全的 RSH 连接。
#### 16. 禁用 host-based 授权 (核实)
禁用 host-based 授权,更新 sshd_config 文件的以下选项:
`HostbasedAuthentication no`
#### 17. 为 OpenSSH 和 操作系统打补丁
推荐你使用类似 [yum][25]、[apt-get][26] 和 [freebsd-update][27] 等工具保持系统安装了最新的安全补丁。
#### 18. Chroot OpenSSH (将用户锁定在主目录)
默认设置下用户可以浏览诸如 /etc/、/bin 等目录。可以使用 chroot 或者其他专有工具如 [rssh][28] 来保护ssh连接。从版本 4.8p1 或 4.9p1 起OpenSSH 不再需要依赖诸如 rssh 或复杂的 chroot(1) 等第三方工具来将用户锁定在主目录中。可以使用新的 ChrootDirectory 指令将用户锁定在其主目录,参见[这篇博文][29]。
#### 19. 禁用客户端的 OpenSSH 服务
工作站和笔记本不需要 OpenSSH 服务。如果不需要提供 SSH 远程登录和文件传输功能的话,可以禁用 SSHD 服务。CentOS / RHEL 用户可以使用 [yum 命令][30] 禁用或删除openssh-server
`$ sudo yum erase openssh-server`
Debian / Ubuntu 用户可以使用 [apt 命令][31]/[apt-get 命令][32] 删除 openssh-server
`$ sudo apt-get remove openssh-server`
有可能需要更新 iptables 脚本来移除 ssh 例外规则。CentOS / RHEL / Fedora 系统可以编辑文件 /etc/sysconfig/iptables 和 /etc/sysconfig/ip6tables。最后[重启 iptables][33] 服务:
```
# service iptables restart
# service ip6tables restart
```
#### 20. 来自 Mozilla 的额外提示
如果使用 6.7+ 版本的 OpenSSH可以尝试下以下设置
```
#################[ WARNING ]########################
# Do not use any setting blindly. Read sshd_config #
# man page. You must understand cryptography to #
# tweak following settings. Otherwise use defaults #
####################################################
# Supported HostKey algorithms by order of preference.
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
# Specifies the available KEX (Key Exchange) algorithms.
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
# Specifies the ciphers allowed
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
#Specifies the available MAC (message authentication code) algorithms
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com
# LogLevel VERBOSE logs user's key fingerprint on login. Needed to have a clear audit track of which key was using to log in.
LogLevel VERBOSE
# Log sftp level file access (read/write/etc.) that would not be easily logged otherwise.
Subsystem sftp /usr/lib/ssh/sftp-server -f AUTHPRIV -l INFO
```
使用以下命令获取 OpenSSH 支持的加密方法:
```
$ ssh -Q cipher
$ ssh -Q cipher-auth
$ ssh -Q mac
$ ssh -Q kex
$ ssh -Q key
```
[![OpenSSH安全教程查询密码和算法选择][35]][35]
#### 如何测试 sshd_config 文件并重启/重新加载 SSH 服务?
在重启 sshd 前检查配置文件的有效性和密匙的完整性,运行:
`$ sudo sshd -t`
扩展测试模式:
`$ sudo sshd -T`
最后,根据系统的的版本[重启 Linux 或类 Unix 系统中的 sshd 服务][37]
```
$ [sudo systemctl start ssh][38] ## Debian/Ubunt Linux##
$ [sudo systemctl restart sshd.service][39] ## CentOS/RHEL/Fedora Linux##
$ doas /etc/rc.d/sshd restart ## OpenBSD##
$ sudo service sshd restart ## FreeBSD##
```
#### 其他建议
1. [使用 2FA 加强 SSH 的安全性][40] - 可以使用[OATH Toolkit][41] 或 [DuoSecurity][42] 启用多重身份验证。
2. [基于密匙链的身份验证][43] - 密匙链是一个 bash 脚本,可以使得基于密匙的验证非常的灵活方便。相对于无密码密匙,它提供更好的安全性。
#### 更多信息:
* [OpenSSH 官方][44] 项目.
* 用户手册: sshd(8),ssh(1),ssh-add(1),ssh-agent(1)
如果你发现一个方便的软件或者技术,请在下面的评论中分享,以帮助读者保持 OpenSSH 的安全。
#### 关于作者
作者是 nixCraft 的创始人,一个经验丰富的系统管理员和 Linux/Unix 脚本培训师。他曾与全球客户合作领域涉及IT教育国防和空间研究以及非营利部门等多个行业。请在 [Twitter][45]、[Facebook][46]、[Google+][47] 上关注他。
--------------------------------------------------------------------------------
via: https://www.cyberciti.biz/tips/linux-unix-bsd-openssh-server-best-practices.html
作者:[Vivek Gite][a]
译者:[shipsw](https://github.com/shipsw)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.cyberciti.biz
[1]:https://www.cyberciti.biz/media/new/tips/2009/07/openSSH_logo.png
[2]:https://isc.sans.edu/diary/OpenSSH+Rumors/6742
[3]:https://www.cyberciti.biz/tips/wp-content/uploads/2009/07/OpenSSH-server-security-best-practices.png
[4]:https://www.cyberciti.biz/faq/how-to-create-a-sudo-user-on-ubuntu-linux-server/
[5]:https://www.cyberciti.biz/faq/unix-linux-id-command-examples-usage-syntax/ (See Linux/Unix id command examples for more info)
[6]:https://www.cyberciti.biz/faq/how-to-disable-ssh-password-login-on-linux/
[7]:https://www.cyberciti.biz/tips/linux-pam-configuration-that-allows-or-deny-login-via-the-sshd-server.html
[8]:https://www.cyberciti.biz/tips/openssh-deny-or-restrict-access-to-users-and-groups.html
[9]:https://www.cyberciti.biz/tips/linux-check-passwords-against-a-dictionary-attack.html
[10]:https://www.cyberciti.biz/faq/unix-linux-password-cracking-john-the-ripper/
[11]:https://www.cyberciti.biz/faq/rhel-fedorta-linux-iptables-firewall-configuration-tutorial/
[12]:https://www.cyberciti.biz/faq/howto-configure-setup-firewall-with-ufw-on-ubuntu-linux/
[13]:https://www.cyberciti.biz/faq/ufw-allow-incoming-ssh-connections-from-a-specific-ip-address-subnet-on-ubuntu-debian/
[14]:https://www.cyberciti.biz/tips/linux-iptables-examples.html
[15]:https://bash.cyberciti.biz/firewall/pf-firewall-script/
[16]:https://www.cyberciti.biz/faq/tcp-wrappers-hosts-allow-deny-tutorial/
[17]:https://www.cyberciti.biz/faq/block-ssh-attacks-with-denyhosts/
[18]:https://www.cyberciti.biz/faq/rhel-linux-block-ssh-dictionary-brute-force-attacks/
[19]:https://www.fail2ban.org
[20]:https://sshguard.sourceforge.net/
[21]:http://www.bsdconsulting.no/tools/
[22]:https://savannah.nongnu.org/projects/ipqbdb/
[23]:https://en.wikipedia.org/wiki/Port_knocking
[24]:https://www.cyberciti.biz/faq/linux-unix-login-bash-shell-force-time-outs/
[25]:https://www.cyberciti.biz/faq/rhel-centos-fedora-linux-yum-command-howto/
[26]:https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html
[27]:https://www.cyberciti.biz/tips/howto-keep-freebsd-system-upto-date.html
[28]:https://www.cyberciti.biz/tips/rhel-centos-linux-install-configure-rssh-shell.html
[29]:https://www.debian-administration.org/articles/590
[30]:https://www.cyberciti.biz/faq/rhel-centos-fedora-linux-yum-command-howto/ (See Linux/Unix yum command examples for more info)
[31]:https://www.cyberciti.biz/faq/ubuntu-lts-debian-linux-apt-command-examples/ (See Linux/Unix apt command examples for more info)
[32]:https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html (See Linux/Unix apt-get command examples for more info)
[33]:https://www.cyberciti.biz/faq/howto-rhel-linux-open-port-using-iptables/
[34]:https://wiki.mozilla.org/Security/Guidelines/OpenSSH
[35]:https://www.cyberciti.biz/tips/wp-content/uploads/2009/07/OpenSSH-Security-Tutorial-Query-Ciphers-and-algorithms-choice.jpg
[36]:https://www.cyberciti.biz/tips/checking-openssh-sshd-configuration-syntax-errors.html
[37]:https://www.cyberciti.biz/faq/howto-restart-ssh/
[38]:https://www.cyberciti.biz/faq/howto-start-stop-ssh-server/ (Restart sshd on a Debian/Ubuntu Linux)
[39]:https://www.cyberciti.biz/faq/centos-stop-start-restart-sshd-command/ (Restart sshd on a CentOS/RHEL/Fedora Linux)
[40]:https://www.cyberciti.biz/open-source/howto-protect-linux-ssh-login-with-google-authenticator/
[41]:http://www.nongnu.org/oath-toolkit/
[42]:https://duo.com
[43]:https://www.cyberciti.biz/faq/ssh-passwordless-login-with-keychain-for-scripts/
[44]:https://www.openssh.com/
[45]:https://twitter.com/nixcraft
[46]:https://facebook.com/nixcraft
[47]:https://plus.google.com/+CybercitiBiz
[48]:https://www.cyberciti.biz/faq/ssh-passwordless-login-with-keychain-for-scripts/
[49]:https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/
[50]:https://www.cyberciti.biz/faq/how-to-set-up-ssh-keys-on-linux-unix/
[51]:https://www.cyberciti.biz/faq/how-to-upload-ssh-public-key-to-as-authorized_key-using-ansible/
[52]:https://www.cyberciti.biz/faq/generating-random-password/
[53]:https://www.cyberciti.biz/faq/linux-unix-generating-passwords-command/
[54]:https://www.cyberciti.biz/faq/linux-random-password-generator/
[55]:https://www.cyberciti.biz/faq/debian-ubuntu-linux-iptables-knockd-port-knocking-tutorial/

View File

@ -0,0 +1,192 @@
选择一个 Linux 跟踪器2015
======
[![][1]][2]
_Linux 跟踪很神奇_
跟踪器是高级的性能分析和调试工具,如果你使用过 strace(1) 或者 tcpdump(8),你不应该被它吓到 ... 你使用的就是跟踪器。系统跟踪器能让你看到很多的东西,而不仅是系统调用或者包,因为常见的跟踪器都可以跟踪内核或者应用程序的任何东西。
有大量的 Linux 跟踪器可供你选择。由于它们中的每个都有一个官方的(或者非官方的)的吉祥物,我们有足够多的选择给孩子们展示。
你喜欢使用哪一个呢?
我从两类读者的角度来回答这个问题:大多数人和性能/内核工程师。当然,随着时间的推移,这也可能会发生变化,因此,我需要及时去更新本文内容,或许是每年一次,或者更频繁。
## 对于大多数人
大多数人开发者、系统管理员、运维人员、网络可靠性工程师SRE是不需要去学习系统跟踪器的详细内容的。以下是你需要去了解和做的事情
### 1. 使用 perf_events 了解 CPU 概要信息
使用 perf_events 去了解 CPU 的基本情况。它的概要信息可以用一个 [火焰图][3] 来形象地表示。比如:
```
git clone --depth 1 https://github.com/brendangregg/FlameGraph
perf record -F 99 -a -g -- sleep 30
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > perf.svg
```
Linux 的 perf_events又称为 "perf",后面用它来表示命令)是官方为 Linux 用户准备的跟踪器/分析器。它在内核源码中,并且维护的非常好(而且现在它的功能还是快速加强)。它一般是通过 linux-tools-common 这个包来添加的。
perf 可以做的事情很多,但是,如果我建议你只学习其中的一个功能,那就是查看 CPU 概要信息。虽然从技术角度来说,这并不是事件“跟踪”,主要是它很简单。较难的部分是去获得工作的完整栈和符号,这部分的功能在我的 [Linux Profiling at Netflix][4] 中讨论过。
### 2. 知道它能干什么
正如一位朋友所说的:“你不需要知道 X 光机是如何工作的但你需要明白的是如果你吞下了一个硬币X 光机是你的一个选择!”你需要知道使用跟踪器能够做什么,因此,如果你在业务上需要它,你可以以后再去学习它,或者请会使用它的人来做。
简单地说几乎任何事情都可以通过跟踪来了解它。内部文件系统、TCP/IP 处理过程、设备驱动、应用程序内部情况。阅读我在 lwn.net 上的 [ftrace][5] 的文章,也可以去浏览 [perf_events 页面][6],那里有一些跟踪能力的示例。
### 3. 请求一个前端
如果你把它作为一个性能分析工具(有许多公司销售这类产品),并要求支持 Linux 跟踪。希望通过一个“点击”界面去探查内核的内部,包含一个在栈不同位置的延迟的热力图。就像我在 [Monitorama 演讲][7] 中描述的那样。
我创建并开源了我自己的一些前端,虽然它是基于 CLI 的(不是图形界面的)。这样将使其它人使用跟踪器更快更容易。比如,我的 [perf-tools][8],跟踪新进程是这样的:
```
# ./execsnoop
Tracing exec()s. Ctrl-C to end.
PID PPID ARGS
22898 22004 man ls
22905 22898 preconv -e UTF-8
22908 22898 pager -s
22907 22898 nroff -mandoc -rLL=164n -rLT=164n -Tutf8
[...]
```
在 Netflix 上,我创建了一个 [Vector][9],它是一个实例分析工具,实际上它是一个 Linux 跟踪器的前端。
## 对于性能或者内核工程师
一般来说,我们的工作都非常难,因为大多数人或许要求我们去搞清楚如何去跟踪某个事件,以及因此需要选择使用其中一个跟踪器。为完全理解一个跟踪器,你通常需要花至少一百多个小时去使用它。理解所有的 Linux 跟踪器并能在它们之间做出正确的选择是件很难的事情。(我或许是唯一接近完成这件事的人)
在这里我建议选择如下之一:
A) 选择一个全能的跟踪器,并以它为标准。这需要在一个测试环境中,花大量的时间来搞清楚它的细微差别和安全性。我现在的建议是 SystemTap 的最新版本(即从这个 [源][10] 构建的)。我知道有的公司选择的是 LTTng ,尽管它并不是很强大(但是它很安全),但他们也用的很好。如果在 sysdig 中添加了跟踪点或者是 kprobes它也是另外的一个候选者。
B) 按我的 [Velocity 教程中][11] 的流程图。这意味着可能是使用 ftrace 或者 perf_events因为 eBPF 是集成在内核中的,然后用其它的跟踪器,如 SystemTap/LTTng 作为对 eBPF 的补充。我目前在 Netflix 的工作中就是这么做的。
以下是我对各个跟踪器的评价:
### 1. ftrace
我爱 [Ftrace][12]它是内核黑客最好的朋友。它被构建进内核中它能够消费跟踪点、kprobes、以及 uprobes并且提供一些功能使用可选的过滤器和参数进行事件跟踪事件计数和计时内核概览函数流步进。关于它的示例可以查看内核源树中的 [ftrace.txt][13]。它通过 /sys 来管理,是面向单 root 用户的虽然你可以使用缓冲实例来破解它以支持多用户它的界面有时很繁琐但是它比较容易破解并且有前端Steven Rostedtftrace 的主要创建者,他设计了 trace-cmd并且我已经创建了 perf-tools 集合。我最讨厌的就是它不可编程,因此,你也不能,比如,去保存和获取时间戳,计算延迟,以及保存它的历史。你不需要花成本转储事件到用户级以便于进行后期处理。它通过 eBPF 可以实现可编程。
### 2. perf_events
[perf_events][14] 是 Linux 用户的主要跟踪工具,它来源于 Linux 内核,一般是通过 linux-tools-common 包来添加。又称为 "perf",后面的 perf 指的是它的前端它非常高效动态缓存一般用于跟踪并转储到一个文件中perf.data然后可以在以后的某个时间进行后期处理。它可以做大部分 ftrace 能做的事情。它实现不了函数流步进,并且不太容易破解(因为它的安全/错误检查做的非常好。但它可以做概览采样、CPU 性能计数、用户级的栈转换、以及消费对行使用本地变量进行跟踪的调试信息。它也支持多个并发用户。与 ftrace 一样,它也是内核不可编程的,或者 eBPF 支持(已经计划了补丁)。如果只学习一个跟踪器,我建议大家去学习 perf它可以解决大量的问题并且它也很安全。
### 3. eBPF
扩展的伯克利包过滤器eBPF是一个内核虚拟机可以在事件上运行程序它非常高效JIT。它可能最终为 ftrace 和 perf_events 提供内核可编程,并可以去增强其它跟踪器。它现在是由 Alexei Starovoitov 开发还没有实现全整合但是对于一些令人印象深刻的工具有些内核版本比如4.1)已经支持了:比如,块设备 I/O 延迟热力图。更多参考资料,请查阅 Alexei 的 [BPF 演示][15],和它的 [eBPF 示例][16]。
### 4. SystemTap
[SystemTap][17] 是一个非常强大的跟踪器。它可以做任何事情概览、跟踪点、kprobes、uprobes它就来自 SystemTap、USDT、内核编程等等。它将程序编译成内核模块并加载它们 —— 这是一种很难保证安全的方法。它开发的很怪诞,并且在过去的一段时间内出现了很多问题(恐慌或冻结)。许多并不是 SystemTap 的过错 —— 它通常被内核首先用于某些功能跟踪,并首先遇到运行 bug。最新版本的 SystemTap 是非常好的(你需要从它的源代码编译),但是,许多人仍然没有从早期版本的问题阴影中走出来。如果你想去使用它,花一些时间去测试环境,然后,在 irc.freenode.net 的 #systemtap 频道与开发者进行讨论。Netflix 有一个容错架构,我们使用了 SystemTap但是我们或许比起你来说很少担心它的安全性我最讨厌的事情是它假设你有办法得到内核调试信息而我并没有这些信息。没有它我确实可以做一些事情但是缺少相关的文档和示例我现在自己开始帮着做这些了
### 5. LTTng
[LTTng][18] 对事件收集进行了优化,性能要好于其它的跟踪器,也支持许多的事件类型,包括 USDT。它开发的很怪诞。它的核心部分非常简单通过一个很小的且很固定的指令集写入事件到跟踪缓冲区。这样让它既安全又快速。缺点是做内核编程不太容易。我觉得那不是个大问题由于它优化的很好尽管在需要后期处理的情况下仍然可以充分的扩展。它也探索了一种不同的分析技术。很多的“黑匣子”记录了全部有趣的事件可以在以后的 GUI 下学习它。我担心意外的记录丢失事件,我真的需要花一些时间去看看它在实践中是如何工作的。这个跟踪器上我花的时间最少(原因是没有实践过它)。
### 6. ktap
[ktap][19] 是一个很有前途的跟踪器,它在内核中使用了一个 lua 虚拟机,它不需要调试信息和嵌入式设备就可以工作的很好。这使得它进入了人们的视野,在某个时候似乎要成为 Linux 上最好的跟踪器。然而eBPF 开始集成到了内核,而 ktap 的集成工作被推迟了,直到它能够使用 eBPF 而不是它自己的虚拟机。由于 eBPF 在几个月后仍然在集成过程中,使得 ktap 的开发者等待了很长的时间。我希望在今年的晚些时间它能够重启开发。
### 7. dtrace4linux
[dtrace4linux][20] 主要由一个人 (Paul Fox) 利用业务时间将 Sun DTrace 移植到 Linux 中的。它令人印象深刻而一些贡献者的工作还不是很完美它最多应该算是实验性的工具不安全。我认为对于许可证license的担心使人们对它保持谨慎它可能永远也进入不了 Linux 内核,因为 Sun 是基于 CDDL 许可证发布的 DTracePaul 的方法是将它作为一个插件。我非常希望看到 Linux 上的 DTrace并且希望这个项目能够完成我想我加入 Netflix 时将花一些时间来帮它完成。但是,我一直在使用内置的跟踪器 ftrace 和 perf_events。
### 8. OL DTrace
[Oracle Linux DTrace][21] 是将 DTrace 移植到 Linux 的一系列努力之一,尤其是 Oracle Linux。过去这些年的许多发行版都一直稳定的进步开发者甚至谈到了改善 DTrace 测试套件这显示了这个项目很有前途。许多有用的功能已经完成系统调用、概览、sdt、proc、sched、以及 USDT。我一直在等待着 fbt函数边界跟踪对内核的动态跟踪它将成为 Linux 内核上非常强大的功能。它最终能否成功取决于能否吸引足够多的人去使用 Oracle Linux并为支持付费。另一个羁绊是它并非完全开源的内核组件是开源的但用户级代码我没有看到。
### 9. sysdig
[sysdig][22] 是一个很新的跟踪器,它可以使用类似 tcpdump 的语法来处理系统调用事件,并用 lua 做后期处理。它也是令人印象深刻的并且很高兴能看到在系统跟踪空间的创新。它的局限性是它的系统调用只能是在当时并且它不能转储事件到用户级进行后期处理。虽然我希望能看到它去支持跟踪点、kprobes、以及 uprobes但是你还是可以使用系统调用来做一些事情。我也希望在内核概览方面看到它支持 eBPF。sysdig 的开发者现在增加了对容器的支持。可以关注它的进一步发展。
## 深入阅读
我自己的工作中使用到的跟踪器包括:
**ftrace** : 我的 [perf-tools][8] 集合(查看示例目录);我的 lwn.net 的 [ftrace 跟踪器的文章][5] 一个 [LISA14][8] 演讲;和文章: [function counting][23], [iosnoop][24], [opensnoop][25], [execsnoop][26], [TCP retransmits][27], [uprobes][28], 和 [USDT][29]。
**perf_events** : 我的 [perf_events 示例][6] 页面:对于 SCALE 的一个 [Linux Profiling at Netflix][4] 演讲;和文章:[CPU 采样][30][静态跟踪点][31][势力图][32][计数][33][内核行跟踪][34][off-CPU 时间火焰图][35]。
**eBPF** : 文章 [eBPF一个小的进步][36],和一些 [BPF-tools][37] (我需要发布更多)。
**SystemTap** : 很久以前,我写了一篇 [使用 SystemTap][38] 的文章,它有点时间了。最近我发布了一些 [systemtap-lwtools][39]展示了在没有内核调试信息的情况下SystemTap 是如何使用的。
**LTTng** : 我使用它的时间很短,也没有发布什么文章。
**ktap** : 我的 [ktap 示例][40] 页面包括一行程序和脚本,虽然它是早期的版本。
**dtrace4linux** : 在我的 [系统性能][41] 书中包含了一些示例,并且在过去的时间中我为了某些事情开发了一些小的修补,比如, [timestamps][42]。
**OL DTrace** : 因为它是对 DTrace 的简单移植,我早期 DTrace 的大部分工作都 应该是与它相关的(链接太多了,可以去 [我的主页][43] 上搜索)。一旦它更加完美,我可以开发很多专用工具。
**sysdig** : 我贡献了 [fileslower][44] 和 [subsecond offset spectrogram][45] chisels。
**others** : 关于 [strace][46],我写了一些告诫文章。
不好意思,没有更多的跟踪器了! … 如果你想知道为什么 Linux 中的跟踪器不止一个,或者关于 DTrace 的内容,在我的 [从 DTrace 到 Linux][47] 的演讲中有答案,从 [第 28 张幻灯片][48] 开始。
感谢 [Deirdre Straughan][49] 的编辑以及创建了跟踪的小马General Zoi 是小马的创建者)。
--------------------------------------------------------------------------------
via: http://www.brendangregg.com/blog/2015-07-08/choosing-a-linux-tracer.html
作者:[Brendan Gregg.][a]
译者:[qhwdw](https://github.com/qhwdw)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.brendangregg.com
[1]:http://www.brendangregg.com/blog/images/2015/tracing_ponies.png
[2]:http://www.slideshare.net/brendangregg/velocity-2015-linux-perf-tools/105
[3]:http://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html
[4]:http://www.brendangregg.com/blog/2015-02-27/linux-profiling-at-netflix.html
[5]:http://lwn.net/Articles/608497/
[6]:http://www.brendangregg.com/perf.html
[7]:http://www.brendangregg.com/blog/2015-06-23/netflix-instance-analysis-requirements.html
[8]:http://www.brendangregg.com/blog/2015-03-17/linux-performance-analysis-perf-tools.html
[9]:http://techblog.netflix.com/2015/04/introducing-vector-netflixs-on-host.html
[10]:https://sourceware.org/git/?p=systemtap.git;a=blob_plain;f=README;hb=HEAD
[11]:http://www.slideshare.net/brendangregg/velocity-2015-linux-perf-tools
[12]:http://lwn.net/Articles/370423/
[13]:https://www.kernel.org/doc/Documentation/trace/ftrace.txt
[14]:https://perf.wiki.kernel.org/index.php/Main_Page
[15]:http://www.phoronix.com/scan.php?page=news_item&amp;px=BPF-Understanding-Kernel-VM
[16]:https://github.com/torvalds/linux/tree/master/samples/bpf
[17]:https://sourceware.org/systemtap/wiki
[18]:http://lttng.org/
[19]:http://ktap.org/
[20]:https://github.com/dtrace4linux/linux
[21]:http://docs.oracle.com/cd/E37670_01/E38608/html/index.html
[22]:http://www.sysdig.org/
[23]:http://www.brendangregg.com/blog/2014-07-13/linux-ftrace-function-counting.html
[24]:http://www.brendangregg.com/blog/2014-07-16/iosnoop-for-linux.html
[25]:http://www.brendangregg.com/blog/2014-07-25/opensnoop-for-linux.html
[26]:http://www.brendangregg.com/blog/2014-07-28/execsnoop-for-linux.html
[27]:http://www.brendangregg.com/blog/2014-09-06/linux-ftrace-tcp-retransmit-tracing.html
[28]:http://www.brendangregg.com/blog/2015-06-28/linux-ftrace-uprobe.html
[29]:http://www.brendangregg.com/blog/2015-07-03/hacking-linux-usdt-ftrace.html
[30]:http://www.brendangregg.com/blog/2014-06-22/perf-cpu-sample.html
[31]:http://www.brendangregg.com/blog/2014-06-29/perf-static-tracepoints.html
[32]:http://www.brendangregg.com/blog/2014-07-01/perf-heat-maps.html
[33]:http://www.brendangregg.com/blog/2014-07-03/perf-counting.html
[34]:http://www.brendangregg.com/blog/2014-09-11/perf-kernel-line-tracing.html
[35]:http://www.brendangregg.com/blog/2015-02-26/linux-perf-off-cpu-flame-graph.html
[36]:http://www.brendangregg.com/blog/2015-05-15/ebpf-one-small-step.html
[37]:https://github.com/brendangregg/BPF-tools
[38]:http://dtrace.org/blogs/brendan/2011/10/15/using-systemtap/
[39]:https://github.com/brendangregg/systemtap-lwtools
[40]:http://www.brendangregg.com/ktap.html
[41]:http://www.brendangregg.com/sysperfbook.html
[42]:https://github.com/dtrace4linux/linux/issues/55
[43]:http://www.brendangregg.com
[44]:https://github.com/brendangregg/sysdig/commit/d0eeac1a32d6749dab24d1dc3fffb2ef0f9d7151
[45]:https://github.com/brendangregg/sysdig/commit/2f21604dce0b561407accb9dba869aa19c365952
[46]:http://www.brendangregg.com/blog/2014-05-11/strace-wow-much-syscall.html
[47]:http://www.brendangregg.com/blog/2015-02-28/from-dtrace-to-linux.html
[48]:http://www.slideshare.net/brendangregg/from-dtrace-to-linux/28
[49]:http://www.beginningwithi.com/

View File

@ -0,0 +1,138 @@
#我喜欢Vue的10个方面
============================================================
![](https://cdn-images-1.medium.com/max/1600/1*X4ipeKVYzmY2M3UPYgUYuA.png)
我喜欢Vue。当我在2016年第一次接触它时也许那时我已有了JavaScript框架疲劳的观点因为我已经具有Backbone, Angular, React等框架的经验
而且我也没有过度的热情去尝试一个新的框架。直到我在hacker news上读到一份评论其描述Vue是类似于“新jquery”的JavaScript框架从而激发了我的好奇心。在那之前我已经相当满意React这个框架它是一个很好的框架基于可靠的设计原则围绕着视图模板虚拟DOM和状态响应等技术。而Vue也提供了这些重要的内容。在这篇文章中我旨在解释为什么Vue适合我为什么在上文中那些我尝试过的框架中选择它。也许你将同意我的一些观点但至少我希望能够给大家关于使用Vue开发现代JavaScript应用的一些灵感。
##1\. 极少的模板语法
Vue默认提供的视图模板语法是极小的简洁的和可扩展的。像其他Vue部分一样可以很简单的使用类似JSX一样语法而不使用标准的模板语法甚至有官方文档说明如何这样做但是我觉得没必要这么做。关于JSX有好的方面也有一些有依据的批评如混淆了JavaScript和HTML使得很容易在模板中编写出复杂的代码而本来应该分开写在不同的地方的。
Vue没有使用标准的HTML来编写视图模板而是使用极少的模板语法来处理简单的事情如基于视图数据迭代创建元素。
```
<template>
<div id="app">
<ul>
<li v-for='number in numbers' :key='number'>{{ number }}</li>
</ul>
<form @submit.prevent='addNumber'>
<input type='text' v-model='newNumber'>
<button type='submit'>Add another number</button>
</form>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
addNumber() {
const num = +this.newNumber;
if (typeof num === 'number' && !isNaN(num)) {
this.numbers.push(num);
}
}
},
data() {
return {
newNumber: null,
numbers: [1, 23, 52, 46]
};
}
}
</script>
<style lang="scss">
ul {
padding: 0;
li {
list-style-type: none;
color: blue;
}
}
</style>
```
我也喜欢Vue提供的简短绑定语法”用于在模板中绑定数据变量“@”用于绑定事件。这是一个细节,但写起来很爽而且能够让你的组件代码简洁。
##2\. 单文件组件
大多数人使用Vue都使用“单文件组件”。本质上就是一个.vue文件对应一个组件其中包含三部分CSSHTML和JavaScript
这种技术结合是对的。它让人很容易理解每个组件在一个单独的地方同时也非常好的鼓励了大家保持每个组件代码的简短。如果你的组件中JavaScriptCSS和HTML代码占了很多行那么就到了进一步模块化的时刻了。
在使用Vue组件中的<style>scoped.namecssJSCSS
关于单文件组件另一个好处是.vue文件是一个有效的HTML5文件。
<template>, <script>, <style> w3clintersLCTT 使
##3\. Vue “新的 jQuery”
事实上这两个库不相似而且用于做不同的事。让我提供给你一个很精辟的类比我实际上非常喜欢描述Vue和Jquery之间的关系披头士乐队和齐柏林飞船乐队LCTT译注两个都是英国著名的乐队。披头士乐队不需要介绍他们是20世纪60年代最大的和最有影响力的乐队。但很难说披头士乐队是20世纪70年代最大的乐队因为有时这个荣耀属于是齐柏林飞船乐队。你可以说两个乐队之间有着微妙的音乐联系或者说他们的音乐是明显不同的但两者一些先前的艺术和影响力是不可否认的。也许21世纪初JavaScript的世界就像20世纪70年代的音乐世界一样随着Vue获得更多关注使用只会吸引更多粉丝。
一些使jQuery牛逼的哲学理念在Vue中也有呈现非常容易的学习曲线但却具有基于现代web标准构建牛逼web应用所有你需要的功能。Vue的核心本质上就是在JavaScript对象上包装了一层。
##4\. 极易扩展
正如前述Vue默认使用标准的HTMLJS和CSS构建组件但可以很容易插入其他技术。如果我们想使用pugLCTT译注:一款功能丰富的模板引擎,专门为 Node.js平台开发替换HTML或者使用TypescriptLCTT译注一种由微软开发的编程语言,是JavaScript的一个超集替换js或者Sass(LCTT译注一种CSS扩展语言)替换CSS只需要安装相关的node模块和在我们的单文件组件中添加一个属性到相关的标签即可。你甚至可以在一个项目中混合搭配使用-如一些组件使用HTML其他使用pug-然而我不太确定这么做是最好的做法。
##5\. 虚拟DOM
虚拟DOM是很好的技术被用于现如今很多框架。这就表示这些框架
能够做到根据我们状态的改变来高效的完成DOM更新减少重新渲染和优化我们应用的性能。现如今每个框架都有虚拟DOM技术所以虽然它不是什么独特的东西但它仍然很出色。
##6\. Vuex
对于大多数应用管理状态成为一个棘手的问题单独使用一个视图库不能解决这个问题。Vue使用Vuex库来解决这个问题。Vuex很容易构建而且和Vue集成的很好。熟悉redux另一个管理状态的库的学习Vuex会觉得轻车熟路但是我发现Vue和Vuex集成起来更加简洁。最新JavaScript草案中LCTT译注应该是指ES7提供了对象展开运算符LCTT译注符号为...允许我们在状态或函数中进行合并以操纵从Vuex到需要它的Vue组件中的状态。
##7\. Vue的命令行界面CLI
Vue提供的命令行界面非常不错很容易开始搭建一个基于WebpackLCTT译注一个前端资源加载/打包工具的Vue项目。在终端中一行命令即可创建包含单文件组件支持babelLCTT译注js语法转换器lintingLCTT译注代码检查工具测试工具支持以及合理的项目结构。
然而有一个命令我从CLI中错过了那就是“vue构建”。
```
如: `echo '<template><h1>Hello World!</h1></template>' > Hello.vue && vue build Hello.vue -o`
```
“vue build”命令构建和运行组件并在浏览器中测试看起来非常简单。很不幸这个命令后来在Vue中删除了现在推荐使用Poi. Poi本质上是在Webpack工具上封装了一层但我不认我它像tweet上说的一样简单。
##8\. 重新渲染优化
使用Vue你不必声明DOM的哪部分应该被重新渲染。我从来都不喜欢操纵React组件的渲染像在shouldComponentUpdate方法中停止整个DOM树重新渲染这种。Vue在这方面非常巧妙。
##9\. 容易获得帮助
Vue已经达到了使用这个框架来构建各种各样的应用的一种群聚效应。开发文档非常完善。如果你需要进一步的帮助有多种渠道可用每个渠道都有很多活跃开发者stackoverflow, discord,twitter等。相对于其他用户量少的框架这就应该给你更多的信心来使用Vue构建应用。
##10\. 多机构维护
我认为一个开源库在发展方向方面的投票权利没有被单一机构操纵过多是一个好事。就如同React的许可证问题现已解决Vue就不可能涉及到。
总之作为你接下来要开发的任何JavaScript项目我认为Vue都是一个极好的选择。Vue可用的生态圈比我博客中涉及到的其他库都要大。如果想要更全面的产品你可以关注Nuxt.js。如果你需要一些可重复使用的样式组件你可以关注类似Vuetify的库。
Vue是2017年增长最快的库之一我预测在2018年增长速度不会放缓。
如果你有空闲的30分钟为什么不尝试下Vue看它可以给你提供什么呢
P.S.这篇文档很好的展示了Vue和其他框架的比较:[https://vuejs.org/v2/guide/comparison.html][1]
--------------------------------------------------------------------------------
via: https://medium.com/@dalaidunc/10-things-i-love-about-vue-505886ddaff2
作者:[Duncan Grant ][a]
译者:[yizhuoyan](https://github.com/yizhuoyan)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://medium.com/@dalaidunc
[1]:https://vuejs.org/v2/guide/comparison.html

View File

@ -1,158 +0,0 @@
Python中最快解压zip文件的方法
======
假设(现在的)上下文(context计算机术语此处意为业务情景)是这样的一个zip文件被上传到一个[web服务][1]中然后Python需要解压这个zip文件然后分析和处理其中的每个文件。这个特殊的应用查看每个文件各自的名称和大小 并和已经上传到AWS S3上的文件进行比较如果文件(和AWS S3上的相比)有所不同或者文件本身更新那么就将它上传到AWS S3。
[![Uploads today][2]][3]
挑战在于这些zip文件太大了。他们的平均大小是560MB但是其中一些大于1GB。这些文件中大多数是文本文件但是其中同样也有一些巨大的二进制文件。不同寻常的是每个zip文件包含100个文件但是其中1-3个文件却占据了多达95%的zip文件大小。
最开始我尝试在内存中解压文件并且每次只处理一个文件。在各种内存爆炸和EC2耗尽内存的情况下这个方法壮烈失败了。我觉得这个方法应该有用。最开始你有1GB文件在RAM中然后你现在解压每个文件并有了大约2-3GB放在了内存中。所以在很多次测试之后解决方案是将这些zip文件提取(dump)到磁盘上(在临时目录`/tmp`中)然后遍历这些文件。这次情况好多了但是我仍然注意到了整个解压过程花费了巨量的时间。**是否可能有方法优化呢?**
### 原始函数(baseline function)
首先是下面这些模拟对zip文件中文件实际操作的普通函数
```
def _count_file(fn):
with open(fn, 'rb') as f:
return _count_file_object(f)
def _count_file_object(f):
# Note that this iterates on 'f'.
# You *could* do 'return len(f.read())'
# which would be faster but potentially memory
# inefficient and unrealistic in terms of this
# benchmark experiment.
total = 0
for line in f:
total += len(line)
return total
```
这里是可能最简单的另一个(函数)
```
def f1(fn, dest):
with open(fn, 'rb') as f:
zf = zipfile.ZipFile(f)
zf.extractall(dest)
total = 0
for root, dirs, files in os.walk(dest):
for file_ in files:
fn = os.path.join(root, file_)
total += _count_file(fn)
return total
```
如果我更仔细地分析一下,我(将会)发现这个函数花费时间40%运行`extractall`60%的时间在执行读取文件长度的循环。
### 第一步尝试
我的第一步尝试是使用线程。先创建一个`zipfile.ZipFile`的实例,展开每个文件名到其中然后为每一个名称开始一个线程。每个线程都给它一个函数来做"实质工作"(在这个基础测试(benchmark)中,就是遍历每个文件然后获取它的名称)。实际(业务中)的函数进行的工作是复杂的S3Redis和PostgreSQL操作但是在我的基准测试中我只需要制作一个可以找出文件长度的函数就好了。线程池函数
```
def f2(fn, dest):
def unzip_member(zf, member, dest):
zf.extract(member, dest)
fn = os.path.join(dest, member.filename)
return _count_file(fn)
with open(fn, 'rb') as f:
zf = zipfile.ZipFile(f)
futures = []
with concurrent.futures.ThreadPoolExecutor() as executor:
for member in zf.infolist():
futures.append(
executor.submit(
unzip_member,
zf,
member,
dest,
)
)
total = 0
for future in concurrent.futures.as_completed(futures):
total += future.result()
return total
```
**结果:加速~10%**
### 第二步尝试
所以可能是GIL(译者注Global Interpreter Lock一种全局锁CPython中的一个概念)阻碍了我。最自然的想法是尝试使用multiprocessing在多个CPU上分配工作。但是这样做有缺点那就是你不能传递一个非可pickle序列化的对象(译注意为只有可pickle序列化的对象可以被传递),所以你只能发送文件名到之后的函数中:
```
def unzip_member_f3(zip_filepath, filename, dest):
with open(zip_filepath, 'rb') as f:
zf = zipfile.ZipFile(f)
zf.extract(filename, dest)
fn = os.path.join(dest, filename)
return _count_file(fn)
def f3(fn, dest):
with open(fn, 'rb') as f:
zf = zipfile.ZipFile(f)
futures = []
with concurrent.futures.ProcessPoolExecutor() as executor:
for member in zf.infolist():
futures.append(
executor.submit(
unzip_member_f3,
fn,
member.filename,
dest,
)
)
total = 0
for future in concurrent.futures.as_completed(futures):
total += future.result()
return total
```
**结果: 加速~300%**
### 这是作弊
使用处理器池的问题是这样需要存储在磁盘上的原始`.zip`文件。所以为了在我的web服务器上使用这个解决方案我首先得要将内存中的ZIP文件保存到磁盘然后调用这个函数。这样做的代价我不是很清楚但是应该不低。
好吧,再翻翻(poke around)看又没有损失(Well, it doesn't hurt to poke around)。可能,解压过程加速到足以弥补这样做的损失了吧。
但是一定记住这个优化取决于使用所有可用的CPU。如果一些其他的CPU需要执行在`gunicorn`中的其它事务呢这时这些其他进程必须等待直到有CPU可用。由于在这个服务器上有其他的事务正在进行我不是很确定我想要在进程中接管所有其他CPU。
### 结论
一步一步地做(这个任务)这个过程感觉挺好的。你被限制在一个CPU上但是表现仍然特别好。同样地一定要看看在`f1`和`f2`两段代码之间的不同之处!利用`concurrent.futures`池类你可以获取可以使用的CPU的个数但是这样做同样给人感觉不是很好。如果你在虚拟环境中获取的个数是错的呢或者可用的个数太低以致无法从负载分配获取好处并且现在你仅仅是为了移动负载而支付营运开支呢
我将会继续使用`zipfile.ZipFile(file_buffer).extractall(temp_dir)`。这个工作这样做已经足够好了。
### 想试试手吗?
我使用一个`c5.4xlarge` EC2服务器来进行我的基准测试。文件可以从此处下载:
```
wget https://www.peterbe.com/unzip-in-parallel/hack.unzip-in-parallel.py
wget https://www.peterbe.com/unzip-in-parallel/symbols-2017-11-27T14_15_30.zip
```
这里的`.zip`文件有34MB。和在服务器上发生的已经小了很多。
`hack.unzip-in-parallel.py`文件里是一团糟。它包含了大量可怕的入侵和丑恶的事情,但是万幸这只是一个开始(译注:大概入侵没有完成)。
--------------------------------------------------------------------------------
via: https://www.peterbe.com/plog/fastest-way-to-unzip-a-zip-file-in-python
作者:[Peterbe][a]
译者:[Leemeans](https://github.com/leemeans)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.peterbe.com/
[1]:https://symbols.mozilla.org
[2]:https://cdn-2916.kxcdn.com/cache/b7/bb/b7bbcf60347a5fa91420f71bbeed6d37.png
[3]:https://cdn-2916.kxcdn.com/cache/e6/dc/e6dc20acd37d94239edbbc0727721e4a.png

View File

@ -0,0 +1,405 @@
如何在 Ubuntu 16.04 上使用 Gogs 安装 Go 语言编写的 Git 服务器
======
Gogs 是由 Go 语言编写,提供开源且免费的 Git 服务。Gogs 是一款无痛式自托管的 Git 服务器,能在尽可能小的硬件资源开销上搭建并运行您的私有 Git 服务器。Gogs 的网页界面和 GitHub 十分相近,且提供 MySQL、PostgreSQL 和 SQLite 数据库支持。
在本教程中,我们将使用 Gogs 在 Ununtu 16.04 上按步骤,指导您安装和配置您的私有 Git 服务器。这篇教程中涵盖了如何在 Ubuntu 上安装 Go 语言、PostgreSQL 和安装并且配置 Nginx 网页服务器作为 Go 应用的反向代理的细节内容。
### 搭建环境
* Ubuntu 16.04
* Root 权限
### 我们将会接触到的事物
1. 更新和升级系统
2. 安装和配置 PostgreSQL
3. 安装 Go 和 Git
4. 安装 Gogs
5. 配置 Gogs
6. 运行 Gogs 服务器
7. 安装和配置 Nginx 反向代理
8. 测试
### 步骤 1 - 更新和升级系统
继续之前,更新 Ubuntu 所有的库,升级所有包。
运行下面的 apt 命令
```
sudo apt update
sudo apt upgrade
```
### 步骤 2 - 安装和配置 PostgreSQL
Gogs 提供 MySQL、PostgreSQL、SQLite 和 TiDB 数据库系统支持。
此步骤中,我们将使用 PostgreSQL 作为 Gogs 程序的数据库。
使用下面的 apt 命令安装 PostgreSQL。
```
sudo apt install -y postgresql postgresql-client libpq-dev
```
安装完成之后,启动 PostgreSQL 服务并设置为开机启动。
```
systemctl start postgresql
systemctl enable postgresql
```
此时 PostgreSQL 数据库在 Ubuntu 系统上完成安装了。
之后,我们需要为 Gogs 创建数据库和用户。
使用 'postgres' 用户登陆并运行 psql 命令获取 PostgreSQL 操作界面.
```
su - postgres
psql
```
创建一个名为 git 的新用户,给予此用户 CREATEDB 权限。
```
CREATE USER git CREATEDB;
\password git
```
创建名为 gogs_production 的数据库,设置 git 用户作为其所有者。
```
CREATE DATABASE gogs_production OWNER git;
```
[![创建 Gogs 数据库][1]][2]
作为 Gogs 安装时的 gogs_production PostgreSQL 数据库和 git 用户已经创建完毕。
### 步骤 3 - 安装 Go 和 Git
使用下面的 apt 命令从库中安装 Git。
```
sudo apt install git
```
此时,为系统创建名为 git 的新用户。
```
sudo adduser --disabled-login --gecos 'Gogs' git
```
登陆 git 账户并且创建名为 local 的目录。
```
su - git
mkdir -p /home/git/local
```
切换到 local 目录,依照下方所展示的内容,使用 wget 命令下载 Go最新版
```
cd ~/local
wget <https://dl.google.com/go/go1.9.2.linux-amd64.tar.gz>
```
[![安装 Go 和 Git][3]][4]
解压并且删除 go 的压缩文件。
```
tar -xf go1.9.2.linux-amd64.tar.gz
rm -f go1.9.2.linux-amd64.tar.gz
```
Go 二进制文件已经被下载到 ~/local/go 目录。此时我们需要设置环境变量 - 设置 GOROOTGOPATH 目录到系统环境,这样,我们就可以在 git 用户下执行 go 命令。
执行下方的命令。
```
cd ~/
echo 'export GOROOT=$HOME/local/go' >> $HOME/.bashrc
echo 'export GOPATH=$HOME/go' >> $HOME/.bashrc
echo 'export PATH=$PATH:$GOROOT/bin:$GOPATH/bin' >> $HOME/.bashrc
```
之后通过运行 'source ~/.bashrc' 重载 Bash如下
```
source ~/.bashrc
```
确定您使用的 Bash 是默认的 shell。
[![安装 Go 编程语言][5]][6]
现在运行 'go' 的版本查看命令。
```
go version
```
之后确保您得到下图所示的结果。
[![检查 go 版本][7]][8]
现在Go 已经安装在系统的 git 用户下了。
### 步骤 4 - 使用 Gogs 安装 Git 服务
使用 git 用户登陆并且使用 go 命令从 GitHub 下载 Gogs
```
su - git
go get -u github.com/gogits/gogs
```
此命令将在 GOPATH/src 目录下载 Gogs 的所有源代码。
切换至 '$GOPATH/src/github.com/gogits/gogs' 目录,并且使用下列命令搭建 gogs。
```
cd $GOPATH/src/github.com/gogits/gogs
go build
```
确保您没有捕获到错误。
现在使用下面的命令运行 Gogs Go Git 服务器。
```
./gogs web
```
此命令将会默认运行 Gogs 在 3000 端口上。
[![安装 Gogs Go Git 服务][9]][10]
打开网页浏览器,键入您的 IP 地址和端口号,我的是<http://192.168.33.10:3000/>
您应该会得到于下方一致的反馈。
[![Gogs 网页服务器][11]][12]
Gogs 已经在您的 Ubuntu 系统上安装完毕。现在返回到您的终端,并且键入 'Ctrl + c' 中止服务。
### 步骤 5 - 配置 Gogs Go Git 服务器
本步骤中,我们将为 Gogs 创建惯例配置。
进入 Gogs 安装目录并新建 custom/conf 目录。
```
cd $GOPATH/src/github.com/gogits/gogs
mkdir -p custom/conf/
```
复制默认的配置文件到 custom 目录,并使用 [vim][13] 修改。
```
cp conf/app.ini custom/conf/app.ini
vim custom/conf/app.ini
```
**[server]** 选项中,修改 HOST_ADDR127.0.0.1.
```
[server]
PROTOCOL = http
DOMAIN = localhost
ROOT_URL = %(PROTOCOL)s://%(DOMAIN)s:%(HTTP_PORT)s/
HTTP_ADDR = 127.0.0.1
HTTP_PORT = 3000
```
**[database]** 选项中,按照您的数据库信息修改。
```
[database]
DB_TYPE = postgres
HOST = 127.0.0.1:5432
NAME = gogs_production
USER = git
PASSWD = [email protected]#
```
保存并退出。
运行下面的命令验证配置项。
```
./gogs web
```
并且确保您得到如下的结果。
[![配置服务器][14]][15]
Gogs 现在已经按照自定义配置下运行在 localhost 的 3000 端口上了。
### 步骤 6 - 运行 Gogs 服务器
这一步,我们将在 Ubuntu 系统上配置 Gogs 服务器。我们会在 /etc/systemd/system 目录下创建一个新的服务器配置文件 gogs.service
切换到 /etc/systemd/system 目录,使用 [vim][13] 创建服务器配置文件 gogs.service
```
cd /etc/systemd/system
vim gogs.service
```
粘贴下面的代码到 gogs 服务器配置文件中。
```
[Unit]
Description=Gogs
After=syslog.target
After=network.target
After=mariadb.service mysqld.service postgresql.service memcached.service redis.service
[Service]
# Modify these two values and uncomment them if you have
# repos with lots of files and get an HTTP error 500 because
# of that
###
#LimitMEMLOCK=infinity
#LimitNOFILE=65535
Type=simple
User=git
Group=git
WorkingDirectory=/home/git/go/src/github.com/gogits/gogs
ExecStart=/home/git/go/src/github.com/gogits/gogs/gogs web
Restart=always
Environment=USER=git HOME=/home/git
[Install]
WantedBy=multi-user.target
```
之后保存并且退出。
现在可以重载系统服务器。
```
systemctl daemon-reload
```
使用下面的命令开启 gogs 服务器并设置为开机启动。
```
systemctl start gogs
systemctl enable gogs
```
[![运行 Gogs 服务器][16]][17]
Gogs 服务器现在已经运行在 Ubuntu 系统上了。
使用下面的命令检测:
```
netstat -plntu
systemctl status gogs
```
您应该会得到下图所示的结果。
[![Gogs is listening on the network interface][18]][19]
### 步骤 7 - 为 Gogs 安装和配置 Nginx 反向代理
在本步中,我们将为 Gogs 安装和配置 Nginx 反向代理。我们会在自己的库中调用 Nginx 包。
使用下面的命令添加 Nginx 库。
```
sudo add-apt-repository -y ppa:nginx/stable
```
此时更新所有的库并且使用下面的命令安装 Nginx。
```
sudo apt update
sudo apt install nginx -y
```
之后,进入 /etc/nginx/sites-available 目录并且创建虚拟主机文件 gogs
```
cd /etc/nginx/sites-available
vim gogs
```
粘贴下面的代码到配置项。
```
server {
    listen 80;
    server_name git.hakase-labs.co;
    location / {
        proxy_pass http://localhost:3000;
    }
}
```
保存退出。
**注意:**
使用您的域名修改 server_name 项。
现在激活虚拟主机并且测试 nginx 配置。
```
ln -s /etc/nginx/sites-available/gogs /etc/nginx/sites-enabled/
nginx -t
```
确保没有抛错,重启 Nginx 服务器。
```
systemctl restart nginx
```
[![安装和配置 Nginx 反向代理][20]][21]
### 步骤 8 - 测试
打开您的网页浏览器并且输入您的 gogs URL我的是 <http://git.hakase-labs.co>
现在您将进入安装界面。在页面的顶部,输入您所有的 PostgreSQL 数据库信息。
[![Gogs 安装][22]][23]
之后,滚动到底部,点击 Admin account settings 下拉选项。
输入您的管理者用户名和邮箱。
[![键入 gogs 安装设置][24]][25]
之后点击 Install Gogs 按钮。
然后您将会被重定向到下图显示的 Gogs 用户面板。
[![Gogs 面板][26]][27]
下面是 Gogs Admin Dashboard管理员面板
[![浏览 Gogs 面板][28]][29]
现在Gogs 已经通过 PostgreSQL 数据库和 Nginx 网页服务器在您的 Ubuntu 16.04 上完成安装。
--------------------------------------------------------------------------------
via: https://www.howtoforge.com/tutorial/how-to-install-gogs-go-git-service-on-ubuntu-1604/
作者:[Muhammad Arul][a]
译者:[CYLeft](https://github.com/CYLeft)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.howtoforge.com/tutorial/server-monitoring-with-shinken-on-ubuntu-16-04/
[1]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/1.png
[2]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/1.png
[3]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/2.png
[4]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/2.png
[5]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/3.png
[6]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/3.png
[7]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/4.png
[8]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/4.png
[9]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/5.png
[10]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/5.png
[11]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/6.png
[12]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/6.png
[13]:https://www.howtoforge.com/vim-basics
[14]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/7.png
[15]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/7.png
[16]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/8.png
[17]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/8.png
[18]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/9.png
[19]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/9.png
[20]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/10.png
[21]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/10.png
[22]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/11.png
[23]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/11.png
[24]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/12.png
[25]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/12.png
[26]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/13.png
[27]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/13.png
[28]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/14.png
[29]:https://www.howtoforge.com/images/how_to_install_gogs_go_git_service_on_ubuntu_1604/big/14.png