id
int64
2.05k
16.6k
title
stringlengths
5
75
fromurl
stringlengths
19
185
date
timestamp[s]
tags
sequencelengths
0
11
permalink
stringlengths
20
37
content
stringlengths
342
82.2k
fromurl_status
int64
200
526
status_msg
stringclasses
339 values
from_content
stringlengths
0
229k
9,283
如何解决 check_mk 出现 “Cannot fetch deployment URL via curl” 的错误
https://kerneltalks.com/troubleshooting/check_mk-register-cannot-fetch-deployment-url-via-curl-error/
2018-01-27T11:53:28
[ "nagios" ]
https://linux.cn/article-9283-1.html
本文解释了 “ERROR Cannot fetch deployment URL via curl:Couldn't resolve host。The given remote host was not resolved。” 的原因及其解决方案。 ![ERROR Cannot fetch deployment URL via curl:Couldn't resolve host。The given remote host was not resolved。](/data/attachment/album/201801/27/115331ohoqitxjxjhsijkt.png) `check_mk` 是一个帮你配置 [nagios](https://www.nagios.org/) 监控服务器的工具。然后在配置其中一台机器时,我遇到了下面的错误: ``` ERROR Cannot fetch deployment URL via curl:Couldn't resolve host。The given remote host was not resolved。 ``` 该错误是在我使用下面命令尝试将该机器注册到监控服务器时发生的: ``` root@kerneltalks# /usr/bin/cmk-update-agent register -s monitor.kerneltalks.com -i master -H `hostname` -p http -U omdadmin -S ASFKWEFUNSHEFKG -v ``` 其中: * `-s` 指明监控服务器 * `-i` 指定服务器上 Check\_MK 站点的名称 * `-H` 指定 agent 所在的主机名 * `-p` 为协议,可以是 http 或 https (默认为 https) * `-U` 允许下载 agent 的用户 ID * `-S` 为密码。用户的自动操作密码(当是自动用户时) 从错误中可以看出,命令无法解析监控服务器的 DNS 名称 `monitor.kerneltalks.com`。 ### 解决方案: 超级简单。检查 `/etc/resolv.conf`,确保你的 DNS 配置正确。如果还解决不了这个问题那么你可以直接在 [/etc/hosts](https://kerneltalks.com/linux/understanding-etc-hosts-file/) 中指明它的 IP。 ``` root@kerneltalks# cat /etc/hosts 10.0.10.9 monitor.kerneltalks.com ``` 这就搞定了。你现在可以成功注册了。 ``` root@kerneltalks # /usr/bin/cmk-update-agent register -s monitor.kerneltalks.com -i master -H `hostname` -p http -U omdadmin -S ASFKWEFUNSHEFKG -v Going to register agent at deployment server Successfully registered agent for deployment. You can now update your agent by running 'cmk-update-agent -v' Saved your registration settings to /etc/cmk-update-agent.state. ``` 另外,你也可以为 `-s` 直接指定 IP 地址,就没那么多事了! --- via: <https://kerneltalks.com/troubleshooting/check_mk-register-cannot-fetch-deployment-url-via-curl-error/> 作者:[kerneltalks](https://kerneltalks.com) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
*Article explaining ‘ERROR Cannot fetch deployment URL via curl: Couldn’t resolve host. The given remote host was not resolved.’ and how to resolve it.* ![](https://z5.kerneltalks.com/wp-content/uploads/2020/06/resolve-check_mk-error.png) check_mk is a utility that helps you configure your server to be monitored via [nagios monitoring tool](https://www.nagios.org/). While configuring one of the clients I came across below error : `ERROR Cannot fetch deployment URL via curl: Couldn't resolve host. The given remote host was not resolved.` This error came after I tried to register the client with the monitoring server with below command : ``` root@kerneltalks # /usr/bin/cmk-update-agent register -s monitor.kerneltalks.com -i master -H `hostname` -p http -U omdadmin -S ASFKWEFUNSHEFKG -v ``` Here in this command – `-s` is monitoring server`-i` is Name of Check_MK site on that server`-H` is Hostname to fetch agent for`-p` is protocol Either HTTP or HTTPS (default is HTTPS)`-U` User-ID of a user who is allowed to download the agent.`-S` is secret. Automation secret of that user (in case of automation user) From the error, you can figure out that command is not able to resolve to monitor server DNS name `monitor.kerneltalks.com` #### Solution Its pretty simple. Check `/etc/resolv.conf` to make sure that you have proper DNS server entry for your environment. If it still doesn’t resolve the issue then you can add an entry in [/etc/hosts](https://kerneltalks.com/linux/understanding-etc-hosts-file/) for it. ``` root@kerneltalks # cat /etc/hosts 10.0.10.9 monitor.kerneltalks.com ``` Thats it. You would be able to register now successfully. ``` root@kerneltalks # /usr/bin/cmk-update-agent register -s monitor.kerneltalks.com -i master -H `hostname` -p http -U omdadmin -S ASFKWEFUNSHEFKG -v Going to register agent at deployment server Successfully registered agent for deployment. You can now update your agent by running 'cmk-update-agent -v' Saved your registration settings to /etc/cmk-update-agent.state. ``` By the way, you can directly use the IP address for `-s` switch and get rid of all the above jargon including error itself! ## Share Your Comments & Feedback: Cancel reply
9,284
三款简单而优秀的 Linux 网络监视工具
https://www.linux.com/learn/intro-to-linux/2017/10/3-simple-excellent-linux-network-monitors
2018-01-27T12:25:16
[ "网络", "监控", "iftop" ]
https://linux.cn/article-9284-1.html
![network](/data/attachment/album/201801/27/122518y3s2q22s62j21j6z.png "network") > > 通过 `iftop`、 `nethogs` 和 `vnstat` 详细了解你的网络连接状态。 > > > 你可以通过这三个 Linux 命令了解当前网络的大量信息。`iftop` 通过进程号跟踪网络连接,`nethogs` 快速告知你哪些进程在占用你的带宽,而 `vnstat` 以一个良好的轻量级守护进程在后台运行,并实时记录你的网络使用情况。 ### iftop 令人称赞的 `iftop` 可以监听您指定的网络接口,并以 top 的样式呈现。 这是一个不错的小工具,可以用于找出网络拥塞,测速和维持网络流量总量。看到自己到底在用多少带宽往往是非常惊人的,尤其是对于我们这些仍然记得电话线路、调制解调器,“高速”到令人惊叫的 kb 和实时波特率的老人们。我们在很久之前就不再使用波特率,转而钟情于比特率。波特率用于衡量信号变化,尽管有时候与比特率相同,但大多数情况下并非如此。 如果你只有一个网络接口,直接运行 `iftop` 即可。不过 `iftop` 需要 root 权限: ``` $ sudo iftop ``` 如果你有多个网络接口,那就指定你要监控的接口: ``` $ sudo iftop -i wlan0 ``` 就像 `top` 命令一样,你可以在命令运行时更改显示选项: * `h` 切换帮助界面。 * `n` 是否解析域名。 * `s` 切换源地址的显示,`d` 则切换目的地址的显示。 * `S` 是否显示端口号。 * `N` 是否解析端口;若关闭解析则显示端口号。 * `t` 切换文本显示界面。默认的显示方式需要 ncurses。我个人认为图 1 的显示方式在组织性和可读性都更加良好。 * `p` 暂停显示更新。 * `q` 退出程序。 ![text display](/data/attachment/album/201801/27/122519kjjtdh5fftzwfpzp.png "text display") *图 1:组织性和可读性良好的文本显示。* 当你切换显示设置的时候,`iftop` 并不会中断监测流量。当然你也可以单独监测一台主机。而这需要该主机的 IP 地址和子网掩码。现在,我很好奇 Pandora(LCTT 译注:一家美国的电台公司)能给我贫瘠的带宽带来多大的负载。因此我首先使用 dig 命令找到他们的 IP 地址: ``` $ dig A pandora.com [...] ;; ANSWER SECTION: pandora.com. 267 IN A 208.85.40.20 pandora.com. 267 IN A 208.85.40.50 ``` 那子网掩码呢?[ipcalc](https://www.linux.com/learn/intro-to-linux/2017/8/how-calculate-network-addresses-ipcalc) 会告诉我们: ``` $ ipcalc -b 208.85.40.20 Address: 208.85.40.20 Netmask: 255.255.255.0 = 24 Wildcard: 0.0.0.255 => Network: 208.85.40.0/24 ``` 现在,将 IP 地址和子网掩码提供给 `iftop`: ``` $ sudo iftop -F 208.85.40.20/24 -i wlan0 ``` 很棒的不是么?而我也很惊奇地发现,Pandora 在我的网络上,每小时大约使用 500kb。并且就像大多数流媒体服务一样,Pandora 的流量在迅速增长,并依靠缓存稳定下来。 你可以使用 `-G` 选项对 IPv6 地址执行相同的操作。查阅友好的 man 可以帮助你了解 `iftop` 的其他功能,包括使用个人配置文件自定义你的默认选项,以及使用自定义过滤(请参阅 [PCAP-FILTER](http://www.tcpdump.org/manpages/pcap-filter.7.html) 来获取过滤指南)。 ### nethogs 当你想要快速了解是谁在吸取你的带宽的时候,`nethogs` 是个快速而简单的方法。你需要以 root 身份运行并指定要监听的接口。它会给你显示大量的应用程序及其进程号,所以如果你想的话,你可以借此杀死任一进程。 ``` $ sudo nethogs wlan0 nethogs version 0.8.1 PID USER PROGRAM DEV SENT RECEIVED 7690 carla /usr/lib/firefox wlan0 12.494 556.580 KB/sec 5648 carla .../chromium-browser wlan0 0.052 0.038 KB/sec TOTAL 12.546 556.618 KB/sec ``` `nethogs` 并没有多少选项:在 kb/s、kb、b、mb之间循环,按接收和发送的数据包排序,调整刷新延迟。具体请看`man nethogs`,或者是运行 `nethogs -h`。 ### vnstat [vnstat](http://humdi.net/vnstat/)是最容易使用的网络数据收集工具。它十分轻量并且不需要 root 权限。它以守护进程在后台运行,因此可以实时地记录你的网络数据。单个 `vnstat` 命令就可以显示所累计的数据。 ``` $ vnstat -i wlan0 Database updated: Tue Oct 17 08:36:38 2017 wlan0 since 10/17/2017 rx: 45.27 MiB tx: 3.77 MiB total: 49.04 MiB monthly rx | tx | total | avg. rate ------------------------+-------------+-------------+--------------- Oct '17 45.27 MiB | 3.77 MiB | 49.04 MiB | 0.28 kbit/s ------------------------+-------------+-------------+--------------- estimated 85 MiB | 5 MiB | 90 MiB | daily rx | tx | total | avg. rate ------------------------+-------------+-------------+--------------- today 45.27 MiB | 3.77 MiB | 49.04 MiB | 12.96 kbit/s ------------------------+-------------+-------------+--------------- estimated 125 MiB | 8 MiB | 133 MiB | ``` 默认情况下它会显示所有的网络接口。使用 `-i` 选项来选择某个接口。也可以像这样合并多个接口的数据: ``` $ vnstat -i wlan0+eth0+eth1 ``` 你可以通过这几种方式过滤数据显示: * `-h` 按小时显示统计信息。 * `-d` 按天显示统计信息. * `-w` 和 `-m` 分别按周和月份来显示统计信息。 * 使用 `-l` 选项查看实时更新。 以下这条命令将会删除 wlan1 的数据库并不再监视它: ``` $ vnstat -i wlan1 --delete ``` 而下面这条命令将会为你的一个网络接口创建一个别名。这个例子使用了 Ubuntu 16.04 的一个有线接口名称: ``` $ vnstat -u -i enp0s25 --nick eth0 ``` 默认情况下,vnstat 会监视 eth0。你可以在 `/etc/vnstat.conf` 对它进行修改,或者在你的家目录下创建你自己的个人配置文件。请参阅 `man vnstat` 以获取完整的指南。 你也可以安装 `vnstati` 来创建简单的彩图(图 2): ``` $ vnstati -s -i wlx7cdd90a0a1c2 -o vnstat.png ``` ![vnstati](/data/attachment/album/201801/27/122520bdn47s4s847n7j4j.png "vnstati") *图 2:你可以使用vnstati来创建简单的彩图。* 请参阅 `man vnstati` 以获取完整的选项。 *欲了解 Linux 的更多信息,可以通过学习 Linux 基金会和 edX 的免费课程,[“Linux 入门”](https://training.linuxfoundation.org/linux-courses/system-administration-training/introduction-to-linux)。* --- via: <https://www.linux.com/learn/intro-to-linux/2017/10/3-simple-excellent-linux-network-monitors> 作者:[CARLA SCHRODER](https://www.linux.com/users/cschroder) 译者:[KeyLD](https://github.com/KeyLD) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,285
无需 root 实现在 Android 设备上运行 Linux
https://www.ostechnix.com/termux-run-linux-android-devices-no-rooting-required/
2018-01-28T09:24:22
[ "Android" ]
https://linux.cn/article-9285-1.html
![](/data/attachment/album/201801/28/092426b5w9iz45g7z34bgg.jpg) 曾经,我尝试过搜索一种简单的可以在 Android 上运行 Linux 的方法。我当时唯一的意图只是想使用 Linux 以及一些基本的应用程序,比如 SSH,Git,awk 等。要求的并不多!我不想 root 我的 Android 设备。我有一台平板电脑,主要用于阅读电子书、新闻和少数 Linux 博客。除此之外也不怎么用它了。因此我决定用它来实现一些 Linux 的功能。在 Google Play 商店上浏览了几分钟后,一个应用程序瞬间引起了我的注意,勾起了我实验的欲望。如果你也想在 Android 设备上运行 Linux,这个应用可能会有所帮助。 ### Termux - 在 Android 和 Chrome OS 上运行的 Android 终端模拟器 **Termux** 是一个 Android 终端模拟器以及提供 Linux 环境的应用程序。跟许多其他应用程序不同,你无需 root 设备也无需进行设置。它是开箱即用的!它会自动安装好一个最基本的 Linux 系统,当然你也可以使用 APT 软件包管理器来安装其他软件包。总之,你可以让你的 Android 设备变成一台袖珍的 Linux 电脑。它不仅适用于 Android,你还能在 Chrome OS 上安装它。 ![](/data/attachment/album/201801/28/092427qdfflalzndzdvll2.png) Termux 提供了许多重要的功能,比您想象的要多。 * 它允许你通过 openSSH 登录远程服务器。 * 你还能够从远程系统 SSH 到 Android 设备中。 * 使用 rsync 和 curl 将您的智能手机通讯录同步到远程系统。 * 支持不同的 shell,比如 BASH、ZSH,以及 FISH 等等。 * 可以选择不同的文本编辑器来编辑/查看文件,支持 Emacs、Nano 和 Vim。 * 使用 APT 软件包管理器在 Android 设备上安装你想要的软件包。支持 Git、Perl、Python、Ruby 和 Node.js 的最新版本。 * 可以将 Android 设备与蓝牙键盘、鼠标和外置显示器连接起来,就像是整合在一起的设备一样。Termux 支持键盘快捷键。 * Termux 支持几乎所有 GNU/Linux 命令。 此外通过安装插件可以启用其他一些功能。例如,**Termux:API** 插件允许你访问 Android 和 Chrome 的硬件功能。其他有用的插件包括: * Termux:Boot - 设备启动时运行脚本 * Termux:Float - 在浮动窗口中运行 Termux * Termux:Styling - 提供配色方案和支持 Powerline 的字体来定制 Termux 终端的外观。 * Termux:Task - 提供一种从任务栏类的应用中调用 Termux 可执行文件的简易方法。 * Termux:Widget - 提供一种从主屏幕启动小脚本的建议方法。 要了解更多有关 termux 的信息,请长按终端上的任意位置并选择“帮助”菜单选项来打开内置的帮助部分。它唯一的缺点就是**需要 Android 5.0 及更高版本**。如果它支持 Android 4.x 和旧版本的话,将会更有用的多。你可以在 **Google Play 商店**和 **F-Droid** 中找到并安装 Termux。 要在 Google Play 商店中安装 Termux,点击下面按钮。 [![](/data/attachment/album/201801/28/092427izx6r0xxr12xrx1e.png)](https://play.google.com/store/apps/details?id=com.termux) 若要在 F-Droid 中安装,则点击下面按钮。 [![](/data/attachment/album/201801/28/092428ar1u338drsu3fpsm.png)](https://f-droid.org/packages/com.termux/) 你现在知道如何使用 Termux 在 Android 设备上使用 Linux 了。你有用过其他更好的应用吗?请在下面留言框中留言。我很乐意也去尝试他们! 此致敬礼! 相关资源: * [Termux 官网](https://termux.com/) --- via: <https://www.ostechnix.com/termux-run-linux-android-devices-no-rooting-required/> 作者:[SK](https://www.ostechnix.com/author/sk/) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,286
3 个可以替代 Emacs 和 Vim 的文本编辑器
https://opensource.com/article/17/9/3-alternatives-emacs-and-vim
2018-01-28T21:04:03
[ "编辑器", "Vim", "Emacs" ]
/article-9286-1.html
![](/data/attachment/album/201801/28/210355ah11eco6vzwbk1h5.png) > > Vim 和 Emacs 对于 Linux 桌面上进行文本编辑显然是重量级的,但是它们并非唯一之选。 > > > Emacs 和 Vim 的粉丝们,在你们开始编辑器之争之前,请你们理解,这篇文章并不是为了贬低诸位最喜欢的编辑器。我是一个 Emacs 爱好者,但是也很喜欢 Vim。 就是说,我认为 Emacs 和 Vim 并不适合所有人。也许 [编辑器之争](https://en.wikipedia.org/wiki/Editor_war) 略显幼稚,让很多人失望了。也许他们只是想要有一个不太苛刻的现代化的编辑器。 如果你正寻找可以替代 Emacs 或者 Vim 的编辑器,请继续阅读下去。这里有三个可能会让你感兴趣的编辑器。 ### Geany ![用 Geany 编辑一个 LaTeX 文档](/data/attachment/album/201801/28/210408ch76d89g6ybgsdy8.png "Editing a LaTeX document with Geany") *你可以用 Geany 编辑 LaTeX 文档* [Geany](https://www.geany.org/) 是一个古老的编辑器,当我还在过时的硬件上运行轻量级 Linux 发行版的时候,[Geany](https://www.geany.org/) 就是一个优秀的的编辑器。Geany 开始用于我的 [LaTeX](https://opensource.com/article/17/6/introduction-latex) 编辑,但是很快就成为我所有的文本编辑的编辑器了。 尽管 Geany 号称是轻量且快速的 [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment)(集成开发环境),但是它绝不仅仅是一个技术人的工具。Geany 轻便快捷,即便是在一个过时的机器或是 [运行 Linux 的 Chromebook](https://opensource.com/article/17/4/linux-chromebook-gallium-os) 也能轻松运行起来。无论是从编辑配置文件到维护任务列表或日志,从写文章或书籍到编写代码和脚本,Geany 都能轻松胜任。 [插件](http://plugins.geany.org/) 给 Geany 带来一些额外的魅力。这些插件拓展了 Geany 的功能,让你编码或是处理一些标记语言变得更高效,帮助你处理文本,甚至做拼写检查。 ### Atom ![使用 Atom 编辑网页](/data/attachment/album/201801/28/210410aqgdrruf3nggmxea.png "Editing a webpage with Atom") *使用 Atom 编辑网页* 在文本编辑器领域,[Atom](https://atom.io) 后来居上。很短的时间内,Atom 就获得了一批忠实的追随者。 Atom 的定制功能让其拥有如此的吸引力。如果有一些技术癖好,你完全可以在这个编辑器上随意设置。如果你不仅仅是沉迷技术,Atom 也有 [一些主题](https://atom.io/themes) ,你可以用来更改编辑器外观。 千万不要低估 Atom 数以千计的 [拓展包](https://atom.io/packages)。它们能在不同功能上拓展 Atom,能根据你的爱好把 Atom 转化成合适的文本编辑器或是开发环境。Atom 不仅为程序员提供服务。它同样是适用于 [作家的文本编辑器](https://opensource.com/article/17/5/atom-text-editor-packages-writers)。 ### Xed ![使用 Xed 编辑文章](/data/attachment/album/201801/28/210411bu7e5zve56vsu1vn.png "Writing this article in Xed") *使用 Xed 编辑文章* 可能对用户体验来说,Atom 和 Geany 略显臃肿。也许你只想要一个轻量级,一个不要太简陋也不要有太多很少使用的特性的编辑器,如此看来,[Xed](https://github.com/linuxmint/xed) 正是你所期待的。 如果 Xed 你看着眼熟,那是因为它是 MATE 桌面环境中 Pluma 编辑器上的分支。我发现相比于 Pluma,Xed 可能速度更快一点,响应更灵敏一点——不过,因人而异吧。 虽然 Xed 没有那么多的功能,但也不至于太糟。它有扎实的语法高亮,略强于一般的搜索替换和拼写检查功能以及单窗口编辑多文件的选项卡式界面。 ### 其他值得发掘的编辑器 我不是 KDE 痴,当我工作在 KDE 环境下时, [KDevelop](https://www.kdevelop.org/) 就已经是我深度工作时的首选了。它很强大而且灵活,又没有过大的体积,很像 Genany。 虽然我还没感受过对它的喜爱,但是我认识的几个人都用 [Brackets](http://brackets.io/) 感受到了。它很强大,而且不得不承认它的 [拓展](https://registry.brackets.io/) 真的很实用。 被称为 “开发者的编辑器” 的 [Notepadqq](http://notepadqq.altervista.org/s/) ,总让人联想到 [Notepad++](https://opensource.com/article/16/12/notepad-text-editor)。虽然它的发展仍处于早期阶段,但至少它看起来还是很有前景的。 对于那些只有简单的文本编辑器需求的人来说,[Gedit](https://wiki.gnome.org/Apps/Gedit) 和 [Kate](https://kate-editor.org/) 相比是极好的。它绝不是太过原始的编辑器——它有足够完成大型文本编辑的功能。无论是 Gedit 还是 Kate 都以速度和易上手而称名。 你有其他 Emacs 和 Vim 之外的挚爱编辑器么?方便的话留言分享。 --- via: <https://opensource.com/article/17/9/3-alternatives-emacs-and-vim> 作者:[Scott Nesbitt](https://opensource.com/users/scottnesbitt) 译者:[CYLeft](https://github.com/CYLeft) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
9,287
在 Linux 字符界面中获取天气预报
https://linuxconfig.org/get-your-weather-forecast-from-the-linux-cli
2018-01-28T21:20:31
[ "气候" ]
https://linux.cn/article-9287-1.html
![](/data/attachment/album/201801/28/212019uf8fs6lz8wbffcli.jpg) **目标:**使用 Linux 命令行显示天气预报。 **发行版:**所有 Linux 发行版。 **要求:**能连上因特网的 Linux **难度:**容易 **约定:** * `#` - 需要使用 root 权限来执行指定命令,可以直接使用 root 用户来执行也可以使用 `sudo` 命令 * `$` - 可以使用普通用户来执行指定命令 ### 简介 无需打开网页浏览器就能直接从终端获取最新的天气预报那该多方便啊,对吧?你还能把它写成脚本,或者设置定义定时任务。 `http://wttr.in` 是一个允许你搜索世界各地天气预报的网站,而且它的是以 ASCII 字符的形式来显示结果的。通过使用 `cURL` 访问 `http://wttr.in`,就能直接在终端显示查询结果了。 ### 获取所在地的天气 ![Local weather from wttr.in](/data/attachment/album/201801/28/212033thhm9ib99n1ihhjm.jpg) 要抓取所在地的天气情况非常简单。`wttr.in` 会自动根据 IP 地址来探测你的所在地。除非你用了 VPN,否则它的精度还不错。 ``` $ curl wttr.in ``` ### 获取指定城市的天气 ![Weather by city from wttr.in](/data/attachment/album/201801/28/212034ukawk4azxv8b7lge.jpg) 你可以通过在 `wttr.in` 后加上斜杠和城市名称的方式来获得其他城市的天气情况。不过要把名字中的空格替换成 `+`。 ``` $ curl wttr.in/New+York ``` 你也可以以 Unix 时区的形式来填写城市名称。 ``` $ curl wttr.in/New_York ``` 不要直接使用空格,否则会出现奇怪而不准确的结果。 ### 获取机场天气 ![Weather by airport from wttr.in](/data/attachment/album/201801/28/212035opdd4pgs4xqrgws7.jpg) 若你对地区的三位机场代号很熟悉,你也可以使用机场代号来查询天气。一般来说使用机场要比使用城市更贴近你,而且更精确一些。 ``` $ curl wttr.in/JFK ``` ### 猜测所在地 ![Weather by landmark from wttr.in](/data/attachment/album/201801/28/212036cxl2ffbm55bfy551.jpg) 通过使用 `~` 字符,你可以让 `wttr.in` 通过地标来猜测天气情况。 ``` $ curl wttr.in/~Statue+Of+Liberty ``` ### 域名所在地的天气 ![Weather by domain name from wttr.in](/data/attachment/album/201801/28/212036c0x3uazx3nbceexe.jpg) 你想不想知道 LinuxConfig 托管地的天气?现在有一个方法可以知道!`wttr.in` 可以通过域名获取天气。是的,这个功能可能不那么实用,但这很有趣啊。 ``` $ curl wttr.in/@linuxconfig.org ``` ### 更改温度单位 ![Change unit system in wttr.in](/data/attachment/album/201801/28/212037tdv1d8vd3hk8ka3v.jpg) 默认情况下,`wttr.in` 会根据你的实际地址来决定显示哪种温度单位(C 还是 F)。基本上,在美国,使用的是华氏度,而其他地方显示的是摄氏度。你可以指定显示的温度单位,在 URL 后添加 `?u` 会显示华氏度,而添加 `?m` 会显示摄氏度。 ``` $ curl wttr.in/New_York?m $ curl wttr.in/Toronto?u ``` 在 ZSH 上有一个很奇怪的 bug,会使得这两条语句不能正常工作,如果你需要更换单位,恐怕需要改成使用 Bash 了。 ### 总结 你可以很方便地在脚本,定时任务,甚至 MOTD(LCTT 译注:Message Of The Day - 每日消息)中访问 `wttr.in`。当然,你完全没有必要这么做。当你需要查看天气预报的时候只需要访问一下这个超棒的网站就行了。 --- via: <https://linuxconfig.org/get-your-weather-forecast-from-the-linux-cli> 作者:[Nick Congleton](https://linuxconfig.org) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,288
如何在 Linux/Unix/Windows 中发现隐藏的进程和端口
https://www.cyberciti.biz/tips/linux-unix-windows-find-hidden-processes-tcp-udp-ports.html
2018-01-28T22:27:00
[ "进程", "隐藏", "unhide" ]
https://linux.cn/article-9288-1.html
`unhide` 是一个小巧的网络取证工具,能够发现那些借助 rootkit、LKM 及其它技术隐藏的进程和 TCP/UDP 端口。这个工具在 Linux、UNIX 类、MS-Windows 等操作系统下都可以工作。根据其 man 页面的说明: > > Unhide 通过下述三项技术来发现隐藏的进程。 > > > 1. 进程相关的技术,包括将 `/proc` 目录与 [/bin/ps](https://www.cyberciti.biz/faq/show-all-running-processes-in-linux/ "Linux / Unix ps command") 命令的输出进行比较。 > 2. 系统相关的技术,包括将 [/bin/ps](https://www.cyberciti.biz/faq/show-all-running-processes-in-linux/ "Linux / Unix ps command") 命令的输出结果同从系统调用方面得到的信息进行比较。 > 3. 穷举法相关的技术,包括对所有的进程 ID 进行暴力求解,该技术仅限于在基于 Linux2.6 内核的系统中使用。 > > > 绝大多数的 Rootkit 工具或者恶意软件借助内核来实现进程隐藏,这些进程只在内核内部可见。你可以使用 `unhide` 或者诸如 [rkhunter 等工具,扫描 rootkit 程序 、后门程序以及一些可能存在的本地漏洞](https://www.cyberciti.biz/faq/howto-check-linux-rootkist-with-detectors-software/)。 ![](/data/attachment/album/201801/28/222715iwpb9s492l6bbj5p.jpg) 这篇文章描述了如何安装 unhide 并搜索隐藏的进程和 TCP/UDP 端口。 ### 如何安装 unhide 首先建议你在只读介质上运行这个工具。如果使用的是 Ubuntu 或者 Debian 发行版,输入下述的 [apt-get](https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html "See Linux/Unix apt-get command examples for more info")/[apt](//www.cyberciti.biz/faq/ubuntu-lts-debian-linux-apt-command-examples/ "See Linux/Unix apt command examples for more info") 命令以安装 Unhide: ``` $ sudo apt-get install unhide ``` 一切顺利的话你的命令行会输出以下内容: ``` [sudo] password for vivek: Reading package lists... Done Building dependency tree Reading state information... Done Suggested packages: rkhunter The following NEW packages will be installed: unhide 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 46.6 kB of archives. After this operation, 136 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu artful/universe amd64 unhide amd64 20130526-1 [46.6 kB] Fetched 46.6 kB in 0s (49.0 kB/s) Selecting previously unselected package unhide. (Reading database ... 205367 files and directories currently installed.) Preparing to unpack .../unhide_20130526-1_amd64.deb ... Unpacking unhide (20130526-1) ... Setting up unhide (20130526-1) ... Processing triggers for man-db (2.7.6.1-2) ... ``` ### 如何在 RHEL/CentOS/Oracle/Scientific/Fedora 上安装 unhide 输入下列 yum Type the following yum command (first turn on EPLE repo on a CentOS/RHEL version 6.x or version 7.x): 输入以下的 [yum](https://www.cyberciti.biz/faq/rhel-centos-fedora-linux-yum-command-howto/ "See Linux/Unix yum command examples for more info") 命令(CentOS/RHEL [6.x](https://www.cyberciti.biz/faq/fedora-sl-centos-redhat6-enable-epel-repo/) 或 [7.x](https://www.cyberciti.biz/faq/installing-rhel-epel-repo-on-centos-redhat-7-x/) 上首先打开 EPEL 仓库): ``` $ sudo yum install unhide ``` 在 Fedora 上则使用以下 dnf 命令: ``` $ sudo dnf install unhide ``` ### 如何在 Arch 上安装 unhide 键入以下 pacman 命令安装: ``` $ sudo pacman -S unhide ``` ### 如何在 FreeBSD 上安装 unhide 可以通过以下的命令使用 port 来安装 unhide: ``` # cd /usr/ports/security/unhide/ # make install clean ``` 或者可以通过二进制文件安装 hide,使用 pkg 命令安装: ``` # pkg install unhide ``` ### 如何使用 unhide 工具? unhide 的语法是: ``` unhide [options] test_list ``` `test_list` 参数可以是以下测试列表中的一个或者多个标准测试: 1. brute 2. proc 3. procall 4. procfs 5. quick 6. reverse 7. sys 或基本测试: 1. checkbrute 2. checkchdir 3. checkgetaffinity 4. checkgetparam 5. checkgetpgid 6. checkgetprio 7. checkRRgetinterval 8. checkgetsched 9. checkgetsid 10. checkkill 11. checknoprocps 12. checkopendir 13. checkproc 14. checkquick 15. checkreaddir 16. checkreverse 17. checksysinfo 18. checksysinfo2 19. checksysinfo3 你可以通过以下示例命令使用 `unhide`: ``` # unhide proc # unhide sys # unhide quick ``` 示例输出: ``` Unhide 20130526 Copyright © 2013 Yago Jesus & Patrick Gouin License GPLv3+ : GNU GPL version 3 or later http://www.unhide-forensics.info NOTE : This version of unhide is for systems using Linux >= 2.6 Used options: [*]Searching for Hidden processes through comparison of results of system calls, proc, dir and ps ``` ### 如何使用 unhide-tcp 工具辨明 TCP/UDP 端口的身份 以下是来自 man 页面的介绍: > > `unhide-tcp` 取证工具通过对所有可用的 TCP/IP 端口进行暴力求解的方式,辨别所有正在监听,却没有列入 [/bin/netstat](https://www.cyberciti.biz/tips/linux-display-open-ports-owner.html "Linux netstat command") 或者 [/bin/ss](https://www.cyberciti.biz/tips/linux-investigate-sockets-network-connections.html) 命令输出的 TCP/IP 端口身份。 > > > 注一:对于 FreeBSD、OpenBSD系统,一般使用 netstat 命令取代在这些操作系统上不存在的 iproute2,此外,sockstat 命令也用于替代 fuser。 > > > 注二:如果操作系统不支持 iproute2 命令,在使用 `unhide` 时需要在命令上加上 `-n` 或者 `-s` 选项。 > > > ``` # unhide-tcp ``` 示例输出: ``` Unhide 20100201 http://www.security-projects.com/?Unhide Starting TCP checking Starting UDP checking ``` 上述操作中,没有发现隐藏的端口。 但在下述示例中,我展示了一些有趣的事。 ``` # unhide-tcp ``` 示例输出: ``` Unhide 20100201 http://www.security-projects.com/?Unhide Starting TCP checking Found Hidden port that not appears in netstat: 1048 Found Hidden port that not appears in netstat: 1049 Found Hidden port that not appears in netstat: 1050 Starting UDP checking ``` 可以看到 `netstat -tulpn` 和 `ss` 命令确实没有反映出这三个隐藏的端口: ``` # netstat -tulpn | grep 1048 # ss -lp # ss -l | grep 1048 ``` 通过下述的 man 命令可以更多地了解 `unhide`: ``` $ man unhide $ man unhide-tcp ``` ### Windows 用户如何安装使用 unhide 你可以通过这个[页面](http://www.unhide-forensics.info/?Windows:Download)获取 Windows 版本的 unhide。 --- via: <https://www.cyberciti.biz/tips/linux-unix-windows-find-hidden-processes-tcp-udp-ports.html> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[ljgibbslf](https://github.com/ljgibbslf) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,289
热爱你的 Bug
http://akaptur.com/blog/2017/11/12/love-your-bugs/
2018-01-28T23:51:00
[ "bug" ]
https://linux.cn/article-9289-1.html
![](/data/attachment/album/201801/28/235056e16ps197dkaz1aay.jpg) 十月初的时候我在贝洛奥里藏特的[<ruby> 巴西 Python 大会 <rt> Python Brasil </rt></ruby>](http://2017.pythonbrasil.org.br/#)上做了主题演讲。这是稍加改动过的演讲文稿。你可以在[这里](http://www.youtube.com/watch?v=h4pZZOmv4Qs)观看演讲视频。 ### 我爱 bug 我目前是 [Pilot.com](http://www.pilot.com/) 的一位高级工程师,负责给创业公司提供自动记账服务。在此之前,我曾是 [Dropbox](http://www.dropbox.com/) 的桌面客户端组的成员,我今天将分享关于我当时工作的一些故事。更早之前,我是 [Recurse Center](http://www.recurse.com/) 的导师,给身在纽约的程序员提供临时的训练环境。在成为工程师之前,我在大学攻读天体物理学并在金融界工作过几年。 但这些都不重要——关于我你唯一需要知道的是,我爱 bug。我爱 bug 因为它们有趣。它们富有戏剧性。调试一个好的 bug 的过程可以非常迂回曲折。一个好的 bug 像是一个有趣的笑话或者或者谜语——你期望看到某种结果,但却事与愿违。 在这个演讲中我会给你们讲一些我曾经热爱过的 bug,解释为什么我如此爱 bug,然后说服你们也同样去热爱 bug。 ### Bug 1 号 好,让我们直接来看第一个 bug。这是我在 Dropbox 工作时遇到的一个 bug。你们或许听说过,Dropbox 是一个将你的文件从一个电脑上同步到云端和其他电脑上的应用。 ``` +--------------+ +---------------+ | | | | | 元数据服务器 | | 块服务器 | | | | | +-+--+---------+ +---------+-----+ ^ | ^ | | | | | +----------+ | | +---> | | | | | 客户端 +--------+ +--------+ | +----------+ ``` 这是个极度简化的 Dropbox 架构图。桌面客户端在你的电脑本地运行,监听文件系统的变动。当它检测到文件改动时,它读取改变的文件,并把它的内容 hash 成 4 MB 大小的文件块。这些文件块被存放在后端一个叫做<ruby> 块服务器 <rt> blockserver </rt></ruby>的巨大的<ruby> 键值对数据库 <rt> key-value store </rt></ruby>中。 当然,我们想避免多次上传同一个文件块。可以想见,如果你在编写一份文档,你应该大部分时候都在改动文档最底部——我们不想一遍又一遍地上传开头部分。所以在上传文件块到块服务器之前之前,客户端会先和一个负责管理元数据和权限等等的服务器沟通。客户端会询问这个<ruby> 元数据服务器 <rt> metaserver </rt></ruby>它是需要这个文件块,还是已经见过这个文件块了。元数据服务器会返回每一个文件块是否需要上传。 所以这些请求和响应看上去大概是这样:客户端说“我有一个改动过的文件,分为这些文件块,它们的 hash 是 `'abcd,deef,efgh'`。服务器响应说“我有前两块,但需要你上传第三块”。然后客户端会把那个文件块上传到块服务器。 ``` +--------------+ +---------------+ | | | | | 元数据服务器 | | 块服务器 | | | | | +-+--+---------+ +---------+-----+ ^ | ^ | | '有, 有, 无' | 'abcd,deef,efgh' | | +----------+ | efgh: [内容] | +---> | | | | | 客户端 +--------+ +--------+ | +----------+ ``` 这是问题的背景。下面是 bug。 ``` +--------------+ | | | 块服务器 | | | +-+--+---------+ ^ | | | '???' 'abcdldeef,efgh' | | +----------+ ^ | +---> | | ^ | | 客户端 + +--------+ | +----------+ ``` 有时候客户端会提交一个奇怪的请求:每个 hash 值应该包含 16 个字母,但它却发送了 33 个字母——所需数量的两倍加一。服务器不知道该怎么处理它,于是会抛出一个异常。我们收到这个异常的报告,于是去查看客户端的记录文件,然后会看到非常奇怪的事情——客户端的本地数据库损坏了,或者 python 抛出 MemoryError,没有一个合乎情理的。 如果你以前没见过这个问题,可能会觉得毫无头绪。但当你见过一次之后,你以后每次看到都能轻松地认出它来。给你一个提示:在那些 33 个字母的字符串中,`l` 经常会代替逗号出现。其他经常出现的字符是: ``` l \x0c < $ ( . - ``` 英文逗号的 ASCII 码是 44。`l` 的 ASCII 码是 108。它们的二进制表示如下: ``` bin(ord(',')): 0101100 bin(ord('l')): 1101100 ``` 你会注意到 `l` 和逗号只差了一位。问题就出在这里:发生了位反转。桌面客户端使用的内存中的一位发生了错误,于是客户端开始向服务器发送错误的请求。 这是其他经常代替逗号出现的字符的 ASCII 码: ``` , : 0101100 l : 1101100 \x0c : 0001100 < : 0111100 $ : 0100100 ( : 0101000 . : 0101110 - : 0101101 ``` #### 位反转是真的! 我爱这个 bug 因为它证明了位反转是可能真实发生的事情,而不只是一个理论上的问题。实际上,它在某些情况下会比平时更容易发生。其中一种情况是用户使用的是低配或者老旧的硬件,而运行 Dropbox 的电脑很多都是这样。另外一种会造成很多位反转的地方是外太空——在太空中没有大气层来保护你的内存不受高能粒子和辐射的影响,所以位反转会十分常见。 你大概非常在乎在宇宙中运行的程序的正确性——你的代码或许事关国际空间站中宇航员的性命,但即使没有那么重要,也还要考虑到在宇宙中很难进行软件更新。如果你的确需要让你的程序能够处理位反转,有很多硬件和软件措施可供你选择,Katie Betchold 还关于这个问题做过一个[非常有意思的讲座](http://www.youtube.com/watch?v=ETgNLF_XpEM)。 在刚才那种情况下,Dropbox 并不需要处理位反转。出现内存损坏的是用户的电脑,所以即使我们可以检测到逗号字符的位反转,但如果这发生在其他字符上我们就不一定能检测到了,而且如果从硬盘中读取的文件本身发生了位反转,那我们根本无从得知。我们能改进的地方很少,于是我们决定无视这个异常并继续程序的运行。这种 bug 一般都会在客户端重启之后自动解决。 #### 不常见的 bug 并非不可能发生 这是我最喜欢的 bug 之一,有几个原因。第一,它提醒我注意不常见和不可能之间的区别。当规模足够大的时候,不常见的现象会以值得注意的频率发生。 #### 覆盖面广的 bug 这个 bug 第二个让我喜欢的地方是它覆盖面非常广。每当桌面客户端和服务器交流的时候,这个 bug 都可能悄然出现,而这可能会发生在系统里很多不同的端点和组件当中。这意味着许多不同的 Dropbox 工程师会看到这个 bug 的各种版本。你第一次看到它的时候,你 *真的* 会满头雾水,但在那之后诊断这个 bug 就变得很容易了,而调查过程也非常简短:你只需找到中间的字母,看它是不是个 `l`。 #### 文化差异 这个 bug 的一个有趣的副作用是它展示了服务器组和客户端组之间的文化差异。有时候这个 bug 会被服务器组的成员发现并展开调查。如果你的 *服务器* 上发生了位反转,那应该不是个偶然——这很可能是内存损坏,你需要找到受影响的主机并尽快把它从集群中移除,不然就会有损坏大量用户数据的风险。这是个事故,而你必须迅速做出反应。但如果是用户的电脑在破坏数据,你并没有什么可以做的。 #### 分享你的 bug 如果你在调试一个难搞的 bug,特别是在大型系统中,不要忘记跟别人讨论。也许你的同事以前就遇到过类似的 bug。若是如此,你可能会节省很多时间。就算他们没有见过,也不要忘记在你解决了问题之后告诉他们解决方法——写下来或者在组会中分享。这样下次你们组遇到类似的问题时,你们都会早有准备。 ### Bug 如何帮助你进步 #### Recurse Center 在加入 Dropbox 之前,我曾在 Recurse Center 工作。它的理念是建立一个社区让正在自学的程序员们聚到一起来提高能力。这就是 Recurse Center 的全部了:我们没有大纲、作业、截止日期等等。唯一的前提条件是我们都想要成为更好的程序员。参与者中有的人有计算机学位但对自己的实际编程能力不够自信,有的人已经写了十年 Java 但想学 Clojure 或者 Haskell,还有各式各样有着其他的背景的参与者。 我在那里是一位导师,帮助人们更好地利用这个自由的环境,并参考我们从以前的参与者那里学到的东西来提供指导。所以我的同事们和我本人都非常热衷于寻找对成年自学者最有帮助的学习方法。 #### 刻意练习 在学习方法这个领域有很多不同的研究,其中我觉得最有意思的研究之一是刻意练习的概念。刻意练习理论意在解释专业人士和业余爱好者的表现的差距。它的基本思想是如果你只看内在的特征——不论先天与否——它们都无法非常好地解释这种差距。于是研究者们,包括最初的 Ericsson、Krampe 和 Tesch-Romer,开始寻找能够解释这种差距的理论。他们最终的答案是在刻意练习上所花的时间。 他们给刻意练习的定义非常精确:不是为了收入而工作,也不是为了乐趣而玩耍。你必须尽自己能力的极限,去做一个和你的水平相称的任务(不能太简单导致你学不到东西,也不能太难导致你无法取得任何进展)。你还需要获得即时的反馈,知道自己是否做得正确。 这非常令人兴奋,因为这是一套能够用来建立专业技能的系统。但难点在于对于程序员来说这些建议非常难以实施。你很难知道你是否处在自己能力的极限。也很少有即时的反馈帮助你改进——有时候你能得到任何反馈都已经算是很幸运了,还有时候你需要等几个月才能得到反馈。对于在 REPL 中做的简单的事情你可以很快地得到反馈,但如果你在做一个设计上的决定或者技术上的选择,你在很长一段时间里都无法得到反馈。 但是在有一类编程工作中刻意练习是非常有用的,它就是 debug。如果你写了一份代码,那么当时你是理解这份代码是如何工作的。但你的代码有 bug,所以你的理解并不完全正确。根据定义来说,你正处在你理解能力的极限上——这很好!你马上要学到新东西了。如果你可以重现这个 bug,那么这是个宝贵的机会,你可以获得即时的反馈,知道自己的修改是否正确。 像这样的 bug 也许能让你学到关于你的程序的一些小知识,但你也可能会学到一些关于运行你的代码的系统的一些更复杂的知识。我接下来要讲一个关于这种 bug 的故事。 ### Bug 2 号 这也是我在 Dropbox 工作时遇到的 bug。当时我正在调查为什么有些桌面客户端没有像我们预期的那样持续发送日志。我开始调查客户端的日志系统并且发现了很多有意思的 bug。我会挑一些跟这个故事有关的 bug 来讲。 和之前一样,这是一个非常简化的系统架构。 ``` +--------------+ | | +---+ +----------> | 日志服务器 | |日志| | | | +---+ | +------+-------+ | | +-----+----+ | 200 ok | | | | 客户端 | <-----------+ | | +-----+----+ ^ +--------+--------+--------+ | ^ ^ | +--+--+ +--+--+ +--+--+ +--+--+ | 日志 | | 日志 | | 日志 | | 日志 | | | | | | | | | | | | | | | | | +-----+ +-----+ +-----+ +-----+ ``` 桌面客户端会生成日志。这些日志会被压缩、加密并写入硬盘。然后客户端会间歇性地把它们发送给服务器。客户端从硬盘读取日志并发送给日志服务器。服务器会将它解码并存储,然后返回 200。 如果客户端无法连接到日志服务器,它不会让日志目录无限地增长。超过一定大小之后,它会开始删除日志来让目录大小不超过一个最大值。 最初的两个 bug 本身并不严重。第一个 bug 是桌面客户端向服务器发送日志时会从最早的日志而不是最新的日志开始。这并不是很好——比如服务器会在客户端报告异常的时候让客户端发送日志,所以你可能最在乎的是刚刚生成的日志而不是在硬盘上的最早的日志。 第二个 bug 和第一个相似:如果日志目录的大小达到了上限,客户端会从最新的日志而不是最早的日志开始删除。同理,你总是会丢失一些日志文件,但你大概更不在乎那些较早的日志。 第三个 bug 和加密有关。有时服务器会无法对一个日志文件解码(我们一般不知道为什么——也许发生了位反转)。我们在后端没有正确地处理这个错误,而服务器会返回 500。客户端看到 500 之后会做合理的反应:它会认为服务器停机了。所以它会停止发送日志文件并且不再尝试发送其他的日志。 对于一个损坏的日志文件返回 500 显然不是正确的行为。你可以考虑返回 400,因为问题出在客户端的请求上。但客户端同样无法修复这个问题——如果日志文件现在无法解码,我们后也永远无法将它解码。客户端正确的做法是直接删除日志文件然后继续运行。实际上,这正是客户端在成功上传日志文件并从服务器收到 200 的响应时的默认行为。所以我们说,好——如果日志文件无法解码,就返回 200。 所有这些 bug 都很容易修复。前两个 bug 出在客户端上,所以我们在 alpha 版本修复了它们,但大部分的客户端还没有获得这些改动。我们在服务器代码中修复了第三个 bug 并部署了新版的服务器。 #### 激增 突然日志服务器集群的流量开始激增。客服团队找到我们并问我们是否知道原因。我花了点时间把所有的部分拼到一起。 在修复之前,这四件事情会发生: 1. 日志文件从最早的开始发送 2. 日志文件从最新的开始删除 3. 如果服务器无法解码日志文件,它会返回 500 4. 如果客户端收到 500,它会停止发送日志 一个存有损坏的日志文件的客户端会试着发送这个文件,服务器会返回 500,客户端会放弃发送日志。在下一次运行时,它会尝试再次发送同样的文件,再次失败,并再次放弃。最终日志目录会被填满,然后客户端会开始删除最新的日志文件,而把损坏的文件继续保留在硬盘上。 这三个 bug 导致的结果是:如果客户端在任何时候生成了损坏的日志文件,我们就再也不会收到那个客户端的日志了。 问题是,处于这种状态的客户端比我们想象的要多很多。任何有一个损坏文件的客户端都会像被关在堤坝里一样,无法再发送日志。现在这个堤坝被清除了,所有这些客户端都开始发送它们的日志目录的剩余内容。 #### 我们的选择 好的,现在文件从世界各地的电脑如洪水般涌来。我们能做什么?(当你在一个有 Dropbox 这种规模,尤其是这种桌面客户端的规模的公司工作时,会遇到这种有趣的事情:你可以非常轻易地对自己造成 DDoS 攻击)。 当你部署的新版本发生问题时,第一个选项是回滚。这是非常合理的选择,但对于这个问题,它无法帮助我们。我们改变的不是服务器的状态而是客户端的——我们删除了那些出错文件。将服务器回滚可以防止更多客户端进入这种状态,但它并不能解决根本问题。 那扩大日志集群的规模呢?我们试过了——然后因为处理能力增加了,我们开始收到更多的请求。我们又扩大了一次,但你不可能一直这么下去。为什么不能?因为这个集群并不是独立的。它会向另一个集群发送请求,在这里是为了处理异常。如果你的一个集群正在被 DDoS,而你持续扩大那个集群,你最终会把它依赖的集群也弄坏,然后你就有两个问题了。 我们考虑过的另一个选择是减低负载——你不需要每一个日志文件,所以我们可以直接无视一些请求。一个难点是我们并没有一个很好的方法来区分好的请求和坏的请求。我们无法快速地判断哪些日志文件是旧的,哪些是新的。 我们最终使用的是一个 Dropbox 里许多不同场合都用过的一个解决方法:我们有一个自定义的头字段,`chillout`,全世界所有的客户端都遵守它。如果客户端收到一个有这个头字段的响应,它将在字段所标注的时间内不再发送任何请求。很早以前一个英明的程序员把它加到了 Dropbox 客户端里,在之后这些年中它已经不止一次地起了作用。 #### 了解你的系统 这个 bug 的第一个教训是要了解你的系统。我对于客户端和服务器之间的交互有不错的理解,但我并没有考虑到当服务器和所有这些客户端同时交互的时候会发生什么。这是一个我没有完全搞懂的层面。 #### 了解你的工具 第二个教训是要了解你的工具。如果出了差错,你有哪些选项?你能撤销你做的迁移吗?你如何知道事情出了差错,你又如何发现更多信息?所有这些事情都应该在危机发生之前就了解好——但如果你没有,你会在危机发生时学到它们并不会再忘记。 #### 功能开关 & 服务器端功能控制 第三个教训是专门针对移动端和桌面应用开发者的:*你需要服务器端功能控制和功能开关*。当你发现一个问题时如果你没有服务器端的功能控制,你可能需要几天或几星期来推送新版本或者提交新版本到应用商店中,然后问题才能得到解决。这是个很糟糕的处境。Dropbox 桌面客户端不需要经过应用商店的审查过程,但光是把一个版本推送给上千万的用户就已经要花很多时间。相比之下,如果你能在新功能遇到问题的时候在服务器上翻转一个开关:十分钟之后你的问题就已经解决了。 这个策略也有它的代价。加入很多的功能开关会大幅提高你的代码的复杂度。而你的测试代码更是会成指数地复杂化:要考虑 A 功能和 B 功能都开启,或者仅开启一个,或者都不开启的情况——然后每个功能都要相乘一遍。让工程师们在事后清理他们的功能开关是一件很难的事情(我自己也有这个毛病)。另外,桌面客户端会同时有好几个版本有人使用,也会加大思考难度。 但是它的好处——啊,当你需要它的时候,你真的是很需要它。 ### 如何去爱 bug 我讲了几个我爱的 bug,也讲了为什么要爱 bug。现在我想告诉你如何去爱 bug。如果你现在还不爱 bug,我知道唯一一种改变的方法,那就是要有成长型心态。 社会学家 Carol Dweck 做了很多关于人们如何看待智力的研究。她找到两种不同的看待智力的心态。第一种,她叫做固定型心态,认为智力是一个固定的特征,人类无法改变自己智力的多寡。另一种心态叫做成长型心态。在成长型心态下,人们相信智力是可变的而且可以通过努力来增强。 Dweck 发现一个人看待智力的方式——固定型还是成长型心态——可以很大程度地影响他们选择任务的方式、面对挑战的反应、认知能力、甚至是他们的诚信度。 【我在新西兰 Kiwi Pycon 会议所做的主题演讲中也讨论过成长型心态,所以在此只摘录一部分内容。你可以在[这里](http://akaptur.com/blog/2015/10/10/effective-learning-strategies-for-programmers/)找到完整版的演讲稿】 关于诚信的发现: > > 在这之后,他们让学生们给笔友写信讲这个实验,信中说“我们在学校做了这个实验,这是我得的分数”。他们发现 *因智力而受到表扬的学生中几乎一半人谎报了自己的分数* ,而因努力而受表扬的学生则几乎没有人不诚实。 > > > 关于努力: > > 数个研究发现有着固定型心态的人会不愿真正去努力,因为他们认为这意味着他们不擅长做他们正努力去做的这件事情。Dweck 写道,“如果每当一个任务需要努力的时候你就会怀疑自己的智力,那么你会很难对自己的能力保持自信。” > > > 关于面对困惑: > > 他们发现有成长型心态的学生大约能理解 70% 的内容,不论里面是否有难懂的段落。在有固定型心态的学生中,那些被分配没有难懂段落的手册的学生同样可以理解大约 70%。但那些看到了难懂段落的持固定型心态的学生的记忆则降到了 30%。有着固定型心态的学生非常不擅长从困惑中恢复。 > > > 这些发现表明成长型心态对 debug 至关重要。我们必须从从困惑中重整旗鼓,诚实地面对我们理解上的不足,并时不时地在寻找答案的路上努力奋斗——成长型心态会让这些都变得更简单而且不那么痛苦。 #### 热爱你的 bug 我在 Recurse Center 工作时会直白地欢迎挑战,我就是这样学会热爱我的 bug 的。有时参与者会坐到我身边说“唉,我觉得我遇到了个奇怪的 Python bug”,然后我会说“太棒了,我 *爱* 奇怪的 Python bug!” 首先,这百分之百是真的,但更重要的是,我这样是在对参与者强调,找到让自己觉得困难的事情是一种成就,而他们做到了这一点,这是件好事。 像我之前说过的,在 Recurse Center 没有截止日期也没有作业,所以这种态度没有任何成本。我会说,“你现在可以花一整天去在 Flask 里找出这个奇怪的 bug 了,多令人兴奋啊!”在 Dropbox 和之后的 Pilot,我们有产品需要发布,有截止日期,还有用户,于是我并不总是对在奇怪的 bug 上花一整天而感到兴奋。所以我对有截止日期的现实也是感同身受。但是如果我有 bug 需要解决,我就必须得去解决它,而抱怨它的存在并不会帮助我之后更快地解决它。我觉得就算在截止日期临近的时候,你也依然可以保持这样的心态。 如果你热爱你的 bug,你可以在解决困难问题时获得更多乐趣。你可以担心得更少而更加专注,并且从中学到更多。最后,你可以和你的朋友和同事分享你的 bug,这将会同时帮助你自己和你的队友们。 ### 鸣谢! 在此向给我的演讲提出反馈以及给我的演讲提供其他帮助的人士表示感谢: * Sasha Laundy * Amy Hanlon * Julia Evans * Julian Cooper * Raphael Passini Diniz 以及其他的 Python Brasil 组织团队成员 --- via: <http://akaptur.com/blog/2017/11/12/love-your-bugs/> 作者:[Allison Kaptur](http://akaptur.com/about/) 译者:[yixunx](https://github.com/yixunx) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
In early October I gave a keynote at [Python Brasil](//2017.pythonbrasil.org.br/#) in Belo Horizonte. Here is an aspirational and lightly edited transcript of the talk. There is also a video available [here](//www.youtube.com/watch?v=h4pZZOmv4Qs). ### I love bugs I’m currently a senior engineer at [Pilot.com](//www.pilot.com), working on automating bookkeeping for startups. Before that, I worked for [Dropbox](//www.dropbox.com) on the desktop client team, and I’ll have a few stories about my work there. Earlier, I was a facilitator at the [Recurse Center](//www.recurse.com), a writers retreat for programmers in NYC. I studied astrophysics in college and worked in finance for a few years before becoming an engineer. But none of that is really important to remember – the only thing you need to know about me is that I love bugs. I love bugs because they’re entertaining. They’re dramatic. The investigation of a great bug can be full of twists and turns. A great bug is like a good joke or a riddle – you’re expecting one outcome, but the result veers off in another direction. Over the course of this talk I’m going to tell you about some bugs that I have loved, explain why I love bugs so much, and then convince you that you should love bugs too. ## Bug #1 Ok, straight into bug #1. This is a bug that I encountered while working at Dropbox. As you may know, Dropbox is a utility that syncs your files from one computer to the cloud and to your other computers. 1 2 3 4 5 6 7 8 9 10 11 12 | | Here’s a vastly simplified diagram of Dropbox’s architecture. The desktop client runs on your local computer listening for changes in the file system. When it notices a changed file, it reads the file, then hashes the contents in 4MB blocks. These blocks are stored in the backend in a giant key-value store that we call blockserver. The key is the digest of the hashed contents, and the values are the contents themselves. Of course, we want to avoid uploading the same block multiple times. You can imagine that if you’re writing a document, you’re probably mostly changing the end – we don’t want to upload the beginning over and over. So before uploading a block to the blockserver the client talks to a different server that’s responsible for managing metadata and permissions, among other things. The client asks metaserver whether it needs the block or has seen it before. The “metaserver” responds with whether or not each block needs to be uploaded. So the request and response look roughly like this: The client says, “I have a changed file made up of blocks with hashes `'abcd,deef,efgh'` ”. The server responds, “I have those first two, but upload the third.” Then the client sends the block up to the blockserver. 1 2 3 4 5 6 7 8 9 10 11 12 | | That’s the setup. So here’s the bug. 1 2 3 4 5 6 7 8 9 10 11 12 | | Sometimes the client would make a weird request: each hash value should have been sixteen characters long, but instead it was thirty-three characters long – twice as many plus one. The server wouldn’t know what to do with this and would throw an exception. We’d see this exception get reported, and we’d go look at the log files from the desktop client, and really weird stuff would be going on – the client’s local database had gotten corrupted, or python would be throwing MemoryErrors, and none of it would make sense. If you’ve never seen this problem before, it’s totally mystifying. But once you’d seen it once, you can recognize it every time thereafter. Here’s a hint: the middle character of each 33-character string that we’d often see instead of a comma was `l` . These are the other characters we’d see in the middle position: ``` 1 ``` | | The ordinal value for an ascii comma – `,` – is 44. The ordinal value for `l` is 108. In binary, here’s how those two are represented: 1 2 | | You’ll notice that an `l` is exactly one bit away from a comma. And herein lies your problem: a bitflip. One bit of memory that the desktop client is using has gotten corrupted, and now the desktop client is sending a request to the server that is garbage. And here are the other characters we’d frequently see instead of the comma when a different bit had been flipped. 1 2 3 4 5 6 7 8 | | ### Bitflips are real! I love this bug because it shows that bitflips are a real thing that can happen, not just a theoretical concern. In fact, there are some domains where they’re more common than others. One such domain is if you’re getting requests from users with low-end or old hardware, which is true for a lot of laptops running Dropbox. Another domain with lots of bitflips is outer space – there’s no atmosphere in space to protect your memory from energetic particles and radiation, so bitflips are pretty common. You probably really care about correctness in space – your code might be keeping astronauts alive on the ISS, for example, but even if it’s not mission-critical, it’s hard to do software updates to space. If you really need your application to defend against bitflips, there are a variety of hardware & software approaches you can take, and there’s a [very interesting talk](//www.youtube.com/watch?v=ETgNLF_XpEM) by Katie Betchold about this. Dropbox in this context doesn’t really need to protect against bitflips. The machine that is corrupting memory is a user’s machine, so we can detect if the bitflip happens to fall in the comma – but if it’s in a different character we don’t necessarily know it, and if the bitflip is in the actual file data read off of disk, then we have no idea. There’s a pretty limited set of places where we could address this, and instead we decide to basically silence the exception and move on. Often this kind of bug resolves after the client restarts. ### Unlikely bugs aren’t impossible This is one of my favorite bugs for a couple of reasons. The first is that it’s a reminder of the difference between unlikely and impossible. At sufficient scale, unlikely events start to happen at a noticable rate. ### Social bugs My second favorite thing about this bug is that it’s a tremendously social one. This bug can crop up anywhere that the desktop client talks to the server, which is a lot of different endpoints and components in the system. This meant that a lot of different engineers at Dropbox would see versions of the bug. The first time you see it, you can *really* scratch your head, but after that it’s easy to diagnose, and the investigation is really quick: you look at the middle character and see if it’s an `l` . ### Cultural differences One interesting side-effect of this bug was that it exposed a cultural difference between the server and client teams. Occasionally this bug would be spotted by a member of the server team and investigated from there. If one of your *servers* is flipping bits, that’s probably not random chance – it’s probably memory corruption, and you need to find the affected machine and get it out of the pool as fast as possible or you risk corrupting a lot of user data. That’s an incident, and you need to respond quickly. But if the user’s machine is corrupting data, there’s not a lot you can do. ### Share your bugs So if you’re investigating a confusing bug, especially one in a big system, don’t forget to talk to people about it. Maybe your colleagues have seen a bug shaped like this one before. If they have, you might save a lot of time. And if they haven’t, don’t forget to tell people about the solution once you’ve figured it out – write it up or tell the story in your team meeting. Then the next time your teams hits something similar, you’ll all be more prepared. ## How bugs can help you learn ### Recurse Center Before I joined Dropbox, I worked for the Recurse Center. The idea behind RC is that it’s a community of self-directed learners spending time together getting better as programmers. That is the full extent of the structure of RC: there’s no curriculum or assignments or deadlines. The only scoping is a shared goal of getting better as a programmer. We’d see people come to participate in the program who had gotten CS degrees but didn’t feel like they had a solid handle on practical programming, or people who had been writing Java for ten years and wanted to learn Clojure or Haskell, and many other profiles as well. My job there was as a facilitator, helping people make the most of the lack of structure and providing guidance based on what we’d learned from earlier participants. So my colleagues and I were very interested in the best techniques for learning for self-motivated adults. ### Deliberate Practice There’s a lot of different research in this space, and one of the ones I think is most interesting is the idea of deliberate practice. Deliberate practice is an attempt to explain the difference in performance between experts & amateurs. And the guiding principle here is that if you look just at innate characteristics – genetic or otherwise – they don’t go very far towards explaining the difference in performance. So the researchers, originally Ericsson, Krampe, and Tesch-Romer, set out to discover what did explain the difference. And what they settled on was time spent in deliberate practice. Deliberate practice is pretty narrow in their definition: it’s not work for pay, and it’s not playing for fun. You have to be operating on the edge of your ability, doing a project appropriate for your skill level (not so easy that you don’t learn anything and not so hard that you don’t make any progress). You also have to get immediate feedback on whether or not you’ve done the thing correctly. This is really exciting, because it’s a framework for how to build expertise. But the challenge is that as programmers this is really hard advice to apply. It’s hard to know whether you’re operating at the edge of your ability. Immediate corrective feedback is very rare – in some cases you’re lucky to get feedback ever, and in other cases maybe it takes months. You can get quick feedback on small things in the REPL and so on, but if you’re making a design decision or picking a technology, you’re not going to get feedback on those things for quite a long time. But one category of programming where deliberate practice is a useful model is debugging. If you wrote code, then you had a mental model of how it worked when you wrote it. But your code has a bug, so your mental model isn’t quite right. By definition you’re on the boundary of your understanding – so, great! You’re about to learn something new. And if you can reproduce the bug, that’s a rare case where you can get immediate feedback on whether or not your fix is correct. A bug like this might teach you something small about your program, or you might learn something larger about the system your code is running in. Now I’ve got a story for you about a bug like that. ## Bug #2 This bug also one that I encountered at Dropbox. At the time, I was investigating why some desktop client weren’t sending logs as consistently as we expected. I’d started digging into the client logging system and discovered a bunch of interesting bugs. I’ll tell you only the subset of those bugs that is relevant to this story. Again here’s a very simplified architecture of the system. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | | The desktop client would generate logs. Those logs were compress, encrypted, and written to disk. Then every so often the client would send them up to the server. The client would read a log off of disk and send it to the log server. The server would decrypt it and store it, then respond with a 200. If the client couldn’t reach the log server, it wouldn’t let the log directory grow unbounded. After a certain point it would start deleting logs to keep the directory under a maximum size. The first two bugs were not a big deal on their own. The first one was that the desktop client sent logs up to the server starting with the oldest one instead of starting with the newest. This isn’t really what you want – for example, the server would tell the client to send logs if the client reported an exception, so probably you care about the logs that just happened and not the oldest logs that happen to be on disk. The second bug was similar to the first: if the log directory hit its maximum size, the client would delete the logs starting with the newest instead of starting with the oldest. Again, you lose log files either way, but you probably care less about the older ones. The third bug had to do with the encryption. Sometimes, the server would be unable to decrypt a log file. (We generally didn’t figure out why – maybe it was a bitflip.) We weren’t handling this error correctly on the backend, so the server would reply with a 500. The client would behave reasonably in the face of a 500: it would assume that the server was down. So it would stop sending log files and not try to send up any of the others. Returning a 500 on a corrupted log file is clearly not the right behavior. You could consider returning a 400, since it’s a problem with the client request. But the client also can’t fix the problem – if the log file can’t be decrypted now, we’ll never be able to decrypt it in the future. What you really want the client to do is just delete the log and move on. In fact, that’s the default behavior when the client gets a 200 back from the server for a log file that was successfully stored. So we said, ok – if the log file can’t be decrypted, just return a 200. All of these bugs were straightforward to fix. The first two bugs were on the client, so we’d fixed them on the alpha build but they hadn’t gone out to the majority of clients. The third bug we fixed on the server and deployed. ### 📈 Suddenly traffic to the log cluster spikes. The serving team reaches out to us to ask if we know what’s going on. It takes me a minute to put all the pieces together. Before these fixes, there were four things going on: - Log files were sent up starting with the oldest - Log files were deleted starting with the newest - If the server couldn’t decrypt a log file it would 500 - If the client got a 500 it would stop sending logs A client with a corrupted log file would try to send it, the server would 500, the client would give up sending logs. On its next run, it would try to send the same file again, fail again, and give up again. Eventually the log directory would get full, at which point the client would start deleting its newest files, leaving the corrupted one on disk. The upshot of these three bugs: if a client ever had a corrupted log file, we would never see logs from that client again. The problem is that there were a lot more clients in this state than we thought. Any client with a single corrupted file had been dammed up from sending logs to the server. Now that dam was cleared, and all of them were sending up the rest of the contents of their log directories. ### Our options Ok, there’s a huge flood of traffic coming from machines around the world. What can we do? (This is a fun thing about working at a company with Dropbox’s scale, and particularly Dropbox’s scale of desktop clients: you can trigger a self-DDOS very easily.) The first option when you do a deploy and things start going sideways is to rollback. Totally reasonable choice, but in this case, it wouldn’t have helped us. The state that we’d transformed wasn’t the state on the server but the state on the client – we’d deleted those files. Rolling back the server would prevent additional clients from entering this state but it wouldn’t solve the problem. What about increasing the size of the logging cluster? We did that – and started getting even more requests, now that we’d increased our capacity. We increased it again, but you can’t do that forever. Why not? This cluster isn’t isolated. It’s making requests into another cluster, in this case to handle exceptions. If you have a DDOS pointed at one cluster, and you keep scaling that cluster, you’re going to knock over its depedencies too, and now you have two problems. Another option we considered was shedding load – you don’t need every single log file, so can we just drop requests. One of the challenges here was that we didn’t have an easy way to tell good traffic from bad. We couldn’t quickly differentiate which log files were old and which were new. The solution we hit on is one that’s been used at Dropbox on a number of different occassions: we have a custom header, `chillout` , which every client in the world respects. If the client gets a response with this header, then it doesn’t make any requests for the provided number of seconds. Someone very wise added this to the Dropbox client very early on, and it’s come in handy more than once over the years. The logging server didn’t have the ability to set that header, but that’s an easy problem to solve. So two of my colleagues, Isaac Goldberg and John Lai, implemented support for it. We set the logging cluster chillout to two minutes initially and then managed it down as the deluge subsided over the next couple of days. ### Know your system The first lesson from this bug is to know your system. I had a good mental model of the interaction between the client and the server, but I wasn’t thinking about what would happen when the server was interacting with all the clients at once. There was a level of complexity that I hadn’t thought all the way through. ### Know your tools The second lesson is to know your tools. If things go sideways, what options do you have? Can you reverse your migration? How will you know if things are going sideways and how can you discover more? All of those things are great to know before a crisis – but if you don’t, you’ll learn them during a crisis and then never forget. ### Feature flags & server-side gating The third lesson is for you if you’re writing a mobile or a desktop application: *You need server-side feature gating and server-side flags.* When you discover a problem and you don’t have server-side controls, the resolution might take days or weeks as you push out a new release or submit a new version to the app store. That’s a bad situation to be in. The Dropbox desktop client isn’t going through an app store review process, but just pushing out a build to tens of millions of clients takes time. Compare that to hitting a problem in your feature and flipping a switch on the server: ten minutes later your problem is resolved. This strategy is not without its costs. Having a bunch of feature flags in your code adds to the complexity dramatically. You get a combinatoric problem with your testing: what if feature A is enabled and feature B, or just one, or neither – multiplied across N features. It’s extremely difficult to get engineers to clean up their feature flags after the fact (and I was also guilty of this). Then for the desktop client there’s multiple versions in the wild at the same time, so it gets pretty hard to reason about. But the benefit – man, when you need it, you really need it. # How to love bugs I’ve talked about some bugs that I love and I’ve talked about why to love bugs. Now I want to tell you how to love bugs. If you don’t love bugs yet, I know of exactly one way to learn, and that’s to have a growth mindset. The sociologist Carol Dweck has done a ton of interesting research about how people think about intelligence. She’s found that there are two different frameworks for thinking about intelligence. The first, which she calls the fixed mindset, holds that intelligence is a fixed trait, and people can’t change how much of it they have. The other mindset is a growth mindset. Under a growth mindset, people believe that intelligence is malleable and can increase with effort. Dweck found that a person’s theory of intelligence – whether they hold a fixed or growth mindset – can significantly influence the way they select tasks to work on, the way they respond to challenges, their cognitive performance, and even their honesty. [I also talked about a growth mindset in my Kiwi PyCon keynote, so here are just a few excerpts. You can read the full transcript [here](/blog/2015/10/10/effective-learning-strategies-for-programmers/).] Findings about honesty: After this, they had the students write letters to pen pals about the study, saying “We did this study at school, and here’s the score that I got.” They found that almost half of the students praised for intelligence lied about their scores, and almost no one who was praised for working hard was dishonest. On effort: Several studies found that people with a fixed mindset can be reluctant to really exert effort, because they believe it means they’re not good at the thing they’re working hard on. Dweck notes, “It would be hard to maintain confidence in your ability if every time a task requires effort, your intelligence is called into question.” On responding to confusion: They found that students with a growth mindset mastered the material about 70% of the time, regardless of whether there was a confusing passage in it. Among students with a fixed mindset, if they read the booklet without the confusing passage, again about 70% of them mastered the material. But the fixed-mindset students who encountered the confusing passage saw their mastery drop to 30%. Students with a fixed mindset were pretty bad at recovering from being confused. These findings show that a growth mindset is critical while debugging. We have to recover from confusion, be candid about the limitations of our understanding, and at times really struggle on the way to finding solutions – all of which is easier and less painful with a growth mindset. ### Love your bugs I learned to love bugs by explicitly celebrating challenges while working at the Recurse Center. A participant would sit down next to me and say, “[sigh] I think I’ve got a weird Python bug,” and I’d say, “Awesome, I *love* weird Python bugs!” First of all, this is definitely true, but more importantly, it emphasized to the participant that finding something where they struggled an accomplishment, and it was a good thing for them to have done that day. As I mentioned, at the Recurse Center there are no deadlines and no assignments, so this attitude is pretty much free. I’d say, “You get to spend a day chasing down this weird bug in Flask, how exciting!” At Dropbox and later at Pilot, where we have a product to ship, deadlines, and users, I’m not always uniformly delighted about spending a day on a weird bug. So I’m sympathetic to the reality of the world where there are deadlines. However, if I have a bug to fix, I have to fix it, and being grumbly about the existence of the bug isn’t going to help me fix it faster. I think that even in a world where deadlines loom, you can still apply this attitude. If you love your bugs, you can have more fun while you’re working on a tough problem. You can be less worried and more focused, and end up learning more from them. Finally, you can share a bug with your friends and colleagues, which helps you and your teammates. ### Obrigada! My thanks to folks who gave me feedback on this talk and otherwise contributed to my being there: - Sasha Laundy - Amy Hanlon - Julia Evans - Julian Cooper - Raphael Passini Diniz and the rest of the Python Brasil organizing team
9,290
在 Linux 上恢复一个损坏的 USB 设备至初始状态
http://www.linuxandubuntu.com/home/restore-corrupted-usb-drive-to-original-state-in-linux
2018-01-29T22:09:39
[ "USB" ]
https://linux.cn/article-9290-1.html
![](/data/attachment/album/201801/29/220941qr44tpy4tfffz3yl.jpg) 很多时候我们诸如 SD 卡和 U 盘这样的储存器可能会被损坏,并且因此或其他原因不能继续使用。 这可能是因为使用这个设备创建了一个引导媒体或者是通过错误的平台格式化亦或是创建了一个新的分区在这个设备上。 ### 恢复损坏的 USB 设备至初始状态 [![Linux 系统磁盘管理器](/data/attachment/album/201801/29/220948jvujujojubxjkrz3.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/usb.png) **警告:接下来的操作会将你设备上的所有数据格式化。** 无论是上面提及的什么原因,最终的结果是我们无法继续使用这个设备。 所以这里有一个恢复 USB 设备或者是 SD 卡到出厂状态的方法。 大多数时候通过文件浏览器进行一次简单格式化可以解决问题,但是在一些极端情况下,比如文件管理器没有作用,而你又需要你的设备可以继续工作时,你可以使用下面的指导: 我们将会使用一个叫做 `mkusb` 的小工具来实现目标,这个工具的安装非常简单。 添加 mkusb 的仓库: ``` sudo apt add repository ppa:mkusb/ppa ``` 现在更新你的包列表: ``` sudo apt-get update ``` 安装 `mkusb: ``` sudo apt-get install mkusb ``` 现在运行 `mkusb` 你将会看到这个提示,点击 ‘Yes’。 [![运行 mkusb dus](/data/attachment/album/201801/29/220952jnnkdndatzzczkcp.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/run-mkusb.png) 现在 `mkusb` 将会最后一次询问你是否希望继续格式化你的数据,‘Stop’是被默认选择的,你现在选择 ‘Go’ 并点击 ‘OK’。 [![Linux mkusb](/data/attachment/album/201801/29/220956p2v0qiimpp5h2sbp.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/final-checkpoint_1.png) 窗口将会关闭,此时你的终端看起来是这样的。 [![mkusb usb 控制台](/data/attachment/album/201801/29/221008f4tfb63tlz3itzki.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/mkusb.png) 在几秒钟之后,整个过程将会完成,并且你将看到一个这样的弹出窗口。 [![恢复损坏的 USB 设备](/data/attachment/album/201801/29/221013n8022t6s5cx4lqfz.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/usb_1.png) 你现在需要把你的设备从系统推出,然后再重新插进去。你的设备将被恢复成为一个普通设备而且还能像原来一样的工作。 [![Linux 磁盘管理器](/data/attachment/album/201801/29/221022v3tg1iwwii1tjpie.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/usb_2.png) 我们现在所做的操作本可以通过终端命令或是 gparted 或者其他的软件来完成,但是那将会需要一些关于分区管理的知识。 所以有一个像这样可以自动解决专一问题的小工具总是一个好事。 ### 结论 `mkusb` 是一个很容易使用的程序,它可以修复你的 USB 储存设备和 SD 卡。`mkusb` 通过 mkusb 的 PPA 来下载。所有在 `mkusb` 上的操作都需要超级管理员的权限,并且你在这个设备上的所有数据将会被格式化。 一旦操作完成,你将会重置这个设备并让它继续工作。 如果你感到任何疑惑,你可以在下面的评论栏里免费发表。 --- via: <http://www.linuxandubuntu.com/home/restore-corrupted-usb-drive-to-original-state-in-linux> 作者:[LINUXANDUBUNTU](http://www.linuxandubuntu.com) 译者:[Drshu](https://github.com/Drshu) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,291
Linux/Unix 桌面盛典:模仿 “黑客帝国” 界面!
https://www.cyberciti.biz/open-source/command-line-hacks/matrix-digital-rain-on-linux-macos-unix-terminal/
2018-01-29T22:24:23
[ "matrix" ]
https://linux.cn/article-9291-1.html
![](/data/attachment/album/201801/29/222415ln4gn4nh4m6kznmw.jpg) 《黑客帝国》是 1999 年,由 Wachowki 兄弟编导的科幻动作片。这部电影的荧屏里有无尽的绿色字符降落。数字雨模拟着《黑客帝国》中的虚拟现实活动。现在,Linux 和 Unix 终端上,你也可以通过 CMatrix 模仿出矩阵数字雨。 ### 安装 cmatrix 根据你的 Linux/Unix 发行版或操作系统安装并且设置 CMatrix。 #### 如何在 Debian/Ubuntu Linux 发行版中安装 cmatrix 在 Debian/Ubuntu/Mint 系统中键入以下命令 [apt-get 命令](https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html "See Linux/Unix apt-get command examples for more info")/[apt 命令](https://www.cyberciti.biz/faq/ubuntu-lts-debian-linux-apt-command-examples/ "See Linux/Unix apt command examples for more info"): ``` $ sudo apt install cmatrix ``` 示例输出: ``` [sudo] password for vivek: Reading package lists... Done Building dependency tree Reading state information... Done Suggested packages: cmatrix-xfont The following NEW packages will be installed: cmatrix 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 15.8 kB of archives. After this operation, 50.2 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu artful/universe amd64 cmatrix amd64 1.2a-5build2 [15.8 kB] Fetched 15.8 kB in 0s (19.7 kB/s) Selecting previously unselected package cmatrix. (Reading database ... 205388 files and directories currently installed.) Preparing to unpack .../cmatrix_1.2a-5build2_amd64.deb ... Unpacking cmatrix (1.2a-5build2) ... Setting up cmatrix (1.2a-5build2) ... Processing triggers for man-db (2.7.6.1-2) ... ``` #### 如何在 Arch Linux 发行版安装 cmatrix 键入 pacman 命令: ``` $ sudo pacman -S cmatrix ``` #### 如何在 FreeBCD 系统中安装 cmatrix 运行如下命令安装 port: ``` # cd /usr/ports/misc/cmatrix/ && make install clean ``` 或者使用 pkg 命令添加二进制包: ``` # pkg install cmatrix ``` #### 如何在 macOS Unix 发行版中安装 cmatrix 键入下列命令: ``` $ brew install cmatrix ``` #### 如何在 OpenBSD 系统中安装 cmatrix 键入 pkg\_add 命令: ``` # pkg_add cmatrix ``` ### 使用 cmatrix 简单键入命令: ``` $ cmatrix ``` [![cmtarix 运转中](/data/attachment/album/201801/29/222426mrmtjayfitmfiffi.gif)](https://www.cyberciti.biz/media/new/cms/2018/01/small-cmtarix-file.gif) #### 使用键盘 在执行期间,下列按键有效(`-s` 模式下,按键无效): | 按键 | 说明 | | --- | --- | | `a` | 切换异步滚动 | | `b` | 随机字符加粗 | | `B` | 全部字符加粗 | | `n` | 关闭字符加粗 | | `0`-`9` | 调整更新时间 | | `!` `@` `#` `$` `%` `^` `&` `)` | 改变对应的矩阵颜色: `!` – 红、`@` – 绿、`#` – 黄、`$` – 蓝、`%` – 洋红、`^` – 青、 `&` – 白、 `)` – 黑。 | | `q` | 退出程序 | 你可以通过以下命令获取 cmatrix 选项: ``` $ cmatrix -h ``` * `-a`: 异步滚动 * `-b`: 开启字符加粗 * `-B`: 所有字符加粗(优先于 -b 选项) * `-f`: 强制开启 Linux $TERM 模式 * `-l`: Linux 模式(使用 matrix 控制台字体) * `-o`: 启用旧式滚动 * `-h`: 输出使用说明并退出 * `-n`: 关闭字符加粗 (优先于 -b and -B,默认) * `-s`: “屏保”模式, 第一次按键时退出 * `-x`: X 窗口模式,如果你使用的时 mtx.pcf 终端 * `-V`: 输出版本信息并且退出 * `-u delay` (0 - 10,默认 4): 屏幕更新延时 * `-C [color]`: 调整 matrix 颜色(默认绿色) 现在,你拥有了一款最炫酷的终端应用! --- via: <https://www.cyberciti.biz/open-source/command-line-hacks/matrix-digital-rain-on-linux-macos-unix-terminal/> 作者:[nixCraft](https://www.cyberciti.biz) 译者:[CYLeft](https://github.com/CYLeft) 校对:[校对者ID](https://github.com/%E6%A0%A1%E5%AF%B9%E8%80%85ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,292
如何在使用 scp 命令时递归地排除文件
https://www.cyberciti.biz/faq/scp-exclude-files-when-using-command-recursively-on-unix-linux/
2018-01-30T11:35:00
[ "scp", "rsync" ]
https://linux.cn/article-9292-1.html
![](/data/attachment/album/201801/29/224214p1179wdr9laeriwg.jpg) Q:我需要将所有包含 \*.c 文件的文件夹从名为 hostA 的本地笔记本复制到 hostB。我使用的是下面的 `scp` 命令,但不知道如何排除特定的文件(如 \*.out): ``` $ scp -r ~/projects/ user@hostB:/home/delta/projects/ ``` 如何告诉 `scp` 命令在 Linux/Unix 命令行中排除特定的文件或目录? 人们可以使用 `scp` 命令在网络主机之间安全地复制文件。它使用 ssh 进行数据传输和身份验证。典型的语法是: ``` scp file1 user@host:/path/to/dest/ scp -r /path/to/source/ user@host:/path/to/dest/ ``` ### scp 排除文件 我不认为你可以在使用 scp 命令时过滤或排除文件。但是,有一个很好的解决方法来排除文件并使用 ssh 安全地复制它。本页面说明如何在使用 `scp` 递归复制目录时过滤或排除文件。 ### 如何使用 rsync 命令排除文件 语法是: ``` rsync av -e ssh --exclude='*.out' /path/to/source/ user@hostB:/path/to/dest/ ``` 这里: 1. `-a` :递归到目录,即复制所有文件和子目录。另外,打开归档模式和所有其他选项(相当于 `-rlptgoD`) 2. `-v` :详细输出 3. `-e ssh` :使用 ssh 作为远程 shell,这样所有的东西都被加密 4. `--exclude='*.out'` :排除匹配模式的文件,例如 \*.out 或 \*.c 等。 ### rsync 命令的例子 在这个例子中,从 `~/virt/` 目录递归地复制所有文件,但排除所有 \*.new 文件: ``` $ rsync -av -e ssh --exclude='*.new' ~/virt/ root@centos7:/tmp ``` 示例输出: [![Scp exclude files but using rsync exclude command](/data/attachment/album/201801/29/224228pk4edf2dzclkh9hf.jpg)](https://www.cyberciti.biz/media/new/faq/2017/12/scp-exclude-files-on-linux-unix-macos-bash-shell-command-line.jpg) 如果远程服务器上找不到 `rsync`,那么 `rsync` 命令将失败。在这种情况下,请尝试使用以下 `scp` 命令,该命令在当前目录中使用 [bash shell 模式匹配](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html#Pattern-Matching) (它不能与 `-r` 选项一起使用): ``` $ ls ``` 示例输出: ``` centos71.log centos71.qcow2 centos71.qcow2.new centos71.v2.qcow2.new meta-data user-data ``` 复制除 .new 之外的当前目录中的所有内容: ``` $ shopt -s extglob $ scp !(*.new) root@centos7:/tmp/ ``` 示例输出: ``` centos71.log 100 % 4262 1.3MB/s 00:00 centos71.qcow2 100 % 836MB 32.7MB/s 00: 25 meta-data 100 % 47 18.5KB/s 00:00 user-data 100 % 1543 569.7KB/s 00:00 ``` 有关更多信息,请参阅以下手册页: ``` $ man rsync $ man bash $ man scp ``` --- via: <https://www.cyberciti.biz/faq/scp-exclude-files-when-using-command-recursively-on-unix-linux/> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,293
迁移到 Linux:图形操作环境
https://www.linux.com/blog/learn/2017/12/migrating-linux-graphical-environments
2018-01-29T23:31:55
[ "迁移" ]
https://linux.cn/article-9293-1.html
![](/data/attachment/album/201801/29/233159rij9anj6hhiih0ri.jpg) > > 这篇文章对 Linux 图形环境做了一番介绍,展示了在不同的 Linux 发行版上的各种选择。 > > > 这是我们迁移到 Linux 系统系列的第三篇文章。如果你错过了先前的两篇,这里有两文的链接《[入门介绍](/article-9212-1.html)》 和 《[磁盘、文件、和文件系统](/article-9213-1.html)》。本文中,我们将讨论图形操作环境。在 Linux 系统中,你可以依照喜好选择并且定制一个图形界面,你有很大的选择余地,这也是 Linux 优越的体验之一。 一些主流的 Linux 图形界面包括:Cinnamon、Gnome、KDE Plasma、Xfce 和 MATE,总之这里有很多选择。 有一点经常混淆 Linux 新手,虽然某个 Linux 系统分配了一个缺省的图形环境,但是一般你可以随时更换这个图形界面。这和 Windows 或 Mac OS 的惯用者的定势思维不同。安装图形环境是一件独立的事情,很多时候,Linux 和其图形环境的连接并不紧密。此外,你在一个图形环境构建运行的程序同样适用于另一个图形环境。比如说一个为 KDE Plasma 图形环境编写的应用程序完全适用于 Gnome 桌面图形环境。 由于人们熟悉 Windows 和 MacOS 系统,部分 Linux 操作系统的图形环境在一定程度上尝试着去模仿它们,但另一些 Linux 图形界面则是独特的。 下面,我将就一些不同的 Linux 发行版,展示几个 Linux 图形环境。如果你不确定应该采用那个 Linux 发行版,那我建议你从 [Ubuntu](https://www.evernote.com/OutboundRedirect.action?dest=https%3A%2F%2Fwww.ubuntu.com%2Fdownload%2Fdesktop) 开始,获取其长期支持(LTS)的版本(Ubuntu 16.04.3 LTS 正在开发)。Ubuntu 稳定且真的非常好用。 ### 由 Mac 过渡 Elementary OS 发行版提供了和 Mac 系统风格很接近的界面。它的默认图形环境被称作 Pantheon,是一款很适合 Mac 用户过渡使用的图形环境。这款图形界面发行版的屏幕底部有一个停靠栏,专为极简者使用而设计。为了保持简约的风格,很多默认的应用程序甚至都不会有自己的菜单。相反,它们的按钮和控件在应用程序的标题栏上(图 1)。 ![Elementary OS](/data/attachment/album/201801/29/233200wv5joc7g4tvtpb4v.png "Elementary OS") *图 1: Elementary OS Pantheon.* Ubuntu 发行版提供的一个默认的图形界面,也和 Mac 相似。Ubuntu 17.04 或者更老的版本都使用 Unity 图形环境,Unity 停靠栏的默认位置在屏幕的左边,屏幕顶部有一个全局应用程序共享的菜单栏。 ### 由 Windows 过渡 ChaletOS 亦步亦趋模仿 Windows 界面,可以帮助 Windows 用户轻松的过渡到 Linux。ChaletOS 使用的图形环境是 Xfce(图 2)。在屏幕的左下角有一个开始(主)菜单和搜索栏。屏幕的右下角是一个桌面图标和一些通知信息。这看起来和 Windows 非常像,乍一看,可能都会以为桌面跑的是 Windows。 ![ChaletOS](/data/attachment/album/201801/29/233202k11pjqyygx6dmhgs.png) *图 2: ChaletOS with Xfce.* Zorin OS 发行版同样尝试模仿 Windows。 Zorin OS 使用的 Gnome 的改进桌面,工作起来和 Windows 的图形界面很相似。左下角的开始按钮、右下角的通知栏和信息通知栏。开始按钮会弹出一个和 Windows 无异的应用程序列表和搜索框。 ### 独有的图形环境 Gnome 桌面(图 3)是最常用的图形环境之一。许多发行版将 Gnome 作为默认的图形环境。Gnome 并不打算模仿 Windows 或是 MacOS,而是以其自身的优雅和易用为目标。 ![](/data/attachment/album/201801/29/233205g5k8rpxaha138ttx.png) *图 3:openSUSE with Gnome.* Gnome 桌面环境从版本 2 到 版本 3 发生了巨变,Cinnamon 环境为消除该改变带来的不利影响而创造。尽管 Cinnamon 和前辈 Gnome 2 外观不相似,但是它依旧尝试提供一个简约的界面,而且它的功能和 Windows XP 类似。 MATE 图形环境直接模仿于 Gnome 2,在它的屏幕顶部有一个用作设置和存放应用的菜单栏,底部提供了一个应用程序运行选项卡和一些其他组件。 KDE plasma 围绕组件界面而构建,组件可以安装在桌面或是面板上(图 4)。 ![KDE Plasma](/data/attachment/album/201801/29/233208p59qikss9s22ei65.png "KDE Plasma") *图 4: 安装了 KDE Plasma 的 Kubuntu 操作系统。* 没有那个图形环境比另外一个更好。不同的风格适用不同的用户风格。另外,如果选择太多无从下手,那就从 [Ubuntu](https://www.evernote.com/OutboundRedirect.action?dest=https%3A%2F%2Fwww.ubuntu.com%2Fdownload%2Fdesktop) 开始吧。 ### 相似与不同 不同的操作系统处理方式不同,这会给使用者的过渡带来挑战。比如说,菜单栏可能出现在不同的位置,然后设置有可能用不同的选项入口路径。我列举了一些相似或不同地方来帮助减少 Linux 调整。 #### 鼠标 Linux 的鼠标通常和 Windows 与 MacOS 的工作方式有所差异。在 Windows 或 Mac,双击标签,你几乎可以打开任何事物,而这在 Linux 图形界面中很多都被设置为单击。 此外在 Windows 系统中,你通常通过单击窗口获取焦点。在 Linux,很多窗口的焦点获取方式被设置为鼠标悬停,即便鼠标悬停下的窗口并不在屏幕顶端。这种微妙的差异有时候会让人很吃惊。比如说,在 Windows 中,假如有一个后台应用(不在屏幕顶层),你移动鼠标到它的上面,不点击鼠标仅仅转动鼠标滚轮,顶层窗口会滚动。而在 Linux 中,后台窗口(鼠标悬停的那个窗口)会滚动。 #### 菜单 应用菜单是电脑程序的一个主要集中位置,最近似乎可以调整移动菜单栏到不碍事的地方,甚至干脆完全删除。大概,当你迁移到 Linux,你可能找不到你期待的菜单。应用程序菜单会像 MacOS一样出现在全局共享菜单栏内。和很多移动应用程序一样,该菜单可能在“更多选项”的图标里。或者,这个菜单干脆被完全移除被一个按钮取代,正如在 Elementary OS Pantheon 环境里的一些程序一样。 #### 工作空间 很多 Linux 图形环境提供了多个工作空间。一个工作空间包含的正在运行的程序窗口充盈了整个屏幕。切换到不同的工作空间将会改变程序的可见性。这个概念是把当前项目运行使用的全部应用程序分组到一个工作空间,而一些为另一个项目使用的应用程序会被分组到不同的工作空间。 不是每一个人都需要甚至是喜欢工作空间,但是我提到它是因为,作为一个新手,你可能无意间通过一个组合键切换了工作空间,然后,“喂!我的应用程序哪去了?” 如果你看到的还是你熟悉的桌面壁纸,那你可能只是切换了工作空间,你所有的应用程序还在一个工作空间运行,只是现在不可见而已。在很多 Linux 环境中,通过敲击 `Alt+Ctrl` 和一个箭头(上、下、左或右)可以切换工作空间。很有可能发现你的应用程序一直都在另一个工作空间里运行。 当然,如果你刚好喜欢工作空间(很多人都喜欢),然后你就发现了一个 Linux 很有用的默认功能。 #### 设置 许多 Linux 图形环境提供一些类型的设置程序或是面板让你在机器上配置设置。值得注意的是类似 Windows 和 MacOS,Linux 可以配置好很多细节,但不是所有的详细设置都可以在设置程序上找到。但是这些设置项已经足够满足大部分典型的桌面系统,比如选择桌面壁纸,改变熄屏时间,连接打印机等其他一些设置。 和 Windows 或者 MacOS 相比,Linux 的应用程序设置的分组或是命名都有不同的方式。甚至同是 Linux 系统,不同的图形界面也会出现不同的设置,这可能需要时间适应。当然,在你的图形环境中设置配置的问题可以通过在线查询这样不错的方法解决。 #### 应用程序 最后,Linux 的应用程序也可能不同。你可能会发现一些熟悉的应用程序,但是对你来说更多的将会是崭新的应用。比如说,你能在 Linux 上找到 Firefox、Chrome 和 Skype。如果不能找到特定的应用程序,通常你能使用一些替代程序。如果还是不能,那你可以使用 WINE 这样的兼容层来运行 Windows 的应用程序。 在很多 Linux 图形环境中,你可以通过敲击 Windows 的标志键来打开应用程序菜单栏。在其他一些情况中,你不得不点击开始(主)按钮或应用程序菜单。很多图形环境中,你可以通过分类搜索到应用程序而不一定需要它的特定程序名。比如说,你要使用一个你不清楚名字的编辑器程序,这时候,你可以在应用程序菜单栏键的搜索框中键入“editor”字样,它将为你展示一个甚至更多的被认为是编辑器类的应用程序。 为帮你起步,这里列举了一点可能成为 Linux 系统使用的替代程序。 ![](/data/attachment/album/201801/29/233211licpwzsy5pcqtwxw.png) 请注意,Linux 提供了大量的满足你需求的选择,这张表里列举的一点也不完整。 --- via: <https://www.linux.com/blog/learn/2017/12/migrating-linux-graphical-environments> 作者:[John Bonesio](https://www.linux.com/users/johnbonesio) 译者:[CYLeft](https://github.com/CYLeft) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,294
Python 版的 Nmon 分析器:让你远离 excel 宏
https://matthiaslee.com/python-nmon-analyzer-moving-away-from-excel-macros/
2018-01-30T12:12:00
[ "nmon" ]
https://linux.cn/article-9294-1.html
![pyNmonAnalyzer Graph output](/data/attachment/album/201801/30/121232ke7q2v7f44cj2e3c.png "pyNmonAnalyzer Graph output") [Nigel's monitor](http://nmon.sourceforge.net/),也叫做 “Nmon”,是一个很好的监控、记录和分析 Linux/\*nix 系统性能随时间变化的工具。Nmon 最初由 IBM 开发并于 2009 年夏天开源。时至今日 Nmon 已经在所有 Linux 平台和架构上都可用了。它提供了很棒的当前系统统计信息的基于命令行的实时可视化报告,这些统计信息包括 CPU、RAM、网络和磁盘 I/O。然而,Nmon 最棒的特性是可以随着时间的推移记录系统性能快照。 比如:`nmon -f -s 1`。 ![nmon CPU and Disk utilization](/data/attachment/album/201801/30/121232vf9yzxc5tco5spai.png) 会创建一个日志文件,该日志文件最开头是一些系统的元数据(AAA - BBBV 部分),后面是所监控的系统属性的定时快照,比如 CPU 和内存的使用情况。这个输出的文件很难直接由电子表格应用来处理,因此诞生了 [Nmon\_Analyzer](http://www.ibm.com/developerworks/wikis/display/WikiPtype/nmonanalyser) excel 宏。如果你用的是 Windows/Mac 并安装了 Microsoft Office,那么这个工具非常不错。如果没有这个环境那也可以使用 Nmon2rrd 工具,这个工具能将日志文件转换 RRD 输入文件,进而生成图形。这个过程很死板而且有点麻烦。现在出现了一个更灵活的工具,我向你们介绍一下 pyNmonAnalyzer,它提供了一个可定制化的解决方案来生成结构化的 CSV 文件和带有用 [matplotlib](http://matplotlib.org/) 生成的图片的简单 HTML 报告。 ### 入门介绍 系统需求: 从名字中就能看出我们需要有 python。此外 pyNmonAnalyzer 还依赖于 matplotlib 和 numpy。若你使用的是 debian 衍生的系统,则你需要先安装这些包: ``` $ sudo apt-get install python-numpy python-matplotlib ``` #### 获取 pyNmonAnalyzer: 你可以克隆 git 仓库: ``` $ git clone [email protected]:madmaze/pyNmonAnalyzer.git ``` 或者,直接从这里下载:[pyNmonAnalyzer-1.0.zip](https://github.com/madmaze/pyNmonAnalyzer/blob/master/release/pyNmonAnalyzer-1.0.zip) 。(LCTT 译注:这是个 5 年前的项目但是一直在陆陆续续的进行维护) 接下来我们需要一个 Nmon 文件,如果没有的话,可以使用发行版中提供的实例或者自己录制一个样本:`nmon -F test.nmon -s 1 -c 120`,会录制 120 个快照,每秒一个,存储到 test.nmon 文件中。 让我们来看看基本的帮助信息: ``` $ ./pyNmonAnalyzer.py -h usage: pyNmonAnalyzer.py [-h] [-x] [-d] [-o OUTDIR] [-c] [-b] [-r CONFFNAME] input_file nmonParser converts Nmon monitor files into time-sorted CSV/Spreadsheets for easier analysis, without the use of the MS Excel Macro. Also included is an option to build an HTML report with graphs, which is configured through report.config. positional arguments: input_file Input NMON file optional arguments: -h, --help show this help message and exit -x, --overwrite overwrite existing results (Default: False) -d, --debug debug? (Default: False) -o OUTDIR, --output OUTDIR Output dir for CSV (Default: ./data/) -c, --csv CSV output? (Default: False) -b, --buildReport report output? (Default: False) -r CONFFNAME, --reportConfig CONFFNAME Report config file, if none exists: we will write the default config file out (Default: ./report.config) ``` 该工具有两个主要的选项 1. 将 nmon 文件传唤成一系列独立的 CSV 文件 2. 使用 matplotlib 生成带图形的 HTML 报告 下面命令既会生成 CSV 文件,也会生成 HTML 报告: ``` $ ./pyNmonAnalyzer.py -c -b test.nmon ``` 这会创建一个 `./data` 目录,其中有一个存放 CSV 文件的目录 (`./data/csv/`),一个存放 PNG 图片的目录 (`./data/img/`) 以及一个 HTML 报告 (`./data/report.html`)。 默认情况下,HTML 报告中会用图片展示 CPU、磁盘繁忙程度、内存使用情况和网络传输情况。所有这些都定义在一个不言自明的配置文件中 (`report.config`)。目前这个工具还不是特别的灵活,因为 CPU 和 MEM 除了 `on` 和 `off` 外,无法做其他的配置。不过下一步将会改进作图的方法并允许用户灵活地指定针对哪些数据使用哪种作图方法。 目前这些报告还十分的枯燥而且只能打印出基本的几种标记图表,不过它的功能还在不断的完善中。目前在开发的是一个向导来让配置调整变得更容易。如果有任何建议,找到任何 bug 或者有任何功能需求,欢迎与我交流。 --- via: <https://matthiaslee.com/python-nmon-analyzer-moving-away-from-excel-macros/> 作者:[Matthias Lee](https://matthiaslee.com/) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Python Nmon Analyzer: moving away from excel macros [Nigel's monitor](http://nmon.sourceforge.net/), dubbed "Nmon", is a fantastic tool for monitoring, recording and analyzing a Linux/*nix system's performance over time. Nmon was originally developed by IBM and Open Sourced in the summer of 2009. By now Nmon is available on just about every linux platfrom and architecture. It provides a great real-time command line visualization of current system statistics, such as CPU, RAM, Network and Disk I/O. However, Nmon's greatest feature is the capability to record system performance snapshots over time. For example: `nmon -f -s 1` . This will create a log file starting of with some system metadata(Section AAA - BBBV), followed by timed snapshots of all monitored system attributes, such as CPU and Memory usage. This produces a file that is hard to directly interpret with a spreadsheet application, hence the birth of the [Nmon_Analyzer](http://www.ibm.com/developerworks/wikis/display/WikiPtype/nmonanalyser) excel macro. This tool is great, if you have access to Windows/Mac with Microsoft Office installed. If not there is also the Nmon2rrd tool, which generates RRD input files to generate your graphs. This is a very rigid approach and slightly painful. Now to provide a more flexible tool, I am introducing the pyNmonAnalyzer, which aims to provide a customization solution for generating organized CSV files and simple HTML reports with [matplotlib](http://matplotlib.org/) based graphs. #### Getting Started: System requirements: As the name indicates you will need python. Additionally pyNmonAnalyzer depends on matplotlib and numpy. If you are on a debian-derivative system these are the packages you'll need to install: ``` $> sudo apt-get install python-numpy python-matplotlib ``` ###### Getting pyNmonAnalyzer: Either clone the git repository: ``` $> git clone [email protected]:madmaze/pyNmonAnalyzer.git ``` or Download the current release here: [pyNmonAnalyzer-0.1.zip](https://github.com/madmaze/pyNmonAnalyzer/blob/master/release/pyNmonAnalyzer-0.1.zip?raw=true) Next we need an an Nmon file, if you do not already have one, either use the example provided in the release or record a sample: `nmon -F test.nmon -s 1 -c 120` , this will record 120 snapshots at 1 second intervals to test.nmon. Lets have a look at the basic help output: ``` $> ./pyNmonAnalyzer.py -h usage: pyNmonAnalyzer.py [-h] [-x] [-d] [-o OUTDIR] [-c] [-b] [-r CONFFNAME] input_file nmonParser converts Nmon monitor files into time-sorted CSV/Spreadsheets for easier analysis, without the use of the MS Excel Macro. Also included is an option to build an HTML report with graphs, which is configured through report.config. positional arguments: input_file Input NMON file optional arguments: -h, --help show this help message and exit -x, --overwrite overwrite existing results (Default: False) -d, --debug debug? (Default: False) -o OUTDIR, --output OUTDIR Output dir for CSV (Default: ./data/) -c, --csv CSV output? (Default: False) -b, --buildReport report output? (Default: False) -r CONFFNAME, --reportConfig CONFFNAME Report config file, if none exists: we will write the default config file out (Default: ./report.config) ``` There are 2 main options of using this tool - Turn the nmon file into a set of separate CSV file - Generate an HTML report with matplotlib graphs The following command does both: ``` $> ./pyNmonAnalyzer.py -c -b test.nmon ``` This will create a directory called ./data in which you will find a folder of CSV files ("./data/csv/"), a folder of PNG graphs ("./data/img/") and an HTML report ("./data/report.html"). By default the HTML report will include graphs for CPU, Disk Busy, Memory utilization and Network transfers. This is all defined in a self explanitory configuration file, "report.config". At the moment this is not yet very flexible as CPU and MEM are not configurable besides on or off, but one of the next steps will be to refine the plotting approach and to expose more flexibility with which graphs plot which data points. #### Report Example: Currently these reports are very bare bones and only prints out basic labeled graphs, but development is on-going. Currently in development is a wizard that will make adjusting the configurations easier. Please do let me know if you have any suggestions, find any bugs or have feature requests.
9,295
精通 Linux 上的文件搜索
https://www.networkworld.com/article/3227075/linux/mastering-file-searches-on-linux.html
2018-01-30T22:31:40
[ "搜索", "find" ]
https://linux.cn/article-9295-1.html
![](/data/attachment/album/201801/30/223143sx9k09hxykph69ky.jpg) 在 Linux 系统上搜索文件的方法有很多,有的命令很简单,有的很详细。我们的目标是:缩小搜索范围,找到您正在寻找的文件,又不受其他文件的干扰。在今天的文章中,我们将研究一些对文件搜索最有用的命令和选项。我们将涉及: * 快速搜索 * 更复杂的搜索条件 * 组合条件 * 反转条件 * 简单和详细的回应 * 寻找重复的文件 有很多有用的命令可以搜索文件,`find` 命令可能是其中最有名的,但它不是唯一的命令,也不一定总是找到目标文件的最快方法。 ### 快速搜索命令:which 和 locate 搜索文件的最简单的命令可能就是 `which` 和 `locate` 了,但二者都有一些局限性。`which` 命令只会在系统定义的搜索路径中,查找可执行的文件,通常用于识别命令。如果您对输入 `which` 时会运行哪个命令感到好奇,您可以使用命令 `which which`,它会指出对应的可执行文件。 ``` $ which which /usr/bin/which ``` `which` 命令会显示它找到的第一个以相应名称命名的可执行文件(也就是使用该命令时将运行的那个文件),然后停止。 `locate` 命令更大方一点,它可以查找任意数量的文件,但它也有一个限制:仅当文件名被包含在由 `updatedb` 命令构建的数据库时才有效。该文件可能会存储在某个位置,如 `/var/lib/mlocate/mlocate.db`,但不能用 `locate` 以外的任何命令读取。这个文件的更新通常是通过每天通过 cron 运行的 `updatedb` 进行的。 简单的 `find` 命令没有太多限制,不过它需要指定搜索的起点和搜索条件。最简单的 `find` 命令:按文件名搜索文件。如下所示: ``` $ find . -name runme ./bin/runme ``` 如上所示,通过文件名搜索文件系统的当前位置将会搜索所有子目录,除非您指定了搜索深度。 ### 不仅仅是文件名 `find` 命令允许您搜索除文件名以外的多种条件,包括文件所有者、组、权限、大小、修改时间、缺少所有者或组,和文件类型等。除了查找文件外,您还可以删除文件、对其进行重命名、更改所有者、更改权限和对找到的文件运行几乎任何命令。 下面两条命令会查找:在当前目录中 root 用户拥有的文件,以及不被指定用户(在本例中为 shs)所拥有的文件。在这个例子中,两个输出是一样的,但并不总是如此。 ``` $ find . -user root -ls 396926 0 lrwxrwxrwx 1 root root 21 Sep 21 09:03 ./xyz -> /home/peanut/xyz $ find . ! -user shs -ls 396926 0 lrwxrwxrwx 1 root root 21 Sep 21 09:03 ./xyz -> /home/peanut/xyz ``` 感叹号 `!` 字符代表“非”:反转跟随其后的条件。 下面的命令将查找具有特定权限的文件: ``` $ find . -perm 750 -ls 397176 4 -rwxr-x--- 1 shs shs 115 Sep 14 13:52 ./ll 398209 4 -rwxr-x--- 1 shs shs 117 Sep 21 08:55 ./get-updates 397145 4 drwxr-x--- 2 shs shs 4096 Sep 14 15:42 ./newdir ``` 接下来的命令显示具有 777 权限的非符号链接文件: ``` $ sudo find /home -perm 777 ! -type l -ls 397132 4 -rwxrwxrwx 1 shs shs 18 Sep 15 16:06 /home/shs/bin/runme 396949 4 -rwxrwxrwx 1 root root 558 Sep 21 11:21 /home/oops ``` 以下命令将查找大小超过千兆字节的文件。请注意,我们找到了一个非常有趣的文件。它以 ELF core 文件格式表示了该系统的物理内存。 ``` $ sudo find / -size +1G -ls 4026531994 0 -r-------- 1 root root 140737477881856 Sep 21 11:23 /proc/kcore 1444722 15332 -rw-rw-r-- 1 shs shs 1609039872 Sep 13 15:55 /home/shs/Downloads/ubuntu-17.04-desktop-amd64.iso ``` 只要您知道 `find` 命令是如何描述文件类型的,就可以通过文件类型来查找文件。 ``` b = 块设备文件 c = 字符设备文件 d = 目录 p = 命名管道 f = 常规文件 l = 符号链接 s = 套接字 D = 门(仅限 Solaris) ``` 在下面的命令中,我们要寻找符号链接和套接字: ``` $ find . -type l -ls 396926 0 lrwxrwxrwx 1 root root 21 Sep 21 09:03 ./whatever -> /home/peanut/whatever $ find . -type s -ls 395256 0 srwxrwxr-x 1 shs shs 0 Sep 21 08:50 ./.gnupg/S.gpg-agent ``` 您还可以根据 inode 号来搜索文件: ``` $ find . -inum 397132 -ls 397132 4 -rwx------ 1 shs shs 18 Sep 15 16:06 ./bin/runme ``` 另一种通过 inode 搜索文件的方法是使用 `debugfs` 命令。在大的文件系统上,这个命令可能比 `find` 快得多,您可能需要安装 icheck。 ``` $ sudo debugfs -R 'ncheck 397132' /dev/sda1 debugfs 1.42.13 (17-May-2015) Inode Pathname 397132 /home/shs/bin/runme ``` 在下面的命令中,我们从主目录(`~`)开始,限制搜索的深度(即我们将搜索子目录的层数),并只查看在最近一天内创建或修改的文件(`mtime` 设置)。 ``` $ find ~ -maxdepth 2 -mtime -1 -ls 407928 4 drwxr-xr-x 21 shs shs 4096 Sep 21 12:03 /home/shs 394006 8 -rw------- 1 shs shs 5909 Sep 21 08:18 /home/shs/.bash_history 399612 4 -rw------- 1 shs shs 53 Sep 21 08:50 /home/shs/.Xauthority 399615 4 drwxr-xr-x 2 shs shs 4096 Sep 21 09:32 /home/shs/Downloads ``` ### 不仅仅是列出文件 使用 `-exec` 选项,在您使用 `find` 命令找到文件后可以以某种方式更改文件。您只需参照 `-exec` 选项即可运行相应的命令。 ``` $ find . -name runme -exec chmod 700 {} \; $ find . -name runme -ls 397132 4 -rwx------ 1 shs shs 18 Sep 15 16:06 ./bin/runme ``` 在这条命令中,`{}` 代表文件名。此命令将更改当前目录和子目录中任何名为 `runme` 的文件的权限。 把您想运行的任何命令放在 `-exec` 选项之后,并使用类似于上面命令的语法即可。 ### 其他搜索条件 如上面的例子所示,您还可以通过其他条件进行搜索:文件的修改时间、所有者、权限等。以下是一些示例。 #### 根据用户查找文件 ``` $ sudo find /home -user peanut /home/peanut /home/peanut/.bashrc /home/peanut/.bash_logout /home/peanut/.profile /home/peanut/examples.desktop ``` #### 根据权限查找文件 ``` $ sudo find /home -perm 777 /home/shs/whatever /home/oops ``` #### 根据修改时间查找文件 ``` $ sudo find /home -mtime +100 /home/shs/.mozilla/firefox/krsw3giq.default/gmp-gmpopenh264/1.6/gmpopenh264.info /home/shs/.mozilla/firefox/krsw3giq.default/gmp-gmpopenh264/1.6/libgmpopenh264.so ``` #### 通过比较修改时间查找文件 像这样的命令可以让您找到修改时间较近的文件。 ``` $ sudo find /var/log -newer /var/log/syslog /var/log/auth.log ``` ### 寻找重复的文件 如果您正在清理磁盘空间,则可能需要删除较大的重复文件。确定文件是否真正重复的最好方法是使用 `fdupes` 命令。此命令使用 md5 校验和来确定文件是否具有相同的内容。使用 `-r`(递归)选项,`fdupes` 将在一个目录下并查找具有相同校验和而被确定为内容相同的文件。 如果以 root 身份运行这样的命令,您可能会发现很多重复的文件,但是很多文件都是创建时被添加到主目录的启动文件。 ``` # fdupes -rn /home > /tmp/dups.txt # more /tmp/dups.txt /home/jdoe/.profile /home/tsmith/.profile /home/peanut/.profile /home/rocket/.profile /home/jdoe/.bashrc /home/tsmith/.bashrc /home/peanut/.bashrc /home/rocket/.bashrc ``` 同样,您可能会在 `/usr` 中发现很多重复的但不该删除的配置文件。所以,请谨慎利用 `fdupes` 的输出。 `fdupes` 命令并不总是很快,但是要记住,它正在对许多文件运行校验和来做比较,你可能会意识到它是多么有效。 ### 总结 有很多方法可以在 Linux 系统上查找文件。如果您可以描述清楚您正在寻找什么,上面的命令将帮助您找到目标。 --- via: <https://www.networkworld.com/article/3227075/linux/mastering-file-searches-on-linux.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 译者:[jessie-pang](https://github.com/jessie-pang) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,296
从 ISO 和在线仓库创建一个 Yum 仓库
http://linuxtechlab.com/creating-yum-repository-iso-online-repo/
2018-01-30T22:45:46
[ "Yum", "仓库" ]
https://linux.cn/article-9296-1.html
![](/data/attachment/album/201801/30/224540dlqk8tn1sf8lgrgp.jpg) Yum 是 Centos/RHEL/Fedora 中最重要的工具之一。尽管在 Fedora 的最新版本中,它已经被 DNF 所取代,但这并不意味着它自生自灭了。它仍然被广泛用于安装 rpm 包,我们已经在前面的教程([**在这里阅读**](http://linuxtechlab.com/using-yum-command-examples/))中用示例讨论了 Yum。 在本教程中,我们将学习创建一个本地 Yum 仓库,首先使用系统的 ISO 镜像,然后创建一个在线 Yum 仓库的镜像。 ### 用 DVD ISO 创建 Yum 我们在本教程中使用 Centos 7 dvd,同样的过程也应该可以用在 RHEL 7 上。 首先在根文件夹中创建一个名为 Yum 的目录 ``` $ mkdir /YUM ``` 然后挂载 Centos 7 ISO: ``` $ mount -t iso9660 -o loop /home/dan/Centos-7-x86_x64-DVD.iso /mnt/iso/ ``` 接下来,从挂载的 ISO 中复制软件包到 `/YUM` 中。当所有的软件包都被复制到系统中后,我们将安装创建 Yum 所需的软件包。打开 `/YUM` 并安装以下 RPM 包: ``` $ rpm -ivh deltarpm $ rpm -ivh python-deltarpm $ rpm -ivh createrepo ``` 安装完成后,我们将在 `/etc/yum.repos.d` 中创建一个名 为 `local.repo` 的文件,其中包含所有的 Yum 信息。 ``` $ vi /etc/yum.repos.d/local.repo ``` ``` LOCAL REPO] Name=Local YUM baseurl=file:///YUM gpgcheck=0 enabled=1 ``` 保存并退出文件。接下来,我们将通过运行以下命令来创建仓库数据。 ``` $ createrepo -v /YUM ``` 创建仓库数据需要一些时间。一切完成后,请运行: ``` $ yum clean all ``` 清理缓存,然后运行: ``` $ yum repolist ``` 检查所有仓库列表。你应该在列表中看到 `local.repo`。 ### 使用在线仓库创建镜像 Yum 仓库 创建在线 Yum 的过程与使用 ISO 镜像创建 Yum 类似,只是我们将从在线仓库而不是 ISO 中获取 rpm 软件包。 首先,我们需要找到一个在线仓库来获取最新的软件包。建议你找一个离你位置最近的在线 Yum 仓库,以优化下载速度。我们将使用下面的镜像,你可以从 [CENTOS 镜像列表](http://mirror.centos.org/centos/)中选择一个离你最近的镜像。 选择镜像之后,我们将使用 `rsync` 将该镜像与我们的系统同步,但在此之前,请确保你服务器上有足够的空间。 ``` $ rsync -avz rsync://mirror.fibergrid.in/centos/7.2/os/x86_64/Packages/s/ /YUM ``` 同步将需要相当长一段时间(也许一个小时),这取决于你互联网的速度。同步完成后,我们将更新我们的仓库数据。 ``` $ createrepo - v /YUM ``` 我们的 Yum 已经可以使用了。我们可以创建一个 cron 任务来根据你的需求每天或每周定时地自动更新仓库数据。 要创建一个用于同步仓库的 cron 任务,请运行: ``` $ crontab -e ``` 并添加以下行 ``` 30 12 * * * rsync -avz http://mirror.centos.org/centos/7/os/x86_64/Packages/ /YUM ``` 这会在每晚 12:30 同步 Yum。还请记住在 `/etc/yum.repos.d` 中创建仓库配置文件,就像我们上面所做的一样。 就是这样,你现在使用你自己的 Yum 仓库了。如果你喜欢它,请分享这篇文章,并在下面的评论栏留下你的意见/疑问。 --- via: <http://linuxtechlab.com/creating-yum-repository-iso-online-repo/> 作者:[Shusain](http://linuxtechlab.com/author/shsuain/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,297
用命令行查看比特币等加密货币的价格
https://www.ostechnix.com/coinmon-check-cryptocurrency-prices-commandline/
2018-01-30T23:14:32
[ "比特币", "Coinmon" ]
https://linux.cn/article-9297-1.html
![配图](/data/attachment/album/201801/30/231433vbz3szbb77hybasa.jpg) 前段时间,我们发布了一个关于 [Cli-Fyi](https://www.ostechnix.com/cli-fyi-quick-easy-way-fetch-information-ips-emails-domains-lots/) 的指南 - 一个可能有用的命令行查询工具。使用 Cli-Fyi,我们可以很容易地了解加密货币的最新价格和许多其他有用的细节。今天,我们将看到另一个名为 “Coinmon” 的加密货币价格查看工具。不像 Cli.Fyi,Coinmon 只能用来查看不同加密货币的价格。没有其他功能!Coinmon 会在终端上检查加密货币的价格。它将从 [coinmarketcap.com](https://coinmarketcap.com/) API 获取所有详细信息。对于那些 **加密货币投资者**和**工程师**来说是非常有用的。 ### 安装 Coinmon 确保你的系统上安装了 Node.js 和 Npm。如果你的机器上没有安装 Node.js 和/或 npm,请参考以下链接进行安装。 安装完 Node.js 和 Npm 后,从终端运行以下命令安装 Coinmon。 ``` sudo npm install -g coinmon ``` ### 从命令行查看加密货币价格 运行以下命令查看市值排名的前 10 位的加密货币: ``` coinmon ``` 示例输出: ![](/data/attachment/album/201801/30/231433tb7rj2g232h52h07.png) 如我所说,如果你不带任何参数运行 Coinmon,它将显示前 10 位加密货币。你还可以使用 `-t` 标志查看最高的 n 位加密货币,例如 20。 ``` coinmon -t 20 ``` 所有价格默认以美元显示。你还可以使用 `-c` 标志将价格从美元转换为另一种货币。 例如,要将价格转换为 INR(印度卢比),运行: ``` coinmon -c inr ``` ![](/data/attachment/album/201801/30/231433wup1k1rvx8r1k5rt.png) 目前,Coinmon 支持 AUD、BRL、CAD、CHF、CLP、CNY、CZK、DKK、EUR、GBP、HKD、HUF、IDR、ILS、INR、JPY、KRW、MXN、MYR、NOK、NZD、PHP、PKR、PLN、RUB、SEK、SGD、THB、TRY、TWD、ZAR 这些货币。 也可以使用加密货币的符号来搜索价格。 ``` coinmon -f btc ``` 这里,`btc` 是比特币的符号。你可以在[**这里**](https://en.wikipedia.org/wiki/List_of_cryptocurrencies)查看所有可用的加密货币的符号。 有关更多详情,请参阅 coinmon 的帮助部分: ``` $ coinmon -h Usage: coinmon [options] Options: -V, --version output the version number -c, --convert [currency] Convert to your fiat currency (default: usd) -f, --find [symbol] Find specific coin data with coin symbol (can be a comma seperated list) (default: ) -t, --top [index] Show the top coins ranked from 1 - [index] according to the market cap (default: null) -H, --humanize [enable] Show market cap as a humanized number, default true (default: true) -h, --help output usage information ``` 希望这个有帮助。会有更好的东西。敬请关注! 干杯! --- via: <https://www.ostechnix.com/coinmon-check-cryptocurrency-prices-commandline/> 作者:[SK](https://www.ostechnix.com/author/sk/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,298
什么是 .bashrc,为什么要编辑 .bashrc?
https://www.maketecheasier.com/what-is-bashrc/
2018-01-31T14:55:02
[ ".bashrc" ]
https://linux.cn/article-9298-1.html
![](/data/attachment/album/201801/31/145506vz6pxrtzqoxtmgou.png) 你的 home 目录下藏着很多隐藏文件。如果你在运行 macOS 或者主流的 Linux 发行版的话,你就会在靠近隐藏文件列表的上方看见一个名为 `.bashrc` 的文件。那么什么是 `.bashrc`,编辑 `.bashrc` 又有什么用呢? ![finder-find-bashrc](/data/attachment/album/201801/31/145506am14t1jmx4tjzq17.png "finder-find-bashrc") 如果你运行一个基于 Unix 或者类 Unix 的操作系统,bash 很有可能是作为默认终端被安装的。虽然存在很多[不同的 shell](https://www.maketecheasier.com/alternative-linux-shells/),bash 却是最常见或许也是最主流的。如果你不明白那意味着什么,bash 是一个能解释你输入进终端程序的东西,并且基于你的输入来运行命令。它在一定程度上支持使用脚本来定制功能,这时候就要用到 `.bashrc` 了。 为了加载你的配置,bash 在每次启动时都会加载 `.bashrc` 文件的内容。每个用户的 home 目录都有这个 shell 脚本。它用来存储并加载你的终端配置和环境变量。 终端配置可以包含很多不同的东西。最常见的,`.bashrc` 文件包含用户想要用的别名。别名允许用户通过更短的名字或替代的名字来指向命令,对于经常在终端下工作的人来说这可是一个省时利器。 ![terminal-edit-bashrc-1](/data/attachment/album/201801/31/145507bxspgcpiizi4nnng.png "terminal-edit-bashrc-1") 你可以在任何终端文本编辑器上编辑 `.bashrc`。在接下来的例子中我们将使用 `nano`。 要使用 `nano` 来编辑 `.bashrc`,在终端中调用以下命令: ``` nano ~/.bashrc ``` 如果你之前从没有编辑过 `.bashrc` 的话,你也许会发现它是空的。这没关系!如果不是的话,你可以随意在任一行添加你的配置。 你对 bashrc 所做的任何修改将在下一次启动终端时生效。如果你想立刻生效的话,运行下面的命令: ``` source ~/.bashrc ``` 你可以添加到任何 `.bashrc` 的位置,随意使用命令(通过 `#`)来组织你的代码。 编辑 `.bashrc` 需要遵循 [bash 脚本格式](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html)。如果你不知道如何用 bash 编写脚本的话,有很多在线资料可供查阅。这是一本相当全面的[介绍指南](https://www.digitalocean.com/community/tutorials/an-introduction-to-useful-bash-aliases-and-functions),包含一些我们没能在这里提及的 bashrc 的方面。 **相关**: [如何在 Linux 启动时以 root 权限运行 bash 脚本](https://www.maketecheasier.com/run-bash-script-as-root-during-startup-linux/ "How to Run Bash Script as Root During Startup on Linux") 有一些有用的小技巧能使你的终端体验将更高效,也更用户友好。 ### 为什么我要编辑 bashrc ? #### Bash 提示符 bash 提示符允许你自定义你的终端,并让它在你运行命令时显示提示。自定义的 bash 提示符着实能提高你在终端的工作效率。 看看这些即[有用](https://www.maketecheasier.com/8-useful-and-interesting-bash-prompts/)又[有趣](https://www.maketecheasier.com/more-useful-and-interesting-bash-prompts/)的 bash 提示符,你可以把它们添加到你的 `.bashrc` 里。 #### 别名 ![terminal-edit-bashrc-3](/data/attachment/album/201801/31/145509t7n1tnnqwnnn6tnn.png "terminal-edit-bashrc-3") 别名允许你使用简写的代码来执行你想要的某种格式的某个命令。让我们用 `ls` 命令来举个例子吧。`ls` 命令默认显示你目录里的内容。这挺有用的,不过显示目录的更多信息,或者显示目录下的隐藏内容,往往更加有用。因此,有个常见的别名就是 `ll`,用来运行 `ls -lha` 或者其他类似的命令。这样就能显示文件的大部分信息,找出隐藏的文件,并能以“能被人类阅读”的单位显示文件大小,而不是用“块”作为单位。 你需要按照下面这样的格式书写别名: ``` alias ll = "ls -lha" ``` 左边输入你想设置的别名,右边引号里是要执行的命令。你可以用这种方法来创建命令的短版本,防止出现常见的拼写错误,或者让一个命令总是带上你想要的参数来运行。你也可以用你喜欢的缩写来规避讨厌或容易忘记的语法。这是一些[常见的别名的用法](https://www.maketecheasier.com/install-software-in-various-linux-distros/#aliases),你可以添加到你的 `.bashrc` 里。 #### 函数 ![terminal-edit-bashrc-2](/data/attachment/album/201801/31/145509hbz59nzan249fs95.png "terminal-edit-bashrc-2") 除了缩短命令名,你也可以用 bash 函数组合多个命令到一个操作。这些命令可以很复杂,但是它们大多遵循这种语法: ``` function_name () { command_1 command_2 } ``` 下面的命令组合了 `mkdir` 和 `cd` 命令。输入 `md folder_name` 可以在你的工作目录创建一个名为“folder\_name”的目录并立刻导航进入。 ``` md () { mkdir -p $1 cd $1 } ``` 如你所见,函数中的 `$1` 代表第一个参数,就是你在函数名后紧跟着输入的文本。 ### 总结 不像某些自定义终端的方法,变动 bashrc 是非常直接且低风险的。即使你一不小心全搞砸了,你也可以随时删掉 bashrc 文件然后重新来一遍。试试看吧,你会惊叹于你提高的生产力的。 --- via: <https://www.maketecheasier.com/what-is-bashrc/> 作者:[Alexander Fox](https://www.maketecheasier.com/author/alexfox/) 译者:[heart4lor](https://github.com/heart4lor) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![A photograph of an Ubuntu terminal prompt.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-00-featured-image.jpg) There are a number of hidden files tucked away in your home directory. If you run macOS or a popular Linux distribution, you’ll see the “.bashrc” file near the top of your hidden files. This guide explains what the .bashrc file does and why you should edit and customize it. ## What Is .bashrc? If you run a Unix-based or Unix-like operating system, you likely have bash installed as your default terminal. While many [different shells](https://www.maketecheasier.com/alternative-linux-shells/) exist, bash is both the most common and, likely, the most popular. If you don’t know what that means, bash interprets your typed input in the Terminal program and runs commands based on your input. It allows for some degree of customization using scripting, which is where .bashrc comes in. ![finder-find-bashrc A screenshot of the bashrc file inside a file manager.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-01-bashrc-file-nautilus.png) The .bashrc file contains a list of customization options for the bash shell and is loaded at each launch. The .bashrc file is found in the Home user directory. The . (dot) in front of the file name means that it is hidden from plain view. You will need to activate the “View Hidden Files” option to view it. ## How Can I Edit .bashrc? You can edit .bashrc in any text editor. You can also use [nano](https://www.maketecheasier.com/linux-nano-text-editor-beginner-guide/) to edit it in the Terminal. nano ~/.bashrc If you have not edited your .bashrc file before, you may find that it’s empty. That’s fine! If not, feel free to put your additions on any line. Edits in .bashrc have to follow [bash’s scripting format](https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html). If you don’t know how to script with bash, there are a number of online resources. This guide represents a beginner-friendly introduction into the [aspects of Bash that are not mentioned here](https://www.maketecheasier.com/beginners-guide-scripting-linux/). Any changes you make to .bashrc will be applied the next time you launch the terminal. If you want to apply them immediately, run the command below: source ~/.bashrc **Note**: you can add to .bashrc wherever you would like, but feel free to use comment (lines preceded by `#` ) to document your code. ## .bashrc Customization Tips There are a couple of useful tricks to make your terminal experience more efficient and user-friendly. ### 1. Aliases Aliases allow you to create a shorter version of a long command. For example, [the command ls](https://www.maketecheasier.com/linux-ls-commands/) is often used to display the contents of your directory. You can also use `ls -lha` to display the content with more detail. Now there is an alias `ll` , which is set to run `ls -lha` . Just type `ll` in the terminal, and it will run the `ls -lha` command. ![terminal-edit-bashrc-3 A terminal showing a list of basic aliases.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-03-sample-alias-list.png) You’ll need to format your aliases like so: alias ll="ls -lha" Type the text you want to replace on the left and the command on the right between quotes. Use this to create shorter versions of the command, guard against common typos, or force a command to always run with your favored flags. You can also circumvent annoying or easy-to-forget syntax with your own preferred shorthand. ### 2. Functions In addition to shorthand command names, you can combine multiple commands into a single operation using bash functions. They can get pretty complicated, but they generally follow this syntax: function_name () { command_1 command_2 } For example, the command below combines `mkdir` and `cd` . Typing `md folder_name` creates a directory named “folder_name” in your working directory and navigates there immediately. md () { mkdir -p $1 cd $1 } The `$1` you see in the function represents the first argument, which is the text you type immediately after the function name. ### 3. Adding a Simple Bash Prompt You can also use the .bashrc file to create a custom shell prompt. The shell prompt is a line of text that shows up at the start of every terminal input line. This can contain either static information, such as your system’s name or dynamic scripts that change depending on the shell’s current working directory. Here are several [interesting bash prompts](https://www.maketecheasier.com/8-useful-and-interesting-bash-prompts/) you can add to your .bashrc file. ### 4. Modify the PATH Variable The PATH variable is an important variable that tells your shell where to find scripts and binaries for the current session. You can use the .bashrc file to store/change the content of your PATH variable. This is useful in cases where you want to run your own programs from a custom directory. To modify the PATH variable, add the following line of code to the end of your .bashrc: PATH="$PATH:" This will tell your shell to load the default value of PATH before loading any custom arguments. ![A screenshot showing the PATH variable referencing itself.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-12-path-variable-import-system-default.png) Now add your own directories to the end of this PATH variable. PATH=":/home/$USER/bin:/home/$USER/git" ![A screenshot showing a PATH variable with custom directories.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-13-path-variable-add-custom-path.png) ### 5. Exporting New Environment Variables Environment variables are containers that hold session-specific values for a program or system process. It contains strings that give programs either an option or a resource that it can use while running. For example, some programs use the “POSTGRESQL_DATABASE” environment variable when they link to an external database process: POSTGRESQL_DATABASE="postgres://ramces:password@localhost:5432/db" ![A screenshot showing a custom environment variable.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-17-sample-custom-environment-variable.png) Export the variable to your shell. This will convert it from a regular shell variable to an environment variable: POSTGRESQL_DATABASE="postgres://ramces:password@localhost:5432/db" export POSTGRESQL_DATABASE ![A screenshot showing the export command and the new environment variable.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-18-export-environment-variable.png) ### 6. Linking .bashrc with .bash_profile The difference between .bashrc and .bash_profile is one of the biggest points of confusion for a novice Linux user. bash_profile only runs once during login, while .bashrc runs whenever a new shell starts. However, this murky division means that it is possible to mix up the two and fail to run the command that you want to run. One quick way to solve this issue is by ensuring that .bashrc runs as soon as .bash_profile loads. Add the following line of code to the end of the .bashrc file: if [ -f ~/.bashrc ]; then . ~/.bashrc fi ![A terminal showing a basic if statement in bash_profile.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-21-basic-bash-profile-configuration.png) This small block of code will tell the shell to check whether a .bashrc file exists in your home directory. If it finds one, Bash will load the file and run its commands in the current shell instance. **Good to know: **while Bash is often used as a terminal interface for your system, you can also [use Python to automate your computing tasks](https://www.maketecheasier.com/useful-python-one-liners/). ## Frequently Asked Questions ### Will my .bashrc file work with other Linux shells? The developers of Bash designed the .bashrc file to work only with the Bash shell. However, it is important to note that most of the commands inside a .bashrc file are cross-compatible with some Unix-like shells. For example, you can copy the contents of a .bashrc file to its Korn shell counterpart, .kshrc, and it will still work. ### Is it possible to set my default file permissions using Bash? Yes. To do this, you need to add the `umask` command at the end of your .bashrc file. This is a simple program that sets the bit mask on the permission bits that you want to set. For example, the command `umask 027` is the equivalent of running `sudo chmod -R 750 ./directory` . Image credit: [Unsplash](https://unsplash.com/photos/xbEVM6oJ1Fs). All alterations and screenshots by Ramces Red. Our latest tutorials delivered straight to your inbox
9,299
如何在 Linux 上用 Fail2Ban 保护服务器免受暴力攻击
https://www.2daygeek.com/how-to-install-setup-configure-fail2ban-on-linux/
2018-01-31T15:18:33
[ "Fail2Ban", "防火墙" ]
https://linux.cn/article-9299-1.html
![](/data/attachment/album/201801/31/151825ej2k38zwwqwhrmkw.jpg) Linux 管理员的一个重要任务是保护服务器免受非法攻击或访问。 默认情况下,Linux 系统带有配置良好的防火墙,比如iptables、Uncomplicated Firewall(UFW),ConfigServer Security Firewall(CSF)等,可以防止多种攻击。 任何连接到互联网的机器都是恶意攻击的潜在目标。 有一个名为 Fail2Ban 的工具可用来缓解服务器上的非法访问。 ### 什么是 Fail2Ban? [Fail2Ban](https://github.com/fail2ban/fail2ban) 是一款入侵防御软件,可以保护服务器免受暴力攻击。 它是用 Python 编程语言编写的。 Fail2Ban 基于auth 日志文件工作,默认情况下它会扫描所有 auth 日志文件,如 `/var/log/auth.log`、`/var/log/apache/access.log` 等,并禁止带有恶意标志的IP,比如密码失败太多,寻找漏洞等等标志。 通常,Fail2Ban 用于更新防火墙规则,用于在指定的时间内拒绝 IP 地址。 它也会发送邮件通知。 Fail2Ban 为各种服务提供了许多过滤器,如 ssh、apache、nginx、squid、named、mysql、nagios 等。 Fail2Ban 能够降低错误认证尝试的速度,但是它不能消除弱认证带来的风险。 这只是服务器防止暴力攻击的安全手段之一。 ### 如何在 Linux 中安装 Fail2Ban Fail2Ban 已经与大部分 Linux 发行版打包在一起了,所以只需使用你的发行包版的包管理器来安装它。 对于 Debian / Ubuntu,使用 [APT-GET 命令](https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/)或 [APT 命令](https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/)安装。 ``` $ sudo apt install fail2ban ``` 对于 Fedora,使用 [DNF 命令](https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/)安装。 ``` $ sudo dnf install fail2ban ``` 对于 CentOS/RHEL,启用 [EPEL 库](https://www.2daygeek.com/install-enable-epel-repository-on-rhel-centos-scientific-linux-oracle-linux/)或 [RPMForge](https://www.2daygeek.com/install-enable-repoforge-rpmforge-repository-on-rhel-centos-sl/) 库,使用 [YUM 命令](https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/)安装。 ``` $ sudo yum install fail2ban ``` 对于 Arch Linux,使用 [Pacman 命令](https://www.2daygeek.com/pacman-command-examples-manage-packages-arch-linux-system/)安装。 ``` $ sudo pacman -S fail2ban ``` 对于 openSUSE , 使用 [Zypper命令](https://www.2daygeek.com/zypper-command-examples-manage-packages-opensuse-system/)安装。 ``` $ sudo zypper in fail2ban ``` ### 如何配置 Fail2Ban 默认情况下,Fail2Ban 将所有配置文件保存在 `/etc/fail2ban/` 目录中。 主配置文件是 `jail.conf`,它包含一组预定义的过滤器。 所以,不要编辑该文件,这是不可取的,因为只要有新的更新,配置就会重置为默认值。 只需在同一目录下创建一个名为 `jail.local` 的新配置文件,并根据您的意愿进行修改。 ``` # cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local ``` 默认情况下,大多数选项都已经配置的很完美了,如果要启用对任何特定 IP 的访问,则可以将 IP 地址添加到 `ignoreip` 区域,对于多个 IP 的情况,用空格隔开 IP 地址。 配置文件中的 `DEFAULT` 部分包含 Fail2Ban 遵循的基本规则集,您可以根据自己的意愿调整任何参数。 ``` # nano /etc/fail2ban/jail.local [DEFAULT] ignoreip = 127.0.0.1/8 192.168.1.100/24 bantime = 600 findtime = 600 maxretry = 3 destemail = [email protected] ``` * `ignoreip`:本部分允许我们列出 IP 地址列表,Fail2Ban 不会禁止与列表中的地址匹配的主机 * `bantime`:主机被禁止的秒数 * `findtime`:如果在最近 `findtime` 秒期间已经发生了 `maxretry` 次重试,则主机会被禁止 * `maxretry`:是主机被禁止之前的失败次数 ### 如何配置服务 Fail2Ban 带有一组预定义的过滤器,用于各种服务,如 ssh、apache、nginx、squid、named、mysql、nagios 等。 我们不希望对配置文件进行任何更改,只需在服务区域中添加 `enabled = true` 这一行就可以启用任何服务。 禁用服务时将 `true` 改为 `false` 即可。 ``` # SSH servers [sshd] enabled = true port = ssh logpath = %(sshd_log)s backend = %(sshd_backend)s ``` * `enabled`: 确定服务是打开还是关闭。 * `port`:指明特定的服务。 如果使用默认端口,则服务名称可以放在这里。 如果使用非传统端口,则应该是端口号。 * `logpath`:提供服务日志的位置 * `backend`:指定用于获取文件修改的后端。 ### 重启 Fail2Ban 进行更改后,重新启动 Fail2Ban 才能生效。 ``` [For SysVinit Systems] # service fail2ban restart [For systemd Systems] # systemctl restart fail2ban.service ``` ### 验证 Fail2Ban iptables 规则 你可以使用下面的命令来确认是否在防火墙中成功添加了Fail2Ban iptables 规则。 ``` # iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination f2b-apache-auth tcp -- anywhere anywhere multiport dports http,https f2b-sshd tcp -- anywhere anywhere multiport dports 1234 ACCEPT tcp -- anywhere anywhere tcp dpt:1234 Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination Chain f2b-apache-auth (1 references) target prot opt source destination RETURN all -- anywhere anywhere Chain f2b-sshd (1 references) target prot opt source destination RETURN all -- anywhere anywhere ``` ### 如何测试 Fail2Ban 我做了一些失败的尝试来测试这个。 为了证实这一点,我要验证 `/var/log/fail2ban.log` 文件。 ``` 2017-11-05 14:43:22,901 fail2ban.server [7141]: INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.9.6 2017-11-05 14:43:22,987 fail2ban.database [7141]: INFO Connected to fail2ban persistent database '/var/lib/fail2ban/fail2ban.sqlite3' 2017-11-05 14:43:22,996 fail2ban.database [7141]: WARNING New database created. Version '2' 2017-11-05 14:43:22,998 fail2ban.jail [7141]: INFO Creating new jail 'sshd' 2017-11-05 14:43:23,002 fail2ban.jail [7141]: INFO Jail 'sshd' uses poller {} 2017-11-05 14:43:23,019 fail2ban.jail [7141]: INFO Initiated 'polling' backend 2017-11-05 14:43:23,019 fail2ban.filter [7141]: INFO Set maxRetry = 5 2017-11-05 14:43:23,020 fail2ban.filter [7141]: INFO Set jail log file encoding to UTF-8 2017-11-05 14:43:23,020 fail2ban.filter [7141]: INFO Added logfile = /var/log/auth.log 2017-11-05 14:43:23,021 fail2ban.actions [7141]: INFO Set banTime = 600 2017-11-05 14:43:23,021 fail2ban.filter [7141]: INFO Set findtime = 600 2017-11-05 14:43:23,022 fail2ban.filter [7141]: INFO Set maxlines = 10 2017-11-05 14:43:23,070 fail2ban.server [7141]: INFO Jail sshd is not a JournalFilter instance 2017-11-05 14:43:23,081 fail2ban.jail [7141]: INFO Jail 'sshd' started 2017-11-05 14:43:23,763 fail2ban.filter [7141]: INFO [sshd] Found 103.5.134.167 2017-11-05 14:43:23,763 fail2ban.filter [7141]: INFO [sshd] Found 103.5.134.167 2017-11-05 14:43:23,764 fail2ban.filter [7141]: INFO [sshd] Found 181.129.54.170 2017-11-05 14:43:23,764 fail2ban.filter [7141]: INFO [sshd] Found 181.129.54.170 2017-11-05 14:43:23,765 fail2ban.filter [7141]: INFO [sshd] Found 181.129.54.170 2017-11-05 14:43:23,765 fail2ban.filter [7141]: INFO [sshd] Found 181.129.54.170 2017-11-05 15:19:06,192 fail2ban.server [7141]: INFO Stopping all jails 2017-11-05 15:19:06,874 fail2ban.jail [7141]: INFO Jail 'sshd' stopped 2017-11-05 15:19:06,879 fail2ban.server [7141]: INFO Exiting Fail2ban 2017-11-05 15:19:07,123 fail2ban.server [8528]: INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.9.6 2017-11-05 15:19:07,123 fail2ban.database [8528]: INFO Connected to fail2ban persistent database '/var/lib/fail2ban/fail2ban.sqlite3' 2017-11-05 15:19:07,126 fail2ban.jail [8528]: INFO Creating new jail 'sshd' 2017-11-05 15:19:07,129 fail2ban.jail [8528]: INFO Jail 'sshd' uses poller {} 2017-11-05 15:19:07,141 fail2ban.jail [8528]: INFO Initiated 'polling' backend 2017-11-05 15:19:07,142 fail2ban.actions [8528]: INFO Set banTime = 60 2017-11-05 15:19:07,142 fail2ban.filter [8528]: INFO Set findtime = 60 2017-11-05 15:19:07,142 fail2ban.filter [8528]: INFO Set jail log file encoding to UTF-8 2017-11-05 15:19:07,143 fail2ban.filter [8528]: INFO Set maxRetry = 3 2017-11-05 15:19:07,144 fail2ban.filter [8528]: INFO Added logfile = /var/log/auth.log 2017-11-05 15:19:07,144 fail2ban.filter [8528]: INFO Set maxlines = 10 2017-11-05 15:19:07,189 fail2ban.server [8528]: INFO Jail sshd is not a JournalFilter instance 2017-11-05 15:19:07,195 fail2ban.jail [8528]: INFO Jail 'sshd' started 2017-11-05 15:20:03,263 fail2ban.filter [8528]: INFO [sshd] Found 103.5.134.167 2017-11-05 15:20:05,267 fail2ban.filter [8528]: INFO [sshd] Found 103.5.134.167 2017-11-05 15:20:12,276 fail2ban.filter [8528]: INFO [sshd] Found 103.5.134.167 2017-11-05 15:20:12,380 fail2ban.actions [8528]: NOTICE [sshd] Ban 103.5.134.167 2017-11-05 15:21:12,659 fail2ban.actions [8528]: NOTICE [sshd] Unban 103.5.134.167 ``` 要查看启用的监狱列表,请运行以下命令。 ``` # fail2ban-client status Status |- Number of jail: 2 `- Jail list: apache-auth, sshd ``` 通过运行以下命令来获取禁止的 IP 地址。 ``` # fail2ban-client status ssh Status for the jail: ssh |- filter | |- File list: /var/log/auth.log | |- Currently failed: 1 | `- Total failed: 3 `- action |- Currently banned: 1 | `- IP list: 192.168.1.115 `- Total banned: 1 ``` 要从 Fail2Ban 中删除禁止的 IP 地址,请运行以下命令。 ``` # fail2ban-client set ssh unbanip 192.168.1.115 ``` --- via: <https://www.2daygeek.com/how-to-install-setup-configure-fail2ban-on-linux/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 译者:[Flowsnow](https://github.com/Flowsnow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,301
如何安装并设置 Vagrant
https://www.chris-shaw.com/blog/how-to-install-and-setup-vagrant
2018-02-01T14:45:00
[ "虚拟机", "Vagrant", "Virtualbox" ]
https://linux.cn/article-9301-1.html
Vagrant 对于虚拟机来说是一个强大的工具,在这里我们将研究如何在 Ubuntu 上设置和使用 Virtualbox 和 Vagrant 来提供可复制的虚拟机。 ![](/data/attachment/album/201802/01/144530ivtj3kvm8va5vc9s.jpg) ### 虚拟机,并不复杂 多年来,开发人员一直使用虚拟机作为其工作流程的一部分,允许他们交换和更改运行软件的环境,这通常是为了防止项目之间的冲突,例如需要 php 5.3 的项目 A 和需要 php 5.4 的项目 B。 并且使用虚拟机意味着你只需要你正在使用的计算机就行,而不需要专用硬件来镜像你的生产环境。 当多个开发人员在一个项目上工作时,它也很方便,他们都可以运行一个包含所有需求的环境,但是维护多台机器并确保所有的需求都具有相同的版本是非常困难的,这时 Vagrant 就能派上用场了。 #### 使用虚拟机的好处 * 你的虚拟机与主机环境是分开的 * 你可以根据你代码的要求裁剪一个定制虚拟机 * 不会影响其他虚拟机 * 可以运行在你的主机上无法运行的程序,例如在 Ubuntu 中运行一些只能在 Windows 运行的软件 ### 什么是 Vagrant 简而言之,这是一个与虚拟机一起工作的工具,可以让你自动创建和删除虚拟机。 它围绕一个名为 `VagrantFile` 的配置文件而工作,这个配置文件告诉 Vagrant 你想要安装的操作系统,以及一些其他选项,如 IP 和目录同步。 你还可以在虚拟机上添加一个命令的配置脚本。 通过共享这个 `VagrantFile`,项目的所有开发人员全可以使用完全相同的虚拟机。 ### 安装要求 #### 安装 VirtualBox VirtualBox 是运行虚拟机的程序,它可以从 Ubuntu 仓库中安装。 ``` sudo apt-get install virtualbox ``` #### 安装 Vagrant 对于 Vagrant 本身,你要前往 <https://www.vagrantup.com/downloads.html> 查看适用于你的操作系统的安装软件包。 #### 安装增强功能 如果你打算与虚拟机共享任何文件夹,则需要安装以下插件。 ``` vagrant plugin install vagrant-vbguest ``` ### 配置 Vagrant 首先我们需要为 Vagrant 创建一个文件夹。 ``` mkdir ~/Vagrant/test-vm cd ~/Vagrant/test-vm ``` 创建 VagrantFile: ``` vagrant init ``` 开启虚拟机: ``` vagrant up ``` 登录机器: ``` vagrant-ssh ``` 此时,你将拥有一个基本的 vagrant 机器,以及一个名为 `VagrantFile` 的文件。 ### 定制 在上面的步骤中创建的 `VagrantFile` 看起来类似于以下内容 VagrantFile: ``` # -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. config.vm.box = "base" # Disable automatic box update checking. If you disable this, then # boxes will only be checked for updates when the user runs # `vagrant box outdated`. This is not recommended. # config.vm.box_check_update = false # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. In the example below, # accessing "localhost:8080" will access port 80 on the guest machine. # NOTE: This will enable public access to the opened port # config.vm.network "forwarded_port", guest: 80, host: 8080 # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine and only allow access # via 127.0.0.1 to disable public access # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1" # Create a private network, which allows host-only access to the machine # using a specific IP. # config.vm.network "private_network", ip: "192.168.33.10" # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. # config.vm.network "public_network" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # # config.vm.provider "virtualbox" do |vb| # # Display the VirtualBox GUI when booting the machine # vb.gui = true # # # Customize the amount of memory on the VM: # vb.memory = "1024" # end # # View the documentation for the provider you are using for more # information on available options. # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # config.vm.provision "shell", inline: <<-SHELL # apt-get update # apt-get install -y apache2 # SHELL end ``` 现在这个 `VagrantFile` 将创建基本的虚拟机。但 Vagrant 背后的理念是让虚拟机为我们的特定任务而配置,所以我们删除注释和调整配置。 VagrantFile: ``` # -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| # Set the Linux Version to Debian Jessie config.vm.box = "debian/jessie64" # Set the IP of the Box config.vm.network "private_network", ip: "192.168.33.10" # Sync Our Projects Directory with the WWW directory config.vm.synced_folder "~/Projects", "/var/www/" # Run the following to Provision config.vm.provision "shell", path: "install.sh" end ``` 现在我们有一个简单的 `VagrantFile`,它将 Linux 版本设置为 debian jessie,设置一个 IP 给我们使用,同步我们感兴趣的文件夹,并最后运行 `install.sh`,这是我们可以运行 shell 命令的地方。 install.sh: ``` #! /usr/bin/env bash # Variables DBHOST=localhost DBNAME=dbname DBUSER=dbuser DBPASSWD=test123 echo "[ Provisioning machine ]" echo "1) Update APT..." apt-get -qq update echo "1) Install Utilities..." apt-get install -y tidy pdftk curl xpdf imagemagick openssl vim git echo "2) Installing Apache..." apt-get install -y apache2 echo "3) Installing PHP and packages..." apt-get install -y php5 libapache2-mod-php5 libssh2-php php-pear php5-cli php5-common php5-curl php5-dev php5-gd php5-imagick php5-imap php5-intl php5-mcrypt php5-memcached php5-mysql php5-pspell php5-xdebug php5-xmlrpc #php5-suhosin-extension, php5-mysqlnd echo "4) Installing MySQL..." debconf-set-selections <<< "mysql-server mysql-server/root_password password secret" debconf-set-selections <<< "mysql-server mysql-server/root_password_again password secret" apt-get install -y mysql-server mysql -uroot -p$DBPASSWD -e "CREATE DATABASE $DBNAME" mysql -uroot -p$DBPASSWD -e "grant all privileges on $DBNAME.* to '$DBUSER'@'localhost' identified by '$DBPASSWD'" echo "5) Generating self signed certificate..." mkdir -p /etc/ssl/localcerts openssl req -new -x509 -days 365 -nodes -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -out /etc/ssl/localcerts/apache.pem -keyout /etc/ssl/localcerts/apache.key chmod 600 /etc/ssl/localcerts/apache* echo "6) Setup Apache..." a2enmod rewrite > /etc/apache2/sites-enabled/000-default.conf echo " <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> " >> /etc/apache2/sites-enabled/000-default.conf service apache2 restart echo "7) Composer Install..." curl --silent https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer echo "8) Install NodeJS..." curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - apt-get -qq update apt-get -y install nodejs echo "9) Install NPM Packages..." npm install -g gulp gulp-cli echo "Provisioning Completed" ``` 通过上面的步骤,在你的目录中会有 `VagrantFile` 和 `install.sh`,运行 vagrant 会做下面的事情: * 采用 Debian Jessie 来创建虚拟机 * 将机器的 IP 设置为 192.168.33.10 * 同步 `~/Projects` 和 `/var/www/` 目录 * 安装并设置 Apache、Mysql、PHP、Git、Vim * 安装并运行 Composer * 安装 Nodejs 和 gulp * 创建一个 MySQL 数据库 * 创建自签名证书 通过与其他人共享 `VagrantFile` 和 `install.sh`,你可以在两台不同的机器上使用完全相同的环境。 --- via: <https://www.chris-shaw.com/blog/how-to-install-and-setup-vagrant> 作者:[Christopher Shaw](https://www.chris-shaw.com) 译者:[MjSeven](https://github.com/MjSeven) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,302
如何在 Linux 或者 UNIX 下调试 Bash Shell 脚本
https://www.cyberciti.biz/tips/debugging-shell-script.html
2018-02-01T15:13:09
[ "shell", "脚本", "调试" ]
https://linux.cn/article-9302-1.html
来自我的邮箱: > > 我写了一个 hello world 小脚本。我如何能调试运行在 Linux 或者类 UNIX 的系统上的 bash shell 脚本呢? > > > 这是 Linux / Unix 系统管理员或新用户最常问的问题。shell 脚本调试可能是一项繁琐的工作(不容易阅读)。调试 shell 脚本有多种方法。 您需要传递 `-x` 或 `-v` 参数,以在 bash shell 中浏览每行代码。 [![如何在 Linux 或者 UNIX 下调试 Bash Shell 脚本](/data/attachment/album/201802/01/151311iy411omf3kfwy2wy.jpg)](https://www.cyberciti.biz/tips/wp-content/uploads/2007/01/How-to-debug-a-bash-shell-script-on-Linux-or-Unix.jpg) 让我们看看如何使用各种方法调试 Linux 和 UNIX 上运行的脚本。 ### -x 选项来调试脚本 用 `-x` 选项来运行脚本: ``` $ bash -x script-name $ bash -x domains.sh ``` ### 使用 set 内置命令 bash shell 提供调试选项,可以打开或关闭使用 [set 命令](https://bash.cyberciti.biz/guide/Set_command): * `set -x` : 显示命令及其执行时的参数。 * `set -v` : 显示 shell 输入行作为它们读取的 可以在 shell 脚本本身中使用上面的两个命令: ``` #!/bin/bash clear # turn on debug mode set -x for f in * do file $f done # turn OFF debug mode set +x ls # more commands ``` 你可以代替 [标准释伴](https://bash.cyberciti.biz/guide/Shebang) 行: ``` #!/bin/bash ``` 用以下代码(用于调试): ``` #!/bin/bash -xv ``` ### 使用智能调试功能 首先添加一个叫做 `_DEBUG` 的特殊变量。当你需要调试脚本的时候,设置 `_DEBUG` 为 `on`: ``` _DEBUG="on" ``` 在脚本的开头放置以下函数: ``` function DEBUG() { [ "$_DEBUG" == "on" ] && $@ } ``` 现在,只要你需要调试,只需使用 `DEBUG` 函数如下: ``` DEBUG echo "File is $filename" ``` 或者: ``` DEBUG set -x Cmd1 Cmd2 DEBUG set +x ``` 当调试完(在移动你的脚本到生产环境之前)设置 `_DEBUG` 为 `off`。不需要删除调试行。 ``` _DEBUG="off" # 设置为非 'on' 的任何字符 ``` 示例脚本: ``` #!/bin/bash _DEBUG="on" function DEBUG() { [ "$_DEBUG" == "on" ] && $@ } DEBUG echo 'Reading files' for i in * do grep 'something' $i > /dev/null [ $? -eq 0 ] && echo "Found in $i file" done DEBUG set -x a=2 b=3 c=$(( $a + $b )) DEBUG set +x echo "$a + $b = $c" ``` 保存并关闭文件。运行脚本如下: ``` $ ./script.sh ``` 输出: ``` Reading files Found in xyz.txt file + a=2 + b=3 + c=5 + DEBUG set +x + '[' on == on ']' + set +x 2 + 3 = 5 ``` 现在设置 `_DEBUG` 为 `off`(你需要编辑该文件): ``` _DEBUG="off" ``` 运行脚本: ``` $ ./script.sh ``` 输出: ``` Found in xyz.txt file 2 + 3 = 5 ``` 以上是一个简单但非常有效的技术。还可以尝试使用 `DEBUG` 作为别名而不是函数。 ### 调试 Bash Shell 的常见错误 Bash 或者 sh 或者 ksh 在屏幕上给出各种错误信息,在很多情况下,错误信息可能不提供详细的信息。 #### 跳过在文件上应用执行权限 当你 [编写你的第一个 hello world 脚本](https://www.cyberciti.biz/faq/hello-world-bash-shell-script/),您可能会得到一个错误,如下所示: ``` bash: ./hello.sh: Permission denied ``` 设置权限使用 `chmod` 命令: ``` $ chmod +x hello.sh $ ./hello.sh $ bash hello.sh ``` #### 文件结束时发生意外的错误 如果您收到文件结束意外错误消息,请打开脚本文件,并确保它有打开和关闭引号。在这个例子中,`echo` 语句有一个开头引号,但没有结束引号: ``` #!/bin/bash ... .... echo 'Error: File not found ^^^^^^^ missing quote ``` 还要确保你检查缺少的括号和大括号 `{}`: ``` #!/bin/bash ..... [ ! -d $DIRNAME ] && { echo "Error: Chroot dir not found"; exit 1; ^^^^^^^^^^^^^ missing brace } ... ``` #### 丢失像 fi,esac,;; 等关键字。 如果你缺少了结尾的关键字,如 `fi` 或 `;;` 你会得到一个错误,如 “XXX 意外”。因此,确保所有嵌套的 `if` 和 `case` 语句以适当的关键字结束。有关语法要求的页面。在本例中,缺少 `fi`: ``` #!/bin/bash echo "Starting..." .... if [ $1 -eq 10 ] then if [ $2 -eq 100 ] then echo "Do something" fi for f in $files do echo $f done # 注意 fi 丢失了 ``` #### 在 Windows 或 UNIX 框中移动或编辑 shell 脚本 不要在 Linux 上创建脚本并移动到 Windows。另一个问题是编辑 Windows 10上的 shell 脚本并将其移动到 UNIX 服务器上。这将由于换行符不同而导致命令没有发现的错误。你可以使用下列命令 [将 DOS 换行转换为 CR-LF 的Unix/Linux 格式](https://www.cyberciti.biz/faq/howto-unix-linux-convert-dos-newlines-cr-lf-unix-text-format/) : ``` dos2unix my-script.sh ``` ### 技巧 #### 技巧 1 - 发送调试信息输出到标准错误 [标准错误] 是默认错误输出设备,用于写所有系统错误信息。因此,将消息发送到默认的错误设备是个好主意: ``` # 写错误到标准输出 echo "Error: $1 file not found" # # 写错误到标准错误(注意 1>&2 在 echo 命令末尾) # echo "Error: $1 file not found" 1>&2 ``` #### 技巧 2 - 在使用 vim 文本编辑器时,打开语法高亮 大多数现代文本编辑器允许设置语法高亮选项。这对于检测语法和防止常见错误如打开或关闭引号非常有用。你可以在不同的颜色中看到。这个特性简化了 shell 脚本结构中的编写,语法错误在视觉上截然不同。高亮不影响文本本身的意义,它只为你提示而已。在这个例子中,我的脚本使用了 vim 语法高亮: [!如何调试 Bash Shell 脚本,在 Linux 或者 UNIX 使用 Vim 语法高亮特性](https://www.cyberciti.biz/media/new/tips/2007/01/bash-vim-debug-syntax-highlighting.png)][7](https://www.cyberciti.biz/media/new/tips/2007/01/bash-vim-debug-syntax-highlighting.png) #### 技巧 3 - 使用 shellcheck 检查脚本 [shellcheck 是一个用于静态分析 shell 脚本的工具](https://www.cyberciti.biz/programming/improve-your-bashsh-shell-script-with-shellcheck-lint-script-analysis-tool/)。可以使用它来查找 shell 脚本中的错误。这是用 Haskell 编写的。您可以使用这个工具找到警告和建议。你可以看看如何在 Linux 或 类UNIX 系统上安装和使用 shellcheck 来改善你的 shell 脚本,避免错误和高效。 作者:Vivek Gite 作者是 nixCraft 创造者,一个经验丰富的系统管理员和一个练习 Linux 操作系统/ UNIX shell 脚本的教练。他曾与全球客户和各种行业,包括 IT,教育,国防和空间研究,以及非营利部门。关注他的 [推特](https://twitter.com/nixcraft),[脸谱网](https://facebook.com/nixcraft),[谷歌+](https://plus.google.com/+CybercitiBiz) 。 --- via: <https://www.cyberciti.biz/tips/debugging-shell-script.html> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[zjon](https://github.com/zjon) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,303
当 CPU 空闲时它都在做什么?
https://manybutfinite.com/post/what-does-an-idle-cpu-do/
2018-02-01T20:52:00
[ "CPU", "空闲" ]
https://linux.cn/article-9303-1.html
![](/data/attachment/album/201802/01/205242mph41wle167mmflp.jpg) 在 [上篇文章中](/article-9095-1.html) 我说了操作系统行为的基本原理是,*在任何一个给定的时刻*,在一个 CPU 上**有且只有一个任务是活动的**。但是,如果 CPU 无事可做的时候,又会是什么样的呢? 事实证明,这种情况是非常普遍的,对于绝大多数的个人电脑来说,这确实是一种常态:大量的睡眠进程,它们都在等待某种情况下被唤醒,差不多在 100% 的 CPU 时间中,都处于虚构的“空闲任务”中。事实上,如果一个普通用户的 CPU 处于持续的繁忙中,它可能意味着有一个错误、bug、或者运行了恶意软件。 因为我们不能违反我们的原理,*一些任务需要在一个 CPU 上激活*。首先是因为,这是一个良好的设计:持续很长时间去遍历内核,检查是否*有*一个活动任务,这种特殊情况是不明智的做法。最好的设计是*没有任何例外的情况*。无论何时,你写一个 `if` 语句,Nyan Cat 就会喵喵喵。其次,我们需要使用空闲的 CPU 去做*一些事情*,让它们充满活力,你懂得,就是创建天网计划呗。 因此,保持这种设计的连续性,并领先于那些邪恶计划一步,操作系统开发者创建了一个**空闲任务**,当没有其它任务可做时就调度它去运行。我们可以在 Linux 的 [引导过程](https://manybutfinite.com/post/kernel-boot-process) 中看到,这个空闲任务就是进程 0,它是由计算机打开电源时运行的第一个指令直接派生出来的。它在 [rest\_init](https://github.com/torvalds/linux/blob/v3.17/init/main.c#L393) 中初始化,在 [init\_idle\_bootup\_task](https://github.com/torvalds/linux/blob/v3.17/kernel/sched/core.c#L4538) 中初始化空闲<ruby> 调度类 <rt> scheduling class </rt></ruby>。 简而言之,Linux 支持像实时进程、普通用户进程等等的不同调度类。当选择一个进程变成活动任务时,这些类按优先级进行查询。通过这种方式,核反应堆的控制代码总是优先于 web 浏览器运行。尽管在通常情况下,这些类返回 `NULL`,意味着它们没有合适的任务需要去运行 —— 它们总是处于睡眠状态。但是空闲调度类,它是持续运行的,从不会失败:它总是返回空闲任务。 好吧,我们来看一下这个空闲任务*到底做了些什么*。下面是 [cpu\_idle\_loop](https://github.com/torvalds/linux/blob/v3.17/kernel/sched/idle.c#L183),感谢开源能让我们看到它的代码: ``` while (1) { while(!need_resched()) { cpuidle_idle_call(); } /* [Note: Switch to a different task. We will return to this loop when the idle task is again selected to run.] */ schedule_preempt_disabled(); } ``` *cpu\_*idle\_*loop* 我省略了很多的细节,稍后我们将去了解任务切换,但是,如果你阅读了这些源代码,你就会找到它的要点:由于这里不需要重新调度(即改变活动任务),它一直处于空闲状态。以所经历的时间来计算,这个循环和其它操作系统中它的“堂兄弟们”相比,在计算的历史上它是运行的最多的代码片段。对于 Intel 处理器来说,处于空闲状态意味着运行着一个 [halt](https://github.com/torvalds/linux/blob/v3.17/arch/x86/include/asm/irqflags.h#L52) 指令: ``` static inline void native_halt(void) { asm volatile("hlt": : :"memory"); } ``` *native\_halt* `hlt` 指令停止处理器中的代码执行,并将它置于 `halt` 的状态。奇怪的是,全世界各地数以百万计的 Intel 类的 CPU 们花费大量的时间让它们处于 `halt` 的状态,甚至它们在通电的时候也是如此。这并不是高效、节能的做法,这促使芯片制造商们去开发处理器的深度睡眠状态,以带来着更少的功耗和更长休眠时间。内核的 [cpuidle 子系统](http://lwn.net/Articles/384146/) 是这些节能模式能够产生好处的原因。 现在,一旦我们告诉 CPU 去 `halt`(睡眠)之后,我们需要以某种方式让它醒来。如果你读过 [上篇文章《你的操作系统什么时候运行?》](/article-9095-1.html) ,你可能会猜到*中断*会参与其中,而事实确实如此。中断促使 CPU 离开 `halt` 状态返回到激活状态。因此,将这些拼到一起,下图是当你阅读一个完全呈现的 web 网页时,你的系统主要做的事情: ![](/data/attachment/album/201802/01/205258o8ie97zvp9ttq1od.png) 除定时器中断外的其它中断也会使处理器再次发生变化。如果你再次点击一个 web 页面就会产生这种变化,例如:你的鼠标发出一个中断,它的驱动会处理它,并且因为它产生了一个新的输入,突然进程就可运行了。在那个时刻, `need_resched()` 返回 `true`,然后空闲任务因你的浏览器而被踢出而终止运行。 如果我们呆呆地看着这篇文章,而不做任何事情。那么随着时间的推移,这个空闲循环就像下图一样: ![](/data/attachment/album/201802/01/205259oq5c3kfhhfoo08kf.png) 在这个示例中,由内核计划的定时器中断会每 4 毫秒发生一次。这就是<ruby> 滴答 <rt> tick </rt></ruby>周期。也就是说每秒钟将有 250 个滴答,因此,这个*滴答速率(频率)*是 250 Hz。这是运行在 Intel 处理器上的 Linux 的典型值,而其它操作系统喜欢使用 100 Hz。这是由你构建内核时在 `CONFIG_HZ` 选项中定义的。 对于一个*空闲 CPU* 来说,它看起来似乎是个无意义的工作。如果外部世界没有新的输入,在你的笔记本电脑的电池耗尽之前,CPU 将始终处于这种每秒钟被唤醒 250 次的地狱般折磨的小憩中。如果它运行在一个虚拟机中,那我们正在消耗着宿主机 CPU 的性能和宝贵的时钟周期。 在这里的解决方案是 [动态滴答](https://github.com/torvalds/linux/blob/v3.17/Documentation/timers/NO_HZ.txt#L17),当 CPU 处于空闲状态时,定时器中断被 [暂停或重计划](https://github.com/torvalds/linux/blob/v3.17/Documentation/timers/highres.txt#L215),直到内核*知道*将有事情要做时(例如,一个进程的定时器可能要在 5 秒内过期,因此,我们不能再继续睡眠了),定时器中断才会重新发出。这也被称为*无滴答模式*。 最后,假设在一个系统中你有一个*活动进程*,例如,一个长时间运行的 CPU 密集型任务。那样几乎就和一个空闲系统是相同的:这些示意图仍然是相同的,只是将空闲任务替换为这个进程,并且相应的描述也是准确的。在那种情况下,每 4 毫秒去中断一次任务仍然是无意义的:它只是操作系统的性能抖动,甚至会使你的工作变得更慢而已。Linux 也可以在这种单一进程的场景中停止这种固定速率的滴答,这被称为 [自适应滴答](https://github.com/torvalds/linux/blob/v3.17/Documentation/timers/NO_HZ.txt#L100) 模式。最终,这种固定速率的滴答可能会 [完全消失](http://lwn.net/Articles/549580/)。 对于阅读一篇文章来说,CPU 基本是无事可做的。内核的这种空闲行为是操作系统难题的一个重要部分,并且它与我们看到的其它情况非常相似,因此,这将帮助我们理解一个运行中的内核。 --- via: <https://manybutfinite.com/post/what-does-an-idle-cpu-do/> 作者:[Gustavo Duarte](http://duartes.org/gustavo/blog/about/) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
In the [last post](/post/when-does-your-os-run) I said the fundamental axiom of OS behavior is that *at any given time*, exactly **one and only one task is active** on a CPU. But if there’s absolutely nothing to do, then what? It turns out that this situation is extremely common, and for most personal computers it’s actually the norm: an ocean of sleeping processes, all waiting on some condition to wake up, while nearly 100% of CPU time is going into the mythical “idle task.” In fact, if the CPU is consistently busy for a normal user, it’s often a misconfiguration, bug, or malware. Since we can’t violate our axiom, *some task needs to be active* on a CPU. First because it’s good design: it would be unwise to spread special cases all over the kernel checking whether there *is* in fact an active task. A design is far better when there are *no exceptions*. Whenever you write an `if` statement, Nyan Cat cries. And second, we need to do *something* with all those idle CPUs, lest they get spunky and, you know, create Skynet. So to keep design consistency and be one step ahead of the devil, OS developers create an **idle task** that gets scheduled to run when there’s no other work. We have seen in the Linux [boot process](/post/kernel-boot-process) that the idle task is process 0, a direct descendent of the very first instruction that runs when a computer is first turned on. It is initialized in [rest_init](https://github.com/torvalds/linux/blob/v3.17/init/main.c#L393), where [init_idle_bootup_task](https://github.com/torvalds/linux/blob/v3.17/kernel/sched/core.c#L4538) initializes the idle **scheduling class**. Briefly, Linux supports different scheduling classes for things like real-time processes, regular user processes, and so on. When it’s time to choose a process to become the active task, these classes are queried in order of priority. That way, the nuclear reactor control code always gets to run before the web browser. Often, though, these classes return `NULL` , meaning they don’t have a suitable process to run - they’re all sleeping. But the idle scheduling class, which runs last, never fails: it always returns the idle task. That’s all good, but let’s get down to just *what exactly* this idle task is doing. So here is [cpu_idle_loop](https://github.com/torvalds/linux/blob/v3.17/kernel/sched/idle.c#L183), courtesy of open source: 1 | while (1) { | I’ve omitted many details, and we’ll look at task switching closely later on, but if you read the code you’ll get the gist of it: as long as there’s no need to reschedule, meaning change the active task, stay idle. Measured in elapsed time, this loop and its cousins in other OSes are probably the most executed pieces of code in computing history. For Intel processors, staying idle traditionally meant running the [halt](https://github.com/torvalds/linux/blob/v3.17/arch/x86/include/asm/irqflags.h#L52) instruction: 1 | static inline void native_halt(void) | `hlt` stops code execution in the processor and puts it in a halted state. It’s weird to think that across the world millions and millions of Intel-like CPUs are spending the majority of their time halted, even while they’re powered up. It’s also not terribly efficient, energy wise, which led chip makers to develop deeper sleep states for processors, which trade off less power consumption for longer wake-up latency. The kernel’s [cpuidle subsystem](http://lwn.net/Articles/384146/) is responsible for taking advantage of these power-saving modes. Now once we tell the CPU to halt, or sleep, we need to somehow bring it back to life. If you’ve read the [last post](/post/when-does-your-os-run), you might suspect *interrupts* are involved, and indeed they are. Interrupts spur the CPU out of its halted state and back into action. So putting this all together, here’s what your system mostly does as you read a fully rendered web page: ![](/img/os/idle.png) Other interrupts besides the timer interrupt also get the processor moving again. That’s what happens if you click on a web page, for example: your mouse issues an interrupt, its driver processes it, and suddenly a process is runnable because it has fresh input. At that point `need_resched()` returns true, and the idle task is booted out in favor of your browser. But let’s stick to idleness in this post. Here’s the idle loop over time: ![](/img/os/idleCycles.png) In this example the timer interrupt was programmed by the kernel to happen every 4 milliseconds (ms). This is the *tick period*. That means we get 250 ticks per second, so the *tick rate* or *tick frequency* is 250 Hz. That’s a typical value for Linux running on Intel processors, with 100 Hz being another crowd favorite. This is defined in the `CONFIG_HZ` option when you build the kernel. Now that looks like an awful lot of pointless work for an *idle CPU*, and it is. Without fresh input from the outside world, the CPU will remain stuck in this hellish nap getting woken up 250 times a second while your laptop battery is drained. If this is running in a virtual machine, we’re burning both power and valuable cycles from the host CPU. The solution here is to have a [dynamic tick](https://github.com/torvalds/linux/blob/v3.17/Documentation/timers/NO_HZ.txt#L17) so that when the CPU is idle, the timer interrupt is either [deactivated or reprogrammed](https://github.com/torvalds/linux/blob/v3.17/Documentation/timers/highres.txt#L215) to happen at a point where the kernel *knows* there will be work to do (for example, a process might have a timer expiring in 5 seconds, so we must not sleep past that). This is also called *tickless mode*. Finally, suppose you have *one active process* in a system, for example a long-running CPU-intensive task. That’s nearly identical to an idle system: these diagrams remain about the same, just substitute the one process for the idle task and the pictures are accurate. In that case it’s still pointless to interrupt the task every 4 ms for no good reason: it’s merely OS jitter slowing your work ever so slightly. Linux can also stop the fixed-rate tick in this one-process scenario, in what’s called [adaptive-tick](https://github.com/torvalds/linux/blob/v3.17/Documentation/timers/NO_HZ.txt#L100) mode. Eventually, a fixed-rate tick may be gone [altogether](http://lwn.net/Articles/549580/). That’s enough idleness for one post. The kernel’s idle behavior is an important part of the OS puzzle, and it’s very similar to other situations we’ll see, so this helps us build the picture of a running kernel. More next week, [RSS](https://manybutfinite.com/feed.xml) and [Twitter](http://twitter.com/manybutfinite). ## Comments
9,304
互联网化疗 —— BrickerBot 僵尸网络创建者的行动
https://ghostbin.com/paste/q2vq2
2018-02-02T22:18:00
[ "僵尸网络", "IoT", "BrickerBot" ]
https://linux.cn/article-9304-1.html
![](/data/attachment/album/201802/02/221709kct6bmcbtgygsy5y.jpg) > > 本文作者 janit0r 被认为是 BrickerBot 病毒的作者。此病毒会攻击物联网上安全性不足的设备并使其断开和其他网络设备的连接。janit0r 宣称他使用这个病毒的目的是保护互联网的安全,避免这些设备被入侵者用于入侵网络上的其他设备。janit0r 称此项目为“互联网化疗”。janit0r 决定在 2017 年 12 月终止这个项目,并在网络上发表了这篇文章。 > > > ### --[ 1 互联网化疗 <ruby> 互联网化疗 <rt> Internet Chemotherapy </rt></ruby>是在 2016 年 11 月 到 2017 年 12 月之间的一个为期 13 个月的项目。它曾被称为 “BrickerBot”、“错误的固件升级”、“勒索软件”、“大规模网络瘫痪”,甚至 “前所未有的恐怖行为”。最后一个有点伤人了,费尔南德斯(LCTT 译注:委内瑞拉电信公司 CANTV 的光纤网络曾在 2017 年 8 月受到病毒攻击,公司董事长曼努埃尔·费尔南德斯称这次攻击为[“前所未有的恐怖行为”](https://www.telecompaper.com/news/venezuelan-operators-hit-by-unprecedented-cyberattack--1208384)),但我想我大概不能让所有人都满意吧。 你可以从 <http://91.215.104.140/mod_plaintext.py> 下载我的代码模块,它可以基于 http 和 telnet 发送恶意请求(LCTT 译注:这个链接已经失效,不过在 [Github](https://github.com/JeremyNGalloway/mod_plaintext.py) 上有备份)。因为平台的限制,模块里是代码混淆过的单线程 Python 代码,但<ruby> 载荷 <rt> payload </rt></ruby>(LCTT 译注:payload,指实质的攻击/利用代码)依然是明文,任何合格的程序员应该都能看得懂。看看这里面有多少载荷、0-day 漏洞和入侵技巧,花点时间让自己接受现实。然后想象一下,如果我是一个黑客,致力于创造出强大的 DDoS 生成器来勒索那些最大的互联网服务提供商(ISP)和公司的话,互联网在 2017 年会受到怎样的打击。我完全可以让他们全部陷入混乱,并同时对整个互联网造成巨大的伤害。 我的 ssh 爬虫太危险了,不能发布出来。它包含很多层面的自动化,可以只利用一个被入侵的路由器就能够在设计有缺陷的 ISP 的网络上平行移动并加以入侵。正是因为我可以征用数以万计的 ISP 的路由器,而这些路由器让我知晓网络上发生的事情并给我提供源源不断的节点用来进行入侵行动,我才得以进行我的反物联网僵尸网络项目。我于 2015 年开始了我的非破坏性的 ISP 的网络清理项目,于是当 Mirai 病毒入侵时我已经做好了准备来做出回应。主动破坏其他人的设备仍然是一个困难的决定,但无比危险的 CVE-2016-10372 漏洞让我别无选择。从那时起我就决定一不做二不休。 (LCTT 译注:上一段中提到的 Mirai 病毒首次出现在 2016 年 8 月。它可以远程入侵运行 Linux 系统的网络设备并利用这些设备构建僵尸网络。本文作者 janit0r 宣称当 Mirai 入侵时他利用自己的 BrickerBot 病毒强制将数以万计的设备从网络上断开,从而减少 Mirai 病毒可以利用的设备数量。) 我在此警告你们,我所做的只是权宜之计,它并不足以在未来继续拯救互联网。坏人们正变得更加聪明,潜在存在漏洞的设备数量在持续增加,发生大规模的、能使网络瘫痪的事件只是时间问题。如果你愿意相信,我曾经在一个持续 13 个月的项目中使上千万有漏洞的设备变得无法使用,那么不过分地说,如此严重的事件本已经在 2017 年发生了。 **你们应该意识到,只需要再有一两个严重的物联网漏洞,我们的网络就会严重瘫痪。** 考虑到我们的社会现在是多么依赖数字网络,而计算机安全应急响应组(CERT)、ISP 们和政府们又是多么地忽视这种问题的严重性,这种事件造成的伤害是无法估计的。ISP 在持续地部署暴露了控制端口的设备,而且即使像 Shodan 这样的服务可以轻而易举地发现这些问题,国家 CERT 还是似乎并不在意。而很多国家甚至都没有自己的 CERT 。世界上许多最大的 ISP 都没有雇佣任何熟知计算机安全问题的人,而是在出现问题的时候依赖于外来的专家来解决。我曾见识过大型 ISP 在我的僵尸网络的调节之下连续多个月持续受损,但他们还是不能完全解决漏洞(几个好的例子是 BSNL、Telkom ZA、PLDT、某些时候的 PT Telkom,以及南半球大部分的大型 ISP )。只要看看 Telkom ZA 解决他们的 Aztech 调制解调器问题的速度有多慢,你就会开始理解现状有多么令人绝望。在 99% 的情况下,要解决这个问题只需要 ISP 部署合理的访问控制列表,并把部署在用户端的设备(CPE)单独分段就行,但是几个月过去之后他们的技术人员依然没有弄明白。如果 ISP 在经历了几周到几个月的针对他们设备的蓄意攻击之后仍然无法解决问题,我们又怎么能期望他们会注意到并解决 Mirai 在他们网络上造成的问题呢?世界上许多最大的 ISP 对这些事情无知得令人发指,而这毫无疑问是最大的危险,但奇怪的是,这应该也是最容易解决的问题。 我已经尽自己的责任试着去让互联网多坚持一段时间,但我已经尽力了。接下来要交给你们了。即使很小的行动也是非常重要的。你们能做的事情有: * 使用像 Shodan 之类的服务来检查你的 ISP 的安全性,并驱使他们去解决他们网络上开放的 telnet、http、httpd、ssh 和 tr069 等端口。如果需要的话,可以把这篇文章给他们看。从来不存在什么好的理由来让这些端口可以从外界访问。暴露控制端口是业余人士的错误。如果有足够的客户抱怨,他们也许真的会采取行动! * 用你的钱包投票!拒绝购买或使用任何“智能”产品,除非制造商保证这个产品能够而且将会收到及时的安全更新。在把你辛苦赚的钱交给提供商之前,先去查看他们的安全记录。为了更好的安全性,可以多花一些钱。 * 游说你本地的政治家和政府官员,让他们改进法案来规范物联网设备,包括路由器、IP 照相机和各种“智能”设备。不论私有还是公有的公司目前都没有足够的动机去在短期内解决该问题。这件事情和汽车或者通用电器的安全标准一样重要。 * 考虑给像 GDI 基金会或者 Shadowserver 基金会这种缺少支持的白帽黑客组织贡献你的时间或者其他资源。这些组织和人能产生巨大的影响,并且他们可以很好地发挥你的能力来帮助互联网。 * 最后,虽然希望不大,但可以考虑通过设立法律先例来让物联网设备成为一种“<ruby> 诱惑性危险品 <rt> attractive nuisance </rt></ruby>”(LCTT 译注:attractive nuisance 是美国法律中的一个原则,意思是如果儿童在私人领地上因为某些对儿童有吸引力的危险物品而受伤,领地的主人需要负责,无论受伤的儿童是否是合法进入领地)。如果一个房主可以因为小偷或者侵入者受伤而被追责,我不清楚为什么设备的主人(或者 ISP 和设备制造商)不应该因为他们的危险的设备被远程入侵所造成的伤害而被追责。连带责任原则应该适用于对设备应用层的入侵。如果任何有钱的大型 ISP 不愿意为设立这样的先例而出钱(他们也许的确不会,因为他们害怕这样的先例会反过来让自己吃亏),我们甚至可以在这里还有在欧洲为这个行动而进行众筹。 ISP 们:把你们在用来应对 DDoS 的带宽上省下的可观的成本当做我为这个目标的间接投资,也当做它的好处的证明吧。 ### --[ 2 时间线 下面是这个项目中一些值得纪念的事件: * 2016 年 11 月底的德国电信 Mirai 事故。我匆忙写出的最初的 TR069/64 请求只执行了 `route del default`,不过这已经足够引起 ISP 去注意这个问题,而它引发的新闻头条警告了全球的其他 ISP 来注意这个迫近的危机。 * 大约 1 月 11 日 到 12 日,一些位于华盛顿特区的开放了 6789 控制端口的硬盘录像机被 Mirai 入侵并瘫痪,这上了很多头条新闻。我要给 Vemulapalli 点赞,她居然认为 Mirai 加上 `/dev/urandom` 一定是“非常复杂的勒索软件”(LCTT 译注:Archana Vemulapalli 当时是华盛顿市政府的 CTO)。欧洲的那两个可怜人又怎么样了呢? * 2017 年 1 月底发生了第一起真正的大规模 ISP 下线事件。Rogers Canada 的提供商 Hitron 非常粗心地推送了一个在 2323 端口上监听的无验证的 root shell(这可能是一个他们忘记关闭的 debug 接口)。这个惊天的失误很快被 Mirai 的僵尸网络所发现,造成大量设备瘫痪。 * 在 2017 年 2 月,我注意到 Mirai 在这一年里的第一次扩张,Netcore/Netis 以及 Broadcom 的基于 CLI (命令行接口)的调制解调器都遭受了攻击。BCM CLI 后来成为了 Mirai 在 2017 年的主要战场,黑客们和我自己都在这一年的余下时间里花大量时间寻找无数 ISP 和设备制造商设置的默认密码。前面代码中的“broadcom” 载荷也许看上去有点奇怪,但它们是统计角度上最可能禁用那些大量的有问题的 BCM CLI 固件的序列。 * 在 2017 年 3 月,我大幅提升了我的僵尸网络的节点数量并开始加入更多的网络载荷。这是为了应对包括 Imeij、Amnesia 和 Persirai 在内的僵尸网络的威胁。大规模地禁用这些被入侵的设备也带来了新的一些问题。比如在 Avtech 和 Wificam 设备所泄露的登录信息当中,有一些用户名和密码非常像是用于机场和其他重要设施的,而英国政府官员大概在 2017 年 4 月 1 日关于针对机场和核设施的“实际存在的网络威胁”做出过警告。哎呀。 * 这种更加激进的扫描还引起了民间安全研究者的注意,安全公司 Radware 在 2017 年 4 月 6 日发表了一篇关于我的项目的文章。这个公司把它叫做“BrickerBot”。显然,如果我要继续增加我的物联网防御措施的规模,我必须想出更好的网络映射与检测方法来应对蜜罐或者其他有风险的目标。 * 2017 年 4 月 11 日左右的时候发生了一件非常不寻常的事情。一开始这看上去和许多其他的 ISP 下线事件相似,一个叫 Sierra Tel 的半本地 ISP 在一些 Zyxel 设备上使用了默认的 telnet 用户名密码 supervisor/zyad1234。一个 Mirai 运行器发现了这些有漏洞的设备,我的僵尸网络紧随其后,2017 年精彩绝伦的 BCM CLI 战争又开启了新的一场战斗。这场战斗并没有持续很久。它本来会和 2017 年的其他数百起 ISP 下线事件一样,如果不是在尘埃落定之后发生的那件非常不寻常的事情的话。令人惊奇的是,这家 ISP 并没有试着把这次网络中断掩盖成某种网络故障、电力超额或错误的固件升级。他们完全没有对客户说谎。相反,他们很快发表了新闻公告,说他们的调制解调器有漏洞,这让他们的客户们得以评估自己可能遭受的风险。这家全世界最诚实的 ISP 为他们值得赞扬的公开行为而收获了什么呢?悲哀的是,它得到的只是批评和不好的名声。这依然是我记忆中最令人沮丧的“为什么我们得不到好东西”的例子,这很有可能也是为什么 99% 的安全错误都被掩盖而真正的受害者被蒙在鼓里的最主要原因。太多时候,“有责任心的信息公开”会直接变成“粉饰太平”的委婉说法。 * 在 2017 年 4 月 14 日,国土安全部关于“BrickerBot 对物联网的威胁”做出了警告,我自己的政府把我作为一个网络威胁这件事让我觉得他们很不公平而且目光短浅。跟我相比,对美国人民威胁最大的难道不应该是那些部署缺乏安全性的网络设备的提供商和贩卖不成熟的安全方案的物联网设备制造商吗?如果没有我,数以百万计的人们可能还在用被入侵的设备和网络来处理银行业务和其他需要保密的交易。如果国土安全部里有人读到这篇文章,我强烈建议你重新考虑一下保护国家和公民究竟是什么意思。 * 在 2017 年 4 月底,我花了一些时间改进我的 TR069/64 攻击方法,然后在 2017 年 5 月初,一个叫 Wordfence 的公司(现在叫 Defiant)报道称一个曾给 Wordpress 网站造成威胁的基于入侵 TR069 的僵尸网络很明显地衰减了。值得注意的是,同一个僵尸网络在几星期后使用了一个不同的入侵方式暂时回归了(不过这最终也同样被化解了)。 * 在 2017 年 5 月,主机托管公司 Akamai 在它的 2017 年第一季度互联网现状报告中写道,相比于 2016 年第一季度,大型(超过 100 Gbps)DDoS 攻击数减少了 89%,而总体 DDoS 攻击数减少了 30%。鉴于大型 DDoS 攻击是 Mirai 的主要手段,我觉得这给这些月来我在物联网领域的辛苦劳动提供了实际的支持。 * 在夏天我持续地改进我的入侵技术军火库,然后在 7 月底我针对亚太互联网络信息中心(APNIC)的 ISP 进行了一些测试。测试结果非常令人吃惊。造成的影响之一是数十万的 BSNL 和 MTNL 调制解调器被禁用,而这次中断事故在印度成为了头条新闻。考虑到当时在印度和中国之间持续升级的地缘政治压力,我觉得这个事故有很大的风险会被归咎于中国所为,于是我很罕见地决定公开承认是我所做。Catalin,我很抱歉你在报道这条新闻之后突然被迫放的“两天的假期”。 * 在处理过亚太互联网络信息中心(APNIC)和非洲互联网络信息中心(AfriNIC)的之后,在 2017 年 8 月 9 日我又针对拉丁美洲与加勒比地区互联网络信息中心(LACNIC)进行了大规模的清理,给这个大洲的许多提供商造成了问题。在数百万的 Movilnet 的手机用户失去连接之后,这次攻击在委内瑞拉被大幅报道。虽然我个人反对政府监管互联网,委内瑞拉的这次情况值得注意。许多拉美与加勒比地区的提供商与网络曾在我的僵尸网络的持续调节之下连续数个月逐渐衰弱,但委内瑞拉的提供商很快加强了他们的网络防护并确保了他们的网络设施的安全。我认为这是由于委内瑞拉相比于该地区的其他国家来说进行了更具侵入性的深度包检测。值得思考一下。 * F5 实验室在 2017 年 8 月发布了一个题为“狩猎物联网:僵尸物联网的崛起”的报告,研究者们在其中对近期 telnet 活动的平静表达了困惑。研究者们猜测这种活动的减少也许证实了一个或多个非常大型的网络武器正在成型(我想这大概确实是真的)。这篇报告是在我印象中对我的项目的规模最准确的评估,但神奇的是,这些研究者们什么都推断不出来,尽管他们把所有相关的线索都集中到了一页纸上。 * 2017 年 8 月,Akamai 的 2017 年第二季度互联网现状报告宣布这是三年以来首个该提供商没有发现任何大规模(超过 100 Gbps)攻击的季度,而且 DDoS 攻击总数相比 2017 年第一季度减少了 28%。这看上去给我的清理工作提供了更多的支持。这个出奇的好消息被主流媒体所完全忽视了,这些媒体有着“流血的才是好新闻”的心态,即使是在信息安全领域。这是我们为什么不能得到好东西的又一个原因。 * 在 CVE-2017-7921 和 7923 于 2017 年 9 月公布之后,我决定更密切地关注海康威视公司的设备,然后我惊恐地发现有一个黑客们还没有发现的方法可以用来入侵有漏洞的固件。于是我在 9 月中旬开启了一个全球范围的清理行动。超过一百万台硬盘录像机和摄像机(主要是海康威视和大华出品)在三周内被禁用,然后包括 IPVM.com 在内的媒体为这些攻击写了多篇报道。大华和海康威视在新闻公告中提到或暗示了这些攻击。大量的设备总算得到了固件升级。看到这次清理活动造成的困惑,我决定给这些闭路电视制造商写一篇[简短的总结](http://depastedihrn3jtw.onion.link/show.php?md5=62d1d87f67a8bf485d43a05ec32b1e6f)(请原谅在这个粘贴板网站上的不和谐的语言)。这令人震惊的有漏洞而且在关键的安全补丁发布之后仍然在线的设备数量应该能够唤醒所有人,让他们知道现今的物联网补丁升级过程有多么无力。 * 2017 年 9 月 28 日左右,Verisign 发表了报告称 2017 年第二季度的 DDoS 攻击数相比第一季度减少了 55%,而且攻击峰值大幅减少了 81%。 * 2017 年 11 月 23 日,CDN 供应商 Cloudflare 报道称“近几个月来,Cloudflare 看到试图用垃圾流量挤满我们的网络的简单进攻尝试有了大幅减少”。Cloudflare 推测这可能和他们的政策变化有一定关系,但这些减少也和物联网清理行动有着明显的重合。 * 2017 年 11 月底,Akamai 的 2017 年第三季度互联网现状报告称 DDoS 攻击数较前一季度小幅增加了 8%。虽然这相比 2016 年的第三季度已经减少了很多,但这次小幅上涨提醒我们危险仍然存在。 * 作为潜在危险的更进一步的提醒,一个叫做“Satori”的新的 Mirai 变种于 2017 年 11 月至 12 月开始冒头。这个僵尸网络仅仅通过一个 0-day 漏洞而达成的增长速度非常值得注意。这起事件凸显了互联网的危险现状,以及我们为什么距离大规模的事故只差一两起物联网入侵。当下一次威胁发生而且没人阻止的时候,会发生什么?Sinkholing 和其他的白帽或“合法”的缓解措施在 2018 年不会有效,就像它们在 2016 年也不曾有效一样。也许未来各国政府可以合作创建一个国际范围的反黑客特别部队来应对特别严重的会影响互联网存续的威胁,但我并不抱太大期望。 * 在年末出现了一些危言耸听的新闻报道,有关被一个被称作“Reaper”和“IoTroop”的新的僵尸网络。我知道你们中有些人最终会去嘲笑那些把它的规模估算为一两百万的人,但你们应该理解这些网络安全研究者们对网络上发生的事情以及不由他们掌控的硬件的事情都是一知半解。实际来说,研究者们不可能知道或甚至猜测到大部分有漏洞的设备在僵尸网络出现时已经被禁用了。给“Reaper”一两个新的未经处理的 0-day 漏洞的话,它就会变得和我们最担心的事情一样可怕。 ### --[ 3 临别赠言 我很抱歉把你们留在这种境况当中,但我的人身安全受到的威胁已经不允许我再继续下去。我树了很多敌人。如果你想要帮忙,请看前面列举的该做的事情。祝你好运。 也会有人批评我,说我不负责任,但这完全找错了重点。真正的重点是如果一个像我一样没有黑客背景的人可以做到我所做到的事情,那么一个比我厉害的人可以在 2017 年对互联网做比这要可怕太多的事情。我并不是问题本身,我也不是来遵循任何人制定的规则的。我只是报信的人。你越早意识到这点越好。 ——Dr Cyborkian 又名 janit0r,“病入膏肓”的设备的调节者。 --- via:<https://ghostbin.com/paste/q2vq2> 作者:janit0r 译者:[yixunx](https://github.com/yixunx) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译, [Linux中国](https://linux.cn/) 荣誉推出
302
Moved Temporarily
null
9,305
怎样完整地离线更新并升级基于 Debian 的操作系统
https://www.ostechnix.com/fully-update-upgrade-offline-debian-based-systems/
2018-02-02T23:54:38
[ "Debian", "更新", "离线" ]
https://linux.cn/article-9305-1.html
![](/data/attachment/album/201802/02/235441cehgxrxg3gfrzgfi.png) 不久之前我已经向你展示了如何在任意离线的 [Ubuntu](https://www.ostechnix.com/install-softwares-offline-ubuntu-16-04/) 和 [Arch Linux](https://www.ostechnix.com/install-packages-offline-arch-linux/) 操作系统上安装软件。 今天,我们将会看看如何完整地离线更新并升级基于 Debian 的操作系统。 和之前所述方法的不同之处在于,这次我们将会升级整个操作系统,而不是单个的软件包。这个方法在你没有网络链接或拥有的网络速度很慢的时候十分有用。 ### 完整地离线更新并升级基于 Debian 的操作系统 首先假设,你在单位拥有正在运行并配置有高速互联网链接的系统(Windows 或者 Linux),而在家有一个没有网络链接或网络很慢(例如拨号网络)的 Debian 或其衍生的操作系统。现在如果你想要离线更新你家里的操作系统怎么办?购买一个更加高速的网络链接?不,根本不需要!你仍然可以通过互联网离线更新升级你的操作系统。这正是 **Apt-Offline**工具可以帮助你做到的。 正如其名,apt-offline 是一个为 Debian 及其衍生发行版(诸如 Ubuntu、Linux Mint 这样基于 APT 的操作系统)提供的离线 APT 包管理器。使用 apt-offline,我们可以完整地更新/升级我们的 Debian 系统而不需要网络链接。这个程序是由 Python 编程语言写成的兼具 CLI 和图形界面的跨平台工具。 #### 准备工作 * 一个已经联网的操作系统(Windows 或者 Linux)。在这份指南中,为了便于理解,我们将之称为在线操作系统。 * 一个离线操作系统(Debian 及其衍生版本)。我们称之为离线操作系统。 * 有足够空间容纳所有更新包的 USB 驱动器或者外接硬盘。 #### 安装 Apt-Offline 可以在 Debian 及其衍生版本的默认仓库中获得。如果你的在线操作系统是运行的 Debian、Ubuntu、Linux Mint,及其它基于 DEB 的操作系统,你可以通过下面的命令安装 Apt-Offline: ``` sudo apt-get install apt-offline ``` 如果你的在线操作系统运行的是非 Debian 类的发行版,使用 `git clone` 获取 Apt-Offline 仓库: ``` git clone https://github.com/rickysarraf/apt-offline.git ``` 切换到克隆的目录下并在此处运行: ``` cd apt-offline/ sudo ./apt-offline ``` #### 在离线操作系统(没有联网的操作系统)上的步骤 到你的离线操作系统上创建一个你想存储签名文件的目录: ``` mkdir ~/tmp cd ~/tmp/ ``` 你可以自己选择使用任何目录。接下来,运行下面的命令生成签名文件: ``` sudo apt-offline set apt-offline.sig ``` 示例输出如下: ``` Generating database of files that are needed for an update. Generating database of file that are needed for operation upgrade ``` 默认条件下,apt-offline 将会生成需要更新和升级的相关文件的数据库。你可以使用 `--update` 或者 `--upgrade` 选项相应创建。 拷贝完整的 `tmp` 目录到你的 USB 驱动器或者或者外接硬盘上,然后换到你的在线操作系统(有网络链接的操作系统)。 #### 在在线操作系统上的步骤 插入你的 USB 驱动器然后进入 `tmp` 文件夹: ``` cd tmp/ ``` 然后,运行如下命令: ``` sudo apt-offline get apt-offline.sig --threads 5 --bundle apt-offline-bundle.zip ``` 在这里的 `-threads 5` 代表着(并发连接的) APT 仓库的数目。如果你想要从更多的仓库下载软件包,你可以增加这里的数值。然后 `-bundle apt-offline-bundle.zip` 选项表示所有的软件包将会打包到一个叫做 `apt-offline-bundle.zip` 的单独存档中。这个存档文件将会被保存在你的当前工作目录中(LCTT 译注:即 `tmp` 目录)。 上面的命令将会按照之前在离线操作系统上生成的签名文件下载数据。 ![](/data/attachment/album/201802/02/235442uvzhg7tsujjf0zfz.png) 根据你的网络状况,这个操作将会花费几分钟左右的时间。请记住,apt-offline 是跨平台的,所以你可以在任何操作系统上使用它下载包。 一旦下载完成,拷贝 `tmp` 文件夹到你的 USB 或者外接硬盘上并且返回你的离线操作系统(LCTT 译注:此处的复制操作似不必要,因为我们一直在 USB 存储器的 `tmp` 目录中操作)。千万保证你的 USB 驱动器上有足够的空闲空间存储所有的下载文件,因为所有的包都放在 `tmp` 文件夹里了。 #### 离线操作系统上的步骤 把你的设备插入你的离线操作系统,然后切换到你之前下载了所有包的 `tmp`目录下。 ``` cd tmp ``` 然后,运行下面的命令来安装所有下载好的包。 ``` sudo apt-offline install apt-offline-bundle.zip ``` 这个命令将会更新 APT 数据库,所以 APT 将会在 APT 缓冲里找所有需要的包。 **注意事项:** 如果在线和离线操作系统都在同一个局域网中,你可以通过 `scp` 或者其他传输应用程序将 `tmp` 文件传到离线操作系统中。如果两个操作系统在不同的位置(LCTT 译注:意指在不同的局域网),那就使用 USB 设备来拷贝。 好了大伙儿,现在就这么多了。 希望这篇指南对你有用。还有更多好东西正在路上。敬请关注! 祝你愉快! --- via: <https://www.ostechnix.com/fully-update-upgrade-offline-debian-based-systems/> 作者:[SK](https://www.ostechnix.com/author/sk/) 译者:[leemeans](https://github.com/leemeans) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,306
为初学者准备的 MariaDB 管理命令
http://linuxtechlab.com/mariadb-administration-commands-beginners/
2018-02-03T00:15:00
[ "MySQL", "MariaDB" ]
https://linux.cn/article-9306-1.html
之前我们学过了[在 Centos/RHEL 7 上安装 MariaDB 服务器并保证其安全](http://linuxtechlab.com/installing-configuring-mariadb-rhelcentos/),使之成为了 RHEL/CentOS 7 的默认数据库。现在我们再来看看一些有用的 MariaDB 管理命令。这些都是使用 MariaDB 最基础的命令,而且它们对 MySQL 也同样适合,因为 MariaDB 就是 MySQL 的一个分支而已。 (推荐阅读:[在 RHEL/CentOS 上安装并配置 MongoDB](http://linuxtechlab.com/mongodb-installation-configuration-rhelcentos/)) ![](/data/attachment/album/201802/03/001533ewhva1wp1zwhz1m1.jpg) ### MariaDB 管理命令 #### 1、查看 MariaDB 安装的版本 要查看所安装数据库的当前版本,在终端中输入下面命令: ``` $ mysql -version ``` 该命令会告诉你数据库的当前版本。此外你也可以运行下面命令来查看版本的详细信息: ``` $ mysqladmin -u root -p version ``` #### 2、登录 MariaDB 要登录 MariaDB 服务器,运行: ``` $ mysql -u root -p ``` 然后输入密码登录。 #### 3、列出所有的数据库 要列出 MariaDB 当前拥有的所有数据库,在你登录到 MariaDB 中后运行: ``` > show databases; ``` (LCTT 译注:`$` 这里代表 shell 的提示符,`>` 这里代表 MariaDB shell 的提示符。) #### 4、创建新数据库 在 MariaDB 中创建新数据库,登录 MariaDB 后运行: ``` > create database dan; ``` 若想直接在终端创建数据库,则运行: ``` $ mysqladmin -u user -p create dan ``` 这里,`dan` 就是新数据库的名称。 #### 5、删除数据库 要删除数据库,在已登录的 MariaDB 会话中运行: ``` > drop database dan; ``` 此外你也可以运行, ``` $ mysqladmin -u root -p drop dan ``` **注意:** 若在运行 `mysqladmin` 命令时提示 “access denied” 错误,这应该是由于我们没有给 root 授权。要对 root 授权,请参照第 7 点方法,只是要将用户改成 root。 #### 6、创建新用户 为数据库创建新用户,运行: ``` > CREATE USER 'dan'@'localhost' IDENTIFIED BY 'password'; ``` #### 7、授权用户访问某个数据库 授权用户访问某个数据库,运行: ``` > GRANT ALL PRIVILEGES ON test.* to 'dan'@'localhost'; ``` 这会赋予用户 `dan` 对名为 `test` 的数据库完全操作的权限。我们也可以限定为用户只赋予 `SELECT`、`INSERT`、`DELETE` 权限。 要赋予访问所有数据库的权限,将 `test` 替换成 `*` 。像这样: ``` > GRANT ALL PRIVILEGES ON *.* to 'dan'@'localhost'; ``` #### 8、备份/导出数据库 要创建单个数据库的备份,在终端窗口中运行下列命令, ``` $ mysqldump -u root -p database_name>db_backup.sql ``` 若要一次性创建多个数据库的备份则运行: ``` $ mysqldump -u root -p --databases db1 db2 > db12_backup.sql ``` 要一次性导出多个数据库,则运行: ``` $ mysqldump -u root -p --all-databases > all_dbs.sql ``` #### 9、从备份中恢复数据库 要从备份中恢复数据库,运行: ``` $ mysql -u root -p database_name < db_backup.sql ``` 但这条命令成功的前提是预先没有存在同名的数据库。如果想要恢复数据库数据到已经存在的数据库中,则需要用到 `mysqlimport` 命令: ``` $ mysqlimport -u root -p database_name < db_backup.sql ``` #### 10、更改 MariaDB 用户的密码 本例中我们会修改 `root` 的密码,但修改其他用户的密码也是一样的过程。 登录 MariaDB 并切换到 'mysql' 数据库: ``` $ mysql -u root -p > use mysql; ``` 然后运行下面命令: ``` > update user set password=PASSWORD('your_new_password_here') where User='root'; ``` 下一步,重新加载权限: ``` > flush privileges; ``` 然后退出会话。 我们的教程至此就结束了,在本教程中我们学习了一些有用的 MariaDB 管理命令。欢迎您的留言。 --- via: <http://linuxtechlab.com/mariadb-administration-commands-beginners/> 作者:[Shusain](http://linuxtechlab.com/author/shsuain/) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,307
如何统计 Linux 中文件和文件夹/目录的数量
https://www.2daygeek.com/how-to-count-the-number-of-files-and-folders-directories-in-linux/
2018-02-03T20:25:23
[ "目录", "统计" ]
https://linux.cn/article-9307-1.html
![](/data/attachment/album/201802/03/202516ai28uur2pipxkfud.jpg) 嗨,伙计们,今天我们再次带来一系列可以多方面帮助到你的复杂的命令。 通过操作命令,可以帮助您计数当前目录中的文件和目录、递归计数,统计特定用户创建的文件列表等。 在本教程中,我们将向您展示如何使用多个命令,并使用 `ls`、`egrep`、`wc` 和 `find` 命令执行一些高级操作。 下面的命令将可用在多个方面。 为了实验,我打算总共创建 7 个文件和 2 个文件夹(5 个常规文件和 2 个隐藏文件)。 下面的 `tree` 命令的输出清楚的展示了文件和文件夹列表。 ``` # tree -a /opt /opt ├── magi │ └── 2g │ ├── test5.txt │ └── .test6.txt ├── test1.txt ├── test2.txt ├── test3.txt ├── .test4.txt └── test.txt 2 directories, 7 files ``` ### 示例-1 统计当前目录的文件(不包括隐藏文件)。 运行以下命令以确定当前目录中有多少个文件,并且不计算点文件(LCTT 译注:点文件即以“.” 开头的文件,它们在 Linux 默认是隐藏的)。 ``` # ls -l . | egrep -c '^-' 4 ``` **细节:** * `ls` : 列出目录内容 * `-l` : 使用长列表格式 * `.` : 列出有关文件的信息(默认为当前目录) * `|` : 将一个程序的输出发送到另一个程序进行进一步处理的控制操作符 * `egrep` : 打印符合模式的行 * `-c` : 通用输出控制 * `'^-'` : 以“-”开头的行(`ls -l` 列出长列表时,行首的 “-” 代表普通文件) ### 示例-2 统计当前目录包含隐藏文件在内的文件。 包括当前目录中的点文件。 ``` # ls -la . | egrep -c '^-' 5 ``` ### 示例-3 运行以下命令来计数当前目录的文件和文件夹。 它会计算所有的文件和目录。 ``` # ls -l | wc -l 5 ``` **细节:** * `ls` : 列出目录内容 * `-l` : 使用长列表格式 * `|` : 将一个程序的输出发送到另一个程序进行进一步处理的控制操作符 * `wc` : 这是一个统计每个文件的换行符、单词和字节数的命令 * `-l` : 输出换行符的数量 ### 示例-4 统计当前目录包含隐藏文件和目录在内的文件和文件夹。 ``` # ls -la | wc -l 8 ``` ### 示例-5 递归计算当前目录的文件,包括隐藏文件。 ``` # find . -type f | wc -l 7 ``` **细节 :** * `find` : 搜索目录结构中的文件 * `-type` : 文件类型 * `f` : 常规文件 * `wc` : 这是一个统计每个文件的换行符、单词和字节数的命令 * `-l` : 输出换行符的数量 ### 示例-6 使用 `tree` 命令输出目录和文件数(不包括隐藏文件)。 ``` # tree | tail -1 2 directories, 5 files ``` ### 示例-7 使用包含隐藏文件的 `tree` 命令输出目录和文件计数。 ``` # tree -a | tail -1 2 directories, 7 files ``` ### 示例-8 运行下面的命令递归计算包含隐藏目录在内的目录数。 ``` # find . -type d | wc -l 3 ``` ### 示例-9 根据文件扩展名计数文件数量。 这里我们要计算 `.txt` 文件。 ``` # find . -name "*.txt" | wc -l 7 ``` ### 示例-10 组合使用 `echo` 命令和 `wc` 命令统计当前目录中的所有文件。 `4` 表示当前目录中的文件数量。 ``` # echo *.* | wc 1 4 39 ``` ### 示例-11 组合使用 `echo` 命令和 `wc` 命令来统计当前目录中的所有目录。 第二个 `1` 表示当前目录中的目录数量。 ``` # echo */ | wc 1 1 6 ``` ### 示例-12 组合使用 `echo` 命令和 `wc` 命令来统计当前目录中的所有文件和目录。 `5` 表示当前目录中的目录和文件的数量。 ``` # echo * | wc 1 5 44 ``` ### 示例-13 统计系统(整个系统)中的文件数。 ``` # find / -type f | wc -l 69769 ``` ### 示例-14 统计系统(整个系统)中的文件夹数。 ``` # find / -type d | wc -l 8819 ``` ### 示例-15 运行以下命令来计算系统(整个系统)中的文件、文件夹、硬链接和符号链接数。 ``` # find / -type d -exec echo dirs \; -o -type l -exec echo symlinks \; -o -type f -links +1 -exec echo hardlinks \; -o -type f -exec echo files \; | sort | uniq -c 8779 dirs 69343 files 20 hardlinks 11646 symlinks ``` --- via: <https://www.2daygeek.com/how-to-count-the-number-of-files-and-folders-directories-in-linux/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 译者:[Flowsnow](https://github.com/Flowsnow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,308
为什么 Kubernetes 很酷
https://jvns.ca/blog/2017/10/05/reasons-kubernetes-is-cool/
2018-02-03T23:41:21
[ "Kubernetes", "容器" ]
https://linux.cn/article-9308-1.html
![](/data/attachment/album/201802/03/234107htpn7qntr02q6qos.jpg) 在我刚开始学习 Kubernetes(大约是一年半以前吧?)时,我真的不明白为什么应该去关注它。 在我使用 Kubernetes 全职工作了三个多月后,我才逐渐明白了为什么我应该使用它。(我距离成为一个 Kubernetes 专家还很远!)希望这篇文章对你理解 Kubernetes 能做什么会有帮助! 我将尝试去解释我对 Kubernetes 感兴趣的一些原因,而不去使用 “<ruby> 原生云 <rt> cloud native </rt></ruby>”、“<ruby> 编排系统 <rt> orchestration </rt></ruby>”、“<ruby> 容器 <rt> container </rt></ruby>”,或者任何 Kubernetes 专用的术语 :)。我去解释的这些观点主要来自一位 Kubernetes 操作者/基础设施工程师,因为,我现在的工作就是去配置 Kubernetes 和让它工作的更好。 我不会去尝试解决一些如 “你应该在你的生产系统中使用 Kubernetes 吗?”这样的问题。那是非常复杂的问题。(不仅是因为“生产系统”根据你的用途而总是有不同的要求) ### Kubernetes 可以让你无需设置一台新的服务器即可在生产系统中运行代码 我首次被说教使用 Kubernetes 是与我的伙伴 Kamal 的下面的谈话: 大致是这样的: * Kamal: 使用 Kubernetes 你可以通过一条命令就能设置一台新的服务器。 * Julia: 我觉得不太可能吧。 * Kamal: 像这样,你写一个配置文件,然后应用它,这时候,你就在生产系统中运行了一个 HTTP 服务。 * Julia: 但是,现在我需要去创建一个新的 AWS 实例,明确地写一个 Puppet 清单,设置服务发现,配置负载均衡,配置我们的部署软件,并且确保 DNS 正常工作,如果没有什么问题的话,至少在 4 小时后才能投入使用。 * Kamal: 是的,使用 Kubernetes 你不需要做那么多事情,你可以在 5 分钟内设置一台新的 HTTP 服务,并且它将自动运行。只要你的集群中有空闲的资源它就能正常工作! * Julia: 这儿一定是一个“坑”。 这里有一种陷阱,设置一个生产用 Kubernetes 集群(在我的经险中)确实并不容易。(查看 [Kubernetes 艰难之旅](https://github.com/kelseyhightower/kubernetes-the-hard-way) 中去开始使用时有哪些复杂的东西)但是,我们现在并不深入讨论它。 因此,Kubernetes 第一个很酷的事情是,它可能使那些想在生产系统中部署新开发的软件的方式变得更容易。那是很酷的事,而且它真的是这样,因此,一旦你使用一个运作中的 Kubernetes 集群,你真的可以仅使用一个配置文件就在生产系统中设置一台 HTTP 服务(在 5 分钟内运行这个应用程序,设置一个负载均衡,给它一个 DNS 名字,等等)。看起来真的很有趣。 ### 对于运行在生产系统中的代码,Kubernetes 可以提供更好的可见性和可管理性 在我看来,在理解 etcd 之前,你可能不会理解 Kubernetes 的。因此,让我们先讨论 etcd! 想像一下,如果现在我这样问你,“告诉我你运行在生产系统中的每个应用程序,它运行在哪台主机上?它是否状态很好?是否为它分配了一个 DNS 名字?”我并不知道这些,但是,我可能需要到很多不同的地方去查询来回答这些问题,并且,我需要花很长的时间才能搞定。我现在可以很确定地说不需要查询,仅一个 API 就可以搞定它们。 在 Kubernetes 中,你的集群的所有状态 – 运行中的应用程序 (“pod”)、节点、DNS 名字、 cron 任务、 等等 —— 都保存在一个单一的数据库中(etcd)。每个 Kubernetes 组件是无状态的,并且基本是通过下列方式工作的: * 从 etcd 中读取状态(比如,“分配给节点 1 的 pod 列表”) * 产生变化(比如,“在节点 1 上运行 pod A”) * 更新 etcd 中的状态(比如,“设置 pod A 的状态为 ‘running’”) 这意味着,如果你想去回答诸如 “在那个可用区中有多少台运行着 nginx 的 pod?” 这样的问题时,你可以通过查询一个统一的 API(Kubernetes API)去回答它。并且,你可以在每个其它 Kubernetes 组件上运行那个 API 去进行同样的访问。 这也意味着,你可以很容易地去管理每个运行在 Kubernetes 中的任何东西。比如说,如果你想要: * 部署实现一个复杂的定制的部署策略(部署一个东西,等待 2 分钟,部署 5 个以上,等待 3.7 分钟,等等) * 每当推送到 github 上一个分支,自动化 [启动一个新的 web 服务器](https://github.com/kamalmarhubi/kubereview) * 监视所有你的运行的应用程序,确保它们有一个合理的内存使用限制。 这些你只需要写一个程序与 Kubernetes API(“controller”)通讯就可以了。 另一个关于 Kubernetes API 的令人激动的事情是,你不会局限于 Kubernetes 所提供的现有功能!如果对于你要部署/创建/监视的软件有你自己的方案,那么,你可以使用 Kubernetes API 去写一些代码去达到你的目的!它可以让你做到你想做的任何事情。 ### 即便每个 Kubernetes 组件都“挂了”,你的代码将仍然保持运行 关于 Kubernetes 我(在各种博客文章中 :))承诺的一件事情是,“如果 Kubernetes API 服务和其它组件‘挂了’也没事,你的代码将一直保持运行状态”。我认为理论上这听起来很酷,但是我不确定它是否真是这样的。 到目前为止,这似乎是真的! 我已经断开了一些正在运行的 etcd,发生了这些情况: 1. 所有的代码继续保持运行状态 2. 不能做 *新的* 事情(你不能部署新的代码或者生成变更,cron 作业将停止工作) 3. 当它恢复时,集群将赶上这期间它错过的内容 这样做意味着如果 etcd 宕掉,并且你的应用程序的其中之一崩溃或者发生其它事情,在 etcd 恢复之前,它不能够恢复。 ### Kubernetes 的设计对 bug 很有弹性 与任何软件一样,Kubernetes 也会有 bug。例如,到目前为止,我们的集群控制管理器有内存泄漏,并且,调度器经常崩溃。bug 当然不好,但是,我发现 Kubernetes 的设计可以帮助减轻它的许多核心组件中的错误的影响。 如果你重启动任何组件,将会发生: * 从 etcd 中读取所有的与它相关的状态 * 基于那些状态(调度 pod、回收完成的 pod、调度 cron 作业、按需部署等等),它会去做那些它认为必须要做的事情 因为,所有的组件并不会在内存中保持状态,你在任何时候都可以重启它们,这可以帮助你减轻各种 bug 的影响。 例如,如果在你的控制管理器中有内存泄露。因为,控制管理器是无状态的,你可以每小时定期去重启它,或者,在感觉到可能导致任何不一致的问题发生时重启它。又或者,在调度器中遇到了一个 bug,它有时忘记了某个 pod,从来不去调度它们。你可以每隔 10 分钟来重启调度器来缓减这种情况。(我们并不会这么做,而是去修复这个 bug,但是,你*可以这样做* :)) 因此,我觉得即使在它的核心组件中有 bug,我仍然可以信任 Kubernetes 的设计可以让我确保集群状态的一致性。并且,总在来说,随着时间的推移软件质量会提高。唯一你必须去操作的有状态的东西就是 etcd。 不用过多地讨论“状态”这个东西 —— 而我认为在 Kubernetes 中很酷的一件事情是,唯一需要去做备份/恢复计划的东西是 etcd (除非为你的 pod 使用了持久化存储的卷)。我认为这样可以使 Kubernetes 运维比你想的更容易一些。 ### 在 Kubernetes 之上实现新的分布式系统是非常容易的 假设你想去实现一个分布式 cron 作业调度系统!从零开始做工作量非常大。但是,在 Kubernetes 里面实现一个分布式 cron 作业调度系统是非常容易的!(仍然没那么简单,毕竟它是一个分布式系统) 我第一次读到 Kubernetes 的 cron 作业控制器的代码时,我对它是如此的简单感到由衷高兴。去读读看,其主要的逻辑大约是 400 行的 Go 代码。去读它吧! => [cronjob\_controller.go](https://github.com/kubernetes/kubernetes/blob/e4551d50e57c089aab6f67333412d3ca64bc09ae/pkg/controller/cronjob/cronjob_controller.go) <= cron 作业控制器基本上做的是: * 每 10 秒钟: + 列出所有已存在的 cron 作业 + 检查是否有需要现在去运行的任务 + 如果有,创建一个新的作业对象去调度,并通过其它的 Kubernetes 控制器实际运行它 + 清理已完成的作业 + 重复以上工作 Kubernetes 模型是很受限制的(它有定义在 etcd 中的资源模式,控制器读取这个资源并更新 etcd),我认为这种相关的固有的/受限制的模型,可以使它更容易地在 Kubernetes 框架中开发你自己的分布式系统。 Kamal 给我说的是 “Kubernetes 是一个写你自己的分布式系统的很好的平台” ,而不是“ Kubernetes 是一个你可以使用的分布式系统”,并且,我觉得它真的很有意思。他做了一个 [为你推送到 GitHub 的每个分支运行一个 HTTP 服务的系统](https://github.com/kamalmarhubi/kubereview) 的原型。这花了他一个周末的时间,大约 800 行 Go 代码,我认为它真不可思议! ### Kubernetes 可以使你做一些非常神奇的事情(但并不容易) 我一开始就说 “kubernetes 可以让你做一些很神奇的事情,你可以用一个配置文件来做这么多的基础设施,它太神奇了”。这是真的! 为什么说 “Kubernetes 并不容易”呢?是因为 Kubernetes 有很多部分,学习怎么去成功地运营一个高可用的 Kubernetes 集群要做很多的工作。就像我发现它给我了许多抽象的东西,我需要去理解这些抽象的东西才能调试问题和正确地配置它们。我喜欢学习新东西,因此,它并不会使我发狂或者生气,但是我认为了解这一点很重要 :) 对于 “我不能仅依靠抽象概念” 的一个具体的例子是,我努力学习了许多 [Linux 上网络是如何工作的](https://jvns.ca/blog/2016/12/22/container-networking/),才让我对设置 Kubernetes 网络稍有信心,这比我以前学过的关于网络的知识要多很多。这种方式很有意思但是非常费时间。在以后的某个时间,我或许写更多的关于设置 Kubernetes 网络的困难/有趣的事情。 或者,为了成功设置我的 Kubernetes CA,我写了一篇 [2000 字的博客文章](https://jvns.ca/blog/2017/08/05/how-kubernetes-certificates-work/),述及了我不得不学习 Kubernetes 不同方式的 CA 的各种细节。 我觉得,像 GKE (Google 的 Kubernetes 产品) 这样的一些监管的 Kubernetes 的系统可能更简单,因为,他们为你做了许多的决定,但是,我没有尝试过它们。 --- via: <https://jvns.ca/blog/2017/10/05/reasons-kubernetes-is-cool/> 作者:[Julia Evans](https://jvns.ca/about) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
When I first learned about Kubernetes (a year and a half ago?) I really didn’t understand why I should care about it. I’ve been working full time with Kubernetes for 3 months or so and now have some thoughts about why I think it’s useful. (I’m still very far from being a Kubernetes expert!) Hopefully this will help a little in your journey to understand what even is going on with Kubernetes! I will try to explain some reason I think Kubenetes is interesting without using the words “cloud native”, “orchestration”, “container”, or any Kubernetes-specific terminology :). I’m going to explain this mostly from the perspective of a kubernetes operator / infrastructure engineer, since my job right now is to set up Kubernetes and make it work well. I’m not going to try to address the question of “should you use kubernetes for your production systems?” at all, that is a very complicated question. (not least because “in production” has totally different requirements depending on what you’re doing) ### Kubernetes lets you run code in production without setting up new servers The first pitch I got for Kubernetes was the following conversation with my partner Kamal: Here’s an approximate transcript: - Kamal: With Kubernetes you can set up a new service with a single command - Julia: I don’t understand how that’s possible. - Kamal: Like, you just write 1 configuration file, apply it, and then you have a HTTP service running in production - Julia: But today I need to create new AWS instances, write a puppet manifest, set up service discovery, configure my load balancers, configure our deployment software, and make sure DNS is working, it takes at least 4 hours if nothing goes wrong. - Kamal: Yeah. With Kubernetes you don’t have to do any of that, you can set up a new HTTP service in 5 minutes and it’ll just automatically run. As long as you have spare capacity in your cluster it just works! - Julia: There must be a trap There kind of is a trap, setting up a production Kubernetes cluster is (in my experience) is definitely not easy. (see [Kubernetes The Hard Way](https://github.com/kelseyhightower/kubernetes-the-hard-way) for what’s involved to get started). But we’re not going to go into that right now! So the first cool thing about Kubernetes is that it has the potential to make life way easier for developers who want to deploy new software into production. That’s cool, and it’s actually true, once you have a working Kubernetes cluster you really can set up a production HTTP service (“run 5 of this application, set up a load balancer, give it this DNS name, done”) with just one configuration file. It’s really fun to see. ### Kubernetes gives you easy visibility & control of what code you have running in production IMO you can’t understand Kubernetes without understanding etcd. So let’s talk about etcd! Imagine that I asked you today “hey, tell me every application you have running in production, what host it’s running on, whether it’s healthy or not, and whether or not it has a DNS name attached to it”. I don’t know about you but I would need to go look in a bunch of different places to answer this question and it would take me quite a while to figure out. I definitely can’t query just one API. In Kubernetes, all the state in your cluster – applications running (“pods”), nodes, DNS names, cron jobs, and more – is stored in a single database (etcd). Every Kubernetes component is stateless, and basically works by - Reading state from etcd (eg “the list of pods assigned to node 1”) - Making changes (eg “actually start running pod A on node 1”) - Updating the state in etcd (eg “set the state of pod A to ‘running’”) This means that if you want to answer a question like “hey, how many nginx pods do I have running right now in that availabliity zone?” you can answer it by querying a single unified API (the Kubernetes API!). And you have exactly the same access to that API that every other Kubernetes component does. This also means that you have easy control of everything running in Kubernetes. If you want to, say, - Implement a complicated custom rollout strategy for deployments (deploy 1 thing, wait 2 minutes, deploy 5 more, wait 3.7 minutes, etc) - Automatically [start a new webserver](https://github.com/kamalmarhubi/kubereview)every time a branch is pushed to github - Monitor all your running applications to make sure all of them have a reasonable cgroups memory limit all you need to do is to write a program that talks to the Kubernetes API. (a “controller”) Another very exciting thing about the Kubernetes API is that you’re not limited to just functionality that Kubernetes provides! If you decide that you have your own opinions about how your software should be deployed / created / monitored, then you can write code that uses the Kubernetes API to do it! It lets you do everything you need. ### If every Kubernetes component dies, your code will still keep running One thing I was originally promised (by various blog posts :)) about Kubernetes was “hey, if the Kubernetes apiserver and everything else dies, it’s ok, your code will just keep running”. I thought this sounded cool in theory but I wasn’t sure if it was actually true. So far it seems to be actually true! I’ve been through some etcd outages now, and what happens is - All the code that was running keeps running - Nothing *new*happens (you can’t deploy new code or make changes, cron jobs will stop working) - When everything comes back, the cluster will catch up on whatever it missed This does mean that if etcd goes down and one of your applications crashes or something, it can’t come back up until etcd returns. ### Kubernetes’ design is pretty resilient to bugs Like any piece of software, Kubernetes has bugs. For example right now in our cluster the controller manager has a memory leak, and the scheduler crashes pretty regularly. Bugs obviously aren’t good but so far I’ve found that Kubernetes’ design helps mitigate a lot of the bugs in its core components really well. If you restart any component, what happens is: - It reads all its relevant state from etcd - It starts doing the necessary things it’s supposed to be doing based on that state (scheduling pods, garbage collecting completed pods, scheduling cronjobs, deploying daemonsets, whatever) Because all the components don’t keep any state in memory, you can just restart them at any time and that can help mitigate a variety of bugs. For example! Let’s say you have a memory leak in your controller manager. Because the controller manager is stateless, you can just periodically restart it every hour or something and feel confident that you won’t cause any consistency issues. Or we ran into a bug in the scheduler where it would sometimes just forget about pods and never schedule them. You can sort of mitigate this just by restarting the scheduler every 10 minutes. (we didn’t do that, we fixed the bug instead, but you *could* :) ) So I feel like I can trust Kubernetes’ design to help make sure the state in the cluster is consistent even when there are bugs in its core components. And in general I think the software is generally improving over time. The only stateful thing you have to operate is etcd Not to harp on this “state” thing too much but – I think it’s cool that in Kubernetes the only thing you have to come up with backup/restore plans for is etcd (unless you use persistent volumes for your pods). I think it makes kubernetes operations a lot easier to think about. ### Implementing new distributed systems on top of Kubernetes is relatively easy Suppose you want to implement a distributed cron job scheduling system! Doing that from scratch is a ton of work. But implementing a distributed cron job scheduling system inside Kubernetes is much easier! (still not trivial, it’s still a distributed system) The first time I read the code for the Kubernetes cronjob controller I was really delighted by how simple it was. Here, go read it! The main logic is like 400 lines of Go. Go ahead, read it! => [cronjob_controller.go](https://github.com/kubernetes/kubernetes/blob/e4551d50e57c089aab6f67333412d3ca64bc09ae/pkg/controller/cronjob/cronjob_controller.go) <= Basically what the cronjob controller does is: - Every 10 seconds: - Lists all the cronjobs that exist - Checks if any of them need to run right now - If so, creates a new Job object to be scheduled & actually run by other Kubernetes controllers - Clean up finished jobs - Repeat The Kubernetes model is pretty constrained (it has this pattern of resources are defined in etcd, controllers read those resources and update etcd), and I think having this relatively opinionated/constrained model makes it easier to develop your own distributed systems inside the Kubernetes framework. Kamal introduced me to this idea of “Kubernetes is a good platform for writing your own distributed systems” instead of just “Kubernetes is a distributed system you can use” and I think it’s really interesting. He has a prototype of a [system to run an HTTP service for every branch you push to github](https://github.com/kamalmarhubi/kubereview). It took him a weekend and is like 800 lines of Go, which I thought was impressive! ### Kubernetes lets you do some amazing things (but isn’t easy) I started out by saying “kubernetes lets you do these magical things, you can just spin up so much infrastructure with a single configuration file, it’s amazing”. And that’s true! What I mean by “Kubernetes isn’t easy” is that Kubernetes has a lot of moving parts learning how to successfully operate a highly available Kubernetes cluster is a lot of work. Like I find that with a lot of the abstractions it gives me, I need to understand what is underneath those abstractions in order to debug issues and configure things properly. I love learning new things so this doesn’t make me angry or anything, I just think it’s important to know :) One specific example of “I can’t just rely on the abstractions” that I’ve struggled with is that I needed to learn a LOT [about how networking works on Linux](https://jvns.ca/blog/2016/12/22/container-networking/) to feel confident with setting up Kubernetes networking, way more than I’d ever had to learn about networking before. This was very fun but pretty time consuming. I might write more about what is hard/interesting about setting up Kubernetes networking at some point. Or I wrote a [2000 word blog post](https://jvns.ca/blog/2017/08/05/how-kubernetes-certificates-work/) about everything I had to learn about Kubernetes’ different options for certificate authorities to be able to set up my Kubernetes CAs successfully. I think some of these managed Kubernetes systems like GKE (google’s kubernetes product) may be simpler since they make a lot of decisions for you but I haven’t tried any of them.
9,309
创建局域网内的离线 YUM 仓库
http://linuxtechlab.com/offline-yum-repository-for-lan/
2018-02-04T00:03:42
[ "Yum", "RPM" ]
https://linux.cn/article-9309-1.html
![](/data/attachment/album/201802/04/000335adp4ph6whg6i9vc3.jpg) 在早先的教程中,我们讨论了[如何使用 ISO 镜像和在线 Yum 仓库的方式来创建自己的 Yum 仓库](/article-9296-1.html) 。创建自己的 Yum 仓库是一个不错的想法,但若网络中只有 2-3 台 Linux 机器那就没啥必要了。不过若你的网络中有大量的 Linux 服务器,而且这些服务器还需要定时进行升级,或者你有大量服务器无法直接访问互联网,那么创建自己的 Yum 仓库就很有必要了。 当我们有大量的 Linux 服务器,而每个服务器都直接从互联网上升级系统时,数据消耗会很可观。为了节省数据量,我们可以创建个离线 Yum 源并将之分享到本地网络中。网络中的其他 Linux 机器就可以直接从本地 Yum 上获取系统更新,从而节省数据量,而且传输速度也会很好。 我们可以使用下面两种方法来分享 Yum 仓库: * 使用 Web 服务器(Apache) * 使用 FTP 服务器(VSFTPD) 在开始讲解这两个方法之前,我们需要先根据[之前的教程](/article-9296-1.html)创建一个 Yum 仓库。 ### 使用 Web 服务器 首先在 Yum 服务器上安装 Web 服务器(Apache),我们假设服务器 IP 是 `192.168.1.100`。我们已经在这台系统上配置好了 Yum 仓库,现在我们来使用 `yum` 命令安装 Apache Web 服务器, ``` $ yum install httpd ``` 下一步,拷贝所有的 rpm 包到默认的 Apache 根目录下,即 `/var/www/html`,由于我们已经将包都拷贝到了 `/YUM` 下,我们也可以创建一个软连接来从 `/var/www/html` 指向 `/YUM`。 ``` $ ln -s /var/www/html/Centos /YUM ``` 重启 Web 服务器应用改变: ``` $ systemctl restart httpd ``` #### 配置客户端机器 服务端的配置就完成了,现在需要配置下客户端来从我们创建的离线 Yum 中获取升级包,这里假设客户端 IP 为 `192.168.1.101`。 在 `/etc/yum.repos.d` 目录中创建 `offline-yum.repo` 文件,输入如下信息, ``` $ vi /etc/yum.repos.d/offline-yum.repo ``` ``` name=Local YUM baseurl=http://192.168.1.100/CentOS/7 gpgcheck=0 enabled=1 ``` 客户端也配置完了。试一下用 `yum` 来安装/升级软件包来确认仓库是正常工作的。 ### 使用 FTP 服务器 在 FTP 上分享 Yum,首先需要安装所需要的软件包,即 vsftpd。 ``` $ yum install vsftpd ``` vsftp 的默认根目录为 `/var/ftp/pub`,因此你可以拷贝 rpm 包到这个目录,或者为它创建一个软连接: ``` $ ln -s /var/ftp/pub /YUM ``` 重启服务应用改变: ``` $ systemctl restart vsftpd ``` #### 配置客户端机器 像上面一样,在 `/etc/yum.repos.d` 中创建 `offline-yum.repo` 文件,并输入下面信息, ``` $ vi /etc/yum.repos.d/offline-yum.repo ``` ``` [Offline YUM] name=Local YUM baseurl=ftp://192.168.1.100/pub/CentOS/7 gpgcheck=0 enabled=1 ``` 现在客户机可以通过 ftp 接收升级了。要配置 vsftpd 服务器为其他 Linux 系统分享文件,请[阅读这篇指南](http://linuxtechlab.com/ftp-secure-installation-configuration/)。 这两种方法都很不错,你可以任意选择其中一种方法。有任何疑问或这想说的话,欢迎在下面留言框中留言。 --- via: <http://linuxtechlab.com/offline-yum-repository-for-lan/> 作者:[Shusain](http://linuxtechlab.com/author/shsuain/) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,310
用 Apache 服务器模块保护您的网站免受应用层 DOS 攻击
https://bash-prompt.net/guides/mod_proxy/
2018-02-04T21:11:57
[ "DOS", "攻击" ]
https://linux.cn/article-9310-1.html
![](/data/attachment/album/201802/04/211129wijnojhizpucof8u.jpg) 有多种可以导致网站下线的攻击方法,比较复杂的方法要涉及数据库和编程方面的技术知识。一个更简单的方法被称为“<ruby> 拒绝服务 <rt> Denial Of Service </rt></ruby>”(DOS)攻击。这个攻击方法的名字来源于它的意图:使普通客户或网站访问者的正常服务请求被拒绝。 一般来说,有两种形式的 DOS 攻击: 1. OSI 模型的三、四层,即网络层攻击 2. OSI 模型的七层,即应用层攻击 第一种类型的 DOS 攻击——网络层,发生于当大量的垃圾流量流向网页服务器时。当垃圾流量超过网络的处理能力时,网站就会宕机。 第二种类型的 DOS 攻击是在应用层,是利用合法的服务请求,而不是垃圾流量。当页面请求数量超过网页服务器能承受的容量时,即使是合法访问者也将无法使用该网站。 本文将着眼于缓解应用层攻击,因为减轻网络层攻击需要大量的可用带宽和上游提供商的合作,这通常不是通过配置网络服务器就可以做到的。 通过配置普通的网页服务器,可以保护网页免受应用层攻击,至少是适度的防护。防止这种形式的攻击是非常重要的,因为 [Cloudflare](https://www.cloudflare.com) 最近 [报告称](https://blog.cloudflare.com/the-new-ddos-landscape/) 网络层攻击的数量正在减少,而应用层攻击的数量则在增加。 本文将介绍如何使用 [zdziarski](https://www.zdziarski.com/blog/) 开发的 Apache2 的模块 [mod\_evasive](https://github.com/jzdziarski/mod_evasive)。 另外,mod\_evasive 会阻止攻击者通过尝试数百个用户名和密码的组合来进行猜测(即暴力攻击)的企图。 mod\_evasive 会记录来自每个 IP 地址的请求的数量。当这个数字超过相应 IP 地址的几个阈值之一时,会出现一个错误页面。错误页面所需的资源要比一个能够响应合法访问的在线网站少得多。 ### 在 Ubuntu 16.04 上安装 mod\_evasive Ubuntu 16.04 默认的软件库中包含了 mod\_evasive,名称为 “libapache2-mod-evasive”。您可以使用 `apt-get` 来完成安装: ``` apt-get update apt-get upgrade apt-get install libapache2-mod-evasive ``` 现在我们需要配置 mod\_evasive。 它的配置文件位于 `/etc/apache2/mods-available/evasive.conf`。默认情况下,所有模块的设置在安装后都会被注释掉。因此,在修改配置文件之前,模块不会干扰到网站流量。 ``` <IfModule mod_evasive20.c> #DOSHashTableSize 3097 #DOSPageCount 2 #DOSSiteCount 50 #DOSPageInterval 1 #DOSSiteInterval 1 #DOSBlockingPeriod 10 #DOSEmailNotify [email protected] #DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" #DOSLogDir "/var/log/mod_evasive" </IfModule> ``` 第一部分的参数的含义如下: * `DOSHashTableSize` - 正在访问网站的 IP 地址列表及其请求数的当前列表。 * `DOSPageCount` - 在一定的时间间隔内,每个页面的请求次数。时间间隔由 DOSPageInterval 定义。 * `DOSPageInterval` - mod\_evasive 统计页面请求次数的时间间隔。 * `DOSSiteCount` - 与 `DOSPageCount` 相同,但统计的是来自相同 IP 地址对网站内任何页面的请求数量。 * `DOSSiteInterval` - mod\_evasive 统计网站请求次数的时间间隔。 * `DOSBlockingPeriod` - 某个 IP 地址被加入黑名单的时长(以秒为单位)。 如果使用上面显示的默认配置,则在如下情况下,一个 IP 地址会被加入黑名单: * 每秒请求同一页面超过两次。 * 每秒请求 50 个以上不同页面。 如果某个 IP 地址超过了这些阈值,则被加入黑名单 10 秒钟。 这看起来可能不算久,但是,mod\_evasive 将一直监视页面请求,包括在黑名单中的 IP 地址,并重置其加入黑名单的起始时间。只要一个 IP 地址一直尝试使用 DOS 攻击该网站,它将始终在黑名单中。 其余的参数是: * `DOSEmailNotify` - 用于接收 DOS 攻击信息和 IP 地址黑名单的电子邮件地址。 * `DOSSystemCommand` - 检测到 DOS 攻击时运行的命令。 * `DOSLogDir` - 用于存放 mod\_evasive 的临时文件的目录。 ### 配置 mod\_evasive 默认的配置是一个很好的开始,因为它不会阻塞任何合法的用户。取消配置文件中的所有参数(`DOSSystemCommand` 除外)的注释,如下所示: ``` <IfModule mod_evasive20.c> DOSHashTableSize 3097 DOSPageCount 2 DOSSiteCount 50 DOSPageInterval 1 DOSSiteInterval 1 DOSBlockingPeriod 10 DOSEmailNotify [email protected] #DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" DOSLogDir "/var/log/mod_evasive" </IfModule> ``` 必须要创建日志目录并且要赋予其与 apache 进程相同的所有者。这里创建的目录是 `/var/log/mod_evasive` ,并且在 Ubuntu 上将该目录的所有者和组设置为 `www-data` ,与 Apache 服务器相同: ``` mkdir /var/log/mod_evasive chown www-data:www-data /var/log/mod_evasive ``` 在编辑了 Apache 的配置之后,特别是在正在运行的网站上,在重新启动或重新加载之前,最好检查一下语法,因为语法错误将影响 Apache 的启动从而使网站宕机。 Apache 包含一个辅助命令,是一个配置语法检查器。只需运行以下命令来检查您的语法: ``` apachectl configtest ``` 如果您的配置是正确的,会得到如下结果: ``` Syntax OK ``` 但是,如果出现问题,您会被告知在哪部分发生了什么错误,例如: ``` AH00526: Syntax error on line 6 of /etc/apache2/mods-enabled/evasive.conf: DOSSiteInterval takes one argument, Set site interval Action 'configtest' failed. The Apache error log may have more information. ``` 如果您的配置通过了 configtest 的测试,那么这个模块可以安全地被启用并且 Apache 可以重新加载: ``` a2enmod evasive systemctl reload apache2.service ``` mod\_evasive 现在已配置好并正在运行了。 ### 测试 为了测试 mod\_evasive,我们只需要向服务器提出足够的网页访问请求,以使其超出阈值,并记录来自 Apache 的响应代码。 一个正常并成功的页面请求将收到如下响应: ``` HTTP/1.1 200 OK ``` 但是,被 mod\_evasive 拒绝的将返回以下内容: ``` HTTP/1.1 403 Forbidden ``` 以下脚本会尽可能迅速地向本地主机(127.0.0.1,localhost)的 80 端口发送 HTTP 请求,并打印出每个请求的响应代码。 你所要做的就是把下面的 bash 脚本复制到一个文件中,例如 `mod_evasive_test.sh`: ``` #!/bin/bash set -e for i in {1..50}; do curl -s -I 127.0.0.1 | head -n 1 done ``` 这个脚本的部分含义如下: * `curl` - 这是一个发出网络请求的命令。 + `-s` - 隐藏进度表。 + `-I` - 仅显示响应头部信息。 * `head` - 打印文件的第一部分。 + `-n 1` - 只显示第一行。 然后赋予其执行权限: ``` chmod 755 mod_evasive_test.sh ``` 在启用 mod\_evasive **之前**,脚本运行时,将会看到 50 行 “HTTP / 1.1 200 OK” 的返回值。 但是,启用 mod\_evasive 后,您将看到以下内容: ``` HTTP/1.1 200 OK HTTP/1.1 200 OK HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden ... ``` 前两个请求被允许,但是在同一秒内第三个请求发出时,mod\_evasive 拒绝了任何进一步的请求。您还将收到一封电子邮件(邮件地址在选项 `DOSEmailNotify` 中设置),通知您有 DOS 攻击被检测到。 mod\_evasive 现在已经在保护您的网站啦! --- via: <https://bash-prompt.net/guides/mod_proxy/> 作者:[Elliot Cooper](https://bash-prompt.net/about/) 译者:[jessie-pang](https://github.com/jessie-pang) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
There exist many ways of maliciously taking a website offline. The more complicated methods involve technical knowledge of databases and programming. A far simpler method is known as a “Denial Of Service”, or “DOS” attack. This attack derives its name from its goal which is to deny your regular clients or site visitors normal website service. There are, generally speaking, two forms of DOS attack; - Layer 3,4 or Network-Layer attacks. - Layer 7 or Application-Layer attacks. The first type of DOS attack, network-layer, is when a huge quantity of junk traffic is directed at the web server. When the quantity of junk traffic exceeds the capacity of the network infrastructure the website is taken offline. The second type of DOS attack, application-layer, is where instead of junk traffic legitimate looking page requests are made. When the number of page requests exceeds the capacity of the web server to serve pages legitimate visitors will not be able to use the site. This guide will look at mitigating application-layer attacks. This is because mitigating networking-layer attacks requires huge quantities of available bandwidth and the co-operation of upstream providers. This is usually not something that can be protected against through configuration of the web server. An application-layer attack, at least a modest one, can be protected against through the configuration of a normal web server. Protecting against this form of attack is important because [Cloudflare](https://www.cloudflare.com) have [recently reported](https://blog.cloudflare.com/the-new-ddos-landscape/) that the number of network-layer attacks is diminishing while the number of application-layer attacks is increasing. This guide will explain using the Apache2 module [mod_evasive](https://github.com/jzdziarski/mod_evasive) by [zdziarski](https://www.zdziarski.com/blog/). In addition, mod_evasive will stop an attacker trying to guess a username/password combination by attempting hundreds of combinations i.e. a brute force attack. Mod_evasive works by keeping a record of the number of requests arriving from each IP address. When this number exceeds one of the several thresholds that IP is served an error page. Error pages require far fewer resources than a site page keeping the site online for legitimate visitors. ## Installing mod_evasive on Ubuntu 16.04 Mod_evasive is contained in the default Ubuntu 16.04 repositories with the package name “libapache2-mod-evasive”. A simple `apt-get` will get it installed: ``` apt-get update apt-get upgrade apt-get install libapache2-mod-evasive ``` We now need to configure mod_evasive. It’s configuration file is located at `/etc/apache2/mods-available/evasive.conf` . By default, all the modules settings are commented after installation. Therefore, the module won’t interfere with site traffic until the configuration file has been edited. ``` <IfModule mod_evasive20.c> #DOSHashTableSize 3097 #DOSPageCount 2 #DOSSiteCount 50 #DOSPageInterval 1 #DOSSiteInterval 1 #DOSBlockingPeriod 10 #DOSEmailNotify [email protected] #DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" #DOSLogDir "/var/log/mod_evasive" </IfModule> ``` The first block of directives mean as follows: **DOSHashTableSize**– The current list of accessing IP’s and their request count.**DOSPageCount**– The threshold number of page requests per DOSPageInterval.**DOSPageInterval**– The amount of time in which mod_evasive counts up the page requests.**DOSSiteCount**– The same as the DOSPageCount but counts requests from the same IP for any page on the site.**DOSSiteInterval**– The amount of time that mod_evasive counts up the site requests.**DOSBlockingPeriod**– The amount of time in seconds that an IP is blocked for. If the default configuration shown above is used then an IP will be blocked if it: - Requests a single page more than twice a second. - Requests more than 50 pages different pages per second. If an IP exceeds these thresholds it is blocked for 10 seconds. This may not seem like a lot, however, mod_evasive will continue monitoring the page requests even for blocked IP’s and reset their block period. As long as an IP is attempting to DOS the site it will remain blocked. The remaining directives are: **DOSEmailNotify**– An email address to receive notification of DOS attacks and IP’s being blocked.**DOSSystemCommand**– A command to run in the event of a DOS.**DOSLogDir**– The directory where mod_evasive keeps some temporary files. ## Configuring mod_evasive The default configuration is a good place to start as it should not block any legitimate users. The configuration file with all directives (apart from DOSSystemCommand) uncommented looks like the following: ``` <IfModule mod_evasive20.c> DOSHashTableSize 3097 DOSPageCount 2 DOSSiteCount 50 DOSPageInterval 1 DOSSiteInterval 1 DOSBlockingPeriod 10 DOSEmailNotify [email protected] #DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" DOSLogDir "/var/log/mod_evasive" </IfModule> ``` The log directory must be created and given the same owner as the apache process. Here it is created at `/var/log/mod_evasive` and given the owner and group of the Apache web server on Ubuntu `www-data` : ``` mkdir /var/log/mod_evasive chown www-data:www-data /var/log/mod_evasive ``` After editing Apache’s configuration, especially on a live website, it is always a good idea to check the syntax of the edits before restarting or reloading. This is because a syntax error will stop Apache from re-starting and taking your site offline. Apache comes packaged with a helper command that has a configuration syntax checker. Simply run the following command to check your edits: ``` apachectl configtest ``` If your configuration is correct you will get the response: ``` Syntax OK ``` However, if there is a problem you will be told where it occurred and what it was, e.g.: ``` AH00526: Syntax error on line 6 of /etc/apache2/mods-enabled/evasive.conf: DOSSiteInterval takes one argument, Set site interval Action 'configtest' failed. The Apache error log may have more information. ``` If your configuration passes the configtest then the module can be safely enabled and Apache reloaded: ``` a2enmod evasive systemctl reload apache2.service ``` Mod_evasive is now configured and running. ## Testing In order to test mod_evasive, we simply need to make enough web requests to the server that we exceed the threshold and record the response codes from Apache. A normal, successful page request will receive the response: ``` HTTP/1.1 200 OK ``` However, one that has been denied by mod_evasive will return the following: ``` HTTP/1.1 403 Forbidden ``` The following script will make HTTP requests to `127.0.0.1:80` , that is localhost on port 80, as rapidly as possible and print out the response code of every request. All you need to do is to copy the following bash script into a file e.g. `mod_evasive_test.sh` : ``` #!/bin/bash set -e for i in {1..50}; do curl -s -I 127.0.0.1 | head -n 1 done ``` The parts of this script mean as follows: - curl - This is a command to make web requests. - -s - Hide the progress meter. - -I - Only display the response header information. - head - Print the first part of a file. - -n 1 - Only display the first line. Then make it executable: ``` chmod 755 mod_evasive_test.sh ``` When the script is run **before** mod_evasive is enabled you will see 50 lines of `HTTP/1.1 200 OK` returned. However, after mod_evasive is enabled you will see the following: ``` HTTP/1.1 200 OK HTTP/1.1 200 OK HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden ... ``` The first two requests were allowed, but then once a third in the same second was made mod_evasive denied any further requests. You will also receive an email letting you know that a DOS attempt was detected to the address you set with the `DOSEmailNotify` option. Mod_evasive is now protecting your site!
9,311
循序渐进学习如何在 MariaDB 中配置主从复制
http://linuxtechlab.com/creating-master-slave-replication-mariadb/
2018-02-04T22:13:00
[ "MariaDB", "数据库", "主从复制" ]
https://linux.cn/article-9311-1.html
![](/data/attachment/album/201802/04/221301ve5vvocwioceiz5t.jpg) 在我们前面的教程中,我们已经学习了 [如何安装和配置 MariaDB](/article-8320-1.html),也学习了 [管理 MariaDB 的一些基础命令](/article-9306-1.html)。现在我们来学习,如何在 MariaDB 服务器上配置一个主从复制。 复制是用于为我们的数据库创建多个副本,这些副本可以在其它数据库上用于运行查询,像一些非常繁重的查询可能会影响主数据库服务器的性能,或者我们可以使用它来做数据冗余,或者兼具以上两个目的。我们可以将这个过程自动化,即主服务器到从服务器的复制过程自动进行。执行备份而不影响在主服务器上的写操作。 因此,我们现在去配置我们的主-从复制,它需要两台安装了 MariaDB 的机器。它们的 IP 地址如下: * **主服务器 -** 192.168.1.120 **主机名 -** master.ltechlab.com * **从服务器 -** 192.168.1.130 **主机名 -** slave.ltechlab.com MariaDB 安装到这些机器上之后,我们继续进行本教程。如果你需要安装和配置 MariaDB 的教程,请查看[**这个教程**](/article-8320-1.html)。 ### 第 1 步 - 主服务器配置 我们现在进入到 MariaDB 中的一个命名为 `important` 的数据库,它将被复制到我们的从服务器。为开始这个过程,我们编辑名为 `/etc/my.cnf` 的文件,它是 MariaDB 的配置文件。 ``` $ vi /etc/my.cnf ``` 在这个文件中找到 `[mysqld]` 节,然后输入如下内容: ``` [mysqld] log-bin server_id=1 replicate-do-db=important bind-address=192.168.1.120 ``` 保存并退出这个文件。完成之后,需要重启 MariaDB 服务。 ``` $ systemctl restart mariadb ``` 接下来,我们登入我们的主服务器上的 Mariadb 实例。 ``` $ mysql -u root -p ``` 在它上面创建一个命名为 `slaveuser` 的为主从复制使用的新用户,然后运行如下的命令为它分配所需要的权限: ``` STOP SLAVE; GRANT REPLICATION SLAVE ON *.* TO 'slaveuser'@'%' IDENTIFIED BY 'iamslave'; FLUSH PRIVILEGES; FLUSH TABLES WITH READ LOCK; SHOW MASTER STATUS; ``` **注意:** 我们配置主从复制需要 `MASTER_LOG_FILE` 和 `MASTER_LOG_POS` 的值,它可以通过 `show master status` 来获得,因此,你一定要确保你记下了它们的值。 这些命令运行完成之后,输入 `exit` 退出这个会话。 ### 第 2 步 - 创建一个数据库备份,并将它移动到从服务器上 现在,我们需要去为我们的数据库 `important` 创建一个备份,可以使用 `mysqldump` 命令去备份。 ``` $ mysqldump -u root -p important > important_backup.sql ``` 备份完成后,我们需要重新登录到 MariaDB 数据库,并解锁我们的表。 ``` $ mysql -u root -p $ UNLOCK TABLES; ``` 然后退出这个会话。现在,我们移动我们刚才的备份到从服务器上,它的 IP 地址是:192.168.1.130。 在主服务器上的配置已经完成了,现在,我们开始配置从服务器。 ### 第 3 步:配置从服务器 我们再次去编辑(从服务器上的) `/etc/my.cnf` 文件,找到配置文件中的 `[mysqld]` 节,然后输入如下内容: ``` [mysqld] server-id = 2 replicate-do-db=important [ …] ``` 现在,我们恢复我们主数据库的备份到从服务器的 MariaDB 上,运行如下命令: ``` $ mysql -u root -p < /data/ important_backup.sql ``` 当这个恢复过程结束之后,我们将通过登入到从服务器上的 MariaDB,为数据库 `important` 上的用户 'slaveuser' 授权。 ``` $ mysql -u root -p ``` ``` GRANT ALL PRIVILEGES ON important.* TO 'slaveuser'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES; ``` 接下来,为了这个变化生效,重启 MariaDB。 ``` $ systemctl restart mariadb ``` ### 第 4 步:启动复制 记住,我们需要 `MASTER_LOG_FILE` 和 `MASTER_LOG_POS` 变量的值,它可以通过在主服务器上运行 `SHOW MASTER STATUS` 获得。现在登入到从服务器上的 MariaDB,然后通过运行下列命令,告诉我们的从服务器它应该去哪里找主服务器。 ``` STOP SLAVE; CHANGE MASTER TO MASTER_HOST= '192.168.1.110′, MASTER_USER='slaveuser', MASTER_PASSWORD='iamslave', MASTER_LOG_FILE='mariadb-bin.000001′, MASTER_LOG_POS=460; SLAVE START; SHOW SLAVE STATUS\G; ``` **注意:** 请根据你的机器的具体情况来改变主服务器的配置。 ### 第 5 步:测试复制 我们将在我们的主服务器上创建一个新表来测试主从复制是否正常工作。因此,登入到主服务器上的 MariaDB。 ``` $ mysql -u root -p ``` 选择数据库为 `important`: ``` use important; ``` 在这个数据库上创建一个名为 `test` 的表: ``` create table test (c int); ``` 然后在这个表中插入一些数据: ``` insert into test (c) value (1); ``` 检索刚才插入的值是否存在: ``` select * from test; ``` 你将会看到刚才你插入的值已经在这个新建的表中了。 现在,我们登入到从服务器的数据库中,查看主从复制是否正常工作。 ``` $ mysql -u root -p $ use important; $ select * from test; ``` 你可以看到与前面在主服务器上的命令输出是一样的。因此,说明我们的主从服务工作正常,没有发生任何问题。 我们的教程结束了,请在下面的评论框中留下你的查询/问题。 --- via: <http://linuxtechlab.com/creating-master-slave-replication-mariadb/> 作者:[Shusain](http://linuxtechlab.com/author/shsuain/) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,312
Linux 与 Unix 之差异
http://www.linuxandubuntu.com/home/linux-vs-unix
2018-02-04T23:20:00
[ "Linux", "Unix" ]
https://linux.cn/article-9312-1.html
[![Linux vs. Unix](/data/attachment/album/201802/04/232043iar4qacg04g5gbqq.jpg)](http://www.linuxandubuntu.com/home/linux-vs-unix) 在计算机时代,相当一部分的人错误地认为 **Unix** 和 **Linux** 操作系统是一样的。然而,事实恰好相反。让我们仔细看看。 ### 什么是 Unix? [![what is unix](/data/attachment/album/201802/04/232044kquua99l0dbrzk0p.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/unix_orig.png) 在 IT 领域,以操作系统而为人所知的 Unix,是 1969 年 AT&T 公司在美国新泽西所开发的(目前它的商标权由国际开放标准组织所拥有)。大多数的操作系统都受到了 Unix 的启发,而 Unix 也受到了未完成的 Multics 系统的启发。Unix 的另一版本是来自贝尔实验室的 Plan 9。 #### Unix 被用于哪里? 作为一个操作系统,Unix 大多被用在服务器、工作站,现在也有用在个人计算机上。它在创建互联网、计算机网络或客户端/服务器模型方面发挥着非常重要的作用。 #### Unix 系统的特点 * 支持多任务 * 相比 Multics 操作更加简单 * 所有数据以纯文本形式存储 * 采用单一根文件的树状存储 * 能够同时访问多用户账户 #### Unix 操作系统的组成 **a)** 单核操作系统,负责低级操作以及由用户发起的操作,内核之间的通信通过系统调用进行。 **b)** 系统工具 **c)** 其他应用程序 ### 什么是 Linux? [![what is linux](/data/attachment/album/201802/04/232045vhmmnbpmmzqqhrbi.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/linux_orig.png) 这是一个基于 Unix 操作系统原理的开源操作系统。正如开源的含义一样,它是一个可以自由下载的系统。它也可以通过编辑、添加及扩充其源代码而定制该系统。这是它最大的好处之一,而不像今天的其它操作系统(Windows、Mac OS X 等)需要付费。Unix 系统不是创建新系统的唯一模版,另外一个重要的因素是 MINIX 系统,不像 Linus,此版本被其缔造者(Andrew Tanenbaum)用于商业系统。 Linux 由 Linus Torvalds 开发于 1991 年,这是一个其作为个人兴趣的操作系统。为什么 Linux 借鉴 Unix 的一个主要原因是因为其简洁性。Linux 第一个官方版本(0.01)发布于 1991 年 9 月 17 日。虽然这个系统并不是很完美和完善,但 Linus 对它产生很大的兴趣,并在几天内,Linus 发出了一些关于 Linux 源代码扩展以及其他想法的电子邮件。 #### Linux 的特点 Linux 的基石是 Unix 内核,其基于 Unix 的基本特点以及 **POSIX** 和单独的 **UNIX 规范标准**。看起来,该操作系统官方名字取自于 **Linus**,其中其操作系统名称的尾部的 “x” 和 **Unix 系统**相联系。 #### 主要功能 * 同时运行多任务(多任务) * 程序可以包含一个或多个进程(多用途系统),且每个进程可能有一个或多个线程。 * 多用户,因此它可以运行多个用户程序。 * 个人帐户受适当授权的保护。 * 因此账户准确地定义了系统控制权。 **企鹅 Tux** 的 Logo 作者是 Larry Ewing,他选择这个企鹅作为他的开源 **Linux 操作系统**的吉祥物。**Linux Torvalds** 最初提出这个新的操作系统的名字为 “Freax” ,即为 “自由(free)” + “奇异(freak)” + x(UNIX 系统)的结合字,而不像存放它的首个版本的 FTP 服务器上所起的名字(Linux)。 --- via: <http://www.linuxandubuntu.com/home/linux-vs-unix> 作者:[linuxandubuntu](http://www.linuxandubuntu.com) 译者:[HardworkFish](https://github.com/HardworkFish) 校对:[imquanquan](https://github.com/imquanquan), [wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,313
我在 Twitch 平台直播编程的经验
https://medium.freecodecamp.org/lessons-from-my-first-year-of-live-coding-on-twitch-41a32e2f41c1
2018-02-05T21:54:00
[ "编程", "直播" ]
https://linux.cn/article-9313-1.html
去年 7 月我进行了第一次直播。不像大多数人那样在 Twitch 上进行游戏直播,我想直播的内容是我利用个人时间进行的开源工作。我对 NodeJS 硬件库有一定的研究(其中大部分是靠我自学的)。考虑到我已经在 Twitch 上有了一个直播间,为什么不再建一个更小更专业的直播间,比如 <ruby> 由 JavaScript 驱动的硬件 <rt> JavaScript powered hardware </rt></ruby> ;) 我注册了 [我自己的频道](https://www.twitch.tv/noopkat) ,从那以后我就开始定期直播。 我当然不是第一个这么做的人。[Handmade Hero](https://www.twitch.tv/handmade_hero) 是我最早看到的几个在线直播编程的程序员之一。很快这种直播方式被 Vlambeer 发扬光大,他在 Twitch 的 [Nuclear Throne live](http://nuclearthrone.com/twitch/) 直播间进行直播。我对 Vlambeer 尤其着迷。 我的朋友 [Nolan Lawson](https://twitter.com/nolanlawson) 让我 *真正开始做* 这件事,而不只是单纯地 *想要做* 。我看了他 [在周末直播开源工作](https://www.youtube.com/watch?v=9FBvpKllTQQ) ,做得棒极了。他解释了他当时做的每一件事。是的,每一件事,包括回复 GitHub 上的 <ruby> 问题 <rt> issues </rt></ruby> ,鉴别 bug ,在 <ruby> 分支 <rt> branches </rt></ruby> 中调试程序,你知道的。这令我着迷,因为 Nolan 使他的开源库得到了广泛的使用。他的开源生活和我的完全不一样。 你甚至可以看到我在他视频下的评论: ![](/data/attachment/album/201802/05/215408bwfctzc90uvdz9kk.png) 我大约在一周或更久之后建好了自己的 Twitch 频道,并摸清了 OBS 的使用方法,随后开始了自己的直播。我当时用的是 [Avrgirl-Arduino](https://github.com/noopkat/avrgirl-arduino) ,现在我依然经常用它直播。第一次直播十分粗糙。我前一天晚上排练得很晚,但直播时我依然很紧张。 那个星期六我极少的几个听众给了我很大的鼓舞,因此我坚持了下去。现在我有了超过一千个听众,他们中的一些人形成了一个可爱的小团体,他们会定期观看我的直播,我称呼他们为 “noopkat 家庭” 。 我们很开心。我想称呼这个即时编程部分为“多玩家在线组队编程”。我真的被他们每个人的热情和才能触动了。一次,一个团体成员指出我的 Arduino 开发板不能随同我的软件工作,因为板子上的芯片丢了。这真是最有趣的时刻之一。 我经常暂停直播,检查我的收件箱,看看有没有人对我提及过但没有时间完成的工作发起 <ruby> 拉取请求 <rt> pull request </rt></ruby> 。感谢我 Twitch 社区对我的帮助和鼓励。 我很想聊聊 Twitch 直播给我带来的好处,但它的内容太多了,我应该会在我下一篇博客里介绍。我在这里想要分享的,是我学习的关于如何自己实现直播编程的课程。最近几个开发者问我怎么开始自己的直播,因此我在这里想大家展示我给他们的建议! 首先,我在这里贴出一个给过我很大帮助的教程 [“Streaming and Finding Success on Twitch”](https://www.reddit.com/r/Twitch/comments/4eyva6/a_guide_to_streaming_and_finding_success_on_twitch/) 。它专注于 Twitch 与游戏直播,但也有很多和我们要做的东西相关的部分。我建议首先阅读这个教程,然后再考虑一些建立直播频道的细节(比如如何选择设备和软件)。 下面我列出我自己的配置。这些配置是从我多次的错误经验中总结出来的,其中要感谢我的直播同行的智慧与建议。(对,你们知道就是你们!) ### 软件 有很多免费的直播软件。我用的是 [Open Broadcaster Software (OBS)](https://obsproject.com/) 。它适用于大多数的平台。我觉得它十分直观且易于入门,但掌握其他的进阶功能则需要一段时间的学习。学好它你会获得很多好处!这是今天我直播时 OBS 的桌面截图(题图)。 ![](/data/attachment/album/201802/05/215410rqq4npcoarqqnylz.png) 你直播时需要在不用的“<ruby> 场景 <rt> scenes </rt></ruby>”中进行切换。一个“场景”是多个“<ruby> 素材 <rt> sources </rt></ruby>”通过堆叠和组合产生的集合。一个“素材”可以是照相机、麦克风、你的桌面、网页、动态文本、图片等等。 OBS 是一个很强大的软件。 最上方的桌面场景是我编程的环境,我直播的时候主要停留在这里。我使用 iTerm 和 vim ,同时打开一个可以切换的浏览器窗口来查阅文献或在 GitHub 上分类检索资料。 底部的黑色长方形是我的网络摄像头,人们可以通过这种更个人化的连接方式来观看我工作。 我的场景中有一些“标签”,很多都与状态或者顶栏信息有关。顶栏只是添加了个性化信息,它在直播时是一个很好的连续性素材。这是我在 [GIMP](https://www.gimp.org/) 里制作的图片,在你的场景里它会作为一个素材来加载。一些标签是从文本文件里添加的动态内容(例如最新粉丝)。另一个标签是一个 [custom one I made](https://github.com/noopkat/study-temp) ,它可以展示我直播的房间的动态温度与湿度。 我还在我的场景里设置了“闹钟”,当有人粉了我或者给了打赏,它会显示在最前方。我使用 [Stream Labs](https://streamlabs.com/) 网络服务来实现它,将它作为一个浏览器网页素材引进我的场景。 Stream Labs 也会在顶栏里给出我最新粉丝的动态信息。 我直播的时候,也会使用一个备用场景: ![](/data/attachment/album/201802/05/215414tblwlppiziafol1b.png) 当我输入密码和 API keys 的时候,我另外需要一个场景。它会在网络摄像头里展示我,但是将我的桌面用一个娱乐页面隐藏起来,这样我可以做一些私密的工作: ![](/data/attachment/album/201802/05/215416vmigz8vv3rco7ma8.png) 正如你看到的,我直播的时候没有把窗口填的太满,但我让我的观众尽可能多地看到我的内容。 但现在有一个现实的秘密:我使用 OBS 来安排我屏幕的底部和右侧,同时视频保持了 Twitch 要求的长宽比。这让我有了空间在底部查看我的事件(订阅数等),同时在右侧观看和回复我的频道聊天室。 Twitch 允许新窗口“弹出”聊天室,这很有用。 这是我完整的桌面看起来的样子: ![](/data/attachment/album/201802/05/215421dhhek6roho8hbe4r.png) 我几个月前开始做这个,还没有回顾过。我甚至不确定我的观众们有没有意识到我进行的这些精心的设置。我想他们可能会把“我可以看到每个东西”视作理所应当,而事实上我常常忙于敲代码,而看不到正在直播的东西! 你可能想知道为什么我只用一个显示器。这是因为两个显示器在我直播的时候太难以管理了。我很快意识到这一点,并且恢复了单屏。 ### 硬件 我从使用便宜的器材开始,当我意识到我会长期坚持直播之后,才将它们逐渐换成更好的。开始的时候尽量使用你现有的器材,即使是只用电脑内置的摄像头与麦克风。 现在我使用 Logitech Pro C920 网络摄像头,和一个固定有支架的 Blue Yeti 麦克风。花费是值得的。我直播的质量完全不同了。 我使用大屏显示器(27"),因为我之前说的,使用两个屏幕对我来说不方便。我常常错过聊天,因为我经常不检查我的第二屏幕。你可能觉得使用两个屏幕很方便,但对我来说,把所有东西放在一个屏幕上有利于我对所有事情保持注意力。 这基本上就是硬件部分的大部分内容了。我没有使用复杂的设置。 如果你感兴趣,我的桌面看起来不错,除了刺眼的麦克风: ![](/data/attachment/album/201802/05/215421z57tii2jtz213tv6.jpg) ### 建议 最后这里有一些我通过实践得出的一般性建议,这使我的直播从整体来看变得更好,更有趣。 #### 布告板 花点时间建立一个好的布告版。布告板是位于每个人频道底部的小内容框。我把它们看作新的个人空间窗口(真的)。理想的布告板可以有类似于聊天规则,有关直播内容的信息,你使用的电脑和设备,你最喜欢的猫的种类,等等这样的东西。任何关于个人形象的内容都可以。我们可以看看其他人(尤其是热播播主)的理想的布告板是什么样的! 一个我的布告板的例子: ![](/data/attachment/album/201802/05/215422bnmw6fpxutfevua0.png) #### 聊天 聊天真的很重要。你可能会被中途观看你直播的人一遍又一遍地问同样的问题,如果可以像现实生活中那样聊天那样会很方便。“你正在做什么?”是我敲代码的时候别人最常问我的问题。我用 [Nightbot](https://beta.nightbot.tv/) 设置了一个聊天快捷命令。当你输入一些像 *whatamidoing*(我正在做什么) 这样的单词时,会自动给出我事先设好的解释。 当人们问问题或者给出一些有趣的评论时,要回复他们!和他们说谢谢,说他们的 Twitch 用的很好,他们会感谢你的关心和认可。一开始的时候很难对这些都保持注意力,但你做得多了之后,你会发现同时做这几件事变得更容易了。尝试着每两分钟就花几秒去关注聊天室。 当你编程的时候,*解释你正在做的事* 。多说点。开开玩笑。即使我碰到了麻烦,我也会说:“哦,糟糕,我忘了这个方法怎么用了,我 Google 一下看看”。人们一般都很友好,有时他们还会和你一起寻找解决的办法。这很有趣,让人们一直看着你。 如果播主一直安静地坐在那敲代码,不去聊天,也不管他新粉丝的信息,我会很快对他失去兴趣。 很可能你 99% 的观众都很友好,并且都有好奇心。我偶尔还是会碰到挑衅的人,但 Twitch 提供的检查工具可以有效避免这种情况。 #### 准备时间 尽量将你的配置“自动化”。我的终端是 iTerm ,它可以让你保存窗口排列和字体大小的配置,这样你以后就可以再现这些配置。我有一个直播时的配置和一个不直播时的配置,这非常省事。我输入一个命令,所有东西就都在合适的位置并保持最完美的尺寸,并可以使用了。 还有其他的应用可以用来自动化你的窗口位置,看看有没有对你有用的。 让你的字体在终端和编辑器中尽可能的大,这样所有人都能看清。 #### 定期直播 让你的日程表更有规律。我一周只直播一次,但总是在同一时间。如果你临时有事不能在你平常直播的时间直播,要让人们知道。这让我保持了一些固定观众。一些人喜欢固定的时间,这就像和朋友在一起一样。你和你的社区在一个社交圈子里,所以要像对待朋友一样对待他们。 我想要提高我更新直播的频率,但我知道因为旅游的缘故我不能适应超过一周一次的直播频率。我正在尝试找到一种可以让我在路上也能高质量地直播的方法。或许可以临时将我聊天和写代码的过程保存起来,周末直播的时候再放出来。我仍然在探索这些办法! #### 紧张心理 当你即将开始的时候,你会感觉很奇怪,不适应。你会在人们看着你写代码的时候感到紧张。这很正常!尽管我之前有过公共演说的经历,我一开始的时候还是感到陌生而不适应。我感觉我无处可藏,这令我害怕。我想:“大家可能都觉得我的代码很糟糕,我是一个糟糕的开发者。”这是一个困扰了我 *整个职业生涯* 的想法,对我来说不新鲜了。我知道带着这些想法,我不能在发布到 GitHub 之前仔细地再检查一遍代码,而这样做更有利于我保持我作为开发者的声誉。 我从 Twitch 直播中发现了很多关于我代码风格的东西。我知道我的风格绝对是“先让它跑起来,然后再考虑可读性,然后再考虑运行速度”。我不再在前一天晚上提前排练好直播的内容(一开始的三、四次直播我都是这么做的),所以我在 Twitch 上写的代码是相当粗糙的,我还得保证它们运行起来没问题。当我不看别人的聊天和讨论的时候,我可以写出我最好的代码,这样是没问题的。但我总会忘记我使用过无数遍的方法的名字,而且每次直播的时候都会犯“愚蠢的”错误。一般来说,这不是一个让你能达到你最好状态的生产环境。 我的 Twitch 社区从来不会因为这个苛求我,反而是他们帮了我很多。他们理解我正同时做着几件事,而且真的给了很多务实的意见和建议。有时是他们帮我找到了解决方法,有时是我要向他们解释为什么他们的建议不适合解决这个问题。这真的很像一般意义的组队编程! 我想这种“不管重要不重要,什么都说”的情况对于直播这种媒介来说是一种优势,而不是劣势。它让我想的更多。理解一个观念很重要,那就是没有完美的程序员,也没有完美的代码。对于一个新手程序员来说这是令人耳目一新的经历,对我这个老手来说却是微不足道的。 ### 总结 如果你想过在 Twitch 上直播,我希望你试一下!如果你想知道怎么迈出第一步,我希望这篇博客可以帮的到你。 如果你周日想要加入我的直播,你可以 [订阅我的 Twitch 频道](https://www.twitch.tv/noopkat) :) 最后我想说一下,我自己十分感谢 [Mattias Johansson](https://twitter.com/mpjme) 在我早期开始直播的时候给我的建议和鼓励。他的 [FunFunFunction YouTube channel](https://www.youtube.com/channel/UCO1cgjhGzsSYb1rsB4bFe4Q) 也是一个令人激动的定期直播频道。 另:许多人问过我的键盘和其他工作设备是什么样的, [这是我使用的器材的完整列表](https://gist.github.com/noopkat/5de56cb2c5917175c5af3831a274a2c8) 。感谢关注! --- via: <https://medium.freecodecamp.org/lessons-from-my-first-year-of-live-coding-on-twitch-41a32e2f41c1> 作者:[Suz Hinton](https://medium.freecodecamp.org/@suzhinton) 译者:[lonaparte](https://github.com/lonaparte) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,314
为什么应该在 Linux 上使用命名管道
https://www.networkworld.com/article/3251853/linux/why-use-named-pipes-on-linux.html
2018-02-05T22:58:08
[ "管道", "命名管道", "mkfifo" ]
https://linux.cn/article-9314-1.html
> > 命名管道并不常用,但是它们为进程间通讯提供了一些有趣的特性。 > > > ![](/data/attachment/album/201802/05/225813e9cvc9gscgz7mzgw.jpg) 估计每一位 Linux 使用者都熟悉使用 “|” 符号将数据从一个进程传输到另一个进程的操作。它使用户能简便地从一个命令输出数据到另一个命令,并筛选出想要的数据而无须写脚本进行选择、重新格式化等操作。 还有另一种管道, 虽然也叫“管道”这个名字却有着非常不同的性质。即您可能尚未使用甚至尚未知晓的——命名管道。 普通管道与命名管道的一个主要区别就是命名管道是以文件形式实实在在地存在于文件系统中的,没错,它们表现出来就是文件。但是与其它文件不同的是,命名管道文件似乎从来没有文件内容。即使用户往命名管道中写入大量数据,该文件看起来还是空的。 ### 如何在 Linux 上创建命名管道 在我们研究这些空空如也的命名管道之前,先追根溯源来看看命名管道是如何被创建的。您应该使用名为 `mkfifo` 的命令来创建它们。为什么提及“FIFO”?是因为命名管道也被认为是一种 FIFO 特殊文件。术语 “FIFO” 指的是它的<ruby> 先进先出 <rt> first-in, first-out </rt></ruby>特性。如果你将冰淇淋盛放到碟子中,然后可以品尝它,那么你执行的就是一个LIFO(<ruby> 后进先出 <rt> last-in, first-out </rt></ruby>操作。如果你通过吸管喝奶昔,那你就在执行一个 FIFO 操作。好,接下来是一个创建命名管道的例子。 ``` $ mkfifo mypipe $ ls -l mypipe prw-r-----. 1 shs staff 0 Jan 31 13:59 mypipe ``` 注意一下特殊的文件类型标记 “p” 以及该文件大小为 0。您可以将重定向数据写入命名管道文件,而文件大小依然为 0。 ``` $ echo "Can you read this?" > mypipe ``` 正如上面所说,敲击回车后似乎什么都没有发生(LCTT 译注:没有返回命令行提示符)。 另外再开一个终端,查看该命名管道的大小,依旧是 0: ``` $ ls -l mypipe prw-r-----. 1 shs staff 0 Jan 31 13:59 mypipe ``` 也许这有违直觉,用户输入的文本已经进入该命名管道,而你仍然卡在输入端。你或者其他人应该等在输出端,并准备读取放入管道的数据。现在让我们读取看看。 ``` $ cat mypipe Can you read this? ``` 一旦被读取之后,管道中的内容就没有了。 另一种研究命名管道如何工作的方式是通过将放入数据的操作置入后台来执行两个操作(将数据放入管道,而在另外一段读取它)。 ``` $ echo "Can you read this?" > mypipe & [1] 79302 $ cat mypipe Can you read this? [1]+ Done echo "Can you read this?" > mypipe ``` 一旦管道被读取或“耗干”,该管道就清空了,尽管我们还能看见它并再次使用。可为什么要费此周折呢? ### 为何要使用命名管道? 命名管道很少被使用的理由似乎很充分。毕竟在 Unix 系统上,总有多种不同的方式完成同样的操作。有多种方式写文件、读文件、清空文件,尽管命名管道比它们来得更高效。 值得注意的是,命名管道的内容驻留在内存中而不是被写到硬盘上。数据内容只有在输入输出端都打开时才会传送。用户可以在管道的输出端打开之前向管道多次写入。通过使用命名管道,用户可以创建一个进程写入管道并且另外一个进程读取管道的流程,而不用关心协调二者时间上的同步。 用户可以创建一个单纯等待数据出现在管道输出端的进程,并在拿到输出数据后对其进行操作。下列命令我们采用 `tail` 来等待数据出现。 ``` $ tail -f mypipe ``` 一旦供给管道数据的进程结束了,我们就可以看到一些输出。 ``` $ tail -f mypipe Uranus replicated to WCDC7 Saturn replicated to WCDC8 Pluto replicated to WCDC9 Server replication operation completed ``` 如果研究一下向命名管道写入的进程,用户也许会惊讶于它的资源消耗之少。在下面的 `ps` 命令输出中,唯一显著的资源消耗是虚拟内存(VSZ 那一列)。 ``` ps u -P 80038 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND shs 80038 0.0 0.0 108488 764 pts/4 S 15:25 0:00 -bash ``` 命名管道与 Unix/Linux 系统上更常用的管道相比足以不同到拥有另一个名号,但是“管道”确实能反映出它们如何在进程间传送数据的形象,故将称其为“命名管道”还真是恰如其分。也许您在执行操作时就能从这个聪明的 Unix/Linux 特性中获益匪浅呢。 --- via: <https://www.networkworld.com/article/3251853/linux/why-use-named-pipes-on-linux.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 译者:[YPBlib](https://github.com/YPBlib) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,315
如何在 Linux 系统查询机器最近重启时间
https://www.cyberciti.biz/tips/linux-last-reboot-time-and-date-find-out.html
2018-02-06T00:25:24
[ "重启", "时间" ]
https://linux.cn/article-9315-1.html
![](/data/attachment/album/201802/06/002508sxtqeyxmetsjgeul.jpg) 在你的 Linux 或类 UNIX 系统中,你是如何查询系统上次重新启动的日期和时间?怎样显示系统关机的日期和时间? `last` 命令不仅可以按照时间从近到远的顺序列出该会话的特定用户、终端和主机名,而且还可以列出指定日期和时间登录的用户。输出到终端的每一行都包括用户名、会话终端、主机名、会话开始和结束的时间、会话持续的时间。要查看 Linux 或类 UNIX 系统重启和关机的时间和日期,可以使用下面的命令。 * `last` 命令 * `who` 命令 ### 使用 who 命令来查看系统重新启动的时间/日期 你需要在终端使用 [who](https://www.cyberciti.biz/faq/unix-linux-who-command-examples-syntax-usage/ "See Linux/Unix who command examples for more info") 命令来打印有哪些人登录了系统,`who` 命令同时也会显示上次系统启动的时间。使用 `last` 命令来查看系统重启和关机的日期和时间,运行: ``` $ who -b ``` 示例输出: ``` system boot 2017-06-20 17:41 ``` 使用 `last` 命令来查询最近登录到系统的用户和系统重启的时间和日期。输入: ``` $ last reboot | less ``` 示例输出: [![Fig.01: last command in action](/data/attachment/album/201802/06/002526ha8bfu85gahgur5b.jpg)](https://www.cyberciti.biz/tips/wp-content/uploads/2006/04/last-reboot.jpg) 或者,尝试输入: ``` $ last reboot | head -1 ``` 示例输出: ``` reboot system boot 4.9.0-3-amd64 Sat Jul 15 19:19 still running ``` `last` 命令通过查看文件 `/var/log/wtmp` 来显示自 wtmp 文件被创建时的所有登录(和登出)的用户。每当系统重新启动时,这个伪用户 `reboot` 就会登录。因此,`last reboot` 命令将会显示自该日志文件被创建以来的所有重启信息。 ### 查看系统上次关机的时间和日期 可以使用下面的命令来显示上次关机的日期和时间: ``` $ last -x|grep shutdown | head -1 ``` 示例输出: ``` shutdown system down 2.6.15.4 Sun Apr 30 13:31 - 15:08 (01:37) ``` 命令中, * `-x`:显示系统关机和运行等级改变信息 这里是 `last` 命令的其它的一些选项: ``` $ last $ last -x $ last -x reboot $ last -x shutdown ``` 示例输出: ![Fig.01: How to view last Linux System Reboot Date/Time ](/data/attachment/album/201802/06/002526rvvf9ifl79vzvry9.jpg) ### 查看系统正常的运行时间 评论区的读者建议的另一个命令如下: ``` $ uptime -s ``` 示例输出: ``` 2017-06-20 17:41:51 ``` ### OS X/Unix/FreeBSD 查看最近重启和关机时间的命令示例 在终端输入下面的命令: ``` $ last reboot ``` 在 OS X 示例输出结果如下: ``` reboot ~ Fri Dec 18 23:58 reboot ~ Mon Dec 14 09:54 reboot ~ Wed Dec 9 23:21 reboot ~ Tue Nov 17 21:52 reboot ~ Tue Nov 17 06:01 reboot ~ Wed Nov 11 12:14 reboot ~ Sat Oct 31 13:40 reboot ~ Wed Oct 28 15:56 reboot ~ Wed Oct 28 11:35 reboot ~ Tue Oct 27 00:00 reboot ~ Sun Oct 18 17:28 reboot ~ Sun Oct 18 17:11 reboot ~ Mon Oct 5 09:35 reboot ~ Sat Oct 3 18:57 wtmp begins Sat Oct 3 18:57 ``` 查看关机日期和时间,输入: ``` $ last shutdown ``` 示例输出: ``` shutdown ~ Fri Dec 18 23:57 shutdown ~ Mon Dec 14 09:53 shutdown ~ Wed Dec 9 23:20 shutdown ~ Tue Nov 17 14:24 shutdown ~ Mon Nov 16 21:15 shutdown ~ Tue Nov 10 13:15 shutdown ~ Sat Oct 31 13:40 shutdown ~ Wed Oct 28 03:10 shutdown ~ Sun Oct 18 17:27 shutdown ~ Mon Oct 5 09:23 wtmp begins Sat Oct 3 18:57 ``` ### 如何查看是谁重启和关闭机器? 你需要[启用 psacct 服务然后运行下面的命令](https://www.cyberciti.biz/tips/howto-log-user-activity-using-process-accounting.html)来查看执行过的命令(包括用户名),在终端输入 [lastcomm](https://www.cyberciti.biz/faq/linux-unix-lastcomm-command-examples-usage-syntax/ "See Linux/Unix lastcomm command examples for more info") 命令查看信息 ``` # lastcomm userNameHere # lastcomm commandNameHere # lastcomm | more # lastcomm reboot # lastcomm shutdown ### 或者查看重启和关机时间 # lastcomm | egrep 'reboot|shutdown' ``` 示例输出: ``` reboot S X root pts/0 0.00 secs Sun Dec 27 23:49 shutdown S root pts/1 0.00 secs Sun Dec 27 23:45 ``` 我们可以看到 root 用户在当地时间 12 月 27 日星期二 23:49 在 pts/0 重新启动了机器。 ### 参见 * 更多信息可以查看 man 手册(`man last`)和参考文章 [如何在 Linux 服务器上使用 tuptime 命令查看历史和统计的正常的运行时间](https://www.cyberciti.biz/hardware/howto-see-historical-statistical-uptime-on-linux-server/)。 ### 关于作者 作者是 nixCraft 的创立者,同时也是一名经验丰富的系统管理员,也是 Linux,类 Unix 操作系统 shell 脚本的培训师。他曾与全球各行各业的客户工作过,包括 IT,教育,国防和空间研究以及非营利部门等等。你可以在 [Twitter](https://twitter.com/nixcraft)、[Facebook](https://facebook.com/nixcraft)、[Google+](https://plus.google.com/+CybercitiBiz) 关注他。 --- via: <https://www.cyberciti.biz/tips/linux-last-reboot-time-and-date-find-out.html> 作者:[Vivek Gite](https://www.cyberciti.biz/) 译者:[amwps290](https://github.com/amwps290) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,316
容器、GPL 与左版:无需过度担忧
https://opensource.com/article/18/1/containers-gpl-and-copyleft
2018-02-06T18:43:00
[ "许可证", "容器" ]
https://linux.cn/article-9316-1.html
> > 提要:想要知道开源许可证对 Linux 容器有什么影响吗?以下问题您需要了解。 > > > ![](/data/attachment/album/201802/06/184358sadosnlnarp9ybqr.png) 尽管目前开源软件已经成为主流,但是不断涌现的软件新技术以及重新流行的旧技术有时也会引发对开源许可证的强烈担忧。大多数情况下,大家关注的焦点是 GPL 许可证,特别是经常(有时是误导性的)被描述为 GPL 衍生作品问题的<ruby> 左版 <rp> ( </rp> <rt> copyleft </rt> <rp> ) </rp></ruby>范围问题。 将该问题结构化的一个不完美方式是:遵循 GPL 许可证的代码在某种意义上与专有代码相结合,形成一个单独的修改后作品,是否可以解释为该专有代码受到 GPL 许可证的约束?虽然我们还没有看到很多针对 Linux 容器的问题,但随着容器的采用持续增长,我们预计会有更多的问题提出来。不过,有相当简单的方式可以表明,容器不会引发新的或有关 GPL 范围的问题。 法规和判例在解释类似 GPL 这样的许可证方面几乎没有什么帮助。另一方面,即使是在自由软件基金会(FSF)不是相关软件版权持有者的典型情况下,我们中的许多人也重视 FSF 作为 GPL 起草者和管理者的解释性观点。除了作为许可证文本的作者之外,FSF 多年来一直致力于向社区提供有关许可证的评论和指导。基于自由软件政策的公共利益使命和领导力,FSF 的观点具有特殊的可信度和影响力。 FSF 关于 GPL 解释的现有指导,有助于理解在容器中将 GPL 代码和非 GPL 代码包含在内所产生的效果。FSF 在界定左版范围时重点考虑了进程的边界,以及多个软件组件之间的通信机制和语义,以确定它们的紧密集成程度是否足以被视为 GPL 意义下的单个程序。例如,[GNU 许可证常见问题解答](https://www.gnu.org/licenses/gpl-faq.en.html#MereAggregation)认为,在没有足够<ruby> “密切” <rp> ( </rp> <rt> intimate </rt> <rp> ) </rp></ruby>通信的情况下,**管道、套接字和命令行参数通常可以被隐含认为是具备独立性的机制**。 考虑容器中有 GPL 代码和专有代码可能共存并执行的情况,实际上,容器是一个孤立的用户空间栈。在 [OCI 容器映像格式](https://github.com/opencontainers/image-spec/blob/master/spec.md)中,代码被打包为一组文件系统的变更层,基本层通常是一个没有内核的精简传统 Linux 发行版。与非容器化的 Linux 发行版的用户空间一样,这些基本层包括许多遵循 GPL 许可证(GPL v2 以及 GPL v3)的软件包,以及许多遵循被认为与 GPL 不兼容许可证的软件包,并且通常作为专有以及开源应用的运行环境。GPL v2 中“<ruby> <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html#section2"> 单纯聚合 </a> <rp> ( </rp> <rt> mere aggregation </rt> <rp> ) </rp></ruby>”条款(以及 GPL v3 中有关“[聚合](https://www.gnu.org/licenses/gpl.html#section5)”的条款)表明,这种组合通常是可以被接受的,在 GPL 中进行了特别考虑,如果不兼容的被许可组件是分离和独立的,就不会影响两个程序的许可。 当然,在特定情况下,两个组件之间的关系可能不是“单纯聚合”,但是在 Linux 系统上的非容器化用户空间中运行的软件也是如此。容器或容器映像的技术构成中没有任何暗示表明需要应用特殊形式的左版范围分析。 因此,当考察运行在容器中的代码和运行在容器外面的代码之间的关系时,几乎肯定会满足“分离和独立”的标准。代码将作为单独的进程运行,使用容器的整个技术要点是与运行在系统上的其他软件隔离。 现在考虑两个组件的情况,其中一个遵循 GPL 许可证,另一个为专有软件,它们运行在分离但可能交互的容器中,也许作为使用[微服务](https://www.redhat.com/en/topics/microservices)体系结构设计的应用程序的一部分。在没有特别不寻常事实的情况下,我们不应该期望看到左版的范围跨越多个容器。分离的容器涉及分离的进程。通过网络接口在容器之间进行通信类似于管道、套接字等机制,多容器微服务场景似乎排除了 FSF 所定义的“[密切](https://www.gnu.org/licenses/gpl-faq.en.html#GPLPlugins)”通信。使用多个容器的应用程序的组成可能不是 GPL 范围问题的决定因素,但它使组件之间的技术边界更加明显,并为争论“分离性”提供了强有力的基础。这其中也没有容器的技术特征暗示对左版的范围分析应用不同或更严格的方法。 过度关心分发 GPL 代码潜在影响的企业可能会试图禁止其开发人员将任何此类代码添加到计划分发的容器映像中,目的就是为了避免依据 GPL 许可证分发代码,但这是一个容易受到质疑的策略。如上所述,常规容器映像的基础层将包含多个遵循 GPL 的组件。如果该公司将容器映像推送到注册表中,通常无法保证这其中不包含基础层,即使它被广泛共享。 另一方面,通过隔离 GPL 代码和专有代码,企业可能会决定采用容器化作为减少左版范围影响的一种手段,虽然人们希望基于技术上的益处,而不是莫须有的对 GPL 焦虑所带来的法律担忧来推动该决策。而在非容器化环境中,两个相互作用的软件组件之间的关系往往是单纯聚合,容器化所提供的“分离性”证据可能让那些担心 GPL 范围的人们感到安慰。 共享容器映像时,可能会出现开源许可证合规义务问题。但是,对于容器来说,没有什么技术上的不同或独一无二的东西可以改变这些义务的性质,或者使它们更难满足。关于左版的范围,容器化应该能够缓解过度的担忧。 --- 作者简介:Richard Fontana 是红帽公司法律部门产品和技术团队的高级商业顾问。 他的大部分工作都集中在开源相关的法律问题上。 译者简介:薛亮,集慧智佳知识产权咨询公司高级咨询师,擅长专利检索、专利分析、竞争对手跟踪、FTO分析、开源软件知识产权风险分析,致力于为互联网企业、高科技公司提供知识产权咨询服务。 ![](/data/attachment/album/201802/06/184136idk4jss0a42b449t.png)
200
OK
Though open source is thoroughly mainstream, new software technologies and old technologies that get newly popularized sometimes inspire hand-wringing about open source licenses. Most often the concern is about the GNU General Public License (GPL), and specifically the scope of its copyleft requirement, which is often described (somewhat misleadingly) as the GPL’s derivative work issue. One imperfect way of framing the question is whether GPL-licensed code, when combined in some sense with proprietary code, forms a single modified work such that the proprietary code could be interpreted as being subject to the terms of the GPL. While we haven’t yet seen much of that concern directed to Linux containers, we expect more questions to be raised as adoption of containers continues to grow. But it’s fairly straightforward to show that containers do *not* raise new or concerning GPL scope issues. Statutes and case law provide little help in interpreting a license like the GPL. On the other hand, many of us give significant weight to the interpretive views of the Free Software Foundation (FSF), the drafter and steward of the GPL, even in the typical case where the FSF is not a copyright holder of the software at issue. In addition to being the author of the license text, the FSF has been engaged for many years in providing commentary and guidance on its licenses to the community. Its views have special credibility and influence based on its public interest mission and leadership in free software policy. The FSF’s existing guidance on GPL interpretation has relevance for understanding the effects of including GPL and non-GPL code in containers. The FSF has placed emphasis on the process boundary when considering copyleft scope, and on the mechanism and semantics of the communication between multiple software components to determine whether they are closely integrated enough to be considered a single program for GPL purposes. For example, the [GNU Licenses FAQ](https://www.gnu.org/licenses/gpl-faq.en.html#MereAggregation) takes the view that pipes, sockets, and command-line arguments are mechanisms that are normally suggestive of separateness (in the absence of sufficiently "intimate" communications). Consider the case of a container in which both GPL code and proprietary code might coexist and execute. A container is, in essence, an isolated userspace stack. In the [OCI container image format](https://github.com/opencontainers/image-spec/blob/master/spec.md), code is packaged as a set of filesystem changeset layers, with the base layer normally being a stripped-down conventional Linux distribution without a kernel. As with the userspace of non-containerized Linux distributions, these base layers invariably contain many GPL-licensed packages (both GPLv2 and GPLv3), as well as packages under licenses considered GPL-incompatible, and commonly function as a runtime for proprietary as well as open source applications. The ["mere aggregation" clause](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html#section2) in GPLv2 (as well as its counterpart GPLv3 provision on ["aggregates"](https://www.gnu.org/licenses/gpl.html#section5)) shows that this type of combination is generally acceptable, is specifically contemplated under the GPL, and has no effect on the licensing of the two programs, assuming incompatibly licensed components are separate and independent. Of course, in a given situation, the relationship between two components may not be "mere aggregation," but the same is true of software running in non-containerized userspace on a Linux system. There is nothing in the technical makeup of containers or container images that suggests a need to apply a special form of copyleft scope analysis. It follows that when looking at the relationship between code running in a container and code running outside a container, the "separate and independent" criterion is almost certainly met. The code will run as separate processes, and the whole technical point of using containers is isolation from other software running on the system. Now consider the case where two components, one GPL-licensed and one proprietary, are running in separate but potentially interacting containers, perhaps as part of an application designed with a [microservices](https://www.redhat.com/en/topics/microservices) architecture. In the absence of very unusual facts, we should not expect to see copyleft scope extending across multiple containers. Separate containers involve separate processes. Communication between containers by way of network interfaces is analogous to such mechanisms as pipes and sockets, and a multi-container microservices scenario would seem to preclude what the FSF calls "[intimate](https://www.gnu.org/licenses/gpl-faq.en.html#GPLPlugins)" communication by definition. The composition of an application using multiple containers may not be dispositive of the GPL scope issue, but it makes the technical boundaries between the components more apparent and provides a strong basis for arguing separateness. Here, too, there is no technical feature of containers that suggests application of a different and stricter approach to copyleft scope analysis. A company that is overly concerned with the potential effects of distributing GPL-licensed code might attempt to prohibit its developers from adding any such code to a container image that it plans to distribute. Insofar as the aim is to avoid distributing code under the GPL, this is a dubious strategy. As noted above, the base layers of conventional container images will contain multiple GPL-licensed components. If the company pushes a container image to a registry, there is normally no way it can guarantee that this will not include the base layer, even if it is widely shared. On the other hand, the company might decide to embrace containerization as a means of limiting copyleft scope issues by isolating GPL and proprietary code—though one would hope that technical benefits would drive the decision, rather than legal concerns likely based on unfounded anxiety about the GPL. While in a non-containerized setting the relationship between two interacting software components will often be mere aggregation, the evidence of separateness that containers provide may be comforting to those who worry about GPL scope. Open source license compliance obligations may arise when sharing container images. But there’s nothing technically different or unique about containers that changes the nature of these obligations or makes them harder to satisfy. With respect to copyleft scope, containerization should, if anything, ease the concerns of the extra-cautious. ## Comments are closed.
9,317
在 Linux 上检测 IDE/SATA SSD 硬盘的传输速度
https://www.cyberciti.biz/tips/how-fast-is-linux-sata-hard-disk.html
2018-02-06T19:22:56
[ "磁盘", "测试" ]
https://linux.cn/article-9317-1.html
![](/data/attachment/album/201802/06/192251yo898kcvcc24cqhp.jpg) 你知道你的硬盘在 Linux 下传输有多快吗?不打开电脑的机箱或者机柜,你知道它运行在 SATA I (150 MB/s) 、 SATA II (300 MB/s) 还是 SATA III (6.0Gb/s) 呢? 你能够使用 `hdparm` 和 `dd` 命令来检测你的硬盘速度。它为各种硬盘的 ioctls 提供了命令行界面,这是由 Linux 系统的 ATA / IDE / SATA 设备驱动程序子系统所支持的。有些选项只能用最新的内核才能正常工作(请确保安装了最新的内核)。我也推荐使用最新的内核源代码的包含头文件来编译 `hdparm` 命令。 ### 如何使用 hdparm 命令来检测硬盘的传输速度 以 root 管理员权限登录并执行命令: ``` $ sudo hdparm -tT /dev/sda ``` 或者, ``` $ sudo hdparm -tT /dev/hda ``` 输出: ``` /dev/sda: Timing cached reads: 7864 MB in 2.00 seconds = 3935.41 MB/sec Timing buffered disk reads: 204 MB in 3.00 seconds = 67.98 MB/sec ``` 为了检测更精准,这个操作应该**重复2-3次** 。这显示了无需访问磁盘,直接从 Linux 缓冲区缓存中读取的速度。这个测量实际上是被测系统的处理器、高速缓存和存储器的吞吐量的指标。这是一个 [for 循环的例子](https://www.cyberciti.biz/faq/bash-for-loop/),连续运行测试 3 次: ``` for i in 1 2 3; do hdparm -tT /dev/hda; done ``` 这里, * `-t` :执行设备读取时序 * `-T` :执行缓存读取时间 * `/dev/sda` :硬盘设备文件 要 [找出 SATA 硬盘的连接速度](https://www.cyberciti.biz/faq/linux-command-to-find-sata-harddisk-link-speed/) ,请输入: ``` sudo hdparm -I /dev/sda | grep -i speed ``` 输出: ``` * Gen1 signaling speed (1.5Gb/s) * Gen2 signaling speed (3.0Gb/s) * Gen3 signaling speed (6.0Gb/s) ``` 以上输出表明我的硬盘可以使用 1.5Gb/s、3.0Gb/s 或 6.0Gb/s 的速度。请注意,您的 BIOS/主板必须支持 SATA-II/III 才行: ``` $ dmesg | grep -i sata | grep 'link up' ``` [![Linux Check IDE SATA SSD Hard Disk Transfer Speed](/data/attachment/album/201802/06/192257w78t9tpt17k7r72k.jpg)](https://www.cyberciti.biz/tips/wp-content/uploads/2007/10/Linux-Check-IDE-SATA-SSD-Hard-Disk-Transfer-Speed.jpg) ### dd 命令 你使用 `dd` 命令也可以获取到相应的速度信息: ``` dd if=/dev/zero of=/tmp/output.img bs=8k count=256k rm /tmp/output.img ``` 输出: ``` 262144+0 records in 262144+0 records out 2147483648 bytes (2.1 GB) copied, 23.6472 seconds, `90.8 MB/s` ``` 下面是 [推荐的 dd 命令参数](https://www.cyberciti.biz/faq/howto-linux-unix-test-disk-performance-with-dd-command/): ``` dd if=/dev/input.file of=/path/to/output.file bs=block-size count=number-of-blocks oflag=dsync ## GNU dd syntax ## dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync ## OR alternate syntax for GNU/dd ## dd if=/dev/zero of=/tmp/testALT.img bs=1G count=1 conv=fdatasync ``` 这是上面命令的第三个命令的输出结果: ``` 1+0 records in 1+0 records out 1073741824 bytes (1.1 GB, 1.0 GiB) copied, 4.23889 s, 253 MB/s ``` ### “磁盘与存储” - GUI 工具 您还可以使用位于“系统>管理>磁盘实用程序”菜单中的磁盘实用程序。请注意,在最新版本的 Gnome 中,它简称为“磁盘”。 #### 如何使用 Linux 上的“磁盘”测试我的硬盘的性能? 要测试硬盘的速度: 1. 从“活动概览”中打开“磁盘”(按键盘上的 super 键并键入“disks”) 2. 从“左侧窗格”的列表中选择“磁盘” 3. 选择菜单按钮并从菜单中选择“测试磁盘性能……” 4. 单击“开始性能测试……”并根据需要调整传输速率和访问时间参数。 5. 选择“开始性能测试”来测试从磁盘读取数据的速度。需要管理权限请输入密码。 以上操作的快速视频演示: <https://www.cyberciti.biz/tips/wp-content/uploads/2007/10/disks-performance.mp4> #### 只读 Benchmark (安全模式下) 然后,选择 > 只读: ![Fig.01: Linux Benchmarking Hard Disk Read Only Test Speed](/data/attachment/album/201802/06/192257lmuyvttkzzz1zx0v.png "Linux Benchmark Hard Disk Speed") 上述选项不会销毁任何数据。 #### 读写的 Benchmark(所有数据将丢失,所以要小心) 访问“系统>管理>磁盘实用程序菜单>单击性能测试>单击开始读/写性能测试按钮: ![Fig.02:Linux Measuring read rate, write rate and access time](/data/attachment/album/201802/06/192257v48g48fr4vgmrrdb.png "Linux Hard Disk Benchmark Read / Write Rate and Access Time") ### 作者 作者是 nixCraft 的创造者,是经验丰富的系统管理员,也是 Linux 操作系统/ Unix shell 脚本的培训师。他曾与全球客户以及 IT,教育,国防和空间研究以及非营利部门等多个行业合作。在Twitter,Facebook和Google+上关注他。 --- via: <https://www.cyberciti.biz/tips/how-fast-is-linux-sata-hard-disk.html> 作者:[Vivek Gite](https://www.cyberciti.biz/) 译者:[MonkeyDEcho](https://github.com/MonkeyDEcho) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,318
八种在 Linux 上生成随机密码的方法
https://kerneltalks.com/tips-tricks/8-ways-to-generate-random-password-in-linux/
2018-02-06T23:58:14
[ "密码" ]
https://linux.cn/article-9318-1.html
> > 学习使用 8 种 Linux 原生命令或第三方实用程序来生成随机密码。 > > > ![](/data/attachment/album/201802/06/235820hjcj4fw6mmxw6fzw.png) 在这篇文章中,我们将引导你通过几种不同的方式在 Linux 终端中生成随机密码。其中几种利用原生 Linux 命令,另外几种则利用极易在 Linux 机器上安装的第三方工具或实用程序实现。在这里我们利用像 `openssl`, [dd](https://kerneltalks.com/commands/learn-dd-command-with-examples/), `md5sum`, `tr`, `urandom` 这样的原生命令和 mkpasswd,randpw,pwgen,spw,gpg,xkcdpass,diceware,revelation,keepaasx,passwordmaker 这样的第三方工具。 其实这些方法就是生成一些能被用作密码的随机字母字符串。随机密码可以用于新用户的密码,不管用户基数有多大,这些密码都是独一无二的。话不多说,让我们来看看 8 种不同的在 Linux 上生成随机密码的方法吧。 ### 使用 mkpasswd 实用程序生成密码 `mkpasswd` 在基于 RHEL 的系统上随 `expect` 软件包一起安装。在基于 Debian 的系统上 `mkpasswd` 则在软件包 `whois` 中。直接安装 `mkpasswd` 软件包将会导致错误: * RHEL 系统:软件包 mkpasswd 不可用。 * Debian 系统:错误:无法定位软件包 mkpasswd。 所以按照上面所述安装他们的父软件包,就没问题了。 运行 `mkpasswd` 来获得密码 ``` root@kerneltalks# mkpasswd << on RHEL zt*hGW65c root@kerneltalks# mkpasswd teststring << on Ubuntu XnlrKxYOJ3vik ``` 这个命令在不同的系统上表现得不一样,所以工作方式各异。你也可以通过参数来控制长度等选项,可以查阅 man 手册来探索。 ### 使用 openssl 生成密码 几乎所有 Linux 发行版都包含 openssl。我们可以利用它的随机功能来生成可以用作密码的随机字母字符串。 ``` root@kerneltalks # openssl rand -base64 10 nU9LlHO5nsuUvw== ``` 这里我们使用 `base64` 编码随机函数,最后一个数字参数表示长度。 ### 使用 urandom 生成密码 设备文件 `/dev/urandom` 是另一个获得随机字符串的方法。我们使用 `tr` 功能并裁剪输出来获得随机字符串,并把它作为密码。 ``` root@kerneltalks # strings /dev/urandom |tr -dc A-Za-z0-9 | head -c20; echo UiXtr0NAOSIkqtjK4c0X ``` ### 使用 dd 命令生成密码 我们甚至可以使用 `/dev/urandom` 设备配合 [dd 命令](https://kerneltalks.com/commands/learn-dd-command-with-examples/) 来获取随机字符串。 ``` root@kerneltalks# dd if=/dev/urandom bs=1 count=15|base64 -w 0 15+0 records in 15+0 records out 15 bytes (15 B) copied, 5.5484e-05 s, 270 kB/s QMsbe2XbrqAc2NmXp8D0 ``` 我们需要将结果通过 `base64` 编码使它能被人类可读。你可以使用数值来获取想要的长度。想要获得更简洁的输出的话,可以将“标准错误输出”重定向到 `/dev/null`。简洁输出的命令是: ``` root@kerneltalks # dd if=/dev/urandom bs=1 count=15 2>/dev/null|base64 -w 0 F8c3a4joS+a3BdPN9C++ ``` ### 使用 md5sum 生成密码 另一种获取可用作密码的随机字符串的方法是计算 MD5 校验值!校验值看起来确实像是随机字符串组合在一起,我们可以用作密码。确保你的计算源是个变量,这样的话每次运行命令时生成的校验值都不一样。比如 `date` ![date 命令](https://kerneltalks.com/commands/date-time-management-using-timedatectl-command/) 总会生成不同的输出。 ``` root@kerneltalks # date |md5sum 4d8ce5c42073c7e9ca4aeffd3d157102 - ``` 在这里我们将 `date` 命令的输出通过 `md5sum` 得到了校验和!你也可以用 [cut 命令](https://kerneltalks.com/linux/cut-command-examples/) 裁剪你需要的长度。 ### 使用 pwgen 生成密码 `pwgen` 软件包在类似 [EPEL 软件仓库](https://kerneltalks.com/package/how-to-install-epel-repository/)(LCTT 译注:企业版 Linux 附加软件包)中。`pwgen` 更专注于生成可发音的密码,但它们不在英语词典中,也不是纯英文的。标准发行版仓库中可能并不包含这个工具。安装这个软件包然后运行 `pwgen` 命令行。Boom ! ``` root@kerneltalks # pwgen thu8Iox7 ahDeeQu8 Eexoh0ai oD8oozie ooPaeD9t meeNeiW2 Eip6ieph Ooh1tiet cootad7O Gohci0vo wah9Thoh Ohh3Ziur Ao1thoma ojoo6aeW Oochai4v ialaiLo5 aic2OaDa iexieQu8 Aesoh4Ie Eixou9ph ShiKoh0i uThohth7 taaN3fuu Iege0aeZ cah3zaiW Eephei0m AhTh8guo xah1Shoo uh8Iengo aifeev4E zoo4ohHa fieDei6c aorieP7k ahna9AKe uveeX7Hi Ohji5pho AigheV7u Akee9fae aeWeiW4a tiex8Oht ``` 你的终端会呈现出一个密码列表!你还想要什么呢?好吧。你还想再仔细探索的话, `pwgen` 还有很多自定义选项,这些都可以在 man 手册里查阅到。 ### 使用 gpg 工具生成密码 GPG 是一个遵循 OpenPGP 标准的加密及签名工具。大部分 gpg 工具都预先被安装好了(至少在我的 RHEL7 上是这样)。但如果没有的话你可以寻找 `gpg` 或 `gpg2` 软件包并[安装](https://kerneltalks.com/tools/package-installation-linux-yum-apt/)它。 使用下面的命令以从 gpg 工具生成密码。 ``` root@kerneltalks # gpg --gen-random --armor 1 12 mL8i+PKZ3IuN6a7a ``` 这里我们传了生成随机字节序列选项(`--gen-random`),质量为 1(第一个参数),次数 12 (第二个参数)。选项 `--armor` 保证以 `base64` 编码输出。 ### 使用 xkcdpass 生成密码 著名的极客幽默网站 [xkcd](https://xkcd.com/),发表了一篇非常有趣的文章,是关于好记但又复杂的密码的。你可以在[这里](https://xkcd.com/936/)阅读。所以 `xkcdpass` 工具就受这篇文章启发,做了这样的工作!这是一个 Python 软件包,可以在[这里](https://pypi.python.org/pypi/xkcdpass/)的 Python 的官网上找到它。 ![](/data/attachment/album/201802/06/235825mza9bbbbpypzj99h.png) 所有的安装使用说明都在上面那个页面提及了。这里是安装步骤和我的测试 RHEL 服务器的输出,以供参考。 ``` root@kerneltalks # wget https://pypi.python.org/packages/b4/d7/3253bd2964390e034cf0bba227db96d94de361454530dc056d8c1c096abc/xkcdpass-1.14.3.tar.gz#md5=5f15d52f1d36207b07391f7a25c7965f --2018-01-23 19:09:17-- https://pypi.python.org/packages/b4/d7/3253bd2964390e034cf0bba227db96d94de361454530dc056d8c1c096abc/xkcdpass-1.14.3.tar.gz Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223 Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 871848 (851K) [binary/octet-stream] Saving to: ‘xkcdpass-1.14.3.tar.gz’ 100%[==============================================================================================================================>] 871,848 --.-K/s in 0.01s 2018-01-23 19:09:17 (63.9 MB/s) - ‘xkcdpass-1.14.3.tar.gz’ saved [871848/871848] root@kerneltalks # tar -xvf xkcdpass-1.14.3.tar.gz xkcdpass-1.14.3/ xkcdpass-1.14.3/examples/ xkcdpass-1.14.3/examples/example_import.py xkcdpass-1.14.3/examples/example_json.py xkcdpass-1.14.3/examples/example_postprocess.py xkcdpass-1.14.3/LICENSE.BSD xkcdpass-1.14.3/MANIFEST.in xkcdpass-1.14.3/PKG-INFO xkcdpass-1.14.3/README.rst xkcdpass-1.14.3/setup.cfg xkcdpass-1.14.3/setup.py xkcdpass-1.14.3/tests/ xkcdpass-1.14.3/tests/test_list.txt xkcdpass-1.14.3/tests/test_xkcdpass.py xkcdpass-1.14.3/tests/__init__.py xkcdpass-1.14.3/xkcdpass/ xkcdpass-1.14.3/xkcdpass/static/ xkcdpass-1.14.3/xkcdpass/static/eff-long xkcdpass-1.14.3/xkcdpass/static/eff-short xkcdpass-1.14.3/xkcdpass/static/eff-special xkcdpass-1.14.3/xkcdpass/static/fin-kotus xkcdpass-1.14.3/xkcdpass/static/ita-wiki xkcdpass-1.14.3/xkcdpass/static/legacy xkcdpass-1.14.3/xkcdpass/static/spa-mich xkcdpass-1.14.3/xkcdpass/xkcd_password.py xkcdpass-1.14.3/xkcdpass/__init__.py xkcdpass-1.14.3/xkcdpass.1 xkcdpass-1.14.3/xkcdpass.egg-info/ xkcdpass-1.14.3/xkcdpass.egg-info/dependency_links.txt xkcdpass-1.14.3/xkcdpass.egg-info/entry_points.txt xkcdpass-1.14.3/xkcdpass.egg-info/not-zip-safe xkcdpass-1.14.3/xkcdpass.egg-info/PKG-INFO xkcdpass-1.14.3/xkcdpass.egg-info/SOURCES.txt xkcdpass-1.14.3/xkcdpass.egg-info/top_level.txt root@kerneltalks # cd xkcdpass-1.14.3 root@kerneltalks # python setup.py install running install running bdist_egg running egg_info writing xkcdpass.egg-info/PKG-INFO writing top-level names to xkcdpass.egg-info/top_level.txt writing dependency_links to xkcdpass.egg-info/dependency_links.txt writing entry points to xkcdpass.egg-info/entry_points.txt reading manifest file 'xkcdpass.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'xkcdpass.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py creating build creating build/lib creating build/lib/xkcdpass copying xkcdpass/xkcd_password.py -> build/lib/xkcdpass copying xkcdpass/__init__.py -> build/lib/xkcdpass creating build/lib/xkcdpass/static copying xkcdpass/static/eff-long -> build/lib/xkcdpass/static copying xkcdpass/static/eff-short -> build/lib/xkcdpass/static copying xkcdpass/static/eff-special -> build/lib/xkcdpass/static copying xkcdpass/static/fin-kotus -> build/lib/xkcdpass/static copying xkcdpass/static/ita-wiki -> build/lib/xkcdpass/static copying xkcdpass/static/legacy -> build/lib/xkcdpass/static copying xkcdpass/static/spa-mich -> build/lib/xkcdpass/static creating build/bdist.linux-x86_64 creating build/bdist.linux-x86_64/egg creating build/bdist.linux-x86_64/egg/xkcdpass copying build/lib/xkcdpass/xkcd_password.py -> build/bdist.linux-x86_64/egg/xkcdpass copying build/lib/xkcdpass/__init__.py -> build/bdist.linux-x86_64/egg/xkcdpass creating build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/eff-long -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/eff-short -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/eff-special -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/fin-kotus -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/ita-wiki -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/legacy -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/spa-mich -> build/bdist.linux-x86_64/egg/xkcdpass/static byte-compiling build/bdist.linux-x86_64/egg/xkcdpass/xkcd_password.py to xkcd_password.pyc byte-compiling build/bdist.linux-x86_64/egg/xkcdpass/__init__.py to __init__.pyc creating build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/entry_points.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO creating dist creating 'dist/xkcdpass-1.14.3-py2.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing xkcdpass-1.14.3-py2.7.egg creating /usr/lib/python2.7/site-packages/xkcdpass-1.14.3-py2.7.egg Extracting xkcdpass-1.14.3-py2.7.egg to /usr/lib/python2.7/site-packages Adding xkcdpass 1.14.3 to easy-install.pth file Installing xkcdpass script to /usr/bin Installed /usr/lib/python2.7/site-packages/xkcdpass-1.14.3-py2.7.egg Processing dependencies for xkcdpass==1.14.3 Finished processing dependencies for xkcdpass==1.14.3 ``` 现在运行 `xkcdpass` 命令,将会随机给出你几个像下面这样的字典单词: ``` root@kerneltalks # xkcdpass broadside unpadded osmosis statistic cosmetics lugged ``` 你可以用这些单词作为其他命令,比如 `md5sum` 的输入,来获取随机密码(就像下面这样),甚至你也可以用每个单词的第 N 个字母来生成你的密码! ``` root@kerneltalks # xkcdpass |md5sum 45f2ec9b3ca980c7afbd100268c74819 - root@kerneltalks # xkcdpass |md5sum ad79546e8350744845c001d8836f2ff2 - ``` 或者你甚至可以把所有单词串在一起作为一个超长的密码,不仅非常好记,也不容易被电脑程序攻破。 Linux 上还有像 [Diceware](http://world.std.com/%7Ereinhold/diceware.html)、 [KeePassX](https://www.keepassx.org/)、 [Revelation](https://packages.debian.org/sid/gnome/revelation)、 [PasswordMaker](https://passwordmaker.org/) 这样的工具,也可以考虑用来生成强随机密码。 --- via: <https://kerneltalks.com/tips-tricks/8-ways-to-generate-random-password-in-linux/> 作者:[kerneltalks](https://kerneltalks.com) 译者:[heart4lor](https://github.com/heart4lor) 校对:[Locez](https://github.com/locez) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
*Learn 8 different ways to generate a random password in Linux using Linux native commands or third-party utilities.* ![](https://z5.kerneltalks.com/wp-content/uploads/2020/06/different-ways-to-generate-password-in-linux.png) In this article, we will walk you through various different ways to generate a random password in the Linux terminal. Few of them are using native Linux commands and others are using third-party tools or utilities which can easily be installed on the Linux machine. Here we are looking at native commands like,`openssl` [dd](https://kerneltalks.com/commands/learn-dd-command-with-examples/), `md5sum` , `tr` , `urandom` and third-party tools like mkpasswd, randpw, pwgen, spw, gpg, xkcdpass, diceware, revelation, keepaasx, passwordmaker. These are actually ways to get some random alphanumeric string which can be utilized as a password. Random passwords can be used for new users so that there will be uniqueness no matter how large your user base is. Without any further delay, let’s jump into those 15 different ways to generate the random password in Linux. ### Generate password using mkpasswd utility `mkpasswd` comes with the install of `expect` package on RHEL based systems. On Debian based systems `mkpasswd` comes with package `whois` . Trying to install `mkpasswd` package will result in error – *No package mkpasswd available.* on RHEL system and *E: Unable to locate package mkpasswd* in Debian based. So install their parent packages as mentioned above and you are good to go. Run `mkpasswd` to get passwords ``` root@kerneltalks# mkpasswd << on RHEL zt*hGW65c root@kerneltalks# mkpasswd teststring << on Ubuntu XnlrKxYOJ3vik ``` Command behaves differently on different systems so work accordingly. There are many switches that can be used to control length etc parameters. You can explore them from man pages. ### Generate password using OpenSSL OpenSSL comes in build with almost all the Linux distributions. We can use its random function to get alphanumeric string generated which can be used as a password. ``` root@kerneltalks # openssl rand -base64 10 nU9LlHO5nsuUvw== ``` Here, we are using `base64` encoding with random function and last digit for the argument to `base64` encoding. ### Generate password using urandom The device file `/dev/urandom` is another source of getting random characters. We are using `tr` function and trimming output to get the random string to use as a password. ``` root@kerneltalks # strings /dev/urandom |tr -dc A-Za-z0-9 | head -c20; echo UiXtr0NAOSIkqtjK4c0X ``` ### dd command to generate password We can even use `/dev/urandom` device along with [dd command ](https://kerneltalks.com/commands/learn-dd-command-with-examples/)to get a string of random characters. ``` root@kerneltalks# dd if=/dev/urandom bs=1 count=15|base64 -w 0 15+0 records in 15+0 records out 15 bytes (15 B) copied, 5.5484e-05 s, 270 kB/s QMsbe2XbrqAc2NmXp8D0 ``` We need to pass output through `base64` encoding to make it human-readable. You can play with count value to get the desired length. For much cleaner output, redirect std2 to `/dev/null` . The clean command is – ``` root@kerneltalks # dd if=/dev/urandom bs=1 count=15 2>/dev/null|base64 -w 0 F8c3a4joS+a3BdPN9C++ ``` ### Using md5sum to generate password Another way to get an array of random characters which can be used as the password is to calculate MD5 checksum! s you know checksum value indeed looks like random characters grouped together we can use it as the password. Make sure you use the source as something variable so that you get different checksum every time you run command. For example `date` ! [date command](https://kerneltalks.com/commands/date-time-management-using-timedatectl-command/) always yields changing the output. ``` root@kerneltalks # date |md5sum 4d8ce5c42073c7e9ca4aeffd3d157102 - ``` Here we passed `date` command output to `md5sum` and get the checksum hash! You can use [cut command](https://kerneltalks.com/linux/cut-command-examples/) to get the desired length of the output. ### Generate password using pwgen `pwgen` package comes with [repositories like EPEL](https://kerneltalks.com/package/how-to-install-epel-repository/). `pwgen` is more focused on generating passwords that are pronounceable but not a dictionary word or not in plain English. You may not find it in standard distribution repo. Install the package and run `pwgen` command. Boom! ``` root@kerneltalks # pwgen thu8Iox7 ahDeeQu8 Eexoh0ai oD8oozie ooPaeD9t meeNeiW2 Eip6ieph Ooh1tiet cootad7O Gohci0vo wah9Thoh Ohh3Ziur Ao1thoma ojoo6aeW Oochai4v ialaiLo5 aic2OaDa iexieQu8 Aesoh4Ie Eixou9ph ShiKoh0i uThohth7 taaN3fuu Iege0aeZ cah3zaiW Eephei0m AhTh8guo xah1Shoo uh8Iengo aifeev4E zoo4ohHa fieDei6c aorieP7k ahna9AKe uveeX7Hi Ohji5pho AigheV7u Akee9fae aeWeiW4a tiex8Oht ``` You will be presented with the list of passwords at your terminal! What else you want? Ok. You still want to explore, `pwgen` comes with many custom options that can be referred for man page. ### Generate password using gpg tool GPG is an OpenPGP encryption and signing tool. Mostly gpg tool comes pre-installed (at least it is on my RHEL7). But if not you can look for `gpg` or `gpg2` package and [install](https://kerneltalks.com/tools/package-installation-linux-yum-apt/) it. Use below command to generate password from gpg tool. ``` root@kerneltalks # gpg --gen-random --armor 1 12 mL8i+PKZ3IuN6a7a ``` Here we are passing generate random byte sequence switch (`--gen-random` ) of quality 1 (first argument) with a count of 12 (second argument). Switch `--armor` ensures output is `base64` encoded. ### Generate password using xkcdpass Famous geek humor website [xkcd](https://xkcd.com/), published a very interesting post about memorable but still complex passwords. You can view it [here](https://xkcd.com/936/). So `xkcdpass` tool took inspiration from this post and did its work! It’s a python package and available on python’s official website [here](https://pypi.python.org/pypi/xkcdpass/) All installation and usage instructions are mentioned on that page. Here is install steps and outputs from my test RHEL server for your reference. ``` root@kerneltalks # wget https://pypi.python.org/packages/b4/d7/3253bd2964390e034cf0bba227db96d94de361454530dc056d8c1c096abc/xkcdpass-1.14.3.tar.gz#md5=5f15d52f1d36207b07391f7a25c7965f --2018-01-23 19:09:17-- https://pypi.python.org/packages/b4/d7/3253bd2964390e034cf0bba227db96d94de361454530dc056d8c1c096abc/xkcdpass-1.14.3.tar.gz Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223 Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 871848 (851K) [binary/octet-stream] Saving to: ‘xkcdpass-1.14.3.tar.gz’ 100%[==============================================================================================================================>] 871,848 --.-K/s in 0.01s 2018-01-23 19:09:17 (63.9 MB/s) - ‘xkcdpass-1.14.3.tar.gz’ saved [871848/871848] root@kerneltalks # tar -xvf xkcdpass-1.14.3.tar.gz xkcdpass-1.14.3/ xkcdpass-1.14.3/examples/ xkcdpass-1.14.3/examples/example_import.py xkcdpass-1.14.3/examples/example_json.py xkcdpass-1.14.3/examples/example_postprocess.py xkcdpass-1.14.3/LICENSE.BSD xkcdpass-1.14.3/MANIFEST.in xkcdpass-1.14.3/PKG-INFO xkcdpass-1.14.3/README.rst xkcdpass-1.14.3/setup.cfg xkcdpass-1.14.3/setup.py xkcdpass-1.14.3/tests/ xkcdpass-1.14.3/tests/test_list.txt xkcdpass-1.14.3/tests/test_xkcdpass.py xkcdpass-1.14.3/tests/__init__.py xkcdpass-1.14.3/xkcdpass/ xkcdpass-1.14.3/xkcdpass/static/ xkcdpass-1.14.3/xkcdpass/static/eff-long xkcdpass-1.14.3/xkcdpass/static/eff-short xkcdpass-1.14.3/xkcdpass/static/eff-special xkcdpass-1.14.3/xkcdpass/static/fin-kotus xkcdpass-1.14.3/xkcdpass/static/ita-wiki xkcdpass-1.14.3/xkcdpass/static/legacy xkcdpass-1.14.3/xkcdpass/static/spa-mich xkcdpass-1.14.3/xkcdpass/xkcd_password.py xkcdpass-1.14.3/xkcdpass/__init__.py xkcdpass-1.14.3/xkcdpass.1 xkcdpass-1.14.3/xkcdpass.egg-info/ xkcdpass-1.14.3/xkcdpass.egg-info/dependency_links.txt xkcdpass-1.14.3/xkcdpass.egg-info/entry_points.txt xkcdpass-1.14.3/xkcdpass.egg-info/not-zip-safe xkcdpass-1.14.3/xkcdpass.egg-info/PKG-INFO xkcdpass-1.14.3/xkcdpass.egg-info/SOURCES.txt xkcdpass-1.14.3/xkcdpass.egg-info/top_level.txt root@kerneltalks # cd xkcdpass-1.14.3 root@kerneltalks # python setup.py install running install running bdist_egg running egg_info writing xkcdpass.egg-info/PKG-INFO writing top-level names to xkcdpass.egg-info/top_level.txt writing dependency_links to xkcdpass.egg-info/dependency_links.txt writing entry points to xkcdpass.egg-info/entry_points.txt reading manifest file 'xkcdpass.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'xkcdpass.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py creating build creating build/lib creating build/lib/xkcdpass copying xkcdpass/xkcd_password.py -> build/lib/xkcdpass copying xkcdpass/__init__.py -> build/lib/xkcdpass creating build/lib/xkcdpass/static copying xkcdpass/static/eff-long -> build/lib/xkcdpass/static copying xkcdpass/static/eff-short -> build/lib/xkcdpass/static copying xkcdpass/static/eff-special -> build/lib/xkcdpass/static copying xkcdpass/static/fin-kotus -> build/lib/xkcdpass/static copying xkcdpass/static/ita-wiki -> build/lib/xkcdpass/static copying xkcdpass/static/legacy -> build/lib/xkcdpass/static copying xkcdpass/static/spa-mich -> build/lib/xkcdpass/static creating build/bdist.linux-x86_64 creating build/bdist.linux-x86_64/egg creating build/bdist.linux-x86_64/egg/xkcdpass copying build/lib/xkcdpass/xkcd_password.py -> build/bdist.linux-x86_64/egg/xkcdpass copying build/lib/xkcdpass/__init__.py -> build/bdist.linux-x86_64/egg/xkcdpass creating build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/eff-long -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/eff-short -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/eff-special -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/fin-kotus -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/ita-wiki -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/legacy -> build/bdist.linux-x86_64/egg/xkcdpass/static copying build/lib/xkcdpass/static/spa-mich -> build/bdist.linux-x86_64/egg/xkcdpass/static byte-compiling build/bdist.linux-x86_64/egg/xkcdpass/xkcd_password.py to xkcd_password.pyc byte-compiling build/bdist.linux-x86_64/egg/xkcdpass/__init__.py to __init__.pyc creating build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/entry_points.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO copying xkcdpass.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO creating dist creating 'dist/xkcdpass-1.14.3-py2.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing xkcdpass-1.14.3-py2.7.egg creating /usr/lib/python2.7/site-packages/xkcdpass-1.14.3-py2.7.egg Extracting xkcdpass-1.14.3-py2.7.egg to /usr/lib/python2.7/site-packages Adding xkcdpass 1.14.3 to easy-install.pth file Installing xkcdpass script to /usr/bin Installed /usr/lib/python2.7/site-packages/xkcdpass-1.14.3-py2.7.egg Processing dependencies for xkcdpass==1.14.3 Finished processing dependencies for xkcdpass==1.14.3 ``` Now running `xkcdpass` command will give you a random set of dictionary words like below – ``` root@kerneltalks # xkcdpass broadside unpadded osmosis statistic cosmetics lugged ``` You can use these words as input to other commands like `md5sum` to get the random password (like below) or you can even use the Nth letter of each word to form your password! ``` root@kerneltalks # xkcdpass |md5sum 45f2ec9b3ca980c7afbd100268c74819 - root@kerneltalks # xkcdpass |md5sum ad79546e8350744845c001d8836f2ff2 - ``` Or even you can use all those words together as such a long password which is easy to remember for a user and very hard to crack using the computer program. There are tools like [Diceware](http://world.std.com/~reinhold/diceware.html), [KeePassX](https://www.keepassx.org/), [Revelation](https://packages.debian.org/sid/gnome/revelation), [PasswordMaker](https://passwordmaker.org/) for Linux which can be considered for making strong random passwords. There’s an another simple way to do that Running: head -c 21 /dev/urandom |base64 You can change the number in order to get more characters I remain mystified about the raison d’etre for these applications. They are not any good for generating passwords that people will remember; there are several techniques to create passwords off the top of one’s head that will be reasonably difficult to break, and memorable at the same time. When it comes generating random passwords that will be protected by a master password, piping /dev/[u]random, as suggested, is more than enough. For throwaway passwords (for sites that obnoxiously force you to register, even if you are going to visit them once) they are irrelevant. Quite frankly, they do little more than filling out a much-needed gap in the Linux world. good article thanks for sharing this article
9,319
手把手指导您使用 Git
https://opensource.com/article/18/1/step-step-guide-git
2018-02-07T09:50:15
[ "Git", "GitHub" ]
https://linux.cn/article-9319-1.html
![](/data/attachment/album/201802/07/095020f7a0abz7xpp0u328.png) 如果您从未使用过 [Git](https://opensource.com/resources/what-is-git),甚至可能从未听说过它。莫慌张,只需要一步步地跟着这篇入门教程,很快您就会在 [GitHub](https://opensource.com/life/15/11/short-introduction-github) 上拥有一个全新的 Git 仓库。 在开始之前,让我们先理清一个常见的误解:Git 并不是 GitHub。Git 是一套版本控制系统(或者说是一款软件),能够协助您跟踪计算机程序和文件在任何时间的更改。它同样允许您在程序、代码和文件操作上与同事协作。GitHub 以及类似服务(包括 GitLab 和 BitBucket)都属于部署了 Git 程序的网站,能够托管您的代码。 ### 步骤 1:申请一个 GitHub 账户 在 [GitHub.com](https://github.com/) 网站上(免费)创建一个账户是最简单的方式。 ![](/data/attachment/album/201802/07/095020sdrezlrjk3e2ncz2.png) 选择一个用户名(比如说,octocat123),输入您的邮箱地址和密码,然后点击 **Sign up for GitHub**。进入之后,您将看到下方插图的界面: ![](/data/attachment/album/201802/07/095020o5fld520f0zrggcl.png) ### 步骤 2:创建一个新的仓库 一个仓库( repository),类似于能储存物品的场所或是容器;在这里,我们创建仓库存储代码。在 `+` 符号(在插图的右上角,我已经选中它了) 的下拉菜单中选择 **New Repository**。 ![](/data/attachment/album/201802/07/095021ccassasd742umx7i.png) 给您的仓库命名(比如说,Demo)然后点击 **Create Repository**。无需考虑本页面的其他选项。 恭喜!您已经在 GitHub.com 中建立了您的第一个仓库。 ### 步骤 3: 创建文件 当仓库创建完毕后,界面将和下方一致: ![](/data/attachment/album/201802/07/095021fm2caykj6j2hfyjk.png) 不必惊慌,它比看上去简单。跟紧步骤。忽略其他内容,注意截图上的 “...or create a new repository on the command line,”。 在您的计算机中打开终端。 ![](/data/attachment/album/201802/07/095022lzfy06qrq9v4vbk0.png) 键入 `git` 然后回车。如果命令行显示 `bash: git: command not found`,在您的操作系统或发行版 [安装 Git](https://www.linuxbabe.com/linux-server/install-git-verion-control-on-linux-debianubuntufedoraarchlinux#crt-2) 命令。键入 `git` 并回车检查是否成功安装;如果安装成功,您将看见大量关于使用该命令的说明信息。 在终端内输入: ``` mkdir Demo ``` 这个命令将会创建一个名为 Demo 的目录(文件夹)。 如下命令将会切换终端目录,跳转到 Demo 目录: ``` cd Demo ``` 然后输入: ``` echo "#Demo" >> README.md ``` 创建一个名为 `README.md` 的文件,并写入 `#Demo`。检查文件是否创建成功,请输入: ``` cat README.md ``` 这将会为您显示 `README.md` 文件的内容,如果文件创建成功,您的终端会有如下显示: ![](/data/attachment/album/201802/07/095023nie51jid1wjq1wqw.png) 使用 Git 程序告诉您的电脑,Demo 是一个被 Git 管理的目录,请输入: ``` git init ``` 然后,告诉 Git 程序您关心的文件并且想在此刻起跟踪它的任何改变,请输入: ``` git add README.md ``` ### 步骤 4:创建一次提交 目前为止,您已经创建了一个文件,并且已经通知了 Git,现在,是时候创建一次<ruby> 提交 <rt> commit </rt></ruby>了。提交可以看作是一个里程碑。每当完成一些工作之时,您都可以创建一次提交,保存文件当前版本,这样一来,您可以返回之前的版本,并且查看那时候的文件内容。无论何时您修改了文件,都可以对文件创建一个上一次的不一样的新版本。 创建一次提交,请输入: ``` git commit -m "first commit" ``` 就是这样!刚才您创建了包含一条注释为 “first commit” 的 Git 提交。每次提交,您都必须编辑注释信息;它不仅能协助您识别提交,而且能让您理解此时您对文件做了什么修改。这样到了明天,如果您在文件中添加新的代码,您可以写一句提交信息:“添加了新的代码”,然后当您一个月后回来查看提交记录或者 Git 日志(即提交列表),您还能知道当时的您在文件夹里做了什么。 ### 步骤 5: 将您的计算机与 GitHub 仓库相连接 现在,是时候用如下命令将您的计算机连接到 GitHub 仓库了: ``` git remote add origin https://github.com/<your_username>/Demo.git ``` 让我们一步步的分析这行命令。我们通知 Git 去添加一个叫做 `origin` (起源)的,拥有地址为 `https://github.com/<your_username>/Demo.git`(它也是您的仓库的 GitHub 地址) 的 `remote` (远程仓库)。当您提交代码时,这允许您在 GitHub.com 和 Git 仓库交互时使用 `origin` 这个名称而不是完整的 Git 地址。为什么叫做 `origin`?当然,您可以叫点别的,只要您喜欢(惯例而已)。 现在,我们已经将本地 Demo 仓库副本连接到了其在 GitHub.com 远程副本上。您的终端看起来如下: ![](/data/attachment/album/201802/07/095024jyrubjj82zf2uqb6.png) 此刻我们已经连接到远程仓库,可以推送我们的代码 到 GitHub.com(例如上传 `README.md` 文件)。 执行完毕后,您的终端会显示如下信息: ![](/data/attachment/album/201802/07/095024fcii0difz0fvgnc8.png) 然后,如果您访问 `https://github.com/<your_username>/Demo`,您会看到截图内显示的情况: ![](/data/attachment/album/201802/07/095025nzttwrljxokj1br9.png) 就是这么回事!您已经创建了您的第一个 GitHub 仓库,连接到了您的电脑,并且从你的计算机推送(或者称:上传)一个文件到 GitHub.com 名叫 Demo 的远程仓库上了。下一次,我将编写关于 Git 复制(从 GitHub 上下载文件到你的计算机上)、添加新文件、修改现存文件、推送(上传)文件到 GitHub。 --- via: <https://opensource.com/article/18/1/step-step-guide-git> 作者:[Kedar Vijay Kulkarni](https://opensource.com/users/kkulkarn) 译者:[CYLeft](https://github.com/CYLeft) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
If you've never used [Git](https://opensource.com/resources/what-is-git), you may be nervous about it. There's nothing to worry about—just follow along with this step-by-step getting-started guide, and you will soon have a new Git repository hosted on [GitHub](https://opensource.com/life/15/11/short-introduction-github). Before we dive in, let's clear up a common misconception: Git isn't the same thing as GitHub. Git is a version-control system (i.e., a piece of software) that helps you keep track of your computer programs and files and the changes that are made to them over time. It also allows you to collaborate with your peers on a program, code, or file. GitHub and similar services (including GitLab and BitBucket) are websites that host a Git server program to hold your code. ## Step 1: Create a GitHub account The easiest way to get started is to create an account on [GitHub.com](https://github.com/) (it's free). ![Create a GitHub account](https://opensource.com/sites/default/files/u128651/git_guide1.png) opensource.com Pick a username (e.g., octocat123), enter your email address and a password, and click **Sign up for GitHub**. Once you are in, it will look something like this: ![Signed in to GitHub](https://opensource.com/sites/default/files/u128651/git_guide2.png) opensource.com ## Step 2: Create a new repository A repository is like a place or a container where something is stored; in this case we're creating a Git repository to store code. To create a new repository, select **New Repository** from the `+` sign dropdown menu (you can see I've selected it in the upper-right corner in the image above). ![Create a new repository](https://opensource.com/sites/default/files/u128651/git_guide3.png) opensource.com Enter a name for your repository (e.g, "Demo") and click **Create Repository**. Don't worry about changing any other options on this page. Congratulations! You have set up your first repo on GitHub.com. ## Step 3: Create a file Once your repo is created, it will look like this: ![New repo on GitHub](https://opensource.com/sites/default/files/u128651/git_guide4.png) opensource.com Don't panic, it's simpler than it looks. Stay with me. Look at the section that starts "...or create a new repository on the command line," and ignore the rest for now. Open the *Terminal* program on your computer. ![Terminal](https://opensource.com/sites/default/files/u128651/git_guide5.png) opensource.com Type `git` and hit **Enter**. If it says command `bash: git: command not found` , then [install Git](https://www.linuxbabe.com/linux-server/install-git-verion-control-on-linux-debianubuntufedoraarchlinux#crt-2) with the command for your Linux operating system or distribution. Check the installation by typing `git` and hitting **Enter**; if it's installed, you should see a bunch of information about how you can use the command. In the terminal, type: ``` ````mkdir Demo` This command will create a directory (or folder) named *Demo*. Change your terminal to the *Demo* directory with the command: ``` ````cd Demo` Then enter: ``` ````echo "#Demo" >> README.md` This creates a file named `README.md` and writes `#Demo` in it. To check that the file was created successfully, enter: ``` ````cat README.md` This will show you what is inside the `README.md` file, if the file was created correctly. Your terminal will look like this: ![Terminal](https://opensource.com/sites/default/files/u128651/git_guide7.png) opensource.com To tell your computer that *Demo* is a directory managed by the Git program, enter: ``` ````git init` Then, to tell the Git program you care about this file and want to track any changes from this point forward, enter: ``` ````git add README.md` ## Step 4: Make a commit So far you've created a file and told Git about it, and now it's time to create a *commit*. Commit can be thought of as a milestone. Every time you accomplish some work, you can write a Git commit to store that version of your file, so you can go back later and see what it looked like at that point in time. Whenever you make a change to your file, you create a new version of that file, different from the previous one. To make a commit, enter: ``` ````git commit -m "first commit"` That's it! You just created a Git commit and included a message that says *first commit*. You must always write a message in commit; it not only helps you identify a commit, but it also enables you to understand what you did with the file at that point. So tomorrow, if you add a new piece of code in your file, you can write a commit message that says, *Added new code*, and when you come back in a month to look at your commit history or Git log (the list of commits), you will know what you changed in the files. ## Step 5: Connect your GitHub repo with your computer Now, it's time to connect your computer to GitHub with the command: ``` ````git remote add origin https://github.com/<your_username>/Demo.git` Let's look at this command step by step. We are telling Git to add a `remote` called `origin` with the address `https://github.com/<your_username>/Demo.git` (i.e., the URL of your Git repo on GitHub.com). This allows you to interact with your Git repository on GitHub.com by typing `origin` instead of the full URL and Git will know where to send your code. Why `origin` ? Well, you can name it anything else if you'd like. Now we have connected our local copy of the *Demo* repository to its remote counterpart on GitHub.com. Your terminal looks like this: ![Terminal](https://opensource.com/sites/default/files/u128651/git_guide8.png) opensource.com Now that we have added the remote, we can push our code (i.e., upload our `README.md` file) to GitHub.com. Once you are done, your terminal will look like this: ![Terminal](https://opensource.com/sites/default/files/u128651/git_guide9.png) opensource.com And if you go to `https://github.com/<your_username>/Demo` you will see something like this: ![Demo repo on GitHub](https://opensource.com/sites/default/files/u128651/git_guide10.png) opensource.com That's it! You have created your first GitHub repo, connected it to your computer, and pushed (or uploaded) a file from your computer to your repository called *Demo* on GitHub.com. Next time, I will write about Git cloning (downloading your code from GitHub to your computer), adding new files, modifying existing files, and pushing (uploading) files to GitHub. ## 10 Comments
9,320
Linux 终端下的多媒体应用
https://www.linux.com/learn/intro-to-linux/2018/1/multimedia-apps-linux-console
2018-02-07T12:35:55
[ "终端", "多媒体" ]
https://linux.cn/article-9320-1.html
![](/data/attachment/album/201802/07/123559ud6bj12jkjjg2kks.jpg) > > Linux 终端是支持多媒体的,所以你可以在终端里听音乐,看电影,看图片,甚至是阅读 PDF。 > > > 在我的上一篇文章里,我们了解到 Linux 终端是可以支持多媒体的。是的,这是真的!你可以使用 Mplayer、fbi 和 fbgs 来实现不打开 X 会话就听音乐、看电影、看照片,甚至阅读 PDF。此外,你还可以通过 CMatrix 来体验黑客帝国(Matrix)风格的屏幕保护。 不过你可能需要对系统进行一些修改才能达到前面这些目的。下文的操作都是在 Ubuntu 16.04 上进行的。 ### MPlayer 你可能会比较熟悉功能丰富的 MPlayer。它支持几乎所有格式的视频与音频,并且能在绝大部分现有的平台上运行,像 Linux、Android、Windows、Mac、Kindle、OS/2 甚至是 AmigaOS。不过,要在你的终端运行 MPlayer 可能需要多做一点工作,这些工作与你使用的 Linux 发行版有关。来,我们先试着播放一个视频: ``` $ mplayer [视频文件名] ``` 如果上面的命令正常执行了,那么很好,接下来你可以把时间放在了解 MPlayer 的常用选项上了,譬如设定视频大小等。但是,有些 Linux 发行版在对<ruby> 帧缓冲 <rt> framebuffer </rt></ruby>的处理方式上与早期的不同,那么你就需要进行一些额外的设置才能让其正常工作了。下面是在最近的 Ubuntu 发行版上需要做的一些操作。 首先,将你自己添加到 `video` 用户组。 其次,确认 `/etc/modprobe.d/blacklist-framebuffer.conf` 文件中包含这样一行:`#blacklist vesafb`。这一行应该默认被注释掉了,如果不是的话,那就手动把它注释掉。此外的其他模块行需要确认没有被注释,这样设置才能保证其他那些模块不会被载入。注:如果你想要更深入的利用<ruby> 帧缓冲 <rt> framebuffer </rt></ruby>,这些针对你的显卡的模块可以使你获得更好的性能。 然后,在 `/etc/initramfs-tools/modules` 的结尾增加两个模块:`vesafb` 和 `fbcon`,并且更新 iniramfs 镜像: ``` $ sudo nano /etc/initramfs-tools/modules # List of modules that you want to include in your initramfs. # They will be loaded at boot time in the order below. fbcon vesafb $ sudo update-initramfs -u ``` [fbcon](https://www.mjmwired.net/kernel/Documentation/fb/fbcon.txt) 是 Linux <ruby> 帧缓冲 <rt> framebuffer </rt></ruby>终端,它运行在<ruby> 帧缓冲 <rt> framebuffer </rt></ruby>之上并为其增加图形功能。而它需要一个<ruby> 帧缓冲 <rt> framebuffer </rt></ruby>设备,这则是由 `vesafb` 模块来提供的。 接下来,你需要修改你的 GRUB2 配置。在 `/etc/default/grub` 中你将会看到类似下面的一行: ``` GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" ``` 它也可能还会有一些别的参数,不用管它,在其后加上 `vga=789`: ``` GRUB_CMDLINE_LINUX_DEFAULT="quiet splash vga=789" ``` 重启之后进入你的终端(`Ctrl+Alt+F1`)(LCTT 译注:在某些发行版中 `Ctrl+Alt+F1` 默认为图形界面,可以尝试 `Ctrl+Alt+F2`),然后就可以尝试播放一个视频了。下面的命令指定了 `fbdev2` 为视频输出设备,虽然我还没弄明白如何去选择用哪个输入设备,但是我用它成功过。默认的视频大小是 320x240,在此我给缩放到了 960: ``` $ mplayer -vo fbdev2 -vf scale -zoom -xy 960 AlienSong_mp4.mov ``` 来看图 1。粗糙的画面是由于我原视频的质量不高,而不是 MPlayer 的显示问题。 ![图 1 播放视频](/data/attachment/album/201802/07/123600pmn98my83739ssz8.jpg) MPlayer 可以播放 CD、DVD 以及网络视频流,并且还有一系列的回放选项,这些将作为作业留给大家自己去发现。 ### fbi 图片查看器 `fbi` 是一个帧缓冲图片查看器。在大部分的 Linux 发行版中,它被包含在 [fbida](https://www.kraxel.org/blog/linux/fbida/) 包里。它原生支持一些常见的图片格式,而如果你安装了 `convert`(来自于 Image Magick),那么它还能借此打开一些其他格式。最简单的用法是用来查看一个图片文件: ``` $ fbi 文件名 ``` 你可以使用方向键来在大图片中移动视野,使用 `+` 和 `-` 来缩放,或者使用 `r` 或 `l` 来向右或向左旋转 90 度。`Escape` 键则可以关闭查看的图片。此外,你还可以给 `fbi` 一个文件列表来实现幻灯播放: ``` $ fbi --list 文件列表.txt ``` `fbi` 还支持自动缩放。还可以使用 `-a` 选项来控制缩放比例。`--autoup` 和 `--autodown` 则是用于告知 `fbi` 只进行放大或者缩小。要调整图片切换时淡入淡出的时间则可以使用 `--blend [时间]` 来指定一个以毫秒为单位的时间长度。使用 `k` 和 `j` 键则可以切换文件列表中的上一张或下一张图片。 `fbi` 还提供了命令来为你浏览过的文件创建文件列表,或者将你的命令导出到文件中,以及一系列其它很棒的选项。你可以通过 `man fbi` 来查阅完整的选项列表。 ### CMatrix 终端屏保 <ruby> 黑客帝国 <rt> The Matrix </rt></ruby>屏保仍然是我非常喜欢的屏保之一(如图 2),仅次于<ruby> 弹跳牛 <rt> bouncing cow </rt></ruby>。[CMatrix](http://www.asty.org/cmatrix/) 可以在终端运行。要运行它只需输入 `cmatrix`,然后可以用 `Ctrl+C` 来停止运行。执行 `cmatrix -s` 则会启动屏保模式,这样的话,按任意键都会直接退出。`-C` 参数可以设定颜色,譬如绿色(`green`)、红色(`red`)、蓝色(`blue`)、黄色(`yellow`)、白色(`white`)、紫色(`magenta`)、青色(`cyan`)或者黑色(`black`)。 ![图 2 黑客帝国屏保](/data/attachment/album/201802/07/123600qxxf0hfncc3tqife.jpg) CMatrix 还支持异步按键,这意味着你可以在它运行的时候改变设置选项。 `-B` 设置全部使用粗体,而 `-b`(LCTT 译注:原文误为 `-B`)则可以设置部分字体加粗。 ### fbgs PDF 阅读器 看起来,PDF 文档是普遍流行且无法避免的,而且 PDF 比它之前的功能好了很多,譬如超链接、复制粘贴以及更好的文本搜索功能等。`fbgs` 是 `fbida` 包中提供的一个 PDF 阅读器。它可以设置页面大小、分辨率、指定页码以及绝大部分 `fbi` 所提供的选项,当然除了一些在 `man fbgs` 中列举出来的不可用选项。我主要用到的选项是页面大小,你可以选择 `-l`、`xl` 或者 `xxl`: ``` $ fbgs -xl annoyingpdf.pdf ``` 欢迎通过 Linux 基金会与 edX 免费提供的[“Linux 入门”](https://training.linuxfoundation.org/linux-courses/system-administration-training/introduction-to-linux)课程学习更多 Linux 知识。 --- via: <https://www.linux.com/learn/intro-to-linux/2018/1/multimedia-apps-linux-console> 作者:[Carla Schroder](https://www.linux.com/users/cschroder) 译者:[Yinr](https://github.com/Yinr) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,321
8 个你不一定全都了解的 rm 命令示例
https://www.howtoforge.com/linux-rm-command/
2018-02-07T20:36:47
[ "rm", "删除" ]
https://linux.cn/article-9321-1.html
![](/data/attachment/album/201802/07/203619n9bb3pdwmmpqxwfw.jpg) 删除文件和复制/移动文件一样,都是很基础的操作。在 Linux 中,有一个专门的命令 `rm`,可用于完成所有删除相关的操作。在本文中,我们将用些容易理解的例子来讨论这个命令的基本使用。 但在我们开始前,值得指出的是本文所有示例都在 Ubuntu 16.04 LTS 中测试过。 ### Linux rm 命令概述 通俗的讲,我们可以认为 `rm` 命令是用于删除文件和目录的。下面是此命令的语法: ``` rm [选项]... [要删除的文件/目录]... ``` 下面是命令使用说明: > > GUN 版本 `rm` 命令的手册文档。`rm` 删除每个指定的文件,默认情况下不删除目录。 > > > 当删除的文件超过三个或者提供了选项 `-r`、`-R` 或 `--recursive`(LCTT 译注:表示递归删除目录中的文件)时,如果给出 `-I`(LCTT 译注:大写的 I)或 `--interactive=once` 选项(LCTT 译注:表示开启交互一次),则 `rm` 命令会提示用户是否继续整个删除操作,如果用户回应不是确认(LCTT 译注:即没有回复 `y`),则整个命令立刻终止。 > > > 另外,如果被删除文件是不可写的,标准输入是终端,这时如果没有提供 `-f` 或 `--force` 选项,或者提供了 `-i`(LCTT 译注:小写的 i) 或 `--interactive=always` 选项,`rm` 会提示用户是否要删除此文件,如果用户回应不是确认(LCTT 译注:即没有回复 `y`),则跳过此文件。 > > > 下面这些问答式例子会让你更好的理解这个命令的使用。 ### Q1. 如何用 rm 命令删除文件? 这是非常简单和直观的。你只需要把文件名(如果文件不是在当前目录中,则还需要添加文件路径)传入给 `rm` 命令即可。 (LCTT 译注:可以用空格隔开传入多个文件名称。) ``` rm 文件1 文件2 ... ``` 如: ``` rm testfile.txt ``` [![How to remove files using rm command](/data/attachment/album/201802/07/203650qdudn2d8efkb2jln.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-basic-usage.png) ### Q2. 如何用 `rm` 命令删除目录? 如果你试图删除一个目录,你需要提供 `-r` 选项。否则 `rm` 会抛出一个错误告诉你正试图删除一个目录。 (LCTT 译注:`-r` 表示递归地删除目录下的所有文件和目录。) ``` rm -r [目录名称] ``` 如: ``` rm -r testdir ``` [![How to remove directories using rm command](/data/attachment/album/201802/07/203653tq2kvwwe3kquvabw.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-r.png) ### Q3. 如何让删除操作前有确认提示? 如果你希望在每个删除操作完成前都有确认提示,可以使用 `-i` 选项。 ``` rm -i [文件/目录] ``` 比如,你想要删除一个目录“testdir”,但需要每个删除操作都有确认提示,你可以这么做: ``` rm -r -i testdir ``` [![How to make rm prompt before every removal](/data/attachment/album/201802/07/203654jb36a85jpd34535a.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-i-option.png) ### Q4. 如何让 rm 忽略不存在的文件或目录? 如果你删除一个不存在的文件或目录时,`rm` 命令会抛出一个错误,如: [![Linux rm command example](/data/attachment/album/201802/07/203656gjq41qjdx7b1gw44.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-non-ext-error.png) 然而,如果你愿意,你可以使用 `-f` 选项(LCTT 译注:即 “force”)让此次操作强制执行,忽略错误提示。 ``` rm -f [文件...] ``` [![How to force rm to ignore nonexistent files](/data/attachment/album/201802/07/203658clziljliiqu5sl5d.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-f-option.png) ### Q5. 如何让 rm 仅在某些场景下确认删除? 选项 `-I`,可保证在删除超过 3 个文件时或递归删除时(LCTT 译注: 如删除目录)仅提示一次确认。 比如,下面的截图展示了 `-I` 选项的作用——当两个文件被删除时没有提示,当超过 3 个文件时会有提示。 [![How to make rm prompt only in some scenarios](/data/attachment/album/201802/07/203701yk3ace3i8f3wki3w.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-I-option.png) ### Q6. 当删除根目录是 rm 是如何工作的? 当然,删除根目录(`/`)是 Linux 用户最不想要的操作。这也就是为什么默认 `rm` 命令不支持在根目录上执行递归删除操作。(LCTT 译注:早期的 `rm` 命令并无此预防行为。) [![How rm works when dealing with root directory](/data/attachment/album/201802/07/203703r88y4ws00yoddf8k.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-root-default.png) 然而,如果你非得完成这个操作,你需要使用 `--no-preserve-root` 选项。当提供此选项,`rm` 就不会特殊处理根目录(`/`)了。 假如你想知道在哪些场景下 Linux 用户会删除他们的根目录,点击[这里](https://superuser.com/questions/742334/is-there-a-scenario-where-rm-rf-no-preserve-root-is-needed)。 ### Q7. 如何让 rm 仅删除空目录? 假如你需要 `rm` 在删除目录时仅删除空目录,你可以使用 `-d` 选项。 ``` rm -d [目录] ``` 下面的截图展示 `-d` 选项的用途——仅空目录被删除了。 [![How to make rm only remove empty directories](/data/attachment/album/201802/07/203705afvq3ffmxjx5navb.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-d-option.png) ### Q8. 如何让 rm 显示当前删除操作的详情? 如果你想 rm 显示当前操作完成时的详细情况,使用 `-v` 选项可以做到。 ``` rm -v [文件/目录] ``` 如: [![How to force rm to emit details of operation it is performing](/data/attachment/album/201802/07/203707p3aspiahi11iivq3.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-v-option.png) ### 结论 考虑到 `rm` 命令提供的功能,可以说其是 Linux 中使用频率最高的命令之一了(就像 [cp](https://www.howtoforge.com/linux-cp-command/) 和 `mv` 一样)。在本文中,我们涉及到了其提供的几乎所有主要选项。`rm` 命令有些学习曲线,因此在你日常工作中开始使用此命令之前 你将需要花费些时间去练习它的选项。更多的信息,请点击此命令的 [man 手册页](https://linux.die.net/man/1/rm)。 --- via: <https://www.howtoforge.com/linux-rm-command/> 作者:[Himanshu Arora](https://www.howtoforge.com) 译者:[yizhuoyan](https://github.com/yizhuoyan) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Linux rm Command Explained for Beginners (8 Examples) ### On this page [Linux rm command](#linux-rm-command)[Q1. How to remove files using rm command?](#q-how-to-remove-files-using-rm-command)[Q2. How to remove directories using rm command?](#q-how-to-remove-directories-using-rm-command)[Q3. How to make rm prompt before every removal?](#q-how-to-make-rm-prompt-before-every-removal)[Q4. How to force rm to ignore nonexistent files?](#q-how-to-force-rm-to-ignore-nonexistent-files)[Q5. How to make rm prompt only in some scenarios?](#q-how-to-make-rm-prompt-only-in-some-scenarios)[Q6. How rm works when dealing with root directory?](#q-how-rm-works-when-dealing-with-root-directory)[Q7. How to make rm only remove empty directories?](#q-how-to-make-rm-only-remove-empty-directories)[Q8. How to force rm to emit details of operation it is performing?](#q-how-to-force-rm-to-emit-details-of-operation-it-is-performing)[Conclusion](#conclusion) Deleting files is a fundamental operation, just like copying files or renaming/moving them. In Linux, there's a dedicated command - dubbed **rm** - that lets you perform all deletion-related operations. In this tutorial, we will discuss the basics of this tool along with some easy to understand examples. But before we do that, it's worth mentioning that all examples mentioned in the article have been tested on Ubuntu 16.04 LTS. ## Linux rm command So in layman's terms, we can simply say the rm command is used for removing/deleting files and directories. Following is the syntax of the command: rm [OPTION]... [FILE]... And here's how the tool's man page describes it: This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. The following Q&A-styled examples will give you a better idea on how the tool works. ## Q1. How to remove files using rm command? That's pretty easy and straightforward. All you have to do is to pass the name of the files (along with paths if they are not in the current working directory) as input to the rm command. rm [filename] For example: rm testfile.txt ## Q2. How to remove directories using rm command? If you are trying to remove a directory, then you need to use the **-r** command line option. Otherwise, rm will throw an error saying what you are trying to delete is a directory. rm -r [dir name] For example: rm -r testdir ## Q3. How to make rm prompt before every removal? If you want rm to prompt before each delete action it performs, then use the **-i** command line option. rm -i [file or dir] For example, suppose you want to delete a directory 'testdir' and all its contents, but want rm to prompt before every deletion, then here's how you can do that: rm -r -i testdir ## Q4. How to force rm to ignore nonexistent files? The rm command lets you know through an error message if you try deleting a non-existent file or directory. However, if you want, you can make rm suppress such error/notifications - all you have to do is to use the **-f** command line option. rm -f [filename] ## Q5. How to make rm prompt only in some scenarios? There exists a command line option **-I**, which when used, makes sure the command only prompts once before removing more than three files, or when removing recursively. For example, the following screenshot shows this option in action - there was no prompt when two files were deleted, but the command prompted when more than three files were deleted. ## Q6. How rm works when dealing with root directory? Of course, deleting root directory is the last thing a Linux user would want. That's why, the rm command doesn't let you perform a recursive delete operation on this directory by default. However, if you want to go ahead with this operation for whatever reason, then you need to tell this to rm by using the * --no-preserve-root* option. When this option is enabled, rm doesn't treat the root directory (/) specially. *In case you want to know the scenarios in which a user might want to delete the root directory of their system, head here.* ## Q7. How to make rm only remove empty directories? In case you want to restrict rm's directory deletion ability to only empty directories, then you can use the -d command line option. rm -d [dir] The following screenshot shows the -d command line option in action - only empty directory got deleted. ## Q8. How to force rm to emit details of operation it is performing? If you want rm to display detailed information of the operation being performed, then this can be done by using the **-v** command line option. rm -v [file or directory name] For example: ## Conclusion Given the kind of functionality it offers, rm is one of the most frequently used commands in Linux (like [cp](https://www.howtoforge.com/linux-cp-command/) and mv). Here, in this tutorial, we have covered almost all major command line options this tool provides. rm has a bit of learning curve associated with, so you'll have to spent some time practicing its options before you start using the tool in your day to day work. For more information, head to the command's [man page](https://linux.die.net/man/1/rm).
9,322
MapSCII:在终端显示世界地图
https://www.ostechnix.com/mapscii-world-map-terminal/
2018-02-07T22:34:38
[ "地图", "终端" ]
https://linux.cn/article-9322-1.html
![](/data/attachment/album/201802/07/223442p37po74lby3uum6p.png) 我偶然发现了一个有趣的工具。在终端里的世界地图!是的,这太酷了。给 `MapSCII` 打 call,这是可在 xterm 兼容终端上渲染的布莱叶盲文和 ASCII 世界地图。它支持 GNU/Linux、Mac OS 和 Windows。我原以为它只不过是一个在 GitHub 上托管的项目而已,但是我错了!他们做的事令人印象深刻。我们可以使用我们的鼠标指针在世界地图的任何地方拖拽放大和缩小。其他显著的特性是: * 发现任何特定地点周围的兴趣点 * 高度可定制的图层样式,支持 [Mapbox 样式](https://www.mapbox.com/mapbox-gl-style-spec/) * 可连接到任何公共或私有的矢量贴片服务器 * 或者使用已经提供并已优化的基于 [OSM2VectorTiles](https://github.com/osm2vectortiles) 服务器 * 可以离线工作并发现本地的 [VectorTile](https://github.com/mapbox/vector-tile-spec)/[MBTiles](https://github.com/mapbox/mbtiles-spec) * 兼容大多数 Linux 和 OSX 终端 * 高度优化算法的流畅体验 ### 使用 MapSCII 在终端中显示世界地图 要打开地图,只需从终端运行以下命令: ``` telnet mapscii.me ``` 这是我终端上的世界地图。 ![](/data/attachment/album/201802/07/223443njaa5uij55335ic3.png) 很酷,是吗? 要切换到布莱叶盲文视图,请按 `c`。 ![](/data/attachment/album/201802/07/223445ps444sbp9zysqz33.png) 再次输入 `c` 切回以前的格式。 要滚动地图,请使用“向上”、“向下”、“向左”、“向右”箭头键。要放大/缩小位置,请使用 `a` 和 `z` 键。另外,你可以使用鼠标的滚轮进行放大或缩小。要退出地图,请按 `q`。 就像我已经说过的,不要认为这是一个简单的项目。点击地图上的任何位置,然后按 `a` 放大。 放大后,下面是一些示例截图。 ![](/data/attachment/album/201802/07/223446wvccjh5vib9zevka.png) 我可以放大查看我的国家(印度)的州。 ![](/data/attachment/album/201802/07/223448slxz9tb5akabzoag.png) 和州内的地区(Tamilnadu): ![](/data/attachment/album/201802/07/223450keltechl9hr9ch04.png) 甚至是地区内的镇 [Taluks](https://en.wikipedia.org/wiki/Tehsils_of_India): ![](/data/attachment/album/201802/07/223452hwdckwck1c2wwzkw.png) 还有,我完成学业的地方: ![](/data/attachment/album/201802/07/223454c6x3z5wxnks2mwun.png) 即使它只是一个最小的城镇,MapSCII 也能准确地显示出来。 MapSCII 使用 [OpenStreetMap](https://www.openstreetmap.org/) 来收集数据。 ### 在本地安装 MapSCII 喜欢它吗?很好!你可以安装在你自己的系统上。 确保你的系统上已经安装了 Node.js。如果还没有,请参阅以下链接。 * [在 Linux 上安装 NodeJS](https://www.ostechnix.com/install-node-js-linux/) 然后,运行以下命令来安装它。 ``` sudo npm install -g mapscii ``` 要启动 MapSCII,请运行: ``` mapscii ``` 玩的开心!会有更好的东西。敬请关注! 干杯! --- via: <https://www.ostechnix.com/mapscii-world-map-terminal/> 作者:[SK](https://www.ostechnix.com/author/sk/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,323
使用 Vi/Vim 编辑器:基础篇
http://linuxtechlab.com/working-vi-editor-basics/
2018-02-08T19:13:00
[ "Vim", "Vi" ]
https://linux.cn/article-9323-1.html
![](/data/attachment/album/201802/08/191332xx3uhxhek3kk0g3f.png) VI 编辑器是一个基于命令行的、功能强大的文本编辑器,最早为 Unix 系统开发,后来也被移植到许多的 Unix 和 Linux 发行版上。 在 Linux 上还存在着另一个 VI 编辑器的高阶版本 —— VIM(也被称作 VI IMproved)。VIM 只是在 VI 已经很强的功能上添加了更多的功能,这些功能有: * 支持更多 Linux 发行版, * 支持多种编程语言,包括 python、c++、perl 等语言的代码块折叠,语法高亮, * 支持通过多种网络协议,包括 http、ssh 等编辑文件, * 支持编辑压缩归档中的文件, * 支持分屏同时编辑多个文件。 接下来我们会讨论 VI/VIM 的命令以及选项。本文出于教学的目的,我们使用 VI 来举例,但所有的命令都可以被用于 VIM。首先我们先介绍 VI 编辑器的两种模式。 ### 命令模式 命令模式下,我们可以执行保存文件、在 VI 内运行命令、复制/剪切/粘贴操作,以及查找/替换等任务。当我们处于插入模式时,我们可以按下 `Escape`(`Esc`)键返回命令模式 ### 插入模式 在插入模式下,我们可以键入文件内容。在命令模式下按下 `i` 进入插入模式。 ### 创建文件 我们可以通过下述命令建立一个文件(LCTT 译注:如果该文件存在,则编辑已有文件): ``` $ vi filename ``` 一旦该文件被创建或者打开,我们首先进入命令模式,我们需要进入输入模式以在文件中输入内容。我们通过前文已经大致上了解这两种模式。 ### 退出 Vi 如果是想从插入模式中退出,我们首先需要按下 `Esc` 键进入命令模式。接下来我们可以根据不同的需要分别使用两种命令退出 Vi。 1. 不保存退出 - 在命令模式中输入 `:q!` 2. 保存并退出 - 在命令模式中输入 `:wq` ### 移动光标 下面我们来讨论下那些在命令模式中移动光标的命令和选项: 1. `k` 将光标上移一行 2. `j` 将光标下移一行 3. `h` 将光标左移一个字母 4. `l` 将光标右移一个字母 注意:如果你想通过一个命令上移或下移多行,或者左移、右移多个字母,你可以使用 `4k` 或者 `5l`,这两条命令会分别上移 4 行或者右移 5 个字母。 5. `0` 将光标移动到该行行首 6. `$` 将光标移动到该行行尾 7. `nG` 将光标移动到第 n 行 8. `G` 将光标移动到文件的最后一行 9. `{` 将光标移动到上一段 10. `}` 将光标移动到下一段 除此之外还有一些命令可以用于控制光标的移动,但上述列出的这些命令应该就能应付日常工作所需。 ### 编辑文本 这部分会列出一些用于命令模式的命令,可以进入插入模式来编辑当前文件 1. `i` 在当前光标位置之前插入内容 2. `I` 在光标所在行的行首插入内容 3. `a` 在当前光标位置之后插入内容 4. `A` 在光标所在行的行尾插入内容 5. `o` 在当前光标所在行之后添加一行 6. `O` 在当前光标所在行之前添加一行 ### 删除文本 以下的这些命令都只能在命令模式下使用,所以首先需要按下 `Esc` 进入命令模式,如果你正处于插入模式: 1. `dd` 删除光标所在的整行内容,可以在 `dd` 前增加数字,比如 `2dd` 可以删除从光标所在行开始的两行 2. `d$` 删除从光标所在位置直到行尾 3. `d^` 删除从光标所在位置直到行首 4. `dw` 删除从光标所在位置直到下一个词开始的所有内容 ### 复制与黏贴 1. `yy` 复制当前行,在 `yy` 前添加数字可以复制多行 2. `p` 在光标之后粘贴复制行 3. `P` 在光标之前粘贴复制行 上述就是可以在 VI/VIM 编辑器上使用的一些基本命令。在未来的教程中还会继续教授一些更高级的命令。如果有任何疑问和建议,请在下方评论区留言。 --- via: <http://linuxtechlab.com/working-vi-editor-basics/> 作者:[Shusain](http://linuxtechlab.com/author/shsuain/) 译者:[ljgibbslf](https://github.com/ljgibbslf) 校对:[wxy](https://github.com/wxy) 本文由 LCTT 原创编译,Linux中国 荣誉推出
301
Moved Permanently
null
9,324
定制嵌入式 Linux 发行版
http://www.linuxjournal.com/content/custom-embedded-linux-distributions
2018-02-08T23:02:44
[ "嵌入式", "发行版" ]
https://linux.cn/article-9324-1.html
![](/data/attachment/album/201802/08/230216ozk2ks8swoy77gkk.jpg) 便宜的物联网板的普及意味着它不仅会控制应用程序,还会控制整个软件平台。 那么,如何构建一个针对特定用途的交叉编译应用程序的自定义发行版呢? 正如 Michael J. Hammel 在这里解释的那样,它并不像你想象的那么难。 ### 为什么要定制? 以前,许多嵌入式项目都使用现成的发行版,然后出于种种原因,再将它们剥离到只剩下基本的必需的东西。首先,移除不需要的包以减少占用的存储空间。在启动时,嵌入式系统一般不需要大量的存储空间以及可用存储空间。在嵌入式系统运行时,可能从非易失性内存中拷贝大量的操作系统文件到内存中。第二,移除用不到的包可以降低可能的攻击面。如果你不需要它们就没有必要把这些可能有漏洞的包挂在上面。最后,移除用不到包可以降低发行版管理的开销。如果在包之间有依赖关系,意味着任何一个包请求从上游更新,那么它们都必须保持同步。那样可能就会出现验证噩梦。 然而,从一个现有的发行版中去移除包并不像说的那样容易。移除一个包可能会打破与其它包保持的各种依赖关系,以及可能在上游的发行版管理中改变依赖。另外,由于一些包原生集成在引导或者运行时进程中,它们并不能轻易地简单地移除。所有这些都是项目之外的平台的管理,并且有可能会导致意外的开发延迟。 一个流行的选择是使用上游发行版供应商提供的构建工具去构建一个定制的发行版。无论是 Gentoo 还是 Debian 都提供这种自下而上的构建方式。这些构建工具中最为流行的可能是 Debian 的 debootstrap 实用程序。它取出预构建的核心组件并允许用户去精选出它们感兴趣的包来构建用户自己的平台。但是,debootstrap 最初仅在 x86 平台上可用,虽然,现在有了 ARM(也有可能会有其它的平台)选项。debootstrap 和 Gentoo 的 catalyst 仍然需要从本地项目中将依赖管理移除。 一些人认为让别人去管理平台软件(像 Android 一样)要比自己亲自管理容易的多。但是,那些发行版都是多用途的,当你在一个轻量级的、资源有限的物联网设备上使用它时,你可能会再三考虑从你手中被拿走的任何资源。 ### 系统引导的基石 一个定制的 Linux 发行版要求许多软件组件。其中第一个就是<ruby> 工具链 <rt> toolchain </rt></ruby>。工具链是用于编译软件的一套工具集。包括(但不限于)一个编译器、链接器、二进制操作工具以及标准的 C 库。工具链是为一个特定的目标硬件设备专门构建的。如果一个构建在 x86 系统上的工具链想要用于树莓派,那么这个工具链就被称为交叉编译工具链。当在内存和存储都十分有限的小型嵌入式设备上工作时,最好是使用一个交叉编译工具链。需要注意的是,即便是使用像 JavaScript 这样的需要运行在特定平台的脚本语言为特定用途编写的应用程序,也需要使用交叉编译工具链编译。 ![](/data/attachment/album/201802/08/230248s36qs6s336266s6s.png) *图 1. 编译依赖和引导顺序* 交叉编译工具链用于为目标硬件构建软件组件。需要的第一个组件是<ruby> 引导加载程序 <rt> bootloader </rt></ruby>。当计算机主板加电之后,处理器(可能有差异,取决于设计)尝试去跳转到一个特定的内存位置去开始运行软件。那个内存位置就是保存引导加载程序的地方。硬件可能有内置的引导加载程序,它可能直接从它的存储位置或者可能在它运行前首先拷贝到内存中。也可能会有多个引导加载程序。例如,第一阶段的引导加载程序可能位于硬件的 NAND 或者 NOR 闪存中。它唯一的功能是设置硬件以便于执行第二阶段的引导加载程序——比如,存储在 SD 卡中的可以被加载并运行的引导加载程序。 引导加载程序能够从硬件中取得足够的信息,将 Linux 加载到内存中并跳转到正确的位置,将控制权有效地移交到 Linux。Linux 是一个操作系统。这意味着,在这种设计中,它除了监控硬件和向上层软件(也就是应用程序)提供服务外,它实际上什么都不做。[Linux 内核](https://www.kernel.org) 中通常是各种各样的固件块。那些预编译的软件对象,通常包含硬件平台使用的设备的专用 IP(知识资产)。当构建一个定制发行版时,在开始编译内核之前,它可能会要求获得一些 Linux 内核源代码树没有提供的必需的固件块。 应用程序保存在根文件系统中,这个根文件系统是通过编译构建的,它集合了各种软件库、工具、脚本以及配置文件。总的来说,它们都提供各种服务,比如,网络配置和 USB 设备挂载,这些都是将要运行的项目应用程序所需要的。 总的来说,一个完整的系统构建要求下列的组件: 1. 一个交叉编译工具链 2. 一个或多个引导加载程序 3. Linux 内核和相关的固件块 4. 一个包含库、工具以及实用程序的根文件系统 5. 定制的应用程序 ### 使用适当的工具开始构建 交叉编译工具链的组件可以手工构建,但这是一个很复杂的过程。幸运的是,现有的工具可以很容易地完成这一过程。构建交叉编译工具链的最好工具可能是 [Crosstool-NG](http://crosstool-ng.github.io),这个工具使用了与 Linux 内核相同的 kconfig 菜单系统来构建工具链的每个细节和方面。使用这个工具的关键是,为目标平台找到正确的配置项。配置项通常包含下列内容: 1. 目标架构,比如,是 ARM 还是 x86。 2. 字节顺序:小端字节顺序(一般情况下,Intel 采用这种顺序)还是大端字节顺序(一般情况下,ARM 或者其它的平台采用这种顺序)。 3. 编译器已知的 CPU 类型,比如,GCC 可以使用 `-mcpu` 或 `--with-cpu`。 4. 支持的浮点类型,如果有的话,比如,GCC 可以使用 `-mfpu` 或 `--with-fpu`。 5. <ruby> 二进制实用工具 <rt> binutils </rt></ruby>、C 库以及 C 编译器的特定版本信息。 ![](/data/attachment/album/201802/08/230253irtdk4h4j40m8rej.png) *图 2. Crosstool-NG 配置菜单* 前四个一般情况下可以从处理器制造商的文档中获得。对于较新的处理器,它们可能不容易找到,但是,像树莓派或者 BeagleBoards(以及它们的后代和分支),你可以在像 [嵌入式 Linux Wiki](https://elinux.org/Main_Page) 这样的地方找到相关信息。 二进制实用工具、C 库、以及 C 编译器的版本,将与任何第三方提供的其它工具链分开。首先,它们中的每一个都有多个提供者。Linaro 为最新的处理器类型提供了最先进的版本,同时致力于将该支持合并到像 GNU C 库这样的上游项目中。尽管你可以使用各种提供者的工具,你可能依然想去使用现成的 GNU 工具链或者相同的 Linaro 版本。 在 Crosstool-NG 中的另外的重要选择是 Linux 内核的版本。这个选择将得到用于各种工具链组件的<ruby> 头文件 <rt> headers </rt></ruby>,但是它没有必要一定与你在目标硬件上将要引导的 Linux 内核相同。选择一个不比目标硬件的内核更新的 Linux 内核是很重要的。如果可能的话,尽量选择一个比目标硬件使用的内核更老的长周期支持(LTS)的内核。 对于大多数不熟悉构建定制发行版的开发者来说,工具链的构建是最为复杂的过程。幸运的是,大多数硬件平台的二进制工具链都可以想办法得到。如果构建一个定制的工具链有问题,可以在线搜索像 [嵌入式 Linux Wiki](https://elinux.org/Main_Page) 这样的地方去查找预构建工具链。 ### 引导选项 在构建完工具链之后,接下来的工作是引导加载程序。引导加载程序用于设置硬件,以便于越来越复杂的软件能够使用这些硬件。第一阶段的引导加载程序通常由目标平台制造商提供,它通常被烧录到类似于 EEPROM 或者 NOR 闪存这类的在硬件上的存储中。第一阶段的引导加载程序将使设备从这里(比如,一个 SD 存储卡)开始引导。树莓派的引导加载程序就是这样的,它样做也就没有必要再去创建一个定制引导加载程序。 尽管如此,许多项目还是增加了第二阶段的引导加载程序,以便于去执行一个多样化的任务。在无需使用 Linux 内核或者像 plymouth 这样的用户空间工具的情况下提供一个启动动画,就是其中一个这样的任务。一个更常见的第二阶段引导加载程序的任务是去提供基于网络的引导或者使连接到 PCI 上的磁盘可用。在那种情况下,一个第三阶段的引导加载程序,比如 GRUB,可能才是让系统运行起来所必需的。 最重要的是,引导加载程序加载 Linux 内核并使它开始运行。如果第一阶段引导加载程序没有提供一个在启动时传递内核参数的机制,那么,在第二阶段的引导加载程序中就必须要提供。 有许多的开源引导加载程序可以使用。[U-Boot 项目](https://www.denx.de/wiki/U-Boot) 通常用于像树莓派这样的 ARM 平台。CoreBoot 一般是用于像 Chromebook 这样的 x86 平台。引导加载程序是特定于目标硬件专用的。引导加载程序的选择总体上取决于项目的需求以及目标硬件(可以去网络上在线搜索开源引导加载程序的列表)。 ### 现在到了 Linux 登场的时候 引导加载程序将加载 Linux 内核到内存中,然后去运行它。Linux 就像一个扩展的引导加载程序:它进行进行硬件设置以及准备加载高级软件。内核的核心将设置和提供在应用程序和硬件之间共享使用的内存;提供任务管理器以允许多个应用程序同时运行;初始化没有被引导加载程序配置的或者是已经配置了但是没有完成的硬件组件;以及开启人机交互界面。内核也许不会配置为在自身完成这些工作,但是,它可以包含一个嵌入的、轻量级的文件系统,这类文件系统大家熟知的有 initramfs 或者 initrd,它们可以独立于内核而创建,用于去辅助设置硬件。 内核操作的另外的事情是去下载二进制块(通常称为固件)到硬件设备。固件是用特定格式预编译的对象文件,用于在引导加载程序或者内核不能访问的地方去初始化特定硬件。许多这种固件对象可以从 Linux 内核源仓库中获取,但是,还有很多其它的固件只能从特定的硬件供应商处获得。例如,经常由它们自己提供固件的设备有数字电视调谐器或者 WiFi 网卡等。 固件可以从 initramfs 中加载,也或者是在内核从根文件系统中启动 init 进程之后加载。但是,当你去创建一个定制的 Linux 发行版时,创建内核的过程常常就是获取各种固件的过程。 ### 轻量级核心平台 Linux 内核做的最后一件事情是尝试去运行一个被称为 init 进程的专用程序。这个专用程序的名字可能是 init 或者 linuxrc 或者是由加载程序传递给内核的名字。init 进程保存在一个能够被内核访问的文件系统中。在 initramfs 这种情况下,这个文件系统保存在内存中(它可能是被内核自己放置到那里,也可能是被引导加载程序放置在那里)。但是,对于运行更复杂的应用程序,initramfs 通常并不够完整。因此需要另外一个文件系统,这就是众所周知的根文件系统。 ![](/data/attachment/album/201802/08/230256cbbmpamzrjkak7zk.png) *图 3. 构建 root 配置菜单* initramfs 文件系统可以使用 Linux 内核自身构建,但是更常用的作法是,使用一个被称为 [BusyBox](https://busybox.net) 的项目去创建。BusyBox 组合许多 GNU 实用程序(比如,grep 或者 awk)到一个单个的二进制文件中,以便于减小文件系统自身的大小。BusyBox 通常用于去启动根文件系统的创建过程。 但是,BusyBox 是特意轻量化设计的。它并不打算提供目标平台所需要的所有工具,甚至提供的工具也是经过功能简化的。BusyBox 有一个“姊妹”项目叫做 [Buildroot](https://buildroot.org),它可以用于去得到一个完整的根文件系统,提供了各种库、实用程序,以及脚本语言。像 Crosstool-NG 和 Linux 内核一样,BusyBox 和 Buildroot 也都允许使用 kconfig 菜单系统去定制配置。更重要的是,Buildroot 系统自动处理依赖关系,因此,选定的实用程序将会保证该程序所需要的软件也会被构建并安装到 root 文件系统。 Buildroot 可以用多种格式去生成一个根文件系统包。但是,需要重点注意的是,这个文件系统是被归档的。单个的实用程序和库并不是以 Debian 或者 RPM 格式打包进去的。使用 Buildroot 将生成一个根文件系统镜像,但是它的内容不是单独的包。即使如此,Buildroot 还是提供了对 opkg 和 rpm 包管理器的支持的。这意味着,虽然根文件系统自身并不支持包管理,但是,安装在根文件系统上的定制应用程序能够进行包管理。 ### 交叉编译和脚本化 Buildroot 的其中一个特性是能够生成一个临时树。这个目录包含库和实用程序,它可以被用于去交叉编译其它应用程序。使用临时树和交叉编译工具链,使得在主机系统上而不是目标平台上对 Buildroot 之外的其它应用程序编译成为可能。使用 rpm 或者 opkg 包管理软件之后,这些应用程序可以在运行时使用包管理软件安装在目标平台的根文件系统上。 大多数定制系统的构建都是围绕着用脚本语言构建应用程序的想法去构建的。如果需要在目标平台上运行脚本,在 Buildroot 上有多种可用的选择,包括 Python、PHP、Lua 以及基于 Node.js 的 JavaScript。对于需要使用 OpenSSL 加密的应用程序也提供支持。 ### 接下来做什么 Linux 内核和引导加载程序的编译过程与大多数应用程序是一样的。它们的构建系统被设计为去构建一个专用的软件位。Crosstool-NG 和 Buildroot 是<ruby> 元构建 <rt> metabuild </rt></ruby>。元构建是将一系列有自己构建系统的软件集合封装为一个构建系统。可靠的元构建包括 [Yocto](https://www.yoctoproject.org) 和 [OpenEmbedded](https://www.openembedded.org/wiki/Main_Page)。Buildroot 的好处是可以将更高级别的元构建进行轻松的封装,以便于将定制 Linux 发行版的构建过程自动化。这样做之后,将会打开 Buildroot 指向到项目专用的缓存仓库的选项。使用缓存仓库可以加速开发过程,并且可以在无需担心上游仓库变化的情况下提供构建快照。 一个实现高级构建系统的示例是 [PiBox](https://www.piboxproject.com)。PiBox 就是封装了在本文中讨论的各种工具的一个元构建。它的目的是围绕所有工具去增加一个通用的 GNU Make 目标架构,以生成一个核心平台,这个平台可以构建或分发其它软件。PiBox 媒体中心和 kiosk 项目是安装在核心平台之上的应用层软件的实现,目的是用于去产生一个构建平台。[Iron Man 项目](http://redmine.graphics-muse.org/projects/ironman/wiki/Getting_Started) 是为了家庭自动化的目的而扩展了这种应用程序,它集成了语音管理和物联网设备的管理。 但是,PiBox 如果没有这些核心的软件工具,它什么也做不了。并且,如果不去深入了解一个完整的定制发行版的构建过程,那么你将无法正确运行 PiBox。而且,如果没有 PiBox 开发团队对这个项目的长期奉献,也就没有 PiBox 项目,它完成了定制发行版构建中的大量任务。 --- via: <http://www.linuxjournal.com/content/custom-embedded-linux-distributions> 作者:[Michael J.Hammel](http://www.linuxjournal.com/user/1000879) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,325
优化 MySQL: 3 个简单的小调整
https://medium.com/@richb_/tuning-mysql-3-simple-tweaks-6356768f9b90
2018-02-09T12:38:11
[ "MySQL", "优化" ]
https://linux.cn/article-9325-1.html
如果你不改变 MySQL 的缺省配置,你的服务器的性能就像题图的坏在一档的法拉利一样 “虎落平阳被犬欺” … ![](/data/attachment/album/201802/09/123814odzby7s38od8u48h.png) 我并不期望成为一个专家级的 DBA,但是,在我优化 MySQL 时,我推崇 80/20 原则,明确说就是通过简单的调整一些配置,你可以压榨出高达 80% 的性能提升。尤其是在服务器资源越来越便宜的当下。 ### 警告 1. 没有两个数据库或者应用程序是完全相同的。这里假设我们要调整的数据库是为一个“典型”的 Web 网站服务的,优先考虑的是快速查询、良好的用户体验以及处理大量的流量。 2. 在你对服务器进行优化之前,请做好数据库备份! ### 1、 使用 InnoDB 存储引擎 如果你还在使用 MyISAM 存储引擎,那么是时候转换到 InnoDB 了。有很多的理由都表明 InnoDB 比 MyISAM 更有优势,如果你关注性能,那么,我们来看一下它们是如何利用物理内存的: * MyISAM:仅在内存中保存索引。 * InnoDB:在内存中保存索引**和**数据。 结论:保存在内存的内容访问速度要比磁盘上的更快。 下面是如何在你的表上去转换存储引擎的命令: ``` ALTER TABLE table_name ENGINE=InnoDB; ``` *注意:你已经创建了所有合适的索引,对吗?为了更好的性能,创建索引永远是第一优先考虑的事情。* ### 2、 让 InnoDB 使用所有的内存 你可以在 `my.cnf` 文件中编辑你的 MySQL 配置。使用 `innodb_buffer_pool_size` 参数去配置在你的服务器上允许 InnoDB 使用物理内存数量。 对此(假设你的服务器*仅仅*运行 MySQL),公认的“经验法则”是设置为你的服务器物理内存的 80%。在保证操作系统不使用交换分区而正常运行所需要的足够内存之后 ,尽可能多地为 MySQL 分配物理内存。 因此,如果你的服务器物理内存是 32 GB,可以将那个参数设置为多达 25 GB。 ``` innodb_buffer_pool_size = 25600M ``` \*注意:(1)如果你的服务器内存较小并且小于 1 GB。为了适用本文的方法,你应该去升级你的服务器。 (2) 如果你的服务器内存特别大,比如,它有 200 GB,那么,根据一般常识,你也没有必要为操作系统保留多达 40 GB 的内存。 \* ### 3、 让 InnoDB 多任务运行 如果服务器上的参数 `innodb_buffer_pool_size` 的配置是大于 1 GB,将根据参数 `innodb_buffer_pool_instances` 的设置, 将 InnoDB 的缓冲池划分为多个。 拥有多于一个的缓冲池的好处有: > > 在多线程同时访问缓冲池时可能会遇到瓶颈。你可以通过启用多缓冲池来最小化这种争用情况: > > > 对于缓冲池数量的官方建议是: > > 为了实现最佳的效果,要综合考虑 `innodb_buffer_pool_instances` 和 `innodb_buffer_pool_size` 的设置,以确保每个实例至少有不小于 1 GB 的缓冲池。 > > > 因此,在我们的示例中,将参数 `innodb_buffer_pool_size` 设置为 25 GB 的拥有 32 GB 物理内存的服务器上。一个合适的设置为 25600M / 24 = 1.06 GB ``` innodb_buffer_pool_instances = 24 ``` ### 注意! 在修改了 `my.cnf` 文件后需要重启 MySQL 才能生效: ``` sudo service mysql restart ``` 还有更多更科学的方法来优化这些参数,但是这几点可以作为一个通用准则来应用,将使你的 MySQL 服务器性能更好。 --- 作者简介: 我喜欢商业技术以及跑车 | 集团 CTO @ Parcel Monkey, Cloud Fulfilment & Kong。 --- via: <https://medium.com/@richb_/tuning-mysql-3-simple-tweaks-6356768f9b90> 作者:[Rich Barrett](https://medium.com/@richb_) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Tuning MySQL: 3 Simple Tweaks **If you don’t change the default MySQL configuration, your server is going to perform like a Ferrari that’s stuck in first gear…** I don’t claim to be an expert DBA, but I am a strong proponent of the 80/20 principle and when it comes to tuning MySQL, it’s fair to say you can squeeze 80% of the juice by making a few simple adjustments to your configuration. Useful, especially when server resources are getting cheaper all the time. ## Health warnings: - No two databases or applications are the same. This is written with the ‘typical’ website owner in mind, where fast queries, a nice user experience and being able to handle lots of traffic are your priorities. - Back up your database before you do this! # 1. Use the InnoDB storage engine If you’re using the MyISAM storage engine, then it’s time to move to InnoDB. There are many reasons why it’s superior, but if performance is what you’re after, it comes down to how each utilises physical memory: **MyISAM:**Only stores indexes in memory.**InnoDB:**Stores indexes*and*data in memory. **Bottom line:** stuff stored in memory is accessible much faster than stuff stored on the disk. Here’s how you convert your tables: `ALTER TABLE `*table_name* ENGINE=InnoDB; *Note:** You have created all of the appropriate indexes, right? That should always be your first priority for better performance.* # 2. Let InnoDB use all that memory You can edit your MySQL configuration in your *my.cnf* file. The amount of memory that InnoDB is allowed to use on your server is configured with the **innodb_buffer_pool_size** parameter. The accepted ‘rule of thumb’ for this (for servers *only* tasked with running MySQL) is to set this to 80% of your server’s physical memory. You want to maximise the use of the RAM, but leave enough for the OS to run without it needing to utilise the swap. So, if your server has 32GB memory, set it to ~ 25GB. `innodb_buffer_pool_size = 25600M` *Notes:** (1) If your server is small and this number comes in less than 1GB, you ought to upgrade to a box with more memory for the rest of this article to be applicable. (2) If you have a huge server, eg. 200gb memory, then use common sense — you don’t need to leave 40gb free memory for the OS.* # 3. Let InnoDB multitask For servers where *innodb_buffer_pool_size* is greater than 1GB, *innodb_buffer_pool_instances *divides the InnoDB buffer pool into this many instances. The benefit to having more than 1 buffer pool is: You might encounter bottlenecks from multiple threads trying to access the buffer pool at once. You can enable multiple buffer pools to minimize this contention. The official recommendation for the number of buffers is: For best efficiency, specify a combination of innodb_buffer_pool_instances and innodb_buffer_pool_size so that each buffer pool instance is at least 1 gigabyte. So in our example of a 32GB server with a 25GB *innodb_buffer_pool_size,* a suitable solution might be 25600M / **24** = 1.06GB `innodb_buffer_pool_instances = 24` # Don’t forget! After making changes to *my.cnf *you’ll need to restart MySQL: `sudo service mysql restart` **There are far more scientific ways to optimise these parameters, but using this as a general guide will get you a long way towards a better performing MySQL server.**
9,326
Gerg:Meltdown 和 Spectre 影响下的 Linux 内核状况
http://kroah.com/log/blog/2018/01/06/meltdown-status/
2018-02-09T21:18:37
[ "KPTI", "Meltdown", "Spectre" ]
https://linux.cn/article-9326-1.html
![](/data/attachment/album/201802/09/211831lzys5xy9p0nxylxx.png) 现在(LCTT 译注:本文发表于 1 月初),每个人都知道一件关乎电脑安全的“大事”发生了,真见鬼,等[每日邮报报道](http://www.dailymail.co.uk/sciencetech/article-5238789/Intel-says-security-updates-fix-Meltdown-Spectre.html)的时候,你就知道什么是糟糕了... 不管怎样,除了告诉你这篇写的及其出色的[披露该问题的 Zero 项目的论文](https://googleprojectzero.blogspot.fr/2018/01/reading-privileged-memory-with-side.html)之外,我不打算去跟进这个问题已经被报道出来的细节。他们应该现在就直接颁布 2018 年的 [Pwnie](https://pwnies.com/) 奖,干的太棒了。 如果你想了解我们如何在内核中解决这些问题的技术细节,你可以保持关注了不起的 [lwn.net](https://lwn.net/Articles/743265/),他们会把这些细节写成文章。 此外,这有一条很好的关于[这些公告](https://lwn.net/Articles/742999/)的摘要,包括了各个厂商的公告。 至于这些涉及的公司是如何处理这些问题的,这可以说是如何**不**与 Linux 内核社区保持沟通的教科书般的例子。这件事涉及到的人和公司都知道发生了什么,我确定这件事最终会出现,但是目前我需要去关注的是如何修复这些涉及到的问题,然后不去点名指责,不管我有多么的想去这么做。 ### 你现在能做什么 如果你的 Linux 系统正在运行一个正常的 Linux 发行版,那么升级你的内核。它们都应该已经更新了,然后在接下来的几个星期里保持更新。我们会统计大量在极端情况下出现的 bug ,这里涉及的测试很复杂,包括庞大的受影响的各种各样的系统和工作任务。如果你的 Linux 发行版没有升级内核,我强烈的建议你马上更换一个 Linux 发行版。 然而有很多的系统因为各种各样的原因(听说它们比起“传统”的企业发行版更多)不是在运行“正常的” Linux 发行版上。它们依靠长期支持版本(LTS)的内核升级,或者是正常的稳定内核升级,或者是内部的某人打造版本的内核。对于这部分人,这篇介绍了你能使用的上游内核中发生的混乱是怎么回事。 ### Meltdown – x86 现在,Linus 的内核树包含了我们当前所知的为 x86 架构解决 meltdown 漏洞的所有修复。开启 `CONFIG_PAGE_TABLE_ISOLATION` 这个内核构建选项,然后进行重构和重启,所有的设备应该就安全了。 然而,Linus 的内核树当前处于 4.15-rc6 这个版本加上一些未完成的补丁。4.15-rc7 版本要明天才会推出,里面的一些补丁会解决一些问题。但是大部分的人不会在一个“正常”的环境里运行 -rc 内核。 因为这个原因,x86 内核开发者在<ruby> 页表隔离 <rt> page table isolation </rt></ruby>代码的开发过程中做了一个非常好的工作,好到要反向移植到最新推出的稳定内核 4.14 的话,我们只需要做一些微不足道的工作。这意味着最新的 4.14 版本(本文发表时是 4.14.12 版本),就是你应该运行的版本。4.14.13 会在接下来的几天里推出,这个更新里有一些额外的修复补丁,这些补丁是一些运行 4.14.12 内核且有启动时间问题的系统所需要的(这是一个显而易见的问题,如果它不启动,就把这些补丁加入更新排队中)。 我个人要感谢 Andy Lutomirski、Thomas Gleixner、Ingo Molnar、 Borislav Petkov、 Dave Hansen、 Peter Zijlstra、 Josh Poimboeuf、 Juergen Gross 和 Linus Torvalds。他们开发出了这些修复补丁,并且为了让我能轻松地使稳定版本能够正常工作,还把这些补丁以一种形式融合到了上游分支里。没有这些工作,我甚至不敢想会发生什么。 对于老的长期支持内核(LTS),我主要依靠 Hugh Dickins、 Dave Hansen、 Jiri Kosina 和 Borislav Petkov 优秀的工作,来为 4.4 到 4.9 的稳定内核代码树分支带去相同的功能。我同样在追踪讨厌的 bug 和缺失的补丁方面从 Guenter Roeck、 Kees Cook、 Jamie Iles 以及其他很多人那里得到了极大的帮助。我要感谢 David Woodhouse、 Eduardo Valentin、 Laura Abbott 和 Rik van Riel 在反向移植和集成方面的帮助,他们的帮助在许多棘手的地方是必不可少的。 这些长期支持版本的内核同样有 `CONFIG_PAGE_TABLE_ISOLATION` 这个内核构建选项,你应该开启它来获得全方面的保护。 从主线版本 4.14 和 4.15 的反向移植是非常不一样的,它们会出现不同的 bug,我们现在知道了一些在工作中遇见的 VDSO 问题。一些特殊的虚拟机安装的时候会报一些奇怪的错,但这是只是现在出现的少数情况,这种情况不应该阻止你进行升级。如果你在这些版本中遇到了问题,请让我们在稳定内核邮件列表中知道这件事。 如果你依赖于 4.4 和 4.9 或是现在的 4.14 以外的内核代码树分支,并且没有发行版支持你的话,你就太不幸了。比起你当前版本内核包含的上百个已知的漏洞和 bug,缺少补丁去解决 meltdown 问题算是一个小问题了。你现在最需要考虑的就是马上把你的系统升级到最新。 与此同时,臭骂那些强迫你运行一个已被废弃且不安全的内核版本的人,他们是那些需要知道这是完全不顾后果的行为的人中的一份子。 ### Meltdown – ARM64 现在 ARM64 为解决 Meltdown 问题而开发的补丁还没有并入 Linus 的代码树,一旦 4.15 在接下来的几周里成功发布,他们就准备[阶段式地并入](https://git.kernel.org/pub/scm/linux/kernel/git/arm64/linux.git/log/?h=kpti) 4.16-rc1,因为这些补丁还没有在一个 Linus 发布的内核中,我不能把它们反向移植进一个稳定的内核版本里(额……我们有这个[规矩](https://www.kernel.org/doc/html/latest/process/stable-kernel-rules.html)是有原因的) 由于它们还没有在一个已发布的内核版本中,如果你的系统是用的 ARM64 的芯片(例如 Android ),我建议你选择 [Android 公共内核代码树](https://android.googlesource.com/kernel/common/),现在,所有的 ARM64 补丁都并入 [3.18](https://android.googlesource.com/kernel/common/+/android-3.18)、[4.4](https://android.googlesource.com/kernel/common/+/android-4.4) 和 [4.9](https://android.googlesource.com/kernel/common/+/android-4.9) 分支 中。 我强烈建议你关注这些分支,看随着时间的过去,由于测试了已并入补丁的已发布的上游内核版本,会不会有更多的修复补丁被补充进来,特别是我不知道这些补丁会在什么时候加进稳定的长期支持内核版本里。 对于 4.4 到 4.9 的长期支持内核版本,这些补丁有很大概率永远不会并入它们,因为需要大量的先决补丁。而所有的这些先决补丁长期以来都一直在 Android 公共内核版本中测试和合并,所以我认为现在对于 ARM 系统来说,仅仅依赖这些内核分支而不是长期支持版本是一个更好的主意。 同样需要注意的是,我合并所有的长期支持内核版本的更新到这些分支后通常会在一天之内或者这个时间点左右进行发布,所以你无论如何都要关注这些分支,来确保你的 ARM 系统是最新且安全的。 ### Spectre 现在,事情变得“有趣”了…… 再一次,如果你正在运行一个发行版的内核,一些内核融入了各种各样的声称能缓解目前大部分问题的补丁,你的内核*可能*就被包含在其中。如果你担心这一类的攻击的话,我建议你更新并测试看看。 对于上游来说,很好,现状就是仍然没有任何的上游代码树分支合并了这些类型的问题相关的修复补丁。有很多的邮件列表在讨论如何去解决这些问题的解决方案,大量的补丁在这些邮件列表中广为流传,但是它们尚处于开发前期,一些补丁系列甚至没有被构建或者应用到任何已知的代码树,这些补丁系列彼此之间相互冲突,这是常见的混乱。 这是由于 Spectre 问题是最近被内核开发者解决的。我们所有人都在 Meltdown 问题上工作,我们没有精确的 Spectre 问题全部的真实信息,而四处散乱的补丁甚至比公开发布的补丁还要糟糕。 因为所有的这些原因,我们打算在内核社区里花上几个星期去解决这些问题并把它们合并到上游去。修复补丁会进入到所有内核的各种各样的子系统中,而且在它们被合并后,会集成并在稳定内核的更新中发布,所以再次提醒,无论你使用的是发行版的内核还是长期支持的稳定内核版本,你最好并保持更新到最新版。 这不是好消息,我知道,但是这就是现实。如果有所安慰的话,似乎没有任何其它的操作系统完全地解决了这些问题,现在整个产业都在同一条船上,我们只需要等待,并让开发者尽快地解决这些问题。 提出的解决方案并非毫不重要,但是它们中的一些还是非常好的。一些新概念会被创造出来来帮助解决这些问题,Paul Turner 提出的 Retpoline 方法就是其中的一个例子。这将是未来大量研究的一个领域,想出方法去减轻硬件中涉及的潜在问题,希望在它发生前就去预见它。 ### 其他架构的芯片 现在,我没有看见任何 x86 和 arm64 架构以外的芯片架构的补丁,听说在一些企业发行版中有一些用于其他类型的处理器的补丁,希望他们在这几周里能浮出水面,合并到合适的上游那里。我不知道什么时候会发生,如果你使用着一个特殊的架构,我建议在 arch-specific 邮件列表上问这件事来得到一个直接的回答。 ### 结论 再次说一遍,更新你的内核,不要耽搁,不要止步。更新会在很长的一段时间里持续地解决这些问题。同样的,稳定和长期支持内核发行版里仍然有很多其它的 bug 和安全问题,它们和问题的类型无关,所以一直保持更新始终是一个好主意。 现在,有很多非常劳累、坏脾气、缺少睡眠的人,他们通常会生气地让内核开发人员竭尽全力地解决这些问题,即使这些问题完全不是开发人员自己造成的。请关爱这些可怜的程序猿。他们需要爱、支持,我们可以为他们免费提供的他们最爱的饮料,以此来确保我们都可以尽可能快地结束修补系统。 --- via: <http://kroah.com/log/blog/2018/01/06/meltdown-status/> 作者:[Greg Kroah-Hartman](http://kroah.com) 译者:[hopefully2333](https://github.com/hopefully2333) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
By now, everyone knows that something “big” just got announced regarding computer security. Heck, when the [Daily Mail does a report on it](http://www.dailymail.co.uk/sciencetech/article-5238789/Intel-says-security-updates-fix-Meltdown-Spectre.html) , you know something is bad… Anyway, I’m not going to go into the details about the problems being reported, other than to point you at the wonderfully written [Project Zero paper on the issues involved here](https://googleprojectzero.blogspot.fr/2018/01/reading-privileged-memory-with-side.html). They should just give out the 2018 [Pwnie](https://pwnies.com/) award right now, it’s that amazingly good. If you do want technical details for how we are resolving those issues in the kernel, see the always awesome [lwn.net writeup for the details](https://lwn.net/Articles/743265/). Also, here’s a good summary of [lots of other postings](https://lwn.net/Articles/742999/) that includes announcements from various vendors. As for how this was all handled by the companies involved, well this could be described as a textbook example of how *NOT* to interact with the Linux kernel community properly. The people and companies involved know what happened, and I’m sure it will all come out eventually, but right now we need to focus on fixing the issues involved, and not pointing blame, no matter how much we want to. ## What you can do right now If your Linux systems are running a normal Linux distribution, go update your kernel. They should all have the updates in them already. And then keep updating them over the next few weeks, we are still working out lots of corner case bugs given that the testing involved here is complex given the huge variety of systems and workloads this affects. If your distro does not have kernel updates, then I strongly suggest changing distros right now. However there are lots of systems out there that are not running “normal” Linux distributions for various reasons (rumor has it that it is way more than the “traditional” corporate distros). They rely on the LTS kernel updates, or the normal stable kernel updates, or they are in-house franken-kernels. For those people here’s the status of what is going on regarding all of this mess in the upstream kernels you can use. ## Meltdown – x86 Right now, Linus’s kernel tree contains all of the fixes we currently know about to handle the Meltdown vulnerability for the x86 architecture. Go enable the CONFIG_PAGE_TABLE_ISOLATION kernel build option, and rebuild and reboot and all should be fine. However, Linus’s tree is currently at 4.15-rc6 + some outstanding patches. 4.15-rc7 should be out tomorrow, with those outstanding patches to resolve some issues, but most people do not run a -rc kernel in a “normal” environment. Because of this, the x86 kernel developers have done a wonderful job in their development of the page table isolation code, so much so that the backport to the latest stable kernel, 4.14, has been almost trivial for me to do. This means that the latest 4.14 release (4.14.12 at this moment in time), is what you should be running. 4.14.13 will be out in a few more days, with some additional fixes in it that are needed for some systems that have boot-time problems with 4.14.12 (it’s an obvious problem, if it does not boot, just add the patches now queued up.) I would personally like to thank Andy Lutomirski, Thomas Gleixner, Ingo Molnar, Borislav Petkov, Dave Hansen, Peter Zijlstra, Josh Poimboeuf, Juergen Gross, and Linus Torvalds for all of the work they have done in getting these fixes developed and merged upstream in a form that was so easy for me to consume to allow the stable releases to work properly. Without that effort, I don’t even want to think about what would have happened. For the older long term stable (LTS) kernels, I have leaned heavily on the wonderful work of Hugh Dickins, Dave Hansen, Jiri Kosina and Borislav Petkov to bring the same functionality to the 4.4 and 4.9 stable kernel trees. I had also had immense help from Guenter Roeck, Kees Cook, Jamie Iles, and many others in tracking down nasty bugs and missing patches. I want to also call out David Woodhouse, Eduardo Valentin, Laura Abbott, and Rik van Riel for their help with the backporting and integration as well, their help was essential in numerous tricky places. These LTS kernels also have the CONFIG_PAGE_TABLE_ISOLATION build option that should be enabled to get complete protection. As this backport is very different from the mainline version that is in 4.14 and 4.15, there are different bugs happening, right now we know of some VDSO issues that are getting worked on, and some odd virtual machine setups are reporting strange errors, but those are the minority at the moment, and should not stop you from upgrading at all right now. If you do run into problems with these releases, please let us know on the stable kernel mailing list. If you rely on any other kernel tree other than 4.4, 4.9, or 4.14 right now, and you do not have a distribution supporting you, you are out of luck. The lack of patches to resolve the Meltdown problem is so minor compared to the hundreds of other known exploits and bugs that your kernel version currently contains. You need to worry about that more than anything else at this moment, and get your systems up to date first. Also, go yell at the people who forced you to run an obsoleted and insecure kernel version, they are the ones that need to learn that doing so is a totally reckless act. ## Meltdown – ARM64 Right now the ARM64 set of patches for the Meltdown issue are not merged into Linus’s tree. They are [staged and ready to be merged](https://git.kernel.org/pub/scm/linux/kernel/git/arm64/linux.git/log/?h=kpti) into 4.16-rc1 once 4.15 is released in a few weeks. Because these patches are not in a released kernel from Linus yet, I can not backport them into the stable kernel releases (hey, we have [rules](https://www.kernel.org/doc/html/latest/process/stable-kernel-rules.html) for a reason…) Due to them not being in a released kernel, if you rely on ARM64 for your systems (i.e. Android), I point you at the [Android Common Kernel tree](https://android.googlesource.com/kernel/common/) All of the ARM64 fixes have been merged into the [3.18,](https://android.googlesource.com/kernel/common/+/android-3.18) [4.4,](https://android.googlesource.com/kernel/common/+/android-4.4) and [4.9 branches](https://android.googlesource.com/kernel/common/+/android-4.9) as of this point in time. I would strongly recommend just tracking those branches as more fixes get added over time due to testing and things catch up with what gets merged into the upstream kernel releases over time, especially as I do not know when these patches will land in the stable and LTS kernel releases at this point in time. For the 4.4 and 4.9 LTS kernels, odds are these patches will never get merged into them, due to the large number of prerequisite patches required. All of those prerequisite patches have been long merged and tested in the android-common kernels, so I think it is a better idea to just rely on those kernel branches instead of the LTS release for ARM systems at this point in time. Also note, I merge all of the LTS kernel updates into those branches usually within a day or so of being released, so you should be following those branches no matter what, to ensure your ARM systems are up to date and secure. ## Spectre Now things get “interesting”… Again, if you are running a distro kernel, you *might* be covered as some of the distros have merged various patches into them that they claim mitigate most of the problems here. I suggest updating and testing for yourself to see if you are worried about this attack vector For upstream, well, the status is there is no fixes merged into any upstream tree for these types of issues yet. There are numerous patches floating around on the different mailing lists that are proposing solutions for how to resolve them, but they are under heavy development, some of the patch series do not even build or apply to any known trees, the series conflict with each other, and it’s a general mess. This is due to the fact that the Spectre issues were the last to be addressed by the kernel developers. All of us were working on the Meltdown issue, and we had no real information on exactly what the Spectre problem was at all, and what patches were floating around were in even worse shape than what have been publicly posted. Because of all of this, it is going to take us in the kernel community a few weeks to resolve these issues and get them merged upstream. The fixes are coming in to various subsystems all over the kernel, and will be collected and released in the stable kernel updates as they are merged, so again, you are best off just staying up to date with either your distribution’s kernel releases, or the LTS and stable kernel releases. It’s not the best news, I know, but it’s reality. If it’s any consolation, it does not seem that any other operating system has full solutions for these issues either, the whole industry is in the same boat right now, and we just need to wait and let the developers solve the problem as quickly as they can. The proposed solutions are not trivial, but some of them are amazingly good. The [Retpoline](https://support.google.com/faqs/answer/7625886) post from Paul Turner is an example of some of the new concepts being created to help resolve these issues. This is going to be an area of lots of research over the next years to come up with ways to mitigate the potential problems involved in hardware that wants to try to predict the future before it happens. ## Other arches Right now, I have not seen patches for any other architectures than x86 and arm64. There are rumors of patches floating around in some of the enterprise distributions for some of the other processor types, and hopefully they will surface in the weeks to come to get merged properly upstream. I have no idea when that will happen, if you are dependant on a specific architecture, I suggest asking on the arch-specific mailing list about this to get a straight answer. ## Conclusion Again, update your kernels, don’t delay, and don’t stop. The updates to resolve these problems will be continuing to come for a long period of time. Also, there are still lots of other bugs and security issues being resolved in the stable and LTS kernel releases that are totally independent of these types of issues, so keeping up to date is always a good idea. Right now, there are a lot of very overworked, grumpy, sleepless, and just generally pissed off kernel developers working as hard as they can to resolve these issues that they themselves did not cause at all. Please be considerate of their situation right now. They need all the love and support and free supply of their favorite beverage that we can provide them to ensure that we all end up with fixed systems as soon as possible.
9,327
为 Linux 初学者讲解 wc 命令
https://www.howtoforge.com/linux-wc-command-explained-for-beginners-6-examples/
2018-02-09T23:29:30
[ "wc" ]
https://linux.cn/article-9327-1.html
![](/data/attachment/album/201802/09/232919mj5ahh8apsuepydt.jpg) 在命令行工作时,有时您可能想要知道一个文件中的单词数量、字节数、甚至换行数量。如果您正在寻找这样做的工具,您会很高兴地知道,在 Linux 中,存在一个命令行实用程序,它被称为 `wc` ,它为您完成所有这些工作。在本文中,我们将通过简单易懂的例子来讨论这个工具。 但是在我们开始之前,值得一提的是,本教程中提供的所有示例都在 Ubuntu 16.04 上进行了测试。 ### Linux wc 命令 `wc` 命令打印每个输入文件的新行、单词和字节数。以下是该命令行工具的语法: ``` wc [OPTION]... [FILE]... ``` 以下是 `wc` 的 man 文档的解释: ``` 为每个文件打印新行、单词和字节数,如果指定多于一个文件,也列出总的行数。单词是由空格分隔的非零长度的字符序列。如果没有指定文件,或当文件为 `-`,则读取标准输入。 ``` 下面的 Q&A 样式的示例将会让您更好地了解 `wc` 命令的基本用法。 注意:在所有示例中我们将使用一个名为 `file.txt` 的文件作为输入文件。以下是该文件包含的内容: ``` hi hello how are you thanks. ``` ### Q1. 如何打印字节数 使用 `-c` 命令选项打印字节数. ``` wc -c file.txt ``` 下面是这个命令在我们的系统上产生的输出: [![如何打印字节数](/data/attachment/album/201802/09/232932ah1iqtgkcn1knddn.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/wc-c-option.png) 文件包含 29 个字节。 ### Q2. 如何打印字符数 要打印字符数,请使用 `-m` 命令行选项。 ``` wc -m file.txt ``` 下面是这个命令在我们的系统上产生的输出: [![如何打印字符数](/data/attachment/album/201802/09/232934j44lgkertkl1vtsg.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/wc-m-option.png) 文件包含 29 个字符。 ### Q3. 如何打印换行数 使用 `-l` 命令选项来打印文件中的新行数: ``` wc -l file.txt ``` 这里是我们的例子的输出: [![如何打印换行数](/data/attachment/album/201802/09/232936ubbehhsephhmvv7v.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/wc-l-option.png) ### Q4. 如何打印单词数 要打印文件中的单词数量,请使用 `-w` 命令选项。 ``` wc -w file.txt ``` 在我们的例子中命令的输出如下: [![如何打印字数](/data/attachment/album/201802/09/232938es50762fhnb5sa01.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/wc-w-option.png) 这显示文件中有 6 个单词。 ### Q5. 如何打印最长行的显示宽度或长度 如果您想要打印输入文件中最长行的长度,请使用 `-l` 命令行选项。 ``` wc -L file.txt ``` 下面是在我们的案例中命令产生的结果: [![如何打印最长行的显示宽度或长度](/data/attachment/album/201802/09/232940ovfdjojdsvufwut8.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/wc-L-option.png) 所以文件中最长的行长度是 11。 ### Q6. 如何从文件读取输入文件名 如果您有多个文件名,并且您希望 `wc` 从一个文件中读取它们,那么使用`-files0-from` 选项。 ``` wc --files0-from=names.txt ``` [![如何从文件读取输入文件名](/data/attachment/album/201802/09/232941aux4u1qphz4epmjg.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/wc-file0-from-option.png) 如你所见 `wc` 命令,在这个例子中,输出了文件 `file.txt` 的行、单词和字符计数。文件名为 `file.txt` 的文件在 `name.txt` 文件中提及。值得一提的是,要成功地使用这个选项,文件中的文件名应该用 NUL 终止——您可以通过键入`Ctrl + v` 然后按 `Ctrl + Shift + @` 来生成这个字符。 ### 结论 正如您所认同的一样,从理解和使用目的来看, `wc` 是一个简单的命令。我们已经介绍了几乎所有的命令行选项,所以一旦你练习了我们这里介绍的内容,您就可以随时在日常工作中使用该工具了。想了解更多关于 `wc` 的信息,请参考它的 [man 文档](https://linux.die.net/man/1/wc)。 --- via: <https://www.howtoforge.com/linux-wc-command-explained-for-beginners-6-examples/> 作者:[Himanshu Arora](https://www.howtoforge.com) 译者:[stevenzdg988](https://github.com/stevenzdg988) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Linux wc Command Explained for Beginners (6 Examples) While working on the command line, sometimes you may want to access the number of words, byte counts, or even newlines in a file. If you are looking for a tool to do this, you'll be glad to know that in Linux, there exists a command line utility - dubbed **wc** - that does all this for you. In this article, we will be discussing this tool through easy to understand examples. But before we jump in, it's worth mentioning that all examples provided in this tutorial have been tested on Ubuntu 16.04. ## Linux wc command The wc command prints newline, word, and byte counts for each input file. Following is the syntax of this command line tool: wc [OPTION]... [FILE]... And here's how wc's man page explains it: Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. A word is a non-zero-length sequence of characters delimited by white space. With no FILE, or when FILE is -, read standard input. The following Q&A-styled examples will give you an even better idea about the basic usage of wc. Note: We'll be using a file named file.txt as the input file in all our examples. Following is what the file contains: hi hello how are you thanks. ## Q1. How to print the byte count Use the **-c** command line option to print the byte count. wc -c file.txt Here's the output this command produced on our system: So the file contains 29 bytes. ## Q2. How to print the character count To print the number of characters, use the **-m** command line option. wc -m file.txt Here's the output this command produced on our system: So the file contains 29 characters. ## Q3. How to print the newline count Use the **-l** command line option to print the number of newlines in the file. wc -l file.txt Here's the output in our case: ## Q4. How to print the word count To print the number of words present in the file, use the **-w** command line option. wc -w file.txt Following the output the command produced in our case: So this reveals there are 6 words in the file. ## Q5. How to print the maximum display width or length of longest line In case you want to print the length of the longest line in the input file, use the **-L** command line option. wc -L file.txt Here's the output the command produced in our case: So the length of the longest file in our file is 11. ## Q6. How to read input file name(s) from a file In case you have multiple file names, and you want wc to read them from a file, then use the **--files0-from** option. wc --files0-from=names.txt So you can see that the wc command, in this case, produced lines, words, and characters count for file.txt in the output. The name file.txt was mentioned in the names.txt file. It's worth mentioning that to successfully use this option, names written the file should be NUL terminated - you can generate this character by typing `Ctrl`+`v` followed by `Ctrl`+`Shift`+`@.` ## Conclusion As you'd agree, wc is a simple command, both from understanding and usage purposes. We've covered pretty much all command line options the tool offers, so you should be ready to use the tool on a daily basis once you practice whatever we've explained here. For more info on wc, head to its [man page](https://linux.die.net/man/1/wc).
9,328
Linux 内核 4.15:“一个不同寻常的发布周期”
https://www.linux.com/blog/intro-to-linux/2018/1/linux-kernel-415-unusual-release-cycle
2018-02-10T09:50:08
[ "Linux", "内核", "KPTI" ]
https://linux.cn/article-9328-1.html
![Linux](/data/attachment/album/201802/10/095011cuxjqpmf7pyxkvh3.png "Linux") > > Linus Torvalds 在周日发布了 Linux 的 4.15 版内核,比原计划发布时间晚了一周。了解这次发行版的关键更新。 > > > Linus Torvalds 在周日(1 月 28 日)[发布了 Linux 内核的 4.15 版](https://lkml.org/lkml/2018/1/28/173),再一次比原计划晚了一周。延迟发布的罪魁祸首是 “Meltdown” 和 “Spectre” bug,由于这两个漏洞,使开发者不得不在这最后的周期中提交重大补丁。Torvalds 不愿意“赶工”,因此,他又给了一周时间去制作这个发行版本。 不出意外的话,这第一批补丁将是去修补前面提及的 [Meltdown 和 Spectre](https://meltdownattack.com/) 漏洞。为防范 Meltdown —— 这个影响 Intel 芯片的问题,在 x86 架构上[开发者实现了页表隔离(PTI)](https://git.kernel.org/linus/5aa90a84589282b87666f92b6c3c917c8080a9bf)。不论什么理由你如果想去关闭它,你可以使用内核引导选项 `pti=off` 去关闭这个特性。 Spectre v2 漏洞对 Intel 和 AMD 芯片都有影响,为防范它,[内核现在带来了 retpoline 机制](https://git.kernel.org/linus/76b043848fd22dbf7f8bf3a1452f8c70d557b860)。Retpoline 要求 GCC 的版本支持 `-mindirect-branch=thunk-extern` 功能。由于使用了 PTI,Spectre 抑制机制可以被关闭,如果需要去关闭它,在引导时使用 `spectre_v2=off` 选项。尽管开发者努力去解决 Spectre v1,但是,到目前为止还没有一个解决方案,因此,在 4.15 的内核版本中并没有这个 bug 的修补程序。 对于在 ARM 上的 Meltdown 解决方案也将在下一个开发周期中推送。但是,[对于 PowerPC 上的 bug,在这个发行版中包含了一个补救措施,那就是使用 L1-D 缓存的 RFI 冲刷特性](https://git.kernel.org/linus/aa8a5e0062ac940f7659394f4817c948dc8c0667)。 一个有趣的事情是,上面提及的所有受影响的新内核中,都带有一个 `/sys/devices/system/cpu/vulnerabilities/` 虚拟目录。这个目录显示了影响你的 CPU 的漏洞以及当前应用的补救措施。 芯片带 bug (以及保守秘密的制造商)的问题重新唤起了开发可行的开源替代品的呼声。这使得已经合并到主线版本的内核提供了对 [RISC-V](https://riscv.org/) 芯片的部分支持。RISC-V 是一个开源的指令集架构,它允许制造商去设计他们自己的基于 RISC-V 芯片的实现。并且因此也有了几个开源的芯片。虽然 RISC-V 芯片目前主要用于嵌入式设备,它能够去做像智能硬盘或者像 Arduino 这样的开发板,RISC-V 的支持者认为这个架构也可以用于个人电脑甚至是多节点的超级计算机上。 正如在上面提到的,[对 RISC-V 的支持](https://git.kernel.org/torvalds/c/b293fca43be544483b6488d33ad4b3ed55881064),仍然没有全部完成,它虽然包含了架构代码,但是没有设备驱动。这意味着,虽然 Linux 内核可以在 RISC-V 芯片上运行,但是没有可行的方式与底层的硬件进行实质的交互。也就是说,RISC-V 不会受到其它闭源架构上的任何 bug 的影响,并且对它的支持的开发工作也在加速进行,因为,[RISC-V 基金会已经得到了一些行业巨头的支持](https://riscv.org/membership/)。 ### 4.15 版新内核中的其它新特性 Torvalds 经常说他喜欢的事情是很无聊的。对他来说,幸运的是,除了 Spectre 和 Meltdown 引发的混乱之外,在 4.15 内核中的大部分其它东西都很普通,比如,对驱动的进一步改进、对新设备的支持等等。但是,还有几点需要重点指出,它们是: * [AMD 对虚拟化安全加密的支持](https://git.kernel.org/linus/33e63acc119d15c2fac3e3775f32d1ce7a01021b)。它允许内核通过加密来实现对虚拟机内存的保护。加密的内存仅能够被使用它的虚拟机所解密。就算是 hypervisor 也不能看到它内部的数据。这意味着在云中虚拟机正在处理的数据,在虚拟机外的任何进程都看不到。 * 由于 [包含了*显示代码*](https://git.kernel.org/torvalds/c/f6705bf959efac87bca76d40050d342f1d212587), AMD GPU 得到了极大的提升,这使得 Radeon RX Vega 和 Raven Ridge 显卡得到了内核主线版本的支持,并且也在 AMD 显卡中实现了 HDMI/DP 音频。 * 树莓派的爱好者应该很高兴,因为在新内核中, [7" 触摸屏现在已经得到原生支持](https://git.kernel.org/linus/2f733d6194bd58b26b705698f96b0f0bd9225369),这将产生成百上千的有趣的项目。 要发现更多的特性,你可以去查看在 [Kernel Newbies](https://kernelnewbies.org/Linux_4.15) 和 [Phoronix](https://www.phoronix.com/scan.php?page=search&amp;q=Linux+4.15) 上的内容。 --- via: <https://www.linux.com/blog/intro-to-linux/2018/1/linux-kernel-415-unusual-release-cycle> 作者:[PAUL BROWN](https://www.linux.com/users/bro66) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,329
如何启动进入 Linux 命令行
http://www.linuxandubuntu.com/home/how-to-boot-into-linux-command-line
2018-02-10T11:20:25
[ "命令行" ]
https://linux.cn/article-9329-1.html
![](/data/attachment/album/201802/10/112026pnx0castr7l1ksvk.jpg) 可能有时候你启动 Linux 时需要或者希望不使用 GUI(图形用户界面),也就是没有 X,而是选择命令行。不管是什么原因,幸运的是,直接启动进入 Linux 命令行非常简单。它需要在其他内核选项之后对引导参数进行简单的更改。此更改将系统引导到指定的运行级别。 ### ​为什么要这样做? 如果你的系统由于无效配置或者显示管理器损坏或任何可能导致 GUI 无法正常启动的情况而无法运行 Xorg,那么启动到命令行将允许你通过登录到终端进行故障排除(假设你知道要怎么做),并能做任何你需要做的东西。引导到命令行也是一个很好的熟悉终端的方式,不然,你也可以为了好玩这么做。 ### ​访问 GRUB 菜单 在启动时,你需要访问 GRUB 启动菜单。如果在每次启动计算机时菜单未设置为显示,那么可能需要在系统启动之前按住 `SHIFT` 键。在菜单中,需要选择 Linux 发行版条目。高亮显示后该条目,按下 `e` 编辑引导参数。 [![zorin os grub menu](/data/attachment/album/201802/10/112027xfj784l4n8tmalto.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/gnu-grub_orig.png) 较老的 GRUB 版本遵循类似的机制。启动管理器应提供有关如何编辑启动参数的说明。 ### ​​指定运行级别 ​会出现一个编辑器,你将看到 GRUB 会解析给内核的选项。移动到以 `linux` 开头的行(旧的 GRUB 版本可能是 `kernel`,选择它并按照说明操作)。这指定了要解析给内核的参数。在该行的末尾(可能会出现跨越多行,具体取决于你的终端分辨率),只需指定要引导的运行级别,即 `3`(多用户模式,纯文本)。 [![customize grub menu](/data/attachment/album/201802/10/112027d8emclm45bm7z47m.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/runlevel_orig.png) 按下 `Ctrl-X` 或 `F10` 将使用这些参数启动系统。开机和以前一样。唯一改变的是启动的运行级别。 这是启动后的页面: [![boot linux in command line](/data/attachment/album/201802/10/112027s4kxpnpfkw4x54pj.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/runlevel_1_orig.png) ### 运行级别 你可以指定不同的运行级别,默认运行级别是 `5` (多用户图形界面)。`1` 启动到“单用户”模式,它会启动进入 root shell。`3` 提供了一个多用户命令行系统。 ### 从命令行切换 在某个时候,你可能想要运行显示管理器来再次使用 GUI,最快的方法是运行这个: ``` $ sudo init 5 ``` 就这么简单。就我个人而言,我发现命令行比使用 GUI 工具更令人兴奋和上手。不过,这只是我的个人偏好。 --- via: <http://www.linuxandubuntu.com/home/how-to-boot-into-linux-command-line> 作者:[LinuxAndUbuntu](http://www.linuxandubuntu.com) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,330
cURL 与 wget:你应该选用哪一个?
https://www.maketecheasier.com/curl-vs-wget/
2018-02-10T11:32:09
[ "curl", "wget", "下载" ]
https://linux.cn/article-9330-1.html
![](/data/attachment/album/201802/10/113214z991g8h9g99zfd4h.jpg) 当想要直接通过 Linux 命令行下载文件,马上就能想到两个工具:wget 和 cURL。它们有很多一样的特征,可以很轻易的完成一些相同的任务。 虽然它们有一些相似的特征,但它们并不是完全一样。这两个程序适用与不同的场合,在特定场合下,都拥有各自的特性。 ### cURL vs wget: 相似之处 wget 和 cURL 都可以下载内容。它们的核心就是这么设计的。它们都可以向互联网发送请求并返回请求项。这可以是文件、图片或者是其他诸如网站的原始 HTML 之类。 这两个程序都可以进行 HTTP POST 请求。这意味着它们都可以向网站发送数据,比如说填充表单什么的。 由于这两者都是命令行工具,它们都被设计成可脚本化。wget 和 cURL 都可以写进你的 [Bash 脚本](https://www.maketecheasier.com/beginners-guide-scripting-linux/) ,自动与新内容交互,下载所需内容。 ### wget 的优势 ![wget download](/data/attachment/album/201802/10/113216xpktn68tnvwnd1hw.jpg "wget download") wget 简单直接。这意味着你能享受它超凡的下载速度。wget 是一个独立的程序,无需额外的资源库,更不会做其范畴之外的事情。 wget 是专业的直接下载程序,支持递归下载。同时,它也允许你下载网页中或是 FTP 目录中的任何内容。 wget 拥有智能的默认设置。它规定了很多在常规浏览器里的事物处理方式,比如 cookies 和重定向,这都不需要额外的配置。可以说,wget 简直就是无需说明,开罐即食! ### cURL 优势 ![cURL Download](/data/attachment/album/201802/10/113216zp8zar8l1tgpbuku.jpg "cURL Download") cURL是一个多功能工具。当然,它可以下载网络内容,但同时它也能做更多别的事情。 cURL 技术支持库是:libcurl。这就意味着你可以基于 cURL 编写整个程序,允许你基于 libcurl 库中编写图形环境的下载程序,访问它所有的功能。 cURL 宽泛的网络协议支持可能是其最大的卖点。cURL 支持访问 HTTP 和 HTTPS 协议,能够处理 FTP 传输。它支持 LDAP 协议,甚至支持 Samba 分享。实际上,你还可以用 cURL 收发邮件。 cURL 也有一些简洁的安全特性。cURL 支持安装许多 SSL/TLS 库,也支持通过网络代理访问,包括 SOCKS。这意味着,你可以越过 Tor 来使用cURL。 cURL 同样支持让数据发送变得更容易的 gzip 压缩技术。 ### 思考总结 那你应该使用 cURL 还是使用 wget?这个比较得看实际用途。如果你想快速下载并且没有担心参数标识的需求,那你应该使用轻便有效的 wget。如果你想做一些更复杂的使用,直觉告诉你,你应该选择 cRUL。 cURL 支持你做很多事情。你可以把 cURL 想象成一个精简的命令行网页浏览器。它支持几乎你能想到的所有协议,可以交互访问几乎所有在线内容。唯一和浏览器不同的是,cURL 不会渲染接收到的相应信息。 --- via: <https://www.maketecheasier.com/curl-vs-wget/> 作者:[Nick Congleton](https://www.maketecheasier.com/author/nickcongleton/) 译者:[CYLeft](https://github.com/CYLeft) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Curl Command Guide Featured](https://www.maketecheasier.com/assets/uploads/2021/11/curl-command-guide-featured.jpg) If you’ve been following terminal-focused installation instructions for Linux applications for a while, you’ve probably come across the `curl` command at some point or another. cURL is a command-line tool for transferring data with URLs. One of the simplest uses is to download a file via the command line. This is deceptive, however, as cURL is an incredibly powerful tool that can do much more. **Also read:** [How to Copy and Paste Text, Files and Folders in Linux Terminal](https://www.maketecheasier.com/copy-paste-files-linux-command-line/) ## What Is cURL? Originally written by Daniel Sternberg in 1996 to grab financial data from web servers and broadcast it to IRC channels, cURL has evolved to become a powerful tool for getting data without having to use a browser. If you’re always using the terminal, this will be one of the more important tools in your arsenal. In most Linux distributions, cURL is preinstalled in the system, and you can use it straight away. Even if it is not installed, it is also found in most repositories, so you can easily install it using the Software Center. For Windows, it does not have a “curl-like” command, and macOS has cURL preinstalled but doesn’t offer [quite as many flags](https://ss64.com/osx/curl.html) as the Linux version. **Also read:** [How to Use the dd Command in Linux](https://www.maketecheasier.com/use-dd-command-linux/) ## Installation Before we proceed any further, we have to make sure that cURL is already installed on our system. ### Linux In Debian/Ubuntu-based distros, use the following command to install cURL: sudo apt install curl In Arch-based distros: sudo pacman -S curl In Fedora/CentOS/RHEL: sudo dnf install curl ### macOS For macOS, it is already preinstalled, so you don’t need to do anything. **Also read:** [How to Launch Terminal in the Current Folder Location on Mac](https://www.maketecheasier.com/launch-terminal-current-folder-mac/) ### Windows - For Windows 7/10/11, head over to the [cURL download page](https://curl.se/windows/)and choose from either the 64-bit or 32-bit packages, according to the architecture you’re running. If you don’t know your architecture, 64-bit is a safe bet, as the vast majority of hardware made after 2006 is on it. - Create a folder either directly on the system drive or in “C:\Program Files\” and call it “cURL.” ![Linuxcurl Newfolder](https://www.maketecheasier.com/assets/uploads/2021/11/linuxcurl-newfolder.png) - Go back to the zip file you downloaded, open it, and find “curl.exe” inside the “bin” folder. Copy that to the cURL folder you created. The EXE you copied is completely self-contained and capable of running every permutation you can run on Linux. - To make this command actually useful, we have to add it to the PATH variable in Windows so that it can run from the command prompt anywhere. - Click on your Start menu, type `environment` , and press`Enter`. - Click on “Environment Variables … ” You should now be in your environment variables settings. ![Linuxcurl Environmentvariables](https://www.maketecheasier.com/assets/uploads/2021/11/linuxcurl-environmentvariables.png) - Select the “Path” environment variable, then click “Edit … “ - Once in the path edit dialog window, click “New” and type out the directory where your “curl.exe” is located – for example, “C:\Program Files\cURL”. ![Linuxcurl Editvariable](https://www.maketecheasier.com/assets/uploads/2021/11/linuxcurl-editvariable.png) - Click “OK” on the dialog windows you opened through this process and enjoy having cURL in your terminal! Every flag in cURL that’s usable in Linux should work in the Windows version. **Word to the wise:** remember that the command prompt should never be confused with Windows Terminal. Windows Terminal comes with its own version of cURL included in the PowerShell that serves similar functionality but works entirely differently. **Also read:** [How to Use Rm Command in Linux](https://www.maketecheasier.com/use-rm-command-linux/) ## Using cURL To get started, simply type `curl maketecheasier.com` in your terminal and press `Enter`. If you are not getting any output, it is because this site’s server is not configured to respond to random connection requests to its non-www domain. If you polled a server that doesn’t exist or isn’t online, you’d get an error message saying that cURL could not resolve the host. ![Linuxcurl Error](https://www.maketecheasier.com/assets/uploads/2021/10/linuxcurl-error.png) To get cURL to do something actually useful, we’ll have to specify a protocol. In our example, we are using the HTTPS protocol to query this site’s home page. Type `curl https://www.maketecheasier.com` . ![Linuxcurl Files](https://www.maketecheasier.com/assets/uploads/2021/10/linuxcurl-files.png) If all goes well, you should be staring at a gigantic wall of data. To make that data a bit more usable, we can tell cURL to put it into an HTML file: curl https://www.maketecheasier.com > ~/Downloads/mte.html ![Linuxcurl Download](https://www.maketecheasier.com/assets/uploads/2021/10/linuxcurl-download.png) This command puts the contents of our site’s output into an HTML file in your Downloads folder. Navigate to the folder with your favorite file manager and double-click the file you just made. It should open a snapshot of the HTML output of this site’s home page. ![Linuxcurl Testing](https://www.maketecheasier.com/assets/uploads/2021/10/linuxcurl-testing.png) Similarly, you can use the `-o` flag to achieve the same result: curl -o ~/Downloads/mte.html https://www.maketecheasier.com ## Following Redirects Most sites automatically redirect the traffic from “http” to “https” protocol. In cURL, you can achieve the same thing with the `-L` flag. This will automatically follow 301 redirects until it reaches a readable page or file. curl -L http://google.com. ![Linuxcurl Redirect](https://www.maketecheasier.com/assets/uploads/2021/11/linuxcurl-redirect.png) ## Resuming a Download When downloading large files, depending on your Internet speed, interruptions can be immensely irritating. Thankfully, cURL has a resume function. Passing the `-C` flag will take care of this issue in a jiffy. To show a real-world example, I interrupted a download of Debian’s testing release ISO on purpose by pressing `Ctrl` and `C` in the middle of grabbing it. ![Linuxcurl Interrupted](https://www.maketecheasier.com/assets/uploads/2021/11/linuxcurl-interrupted.png) For our next command, are attching the `-C` flag. For example, curl -C - -o ~/Downloads/debiantesting.iso -L https://cdimage.debian.org/cdimage/weekly-builds/amd64/iso-dvd/debian-testing-amd64-DVD-1.iso ![Linuxcurl Resume](https://www.maketecheasier.com/assets/uploads/2021/10/linuxcurl-resume.png) The download successfully started where it left off. ## Downloading More than One File Because cURL doesn’t have the most intuitive way to download multiple files, there are two methods, each one with its own compromise. If the files you’re downloading are enumerated (e.g., file1, file2, and so on), you can use brackets to get the full range of files and “#” within the output you specify with the `-o` flag. To make this a bit less confusing, here’s an example: curl "http://example.com/file[1-5].zip" -o "#1_#2" A simpler way of doing this is with `-O` (`--remote-name` ). This flag makes cURL download the remote file onto a local file of the same name. Since you don’t have to specify an output, you should use this command when the terminal is open in the directory you want to download files to. curl -O "https://example.com/file1.zip" -O "https://example.com/file2.zip" If you have a large amount of enumerated files to download, `--remote-name-all` is a better flag for this: curl --remote-name-all "https://example.com/file[1-5].zip" You could even specify non-enumerated files coming from the same site without having to re-type the URL using brackets: curl --remote-name-all "https://example.com/{file1.zip,anotherfile.zip,thisisfun.zip}" ## Downloading with Authentication Download files that require authentication (for example, when grabbing from a private FTP server) with the `-u` flag. Every authentication request must be done with the username first and the password second, with a colon separating the two. Here’s an example to make things simple: curl -u username:password -o ~/Downloads/file.zip ftp://example.com/file.zip This will authenticate our friend bonobo_bob into the FTP server and download the file into the Downloads folder. ## Splitting and Merging Files If for any reason you wish to download a large file and split it into chunks, you can do so with cURL’s `--range` flag. With `--range` , you must specify the byte you want to start at up to the one you want to finish at. If you do not specify an end to the range, it will just download the rest of the file. In the command below, cURL will download the first 100 MB of Arch Linux’s installation image: curl --range 0-99999999 -o arch.part1 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso For the next 100 MB, use `--range 100000000-199999999` , etc. You can chain these commands by using the `&&` operand: curl --range 0-99999999 -o arch.part1 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 100000000-199999999 -o arch.part2 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 200000000-299999999 -o arch.part3 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 300000000-399999999 -o arch.part4 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 400000000-499999999 -o arch.part5 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 500000000-599999999 -o arch.part6 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 600000000-699999999 -o arch.part7 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso && \ curl --range 700000000- -o arch.part8 -L https://mirrors.chroot.ro/archlinux/iso/2021.11.01/archlinux-2021.11.01-x86_64.iso If you followed the above command structure to the letter, eight files should appear where you asked cURL to download them. ![Linuxcurl Parts](https://www.maketecheasier.com/assets/uploads/2021/11/linuxcurl-parts.png) To reunite these files, you’ll have to use the `cat` command if you’re on Linux or macOS like so: cat arch.part? > arch.iso For Windows, you’ll have to use the `copy` command like this: copy /b arch.part* arch.iso ## Other Useful Features There are plenty of flags and uses for cURL: `-#` – Uses a progress bar to indicate how far along you are in what you’re grabbing. Example:`curl -# https://asite.com/somefile.zip > ~/somefile.zip` .`-a` – Asks cURL to append to a file rather than overwrite it. Example:`curl -ao ~/collab-full.x https://example-url.com/collab-part26.x` .`--head` – Only grabs the response header from the server without the output data. This is useful when you’re either debugging a website or having a peek at the server’s programmed responses to clients. Example:`curl --head https://example-url.com` .`--limit-rate` – Orders a download with limited bandwidth. It’s useful in situations where you don’t want cURL hogging all the available bandwidth in your system. A simple number will be interpreted as bytes per second. K represents kilobytes per second; M represents megabytes per second. Example:`curl --limit-rate 8M https://example-url.com/file.zip > ~/file.zip` .`-o` – As mentioned earlier, determines an output file for cURL to use. Example:`curl -o ~/Downloads/file.zip https://thefileplace.com/file.zip -o file2.zip https://thefileplace.com/file2.zip` .`--proxy` – If you want to work with a proxy, this is the way to do it. Example:`curl --proxy proxyurl:port https://example-url.com/file.zip > ~file.zip` . ## cURL vs. Wget Both released in the same year (1996), cURL and [Wget](https://www.maketecheasier.com/use-wget-download-websites-to-pc/) are pretty much sister programs to the casual observer. Dive a little deeper, though, and you can see these two sisters have different purposes. ### Wget - It’s fully built from the ground up to grab data from the Internet. - Doesn’t need the `-L` or`-o` flags like cURL; just type`wget [url]` and go! - Can download recursively to grab everything in a directory with the `-r` flag. - Has all the functions a user needs for daily use and caters to everyday sysadmin tasks. - (In Linux) Doesn’t need many dependencies; all of them should be available out of the box. **Also read:** [How to Install and Use wget on Mac](https://www.maketecheasier.com/install-wget-mac/) ### cURL - Expansive repertoire of flags and useful functions for remote retrieval. - Supports local networking (LDAP) and network printers (Samba). - Works well with gzip compression libraries. - Depends on libcurl, which allows developers to write software or bash scripts that include cURL’s functionality. In short, Wget is the “everyman’s toolbox” for grabbing stuff from the Internet, while cURL expands on this with more granulated control for power users and system administrators. ## Frequently Asked Questions ### 1. I got a certificate error in Linux. How do I fix it? If you got an error that says something like “peer’s certificate issuer has been marked as not trusted,” the easiest way to fix this is by reinstalling the common certificates package in your distro. For Debian/Ubuntu-based systems: sudo apt reinstall ca-certificates For Fedora/CentOS/RHEL: `dnf reinstall ca-certificates` For Arch-based systems: `pacman -S ca-certificates` Note that in Arch you may want to clear your package cache using `pacman -Scc` before reinstalling the certificates package. If you still get this error, there may be something wrong on the server’s end. ### 2. Is it safe to run cURL and bash commands together? While not the most common way to install Linux applications, there are a number of developers (such as the people behind NodeJS) that give you no choice but to use `curl` alongside a root-access command that runs through bash (e.g., `curl [argument] | sudo -E bash -` ) to install the software. It may look a bit scary, but if the people behind the application are trustworthy, it’s very unlikely you’ll break something. Malicious actors are everywhere and can infiltrate repositories like Arch’s AUR, so installing using `curl` in combination with root access commands isn’t generally more unsafe than doing so through your package manager. ### 3. Can I use cURL with Tor? Yes! Start Tor Browser (or a standalone tor service) and use the `--proxy` flag. Tor gives you a local proxy you can use to mask your IP in other applications. Here’s an example of cURL used with Tor: curl --proxy localhost:9050 http://example.com Standalone Tor services will use 9050 as their listening port, while the Tor browser uses port 9150. ## Wrapping Up cURL has proven resilient amid the changing fabric of the Linux world, keeping its position as an important tool in the terminal user’s arsenal. If you are new to the command line, check out some of the [most useful Linux commands](https://www.maketecheasier.com/useful-linux-commands/). If you simply want to search the Web instead of downloading data from the Internet, you can [browse on the terminal too](https://www.maketecheasier.com/how-to-search-web-from-linux-terminal/). Our latest tutorials delivered straight to your inbox
9,331
使用 Ansible 让你的系统管理自动化
https://opensource.com/article/17/7/automate-sysadmin-ansible
2018-02-10T12:11:00
[ "ansible" ]
https://linux.cn/article-9331-1.html
> > 精进你的系统管理能力和 Linux 技能,学习如何设置工具来简化管理多台机器。 > > > ![](/data/attachment/album/201802/10/121144exxulb5xlxeb5lau.jpg) 你是否想精进你的系统管理能力和 Linux 技能?也许你的本地局域网上跑了一些东西,而你又想让生活更轻松一点--那该怎么办呢?在本文中,我会向你演示如何设置工具来简化管理多台机器。 远程管理工具有很多,SaltStack、Puppet、Chef,以及 Ansible 都是很流行的选择。在本文中,我将重点放在 Ansible 上并会解释它是如何帮到你的,不管你是有 5 台还是 1000 台虚拟机。 让我们从多机(不管这些机器是虚拟的还是物理的)的基本管理开始。我假设你知道要做什么,有基础的 Linux 管理技能(至少要有能找出执行每个任务具体步骤的能力)。我会向你演示如何使用这一工具,而是否使用它由你自己决定。 ### 什么是 Ansible? Ansible 的网站上将之解释为 “一个超级简单的 IT 自动化引擎,可以自动进行云供给、配置管理、应用部署、服务内部编排,以及其他很多 IT 需求。” 通过在一个集中的位置定义好服务器集合,Ansible 可以在多个服务器上执行相同的任务。 如果你对 Bash 的 `for` 循环很熟悉,你会发现 Ansible 操作跟这很类似。区别在于 Ansible 是<ruby> 幕等的 <rt> idempotent </rt></ruby>。通俗来说就是 Ansible 一般只有在确实会发生改变时才执行所请求的动作。比如,假设你执行一个 Bash 的 for 循环来为多个机器创建用户,像这样子: ``` for server in serverA serverB serverC; do ssh ${server} "useradd myuser"; done ``` 这会在 serverA、serverB,以及 serverC 上创建 myuser 用户;然而不管这个用户是否存在,每次运行这个 for 循环时都会执行 `useradd` 命令。一个幕等的系统会首先检查用户是否存在,只有在不存在的情况下才会去创建它。当然,这个例子很简单,但是幕等工具的好处将会随着时间的推移变得越发明显。 #### Ansible 是如何工作的? Ansible 会将 Ansible playbooks 转换成通过 SSH 运行的命令,这在管理类 UNIX 环境时有很多优势: 1. 绝大多数类 UNIX 机器默认都开了 SSH。 2. 依赖 SSH 意味着远程主机不需要有代理。 3. 大多数情况下都无需安装额外的软件,Ansible 需要 2.6 或更新版本的 Python。而绝大多数 Linux 发行版默认都安装了这一版本(或者更新版本)的 Python。 4. Ansible 无需主节点。他可以在任何安装有 Ansible 并能通过 SSH 访问的主机上运行。 5. 虽然可以在 cron 中运行 Ansible,但默认情况下,Ansible 只会在你明确要求的情况下运行。 #### 配置 SSH 密钥认证 使用 Ansible 的一种常用方法是配置无需密码的 SSH 密钥登录以方便管理。(可以使用 Ansible Vault 来为密码等敏感信息提供保护,但这不在本文的讨论范围之内)。现在只需要使用下面命令来生成一个 SSH 密钥,如示例 1 所示。 ``` [09:44 user ~]$ ssh-keygen Generating public/private rsa key pair。 Enter file in which to save the key (/home/user/.ssh/id_rsa): Created directory '/home/user/.ssh'。 Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_rsa。 Your public key has been saved in /home/user/.ssh/id_rsa.pub。 The key fingerprint is: SHA256:TpMyzf4qGqXmx3aqZijVv7vO9zGnVXsh6dPbXAZ+LUQ user@user-fedora The key's randomart image is: +---[RSA 2048]----+ | | | | | E | | o . .。| | . + S o+。| | . .o * . .+ooo| | . .+o o o oo+。*| |。.ooo* o。* .*+| | . o+*BO.o+ .o| +----[SHA256]-----+ ``` *示例 1 :生成一个 SSH 密钥* 在示例 1 中,直接按下回车键来接受默认值。任何非特权用户都能生成 SSH 密钥,也能安装到远程系统中任何用户的 SSH 的 `authorized_keys` 文件中。生成密钥后,还需要将之拷贝到远程主机上去,运行下面命令: ``` ssh-copy-id root@servera ``` 注意:运行 Ansible 本身无需 root 权限;然而如果你使用非 root 用户,你*需要*为要执行的任务配置合适的 sudo 权限。 输入 servera 的 root 密码,这条命令会将你的 SSH 密钥安装到远程主机上去。安装好 SSH 密钥后,再通过 SSH 登录远程主机就不再需要输入 root 密码了。 ### 安装 Ansible 只需要在示例 1 中生成 SSH 密钥的那台主机上安装 Ansible。若你使用的是 Fedora,输入下面命令: ``` sudo dnf install ansible -y ``` 若运行的是 CentOS,你需要为 EPEL 仓库配置额外的包: ``` sudo yum install epel-release -y ``` 然后再使用 yum 来安装 Ansible: ``` sudo yum install ansible -y ``` 对于基于 Ubuntu 的系统,可以从 PPA 上安装 Ansible: ``` sudo apt-get install software-properties-common -y sudo apt-add-repository ppa:ansible/ansible sudo apt-get update sudo apt-get install ansible -y ``` 若你使用的是 macOS,那么推荐通过 Python PIP 来安装: ``` sudo pip install ansible ``` 对于其他发行版,请参见 [Ansible 安装文档](http://docs.ansible.com/ansible/intro_installation.html) 。 ### Ansible Inventory Ansible 使用一个 INI 风格的文件来追踪要管理的服务器,这种文件被称之为<ruby> 库存清单 <rt> Inventory </rt></ruby>。默认情况下该文件位于 `/etc/ansible/hosts`。本文中,我使用示例 2 中所示的 Ansible 库存清单来对所需的主机进行操作(为了简洁起见已经进行了裁剪): ``` [arch] nextcloud prometheus desktop1 desktop2 vm-host15 [fedora] netflix [centos] conan confluence 7-repo vm-server1 gitlab [ubuntu] trusty-mirror nwn kids-tv media-centre nas [satellite] satellite [ocp] lb00 ocp_dns master01 app01 infra01 ``` *示例 2 : Ansible 主机文件* 每个分组由中括号和组名标识(像这样 `[group1]` ),是应用于一组服务器的任意组名。一台服务器可以存在于多个组中,没有任何问题。在这个案例中,我有根据操作系统进行的分组(`arch`、`ubuntu`、`centos`、`fedora`),也有根据服务器功能进行的分组(`ocp`、`satellite`)。Ansible 主机文件可以处理比这复杂的多的情况。详细内容,请参阅 [库存清单文档](http://docs.ansible.com/ansible/intro_inventory.html)。 ### 运行命令 将你的 SSH 密钥拷贝到库存清单中所有服务器上后,你就可以开始使用 Ansible 了。Ansible 的一项基本功能就是运行特定命令。语法为: ``` ansible -a "some command" ``` 例如,假设你想升级所有的 CentOS 服务器,可以运行: ``` ansible centos -a 'yum update -y' ``` *注意:不是必须要根据服务器操作系统来进行分组的。我下面会提到,[Ansible Facts](http://docs.ansible.com/ansible/playbooks_variables.html#information-discovered-from-systems-facts) 可以用来收集这一信息;然而,若使用 Facts 的话,则运行特定命令会变得很复杂,因此,如果你在管理异构环境的话,那么为了方便起见,我推荐创建一些根据操作系统来划分的组。* 这会遍历 `centos` 组中的所有服务器并安装所有的更新。一个更加有用的命令应该是 Ansible 的 `ping` 模块了,可以用来验证服务器是否准备好接受命令了: ``` ansible all -m ping ``` 这会让 Ansible 尝试通过 SSH 登录库存清单中的所有服务器。在示例 3 中可以看到 `ping` 命令的部分输出结果。 ``` nwn | SUCCESS => { "changed":false, "ping":"pong" } media-centre | SUCCESS => { "changed":false, "ping":"pong" } nas | SUCCESS => { "changed":false, "ping":"pong" } kids-tv | SUCCESS => { "changed":false, "ping":"pong" } ... ``` *示例 3 :Ansible ping 命令输出* 运行指定命令的能力有助于完成快速任务(LCTT 译注:应该指的那种一次性任务),但是如果我想在以后也能以同样的方式运行同样的任务那该怎么办呢?Ansible [playbooks](http://docs.ansible.com/ansible/playbooks.html) 就是用来做这个的。 ### 复杂任务使用 Ansible playbooks Ansible <ruby> 剧本 <rt> playbook </rt> <rt> </rt></ruby> 就是包含 Ansible 指令的 YAML 格式的文件。我这里不打算讲解类似 Roles 和 Templates 这些比较高深的内容。有兴趣的话,请阅读 [Ansible 文档](http://docs.ansible.com/ansible/playbooks_roles.html)。 在前一章节,我推荐你使用 `ssh-copy-id` 命令来传递你的 SSH 密钥;然而,本文关注于如何以一种一致的、可重复性的方式来完成任务。示例 4 演示了一种以冥等的方式,即使 SSH 密钥已经存在于目标主机上也能保证正确性的实现方法。 ``` --- - hosts:all gather_facts:false vars: ssh_key:'/root/playbooks/files/laptop_ssh_key' tasks: - name:copy ssh key authorized_key: key:"{{ lookup('file',ssh_key) }}" user:root ``` *示例 4:Ansible 剧本 “push ssh keys.yaml”* `- hosts:` 行标识了这个剧本应该在那个主机组上执行。在这个例子中,它会检查库存清单里的所有主机。 `gather_facts:` 行指明 Ansible 是否去搜索每个主机的详细信息。我稍后会做一次更详细的检查。现在为了节省时间,我们设置 `gather_facts` 为 `false`。 `vars:` 部分,顾名思义,就是用来定义剧本中所用变量的。在示例 4 的这个简短剧本中其实不是必要的,但是按惯例我们还是设置了一个变量。 最后由 `tasks:` 标注的这个部分,是存放主体指令的地方。每个任务都有一个 `-name:`。Ansbile 在运行剧本时会显示这个名字。 `authorized_key:` 是剧本所使用 Ansible 模块的名字。可以通过命令 `ansible-doc -a` 来查询 Ansible 模块的相关信息; 不过通过网络浏览器查看 [文档](http://docs.ansible.com/ansible/modules_by_category.html) 可能更方便一些。[authorized\_key 模块](http://docs.ansible.com/ansible/authorized_key_module.html) 有很多很好的例子可以参考。要运行示例 4 中的剧本,只要运行 `ansible-playbook` 命令就行了: ``` ansible-playbook push_ssh_keys.yaml ``` 如果是第一次添加 SSH 密钥,SSH 会提示你输入 root 用户的密码。 现在 SSH 密钥已经传输到服务器中去了,可以来做点有趣的事了。 ### 使用 Ansible 收集信息 Ansible 能够收集目标系统的各种信息。如果你的主机数量很多,那它会特别的耗时。按我的经验,每台主机大概要花个 1 到 2 秒钟,甚至更长时间;然而有时收集信息是有好处的。考虑下面这个剧本,它会禁止 root 用户通过密码远程登录系统: ``` --- - hosts:all gather_facts:true vars: tasks: - name:Enabling ssh-key only root access lineinfile: dest:/etc/ssh/sshd_config regexp:'^PermitRootLogin' line:'PermitRootLogin without-password' notify: - restart_sshd - restart_ssh handlers: - name:restart_sshd service: name:sshd state:restarted enabled:true when:ansible_distribution == 'RedHat' - name:restart_ssh service: name:ssh state:restarted enabled:true when:ansible_distribution == 'Debian' ``` *示例 5:锁定 root 的 SSH 访问* 在示例 5 中 `sshd_config` 文件的修改是有[条件](http://docs.ansible.com/ansible/lineinfile_module.html) 的,只有在找到匹配的发行版的情况下才会执行。在这个案例中,基于 Red Hat 的发行版与基于 Debian 的发行版对 SSH 服务的命名是不一样的,这也是使用条件语句的目的所在。虽然也有其他的方法可以达到相同的效果,但这个例子很好演示了 Ansible 信息的作用。若你想查看 Ansible 默认收集的所有信息,可以在本地运行 `setup` 模块: ``` ansible localhost -m setup |less ``` Ansible 收集的所有信息都能用来做判断,就跟示例 4 中 `vars:` 部分所演示的一样。所不同的是,Ansible 信息被看成是**内置** 变量,无需由系统管理员定义。 ### 更近一步 现在可以开始探索 Ansible 并创建自己的基本了。Ansible 是一个富有深度、复杂性和灵活性的工具,只靠一篇文章不可能就把它讲透。希望本文能够激发你的兴趣,鼓励你去探索 Ansible 的功能。在下一篇文章中,我会再聊聊 `Copy`、`systemd`、`service`、`apt`、`yum`、`virt`,以及 `user` 模块。我们可以在剧本中组合使用这些模块,还可以创建一个简单的 Git 服务器来存储这些所有剧本。 --- via: <https://opensource.com/article/17/7/automate-sysadmin-ansible> 作者:[Steve Ovens](https://opensource.com/users/stratusss) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Do you want to sharpen your system administration or Linux skills? Perhaps you have some stuff running on your local LAN and you want to make your life easier—where do you begin? In this article, I'll explain how to set up tooling to simplify administering multiple machines. When it comes to remote administration tools, SaltStack, Puppet, Chef, and [Ansible](https://opensource.com/tags/ansible) are a few popular options. Throughout this article, I'll focus on Ansible and explain how it can be helpful whether you have 5 virtual machines or a 1,000. Our journey begins with the basic administration of multiple machines, whether they are virtual or physical. I will assume you have an idea of what you want to achieve, and basic Linux administration skills (or at least the ability to look up the steps required to perform each task). I will show you how to use the tools, and it is up to you to decide what to do with them. ## What is Ansible? The Ansible website explains the project as "a radically simple IT automation engine that automates cloud provisioning, configuration management, application deployment, intra-service orchestration, and many other IT needs." Ansible can be used to perform the same tasks across a defined set of servers from a centralized location. If you are familiar with Bash for-loops, you'll find that Ansible operates in a similar fashion. The difference, however, is that Ansible is *idempotent*. In layman's terms this means that generally Ansible only performs the requested action if a change will occur as a result. For example, if you were to perform a Bash for-loop to create a user across all of your machines, it may look something like this: for server in serverA serverB serverC; do ssh ${server} "useradd myuser"; done This would create **myuser** on **serverA**, **serverB**, and **serverC**; however, it would run the **user add** command every single time the for-loop was run, whether or not the user existed. An idempotent system will first check whether the user exists, and if it does not, the tool will create it. This is a simplified example, of course, but the benefits of an idempotent tool will become more clear over time. ### How does Ansible work? Ansible translates *Ansible playbooks* into commands that are run over SSH, which has several benefits when it comes to managing Unix-like environments: - Most, if not all of the Unix-like machines you are administering will have SSH running by default. - Relying on SSH means that no agent is required on the remote host. - In most cases no additional software needs to be installed as Ansible requires Python 2.6 in order to operate. Most, if not all distributions of Linux have this version (or greater) installed by default. - Ansible does not require a *master*node. It can be run from any host that has the Ansible package installed and sufficient SSH access. - Although running Ansible in a cron job is possible, by default Ansible only runs when you tell it to. ### Setting up SSH key authentication A common method for using Ansible is to set up passwordless SSH keys to facilitate ease of management. (Using Ansible Vault for passwords and other sensitive information is possible, but is outside the scope of this article.) For now, simply generate an SSH key with the following command as shown in Example 1. #### Example 1: Generating An SSH Key ``` `````` [09:44 user ~]$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/user/.ssh/id_rsa): Created directory '/home/user/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_rsa. Your public key has been saved in /home/user/.ssh/id_rsa.pub. The key fingerprint is: SHA256:TpMyzf4qGqXmx3aqZijVv7vO9zGnVXsh6dPbXAZ+LUQ user@user-fedora The key's randomart image is: +---[RSA 2048]----+ | | | | | E | | o . .. | | . + S o+. | | . .o * . .+ooo| | . .+o o o oo+.*| |. .ooo* o. * .*+| | . o+*BO.o+ .o| +----[SHA256]-----+ ``` In Example 1, the *Enter* key is used to accept the defaults. An SSH key can be generated by any unprivileged user and installed in any user's SSH **authorized_keys** file on the remote system. After the key has been generated, it will need to be copied to a remote host. To do so, run the following command: ssh-copy-id root@servera *Note: Ansible does not require root access; however, if you choose to use a non-root user, you *must* configure the appropriate sudo permissions for the tasks you want to accomplish.* You will be prompted for the root password for **servera**, which will allow your SSH key to be installed on the remote host. After the initial installation of the SSH key, you will no longer be prompted for the root password on the remote host when logging in over SSH. ## Installing Ansible The installation of the Ansible package is only required on the host that generated the SSH key in Example 1. If you are running Fedora, you can issue the following command: sudo dnf install ansible -y If you run CentOS, you need to configure Extra Packages for Enterprise Linux (EPEL) repositories: sudo yum install epel-release -y Then you can install Ansible with yum: sudo yum install ansible -y For Ubuntu-based systems, you can install Ansible from the PPA: ``` `````` sudo apt-get install software-properties-common -y sudo apt-add-repository ppa:ansible/ansible sudo apt-get update sudo apt-get install ansible -y ``` If you are using macOS, the recommended installation is done via Python PIP: sudo pip install ansible See the [Ansible installation documentation](http://docs.ansible.com/ansible/intro_installation.html) for other distributions. ## Working with Ansible Inventory Ansible uses an INI-style file called an *Inventory* to track which servers it may manage. By default this file is located in **/etc/ansible/hosts**. In this article, I will use the Ansible Inventory shown in Example 2 to perform actions against the desired hosts (which has been paired down for brevity): #### Example 2: Ansible hosts file ``` `````` [arch] nextcloud prometheus desktop1 desktop2 vm-host15 [fedora] netflix [centos] conan confluence 7-repo vm-server1 gitlab [ubuntu] trusty-mirror nwn kids-tv media-centre nas [satellite] satellite [ocp] lb00 ocp_dns master01 app01 infra01 ``` Each group, which is denoted via square brackets and a group name (such as **[group1]**), is an arbitrary group name that can be applied to a set of servers. A server can exist in multiple groups without issue. In this case, I have groups for operating systems (*arch*, *ubuntu*, *centos*, *fedora*), as well as server function (*ocp*, *satellite*). The Ansible host file can handle significantly more advanced functionality than what I am using. For more information, see [the Inventory documentation](http://docs.ansible.com/ansible/intro_inventory.html). ## Running ad hoc commands After you have copied your SSH keys to all the servers in your inventory, you are ready to start using Ansible. A basic Ansible function is the ability to run ad hoc commands. The syntax is: ansible-a "some command" For example, if you want to update all of the CentOS servers, you might run: ansible centos -a 'yum update -y' *Note: Having group names based on the operating system of the server is not necessary. As I will discuss, Ansible Facts can be used to gather this information; however, issuing ad hoc commands becomes more complex when trying to use Facts, and so for convenience I recommend creating a few groups based on operating system if you manage a heterogeneous environment.* This will loop over each of the servers in the group **centos** and install all of the updates. A more useful ad hoc command would be the Ansible **ping** module, which is used to verify that a server is ready to receive commands: ansible all -m ping This will result in Ansible attempting to log in via SSH to all of the servers in your inventory. Truncated output for the **ping** command can be seen in Example 3. #### Example 3: Ansible ping command output ``` `````` nwn | SUCCESS => { "changed": false, "ping": "pong" } media-centre | SUCCESS => { "changed": false, "ping": "pong" } nas | SUCCESS => { "changed": false, "ping": "pong" } kids-tv | SUCCESS => { "changed": false, "ping": "pong" } ... ``` The ability to run ad hoc commands is useful for quick tasks, but what if you want to be able to run the same tasks later, in a repeatable fashion? For that Ansible implements [playbooks](http://docs.ansible.com/ansible/playbooks.html). ## Ansible playbooks for complex tasks An Ansible playbook is a YAML file that contains all the instructions that Ansible should complete during a run. For the purposes of this exercise, I will not get into more advanced topics such as Roles and Templates. If you are interested in learning more, [the documentation](http://docs.ansible.com/ansible/playbooks_roles.html) is a great place to start. In the previous section, I encouraged you to use the **ssh-copy-id** command to propagate your SSH keys; however, this article is focused on how to accomplish tasks in a consistent, repeatable manner. Example 4 demonstrates one method for ensuring, in an idempotent fashion, that an SSH key exists on the target hosts. #### Example 4: Ansible playbook "push_ssh_keys.yaml" ``` `````` --- - hosts: all gather_facts: false vars: ssh_key: '/root/playbooks/files/laptop_ssh_key' tasks: - name: copy ssh key authorized_key: key: "{{ lookup('file', ssh_key) }}" user: root ``` In the playbook from Example 4, all of the critical sections are highlighted. The **- hosts:** line indicates which host groups the playbook should evaluate. In this particular case, it is going to examine all of the hosts from our *Inventory*. The **gather_facts:** line instructs Ansible to attempt to find out detailed information about each host. I will examine this in more detail later. For now, **gather_facts** is set to **false** to save time. The **vars:** section, as one might imagine, is used to define variables that can be used throughout the playbook. In such a short playbook as the one in Example 4, it is more a convenience rather than a necessity. Finally the main section is indicated by **tasks:**. This is where most of the instructions are located. Each task should have a **- name:**. This is what is displayed as Ansible is carrying out a **run**, or playbook execution. The **authorized_key:** heading is the name of the Ansible Module that the playbook is using. Information about Ansible Modules can be accessed on the command line via **ansible-doc -a**; however it may be more convenient to view the [documentation](http://docs.ansible.com/ansible/modules_by_category.html) in a web browser. The [authorized_key module](http://docs.ansible.com/ansible/authorized_key_module.html) has plenty of great examples to get started with. To run the playbook in Example 4, simply use the **ansible-playbook** command: ansible-playbook push_ssh_keys.yaml If this is the first time adding an SSH key to the box, SSH will prompt you for a password for the root user. Now that your servers have SSH keys propagated its time to do something a little more interesting. ## Ansible and gathering facts Ansible has the ability to gather all kinds of facts about the target system. This can consume a significant amount of time if you have a large number of hosts. In my experience, it can take 1 to 2 seconds per host, and possibly longer; however, there are benefits to fact gathering. Consider the following playbook used for turning off the ability for users to log in with a password as the root user: #### Example 5: Lock down root SSH account ``` `````` --- - hosts: all gather_facts: true vars: tasks: - name: Enabling ssh-key only root access lineinfile: dest: /etc/ssh/sshd_config regexp: '^PermitRootLogin' line: 'PermitRootLogin without-password' notify: - restart_sshd - restart_ssh handlers: - name: restart_sshd service: name: sshd state: restarted enabled: true when: ansible_distribution == 'RedHat' - name: restart_ssh service: name: ssh state: restarted enabled: true when: ansible_distribution == 'Debian' ``` In Example 5 the **sshd_config** file is modified with the [conditional](http://docs.ansible.com/ansible/lineinfile_module.html) only executes if a distribution match is found. In this case Red Hat-based distributions name their SSH service different than Debian-based, which is the purpose for the conditional statement. Although there are other ways to achieve this same effect, the example helps demonstrate Ansible facts. If you want to see all of the facts that Ansible gathers by default, you can run the **setup** module on your localhost: ansible localhost -m setup |less Any fact that is discovered by Ansible can be used to base decisions upon much the same way the **vars:** section that was shown in Example 4 is used. The difference is Ansible facts are considered to be **built in** variables, and thus do not have to be defined by the administrator. ## Next steps Now you have the tools to start investigating Ansible and creating your own playbooks. Ansible is a tool that has so much depth, complexity, and flexibility that it would be impossible to cover everything in one article. This article should be enough to pique your interest and inspire you to explore the possibilities Ansible provides. In my next article, I will discuss the **Copy**, **systemd**, **service**, **apt**, **yum**, **virt**, and **user** modules. We can combine these to create update and installation playbooks, and to create a basic Git server to store all of the playbooks that may get created. ## 6 Comments
9,332
如何在 Arch Linux 中设置日语环境
https://www.ostechnix.com/setup-japanese-language-environment-arch-linux/
2018-02-12T10:36:00
[ "日语", "Arch" ]
https://linux.cn/article-9332-1.html
![](/data/attachment/album/201802/10/223727juvyib53zbvlllo3.jpg) 在本教程中,我们将讨论如何在 Arch Linux 中设置日语环境。在其他类 Unix 操作系统中,设置日文布局并不是什么大不了的事情。你可以从设置中轻松选择日文键盘布局。然而,在 Arch Linux 下有点困难,ArchWiki 中没有合适的文档。如果你正在使用 Arch Linux 和/或其衍生产品如 Antergos、Manajaro Linux,请遵循本指南以在 Arch Linux 及其衍生系统中使用日语。 ### 在 Arch Linux 中设置日语环境 首先,为了正确查看日语字符,先安装必要的日语字体: ``` sudo pacman -S adobe-source-han-sans-jp-fonts otf-ipafont pacaur -S ttf-monapo ``` 如果你尚未安装 `pacaur`,请参阅[此链接](https://www.ostechnix.com/install-pacaur-arch-linux/)。 确保你在 `/etc/locale.gen` 中注释掉了(添加 `#` 注释)下面的行。 ``` #ja_JP.UTF-8 ``` 然后,安装 iBus 和 ibus-anthy。对于那些想知道原因的,iBus 是类 Unix 系统的输入法(IM)框架,而 ibus-anthy 是 iBus 的日语输入法。 ``` sudo pacman -S ibus ibus-anthy ``` 在 `~/.xprofile` 中添加以下几行(如果不存在,创建一个): ``` # Settings for Japanese input export GTK_IM_MODULE='ibus' export QT_IM_MODULE='ibus' export XMODIFIERS=@im='ibus' #Toolbar for anthy ibus-daemon -drx ``` `~/.xprofile` 允许我们在 X 用户会话开始时且在窗口管理器启动之前执行命令。 保存并关闭文件。重启 Arch Linux 系统以使更改生效。 登录到系统后,右键单击任务栏中的 iBus 图标,然后选择 “Preferences”。如果不存在,请从终端运行以下命令来启动 iBus 并打开偏好设置窗口。 ``` ibus-setup ``` 选择 “Yes” 来启动 iBus。你会看到一个像下面的页面。点击 Ok 关闭它。 ![](/data/attachment/album/201802/12/114148o1fciib9ecrh39nr.png) 现在,你将看到 iBus 偏好设置窗口。进入 “Input Method” 选项卡,然后单击 “Add” 按钮。 ![](/data/attachment/album/201802/12/114149eh9d18vpw9fcdy2d.png) 在列表中选择 “Japanese”: ![](/data/attachment/album/201802/12/114150lt5k6uh62kyy4vyd.png) 然后,选择 “Anthy” 并点击添加: ![](/data/attachment/album/201802/12/114151wvb5bqwibnssz5bb.png) 就是这样了。你现在将在输入法栏看到 “Japanese - Anthy”: ![](/data/attachment/album/201802/12/114152dzx4eouep04e0ec8.png) 根据你的需求在偏好设置中更改日语输入法的选项(点击 “Japanese-Anthy” -> “Preferences”)。 ![](/data/attachment/album/201802/12/114153olzeexw2ul4dgbae.png) 你还可以在键盘绑定中编辑默认的快捷键。完成所有更改后,点击应用并确定。就是这样。从任务栏中的 iBus 图标中选择日语,或者按下 `SUPER + 空格键”(LCTT 译注:SUPER 键通常为`Command`或`Window` 键)来在日语和英语(或者系统中的其他默认语言)之间切换。你可以从 iBus 首选项窗口更改键盘快捷键。 现在你知道如何在 Arch Linux 及其衍生版中使用日语了。如果你发现我们的指南很有用,那么请您在社交、专业网络上分享,并支持我们。 --- via: <https://www.ostechnix.com/setup-japanese-language-environment-arch-linux/> 作者:[SK](https://www.ostechnix.com) 译者:[geekpi](https://github.com/geekpi) 校对:[Locez](https://github.com/locez) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,333
使用 TLS 加密保护 VNC 服务器的简单指南
http://linuxtechlab.com/secure-vnc-server-tls-encryption/
2018-02-13T09:45:00
[ "VNC", "TLS" ]
https://linux.cn/article-9333-1.html
![](/data/attachment/album/201802/10/225325rqxd5dk3334zi2hx.jpg) 在本教程中,我们将学习安装 VNC 服务器并使用 TLS 加密保护 VNC 会话。 此方法已经在 CentOS 6&7 上测试过了,但是也可以在其它的版本/操作系统上运行(RHEL、Scientific Linux 等)。 **(推荐阅读:[保护 SSH 会话终极指南](http://linuxtechlab.com/ultimate-guide-to-securing-ssh-sessions/))** ### 安装 VNC 服务器 在机器上安装 VNC 服务器之前,请确保我们有一个可用的 GUI(图形用户界面)。如果机器上还没有安装 GUI,我们可以通过执行以下命令来安装: ``` yum groupinstall "GNOME Desktop" ``` 现在我们将 tigervnc 作为我们的 VNC 服务器,运行下面的命令运行: ``` # yum install tigervnc-server ``` 安装完成后,我们将创建一个新的用户访问服务器: ``` # useradd vncuser ``` 并使用以下命令为其分配访问 VNC 的密码: ``` # vncpasswd vncuser ``` 我们在 CentOS 6&7 上配置会有一点改变,我们首先看 CentOS 6 的配置。 #### CentOS 6 现在我们需要编辑 VNC 配置文件: ``` # vim /etc/sysconfig/vncservers ``` 并添加下面这几行: ``` [ …] VNCSERVERS= "1:vncuser" VNCSERVERARGS[1]= "-geometry 1024×768″ ``` 保存文件并退出。接下来重启 vnc 服务使改动生效: ``` # service vncserver restart ``` 并在启动时启用它: ``` # chkconfig vncserver on ``` #### CentOS 7 在 CentOS 7 上,`/etc/sysconfig/vncservers` 已经改为 `/lib/systemd/system/[email protected]`。我们将使用这个配置文件作为参考,所以创建一个文件的副本, ``` # cp /lib/systemd/system/[email protected] /etc/systemd/system/vncserver@:1.service ``` 接下来,我们将编辑文件以包含我们创建的用户: ``` # vim /etc/systemd/system/vncserver@:1.service ``` 编辑下面 2 行中的用户: ``` ExecStart=/sbin/runuser -l vncuser -c "/usr/bin/vncserver %i" PIDFile=/home/vncuser/.vnc/%H%i.pid ``` 保存文件并退出。接下来重启服务并在启动时启用它: ``` # systemctl restart vncserver@:1.service # systemctl enable vncserver@:1.service ``` 现在我们已经设置好了 VNC 服务器,并且可以使用 VNC 服务器的 IP 地址从客户机连接到它。但是,在此之前,我们将使用 TLS 加密保护我们的连接。 ### 保护 VNC 会话 要保护 VNC 会话,我们将首先配置加密方法。我们将使用 TLS 加密,但也可以使用 SSL 加密。执行以下命令在 VNC 服务器上使用 TLS 加密: ``` # vncserver -SecurityTypes=VeNCrypt,TLSVnc ``` 你将被要求输入密码来访问 VNC(如果使用其他用户,而不是上述用户)。 ![secure vnc server](/data/attachment/album/201802/10/225350ru74izoba4xb3fru.png) 现在,我们可以使用客户机上的 VNC 浏览器访问服务器,使用以下命令以安全连接启动 vnc 浏览器: ``` # vncviewer -SecurityTypes=VeNCrypt,TLSVnc 192.168.1.45:1 ``` 这里,192.168.1.45 是 VNC 服务器的 IP 地址。 ![secure vnc server](/data/attachment/album/201802/10/225355u07ozq7lehqaolj6.png) 输入密码,我们可以远程访问服务器,并且也是 TLS 加密的。 这篇教程就完了,欢迎随时使用下面的评论栏提交你的建议或疑问。 --- via: <http://linuxtechlab.com/secure-vnc-server-tls-encryption/> 作者:[Shusain](http://linuxtechlab.com/author/shsuain/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,335
TensorFlow 的简单例子
https://www.codementor.io/likegeeks/define-and-use-tensors-using-simple-tensorflow-examples-ggdgwoy4u
2018-02-11T23:12:08
[ "TensorFlow" ]
https://linux.cn/article-9335-1.html
![](/data/attachment/album/201802/11/231211xv52948zv3sf242f.png) 在本文中,我们将看一些 TensorFlow 的例子,并从中感受到在定义<ruby> 张量 <rt> tensor </rt></ruby>和使用张量做数学计算方面有多么容易,我还会举些别的机器学习相关的例子。 ### TensorFlow 是什么? TensorFlow 是 Google 为了解决复杂的数学计算耗时过久的问题而开发的一个库。 事实上,TensorFlow 能干许多事。比如: * 求解复杂数学表达式 * 机器学习技术。你往其中输入一组数据样本用以训练,接着给出另一组数据样本基于训练的数据而预测结果。这就是人工智能了! * 支持 GPU 。你可以使用 GPU(图像处理单元)替代 CPU 以更快的运算。TensorFlow 有两个版本: CPU 版本和 GPU 版本。 开始写例子前,需要了解一些基本知识。 ### 什么是张量? <ruby> 张量 <rt> tensor </rt></ruby>是 TensorFlow 使用的主要的数据块,它类似于变量,TensorFlow 使用它来处理数据。张量拥有维度和类型的属性。 维度指张量的行和列数,读到后面你就知道了,我们可以定义一维张量、二维张量和三维张量。 类型指张量元素的数据类型。 ### 定义一维张量 可以这样来定义一个张量:创建一个 NumPy 数组(LCTT 译注:NumPy 系统是 Python 的一种开源数字扩展,包含一个强大的 N 维数组对象 Array,用来存储和处理大型矩阵 )或者一个 [Python 列表](https://likegeeks.com/python-list-functions/) ,然后使用 `tf_convert_to_tensor` 函数将其转化成张量。 可以像下面这样,使用 NumPy 创建一个数组: ``` import numpy as np arr = np.array([1, 5.5, 3, 15, 20]) arr = np.array([1, 5.5, 3, 15, 20]) ``` 运行结果显示了这个数组的维度和形状。 ``` import numpy as np arr = np.array([1, 5.5, 3, 15, 20]) print(arr) print(arr.ndim) print(arr.shape) print(arr.dtype) ``` 它和 Python 列表很像,但是在这里,元素之间没有逗号。 现在使用 `tf_convert_to_tensor` 函数把这个数组转化为张量。 ``` import numpy as np import tensorflow as tf arr = np.array([1, 5.5, 3, 15, 20]) tensor = tf.convert_to_tensor(arr,tf.float64) print(tensor) ``` 这次的运行结果显示了张量具体的含义,但是不会展示出张量元素。 要想看到张量元素,需要像下面这样,运行一个会话: ``` import numpy as np import tensorflow as tf arr = np.array([1, 5.5, 3, 15, 20]) tensor = tf.convert_to_tensor(arr,tf.float64) sess = tf.Session() print(sess.run(tensor)) print(sess.run(tensor[1])) ``` ### 定义二维张量 定义二维张量,其方法和定义一维张量是一样的,但要这样来定义数组: ``` arr = np.array([(1, 5.5, 3, 15, 20),(10, 20, 30, 40, 50), (60, 70, 80, 90, 100)]) ``` 接着转化为张量: ``` import numpy as np import tensorflow as tf arr = np.array([(1, 5.5, 3, 15, 20),(10, 20, 30, 40, 50), (60, 70, 80, 90, 100)]) tensor = tf.convert_to_tensor(arr) sess = tf.Session() print(sess.run(tensor)) ``` 现在你应该知道怎么定义张量了,那么,怎么在张量之间跑数学运算呢? ### 在张量上进行数学运算 假设我们有以下两个数组: ``` arr1 = np.array([(1,2,3),(4,5,6)]) arr2 = np.array([(7,8,9),(10,11,12)]) ``` 利用 TenserFlow ,你能做许多数学运算。现在我们需要对这两个数组求和。 使用加法函数来求和: ``` import numpy as np import tensorflow as tf arr1 = np.array([(1,2,3),(4,5,6)]) arr2 = np.array([(7,8,9),(10,11,12)]) arr3 = tf.add(arr1,arr2) sess = tf.Session() tensor = sess.run(arr3) print(tensor) ``` 也可以把数组相乘: ``` import numpy as np import tensorflow as tf arr1 = np.array([(1,2,3),(4,5,6)]) arr2 = np.array([(7,8,9),(10,11,12)]) arr3 = tf.multiply(arr1,arr2) sess = tf.Session() tensor = sess.run(arr3) print(tensor) ``` 现在你知道了吧。 三维张量 ---- 我们已经知道了怎么使用一维张量和二维张量,现在,来看一下三维张量吧,不过这次我们不用数字了,而是用一张 RGB 图片。在这张图片上,每一块像素都由 x、y、z 组合表示。 这些组合形成了图片的宽度、高度以及颜色深度。 首先使用 matplotlib 库导入一张图片。如果你的系统中没有 matplotlib ,可以 [使用 pip](https://likegeeks.com/import-create-install-reload-alias-python-modules/#Install-Python-Modules-Using-pip)来安装它。 将图片放在 Python 文件的同一目录下,接着使用 matplotlib 导入图片: ``` import matplotlib.image as img myfile = "likegeeks.png" myimage = img.imread(myfile) print(myimage.ndim) print(myimage.shape) ``` 从运行结果中,你应该能看到,这张三维图片的宽为 150 、高为 150 、颜色深度为 3 。 你还可以查看这张图片: ``` import matplotlib.image as img import matplotlib.pyplot as plot myfile = "likegeeks.png" myimage = img.imread(myfile) plot.imshow(myimage) plot.show() ``` 真酷! 那怎么使用 TensorFlow 处理图片呢?超级容易。 ### 使用 TensorFlow 生成或裁剪图片 首先,向一个占位符赋值: ``` myimage = tf.placeholder("int32",[None,None,3]) ``` 使用裁剪操作来裁剪图像: ``` cropped = tf.slice(myimage,[10,0,0],[16,-1,-1]) ``` 最后,运行这个会话: ``` result = sess.run(cropped, feed\_dict={slice: myimage}) ``` 然后,你就能看到使用 matplotlib 处理过的图像了。 这是整段代码: ``` import tensorflow as tf import matplotlib.image as img import matplotlib.pyplot as plot myfile = "likegeeks.png" myimage = img.imread(myfile) slice = tf.placeholder("int32",[None,None,3]) cropped = tf.slice(myimage,[10,0,0],[16,-1,-1]) sess = tf.Session() result = sess.run(cropped, feed_dict={slice: myimage}) plot.imshow(result) plot.show() ``` 是不是很神奇? ### 使用 TensorFlow 改变图像 在本例中,我们会使用 TensorFlow 做一下简单的转换。 首先,指定待处理的图像,并初始化 TensorFlow 变量值: ``` myfile = "likegeeks.png" myimage = img.imread(myfile) image = tf.Variable(myimage,name='image') vars = tf.global_variables_initializer() ``` 然后调用 transpose 函数转换,这个函数用来翻转输入网格的 0 轴和 1 轴。 ``` sess = tf.Session() flipped = tf.transpose(image, perm=[1,0,2]) sess.run(vars) result=sess.run(flipped) ``` 接着你就能看到使用 matplotlib 处理过的图像了。 ``` import tensorflow as tf import matplotlib.image as img import matplotlib.pyplot as plot myfile = "likegeeks.png" myimage = img.imread(myfile) image = tf.Variable(myimage,name='image') vars = tf.global_variables_initializer() sess = tf.Session() flipped = tf.transpose(image, perm=[1,0,2]) sess.run(vars) result=sess.run(flipped) plot.imshow(result) plot.show() ``` 以上例子都向你表明了使用 TensorFlow 有多么容易。 --- via: <https://www.codementor.io/likegeeks/define-and-use-tensors-using-simple-tensorflow-examples-ggdgwoy4u> 作者:[LikeGeeks](https://www.codementor.io/likegeeks) 译者:[ghsgz](https://github.com/ghsgz) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
202
Accepted
null
9,336
通过案例学习 xfs 文件系统相关命令
https://kerneltalks.com/commands/xfs-file-system-commands-with-examples/
2018-02-11T23:23:02
[ "xfs" ]
https://linux.cn/article-9336-1.html
![Learn xfs commands with examples](/data/attachment/album/201802/11/232306zk2462tz72sgl77l.png) 在我们另一篇文章中,我带您领略了一下[什么是 xfs,xfs 的相关特性等内容](https://kerneltalks.com/disk-management/xfs-filesystem-in-linux/)。本文我们来看一些常用的 xfs 管理命令。我们将会通过几个例子来讲解如何创建 xfs 文件系统,如何对 xfs 文件系统进行扩容,如何检测并修复 xfs 文件系统。 ### 创建 XFS 文件系统 `mkfs.xfs` 命令用来创建 xfs 文件系统。无需任何特别的参数,其输出如下: ``` root@kerneltalks # mkfs.xfs /dev/xvdf meta-data=/dev/xvdf isize=512 agcount=4, agsize=1310720 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0, sparse=0 data = bsize=4096 blocks=5242880, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal log bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 ``` > > 注意:一旦 XFS 文件系统创建完毕就不能在缩容而只能进行扩容了。 > > > ### 调整 XFS 文件系统容量 你只能对 XFS 进行扩容而不能缩容。我们使用 `xfs_growfs` 来进行扩容。你需要使用 `-D` 参数指定挂载点的新容量。`-D` 接受一个数字的参数,指定文件系统块的数量。若你没有提供 `-D` 参数,则 `xfs_growfs` 会将文件系统扩到最大。 ``` root@kerneltalks # xfs_growfs /dev/xvdf -D 256 meta-data=/dev/xvdf isize=512 agcount=4, agsize=720896 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0 spinodes=0 data = bsize=4096 blocks=2883584, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 data size 256 too small, old size is 2883584 ``` 观察上面的输出中的最后一行。由于我分配的容量要小于现在的容量。它告诉你不能缩减 XFS 文件系统。你只能对它进行扩展。 ``` root@kerneltalks # xfs_growfs /dev/xvdf -D 2883840 meta-data=/dev/xvdf isize=512 agcount=4, agsize=720896 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0 spinodes=0 data = bsize=4096 blocks=2883584, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 data blocks changed from 2883584 to 2883840 ``` 现在我多分配了 1GB 的空间,而且也成功地扩增了容量。 **1GB 块的计算方式:** 当前文件系统 bsize 为 4096,意思是块的大小为 4MB。我们需要 1GB,也就是 256 个块。因此在当前块数,2883584 上加上 256 得到 2883840。因此我为 `-D` 传递参数 2883840。 ### 修复 XFS 文件系统 可以使用 `xfs_repair` 命令进行文件系统一致性检查和修复。使用 `-n` 参数则并不对文件系统做出什么实质性的修改。它只会搜索并报告要做哪些修改。若不带 `-n` 参数,则会修改文件系统以保证文件系统的纯净。 请注意,在检查之前,你需要先卸载 XFS 文件系统。否则会报错。 ``` root@kerneltalks # xfs_repair -n /dev/xvdf xfs_repair: /dev/xvdf contains a mounted filesystem xfs_repair: /dev/xvdf contains a mounted and writable filesystem fatal error -- couldn't initialize XFS library ``` 卸载后运行检查命令。 ``` root@kerneltalks # xfs_repair -n /dev/xvdf Phase 1 - find and verify superblock... Phase 2 - using internal log - zero log... - scan filesystem freespace and inode maps... - found root inode chunk Phase 3 - for each AG... - scan (but don't clear) agi unlinked lists... - process known inodes and perform inode discovery... - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 - process newly discovered inodes... Phase 4 - check for duplicate blocks... - setting up duplicate extent list... - check for inodes claiming duplicate blocks... - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 No modify flag set, skipping phase 5 Phase 6 - check inode connectivity... - traversing filesystem ... - traversal finished ... - moving disconnected inodes to lost+found ... Phase 7 - verify link counts... No modify flag set, skipping filesystem flush and exiting. ``` 你可以看到,命令在每个阶段都显示出了为了文件系统变得健康可能做出的修改。若你希望命令在扫描时实际应用这些修改,则不带任何参数运行命令即可。 ``` root @ kerneltalks # xfs_repair /dev/xvdf Phase 1 - find and verify superblock . . . Phase 2 - using internal log - zero log . . . - scan filesystem freespace and inode maps . . . - found root inode chunk Phase 3 - for each AG . . . - scan and clear agi unlinked lists . . . - process known inodes and perform inode discovery . . . - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 - process newly discovered inodes . . . Phase 4 - check for duplicate blocks . . . - setting up duplicate extent list . . . - check for inodes claiming duplicate blocks . . . - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 Phase 5 - rebuild AG headers and trees . . . - reset superblock . . . Phase 6 - check inode connectivity . . . - resetting contents of realtime bitmap and summary inodes - traversing filesystem . . . - traversal finished . . . - moving disconnected inodes to lost + found . . . Phase 7 - verify and correct link counts . . . done ``` 你会发现 `xfs_repair` 命令对文件系统做出了修改让其变得健康。 ### 查看 XFS 版本以及它的详细信息 查看 xfs 文件系统版本很简单。使用 `-V` 参数运行 `xfs_info` 再加上挂载点就行了。 ``` root@kerneltalks # xfs_info -V /shrikant xfs_info version 4.5.0 ``` 若要查看 XFS 文件系统的详细信息,比如想计算扩容 XFS 文件系统时要新增多少个块,需要了解块大小,块的个数等信息,则不带任何选项运行 `xfs_info` 加上挂载点。 ``` root@kerneltalks # xfs_info /shrikant meta-data=/dev/xvdf isize=512 agcount=5, agsize=720896 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0 spinodes=0 data = bsize=4096 blocks=2883840, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 ``` 则会显示 XFS 文件系统的所有详细信息,就跟创建 XFS 文件系统时显示的信息一样。 此外还有一些 XFS 文件系统管理命令可以修改并管理 XFS 的元数据。我们将在另一篇文章中来讲解。 --- via: <https://kerneltalks.com/commands/xfs-file-system-commands-with-examples/> 作者:[kerneltalks](https://kerneltalks.com) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
*Learn xfs file system commands to create, grow, repair xfs file system along with command examples. * ![](https://z5.kerneltalks.com/wp-content/uploads/2020/06/xfs-commands.png) In our other article, we walked you through [what is xfs, features of xfs, etc](https://kerneltalks.com/disk-management/xfs-filesystem-in-linux/). In this article, we will see some frequently used xfs administrative commands. We will see how to create xfs filesystem, how to grow xfs filesystem, how to repair the xfs file system, and check xfs filesystem along with command examples. ### Create XFS filesystem `mkfs.xfs` command is used to create xfs filesystem. Without any special switches, command output looks like one below – ``` root@kerneltalks # mkfs.xfs /dev/xvdf meta-data=/dev/xvdf isize=512 agcount=4, agsize=1310720 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0, sparse=0 data = bsize=4096 blocks=5242880, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal log bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 ``` Note: Once the XFS filesystem is created it can not be reduced. It can only be extended to a bigger size. ### Resize XFS file system In XFS, you can only extend the file system and can not reduce it. To grow XFS file system use `xfs_growfs` . You need to specify a new size of mount point along with `-D` switch. `-D` takes argument number as file system blocks. If you don’t supply `-D` switch, `xfs_growfs` will grow the filesystem to the maximum available limit on that device. ``` root@kerneltalks # xfs_growfs /dev/xvdf -D 256 meta-data=/dev/xvdf isize=512 agcount=4, agsize=720896 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0 spinodes=0 data = bsize=4096 blocks=2883584, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 data size 256 too small, old size is 2883584 ``` In the above output, observe the last line. Since I supplied a new size smaller than the existing size, `xfs_growfs` didn’t change the filesystem. This shows you can not reduce the XFS file system. You can only extend it. ``` root@kerneltalks # xfs_growfs /dev/xvdf -D 2883840 meta-data=/dev/xvdf isize=512 agcount=4, agsize=720896 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0 spinodes=0 data = bsize=4096 blocks=2883584, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 data blocks changed from 2883584 to 2883840 ``` Now, I supplied new size 1 GB extra and it successfully grew the file system. **1 GB blocks calculation :** The current filesystem has bsize=4096 i.e. block size of 4MB. We need 1 GB i.e. 256 blocks. So add 256 in a current number of blocks i.e. 2883584 which gives you 2883840. So I used 2883840 as an argument to `-D` switch. ### Repair XFS file system File system consistency check and repair of XFS can be performed using `xfs_repair` command. You can run the command with -n switch so that it will not modify anything on the filesystem. It will only scans and reports which modifications to be done. If you are running it without -n switch, it will modify the file system wherever necessary to make it clean. Please note that you need to un-mount the XFS filesystem before you can run checks on it. Otherwise, you will see the below error. ``` root@kerneltalks # xfs_repair -n /dev/xvdf xfs_repair: /dev/xvdf contains a mounted filesystem xfs_repair: /dev/xvdf contains a mounted and writable filesystem fatal error -- couldn't initialize XFS library ``` Once successfully un-mounting file system you can run command on it. ``` root@kerneltalks # xfs_repair -n /dev/xvdf Phase 1 - find and verify superblock... Phase 2 - using internal log - zero log... - scan filesystem freespace and inode maps... - found root inode chunk Phase 3 - for each AG... - scan (but don't clear) agi unlinked lists... - process known inodes and perform inode discovery... - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 - process newly discovered inodes... Phase 4 - check for duplicate blocks... - setting up duplicate extent list... - check for inodes claiming duplicate blocks... - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 No modify flag set, skipping phase 5 Phase 6 - check inode connectivity... - traversing filesystem ... - traversal finished ... - moving disconnected inodes to lost+found ... Phase 7 - verify link counts... No modify flag set, skipping filesystem flush and exiting. ``` In the above output you can observe, in each phase command shows possible modification which can be done to make the file system healthy. If you want the command to do that modification during the scan then run the command without any switch. ``` root@kerneltalks # xfs_repair /dev/xvdf Phase 1 - find and verify superblock... Phase 2 - using internal log - zero log... - scan filesystem freespace and inode maps... - found root inode chunk Phase 3 - for each AG... - scan and clear agi unlinked lists... - process known inodes and perform inode discovery... - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 - process newly discovered inodes... Phase 4 - check for duplicate blocks... - setting up duplicate extent list... - check for inodes claiming duplicate blocks... - agno = 0 - agno = 1 - agno = 2 - agno = 3 - agno = 4 Phase 5 - rebuild AG headers and trees... - reset superblock... Phase 6 - check inode connectivity... - resetting contents of realtime bitmap and summary inodes - traversing filesystem ... - traversal finished ... - moving disconnected inodes to lost+found ... Phase 7 - verify and correct link counts... done ``` In the above output, you can observer `xfs_repair` command is executing possible filesystem modification as well to make it healthy. ### Check XFS version and details Checking the xfs file system requires it to un-mount. Run `xfs_db` command on its device path and once you entered `xfs_db` prompt, run `version` command. `xfs_db` command normally used for examining the XFS file system. version command used to enable features in the file system. Without any argument, the current version and feature bits are printed ``` root@kerneltalks # xfs_db /dev/xvdf1 xfs_db: /dev/xvdf1 contains a mounted filesystem fatal error -- couldn't initialize XFS library root@kerneltalks # umount /shrikant root@kerneltalks # xfs_db /dev/xvdf1 xfs_db> version versionnum [0xb4a5+0x18a] = V5,NLINK,DIRV2,ALIGN,LOGV2,EXTFLG,MOREBITS,ATTR2,LAZYSBCOUNT,PROJID32BIT,CRC,FTYPE xfs_db> quit ``` To view details of the XFS file system like block size and number of blocks which helps you in calculating new block number for growing XFS file system, use `xfs_info` without any switch. ``` root@kerneltalks # xfs_info /shrikant meta-data=/dev/xvdf isize=512 agcount=5, agsize=720896 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=0 spinodes=0 data = bsize=4096 blocks=2883840, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 ``` It displays all details as it shows while creating XFS file system There are other XFS file system management commands which alter and manages its metadata. We will cover them in another article. How do I deal with bad sectors using xfs? Using xfs_repair Hi, Very nice and useful article @author, it is not possible find version of XFS filesystem via xfs_info -V /shrikant This would only print version of the program xfs_info, which depends on which version of xfsprogs package is installed. To find version of given filesystem, use xfs_db /skrikant and issue command “version”. Thanks Ján Lalinský. Correction made. Correction, use xfs_db on device path, i.e. xfs_db /dev/path_to_xfs_partition is it possible to make changes(new) partitions in aws ec2 instance? cause when I tried to make changes in one of them ,they (ec2 instances ) are getting unavailable after rebooting them.what is the solution for it
9,337
如何更改 Linux 控制台上的字体
https://www.linux.com/learn/intro-to-linux/2018/1/how-change-your-linux-console-fonts
2018-02-14T09:12:00
[ "终端", "字体" ]
https://linux.cn/article-9337-1.html
![](/data/attachment/album/201802/12/001611jt67znuetzupntja.jpg) 我尝试尽可能的保持心灵祥和,然而总有一些事情让我意难平,比如控制台字体太小了。记住我的话,朋友,有一天你的眼睛会退化,无法再看清你编码时用的那些细小字体,到那时你就后悔莫及了。 幸好,Linux 死忠们,你可以更改控制台的字体。按照 Linux 一贯的尿性,不断变化的 Linux 环境使得这个问题变得不太简单明了,而 Linux 上也没有字体管理这么个东西,这使得我们很容易就被搞晕了。本文,我将会向你展示,我找到的更改字体的最简方法。 ### Linux 控制台是个什么鬼? 首先让我们来澄清一下我们说的到底是个什么东西。当我提到 Linux 控制台,我指的是 TTY1-6,即你从图形环境用 `Ctrl-Alt-F1` 到 `F6` 切换到的虚拟终端。按下 `Ctrl+Alt+F7` 会切回图形环境。(不过这些热键已经不再通用,你的 Linux 发行版可能有不同的键映射。你的 TTY 的数量也可能不同,你图形环境会话也可能不在 `F7`。比如,Fedora 的默认图形会话是 `F2`,它只有一个额外的终端在 `F1`。) 我觉得能同时拥有 X 会话和终端会话实在是太酷了。 Linux 控制台是内核的一部分,而且并不运行在 X 会话中。它和你在没有图形环境的<ruby> 无头 <rt> headless </rt></ruby>服务器中用的控制台是一样的。我称呼在图形会话中的 X 终端为终端,而将控制台和 X 终端统称为终端模拟器。 但这还没完。Linux 终端从早期的 ANSI 时代开始已经经历了长久的发展,多亏了 Linux framebuffer,它现在支持 Unicode 并且对图形也有了有限的一些支持。而且出现了很多在控制台下运行的[多媒体应用](/article-9320-1.html),这些我们在以后的文章中会提到。 ### 控制台截屏 获取控制台截屏的最简单方法是让控制台跑在虚拟机内部。然后你可以在宿主系统上使用中意的截屏软件来抓取。不过借助 [fbcat](http://jwilk.net/software/fbcat) 和 [fbgrab](https://github.com/jwilk/fbcat/blob/master/fbgrab) 你也可以直接在控制台上截屏。`fbcat` 会创建一个可移植的像素映射格式(PPM)的图像; 这是一个高度可移植的未压缩图像格式,可以在所有的操作系统上读取,当然你也可以把它转换成任何喜欢的其他格式。`fbgrab` 则是 `fbcat` 的一个封装脚本,用来生成一个 PNG 文件。很多人写过多个版本的 `fbgrab`。每个版本的选项都有限而且只能创建截取全屏。 `fbcat` 的执行需要 root 权限,而且它的输出需要重定向到文件中。你无需指定文件扩展名,只需要输入文件名就行了: ``` $ sudo fbcat > Pictures/myfile ``` 在 GIMP 中裁剪后,就得到了图 1。 ![](/data/attachment/album/201802/15/102834n6ppkp6rtt740dt7.png) *图 1 : 裁剪后查看* 如果能在左边空白处有一点填充就好了,如果有读者知道如何实现请在留言框中告诉我。 `fbgrab` 还有一些选项,你可以通过 `man fbgrab` 来查看,这些选项包括对另一个控制台进行截屏,以及延时截屏等。在下面的例子中可以看到,`fbgrab` 截屏跟 `fbcat` 截屏类似,只是你无需明确进行输出重定性了: ``` $ sudo fbgrab Pictures/myOtherfile ``` ### 查找字体 就我所知,除了查看字体存储目录 `/usr/share/consolefonts/`(Debian 等),`/lib/kbd/consolefonts/` (Fedora),`/usr/share/kbd/consolefonts` (openSUSE)外没有其他方法可以列出已安装的字体了。 ### 更改字体 可读字体不是什么新概念。我们应该尊重以前的经验!可读性是很重要的。可配置性也很重要,然而现如今却不怎么看重了。 在 Debian/Ubuntu 等系统上,可以运行 `sudo dpkg-reconfigure console-setup` 来设置控制台字体,然后在控制台运行 `setupcon` 命令来让变更生效。`setupcon` 属于 `console-setup` 软件包中的一部分。若你的 Linux 发行版中不包含该工具,可以在 [openSUSE](https://software.opensuse.org/package/console-setup) 中下载到它。 你也可以直接编辑 `/etc/default/console-setup` 文件。下面这个例子中设置字体为 32 点大小的 Terminus Bold 字体,这是我的最爱,并且严格限制控制台宽度为 80 列。 ``` ACTIVE_CONSOLES="/dev/tty[1-6]" CHARMAP="UTF-8" CODESET="guess" FONTFACE="TerminusBold" FONTSIZE="16x32" SCREEN_WIDTH="80" ``` 这里的 `FONTFACE` 和 `FONTSIZE` 的值来自于字体的文件名 `TerminusBold32x16.psf.gz`。是的,你需要反转 `FONTSIZE` 中值的顺序。计算机就是这么搞笑。然后再运行 `setupcon` 来让新配置生效。可以使用 `showconsolefont` 来查看当前所用字体的所有字符集。要查看完整的选项说明请参考 `man console-setup`。 ### Systemd Systemd 与 `console-setup` 不太一样,除了字体之外,你无需安装任何东西。你只需要编辑 `/etc/vconsole.conf` 然后重启就行了。我在 Fedora 和 openSUSE 系统中安装了一些额外的大字号的 Terminus 字体包,因为默认安装的字体最大只有 16 点而我想要的是 32 点。然后将 `/etc/vconsole.conf` 的内容修改为: ``` KEYMAP="us" FONT="ter-v32b" ``` 下周我们还将学习一些更加酷的控制台小技巧,以及一些在控制台上运行的[多媒体应用](/article-9320-1.html)。 --- via: <https://www.linux.com/learn/intro-to-linux/2018/1/how-change-your-linux-console-fonts> 作者:[Carla Schroder](https://www.linux.com/users/cschroder) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,338
使用 iftop 命令监控网络带宽
http://linuxtechlab.com/monitoring-network-bandwidth-iftop-command/
2018-02-12T16:43:41
[ "iftop" ]
https://linux.cn/article-9338-1.html
![](/data/attachment/album/201802/12/164336kzmi1m13swrwqdss.jpg) 系统管理员需要监控 IT 基础设施来确保一切正常运行。我们需要监控硬件,也就是内存、硬盘和 CPU 等的性能,我们也必须监控我们的网络。我们需要确保我们的网络不被过度使用,否则我们的程序,网站可能无法正常工作。在本教程中,我们将学习使用 `iftop`。 (**推荐阅读**:[**使用 Nagios** 进行资源监控](http://linuxtechlab.com/installing-configuring-nagios-server/)、[**用于检查系统信息的工具**](http://linuxtechlab.com/commands-system-hardware-info/) 、[**要监控的重要日志**](http://linuxtechlab.com/important-logs-monitor-identify-issues/) ) `iftop` 是网络监控工具,它提供实时带宽监控。 `iftop` 测量进出各个套接字连接的总数据量,即它捕获通过网络适配器收到或发出的数据包,然后将这些数据相加以得到使用的带宽。 ### 在 Debian/Ubuntu 上安装 iftop 存在于 Debian/Ubuntu 的默认仓库中,可以使用下面的命令安装: ``` $ sudo apt-get install iftop ``` ### 使用 yum 在 RHEL/Centos 上安装 要在 CentOS 或 RHEL 上安装 iftop,我们需要启用 EPEL 仓库。要启用仓库,请在终端上运行以下命令: **RHEL/CentOS 7:** ``` $ rpm -Uvh https://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-10.noarch.rpm ``` **RHEL/CentOS 6(64 位):** ``` $ rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm ``` **RHEL/CentOS 6 (32 位):** ``` $ rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm ``` EPEL 仓库安装完成后,我们可以用下面的命令安装 `iftop`: ``` $ yum install iftop ``` 这将在你的系统上安装 `iftop`。我们现在将用它来监控我们的网络。 ### 使用 iftop 可以打开终端窗口,并输入下面的命令使用 `iftop`: ``` $ iftop ``` ![network monitoring](/data/attachment/album/201802/12/164344svqhfq5ljszplcqd.jpg) 现在你将看到计算机上发生的网络活动。你也可以使用: ``` $ iftop -n ``` 这将在屏幕上显示网络信息,但使用 `-n`,则不会显示与 IP 地址相关的名称,只会显示 IP 地址。这个选项能节省一些将 IP 地址解析为名称的带宽。 我们也可以看到 `iftop` 可以使用的所有命令。运行 `iftop` 后,按下键盘上的 `h` 查看 `iftop` 可以使用的所有命令。 ![network monitoring](/data/attachment/album/201802/12/164345bgclbuenzk6nlgbt.jpg) 要监控特定的网络接口,我们可以在 `iftop` 后加上接口名: ``` $ iftop -I enp0s3 ``` 如上所述,你可以使用帮助来查看 `iftop` 可以使用的更多选项。但是这些提到的例子只是可能只是监控网络。 --- via: <http://linuxtechlab.com/monitoring-network-bandwidth-iftop-command/> 作者:[SHUSAIN](http://linuxtechlab.com/author/shsuain/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,339
开源软件二十年 —— 过去,现在,未来
https://opensource.com/article/18/2/open-source-20-years-and-counting
2018-02-12T17:18:48
[ "开源" ]
/article-9339-1.html
> > 谨以此文纪念 “<ruby> 开源软件 <rt> open source software </rt></ruby>” 这个名词的二十周年纪念日,开源软件是怎么占有软件的主导地位的?以后会如何发展? > > > ![Open source software: 20 years and counting](/data/attachment/album/201802/12/171853octilrlvccr6tbff.png "Open source software: 20 years and counting") 二十年以前,在 1998 年 2 月,“<ruby> 开源 <rt> open source </rt></ruby>” 这个词汇第一次出现在“软件”这一名词之前。不久之后,<ruby> 开源的定义 <rt> Open Source Definition </rt></ruby>(OSD) 这一文档被创建,并成为了撒播 <ruby> 开放源代码促进会 <rt> Open Source Initiative </rt></ruby>(OSI)的种子。正如 OSD 的作者 [Bruce Perens 所说](https://perens.com/2017/09/26/on-usage-of-the-phrase-open-source/): > > “开源”是这场宣传自由软件的既有概念到商业软件,并将许可证化为一系列规则的运动的正式名称。 > > > 二十年后,我们能看到这一运动是非常成功的,甚至超出了当时参与这一活动的任何人的想象。 如今,开源软件无处不在。它是互联网和网络的基础。它为我们所有使用的电脑和移动设备,以及它们所连接的网络提供动力。没有它,云计算和新兴的物联网将不可能发展,甚至不可能出现。它使新的业务方式可以被测试和验证,还可以让像谷歌和 Facebook 这样的大公司在已有的基础之上继续攀登。 如任何人类的造物一样,它也有黑暗的一面。它也让反乌托邦的监视和必然导致的专制控制的出现成为了可能。它为犯罪分子提供了欺骗受害者的新的途径,还让匿名且大规模的欺凌得以存在。它让有破环性的狂热分子可以暗中组织而不会感到有何不便。这些都是开源的能力之下的黑暗投影。所有的人类工具都是如此,既可以养育人类,亦可以有害于人类。我们需要帮助下一代,让他们能争取无可取代的创新。就如 [费曼所说](https://www.brainpickings.org/2013/07/19/richard-feynman-science-morality-poem/): > > 每个人都掌握着一把开启天堂之门的钥匙,但这把钥匙亦能打开地狱之门。 > > > 开源运动已经渐渐成熟。我们讨论和理解它的方式也渐渐的成熟。如果说第一个十年是拥护与非议对立的十年,那么第二个十年就是接纳和适应并存的十年。 1. 在第一个十年里面,关键问题就是商业模型 —— “我怎样才能自由的贡献代码,且从中受益?” —— 之后,还有更多的人提出了有关管理的难题—— “我怎么才能参与进来,且不受控制 ?” 2. 第一个十年的开源项目主要是替代现有的产品;而在第二个十年中,它们更多地是作为更大的解决方案的组成部分。 3. 第一个十年的项目往往由非正式的个人组织进行;而在第二个十年中,它们经常由创建于各个项目上的机构经营。 4. 第一个十年的开源开发者经常是投入于单一的项目,并经常在业余时间工作。 在第二个十年里,他们越来越多地受雇从事于一个专门的技术 —— 他们成了专业人员。 5. 尽管开源一直被认为是提升软件自由度的一种方式,但在第一个十年中,这个运动与那些更喜欢使用“<ruby> 自由软件 <rt> free software </rt></ruby>”的人产生了冲突。在第二个十年里,随着开源运动的加速发展,这个冲突基本上被忽略了。 第三个十年会带来什么? 1. *更复杂的商业模式* —— 主要的商业模式涉及到将很多开源组件整合而产生的复杂性的解决方案,特别是部署和扩展方面。 开源治理的需求将反映这一点。 2. *开源拼图* —— 开源项目将主要是一系列组件,彼此衔接构成组件堆栈。由此产生的解决方案将是开源组件的拼图。 3. *项目族* —— 越来越多的项目将由诸如 Linux Foundation 和 OpenStack 等联盟/行业协会以及 Apache 和 Software Freedom Conservancy 等机构主办。 4. *专业通才* —— 开源开发人员将越来越多地被雇来将诸多技术集成到复杂的解决方案里,这将有助于一系列的项目的开发。 5. *软件自由度降低* —— 随着新问题的出现,软件自由(将四项自由应用于用户和开发人员之间的灵活性)将越来越多地应用于识别解决方案是否适用于协作社区和独立部署人员。 2018 年,我将在全球各地的主题演讲中阐述这些内容。欢迎观看 [OSI 20 周年纪念全球巡演](https://opensource.org/node/905)! *本文最初发表于 [Meshed Insights Ltd.](https://meshedinsights.com/2017/12/21/20-years-and-counting/) , 已获转载授权,本文,以及我在 OSI 的工作,由 [Patreon patrons](https://patreon.com/webmink) 支持* ### 关于作者 Simon Phipps - 计算机工业和开源软件专家 Simon Phipps 创办了[公共软件公司](https://publicsoftware.eu/),这是一个欧洲开源项目的托管公司,以志愿者身份成为 OSI 的总裁,还是 The Document Foundation 的一名总监。 他的作品是由 [Patreon patrons](https://patreon.com/webmink) 赞助 —— 如果你想看更多的话,来做赞助人吧! 在超过 30 年的职业生涯中,他一直在参与世界领先的战略层面的开发 ... [关于 Simon Phipps](https://opensource.com/users/simonphipps) --- via: <https://opensource.com/article/18/2/open-source-20-years-and-counting> 作者:[Simon Phipps](https://opensource.com/users/simonphipps) 译者:[name1e5s](https://github.com/name1e5s) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
null
HTTPSConnectionPool(host='opensource.com', port=443): Read timed out. (read timeout=10)
null
9,340
Manjaro Gaming:当 Manjaro 的才华遇上 Linux 游戏
https://itsfoss.com/manjaro-gaming-linux/
2018-02-12T17:37:25
[ "Manjaro", "游戏" ]
https://linux.cn/article-9340-1.html
[![见见 Manjaro Gaming, 一个专门为游戏者设计的 Linux 发行版,带有 Manjaro 的所有才能。](/data/attachment/album/201802/12/173728u5gp47pg25e9gp51.jpg)](https://itsfoss.com/wp-content/uploads/2016/06/Manjaro-Gaming.jpg) [在 Linux 上玩转游戏](/article-7316-1.html)? 没错,这是非常可行的,我们正致力于为游戏人群打造一个新的 Linux 发行版。 Manjaro Gaming 是一个专门为游戏人群设计的,带有 Manjaro 所有才能的发行版。之前用过 Manjaro Linux 的人一定知道为什么这对于游戏人群来说是一个如此好的一个消息。 [Manjaro](https://manjaro.github.io/) 是一个 Linux 发行版,它基于最流行的 Linux 发行版之一 —— [Arch Linux](https://www.archlinux.org/)。 Arch Linux 因它的前沿性所带来的轻量、强大、高度定制和最新的体验而闻名于世。尽管这些都非常赞,但是也正是因为 Arch Linux 提倡这种 DIY (do it yourself)方式,导致一个主要的缺点,那就是用户想用好它,需要处理一定的技术问题。 Manjaro 把这些要求全都剥离开去,让 Arch 对新手更亲切,同时也为老手提供了 Arch 所有的高端与强大功能。总之,Manjaro 是一个用户友好型的 Linux 发行版,工作起来行云流水。 Manjaro 会成为一个强大并且极度适用于游戏的原因: * Manjaro 自动检测计算的硬件(例如,显卡) * 自动安装必要的驱动和软件(例如,显示驱动) * 预安装播放媒体文件的编码器 * 专用的软件库提供完整测试过的稳定软件包。 Manjaro Gaming 打包了 Manjaro 的所有强大特性以及各种小工具和软件包,以使得在 Linux 上做游戏即顺畅又享受。 ![Manjaro Gaming 内部](/data/attachment/album/201802/12/173729zt6gqwyyfzt6yapp.png) ### 优化 Manjaro Gaming 做了一些优化: * Manjaro Gaming 使用高度定制化的 XFCE 桌面环境,拥有一个黑暗风格主题。 * 禁用睡眠模式,防止用手柄上玩游戏或者观看一个长过场动画时计算机自动休眠。 ### 软件 维持 Manjaro 工作起来行云流水的传统,Manjaro Gaming 打包了各种开源软件包,提供游戏人群经常需要用到的功能。其中一部分软件有: * [KdenLIVE](https://kdenlive.org/):用于编辑游戏视频的视频编辑软件 * [Mumble](https://www.mumble.info):给游戏人群使用的视频聊天软件 * [OBS Studio](https://obsproject.com/):用于录制视频或在 [Twitch](https://www.twitch.tv/) 上直播游戏用的软件 * [OpenShot](http://www.openshot.org/):Linux 上强大的视频编辑器 * [PlayOnLinux](https://www.playonlinux.com):使用 [Wine](https://www.winehq.org/) 作为后端,在 Linux 上运行 Windows 游戏的软件 * [Shutter](http://shutter-project.org/):多种功能的截图工具 ### 模拟器 Manjaro Gaming 自带很多的游戏模拟器: * [DeSmuME](http://desmume.org/):Nintendo DS 任天堂 DS 模拟器 * [Dolphin Emulator](https://dolphin-emu.org):GameCube 和 Wii 模拟器 * [DOSBox](https://www.dosbox.com/):DOS 游戏模拟器 * [FCEUX](http://www.fceux.com/):任天堂娱乐系统(NES)、 红白机(FC)和 FC 磁盘系统(FDS)模拟器 * Gens/GS:世嘉模拟器 * [PCSXR](https://pcsxr.codeplex.com):PlayStation 模拟器 * [PCSX2](http://pcsx2.net/):Playstation 2 模拟器 * [PPSSPP](http://www.ppsspp.org/):PSP 模拟器 * [Stella](http://stella.sourceforge.net/):Atari 2600 VCS (雅达利)模拟器 * [VBA-M](http://vba-m.com/):Gameboy 和 GameboyAdvance 模拟器 * [Yabause](https://yabause.org/):世嘉土星模拟器 * [ZSNES](http://www.zsnes.com/):超级任天堂模拟器 ### 其它 还有一些终端插件 —— Color、ILoveCandy 和 Screenfetch。也包括带有 Retro Conky(LCTT 译注:复古 Conky)风格的 [Conky 管理器](https://itsfoss.com/conky-gui-ubuntu-1304/)。 注意:上面提到的所有功能并没有全部包含在 Manjaro Gaming 的现行发行版中(版本 16.03)。部分功能计划将在下一版本中纳入 —— Manjaro Gaming 16.06(LCTT 译注:本文发表于 2016 年 5 月)。 ### 下载 Manjaro Gaming 16.06 将会是 Manjaro Gaming 的第一个正式版本。如果你现在就有兴趣尝试,你可以在 Sourceforge 的[项目页面](https://sourceforge.net/projects/mgame/)中下载。去那里然后下载它的 ISO 文件吧。 你觉得 Gaming Linux 发行版怎么样?想尝试吗?告诉我们! --- via: <https://itsfoss.com/manjaro-gaming-linux/> 作者:[Munif Tanjim](https://itsfoss.com/author/munif/) 译者:[XLCYun](https://github.com/XLCYun) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
[Gaming on Linux](https://itsfoss.com/linux-gaming-guide/)? Yes, that’s very much possible, and we have a dedicated new Linux distribution aiming for gamers. Manjaro Gaming is an unofficial respin of Manjaro XFCE edition designed for gamers. No matter if you’re a Manjaro user or not, with Manjaro Gaming edition, you get the goodness of Manjaro Linux and an experience tailored for gamers and streamers as well. In case you didn’t know, [Manjaro](https://manjaro.org) is a Linux distro based on one of the most popular distros — [Arch Linux](https://www.archlinux.org/). Arch Linux is widely known for its bleeding-edge nature offering a lightweight, powerful, extensively customizable and up-to-date experience. And while all those are absolutely great, the main drawback is that Arch Linux embraces the DIY (do it yourself) approach where users need to possess a certain level of technical expertise to get along with it. Manjaro strips that requirement and makes Arch accessible to newcomers, and at the same time provides all the advanced and powerful features of Arch for the experienced users as well. In short, Manjaro is a user-friendly Linux distro that works straight out of the box. The reasons why Manjaro makes a great and extremely suitable distro for gaming are: - Manjaro automatically detects computer’s hardware (e.g. Graphics cards) - Automatically installs the necessary drivers and software (e.g. Graphics drivers) - Various codecs for media files playback comes pre-installed with it - Has dedicated repositories that deliver fully tested and stable packages Manjaro Gaming is packed with all of Manjaro’s awesomeness with the addition of various tweaks and software packages dedicated to make gaming on Linux smooth and enjoyable. ![Manjaro Gaming Linux](https://itsfoss.com/content/images/wordpress/2020/09/manjaro-gaming-linux.jpg) ### Tweaks Some of the tweaks made on Manjaro Gaming are: - Manjaro Gaming uses highly customizable XFCE desktop environment with an overall dark theme. - Sleep mode is disabled for preventing computers from sleeping while playing games with GamePad or watching long cutscenes. ### Softwares Maintaining Manjaro’s tradition of working straight out of the box, Manjaro Gaming comes bundled with various Open Source software to provide often needed functionalities for gamers. Some of the software included are: : Videos editing software for editing gaming videos**KdenLIVE**: Voice chatting software for gamers**Mumble**: Software for video recording and live streaming games videos on**OBS Studio**[Twitch](https://www.twitch.tv/): Powerful video editor for Linux[OpenShot](http://www.openshot.org/): For running Windows games on Linux with**PlayOnLinux**[Wine](https://www.winehq.org/)backend: Feature-rich screenshot tool**Shutter**: For playing games from GOG.com, Origin, Uplay, and Steam**Lutris gaming** ### Emulators Manjaro Gaming comes with a long list of gaming emulators: : Nintendo DS emulator[DeSmuME](http://desmume.org/): GameCube and Wii emulator[Dolphin Emulator](https://dolphin-emu.org): DOS Games emulator**DOSBox**: Nintendo Entertainment System (NES), Famicom, and Famicom Disk System (FDS) emulator[FCEUX](http://www.fceux.com/)**Gens/GS**: Sega Mega Drive emulator: PlayStation Emulator[PCSXR](https://pcsxr.codeplex.com): Playstation 2 emulator**PCSX2**: PSP emulator**PPSSPP**: Atari 2600 VCS emulator[Stella](https://stella-emu.github.io/): Gameboy and GameboyAdvance emulator**VBA-M**: Sega Saturn Emulator**Yabause**: Super Nintendo emulator[ZSNES](http://www.zsnes.com/) #### Others There are some terminal add-ons — Color, ILoveCandy and Screenfetch. [Conky Manager](https://itsfoss.com/conky-gui-ubuntu-1304/) with Retro Conky theme is also included. ## Downloads Manjaro Gaming 18.03 is the latest version of Manjaro Gaming. If you’re interested to try it now, Manjaro Gaming 18.03 is available to download on the Sourceforge [project page](https://sourceforge.net/projects/mgame/). Go there and grab the ISO. How do you feel about this Manjaro spin as a Gaming Linux distro? Are you thinking of giving it a try? Let us know!
9,341
如何在 Linux/Unix 的 Bash 中打开或关闭 ls 命令颜色显示
https://www.cyberciti.biz/faq/how-to-turn-on-or-off-colors-in-bash/
2018-02-16T09:09:00
[ "ls" ]
https://linux.cn/article-9341-1.html
![](/data/attachment/album/201802/13/001317dzxfxxe0k6xlfxu6.jpg) 如何在 Linux 或类 Unix 操作系统上的 bash shell 中打开或关闭文件名称颜色(`ls` 命令颜色)? 大多数现代 Linux 发行版和 Unix 系统都有一个定义了文件名称颜色的别名。然后,`ls` 命令负责在屏幕上显示文件、目录和其他文件系统对象的颜色。 默认情况下,文件类型不会用颜色区分。你需要在 Linux 上将 `--color` 选项传递给 `ls` 命令。如果你正在使用基于 OS X 或 BSD 的系统,请将 `-G` 选项传递给 `ls` 命令。打开或关闭颜色的语法如下。 ### 如何关闭 ls 命令的颜色 输入以下命令: ``` $ ls --color=none ``` 或者用 `unalias` 命令删除别名: ``` $ unalias ls ``` 请注意,下面的 bash shell 别名被定义为用 `ls` 命令显示颜色。这个组合使用 [alias 命令](https://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html "See Linux/Unix alias command examples for more info")和 [grep 命令](https://www.cyberciti.biz/faq/howto-use-grep-command-in-linux-unix/ "See Linux/Unix grep command examples for more info"): ``` $ alias | grep ls ``` 示例输出: ``` alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' ``` ### 如何打开 ls 命令的颜色 使用以下任何一个命令: ``` $ ls --color=auto $ ls --color=tty ``` 如果你想要的话,[可以定义 bash shell 别名](https://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html): ``` alias ls='ls --color=auto' ``` 你可以在 `~/.bash_profile` 或 [~/.bashrc 文件](https://bash.cyberciti.biz/guide/%7E/.bashrc) 中添加或删除 `ls` 别名 。使用文本编辑器(如 vi)编辑文件: ``` $ vi ~/.bashrc ``` 追加下面的代码: ``` # my ls command aliases # alias ls = 'ls --color=auto' ``` [在 Vi/Vim 文本编辑器中保存并关闭文件即可](https://www.cyberciti.biz/faq/linux-unix-vim-save-and-quit-command/)。 ### 关于 \*BSD/macOS/Apple OS X 中 ls 命令的注意点 将 `-G` 选项传递给 `ls` 命令以在 {Free、Net、Open} BSD 或 macOS 和 Apple OS X Unix 操作系统家族上启用彩色输出: ``` $ ls -G ``` 示例输出: [![How to enable colorized output for the ls command in Mac OS X Terminal](/data/attachment/album/201802/13/001348tpyyp4f8p4qpip4x.jpg)](https://www.cyberciti.biz/faq/apple-mac-osx-terminal-color-ls-output-option/) *如何在 Mac OS X 终端中为 ls 命令启用彩色输出* ### 如何临时跳过 ls 命令彩色输出? 你可以使用以下任何一种语法[暂时禁用 bash shell 别名](https://www.cyberciti.biz/faq/bash-shell-temporarily-disable-an-alias/): ``` \ls /bin/ls command ls 'ls' ``` #### 关于作者 作者是 nixCraft 的创建者,经验丰富的系统管理员,也是 Linux 操作系统/Unix shell 脚本的培训师。他曾与全球客户以及IT、教育、国防和太空研究以及非营利部门等多个行业合作。在 [Twitter](https://twitter.com/nixcraft)、[Facebook](https://facebook.com/nixcraft)、[Google +](https://plus.google.com/+CybercitiBiz) 上关注他。 --- via: <https://www.cyberciti.biz/faq/how-to-turn-on-or-off-colors-in-bash/> 作者:[Vivek Gite](https://www.cyberciti.biz/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,342
如何为数字货币定价
https://techcrunch.com/2018/01/22/how-to-price-cryptocurrencies/
2018-02-13T00:47:57
[ "比特币", "数字货币" ]
https://linux.cn/article-9342-1.html
![](/data/attachment/album/201802/13/004800a4z6vmd529jbjmmy.jpg) 预测数字货币价格是一场愚人游戏,然而我想试试。单一数字货币价值的驱动因素目前太多,而且含糊不清,无法根据任何一点进行评估。或许新闻正报道说比特币呈上升趋势,但与此同时,有黑客攻击或是交易所 API 错误,就让比特币的价格下跌。以太坊看起来不够智能?谁知道呢,也许第二天就建立一个新的更智能的 DAO(LCTT 译注:区块链上,基于激励的经济协调机制,以代码作为表达,通过互联网进行传输,允许人们参与数字企业的风险&回报(即分配),代币创建了 DAO 参与者之间的经济链接)将吸引大量参与者。 那么,您该如何投资呢?又或是更准确的讲,您下注在哪种数字货币上呢? 理解什么时候买卖和持有数字货币,关键是使用与评估开源项目价值的相关工具。这已经一次又一次地被提及了,但是为了理解当前数字货币的快速发展,您必须回到 Linux 悄然兴起的时候。 互联网泡沫期间,Linux 出现在大众视野中。那时候,如果您想建立一个 Web 服务器,您必须将一台 Windows 服务器或者 Sun Sparc 工作站运送到一个服务器托管机房,在那里它将为传送 Pets.com(LCTT 译注:一个在线宠物商店,借着互联网繁荣的机会崛起,在互联网泡沫破裂时倒闭)的 HTML 页面而做出努力。与此同时,Linux 就像运行在微软和 Sun 公司平行路径上的货运列车一样,可以让开发人员使用日新月异的操作系统和工具集,快速、轻松地构建一次性项目。相比之下,解决方案提供商的花费比软硬件支出少得多,很快,所有科技巨头的业务由软件转向了服务提供,例如 Sun 公司。 Linux 的萌发促使整个开源市场蓬勃发展起来。但是有一个关键的问题,您无法从开源软件中赚钱。您可以提供服务,也可以销售使用开源组件的产品,但早期开源者主要是为了提升自我,而不是为了赚钱。 数字货币几乎完全遵循 Linux 的老路,但数字货币具有一定货币价值。因此,当您在为一个区块链项目工作时,您不是为了公共利益,也不是为了编写自由软件的乐趣,而是您写它的时候期望得到一大笔钱。因此,这掩盖了许多程序员的价值判断。那些给您带来了 Python、PHP、Django 和 Node.js 的人们回来了……而现在他们正在通过编程赚钱。 ### 审查代码库 今年将是代币销售和数字货币领域大清算的一年。虽然许多公司已经能够摆脱糟糕的或不可用的代码库,但我怀疑开发人员是否能让未来的公司摆脱如此云山雾罩的东西。可以肯定地说,我们可以期待[像这样详细描述 Storj 代码库不足之处的文章成为规范](https://shitcoin.com/storj-not-a-dropbox-killer-1a9f27983d70),这些评论会让许多所谓的“ICO” 们(LCTT 译注:代币首次发行融资)陷入困境。虽然规模巨大,但 ICO 的资金渠道是有限的,在某种程度上不完整的项目会被更严格的审查。 这是什么意思呢?这意味着要了解数字货币,您必须像对待创业公司那样对待它。您要看它是否有一个好团队?它是否是一个好产品?是否能运作?会有人想要使用它吗?现在评估整个数字货币的价值还为时过早,但如果我们假设代币将成为未来计算机互相支付的方式,这就让我们摆脱了许多疑问。毕竟,2000 年没有多少人知道 Apache 会在一个竞争激烈的市场上,几乎击败其他所有的 Web 服务器,或者像 Ubuntu 一样常见以至于可以随时可以搭建和拆毁它们。 理解数字货币价值的关键是忽视泡沫、炒作、恐惧、迷惑和怀疑心理,而是关注其真正的效用。您认为有一天您的手机会为另外一个手机付款,比如游戏内的额外费用吗? 您是否认为信用卡系统会在互联网出现后消失?您是否期望有一天,在生活中花费一点点钱,让自己过得更加舒适?然后,通过一切手段,购买并持有您认为将来可能会使您的生活过得更舒适的东西。如果您认为通过 TCP/IP 互联网的方式并不能够改善您的生活(或是您对其没有足够的了解),那么您可能就不会关注这些。纳斯达克总是开放的,至少在银行的营业时间。 好的,下面是我的预测。 ### 预测 以下是我在考虑加密货币的“投资”时应该考虑的事项评估。在我们开始之前,先讲下注意事项: * 数字货币不是真正的货币投资,而是投资在未来的技术。这就好比:当您购买数字货币时,我们像是在<ruby> 进取号星舰 <rt> Starship Enterprise </rt></ruby>的甲板上交换“<ruby> 星际信用 <rt> Galactic Credit </rt></ruby>”(LCTT 译注:《星球大战》电影中的一种货币)一般。 这是数字货币的唯一不可避免的未来。虽然您可以强制将数字货币附加到各种经济模式中,对其抱有乐观的态度,整个平台是技术乌托邦,并假设各种令人兴奋和不可能的事情将在未来几年来到。如果您有多余的现金,您喜欢《星球大战》,那么您就可以投资这些“黄金”。如果您的兄弟告诉您相关信息,结果您用信用卡买了比特币,那么您可能会要度过一段啃馒头的时间。 * 不要相信任何人。没有担保,除了提供不是投资建议的免责声明,而且这绝不是对任何特定数字货币的背书,甚至是普遍概念,但我们必须明白,我在这里写的任何东西都可能是错误的。事实上,任何关于数字货币的文章都可能是错误的,任何试图卖给您吹得天花乱坠的代币的人,几乎肯定是骗子。总之,每个人都是错的,每个人都想要得到您的钱,所以要非常、非常小心。 * 您也可以持有。如果您是在 18000 美元的价位买的比特币,您最好还是继续持有下去。 现在您就好像正处于帕斯卡赌注。(LCTT 译注:论述——我不知道上帝是否存在,如果他不存在,作为无神论者没有任何好处,但是如果他存在,作为无神论者我将有很大的坏处。所以,宁愿相信上帝存在)是的,也许您因为数字货币让您赔钱而生气,但也许您只是因为您的愚蠢和自大,但现在您不妨保持信仰,因为没有什么是必然的,或者您可以承认您是有点过于热切。虽然现在您被惩罚,但要相信有比特币之神在注视着您。最终您需要深吸一口气,同意这一切都相当怪异,并坚持下去。 现在回过头来评估数字货币。 **比特币** —— 预计明年的涨幅将超过目前的低点。此外,[世界各地的证券交易委员会和其他联邦机构](http://www.businessinsider.com/bitcoin-price-cryptocurrency-warning-from-sec-cftc-2018-1)也会开始以实际行动调整加密货币的买卖。现在银行开玩笑说,他们想要降低数字货币的风险。因此,比特币将成为数字黄金,成为投机者稳定,乏味但充满波动的避风港。尽管所有都不能用作真正的货币,但对于我们所需要的东西来说,这已经足够了,我们也可以期待量子计算的产品去改变最古老,最熟悉的加密货币的面貌。 **以太坊** —— 只要创造者 Vitalik Buterin 不再继续泼冷水,以太坊在价格上可以维持在上千美元。像一个懊悔的<ruby> 维克多·弗兰肯斯坦 <rt> Victor Frankenstein </rt></ruby>(LCTT 译注:来自《维克多·弗兰肯斯坦》电影的一名角色),Buterin 倾向于做出惊人的事情,然后在网上诋毁他们,这种自我鞭策在充满泡沫和谎言的空间中实际上是非常有用的。以太坊是最接近我们有用的加密货币,但它本质上仍然是分布式应用。这是一个很有用,很聪明的方法,可以很容易地进行实验,但是,没有人用新的分布式数据存储或应用程序取代旧系统。总之,这是一个非常令人兴奋的技术,但是还没有人知道该用它做什么。 ![](/data/attachment/album/201802/13/004803w1bfmgzggyng12np.png) 以太坊的价格将何去何从?它将徘徊在 1000 美元左右,今年可能高达 1500 美元,但这是一个原则性的科技项目,但却不是一个保值产品。 **竞争币**(LCTT 译注:除比特币,以太币之外的所有的数字币,亦称之为山寨币) —— 泡沫的标志之一是当普通人说“我买不起比特币,所以我买了莱特币”这样的话时。这正是我从许多人那里听到的,就好像说“我买不起汉堡,所以我买了一斤木屑,我想孩子们会吃的,对不对?”那您要自担风险。竞争币对于很多人来说是一个风险非常低游戏,就好比您根据一个算法创造出某个竞争币,在市值达到一定水平时卖出,那么您可以赚取一笔不错的利润。况且,大多数竞争币不会在一夜之间消失。 我诚实地推荐以太坊而不是竞争币,但是如果您死磕竞争币,那祝您玩得开心。 **代币** —— 这是数字货币变得有趣的地方。代币需要研究机构和高校对技术有深入的了解,才能真正的评估。我见过的许多代币都是一场赌博,价格暴涨暴跌。我不会给其命名,但是经验法则是,如果您在公开市场上买了一个代币,那么您可能已经错过了赚钱的机会。截至 2018 年 1 月,代币销售,庄家开始投资一个代币几美分,最后得到百倍的回报。虽然许多创始人谈论他们的产品的神奇之处和他们的团队的强大,但是就是为了单车变摩托,把价值 4 美分一个的代币升值为 20 美分,再升值成一美元。您将收益乘以数百万,就能看到它的吸引力了。 答案很简单:找到您喜欢的几个项目并潜藏在他们的社区中。评估团队是否有实力,并且很早就知道该如何进入。将钱投入后就当扔掉几个月或几年。但无法保证,因为代币理念太过超前,以至于无法对其评估。 您正在阅读这篇文章,是因为您希望在这错综复杂的环境下得到一个方向。没关系,我已经跟许多数字货币创始人交谈,知道现在许多人不知道的事情,并且知道合谋和肮脏交易的准则。因此,像我们这样的人,要慢慢地分批购买,就会开始明白这究竟是怎么一回事,也许会从数字货币投资中获利。当数字货币的潜力被完全发掘,我们会得到一个像 Linux 一样的时代。 --- via: <https://techcrunch.com/2018/01/22/how-to-price-cryptocurrencies/> 作者:[John Biggs](https://techcrunch.com/author/john-biggs/) 译者:[wyxplus](https://github.com/wyxplus) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Predicting cryptocurrency prices is a fool’s game, yet this fool is about to try. The drivers of a single cryptocurrency’s value are currently too varied and vague to make assessments based on any one point. News is trending up on Bitcoin? Maybe there’s a hack or an API failure that is driving it down at the same time. Ethereum looking sluggish? Who knows: Maybe someone will build a new smarter DAO tomorrow that will draw in the big spenders. So how do you invest? Or, more correctly, on which currency should you bet? The key to understanding what to buy or sell and when to hold is to use the tools associated with assessing the value of open-source projects. This has been said again and again, but to understand the current crypto boom you have to go back to the quiet rise of Linux. Linux appeared on most radars during the dot-com bubble. At that time, if you wanted to set up a web server, you had to physically ship a Windows server or Sun Sparc Station to a server farm where it would do the hard work of delivering Pets.com HTML. At the same time, Linux, like a freight train running on a parallel path to Microsoft and Sun, would consistently allow developers to build one-off projects very quickly and easily using an OS and toolset that were improving daily. In comparison, then, the massive hardware and software expenditures associated with the status quo solution providers were deeply inefficient, and very quickly all of the tech giants that made their money on software now made their money on services or, like Sun, folded. From the acorn of Linux an open-source forest bloomed. But there was one clear problem: You couldn’t make money from open source. You could consult and you could sell products that used open-source components, but early builders built primarily for the betterment of humanity and not the betterment of their bank accounts. Cryptocurrencies have followed the Linux model almost exactly, but cryptocurrencies have cash value. Therefore, when you’re working on a crypto project you’re not doing it for the common good or for the joy of writing free software. You’re writing it with the expectation of a big payout. This, therefore, clouds the value judgements of many programmers. The same folks that brought you Python, PHP, Django and Node.js are back… and now they’re programming money. ## Check the codebase This year will be the year of great reckoning in the token sale and cryptocurrency space. While many companies have been able to get away with poor or unusable codebases, I doubt developers will let future companies get away with so much smoke and mirrors. It’s safe to say we can [expect posts like this one detailing Storj’s anemic codebase to become the norm](https://shitcoin.com/storj-not-a-dropbox-killer-1a9f27983d70) and, more importantly, that these commentaries will sink many so-called ICOs. Though massive, the money trough that is flowing from ICO to ICO is finite and at some point there will be greater scrutiny paid to incomplete work. What does this mean? It means to understand cryptocurrency you have to treat it like a startup. Does it have a good team? Does it have a good product? Does the product work? Would someone want to use it? It’s far too early to assess the value of cryptocurrency as a whole, but if we assume that tokens or coins will become the way computers pay each other in the future, this lets us hand wave away a lot of doubt. After all, not many people knew in 2000 that Apache was going to beat nearly every other web server in a crowded market or that Ubuntu instances would be so common that you’d spin them up and destroy them in an instant. The key to understanding cryptocurrency pricing is to ignore the froth, hype and FUD and instead focus on true utility. Do you think that some day your phone will pay another phone for, say, an in-game perk? Do you expect the credit card system to fold in the face of an Internet of Value? Do you expect that one day you’ll move through life splashing out small bits of value in order to make yourself more comfortable? Then by all means, buy and hold or speculate on things that you think will make your life better. If you don’t expect the Internet of Value to improve your life the way the TCP/IP internet did (or you do not understand enough to hold an opinion), then you’re probably not cut out for this. NASDAQ is always open, at least during banker’s hours. Still will us? Good, here are my predictions. ## The rundown Here is my assessment of what you should look at when considering an “investment” in cryptocurrencies. There are a number of caveats we must address before we begin: - Crypto is not a monetary investment in a real currency, but an investment in a pie-in-the-sky technofuture. That’s right: When you buy crypto you’re basically assuming that we’ll all be on the deck of the Starship Enterprise exchanging them like Galactic Credits one day. This is the only inevitable future for crypto bulls. While you can force crypto into various economic models and hope for the best, the entire platform is techno-utopianist and assumes all sorts of exciting and unlikely things will come to pass in the next few years. If you have spare cash lying around and you like Star Wars, then you’re golden. If you bought bitcoin on a credit card because your cousin told you to, then you’re probably going to have a bad time. - Don’t trust anyone. There is no guarantee and, in addition to offering the disclaimer that this is not investment advice and that this is in no way an endorsement of any particular cryptocurrency or even the concept in general, we must understand that everything I write here could be wrong. In fact, everything ever written about crypto could be wrong, and anyone who is trying to sell you a token with exciting upside is almost certainly wrong. In short, everyone is wrong and everyone is out to get you, so be very, very careful. - You might as well hold. If you bought when BTC was $18,000 you’d best just hold on. Right now you’re in Pascal’s Wager territory. Yes, maybe you’re angry at crypto for screwing you, but maybe you were just stupid and you got in too high and now you might as well keep believing because nothing is certain, or you can admit that you were a bit overeager and now you’re being punished for it but that there is some sort of bitcoin god out there watching over you. Ultimately you need to take a deep breath, agree that all of this is pretty freaking weird, and hold on. Now on with the assessments. **Bitcoin** – Expect a rise over the next year that will surpass the current low. Also expect [bumps as the SEC and other federal agencies](http://www.businessinsider.com/bitcoin-price-cryptocurrency-warning-from-sec-cftc-2018-1) around the world begin regulating the buying and selling of cryptocurrencies in very real ways. Now that banks are in on the joke they’re going to want to reduce risk. Therefore, the bitcoin will become digital gold, a staid, boring and volatility proof safe haven for speculators. Although all but unusable as a real currency, it’s good enough for what we need it to do and we also can expect quantum computing hardware to change the face of the oldest and most familiar cryptocurrency. **Ethereum** – Ethereum could sustain another few thousand dollars on its price as long as Vitalik Buterin, the creator, doesn’t throw too much cold water on it. Like a remorseful Victor Frankenstein, Buterin tends to make amazing things and then denigrate them online, a sort of self-flagellation that is actually quite useful in a space full of froth and outright lies. Ethereum is the closest we’ve come to a useful cryptocurrency, but it is still the Raspberry Pi of distributed computing — it’s a useful and clever hack that makes it easy to experiment but no one has quite replaced the old systems with new distributed data stores or applications. In short, it’s a really exciting technology, but nobody knows what to do with it. Where will the price go? It will hover around $1,000 and possibly go as high as $1,500 this year, but this is a principled tech project and not a store of value. **Altcoins** – One of the signs of a bubble is when average people make statements like “I couldn’t afford a Bitcoin so I bought a Litecoin.” This is exactly what I’ve heard multiple times from multiple people and it’s akin to saying “I couldn’t buy hamburger so I bought a pound of sawdust instead. I think the kids will eat it, right?” Play at your own risk. Altcoins are a very useful low-risk play for many, and if you create an algorithm — say to sell when the asset hits a certain level — then you could make a nice profit. Further, most altcoins will not disappear overnight. I would honestly recommend playing with Ethereum instead of altcoins, but if you’re dead set on it, then by all means, enjoy. **Tokens** – This is where cryptocurrency gets interesting. Tokens require research, education and a deep understanding of technology to truly assess. Many of the tokens I’ve seen are true crapshoots and are used primarily as pump and dump vehicles. I won’t name names, but the rule of thumb is that if you’re buying a token on an open market then you’ve probably already missed out. The value of the token sale as of January 2018 is to allow crypto whales to turn a few cent per token investment into a 100X return. While many founders talk about the magic of their product and the power of their team, token sales are quite simply vehicles to turn 4 cents into 20 cents into a dollar. Multiply that by millions of tokens and you see the draw. The answer is simple: find a few projects you like and lurk in their message boards. Assess if the team is competent and figure out how to get in very, very early. Also expect your money to disappear into a rat hole in a few months or years. There are no sure things, and tokens are far too bleeding-edge a technology to assess sanely. You are reading this post because you are looking to maintain confirmation bias in a confusing space. That’s fine. I’ve spoken to enough crypto-heads to know that nobody knows anything right now and that collusion and dirty dealings are the rule of the day. Therefore, it’s up to folks like us to slowly buy surely begin to understand just what’s going on and, perhaps, profit from it. At the very least we’ll all get a new Linux of Value when we’re all done. Image: Photo by [Fabian Blank](https://unsplash.com/photos/pElSkGRA2NU?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/search/photos/cash?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
9,343
如何列出所有的 Bash Shell 内置命令
https://www.cyberciti.biz/faq/linux-unix-bash-shell-list-all-builtin-commands/
2018-02-13T10:17:00
[ "命令", "内置", "shell" ]
https://linux.cn/article-9343-1.html
![](/data/attachment/album/201802/13/012025cjjsb4449jus4u6j.jpg) 内置命令包含在 bash shell 本身里面。我该如何在 Linux / Apple OS X / \*BSD / Unix 类操作系统列出所有的内置 bash 命令,而不用去读大篇的 bash 操作说明页? shell 内置命令就是一个命令或一个函数,从 shell 中调用,它直接在 shell 中执行。 bash shell 直接执行该命令而无需调用其他程序。你可以使用 `help` 命令查看 Bash 内置命令的信息。以下是几种不同类型的内置命令。 ### 内置命令的类型 1. Bourne Shell 内置命令:内置命令继承自 Bourne Shell。 2. Bash 内置命令:特定于 Bash 的内置命令表。 3. 修改 Shell 行为:修改 shell 属性和可选行为的内置命令。 4. 特别的内置命令:由 POSIX 特别分类的内置命令。 ### 如何查看所有 bash 内置命令 有以下的命令: ``` $ help $ help | less $ help | grep read ``` 样例输出: ``` GNU bash, version 4.1.5(1)-release (x86_64-pc-linux-gnu) These shell commands are defined internally. Type `help' to see this list. Type `help name' to find out more about the function `name'. Use `info bash' to find out more about the shell in general. Use `man -k' or `info' to find out more about commands not in this list. A star (*) next to a name means that the command is disabled. job_spec [&] history [-c] [-d offset] [n] or hist> (( expression )) if COMMANDS; then COMMANDS; [ elif C> . filename [arguments] jobs [-lnprs] [jobspec ...] or jobs > : kill [-s sigspec | -n signum | -sigs> [ arg... ] let arg [arg ...] [[ expression ]] local [option] name[=value] ... alias [-p] [name[=value] ... ] logout [n] bg [job_spec ...] mapfile [-n count] [-O origin] [-s c> bind [-lpvsPVS] [-m keymap] [-f filen> popd [-n] [+N | -N] break [n] printf [-v var] format [arguments] builtin [shell-builtin [arg ...]] pushd [-n] [+N | -N | dir] caller [expr] pwd [-LP] case WORD in [PATTERN [| PATTERN]...)> read [-ers] [-a array] [-d delim] [-> cd [-L|-P] [dir] readarray [-n count] [-O origin] [-s> command [-pVv] command [arg ...] readonly [-af] [name[=value] ...] or> compgen [-abcdefgjksuv] [-o option] > return [n] complete [-abcdefgjksuv] [-pr] [-DE] > select NAME [in WORDS ... ;] do COMM> compopt [-o|+o option] [-DE] [name ..> set [--abefhkmnptuvxBCHP] [-o option> continue [n] shift [n] coproc [NAME] command [redirections] shopt [-pqsu] [-o] [optname ...] declare [-aAfFilrtux] [-p] [name[=val> source filename [arguments] dirs [-clpv] [+N] [-N] suspend [-f] disown [-h] [-ar] [jobspec ...] test [expr] echo [-neE] [arg ...] time [-p] pipeline enable [-a] [-dnps] [-f filename] [na> times eval [arg ...] trap [-lp] [[arg] signal_spec ...] exec [-cl] [-a name] [command [argume> true exit [n] type [-afptP] name [name ...] export [-fn] [name[=value] ...] or ex> typeset [-aAfFilrtux] [-p] name[=val> false ulimit [-SHacdefilmnpqrstuvx] [limit> fc [-e ename] [-lnr] [first] [last] o> umask [-p] [-S] [mode] fg [job_spec] unalias [-a] name [name ...] for NAME [in WORDS ... ] ; do COMMAND> unset [-f] [-v] [name ...] for (( exp1; exp2; exp3 )); do COMMAN> until COMMANDS; do COMMANDS; done function name { COMMANDS ; } or name > variables - Names and meanings of so> getopts optstring name [arg] wait [id] hash [-lr] [-p pathname] [-dt] [name > while COMMANDS; do COMMANDS; done help [-dms] [pattern ...] { COMMANDS ; } ``` 另外一种选择是使用下列命令: ``` compgen -b compgen -b | more ``` ### 查看 Bash 的内置命令信息 运行以下得到详细信息: ``` help command help read ``` 要仅得到所有带简短描述的内置命令的列表,执行如下: ``` $ help -d ``` ### 查找内置命令的语法和其他选项 使用下列语法去找出更多的相关内置命令: ``` help name help cd help fg help for help read help : ``` 样例输出: ``` :: : Null command. No effect; the command does nothing. Exit Status: Always succeeds ``` ### 找出一个命令是内部的(内置)还是外部的 使用 `type` 命令或 `command` 命令: ``` type -a command-name-here type -a cd type -a uname type -a : type -a ls ``` 或者: ``` type -a cd uname : ls uname ``` 样例输出: ``` cd is a shell builtin uname is /bin/uname : is a shell builtin ls is aliased to `ls --color=auto' ls is /bin/ls l is a function l () { ls --color=auto } ``` 或者: ``` command -V ls command -V cd command -V foo ``` [![View list bash built-ins command info on Linux or Unix](/data/attachment/album/201802/13/012043plctt333wtncllco.jpg)](https://www.cyberciti.biz/media/new/faq/2013/03/View-list-bash-built-ins-command-info-on-Linux-or-Unix.jpg) ### 关于作者 作者是 nixCraft 网站的发起人和经验丰富的系统管理员,以及 Linux 操作系统/Unix shell 脚本编程培训师。他与全球客户以及包括 IT、教育、国防和空间研究以及非营利部门在内的各个行业合作。可以在 [Twitter](https://twitter.com/nixcraft)、[Facebook](https://facebook.com/nixcraft)、 [Google+](https://plus.google.com/+CybercitiBiz) 上关注他。 --- via: <https://www.cyberciti.biz/faq/linux-unix-bash-shell-list-all-builtin-commands/> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[KarenMrzhang](https://github.com/KarenMrzhang) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,344
Linux 中 4 个简单的找出进程 ID(PID)的方法
https://www.2daygeek.com/how-to-check-find-the-process-id-pid-ppid-of-a-running-program-in-linux/
2018-02-13T18:57:21
[ "PID", "进程" ]
https://linux.cn/article-9344-1.html
![](/data/attachment/album/201802/13/185715w7awbfirhr7bb4i8.jpg) 每个人都知道 PID,究竟什么是 PID?为什么你想要 PID?你打算用 PID 做什么?你脑子里有同样的问题吗?如果是这样,你就找对地方了解这些细节了。 我们查询 PID 主要是用来杀死一个没有响应的程序,它类似于 Windows 任务管理器一样。 Linux GUI 也提供相同的功能,但 CLI 是执行 `kill` 操作的有效方法。 ### 什么是进程 ID? PID 代表<ruby> 进程标识号 <rt> process identification </rt></ruby>,它在大多数操作系统内核(如 Linux、Unix、macOS 和 Windows)中使用。它是在操作系统中创建时自动分配给每个进程的唯一标识号。一个进程是一个正在运行的程序实例。 **建议阅读:** [如何查看 Apache Web 服务器在 Linux 中的运行时间](https://www.2daygeek.com/check-find-apache-httpd-web-server-uptime-linux/) 除了 init 进程外其他所有的进程 ID 每次都会改变,因为 init 始终是系统上的第一个进程,并且是所有其他进程的父进程。它的 PID 是 1。 PID 默认的最大值是 `32768`。可以在你的系统上运行 `cat /proc/sys/kernel/pid_max` 来验证。在 32 位系统上,`32768` 是最大值,但是我们可以在 64 位系统上将其设置为最大 2<sup> 22(约</sup> 4 百万)内的任何值。 你可能会问,为什么我们需要这么多的 PID?因为我们不能立即重用 PID,这就是为什么。另外为了防止可能的错误。 系统正在运行的进程的 PID 可以通过使用 `pidof`、`pgrep`、`ps` 和 `pstree` 命令找到。 ### 方法 1:使用 pidof 命令 `pidof` 用于查找正在运行的程序的进程 ID。它在标准输出上打印这些 id。为了演示,我们将在 Debian 9(stretch)系统中找出 Apache2 的进程 ID。 ``` # pidof apache2 3754 2594 2365 2364 2363 2362 2361 ``` 从上面的输出中,你可能会遇到难以识别进程 ID 的问题,因为它通过进程名称显示了所有的 PID(包括父进程和子进程)。因此,我们需要找出父 PID(PPID),这是我们要查找的。它可能是第一个数字。在本例中,它是 `3754`,并按降序排列。 ### 方法 2:使用 pgrep 命令 `pgrep` 遍历当前正在运行的进程,并将符合选择条件的进程 ID 列到标准输出中。 ``` # pgrep apache2 2361 2362 2363 2364 2365 2594 3754 ``` 这也与上面的输出类似,但是它将结果从小到大排序,这清楚地说明父 PID 是最后一个。在本例中,它是 `3754`。 **注意:** 如果你有多个进程的进程 ID,那么在使用 `pidof` 和 `pgrep` 识别父进程 ID 时就可能不会很顺利。 ### 方法 3:使用 pstree 命令 `pstree` 将运行的进程显示为一棵树。树的根是某个 pid,如果省略了 pid 参数,那么就是 init。如果在 `pstree` 命令中指定了用户名,则显示相应用户拥有的所有进程。 `pstree` 会将相同的分支放在方括号中,并添加重复计数的前缀来可视化地合并到一起。 ``` # pstree -p | grep "apache2" |- apache2(3754) -|-apache2(2361) | |-apache2(2362) | |-apache2(2363) | |-apache2(2364) | |-apache2(2365) | `-apache2(2594) ``` 要单独获取父进程,请使用以下格式。 ``` # pstree -p | grep "apache2" | head -1 |- apache2(3754) -|-apache2(2361) ``` `pstree` 命令非常简单,因为它分别隔离了父进程和子进程,但这在使用 `pidof` 和 `pgrep` 时命令不容易做到。 ### 方法 4:使用 ps 命令 `ps` 显示活动进程的选择信息。它显示进程 ID(`pid`=PID)、与进程关联的终端(`tname`=TTY)、以 `[DD-]hh:mm:ss` 格式(`time`=TIME)显示的累计 CPU 时间、以及执行名(`ucmd` = CMD)。输出默认是未排序的。 ``` # ps aux | grep "apache2" www-data 2361 0.0 0.4 302652 9732 ? S 06:25 0:00 /usr/sbin/apache2 -k start www-data 2362 0.0 0.4 302652 9732 ? S 06:25 0:00 /usr/sbin/apache2 -k start www-data 2363 0.0 0.4 302652 9732 ? S 06:25 0:00 /usr/sbin/apache2 -k start www-data 2364 0.0 0.4 302652 9732 ? S 06:25 0:00 /usr/sbin/apache2 -k start www-data 2365 0.0 0.4 302652 8400 ? S 06:25 0:00 /usr/sbin/apache2 -k start www-data 2594 0.0 0.4 302652 8400 ? S 06:55 0:00 /usr/sbin/apache2 -k start root 3754 0.0 1.4 302580 29324 ? Ss Dec11 0:23 /usr/sbin/apache2 -k start root 5648 0.0 0.0 12784 940 pts/0 S+ 21:32 0:00 grep apache2 ``` 从上面的输出中,我们可以根据进程的启动日期轻松地识别父进程 ID(PPID)。在此例中,apache2 启动于 `Dec 11`,它是父进程,其他的是子进程。apache2 的 PID 是 `3754`。 --- via: <https://www.2daygeek.com/how-to-check-find-the-process-id-pid-ppid-of-a-running-program-in-linux/> 作者:[Magesh Maruthamuthu](https://www.2daygeek.com/author/magesh/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,345
为什么说 Python 和 Pygame 最适合编程初学者
https://opensource.com/article/17/11/pygame
2018-02-16T10:05:00
[ "Pygame", "Python", "编程" ]
https://linux.cn/article-9345-1.html
> > 我们有三个理由来说明 Pygame 对初学编程者是最好的选择。 > > > ![What's the best game platform for beginning programmers?](/data/attachment/album/201802/13/200646ffjgf8fhl8lf1oon.png "What's the best game platform for beginning programmers?") 上个月,[Scott Nesbitt](https://opensource.com/users/scottnesbitt) 发表了一篇标题为 [Mozilla 支出 50 万美元来支持开源项目](https://opensource.com/article/17/10/news-october-14)的文章。其中一个基于 HTML/JavaScript 的游戏平台项目 Phaser 获得了 50,000 美元的奖励。整整一年里,我都在使用 Phaser 平台来教我的小女儿,用来学习的话,它是最简单也是最好的 HTML 游戏开发平台。然而,对于初学者来说,使用 [Pygame](https://www.pygame.org/news) 也许效果更好。原因如下: ### 1、 小段代码块 Pygame,基于[计算机课程中最流行的语言](https://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext) Python。Python 非常适合用一小段代码来实现我们的想法,孩子们可以从单个文件和单个代码块起开始学习,在掌握函数(function)或类(class)对象之前,就可以写出意大利面条似的代码。 很像手指画,所想即所得。 以这样的方式来学习,当编写的代码越来越难于管理的时候,孩子们很自然的就会把代码分解成函数模块和类模块。在学习函数之前就学习了 Python 语言的语法,学生将掌握基本的编程知识,对了解全局作用域和局部作用域起到更好的作用。 大多数 HTML 游戏在一定程度上会将结构、样式和编程逻辑分为 HTML、CSS 和 JavaScript,并且需要 CSS 和 HTML 的知识。从长远来看,虽然拆分更好,但对初学者来说是个障碍。一旦孩子们发现他们可以用 HTML 和 CSS 快速构建网页,很有可能就会被颜色、字体和图形的视觉刺激分散注意力。即使仅仅只专注于 JavaScript 代码,也需要学习基本的文档结构模型(DOM),以使 JavaScript 代码能够嵌入进去。 ### 2、 全局变量更清晰 Python 和 JavaScript 都使用动态类型变量,这意味着变量只有在赋值才能确定其类型是一个字符串、一个整数还是一个浮点数,然而在 JavaScript 更容易出错。类似于类型变量,JavaScript 和 Python 都有全局变量和局部变量之分。Python 中,如果在函数块内要使用全局变量,就会以 `global` 关键字区分出来。 要理解在 Phaser 上教授编程初学者所面临的挑战的话,让我们以基本的[制作您的第一个 Phaser 游戏教程](http://phaser.io/tutorials/making-your-first-phaser-game)为例子,它是由 Alvin Ourrad 和 Richard Davey 开发制作的。在 JavaScript 中,程序中任何地方都可以访问的全局变量很难追踪调试,常常引起 Bug 且很难解决。因为 Richard 和 Alvin 是专业程序员,所以在这儿特意使用全局变量以使程序简洁。 ``` var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { game.load.image('sky', 'assets/sky.png'); } var player; var platforms; function create() { game.physics.startSystem(Phaser.Physics.ARCADE); ... ``` 在他们的 Phaser 编程手册 [《Interphase》](https://phaser.io/interphase) 中,Richard Davey 和 Ilija Melentijevic 解释说:在很多 Phaser 项目中通常都会使用全局变量,原因是使用它们完成任务更容易、更快捷。 > > “如果您开发过游戏,只要代码量到一定规模,那么(使用全局变量)这种做法会使您陷入困境的,可是我们为什么还要这样做?原因很简单,仅仅只是要使我们的 Phaser 项目容易完成,更简单而已。” > > > 针对一个 Phaser 应用程序,虽然可以使用局部变量和拆分代码块来达到关注点隔离这些手段来重构代码,但要使第一次学习编程的小孩能理解,显然很有难度的。 如果您想教你的孩子学习 JavaScript,或者如果他们已经知道怎样使用像 Python 来编程的话,有个好的 Phaser 课程推荐: [完整的手机游戏开发课程](https://academy.zenva.com/product/the-complete-mobile-game-development-course-platinum-edition/),是由 [Pablo Farias Navarro](https://gamedevacademy.org/author/fariazz/) 开发制作的。虽然标题看着是移动游戏,但实际是关于 JavaScript 和 Phaser 的。JavaScript 和 Phaser 移动应用开发已经转移到 [PhoneGap](https://phonegap.com/) 话题去了。 ### 3、 Pygame 无依赖要求 由于 [Python Wheels](https://pythonwheels.com/) 的出现,Pygame 超级[容易安装](https://pypi.python.org/pypi/Pygame)。在 Fedora/Red Hat 系统下也可使用 `yum` 包管理器来安装: ``` sudo yum install python3-pygame ``` 更多信息请参考官网 [Pygame 安装说明文档](http://www.pygame.org/wiki/GettingStarted#Pygame%20Installation)。 相比来说,虽然 Phaser 本身更容易安装,但需要掌握更多的知识。前面提到的,学生需要在 HTML 文档中组装他们的 JavaScript 代码,同时还需要些 CSS。除了这三种语言(HTML、CSS、JavaScript),还需要使用火狐或谷歌开发工具和编辑器。JavaScript 最常用的编辑器有 Sublime、Atom、VS Code(按使用多少排序)等。 由于[浏览器同源策略](https://blog.chromium.org/2008/12/security-in-depth-local-web-pages.html)的原因,如果您直接在浏览器中打开 HTML 文件的话,Phaser 应用是不会运行的。您必须运行 Web 服务,并通过服务访问这些文件。还好,对于大多数工程项目,可以不用在本地运行 Apache 服务,只需要运行一些轻量级的服务就可以,比如 [httpster](https://simbco.github.io/httpster/)。 ### Phaser 和 JavaScript 的优势 JavaScript 和 Phaser 有着种种的不好,为什么我还继续教授他们?老实说,我考虑了很长一段时间,我在担心着学生学习<ruby> 变量申明提升 <rt> variable hoisting </rt></ruby>和变量作用域的揪心。我开发出基于 Pygame 和 Python 的课程,随后也开发出一涛基于 Phaser 的。最终,我决定使用 Pablo 预先制定的课程作为起点。 我转用 JavaScript 有两个原因。首先,JavaScript 已经成为正式应用的正式语言。除了 Web 应用外,也可使用于移动和服务应用方面。JavaScript 无处不在,其广泛应用于孩子们每天都能看到的应用中。如果他们的朋友使用 Javascript 来编程,他们很可能也会受影响而使用之。正如我看到了 JavaScript 背后的动力,所以深入研究了可编译成 JavaScript 的替代语言,主要是 Dart 和 TypeScript 两种。虽然我不介意额外的转换步骤,但还是最喜欢 JavaScript。 最后,我选择使用 Phaser 和 JavaScript 的组合,是因为我意识到上面那些问题在 JavaScript 可以被解决,仅仅只是一些工作量而已。高质量的调试工具和一些大牛们的工作使得 JavaScript 成为教育孩子编码的可用和有用的语言。 ### 最后话题: Python 对垒 JavaScript 当家长问我使用的什么语言作为孩子的入门语言时,我会立即推荐 Python 和 Pygame。因为有成千上万的课程可选,而且大多数都是免费的。我为我的儿子选择了 Al Sweigart 的 [使用 Python 和 Pygame 开发游戏](https://inventwithpython.com/makinggames.pdf) 课程,同时也在使用 Allen B. Downey 的 [Python 编程思想:如何像计算机科学家一样思考](http://greenteapress.com/thinkpython/html/index.html)。在 Android 手机上可以使用 [Tom Rothame](https://github.com/renpytom) 的 [PAPT Pyame](https://github.com/renpytom/rapt-pygame-example) 来安装 Pygame 游戏。 尽管有我的建议, 我总是怀疑孩子们很快就会搬到 JavaScript。这没关系 —— JavaScript 是一门成熟的编程语言,有很多很多辅助工具。但有多年的帮助大儿子使用 Python 创建炫酷游戏经历的我,依然钟情于 Python 和 Pygame。 ### 关于作者 Craig Oda —— 东京 Linux 用户组的首位总裁和共同创始人,奥莱理日本出版的《Linux 日文环境》的共同作者。在亚洲建立了第一个 ISP 的核心团队成员之一。一个大型 Linux 公司的产品管理及市场的前任副总裁。硅谷开发者关系咨询公司 Oppkey 的合作方。[更多](https://opensource.com/users/codetricity) --- via: <https://opensource.com/article/17/11/pygame> 作者:[Craig Oda](https://opensource.com/users/codetricity) 译者:[runningwater](https://github.com/runningwater) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Last month, [Scott Nesbitt](https://opensource.com/users/scottnesbitt) wrote about [Mozilla awarding $500K to support open source projects](https://opensource.com/article/17/10/news-october-14). Phaser, a HTML/JavaScript game platform, was [awarded $50,000](https://www.patreon.com/photonstorm/posts). I’ve been teaching Phaser to my pre-teen daughter for a year, and it's one of the best and easiest HTML game development platforms to learn. [Pygame](https://www.pygame.org/news), however, may be a better choice for beginners. Here's why. ## 1. One long block of code Pygame is based on Python, the [most popular language for introductory computer courses](https://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext). Python is great for writing out ideas in one long block of code. Kids start off with a single file and with a single block of code. Before they can get to functions or classes, they start with code that will soon resemble spaghetti. It’s like finger-painting, as they throw thoughts onto the page. This approach to learning works. Kids will naturally start to break things into functions and classes as their code gets more difficult to manage. By learning the syntax of a language like Python prior to learning about functions, the student will gain basic programming knowledge before using global and local scope. Most HTML games separate the structure, style, and programming logic into HTML, CSS, and JavaScript to some degree and require knowledge of CSS and HTML. While the separation is better in the long term, it can be a barrier for beginners. Once kids realize that they can quickly build web pages with HTML and CSS, they may get distracted by the visual excitement of colors, fonts, and graphics. Even those who stay focused on JavaScript coding will still need to learn the basic document structure that the JavaScript code sits in. ## 2. Global variables are more obvious Both Python and JavaScript use dynamically typed variables, meaning that a variable becomes a string, an integer, or float when it’s assigned; however, making mistakes is easier in JavaScript. Similar to typed variables, both JavaScript and Python have global and local variable scopes. In Python, global variables inside of a function are identified with the global keyword. Let’s look at the basic [Making your first Phaser game tutorial](http://phaser.io/tutorials/making-your-first-phaser-game), by Alvin Ourrad and Richard Davey, to understand the challenge of using Phaser to teach programming to beginners. In JavaScript, global variables—variables that can be accessed anywhere in the program—are difficult to keep track of and often are the source of bugs that are challenging to solve. Richard and Alvin are expert programmers and use global variables intentionally to keep things concise. ``` `````` var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { game.load.image('sky', 'assets/sky.png'); } var player; var platforms; function create() { game.physics.startSystem(Phaser.Physics.ARCADE); … ``` In their Phaser programming book [ Interphase,](https://phaser.io/interphase) Richard Davey and Ilija Melentijevic explain that global variables are commonly used in many Phaser projects because they make it easier to get things done quickly. “If you’ve ever worked on a game of any significant size then this approach is probably already making you cringe slightly... So why do we do it? The reason is simply because it’s the most concise and least complicated way to demonstrate what Phaser can do.” Although structuring a Phaser application to use local variables and split things up nicely into separation of concerns is possible, that’s tough for kids to understand when they’re first learning to program. If you’re set on teaching your kids to code with JavaScript, or if they already know how to code in another language like Python, a good Phaser course is [The Complete Mobile Game Development Course](https://academy.zenva.com/product/the-complete-mobile-game-development-course-platinum-edition/), by [Pablo Farias Navarro](https://gamedevacademy.org/author/fariazz/). Although the title focuses on mobile games, the actual course focuses on JavaScript and Phaser. The JavaScript and Phaser apps are moved to a mobile phone with [PhoneGap](https://phonegap.com/). ## 3. Pygame comes with less assembly required Thanks to [Python Wheels](https://pythonwheels.com/), Pygame is now super [easy to install](https://pypi.python.org/pypi/Pygame). You can also install it on Fedora/Red Hat with the **yum** package manager: ``` ````sudo yum install python3-pygame` See the official [Pygame installation documentation](http://www.pygame.org/wiki/GettingStarted#Pygame%20Installation) for more information. Although Phaser itself is even easier to install, it does require more knowledge to use. As mentioned previously, the student will need to assemble their JavaScript code within an HTML document with some CSS. In addition to the three languages—HTML, CSS, and JavaScript—Phaser also requires the use of Firefox or Chrome development tools and an editor. The most common editors for JavaScript are Sublime, Atom, VS Code (probably in that order). Phaser applications will not run if you open the HTML file in a browser directly, due to [same-origin policy](https://blog.chromium.org/2008/12/security-in-depth-local-web-pages.html). You must run a web server and access the files by connecting to the web server. Fortunately, you don’t need to run Apache on your local computer; you can run something lightweight like [httpster](https://simbco.github.io/httpster/) for most projects. ## Advantages of Phaser and JavaScript With all the challenges of JavaScript and Phaser, why am I teaching them? Honestly, I held off for a long time. I worried about students learning variable hoisting and scope. I developed my own curriculum based on Pygame and Python, then I developed one based on Phaser. Eventually, I decided to use Pablo’s pre-made curriculum as a starting point. There are really two reasons that I moved to JavaScript. First, JavaScript has emerged as a serious language used in serious applications. In addition to web applications, it’s used for mobile and server applications. JavaScript is everywhere, and it’s used widely in applications kids see every day. If their friends code in JavaScript, they'll likely want to as well. As I saw the momentum behind JavaScript, I looked into alternatives that could compile into JavaScript, primarily Dart and TypeScript. I didn’t mind the extra conversion step, but I still looked at JavaScript. In the end, I chose to use Phaser and JavaScript because I realized that the problems could be solved with JavaScript and a bit of work. High-quality debugging tools and the work of some exceptionally smart people have made JavaScript a language that is both accessible and useful for teaching kids to code. ## Final word: Python vs. JavaScript When people ask me what language to start their kids with, I immediately suggest Python and Pygame. There are tons of great curriculum options, many of which are free. I used ["Making Games with Python & Pygame"](https://inventwithpython.com/makinggames.pdf) by Al Sweigart with my son. I also used * Think Python: How to Think Like a Computer Scientist* by Allen B. Downey. You can get Pygame on your Android phone with [RAPT Pygame](https://github.com/renpytom/rapt-pygame-example)by [Tom Rothamel](https://github.com/renpytom). Despite my recommendation, I always suspect that kids soon move to JavaScript. And that’s okay—JavaScript is a mature language with great tools. They’ll have fun with JavaScript and learn a lot. But after years of helping my daughter’s older brother create cool games in Python, I’ll always have an emotional attachment to Python and Pygame. ## 4 Comments
9,346
如何在 Ubuntu 上使用 ZFS 文件系统
https://www.maketecheasier.com/use-zfs-filesystem-ubuntu-linux/
2018-02-14T00:52:07
[ "ZFS", "RAID" ]
https://linux.cn/article-9346-1.html
![](/data/attachment/album/201802/14/005211baxhkm3vax7a5h75.jpg) 在 Linux 系统上,有大量的[文件系统](https://www.maketecheasier.com/best-linux-filesystem-for-ssd/)可以使用,那么我们为什么还要尝试一个新的文件系统?它们都工作的很好,不是吗?但是它们并不完全相同,其中的一些文件系统具有非常突出的优点,例如 ZFS。 ### 为什么选择 ZFS ZFS 非常的优秀。这是一个真正现代的文件系统,内置的功能对于处理大量的数据很有意义。 现在,如果您正在考虑将 ZFS 用于您的超高速 NVMe SSD,这可能不是一个最佳选择。 它比别的文件系统要慢,不过,这完全没有问题, 它旨在存储大量的数据并保持安全。 ZFS 消除了建立传统 RAID 阵列(LCTT 译注:独立磁盘冗余阵列)的需要。 相反,您可以创建 ZFS 池,甚至可以随时将驱动器添加到这些池中。 ZFS 池的行为操作与 RAID 几乎完全相同,但功能内置于文件系统中。 ZFS 也可以替代 LVM (LCTT 译注:逻辑盘卷管理),使您能够动态地进行分区和管理分区,而无需处理底层的细节,也不必担心相关的风险。 这也是一个 CoW (LCTT 译注:写时复制)文件系统。 这里不会提及太多的技术性,这意味着 ZFS 可以保护您的数据免受逐渐损坏的影响。 ZFS 会创建文件的校验和,并允许您将这些文件回滚到以前的工作版本。 ### 安装 ZFS ![Install ZFS on Ubuntu](/data/attachment/album/201802/14/005212gem4smmvrwczhxdh.jpg "Install ZFS on Ubuntu") 在 Ubuntu 上安装 ZFS 非常简单,但对于 Ubuntu LTS (LCTT 译注:长时间支持版本)和最新版本来说,这个过程稍有不同。 **Ubuntu 16.04 LTS** ``` sudo apt install zfs ``` **Ubuntu 17.04 及以后** ``` sudo apt install zfsutils ``` 当你安装好程序后,可以使用 ZFS 提供的工具创建 ZFS 驱动器和分区。 ### 创建池 ![Create ZFS Pool](/data/attachment/album/201802/14/005212t99r9s9pxxp4r991.jpg "Create ZFS Pool") 在 ZFS 中,池大致相当于 RAID 。 它们很灵活且易于操作。 #### RAID0 RAID0 只是把你的硬盘集中到一个池子里面,就像一个巨大的驱动器一样。 它可以提高你的驱动器速度,(LCTT 译注:数据条带化后,并行访问,可以提高文件读取速度)但是如果你的驱动器有损坏,你可能会失丢失数据。 要使用 ZFS 实现 RAID0,只需创建一个普通的池。 ``` sudo zpool create your-pool /dev/sdc /dev/sdd ``` #### RAID1(镜像) 您可以在 ZFS 中使用 `mirror` 关键字来实现 RAID1 功能。 RAID1 会创建一个一对一的驱动器副本。 这意味着您的数据一直在备份。 它也提高了性能。 当然,你将一半的存储空间用于了复制。 ``` sudo zpool create your-pool mirror /dev/sdc /dev/sdd ``` #### RAID5/RAIDZ1 ZFS 将 RAID5 功能实现为 RAIDZ1。 RAID5 要求驱动器至少是 3 个。并允许您通过将备份奇偶校验数据写入驱动器空间的 1/n(n 是驱动器数),留下的是可用的存储空间。 如果一个驱动器发生故障,阵列仍将保持联机状态,但应尽快更换发生故障的驱动器(LCTT 译注:与原文翻译略有不同,原文是驱动器的数目是三的倍数,根据 wiki, RAID5 至少需要 3 块驱动器,也可以从下面的命令中猜测)。 ``` sudo zpool create your-pool raidz1 /dev/sdc /dev/sdd /dev/sde ``` #### RAID6/RAIDZ2 RAID6 与 RAID5 几乎完全相同,但它至少需要四个驱动器。 它将奇偶校验数据加倍,最多允许两个驱动器损坏,而不会导致阵列关闭(LCTT 译注:这里也与原文略有出入,原文是驱动器的数目是四的倍数,根据 wiki ,RAID6 至少需要四个驱动器)。 ``` sudo zpool create your-pool raidz2 /dev/sdc /dev/sdd /dev/sde /dev/sdf ``` #### RAID10(条带化镜像) RAID10 旨在通过数据条带化提高存取速度和数据冗余来成为一个两全其美的解决方案。 你至少需要四个驱动器,但只能使用一半的空间。 您可以通过在同一个池中创建两个镜像来创建 RAID10 中的池(LCTT 译注:这里也与原文略有出入,原文是驱动器的数目是四的倍数,根据 wiki, RAID10 至少需要四个驱动器)。 ``` sudo zpool create your-pool mirror /dev/sdc /dev/sdd mirror /dev/sde /dev/sdf ``` ### 池的操作 ![ZFS pool Status](/data/attachment/album/201802/14/005212sbj96k1bozm1gbgz.jpg "ZFS pool Status") 还有一些管理工具,一旦你创建了你的池,你就必须使用它们来操作。 首先,检查你的池的状态。 ``` sudo zpool status ``` #### 更新 当你更新 ZFS 时,你也需要更新你的池。 当您检查它们的状态时,您的池会通知您任何更新。 要更新池,请运行以下命令。 ``` sudo zpool upgrade your-pool ``` 你也可以更新全部池。 ``` sudo zpool upgrade -a ``` #### 添加驱动器 您也可以随时将驱动器添加到池中。 告诉 `zpool` 池的名称和驱动器的位置,它会处理好一切。 ``` sudo zpool add your-pool /dev/sdx ``` ### 其它的一些想法 ![ZFS in File Browser](/data/attachment/album/201802/14/005212ij3vwbvq3zllq030.jpg "ZFS in File Browser") ZFS 会在您的池的根文件系统中创建一个目录。 您可以使用 GUI 文件管理器或 CLI 按名称浏览它们。 ZFS 非常强大,还有很多其它的东西可以用它来做,但这些都是基础。 这是一个优秀的存储负载文件系统,即使它只是一个用于文件的硬盘驱动器的 RAID 阵列。 ZFS 在 NAS 系统上也非常出色。 无论 ZFS 的稳定性和可靠性如何,在您的硬盘上实施新的功能时,最好备份您的数据。 --- via: <https://www.maketecheasier.com/use-zfs-filesystem-ubuntu-linux/> 作者:[Nick Congleton](https://www.maketecheasier.com/author/nickcongleton/) 译者:[amwps290](https://github.com/amwps290) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![ZFS on Ubuntu](https://www.maketecheasier.com/assets/uploads/2017/09/zfs-feat.jpg) There are a myriad of [filesystems available for Linux](https://www.maketecheasier.com/best-linux-filesystem-for-ssd/). So why try a new one? They all work, right? They’re not all the same, and some have some very distinct advantages, like ZFS. ## Why ZFS ZFS is awesome. It’s a truly modern filesystem with built-in capabilities that make sense for handling loads of data. Now, if you’re considering ZFS for your ultra-fast NVMe SSD, it might not be the best option. It’s slower than others. That’s okay, though. It was designed to store huge amounts of data and keep it safe. ZFS eliminates the need to set up traditional RAID arrays. Instead, you can create ZFS pools, and even add drives to those pools at any time. ZFS pools behave almost exactly like RAID, but the functionality is built right into the filesystem. ZFS also acts like a replacement for LVM, allowing you to partition and manage partitions on the fly without the need to handle things at a lower level and worry about the associated risks. It’s also a CoW filesystem. Without getting too technical, that means that ZFS protects your data from gradual corruption over time. ZFS creates checksums of files and lets you roll back those files to a previous working version. ## Installing ZFS Installing ZFS on Ubuntu is very easy, though the process is slightly different for Ubuntu LTS and the latest releases. **Ubuntu 16.04 LTS** sudo apt install zfs **Ubuntu 17.04 and Later** sudo apt install zfsutils After you have the utilities installed, you can create ZFS drives and partitions using the tools provided by ZFS. ## Creating Pools Pools are the rough equivalent of RAID in ZFS. They are flexible and can easily be manipulated. ### RAID0 RAID0 just pools your drives into what behaves like one giant drive. It can increase your drive speeds, but if one of your drives fails, you’re probably going to be out of luck. To achieve RAID0 with ZFS, just create a plain pool. sudo zpool create your-pool /dev/sdc /dev/sdd ### RAID1/MIRROR You can achieve RAID1 functionality with the `mirror` keyword in ZFS. Raid1 creates a 1-to-1 copy of your drive. This means that your data is constantly backed up. It also increases performance. Of course, you use half of your storage to the duplication. sudo zpool create your-pool mirror /dev/sdc /dev/sdd ### RAID5/RAIDZ1 ZFS implements RAID5 functionality as RAIDZ1. RAID5 requires drives in multiples of three and allows you to keep 2/3 of your storage space by writing backup parity data to 1/3 of the drive space. If one drive fails, the array will remain online, but the failed drive should be replaced ASAP. sudo zpool create your-pool raidz1 /dev/sdc /dev/sdd /dev/sde ### RAID6/RAIDZ2 RAID6 is almost exactly like RAID5, but it works in multiples of four instead of multiples of three. It doubles the parity data to allow up to two drives to fail without bringing the array down. sudo zpool create your-pool raidz2 /dev/sdc /dev/sdd /dev/sde /dev/sdf ### RAID10/Striped Mirror RAID10 aims to be the best of both worlds by providing both a speed increase and data redundancy with striping. You need drives in multiples of four and will only have access to half of the space. You can create a pool in RAID10 by creating two mirrors in the same pool command. sudo zpool create your-pool mirror /dev/sdc /dev/sdd mirror /dev/sde /dev/sdf ## Working With Pools There are also some management tools that you have to work with your pools once you’ve created them. First, check the status of your pools. `sudo zpool status` ### Updates When you update ZFS you’ll need to update your pools, too. Your pools will notify you of any updates when you check their status. To update a pool, run the following command. `sudo zpool upgrade your-pool` You can also upgrade them all. sudo zpool upgrade -a ### Adding Drives You can also add drives to your pools at any time. Tell `zpool` the name of the pool and the location of the drive, and it’ll take care of everything. sudo zpool add your-pool /dev/sdx ## Other Thoughts ZFS creates a directory in the root filesystem for your pools. You can browse to them by name using your GUI file manager or the CLI. ZFS is awesomely powerful, and there are plenty of other things that you can do with it, too, but these are the basics. It is an excellent filesystem for working with loads of storage, even if it is just a RAID array of hard drives that you use for your files. ZFS works excellently with NAS systems, too. Regardless of how stable and robust ZFS is, it’s always best to back up your data when you implement something new on your hard drives. Our latest tutorials delivered straight to your inbox
9,347
哪个 Linux 内核版本是 “稳定的”?
https://www.linux.com/blog/learn/2018/2/which-linux-kernel-version-stable
2018-02-14T21:52:00
[ "内核", "更新" ]
https://linux.cn/article-9347-1.html
![Linux kernel ](/data/attachment/album/201802/14/215211tx038x3zccrs3crx.jpg "Linux kernel") > > Konstantin Ryabitsev 为你讲解哪个 Linux 内核版本可以被视作“稳定版”,以及你应该如何选择一个适用你的内核版本。 > > > 每次 Linus Torvalds 发布 [一个新 Linux 内核的主线版本](/article-9328-1.html),几乎都会引起这种困惑,那就是到底哪个内核版本才是最新的“稳定版”?是新的那个 X.Y,还是前面的那个 X.Y-1.Z ?最新的内核版本是不是太“新”了?你是不是应该坚持使用以前的版本? [kernel.org](https://www.kernel.org/) 网页上的信息并不会帮你解开这个困惑。目前,在该页面的最顶部,我们看到是最新稳定版内核是 4.15 — 但是在这个表格的下面,4.14.16 也被列为“<ruby> 稳定版 <rt> stable </rt></ruby>”,而 4.15 被列为“<ruby> 主线版本 <rt> mainline </rt></ruby>”,很困惑,是吧? 不幸的是,这个问题并不好回答。我们在这里使用“稳定”这个词有两个不同的意思:一是,作为最初发布的 Git 树的名字,二是,表示这个内核可以被视作“稳定版”,用在“生产系统”。 由于 Git 的分布式特性,Linux 的开发工作在许多 [不同的分叉仓库中](https://git.kernel.org/pub/scm/linux/kernel/git/) 进行。所有的 bug 修复和新特性也是首先由各个子系统维护者收集和准备的,然后提交给 Linus Torvalds,由 Linus Torvalds 包含进 [他自己的 Linux 树](https://git.kernel.org/torvalds/c/v4.15) 中,他的 Git 树被认为是 Git 仓库的 “master”。我们称这个树为 “主线” Linux 树。 ### 候选发布版(RC) 在每个新的内核版本发布之前,它都要经过几轮的“候选发布”,它由开发者进行测试并“打磨”所有的这些很酷的新特性。基于他们这几轮测试的反馈,Linus 决定最终版本是否已经准备就绪。通常有 7 个每周预发布版本,但是,这个数字经常走到 -rc8,并且有时候甚至达到 -rc9 及以上。当 Linus 确信那个新内核已经没有问题了,他就制作最终发行版,我们称这个版本为“稳定版”,表示它不再是一个“候选发布版”。 ### Bug 修复 就像任何一个由不是十全十美的人所写的复杂软件一样,任何一个 Linux 内核的新版本都包含 bug,并且这些 bug 必须被修复。Linux 内核的 bug 修复规则非常简单:所有修复必须首先进入到 Linus 的树。一旦主线仓库中的 bug 被修复后,它接着会被应用到内核开发社区仍在维护的已发布内核中。在它们被考虑回迁到已发布的稳定版本之前,所有的 bug 修复必须满足 [一套重要的标准](https://www.kernel.org/doc/html/latest/process/stable-kernel-rules.html) — 标准的其中之一是,它们 “必须已经存在于 Linus 的树中”。这是一个 [独立的 Git 仓库](https://git.kernel.org/stable/linux-stable/c/v4.14.16),维护它的用途是回迁 bug 修复,而它也被称为“稳定”树 —— 因为它用于跟踪以前发布的稳定内核。这个树由 Greg Kroah-Hartman 策划和维护。 ### 最新的稳定内核 因此,无论在什么时候,为了查看最新的稳定内核而访问 kernel.org 网站时,你应该去使用那个在大黄色按钮所说的“最新的稳定内核”。 ![](/data/attachment/album/201802/14/215257g9bbamoimqqm5mmi.png) 但是,你可能会惊奇地发现 —— 4.15 和 4.14.16 都是稳定版本,那么到底哪一个更“稳定”呢?有些人不愿意使用 “.0” 的内核发行版,因为他们认为这个版本并不足够“稳定”,直到最新的是 ".1" 的为止。很难证明或者反驳这种观点的对与错,并且这两种观点都有赞成或者反对的理由,因此,具体选择哪一个取决于你的喜好。 一方面,任何一个进入到稳定树的发行版都必须首先被接受进入主线内核版本中,并且随后会被回迁到已发行版本中。这意味着内核的主线版本相比稳定树中的发行版本来说,总包含有最新的 bug 修复,因此,如果你想使用的发行版包含的“**已知 bug**”最少,那么使用 “.0” 的主线发行版是最佳选择。 另一方面,主线版本增加了所有很酷的新特性 —— 而新特性也给它们带来了**数量未知的“新 bug”**,而这些“新 bug”在老的稳定版中是**不会存在**的。而新的、未知的 bug 是否比旧的、已知的但尚未修复的 bug 更加令人担心呢? —— 这取决于你的选择。不过需要说明的一点是,许多 bug 修复只对内核的主线版本进行了彻底的测试。当补丁回迁到旧内核时,它们**可能**会工作的很好,但是它们**很少**做与旧内核的集成测试工作。通常都假定,“以前的稳定版本”足够接近当前的确信可用于生产系统的主线版本。而实际上也确实是这样的,当然,这也更加说明了为什么选择“哪个内核版本更稳定”是件**非常困难**的事情了。 因此,从根本上说,我们并没有定量的或者定性的手段去明确的告诉你哪个内核版本更加稳定 —— 4.15 还是 4.14.16?我们能够做到的只是告诉你,它们具有“**不同的**稳定性”,(这个答案可能没有帮到你,但是,至少你明白了这些版本的差别是什么?)。 *学习更多的 Linux 的知识,可以通过来自 Linux 基金会和 edX 的免费课程 ["认识 Linux"](https://training.linuxfoundation.org/linux-courses/system-administration-training/introduction-to-linux) 。* --- via: <https://www.linux.com/blog/learn/2018/2/which-linux-kernel-version-stable> 作者:[KONSTANTIN RYABITSEV](https://www.linux.com/users/mricon) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,348
ncurses 入门指南
http://www.linuxjournal.com/content/getting-started-ncurses
2018-02-16T00:20:00
[ "curses", "ncurses" ]
https://linux.cn/article-9348-1.html
> > 怎样使用 curses 来绘制终端屏幕? > > > ![](/data/attachment/album/201802/14/232431itpppd60pa60ps4w.jpg) 虽然图形界面非常酷,但是不是所有的程序都需要点击式的界面。例如,令人尊敬的 Vi 编辑器在第一个 GUI 出现之前在纯文本终端运行了很久。 Vi 编辑器是一个在“文本”模式下绘制的<ruby> 面向屏幕 <rt> screen-oriented </rt></ruby>程序的例子。它使用了一个叫 curses 的库。这个库提供了一系列的编程接口来操纵终端屏幕。curses 库产生于 BSD UNIX,但是 Linux 系统通过 ncurses 库提供这个功能。 [要了解 ncurses “过去曾引起的风暴”,参见 [ncurses: Portable Screen-Handling for Linux](http://www.linuxjournal.com/article/1124), September 1, 1995, by Eric S. Raymond.] 使用 curses 创建程序实际上非常简单。在这个文章中,我展示了一个利用 curses 来在终端屏幕上绘图的示例程序。 ### 谢尔宾斯基三角形 简单展示一些 curses 函数的一个方法是生成<ruby> 谢尔宾斯基三角形 <rt> Sierpinski's Triangle </rt></ruby>。如果你对生成谢尔宾斯基三角形的这种方法不熟悉的话,这里是一些产生谢尔宾斯基三角形的规则: 1. 设置定义三角形的三个点。 2. 随机选择任意的一个点 `(x,y)`。 然后: 1. 在三角形的顶点中随机选择一个点。 2. 将新的 `x,y` 设置为先前的 `x,y` 和三角顶点的中间点。 3. 重复(上述步骤)。 所以我按照这些指令写了这个程序,程序使用 curses 函数来向终端屏幕绘制谢尔宾斯基三角形: ``` /* triangle.c */ #include <curses.h> #include <stdlib.h> #include "getrandom_int.h" #define ITERMAX 10000 int main(void) { long iter; int yi, xi; int y[3], x[3]; int index; int maxlines, maxcols; /* initialize curses */ initscr(); cbreak(); noecho(); clear(); /* initialize triangle */ maxlines = LINES - 1; maxcols = COLS - 1; y[0] = 0; x[0] = 0; y[1] = maxlines; x[1] = maxcols / 2; y[2] = 0; x[2] = maxcols; mvaddch(y[0], x[0], '0'); mvaddch(y[1], x[1], '1'); mvaddch(y[2], x[2], '2'); /* initialize yi,xi with random values */ yi = getrandom_int() % maxlines; xi = getrandom_int() % maxcols; mvaddch(yi, xi, '.'); /* iterate the triangle */ for (iter = 0; iter < ITERMAX; iter++) { index = getrandom_int() % 3; yi = (yi + y[index]) / 2; xi = (xi + x[index]) / 2; mvaddch(yi, xi, '*'); refresh(); } /* done */ mvaddstr(maxlines, 0, "Press any key to quit"); refresh(); getch(); endwin(); exit(0); } ``` 让我一边解释一边浏览这个程序。首先,`getrandom_int()` 函数是我对 Linux 系统调用 `getrandom()` 的包装器。它保证返回一个正整数(`int`)值。(LCTT 译注:`getrandom()` 系统调用按照字节返回随机值到一个变量中,值是随机的,不保证正负,使用 `stdlib.h` 的 `random()` 函数可以达到同样的效果)另外,按照上面的规则,你应该能够辨认出初始化和迭代谢尔宾斯基三角形的代码。除此之外,我们来看看我用来在终端上绘制三角形的 curses 函数。 大多数 curses 程序以这四条指令开头。 `initscr()` 函数获取包括大小和特征在内的终端类型,并设置终端支持的 curses 环境。`cbreak()` 函数禁用行缓冲并设置 curses 每次只接受一个字符。`noecho()` 函数告诉 curses 不要把输入回显到屏幕上。而 `clear()` 函数清空了屏幕: ``` initscr(); cbreak(); noecho(); clear(); ``` 之后程序设置了三个定义三角的顶点。注意这里使用的 `LINES` 和 `COLS`,它们是由 `initscr()` 来设置的。这些值告诉程序在终端的行数和列数。屏幕坐标从 `0` 开始,所以屏幕左上角是 `0` 行 `0` 列。屏幕右下角是 `LINES - 1` 行,`COLS - 1` 列。为了便于记忆,我的程序里把这些值分别设为了变量 `maxlines` 和 `maxcols`。 在屏幕上绘制文字的两个简单方法是 `addch()` 和 `addstr()` 函数。也可以使用相关的 `mvaddch()` 和 `mvaddstr()` 函数可以将字符放到一个特定的屏幕位置。我的程序在很多地方都用到了这些函数。首先程序绘制三个定义三角的点并标记为 `'0'`,`'1'` 和 `'2'`: ``` mvaddch(y[0], x[0], '0'); mvaddch(y[1], x[1], '1'); mvaddch(y[2], x[2], '2'); ``` 为了绘制任意的一个初始点,程序做了类似的一个调用: ``` mvaddch(yi, xi, '.'); ``` 还有为了在谢尔宾斯基三角形递归中绘制连续的点: ``` mvaddch(yi, xi, '*'); ``` 当程序完成之后,将会在屏幕左下角(在 `maxlines` 行,`0` 列)显示一个帮助信息: ``` mvaddstr(maxlines, 0, "Press any key to quit"); ``` 注意 curses 在内存中维护了一个版本的屏幕显示,并且只有在你要求的时候才会更新这个屏幕,这很重要。特别是当你想要向屏幕显示大量的文字的时候,这样程序会有更好的性能表现。这是因为 curses 只能更新在上次更新之后改变的这部分屏幕。想要让 curses 更新终端屏幕,请使用 `refresh()` 函数。 在我的示例程序中,我选择在“绘制”每个谢尔宾斯基三角形中的连续点时更新屏幕。通过这样做,用户可以观察三角形中的每次迭代。(LCTT 译注:由于 CPU 太快,迭代过程执行就太快了,所以其实很难直接看到迭代过程) 在退出之前,我使用 `getch()` 函数等待用户按下一个键。然后我调用 `endwin()` 函数退出 curses 环境并返回终端程序到一般控制。 ``` getch(); endwin(); ``` ### 编译和示例输出 现在你已经有了你的第一个 curses 示例程序,是时候编译运行它了。记住 Linux 操作系统通过 ncurses 库来实现 curses 功能,所以你需要在编译的时候通过 `-lncurses`来链接——例如: ``` $ ls getrandom_int.c getrandom_int.h triangle.c $ gcc -Wall -lncurses -o triangle triangle.c getrandom_int.c ``` (LCTT 译注:此处命令行有问题,`-lncurses` 选项在我的 Ubuntu 16.04 系统 + gcc 4.9.3 环境下,必须放在命令行最后,否则找不到库文件,链接时会出现未定义的引用。) 在标准的 80x24 终端运行这个 `triangle` 程序并没什么意思。在那样的分辨率下你不能看见谢尔宾斯基三角形的很多细节。如果你运行终端窗口并设置非常小的字体大小,你可以更加容易地看到谢尔宾斯基三角形的不规则性质。在我的系统上,输出如图 1。 ![](/data/attachment/album/201802/14/232441hbttkoalfofoiyl9.png) *图 1. triangle 程序的输出* 虽然迭代具有随机性,但是每次谢尔宾斯基三角形的运行看起来都会很一致。唯一的不同是最初绘制到屏幕的一些点的位置不同。在这个例子中,你可以看到三角形开始的一个小圆点,在点 1 附近。看起来程序接下来选择了点 2,然后你可以看到在圆点和“2”之间的星号。并且看起来程序随机选择了点 2 作为下一个随机数,因为你可以看到在第一个星号和“2”之间的星号。从这里开始,就不能继续分辨三角形是怎样被画出来的了,因为所有的连续点都属于三角形区域。 ### 开始学习 ncurses 这个程序是一个怎样使用 curses 函数绘制字符到屏幕的简单例子。按照你的程序的需要,你可以通过 curses 做得更多。在下一篇文章中,我将会展示怎样使用 curses 让用户和屏幕交互。如果你对于学习 curses 有兴趣,我建议你去读位于 <ruby> <a href="http://www.tldp.org"> Linux 文档计划 </a> <rt> Linux Documentation Project </rt></ruby>的 Pradeep Padala 写的 [NCURSES Programming HOWTO](http://tldp.org/HOWTO/NCURSES-Programming-HOWTO)。 ### 关于作者 Jim Hall 是一个自由及开源软件的倡议者,他最有名的工作是 FreeDOS 计划,也同样致力于开源软件的可用性。Jim 是在明尼苏达州的拉姆齐县的首席信息官。 --- via: <http://www.linuxjournal.com/content/getting-started-ncurses> 作者:[Jim Hall](http://www.linuxjournal.com/users/jim-hall) 译者:[leemeans](https://github.com/leemeans) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,349
TLP 帮助我们的 Linux 机器节能省电
http://www.linuxandubuntu.com/home/save-some-battery-on-our-linux-machines-with-tlp
2018-02-15T09:27:00
[ "电池", "节能" ]
https://linux.cn/article-9349-1.html
![](/data/attachment/album/201802/15/092727g08uuxsxz6exn0ll.jpg) 我发现 Linux 下电池的寿命普遍要比 Windows 下要短。尽管如此,这可是 Linux,我们总会有有办法的。 现在来讲一下这个名叫 TLP 的小工具,它能帮你的设备省点电。 **TLP - Linux 高级电源管理** 是一个小巧的命令行工具,它通过对 Linux 系统执行一些调整来真正帮助延长电池的使用寿命。 ``` sudo apt install tlp ``` [![install tlp in linux](/data/attachment/album/201802/15/092728neii3i4fwmbbiukw.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/install-tlp-in-linux.jpeg) 对于其他的发行版,你可以阅读其[官方网站](http://linrunner.de/en/tlp/docs/tlp-linux-advanced-power-management.html)上的指南。 安装完成之后,你只有在第一次的时候需要运行下面命令来启动 tlp。TLP 会在下次启动系统时自动运行。 [![start tlp on linux](/data/attachment/album/201802/15/092728se660iub3bjtife0.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/start-tlp-on-linux.jpeg) ​现在 TLP 已经被启动起来了,而且已经设置好了节省电池所需要的默认配置。我们可以查看该配置文件。文件路径为 `/etc/default/tlp`。我们需要编辑该文件来修改各项配置。 配置文件中有很多选项,要启用某个选项的话只需要删除行首的 `#` 就行了。每个选项能够赋予什么值都有说明。下面是你可能会用到的选项: * 自动休眠 USB 设备 * 设定启动时启用/禁用无线设备 * 降低硬盘转速 * 关闭无线设备 * 设置 CPU 以性能优先还是节能优先 ### 结论 ​TLP 是一个超棒的工具,可以延长 Linux 系统的电池使用寿命。我个人的经验是使用 TLP 能延长至少 30-40% 的电池使用寿命。 --- via: <http://www.linuxandubuntu.com/home/save-some-battery-on-our-linux-machines-with-tlp> 作者:[LinuxAndUbuntu](http://www.linuxandubuntu.com) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,350
详解 Ubuntu 和 Arch Linux 双启动
http://www.linuxandubuntu.com/home/dual-boot-ubuntu-and-arch-linux
2018-02-15T10:11:48
[ "双启动", "Arch", "Ubuntu" ]
https://linux.cn/article-9350-1.html
![](/data/attachment/album/201802/15/101149ye1nggmi9qy3rh4e.jpg) Ubuntu 和 Arch Linux 双启动不像听起来那么容易,然而,我将使这个过程尽可能地简单明了。首先,我们需要安装 Ubuntu,然后安装 Arch Linux,因为配置 Ubuntu grub 更容易实现 Ubuntu 和 Arch Linux 双启动。 ### Ubuntu 和 Arch Linux 双启动 你需要准备好以下内容: 1、你需要准备你所选择的 Ubuntu 的特色版本,在这个例子中,我将使用 Ubuntu 17.10 ISO 2、两个优盘 3、Windows 或者 Linux 操作系统的 PC 机 4、Arch Linux ISO 5、基于 Windows 的 Rufus 或是基于 Linux 发行版的 etcher 的两款软件中的一种,要根据自己的系统类型来选择哦。 ### ​安装 Ubuntu ​首先, 利用 Rufus 为 Ubuntu 和 Arch Linux [创建可启动的闪存驱动器](http://www.linuxandubuntu.com/home/etcher-burn-images-to-sd-card-make-bootable-usb)。另外,也可以使用 `etcher` 创建 Ubuntu 和 Arch Linux 的可启动闪存驱动器。 [![Ubuntu 可启动 USB 镜像写入工具](/data/attachment/album/201802/15/101149ft82vam896m6m69h.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/bootable-ubuntu-usb-etcher-image-writer_orig.jpg) 为 Ubuntu 选择 ISO 映像文件,然后选择闪存驱动器,然后单击 `Flash!` 创建可引导的闪存驱动器。等到它完成,瞧!你的可启动闪存驱动器已经准备好使用了。 [![在 linux 下创建 Ubuntu USB 启动程序](/data/attachment/album/201802/15/101150mwnfw1wwi71twzzh.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/make-ubuntu-usb-bootable-in-linux_orig.jpg) 打开你的机器并使用载有 Ubuntu 安装媒体的可启动闪存驱动器进行启动。确保引导到 UEFI 或 BIOS 兼容模式,这取决于您所使用的 PC 的类型。我更喜欢使用 UEFI 来构建新的 PC。 [![live Ubuntu 启动](/data/attachment/album/201802/15/101150ijz8feh88oo0ctez.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/live-ubuntu-boot_orig.jpg) ​在成功启动后,您将看到如上图显示,要求您尝试 Ubuntu 或安装 Ubuntu,选择安装 Ubuntu。 ​ [![从可启动 USB 安装](/data/attachment/album/201802/15/101151pja8a5a9r5h5fhro.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/install-usb-from-live-usb_orig.jpg) 然后检查安装第三方软件的图形和 WiFi 硬件、MP3 和其他媒体。如果你有一个互联网连接,你可以选择在安装 Ubuntu 的时候下载更新,因为它会节省安装时间,并且确保安装的是最新更新。 [![自定义磁盘分区安装 Ubuntu](/data/attachment/album/201802/15/101151d8mmnifr0gqsscst.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/custom-partition-hd-install-ubuntu_orig.jpg) ​然后选择点击“Something else”,这样我们就可以对硬盘进行分区,并预留出 Ubuntu 和 Archlinux 的分区以及它们的交换分区的空间。 ​ [![创建交换分区](/data/attachment/album/201802/15/101151uvuqipbycsvxbpv5.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/create-swap-partition-ubuntu_orig.jpg) ​创建一个交换分区。最好是内存的一半大小。在我的例子中,我有 1 GB 的内存,因此创建一个 512 MB 的交换空间。 [![安装 Ubuntu 到根(/)分区](/data/attachment/album/201802/15/101152cm5166s6gm65uv02.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/install-ubuntu-root-partition_orig.jpg) 然后创建挂载点为 `/` 的分区,并且点击“Install Now”按钮。 [![选择时区](/data/attachment/album/201802/15/101152mo20nrke057xqger.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/select-ubuntu-timezone_orig.jpg) 接下来选择你的位置以选择语言和键盘设置。 [![选择键盘布局](/data/attachment/album/201802/15/101153z7bqqhrs53hh6ppt.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/install-ubuntu-select-location-keyboard-layout_orig.jpg) ​然后创建新用户的用户凭据。 ​ [![创建用户名、系统名并开始安装](/data/attachment/album/201802/15/101153p39f3efikfl313yc.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/create-username-system-name-ubuntu-install_orig.jpg) ​点击“Next”开始安装。 ​ [![ubuntu installation finishing](/data/attachment/album/201802/15/101153sqzwx3g8q8f4uoy0.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/ubuntu-installation-finishing_orig.jpg) ​当安装完成后点击“Restart Now”重启 PC。 [![完成 Ubuntu 安装并重启系统](/data/attachment/album/201802/15/101154aw2f7zx11p0jron7.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/ubuntu-installation-finished_orig.jpg) ​移除安装媒介,按下回车继续。 [![移除安装媒介](/data/attachment/album/201802/15/101154gvk8f5rvcrfv2imv.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/remove-installation-media-after-ubuntu_orig.jpg) 在确认成功安装后,重新启动并利用 Arch Linux 安装媒介引导。 ### ​安装 Arch Linux ​在引导到 Arch Linux 安装媒体时,您应该看到如下所示的初始屏幕。选择 “Boot Arch Linux(x86\_64)”。注意 Arch Linux 更类似于一种 [DIY](http://www.linuxandubuntu.com/home/arch-linux-take-your-linux-knowledge-to-next-level-review)(自我定制)的操作系统。 ​ [![Arch Linux 安装引导菜单](/data/attachment/album/201802/15/101154yciu3cdiliggti34.jpg)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/arch-linux-installation-boot-menu_orig.jpg) 选择之后,它将打开一个`tty1`终端,您将使用它来安装操作系统。 [![tty终端](/data/attachment/album/201802/15/101155l4hhq2g1xy1mm1v1.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/arch-linux-tty1-linux_orig.png) 注意:为了成功安装 Arch Linux,您需要一个互联网连接来下载一些必须的系统安装包。所以我们需要检查一下互联网是否运行正常。输入以下命令到终端以检查网络连接。 ``` ping linuxandubuntu.com -c 4 ``` [![检查互联网连接](/data/attachment/album/201802/15/101155twxcpakr1xa1qaka.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/arch-linux-ping-check-internet-connection_orig.png) ​如果互联网运行正常,你应该得到一个回显,显示发送和接收的数据包的数量。在这种情况下,我们发送了 4 个包,并得到了 4 个反馈,这意味着连接是正常的。 如果想在 Arch Linux 中设置 Wifi,请阅读[本文](http://www.linuxandubuntu.com/home/how-to-setup-a-wifi-in-arch-linux-using-terminal)以在 Arch Linux 中配置 Wifi。 ​ ​接下来,我们需要选择之前在安装 Ubuntu 时预留出的空闲分区。 ``` fdisk -l ``` ​上面的命令应该显示可用的磁盘分区在哪里。您应该能看到 Ubuntu 分区以及预留的空闲空间。我们将使用 `cfdisk`命令进行分区。 ``` cfdisk ``` [![利用cfdisk命令安装 Arch 分区](/data/attachment/album/201802/15/101155ip31forbzp6f6o6b.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/install-arch-partition-disk-with-cfdisk_orig.png) 执行命令后将看到分区情况。选择其它已分配分区下面的空闲空间。 您需要选择 “New”,然后输入分区大小。 [![为 Archlinux 分区](/data/attachment/album/201802/15/101156yiuvwraszi6ku6ae.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/partition-free-space-swap-arch-linux_orig.png) 例如,9.3G - G 表示千兆字节。 [![挂载 Arch Linux 分区](/data/attachment/album/201802/15/101156q613z03evnyqgvjz.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/install-arch-linux-partition_orig.png) 如下图所示,选择“primary”进行分区 [![将 Arch Linux 的根(root)分区设置成主分区](/data/attachment/album/201802/15/101157hlsznshszobhlgbl.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/make-arch-linux-root-as-primary-partition_orig.png) 然后选择写分区条目。 [![选择分区安装 Arch](/data/attachment/album/201802/15/101157uh1ltze0l0w2ch0e.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/select-partition-to-install-arch_orig.png) ​键入“yes”,以确认写入分区表。 ​ [![确认创建分区并安装 Arch Linux](/data/attachment/album/201802/15/101157p6xcxxxh7zw7j7n6.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/install-arch-linux-confirm-create-partition_orig.png) 然后选择 “Quit”(退出)选项。 [![退出 Arch Linux 的‘cfdisk’](/data/attachment/album/201802/15/101158as5lvnvyx9s7znsl.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/quit-cfdisk-arch-linux_orig.png) 然后键入: ``` fdisk -l ``` ​确认修改。 [![确认分区修改](/data/attachment/album/201802/15/101158m9szsfg2swishv1v.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/confirm-partition-changes_orig.png) ​然后使用磁盘分区命令: ​ ``` mkfs.ext4 /dev/sda3 ``` ​确保您选择的分区是我们创建的最后一个分区,这样我们就不会破坏 Ubuntu 分区。 ​ [![完成 Arch Linux 分区安装](/data/attachment/album/201802/15/101158vzs4du3osi5hol65.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/complete-arch-linux-installation-partition_orig.png) ​然后使用以下命令安装这个分区: ​ ``` mount /dev/sda3 /mnt ``` [![安装基础分区](/data/attachment/album/201802/15/101159eznmnhf90uhdfmhm.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/mount-base-partition-in-arch-linux.png) 用下面命令创建“home”目录: ``` mkdir .mnt/home ``` [![安装家目录](/data/attachment/album/201802/15/101159bv72blxvkslvw0ll.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/mount-home-partition-arch-linux.png) ​用以下命令安装“home”目录到这个分区上: ``` mount /dev/sda3 /mnt/home ``` [![安装家目录](/data/attachment/album/201802/15/101159xhdik647ny466h4l.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/make-mount-home-directory.png) 现在使用以下命令安装 Archlinux 的基本系统: ``` pacstrap /mnt base ``` 请确保网络连接正常。 ​ 接下来开始下载和配置安装所用时间取决于你的网速。 [![安装Arch Linux 基础系统](/data/attachment/album/201802/15/101200k4aala2s6b20bz0p.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/install-arch-linux-base.png) 这一步骤完成后,将完成 Archlinux 基本安装。 Arch Linux 基础系统安装完成后,使用以下命令创建一个 `fstab` 文件: ``` genfstab -U /mnt >> /mnt/etc/fstab ``` [![创建 fstab文件](/data/attachment/album/201802/15/101200xhjfeh3k1heze3jk.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/create-fstab-file-in-arch-linux.png) 在此之后,您需要验证`fstab`文件,使用下面命令: ``` cat /mnt/etc/fstab ``` [![查看 fstab 文件的终端显示](/data/attachment/album/201802/15/101200tgqjojjj989sqojg.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/cat-fstab-file-data-terminal.png) ### ​配置 Arch Linux 的基础配置 您将需要在安装时配置以下内容: 1. 系统语言和系统语言环境 2. 系统时区 3. Root 用户密码 4. 设置主机名 首先,您需要使用以下命令将`root`切换为新安装的基础系统用户: ``` arch-chroot /mnt ``` #### 1. 系统语言和系统语言环境 然后必须配置系统语言。必须取消对 en\_Utf-8 UTF-8的注释,并加载到文件 `/etc/local.gen` 中。 键入: ``` nano /etc/local.gen ``` 然后将 en\_UTF-8 UTF-8 取消注释。 键入命令: ``` locale-gen ``` 生成本地化设置如下: [![生成本地化配置](/data/attachment/album/201802/15/101200mk1qzqznkx3tlqte.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/generate-localization-arch-linux.png) 相应的需要在 `locale.conf` 文件中配置 LANG 变量。例如: ``` nano /etc/locale.conf ``` ​修改为: ``` LANG=en_US.UTF-8 ``` 配置键盘布局,则在文件 `vconsole.conf` 中进行更改,如下操作: ``` nano /etc/vconsole.conf ``` ​修改为: ``` KEYMAP=us-eng ``` #### 2. 系统时区 ​配置时区需要利用以下命令实现: ``` ln -sf /usr/share/zoneinfo/Region/City /etc/localtime ``` 要查看可用时区,可以在终端使用以下命令: 注意可选时区在屏幕截图中显示为蓝色: ``` ls /usr/share/zoneinfo ``` [![配置时区文件](/data/attachment/album/201802/15/101201wspsgwqu9b9xu1e8.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/setup-zonefile-in-arch-linux.png) [![配置地区](/data/attachment/album/201802/15/101201tkuk87hjfk7djjj2.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/setup-country-zonefile_orig.png) 运行 `hwclock` 命令来生成 `/etc/adjtime`(假设硬件时钟被设置为 UTC): ``` # hwclock --systohc ``` #### 3. 配置 root 用户密码 ​要为 Arch Linux 系统用户 root 设置密码,请使用: ``` passwd ``` ​为 root 用户提供一个新的密码并确认密码使其生效。 [![配置系统用户root密码](/data/attachment/album/201802/15/101202yulu9yjbyjjlbsbh.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/setup-arch-linux-root-password.png) #### 4. 配置主机名和网络 ​需要创建主机名文件: ``` nano /etc/hostname ``` [![配置主机名](/data/attachment/album/201802/15/101202hyagw8dgakaaazkx.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/set-arch-linux-hostname.png) 将名字更改为您的用户名: [![set arch linux username](/data/attachment/album/201802/15/101202d5cbd066m0405465.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/set-arch-linux-username.png) 然后向主机添加一个匹配的条目: ``` nano /etc/hosts ``` ``` 127.0.0.1 localhost.localdomain localhost ::1 localhost.localdomain localhost 127.0.1.1 LinuxandUbuntu.localdomain LinuxandUbuntu ``` 您需要使网络保持连接,然后使用: ``` systemctl enable dhcpd ``` #### 配置 Grub 然后重启机器,进入 Ubuntu 配置 grub。 你可以键入: ``` reboot ``` [![安装完成后重启](/data/attachment/album/201802/15/101202rokdiwwwm7mooiig.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/reboot-system-after-arch-linux-installation.png) Arch Linux 仍然没有出现,因此我们需要在 Ubuntu 中使用 `update-grub` 来安装它。 [![Ubuntu grub 菜单](/data/attachment/album/201802/15/101203zvarrlirrauvz3ai.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/edited/ubuntu-grub-menu.png) 在Ubuntu中打开终端,输入: ``` sudo update-grub ``` 这将更新 grub,添加 Arch Linux 记录。 ### 小结 祝贺您成功地将 Ubuntu 和 Arch Linux 设置为双引导。Ubuntu 安装很简单,但是 Arch Linux 安装对新的 Linux 用户来说是一个挑战。我试着让这个教程变得简单。但是如果你对这篇文章有任何疑问,请在评论部分告诉我。还可以与您的朋友分享这篇文章,并帮助他们学习 Linux。 --- via: <http://www.linuxandubuntu.com/home/dual-boot-ubuntu-and-arch-linux> 作者:[LinuxAndUbuntu](http://www.linuxandubuntu.com) 译者:[stevenzdg988](https://github.com/stevenzdg988) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,351
谨慎使用 Linux find 命令
https://www.networkworld.com/article/3233305/linux/using-the-linux-find-command-with-caution.html
2018-02-15T18:48:41
[ "find" ]
https://linux.cn/article-9351-1.html
> > 当使用 Linux 下的 find 命令时,请使用 -ok 选项来避免文件被意外删除,这个选项会在移除任何文件之前都会请求你的许可。 > > > ![](/data/attachment/album/201802/15/184844iwhl7fwuph7zlvwv.jpg) 最近有朋友提醒我有一个有用的选项来更加谨慎地运行 `find` 命令,它就是 `-ok`。除了一个重要的区别之外,它的工作方式与 `-exec` 相似,它使 `find` 命令在执行指定的操作之前请求权限。 这有一个例子。如果你使用 `find` 命令查找文件并删除它们,你可能使用的是下面的命令: ``` $ find . -name runme -exec rm {} \; ``` 在当前目录及其子目录中中任何名为 “runme” 的文件都将被立即删除 —— 当然,你要有权限删除它们。改用 `-ok` 选项,你会看到类似这样的东西,但 `find` 命令将在删除文件之前会请求权限。回答 `y` 代表 “yes” 将允许 `find` 命令继续并逐个删除文件。 ``` $ find . -name runme -ok rm {} \; < rm ... ./bin/runme > ? ``` ### -execdir 命令也是一个选择 另一个可以用来修改 `find` 命令行为,并可能使其更可控的选项是 `-execdir` 。`-exec` 会运行指定的任何命令,而 `-execdir 则从文件所在的目录运行指定的命令,而不是在运行`find` 命令的目录运行指定的命令。这是两个它的例子: ``` $ pwd /home/shs $ find . -name runme -execdir pwd \; /home/shs/bin ``` ``` $ find . -name runme -execdir ls \; ls rm runme ``` 到现在为止还挺好。但要记住的是,`-execdir` 也会在匹配文件的目录中执行该命令。如果运行下面的命令,并且目录包含一个名为 “ls” 的文件,那么即使该文件*没有*执行权限,它也将运行该文件。使用 `-exec` 或 `-execdir` 类似于通过 `source` 来运行命令。 ``` $ find . -name runme -execdir ls \; Running the /home/shs/bin/ls file ``` ``` $ find . -name runme -execdir rm {} \; This is an imposter rm command ``` ``` $ ls -l bin total 12 -r-x------ 1 shs shs 25 Oct 13 18:12 ls -rwxr-x--- 1 shs shs 36 Oct 13 18:29 rm -rw-rw-r-- 1 shs shs 28 Oct 13 18:55 runme ``` ``` $ cat bin/ls echo Running the $0 file $ cat bin/rm echo This is an imposter rm command ``` ### -okdir 选项也会请求权限 要更谨慎,可以使用 `-okdir` 选项。类似 `-ok`,该选项将请求权限来运行该命令。 ``` $ find . -name runme -okdir rm {} \; < rm ... ./bin/runme > ? ``` 你也可以小心地指定你想用的命令的完整路径,以避免像上面那样的冒牌命令出现的任何问题。 ``` $ find . -name runme -execdir /bin/rm {} \; ``` `find` 命令除了默认打印之外还有很多选项,有些可以使你的文件搜索更精确,但谨慎一点总是好的。 在 [Facebook](https://www.facebook.com/NetworkWorld/) 和 [LinkedIn](https://www.linkedin.com/company/network-world) 上加入 Network World 社区来进行评论。 --- via: <https://www.networkworld.com/article/3233305/linux/using-the-linux-find-command-with-caution.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 译者:[geekpi](https://github.com/geekpi) 校对:[Locez](https://github.com/locez) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,352
在 Linux 上安装和使用 Docker
https://www.linux.com/learn/intro-to-linux/2017/11/how-install-and-use-docker-linux
2018-02-15T19:06:07
[ "Docker" ]
https://linux.cn/article-9352-1.html
![](/data/attachment/album/201802/15/190609ee2ru2cduc5puinu.jpg) 容器现在风靡于 IT 界 —— 这很好理解。容器是轻量级的,包含应用运行所需所有东西(代码、库、运行时环境、系统设置,以及依赖关系)的独立的包。每个容器都部署于它自己的 CPU、内存、块 I/O,以及网络资源上,所有这些都不依赖于某个内核和操作系统。这也是容器与虚拟机之间最大的不同;相比之下,虚拟机是一个运行于宿主机操作系统上的完整的操作系统平台,而容器不是。 容器允许你以一种前所未有的方式扩展交付能力(不管内部还是外部的)。例如,你可以快速部署多个 NGINX 实例(甚至可以应用于多个不同的阶段 —— 比如开发和生产阶段)。跟虚拟机不同,容器不会消耗太多系统资源。 [Docker](https://www.docker.com/) 使得创建、部署,和管理容器变得特别简单。更好的是,安装和使用 Docker 在 Linux 平台上特别的方便。 我将会向你演示在 Linux 上安装 Docker 是多么方便,同时带你入门 Docker。我的演示平台是 [Ubuntu 16.04 Server](http://releases.ubuntu.com/16.04/),但流程在大多数其它 Linux 平台都差不多。 我这里假设你已经启动了 Ubuntu Server 16.04。 ### 安装 由于 Ubuntu Server 16.04 缺少图形界面,我会完全通过命令行来安装和使用 Docker。在你安装前,你需要更新 `apt` 然后进行必要的升级。一定要注意,若系统内核升级了,你会需要重启系统。因此最好挑个服务器能重启的时间进行。 运行下面命令更新 `apt`: ``` sudo apt update ``` 完成后,使用命令升级系统: ``` sudo apt upgrade ``` 若内核升级了,你需要用下面命令重启服务器: ``` sudo reboot ``` 若内核没有升级,你就可以安装 Docker 了(无需重启)。安装 Docker 的命令为: ``` sudo apt install docker.io ``` 若你使用的是其它 Linux 发行版,当尝试用相应的包管理器来安装时却发现没有 `docker.io` 包,则你应该安装 `docker` 包。例如,在 [Fedora](https://getfedora.org/) 上安装应该用命令: ``` sudo dnf install docker ``` 若你使用的是 CentOS 7,那么最好使用安装脚本来安装 docker。首先使用命令 `sudo yum check-update` 更新系统。升级完后,输入下面命令来下载并运行所需的脚本: ``` curl -fsSL https://get.docker.com/ | sh ``` 默认情况下,只有管理员权限能够运行 docker 命令。考虑到安全问题,你不会想用 root 用户或使用 `sudo` 来运行 Docker 的。要解决这个问题,你需要将自己的用户加入到 docker 组中。命令如下: ``` sudo usermod -a -G docker $USER ``` 完成操作后,登出系统然后再重新登录,应该就搞定了。不过若你的平台是 Fedora,则添加用户到 docker 组时会发现这个组是不存在的。那该怎么办呢?你需要首先创建这个组。命令如下: ``` sudo groupadd docker && sudo gpasswd -a ${USER} docker && sudo systemctl restart docker newgrp docker ``` 登出后再登录。就可以开始用 Docker 了。 ### 启动,暂停以及启用 Docker 安装好 Docker 后,你可以让系统在启动时自动启动 Docker 守护进程。使用下面两个命令来实现这一点: ``` sudo systemctl start docker sudo systemctl enable docker ``` 若需要暂停或重启 Docker 守护进程,则命令为: ``` sudo systemctl stop docker sudo systemctl restart docker ``` 现在可以用 Docker 来部署容器了。 ### 拉取镜像 对 Docker 来说,镜像是构建容器的基石。你可以拉下一个镜像(比如 [NGINX](https://www.nginx.com/))然后根据这个镜像部署任意多个容器出来。使用镜像前,你首先需要把镜像拉取到系统中。镜像从注册仓库中拉取,默认情况下安装好的 Docker 包含了一个默认的注册仓库 [Docker Hub](https://hub.docker.com/) —— 这个注册仓库包含了大量别人所贡献的镜像(既包括官方的镜像,也包括用户自己贡献的镜像)。 假设你想要拉取一个 Nginx Web 服务器相关的镜像。在开始拉取前,先检查一下系统中已经有了哪些镜像。输入 `docker images` 命令你会发现现在还没有镜像存在(图 1)。 ![Docker](/data/attachment/album/201802/15/190610zkzgts0lk0519xwd.jpg "Docker") *图 1:还没有镜像。* 让我们来拉取一个镜像。使用下面命令可以从 Docker Hub 中下载 Nginx 镜像: ``` docker pull nginx ``` 上面命令会从 Docker Hub 下载最新的(官方的) Nginx 镜像。现在再运行 `docker images` 命令就能看到有列出镜像了(图 2)。 ![Docker](/data/attachment/album/201802/15/190610rcjqujoejbujanvr.jpg "Docker") *图 2:NGINX 镜像已经被拉取下来了。* 注意到我这里说的是“官方” Nginx 镜像了吗?在 Docker Hub 上有很多的非官方 Nginx 镜像。这些非官方镜像都是基于各种不同的目的而创建出来的。你可以使用下面过命令来搜索 Docker Hub 中的所有 Nginx 镜像: ``` docker search nginx ``` 你会发现(图 3 中),有很多基于不同目的所创建的 Nginx 镜像(反向代理、PHP-FPM(LCTT 译注:<ruby> FastCGI 进程管理器 <rt> FastCGI Process Manager </rt></ruby>是一个 PHPFastCGI 管理器,旨在将 FastCGI 进程管理整合进 PHP 包中)功能、LetsEncrypt(LCTT 译注:由 ISRG 提供的免费 SSL 项目),Bitnami,在树莓派上使用的 Nginx 和 Drupal,等等很多很多)。 ![Docker hub](/data/attachment/album/201802/15/190611t42a9cttzc59ckvc.jpg "Docker hub") *图 3:Docker Hub 上找到的各种 NGINX 镜像。* 假设,你想要下载内建有反向代理功能的 Nginx 镜像,有个非官方的镜像 jwilder/nginx-proxy。因此输入下面命令来拉取这个镜像: ``` docker pull jwilder/nginx-proxy ``` 再输入 `docker images` 命令来查看新拉下来的这个镜像(图 4)。 ![Nginx](/data/attachment/album/201802/15/190611y1cm9ggcw707w9wz.jpg "Nginx") *图 4:已经有了两种不同的 NGINX 镜像了。* 处于谨慎考虑,我建议只使用官方镜像,毕竟你无法确定非官方镜像是否包含了恶意代码。 有了镜像后就可以用它来部署容器了。下次我们再聊聊如何通过这些 Nginx 镜像来发布容器。 Docker 是一个超级强力的系统可以让你的工作更简单,让你的公司更具有伸缩性,也更灵活。想知道 Docker 还能做什么,运行 `man docker` 然后阅读它的帮助文档吧。 --- via: <https://www.linux.com/learn/intro-to-linux/2017/11/how-install-and-use-docker-linux> 作者:[Jack Wallen](https://www.linux.com/users/jlwallen) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,353
我是被 “root@notty” 黑了吗?
http://www.sysadminworld.com/2011/ps-aux-shows-sshd-rootnotty/
2018-02-16T20:12:50
[ "tty", "ps" ]
https://linux.cn/article-9353-1.html
![](/data/attachment/album/201802/16/201244lhzdhhc99jtjn90n.jpg) 当你在 `ps aux` 的输出中看到 `sshd:root@notty` 时会觉得很奇怪吧,`notty` 算是哪门子的主机,是不是黑客计算机的名字啊。不过不用担心;`notty` 仅仅是表示 没有 tty 而已。 当你在本地登录 Linux 机器时,登录终端会在进程列表中显示为 `tty`( 比如,tty7)。若你通过 ssh 登录一台远程服务器,则会看到类似 `root@pts/0` 这样的东西。 而若某个连接是由 sftp 或者是由 scp 拷贝文件而创建的,则该连接会会显示成没有 tty (notty)。 如果你仍然想知道服务器上发生了什么事情,可以检查 `ps auxf` 的输出来查看进程树,或者运行 `netstat -vatn` 来检查所有的 TCP 连接。 --- via: <http://www.sysadminworld.com/2011/ps-aux-shows-sshd-rootnotty/> 作者:[sysadminworld](http://www.sysadminworld.com) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
302
Moved Temporarily
null
9,354
如何在 Linux/Unix 之上绑定 ntpd 到特定的 IP 地址
https://www.cyberciti.biz/faq/how-to-bind-ntpd-to-specific-ip-addresses-on-linuxunix/
2018-02-16T20:59:16
[ "ntp" ]
https://linux.cn/article-9354-1.html
默认的情况下,我们的 ntpd/NTP 服务器会监听所有的端口或者 IP 地址,也就是:`0.0.0.0:123`。 怎么才可以在一个 Linux 或是 FreeBSD Unix 服务器上,确保只监听特定的 IP 地址,比如 `localhost` 或者是 `192.168.1.1:123` ? NTP 是<ruby> 网络时间协议 <rt> Network Time Protocol </rt></ruby>的首字母简写,这是一个用来同步两台电脑之间时间的协议。ntpd 是一个操作系统守护进程,可以设置并且保证系统的时间与互联网标准时间服务器同步。 ![](/data/attachment/album/201802/16/205909z7iy3yhnfineelif.jpg) NTP 使用 `/etc/directory` 之下的 `ntp.conf` 作为配置文件。 ### /etc/ntp.conf 之中的端口指令 你可以通过设置端口命令来防止 ntpd 监听 `0.0.0.0:123`,语法如下: ``` interface listen IPv4|IPv6|all interface ignore IPv4|IPv6|all interface drop IPv4|IPv6|all ``` 上面的配置可以使 `ntpd` 监听那个地址或者不出来任何请求而直接丢弃。`ignore` 会防止打开匹配的地址,`drop` 会导致 ntpd 打开该地址并丢弃所有接收到的包,而不做任何检查。举个例子,如果要忽略所有端口之上的监听,加入下面的语句到 `/etc/ntp.conf`: ``` interface ignore wildcard ``` 如果只监听 127.0.0.1 和 192.168.1.1 则是这样: ``` interface listen 127.0.0.1 interface listen 192.168.1.1 ``` 这是我 FreeBSD 云服务器上的样例 `/etc/ntp.conf` 文件: ``` $ egrep -v '^#|$^' /etc/ntp.conf ``` 样例输出为: ``` tos minclock 3 maxclock 6 pool 0.freebsd.pool.ntp.org iburst restrict default limited kod nomodify notrap noquery nopeer restrict -6 default limited kod nomodify notrap noquery nopeer restrict source limited kod nomodify notrap noquery restrict 127.0.0.1 restrict -6 ::1 leapfile "/var/db/ntpd.leap-seconds.list" interface ignore wildcard interface listen 172.16.3.1 interface listen 10.105.28.1 ``` ### 重启 ntpd 在 FreeBSD Unix 之上重新加载/重启 ntpd: ``` $ sudo /etc/rc.d/ntpd restart ``` 或者 [在 Debian 和 Ubuntu Linux 之上使用下面的命令](https://www.cyberciti.biz/faq/restarting-ntp-service-on-linux/): ``` $ sudo systemctl restart ntp ``` 或者 [在 CentOS/RHEL 7/Fedora Linux 之上使用下面的命令](https://www.cyberciti.biz/faq/restarting-ntp-service-on-linux/): ``` $ sudo systemctl restart ntpd ``` ### 校验 使用 `netstat` 和 `ss` 命令来检查 ntpd 只绑定到了特定的 IP 地址: ``` $ netstat -tulpn | grep :123 ``` 或是: ``` $ ss -tulpn | grep :123 ``` 样例输出: ``` udp 0 0 10.105.28.1:123 0.0.0.0:* - udp 0 0 172.16.3.1:123 0.0.0.0:* - ``` [在 FreeBSD Unix 服务器上使用 sockstat 命令](https://www.cyberciti.biz/faq/freebsd-unix-find-the-process-pid-listening-on-a-certain-port-commands/): ``` $ sudo sockstat $ sudo sockstat -4 $ sudo sockstat -4 | grep :123 ``` 样例输出: ``` root ntpd 59914 22 udp4 127.0.0.1:123 *:* root ntpd 59914 24 udp4 127.0.1.1:123 *:* ``` --- 作者是 nixCraft 的创始人并且是一位经验丰富的系统管理员、DevOps 工程师,也是一名 Linux 操作系统和 Unix shell 脚本的训练师。他为全球不同行业,包括 IT、教育业、安全防护、空间研究和非营利性组织的客户工作。关注他的 [Twitter](https://twitter.com/nixcraft), [Facebook](https://facebook.com/nixcraft), [Google+](https://plus.google.com/+CybercitiBiz)。 --- via: <https://www.cyberciti.biz/faq/how-to-bind-ntpd-to-specific-ip-addresses-on-linuxunix/> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[Drshu](https://github.com/Drshu) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,355
如何使用特殊权限:setuid、setgid 和 sticky 位
https://linuxconfig.org/how-to-use-special-permissions-the-setuid-setgid-and-sticky-bits
2018-02-16T21:19:38
[ "权限" ]
https://linux.cn/article-9355-1.html
![](/data/attachment/album/201802/16/211924c1psmdn0b8szk19m.jpg) ### 目标 了解特殊权限的工作原理,以及如何识别和设置它们。 ### 要求 * [了解标准的 Unix / Linux 权限系统](/article-7460-1.html) ### 难度 简单 ### 约定 * `#` - 要求直接以 root 用户或使用 `sudo` 命令执行指定的命令 * `$` - 用普通的非特权用户来执行指定的命令 ### 介绍 通常,在类 Unix 操作系统上,文件和目录的所有权是基于文件创建者的默认 `uid`(user-id)和 `gid`(group-id)的。启动一个进程时也是同样的情况:它以启动它的用户的 `uid` 和 `gid` 运行,并具有相应的权限。这种行为可以通过使用特殊的权限进行改变。 ### setuid 位 当使用 setuid (设置用户 ID)位时,之前描述的行为会有所变化,所以当一个可执行文件启动时,它不会以启动它的用户的权限运行,而是**以该文件所有者的权限运行**。所以,如果在一个可执行文件上设置了 setuid 位,并且该文件由 root 拥有,当一个普通用户启动它时,它将以 root 权限运行。显然,如果 setuid 位使用不当的话,会带来潜在的安全风险。 使用 setuid 权限的可执行文件的例子是 `passwd`,我们可以使用该程序更改登录密码。我们可以通过使用 `ls` 命令来验证: ``` ls -l /bin/passwd -rwsr-xr-x. 1 root root 27768 Feb 11 2017 /bin/passwd ``` 如何识别 `setuid` 位呢?相信您在上面命令的输出已经注意到,`setuid` 位是用 `s` 来表示的,代替了可执行位的 `x`。小写的 `s` 意味着可执行位已经被设置,否则你会看到一个大写的 `S`。大写的 `S` 发生于当设置了 `setuid` 或 `setgid` 位、但没有设置可执行位 `x` 时。它用于提醒用户这个矛盾的设置:如果可执行位未设置,则 `setuid` 和 `setgid` 位均不起作用。setuid 位对目录没有影响。 ### setgid 位 与 `setuid` 位不同,`setgid` (设置组 ID)位对文件和目录都有影响。在第一个例子中,具有 `setgid` 位设置的文件在执行时,不是以启动它的用户所属组的权限运行,而是**以拥有该文件的组运行**。换句话说,进程的 `gid` 与文件的 `gid` 相同。 当在一个目录上使用时,`setgid` 位与一般的行为不同,它使得在所述目录内创建的文件,不属于创建者所属的组,而是属于父目录所属的组。这个功能通常用于文件共享(目录所属组中的所有用户都可以修改文件)。就像 setuid 一样,setgid 位很容易识别(我们用 test 目录举例): ``` ls -ld test drwxrwsr-x. 2 egdoc egdoc 4096 Nov 1 17:25 test ``` 这次 `s` 出现在组权限的可执行位上。 ### sticky 位 sticky (粘连)位的工作方式有所不同:它对文件没有影响,但当它在目录上使用时,所述目录中的所有文件只能由其所有者删除或移动。一个典型的例子是 `/tmp` 目录,通常系统中的所有用户都对这个目录有写权限。所以,设置 sticky 位使用户不能删除其他用户的文件: ``` $ ls -ld /tmp drwxrwxrwt. 14 root root 300 Nov 1 16:48 /tmp ``` 在上面的例子中,目录所有者、组和其他用户对该目录具有完全的权限(读、写和执行)。sticky 位在可执行位上用 `t` 来标识。同样,小写的 `t` 表示可执行权限 `x`也被设置了,否则你会看到一个大写字母 `T`。 ### 如何设置特殊权限位 就像普通的权限一样,特殊权限位可以用 `chmod` 命令设置,使用数字或者 `ugo/rwx` 格式。在前一种情况下,`setuid`、`setgid` 和 `sticky` 位分别由数值 4、2 和 1 表示。例如,如果我们要在目录上设置 `setgid` 位,我们可以运行: ``` $ chmod 2775 test ``` 通过这个命令,我们在目录上设置了 `setgid` 位(由四个数字中的第一个数字标识),并给它的所有者和该目录所属组的所有用户赋予全部权限,对其他用户赋予读和执行的权限(目录上的执行位意味着用户可以 `cd` 进入该目录或使用 `ls` 列出其内容)。 另一种设置特殊权限位的方法是使用 `ugo/rwx` 语法: ``` $ chmod g+s test ``` 要将 `setuid` 位应用于一个文件,我们可以运行: ``` $ chmod u+s file ``` 要设置 sticky 位,可运行: ``` $ chmod o+t test ``` 在某些情况下,使用特殊权限会非常有用。但如果使用不当,可能会引入严重的漏洞,因此使用之前请三思。 --- via: <https://linuxconfig.org/how-to-use-special-permissions-the-setuid-setgid-and-sticky-bits> 作者:[Egidio Docile](https://linuxconfig.org) 译者:[jessie-pang](https://github.com/jessie-pang) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,356
Linux mkdir 命令的初学者教程
https://www.howtoforge.com/linux-mkdir-command/
2018-02-17T12:47:08
[ "mkdir", "目录" ]
https://linux.cn/article-9356-1.html
![](/data/attachment/album/201802/17/124700v1sssrbsovwoe18y.jpg) 当你使用命令行的时候,无论什么时候,你都位于一个目录中,它告诉了命令行当前所位于的完整目录。在 Linux 中,你可以使用 [rm](/article-9321-1.html) 命令删除目录,但是首先,你需要使用 `mkdir` 命令来创建目录。在这篇教程中,我将使用一些易于理解的例子来讲解这个工具的基本用法。 在开始之前,值得一提的是,这篇教程中的所有例子都已经在 Ubuntu 16.04 LTS 中测试过。 ### Linux mkdir 命令 正如上面所提到的,用户可以使用 `mkdir` 命令来创建目录。它的语法如下: ``` mkdir [OPTION]... DIRECTORY... ``` 下面的内容是 man 手册对这个工具的描述: > > 如果目录还不存在,则创建之。 > > > 下面这些 Q&A 式的例子将能够帮助你更好的理解 `mkdir` 这个命令是如何工作的。 ### Q1. 如何使用 `mkdir` 命令创建目录? 创建目录非常简单,你唯一需要做的就是把你想创建的目录的名字跟在 `mkdir` 命令的后面作为参数。 ``` mkdir [dir-name] ``` 下面是一个简单例子: ``` mkdir test-dir ``` ### Q2. 如何确保当父目录不存在的时候,同时创建父目录? 有时候,我们需要使用一条 `mkdir` 命令来创建一个完整的目录结构,这时候,你只需要使用 `-p` 这个命令行选项即可。 比如,你想创建目录 `dir1/dir2/dir3`,但是,该目录的父目录都不存在,这时候,你可以像下面这样做: ``` mkdir -p dir1/dir2/dir3 ``` [![How to make sure parent directories (if non-existent) are created](/data/attachment/album/201802/17/124712ke4vbazwtebta4eb.png)](https://www.howtoforge.com/images/command-tutorial/big/mkdir-p.png) ### Q3. 如何在创建目录时自定义权限? 默认情况下,`mkdir` 命令创建目录时会把权限设置为 `rwx, rwx, r-x` 。 [![How to set permissions for directory being created](/data/attachment/album/201802/17/124715j7jd9jt9jzc95vth.png)](https://www.howtoforge.com/images/command-tutorial/big/mkdir-def-perm.png) 但是,如果你想自定义权限,那么你可以使用 `-m` 这一命令行选项。 [![mkdir -m command option](/data/attachment/album/201802/17/124716pqzvq22qyxqqytcq.png)](https://www.howtoforge.com/images/command-tutorial/big/mkdir-custom-perm.png) ### Q4. 如何使 `mkdir` 命令显示操作细节? 如果你希望 `mkdir` 命令显示它所执行的操作的完整细节,那么你可以使用 `-v` 这一命令行选项。 ``` mkdir -v [dir] ``` 下面是一个例子: [![How to make mkdir emit details of operation](/data/attachment/album/201802/17/124719w9sdmccbhmbuw2hv.png)](https://www.howtoforge.com/images/command-tutorial/big/mkdir-verbose.png) ### 结论 你已经看到,`mkdir` 是一个非常简单,易于理解和使用的命令。学习这一命令不会遇到任何屏障。在这篇教程中,我们讨论到了它的绝大部分命令行选项。记得练习这些命令,并在日复一日的工作中使用这些命令。如果你想了解关于这一命令的更过内容,请查看它的 [man](https://linux.die.net/man/1/mkdir) 手册。 --- via: <https://www.howtoforge.com/linux-mkdir-command/> 作者:[Himanshu Arora](https://www.howtoforge.com) 译者:[ucasFL](https://github.com/ucasFL) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Linux mkdir Command Explained for Beginners (with examples) At any given time on the command line, you are in a directory. So it speaks for itself how integral directories are to the command line. In Linux, while the rm command lets you delete directories, it's the **mkdir** command that allows you create them in the first place. In this tutorial, we will discuss the basics of this tool using some easy to understand examples. But before we do that, it's worth mentioning that all examples in this tutorial have been tested on Ubuntu 16.04 LTS. ## Linux mkdir command As already mentioned, the mkdir command allows the user to create directories. Following is its syntax: mkdir [OPTION]... DIRECTORY... And here's how the tool's man page describes it: Create the DIRECTORY(ies), if they do not already exist. The following Q&A-styled examples should give you a better idea on how mkdir works. ## Q1. How to create directories using mkdir? Creating directories is pretty simple, all you need to do is to pass the name of the directory you want to create to the mkdir command. mkdir [dir-name] Following is an example: mkdir test-dir ## Q2. How to make sure parent directories (if non-existent) are created in process? Sometimes the requirement is to create a complete directory structure with a single mkdir command. This is possible, but you'll have to use the **-p** command line option. For example, if you want to create dir1/dir2/dir2 when none of these directories are already existing, then you can do this in the following way: mkdir -p dir1/dir2/dir3 ## Q3. How to set permissions for directory being created? By default, the mkdir command sets rwx, rwx, and r-x permissions for the directories created through it. However, if you want, you can set custom permissions using the **-m** command line option. ## Q4. How to make mkdir emit details of operation? In case you want mkdir to display complete details of the operation it's performing, then this can be done through the **-v** command line option. mkdir -v [dir] Here's an example: ## Conclusion So you can see mkdir is a pretty simple command to understand and use. It doesn't have any learning curve associated with it. We have covered almost all of its command line options here. Just practice them and you can start using the command in your day-to-day work. In case you want to know more about the tool, head to its [man page](https://linux.die.net/man/1/mkdir).
9,357
为初学者准备的 Linux rmdir 命令案例教程
https://www.howtoforge.com/linux-rmdir-command/
2018-02-18T09:50:00
[ "rmdir", "目录" ]
https://linux.cn/article-9357-1.html
![](/data/attachment/album/201802/17/125918w3uwdp9b9sebabdi.jpg) 在 Linux 命令行上删除文件和目录,我们已经讨论过 [rm 命令](/article-9321-1.html) 的使用。然而,这里有另一个相关的命令行工具,专门针对目录的删除。这是所指的工具就是 `rmdir`,本教程中,我们将根据一些简单的实例来讨论它。 ### Linux rmdir 命令 见名知意,`rmdir`(remove directory) 命令专门针对删除目录,不过通常目录内空空如也。如下是它的语法: ``` rmdir [OPTION]... DIRECTORY... ``` 下面是 man 文档的说明: > > 如目录为空,则删除之。 > > > 在理解此程序如何工作,下面的 Q&A 风格的案例可能会给您带来更好的灵感。 ### Q1. rmdir 命令如何工作? 这非常直接,只需将目录名作为输入参数传递给它。 比如: ``` rmdir test-dir ``` [![rmdir 命令如何工作](/data/attachment/album/201802/17/125931w7gf7s7gupifjes0.png)](https://www.howtoforge.com/images/command-tutorial/big/rm-basic-usage1.png) ### Q2. 如何让 rmdir 忽略非空目录? 通常情况下,`rmdir` 命令会在您删除非空目录时抛出一个错误。然而,如果需要的话,您可以使用 `--ignore-fail-on-non-empty` 选项,忽略它。 比如说: [![如何让 rmdir 忽视非空目录](/data/attachment/album/201802/17/125931uz7cvhkk0xvqv5hk.png)](https://www.howtoforge.com/images/command-tutorial/big/rmdir-ignore-nonempty.png) ### Q3. 如何让 rmdir 命令移除父目录? 和 [mkdir](/article-9356-1.html) 一样,您可以通过要求 `rmdir` 命令在其父目录执行操作。这意味着,您可以一次性删除目录和目录的上级目录。这个功能可以通过 `-p` 命令选项实现。 比如,下面的命令将会删除 “test” 和 “test-dir” 目录。 ``` rmdir -p test/test-dir/ ``` 注意: 欲此操作生效,所有被删除的父目录都不应该包含要被删除的空目录之外的任何目录。 ### Q4. rmdir 和 rm -r 有何区别? 如果还有印象,您还可以通过提供 `-r` 选项的 `rm` 命令删除目录。那 `rmdir` 和 `rm -r` 区别何在?`rmdir` 仅对空目录生效 —— 您没有办法使用 rmdir 删除非空目录。 因此,`rmdir` 在删除需要检测目录是否为空的情况下,是一个有效的工具。 ### 总结 相信您会认同,`rmdir` 并不是一个难以理解和使用的复杂命令。除此之外,它仅提供少量命令行选项。在此,我们几乎讨论了所有的选项,如果您想掌握的更好,练习在本教程提到的案例即可。关于 `rmdir`,[这里另有 man 文档](https://linux.die.net/man/1/rmdir),备您不时之需。 --- via: <https://www.howtoforge.com/linux-rmdir-command/> 作者:[Himanshu Arora](https://www.howtoforge.com) 译者:[CYLeft](https://github.com/CYLeft) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Linux rmdir Command for Beginners (with Examples) So we've already discussed [the rm command](https://www.howtoforge.com/linux-rm-command/) that's primarily used for deleting files and directories from the Linux command line. However, there's another, related command line utility that is specifically aimed at removing directories. The tool in question is **rmdir**, and in this tutorial, we will discuss the basics of it using some easy to understand examples. ## Linux rmdir command As the name suggests, the rmdir command is focused at removing directories, although empty-ones only. Following is its syntax: rmdir [OPTION]... DIRECTORY... And here's how the man page explains it: Remove the DIRECTORY(ies), if they are empty. The following Q&A-styled examples should give you a good idea on how this utility works. ## Q1. How rmdir works? That's pretty straight forward - just pass the directory name as input to the command. For example: rmdir test-dir ## Q2. How to make rmdir ignore non-empty directories. BY default, the rmdir command throws an error if you try deleting a non-empty directory. However, if you want, you can suppress this behavior of rmdir using the *--ignore-fail-on-non-empty* option. For example: ## Q3. How to make rmdir remove parent directories as well? Just like in the case of [mkdir](https://www.howtoforge.com/linux-mkdir-command/), you can also ask rmdir to perform its operation on parent directories. What that means is, you can also delete parent directories of a directory in one go. This feature is accessible through the -p command line option. For example, the following command will delete both 'test' and 'test-dir' directories. rmdir -p test/test-dir/ **Note**: For this operation to work, all parent directories should not contain anything other than the empty-directory being deleted. ## Q4. What is the difference between rmdir and rm -r ? If you remember, you can also delete directories using the rm command by enabling the -r option it provides. So what's the difference between that and rmdir? Well, the answer is rmdir only works in the case of empty directories - there's no way whatsoever you can use to make rmdir delete non-empty directories. So rmdir is a useful in tool in those situations where you otherwise need to check if a directory is empty before deleting it. ## Conclusion As you'll agree, rmdir isn't a complex command to understand and use. Plus, it offers only a handful command line options. We've discussed almost all of them here, so practice the examples mentioned in this article, and you should be good to go. Just in case you need, [here's the man page](https://linux.die.net/man/1/rmdir) for rmdir.
9,358
在 Linux 上检查网络连接的更多方法
https://www.networkworld.com/article/3233306/linux/more-ways-to-examine-network-connections-on-linux.html
2018-02-17T13:21:04
[ "ip", "ethtool", "traceroute" ]
https://linux.cn/article-9358-1.html
> > 有几个命令可以帮助你在 Linux 系统上看到网络状况,这些包括 ip、ethtool、traceroute、tcptraceroute 和 tcpdump。 > > > ![](/data/attachment/album/201802/17/132109q2w28zeu9m43me9w.jpg) `ifconfig` 和 `netstat` 命令当然非常有用,但还有很多其它命令能帮你查看 Linux 系统上的网络状况。本文探索了一些检查网络连接的非常简便的命令。 ### ip 命令 `ip` 命令显示了许多与你使用 `ifconfig` 命令时的一样信息。其中一些信息以不同的格式呈现,比如显示 `192.168.0.6/24`,而不是 `inet addr:192.168.0.6 Bcast:192.168.0.255`,尽管 `ifconfig` 更适合数据包计数,但 `ip` 命令有许多有用的选项。 首先,`ip a` 命令可以列出所有网络接口的信息。 ``` $ ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 00:1e:4f:c8:43:fc brd ff:ff:ff:ff:ff:ff inet 192.168.0.6/24 brd 192.168.0.255 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::21e:4fff:fec8:43fc/64 scope link valid_lft forever preferred_lft forever ``` 如果你只想看到简单的网络接口列表,你可以用 `grep` 限制它的输出。 ``` $ ip a | grep inet inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host inet 192.168.0.6/24 brd 192.168.0.255 scope global eth0 inet6 fe80::21e:4fff:fec8:43fc/64 scope link ``` 使用如下面的命令,你可以看到你的默认路由: ``` $ ip route show default via 192.168.0.1 dev eth0 192.168.0.0/24 dev eth0 proto kernel scope link src 192.168.0.6 ``` 在这个输出中,你可以看到通过 `eth0` 的默认网关是 `192.168.0.1`,并且本地网络是相当标准的 `192.168.0.0/24`。 你也可以使用 `ip` 命令来启用和禁用网络接口。 ``` $ sudo ip link set eth1 up $ sudo ip link set eth1 down ``` ### ethtool 命令 另一个检查网络非常有用的工具是 `ethtool`。这个命令提供了网络接口上的许多描述性的数据。 ``` $ ethtool eth0 Settings for eth0: Supported ports: [ TP ] Supported link modes: 10baseT/Half 10baseT/Full 100baseT/Half 100baseT/Full 1000baseT/Full Supported pause frame use: No Supports auto-negotiation: Yes Advertised link modes: 10baseT/Half 10baseT/Full 100baseT/Half 100baseT/Full 1000baseT/Full Advertised pause frame use: No Advertised auto-negotiation: Yes Speed: 100Mb/s Duplex: Full Port: Twisted Pair PHYAD: 1 Transceiver: internal Auto-negotiation: on MDI-X: on (auto) Cannot get wake-on-lan settings: Operation not permitted Current message level: 0x00000007 (7) drv probe link Link detected: yes ``` 你也可以使用 `ethtool` 命令来检查以太网驱动程序的设置。 ``` $ ethtool -i eth0 driver: e1000e version: 3.2.6-k firmware-version: 1.4-0 expansion-rom-version: bus-info: 0000:00:19.0 supports-statistics: yes supports-test: yes supports-eeprom-access: yes supports-register-dump: yes supports-priv-flags: no ``` 自动协商的详细信息可以用这样的命令来显示: ``` $ ethtool -a eth0 Pause parameters for eth0: Autonegotiate: on RX: on TX: on ``` ### traceroute 命令 `traceroute` 命令用于显示路由路径。它通过在一系列数据包中设置数据包头的 TTL(生存时间)字段来捕获数据包所经过的路径,以及数据包从一跳到下一跳需要的时间。`traceroute` 的输出有助于评估网络连接的健康状况,因为某些路由可能需要花费更长的时间才能到达最终的目的地。 ``` $ sudo traceroute world.std.com traceroute to world.std.com (192.74.137.5), 30 hops max, 60 byte packets 1 192.168.0.1 (192.168.0.1) 3.691 ms 3.678 ms 3.665 ms 2 10.224.64.1 (10.224.64.1) 26.273 ms 27.354 ms 28.574 ms 3 10.20.0.33 (10.20.0.33) 28.293 ms 30.625 ms 33.959 ms 4 10.20.0.226 (10.20.0.226) 36.807 ms 37.868 ms 37.857 ms 5 204.111.0.132 (204.111.0.132) 38.256 ms 39.091 ms 40.429 ms 6 ash-b1-link.telia.net (80.239.161.69) 41.612 ms 28.214 ms 29.573 ms 7 xe-1-3-1.er1.iad10.us.zip.zayo.com (64.125.13.157) 30.429 ms 27.915 ms 29.065 ms 8 ae6.cr1.dca2.us.zip.zayo.com (64.125.20.117) 31.353 ms 32.413 ms 33.821 ms 9 ae27.cs1.dca2.us.eth.zayo.com (64.125.30.246) 43.474 ms 44.519 ms 46.037 ms 10 ae4.cs1.lga5.us.eth.zayo.com (64.125.29.202) 48.107 ms 48.960 ms 50.024 ms 11 ae8.mpr3.bos2.us.zip.zayo.com (64.125.30.139) 51.626 ms 51.200 ms 39.283 ms 12 64.124.51.229.t495-rtr.towerstream.com (64.124.51.229) 40.233 ms 41.295 ms 39.651 ms 13 69.38.149.18 (69.38.149.18) 44.955 ms 46.210 ms 55.673 ms 14 64.119.137.154 (64.119.137.154) 56.076 ms 56.064 ms 56.052 ms 15 world.std.com (192.74.137.5) 63.440 ms 63.886 ms 63.870 ms ``` ### tcptraceroute 命令 `tcptraceroute` 命令与 `traceroute` 基本上是一样的,只是它能够绕过最常见的防火墙的过滤。正如该命令的手册页所述,`tcptraceroute` 发送 TCP SYN 数据包而不是 UDP 或 ICMP ECHO 数据包,所以其不易被阻塞。 ### tcpdump 命令 `tcpdump` 命令允许你捕获网络数据包来进一步分析。使用 `-D` 选项列出可用的网络接口。 ``` $ tcpdump -D 1.eth0 [Up, Running] 2.any (Pseudo-device that captures on all interfaces) [Up, Running] 3.lo [Up, Running, Loopback] 4.nflog (Linux netfilter log (NFLOG) interface) 5.nfqueue (Linux netfilter queue (NFQUEUE) interface) 6.usbmon1 (USB bus number 1) 7.usbmon2 (USB bus number 2) 8.usbmon3 (USB bus number 3) 9.usbmon4 (USB bus number 4) 10.usbmon5 (USB bus number 5) 11.usbmon6 (USB bus number 6) 12.usbmon7 (USB bus number 7) ``` `-v` 选项控制你看到的细节程度——越多的 `v`,越详细,但超过 3 个 `v` 不会有更多意义。 ``` $ sudo tcpdump -vv host 192.168.0.32 tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes 20:26:31.321816 IP (tos 0x10, ttl 64, id 22411, offset 0, flags [DF], proto TCP (6), length 184) 192.168.0.6.ssh > 192.168.0.32.57294: Flags [P.], cksum 0x8221 (incorrect -> 0x0254), seq 3891093411:3891093555, ack 2388988308, win 329, length 144 20:26:31.321984 IP (tos 0x10, ttl 64, id 22412, offset 0, flags [DF], proto TCP (6), length 200) 192.168.0.6.ssh > 192.168.0.32.57294: Flags [P.], cksum 0x8231 (incorrect -> 0x3db0), seq 144:304, ack 1, win 329, length 160 20:26:31.323791 IP (tos 0x0, ttl 128, id 20259, offset 0, flags [DF], proto TCP (6), length 40) 192.168.0.32.57294 > 192.168.0.6.ssh: Flags [.], cksum 0x643d (correct), seq 1, ack 304, win 385, length 0 20:26:31.383954 IP (tos 0x10, ttl 64, id 22413, offset 0, flags [DF], proto TCP (6), length 248) ... ``` 当你运行像这样的命令时,会看到**非常多**的输出。 这个命令捕获来自特定主机和 `eth0` 上的 `11` 个数据包。`-w` 选项标识保存捕获包的文件。在这个示例命令中,我们只要求捕获 `11` 个数据包。 ``` $ sudo tcpdump -c 11 -i eth0 src 192.168.0.32 -w packets.pcap tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes 11 packets captured 11 packets received by filter 0 packets dropped by kernel ``` ### arp 命令 `arp` 命令将 IPv4 地址映射到硬件地址。它所提供的信息也可以在一定程度上用于识别系统,因为网络适配器可以告诉你使用它们的系统的一些信息。下面的第二个 MAC 地址,以 `f8:8e:85` 开头,很容易被识别出是 Comtrend 路由器。 ``` $ arp -a ? (192.168.0.12) at b0:c0:90:3f:10:15 [ether] on eth0 ? (192.168.0.1) at f8:8e:85:35:7f:b9 [ether] on eth0 ``` 上面的第一行显示了系统本身的网络适配器的 MAC 地址。该网络适配器似乎已由台湾 Chicony 电子公司制造。你可以很容易地在网上查找 MAC 地址关联,例如来自 Wireshark 的这个工具 —— <https://www.wireshark.org/tools/oui-lookup.html> 。 --- via: <https://www.networkworld.com/article/3233306/linux/more-ways-to-examine-network-connections-on-linux.html> 作者:[Sandra Henry-Stocker](https://www.networkworld.com/author/Sandra-Henry_Stocker/) 译者:[kimii](https://github.com/kimii) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
404
Not Found
null
9,359
25 个学习 Linux 的免费资源(英文)
https://itsfoss.com/learn-linux-for-free/
2018-02-17T19:46:00
[ "电子书", "资源" ]
https://linux.cn/article-9359-1.html
> > 在这篇文章中,我将与你分享免费学习 Linux 的最佳资源。这个集合包括了网站、在线视频课程和免费电子书。 > > > **如何学习 Linux ?** 这可能是 Facebook Linux 用户组中最常见的问题。 “如何学习 Linux”这个看起来简单的问题的答案并不简单。 问题在于不同的人对于学习 Linux 有不同的意义。 * 比如有人从来没有使用过 Linux,无论是命令行还是桌面版本,那个人可能只是想知道更多关于它的信息。 * 比如有人使用 Windows 作为桌面,但必须在工作中使用 Linux 命令行,那个人可能对学习 Linux 命令感兴趣。 * 比如有人已经使用过一段时间的 Linux,而且懂得一些基础,但他/她可能想要更上一层楼。 * 比如有人只是对 Linux 特定的发行版本感兴趣。 * 比如有人想要提升或学习几乎与 Linux 命令行差不多的 Bash 脚本。 * 比如有人想要从事一个 Linux 系统管理员的职业,或者想提高他/她的系统管理技能。 你看,“我如何学习 Linux”的答案取决于你追求什么样的 Linux 知识。为此,我收集了大量能用来学习 Linux 的资源。 这些免费的资源包括电子书、视频课程、网站等。这些资源分成几个子类别,以便当你试图学习 Linux 时可以很容易地找到你想要的东西。 再者,这里没有学习 Linux 的最好方式。这完全取决于你如何去学习 Linux,通过在线门户网站、下载电子书、视频课程或者其他。 让我们看看你能如何学习 Linux。 **免责声明** : 这里列举的所有书都可以合法的下载。 据我所知,这里提到的资源都是官方的资源。但是,如果你发现它不是,请让我知道以便我可以采取适当的措施。 ![](/data/attachment/album/201802/17/195021c14bpthi1qqqy4cb.png) ### 1. 对于完全新手学习 Linux 的免费资料 也许你刚刚从朋友那里或者从网上的讨论中听到了 Linux。关于 Linux 的炒作让你对 Linux 很感兴趣,你被互联网上的大量信息所淹没,不知道在哪里寻找更多的关于 Linux 的知识。 不用担心,我们中的大多数,即使不是全部,都经过过这个阶段。 #### Linux 基金会关于 Linux 的介绍 [视频课程] 如果你对于什么是 Linux 和如何开始学习 Linux 完全没有概念的话,我建议你从学习 [Linux 基金会](https://www.linuxfoundation.org/)在 [edX](https://www.edx.org) 上提供的免费的视频课程开始。它可以看做“维护” Linux 的组织的一个官方课程——是的,这个组织是由 Linux 之父 [Linus Torvalds](https://www.youtube.com/watch?v=eE-ovSOQK0Y) 所背书的。 * [Introduction To Linux](https://www.edx.org/course/introduction-linux-linuxfoundationx-lfs101x-0) #### Linux 旅程 [网站] 不是官方的,也许不是很受欢迎。但是这个小网站对于初学者来说是一个 Linux 学习的完美场所。 该网站设计精美,并根据主题组织得很好。它给你提供了能够在阅读完一个片段或章节后的进行的互动式测验。我的建议是收藏这个网站: * [Linux Journey](https://linuxjourney.com/) #### 《5 天学习 Linux》 [电子书] 这本出色的书针对 FOSS 读者来说完全的免费,这完全得感谢 [Linux Training Academy](https://www.linuxtrainingacademy.com/)。 为完全的新手而写,这本免费的 Linux 电子书给了你一个关于 Linux 的概述、常用的 Linux 指令和你开始学习 Linux 所需要的其他东西。 你能够从下面的网页下载该书: * [Learn Linux In 5 Days](https://courses.linuxtrainingacademy.com/itsfoss-ll5d/) #### 《Linux 新手终极指南》 [电子书] 这是一本面向 Linux 初学者的免费下载的电子书。该电子书从解释什么是 Linux 开始,并提供了将 Linux 作为桌面的更多实际使用经验。 您可以从下面的链接下载最新版本的电子书: * [The Ultimate Linux Newbie Guide](https://linuxnewbieguide.org/ulngebook/) ### 2. 初学者进阶的免费书籍 本节列出了那些已经“完成”的 Linux 电子书。 我的意思是,这些之中的大部分就像是专注于 Linux 的每个方面的学术教科书。你可以作为一个绝对的新手阅读这些书,或者你也可以作为一个中级的 Linux 用户来深入学习。即使你已经是专家级,你也可以把它们作为参考。 #### 《Linux 介绍》 [电子书] 《Linux 介绍》是 [Linux 文档计划](http://www.tldp.org/index.html)的免费电子书,而且它是最热门的 Linux 免费电子书之一。即使我认为其中的部分段落需要更新,它仍然是一本非常好的电子书,可以教你 Linux、Linux 的文件系统、命令行、网络和其他相关的东西。 * [Introduction To Linux](http://tldp.org/LDP/intro-linux/intro-linux.pdf) #### 《Linux 基础》 [电子书] 这本由 Paul Cobbaut 编写的免费的电子书可以教你关于 Linux 的历史、安装和你需要知道的基本的 Linux 命令。你能够从下列链接上得到这本书: * [Linux Fundamentals](http://linux-training.be/linuxfun.pdf) #### 《Linux 高级编程》 [电子书] 顾名思义,这是一本面向想要或者正在开发 Linux 软件的高级用户的书。它阐释了那些复杂的功能,比如多进程、多线程、进程间通信以及和硬件设备的交互。 跟着这本书学习会帮你开发一个更快速、更可靠、更安全的使用 GNU/Linux 系统全部功能的项目。 * [Advanced Linux Programming](http://advancedlinuxprogramming.com/alp-folder/advanced-linux-programming.pdf) #### 《LFS》 [电子书] 如果你认为自己对 Linux 有足够的了解,并且你是一个专业人士,那么为什么不创建自己的 Linux 版本呢? Linux From Scratch(LFS)是一个完全基于源代码,为你构建你自定义的 Linux 系统提供手把手的指导。 可以把它叫做 DIY Linux ,它是一个把你的 Linux 专业知识提高到新的高度的方法。 这里有许多的关于这个项目的子项目,你能够在这个网站上查看和下载。 * [Linux From Scratch](http://www.linuxfromscratch.org/) ### 3. 学习 Linux 命令和 Shell 脚本的免费电子书 Linux 的真正强大在于命令行,如果你想要征服 Linux,你必须学习命令行和shell。 事实上,如果你必须在你的工作中使用 Linux 终端,那么熟悉 Linux 命令行实际上会帮助你完成任务,也有可能帮助你提高你的职业生涯(因为你会更有效率)。 在本节中,我们将看到各种 Linux 命令方面的免费电子书。 #### 《GNU/Linux 命令行工具总览》 [电子书] 这本 Linux 文档项目中的电子书是接触 Linux 命令行并开始熟悉 Shell 脚本的好地方。 * [GNU/Linux Command−Line Tools Summary](http://tldp.org/LDP/GNU-Linux-Tools-Summary/GNU-Linux-Tools-Summary.pdf) #### 《GNU Bash 参考手册》 [电子书] 这是一本可以从 [GNU](https://www.gnu.org/home.en.html) 网站下载的免费电子书。 就像名字暗示的那样, 它涉及 Bash Shell (如果我能这么叫的话)。这本书超过了 175 页,而且它包括了许多在 Bash 里和 Linux 有关的主题。 你能够从下面的链接中获取: * [Bash Reference Manual](https://www.gnu.org/software/bash/manual/bash.pdf) #### 《Linux 命令行》 [电子书] 这本 500 多页的由 William Shotts 编写的免费电子书,对于那些认真学习 Linux 命令行的人来说,是一本必须拥有的书。 即使你认为你已经了解了 Linux,你还是会惊讶于这本书能教你很多东西。 它涵盖了从初学者到高级的东西。我敢打赌读完这本书之后你会成为一个更好的 Linux 用户。请下载这本书并且随时携带它。 * [The Linux Command Line](http://linuxcommand.org/tlcl.php) #### 《Bash 入门指南》 [电子书] 如果你想从 Bash 脚本开始,这可能对于你来说是一个很好的助手。 这本电子书也是基于 Linux 文档项目的,它是编写 《Linux 介绍》的电子书的作者(本文前面讨论过)。 * [Bash Guide for Beginners](http://www.tldp.org/LDP/Bash-Beginners-Guide/Bash-Beginners-Guide.pdf) #### 《Bash 脚本高级指南》 [电子书] 如果你认为你已经了解了基本的 Bash 脚本知识,并且你想把你的技能提高到一个新的水平,这本书就是你所需要的。这本书有超过 900 页的各种高级命令和举例。 * [Advanced Bash-Scripting Guide](http://www.tldp.org/LDP/abs/abs-guide.pdf) #### 《AWK 编程语言》 [电子书] 这不是一本很美观的书,但是如果你真的想要深入学习脚本,这本虽旧但是依然很棒的书会很有帮助。 * [The AWK Programming Language](https://ia802309.us.archive.org/25/items/pdfy-MgN0H1joIoDVoIC7/The_AWK_Programming_Language.pdf) #### 《Linux 101 技巧》 [电子书] 这本 270 多页的书来自“The Geek Stuff”,通过易于跟踪学习的例子教给你 Linux 命令行基础。你能够从下列的链接获取: * [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-ebook/) ### 4. 特定发行版的免费学习资料 这个章节专注于特定 Linux 发行版的材料。到目前为止,我们看到的都是以常规的方式学习 Linux,更多的关注于文件系统、命令和其他的核心内容。 这些书,在另一方面,可以被认为是用户手册或者开始学习各种各样的 Linux 发行版的指南。所以如果你正在使用或准备使用一个特定的 Linux 发行版,你可以参考这些资源。是的,这些书更加关注 Linux 桌面。 我还想补充的是,大部分的 Linux 发行版有它们自己的大量的 wiki 或者文档。你能够从网上随时找到它们。 #### 《Ubuntu 用户指南》 [电子书] 不用说,这本书是针对 Ubuntu 用户的。这是一个独立的项目,以免费电子书的形式提供 Ubuntu 的用户指南。它对于每个版本的 Ubuntu 都有更新。 这本书被叫做用户指南因为它是由一步步的指导组成的,而且受众目标是对于 Ubuntu 完全新手的。所以,你会了解到 Unity 桌面,以及怎样逐渐使用它而且查找应用等等。 如果你从来没有使用过 Ubuntu Unity ,那么这是一本你必须拥有的书,因为它帮助你理解怎样在日常中使用 Ubuntu。 * [Ubuntu Manual](https://ubuntu-manual.org/) #### 《面向 Linux Mint:直接告诉我就行!》 [电子书] 一本非常基本的关于 Linux Mint 的电子书。它告诉你怎么样在虚拟机中安装 Linux Mint,怎么样去查找软件,安装更新和自定义 Linux Mint 桌面。 你能够在下面的链接下载电子书: * [Just Tell Me Damnit!](http://downtoearthlinux.com/resources/just-tell-me-damnit/) #### 《Solus Linux 用户指南》 [电子书] 注意!这本书过去是 Solus Linux 的官方用户指南,但是我找不到 Solux 项目的网站上在哪里有提到它。我不知道它是不是已经过时了。尽管如此,反正不要钱,多少学习一点 Solus Linux。 * [Solus Linux User Guide](https://drive.google.com/file/d/0B5Ymf8oYXx-PWTVJR0pmM3daZUE/view) ### 5. 面向系统管理员的免费电子书 这个章节主要关注于系统管理员——开发者的超级英雄。我已经列了一部分会真正帮助那些已经是系统管理者或者想要成为系统管理者的免费的电子书。我还得说,你必须要关注基本的 Linux 命令行,因为它会使你的工作更加简单。 #### 《The Debian 管理手册》 [电子书] 如果你使用 Debian Linux 作为你的服务器,这本书就是你的圣经。这本书从 Debian 的历史、安装、包管理等等开始,接着覆盖一些主题,比如说 [LAMP](https://en.wikipedia.org/wiki/LAMP_(software_bundle))、虚拟机、存储管理和其他核心系统管理。 * [The Debian Administration's Handbook](https://debian-handbook.info/about-the-book/) #### 《高级 Linux 系统管理》 [电子书] 如果在准备 [LPI 认证](https://www.lpi.org/our-certifications/getting-started),那么这本书是一本理想的书。这本书的涉及系统管理员必要的主题,所以了解 Linux 命令行是前置条件。 * [Advanced Linux System Administration](http://www.nongnu.org/lpi-manuals/manual/pdf/GNU-FDL-OO-LPI-201-0.1.pdf) #### 《Linux 系统管理》 [电子书] Paul Cobbaut 编写的另一本免费的电子书。370 页长的的书包括了网络、磁盘管理、用户管理、内核管理、库管理等等。 * [Linux System Administration](http://linux-training.be/linuxsys.pdf) #### 《Linux 服务器》 [电子书] 又一本来自 [linux-training.be](http://linux-training.be/) 的 Paul Cobbaut 编写的电子书。这本书包括了 Web 服务器、MySQL、DHCP、DNS、Samba 和其他文件服务器。 * [Linux Servers](http://linux-training.be/linuxsrv.pdf) #### 《Linux 网络》 [电子书] 网络是系统管理者的面包和黄油,这本也是由 Paul Cobbaut 编写的书是一本好的参考资料。 * [Linux Networking](http://linux-training.be/linuxnet.pdf) #### 《Linux 存储》 [电子书] 这本由 Paul Cobbaut(对,还是他)编写的书详细解释了 Linux 的磁盘管理,而且介绍了许多其他的和存储相关的技术。 * [Linux Storage](http://linux-training.be/linuxsto.pdf) #### 《Linux 安全》 [电子书] 这是这个书单里最后一本由 Paul Cobbaut 编写的书。安全是系统管理员最重要的工作之一。这本书关注文件权限、ACL、SELinux、用户和密码等等。 * [Linux Security](http://linux-training.be/linuxsec.pdf) ### 你有什么最喜爱的 Linux 资料吗? 我知道这是一个不错的免费 Linux 电子书集合,但是它可以做的更好。 如果你有学习 Linux 方面有更大帮助的其它资料,请务必和我们共享。请注意只共享合法的下载资料,以便我可以根据你的建议更新这篇文章而不会有任何问题。 我希望你觉得这篇文章在学习 Linux 时有帮助,欢迎你的反馈。 --- via: <https://itsfoss.com/learn-linux-for-free/> 作者:[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 译者:[yyyfor](https://github.com/yyyfor) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) How to learn Linux? This is perhaps the most commonly asked question in our Facebook group for Linux users. The answer to this simple-looking question ‘how to learn Linux’ is not at all simple. The problem is that different people have different meanings of learning Linux. - If someone has never used Linux, be it the command line or desktop version, that person might just want to know more about it. - If someone uses Windows as the desktop but has to use the Linux command line at work, that person might be interested in learning Linux commands. - If someone has been using Linux for some time and is aware of the basics, they might want to go to the next level. - If someone is just interested in getting your way around a specific Linux distribution. - If someone is trying to improve or learn Bash scripting which is almost synonymous with Linux command line. - If someone is willing to make a career as a Linux SysAdmin or trying to improve his/her sysadmin skills. The answer to “how do I learn Linux” depends on what kind of Linux knowledge you are seeking. And for this purpose, I have collected a bunch of free Linux resources that you could use for learning Linux. ## Best free Linux ebooks Here are a bunch of Linux books you can get for free. Which one is suitable for you? That depends on your requirement. I have put a little description of each book. That will help you in deciding whether you should download the book. ### The Linux Command Line This 500+ pages free eBook by William Shotts is a MUST-HAVE for anyone serious about learning the Linux command line. Even if you think you know things about Linux, you’ll be amazed at how much this book still teaches you. It covers things from beginners to advanced levels. I bet that you’ll be a hell lot of a better Linux user after reading this book. Download it and keep it with you always. ### Introduction to Linux Introduction to Linux is a free eBook from [The Linux Documentation Project](https://tldp.org/) and it is one of the most popular free Linux books out there. Though I think some parts of this book need to be updated, it is still a very good book to teach you about Linux, its file system, command line, networking, and other related stuff. ### Learn Linux in 5 Days This brilliant eBook is available for free exclusively to It’s FOSS readers all thanks to [Linux Training Academy](https://www.linuxtrainingacademy.com/). Written for absolute beginners in mind, this free Linux eBook gives you a quick overview of Linux, common Linux commands, Vim/Nano editors and other things that you need to learn to get started with Linux. ### Linux Fundamentals This free eBook by Paul Cobbaut teaches you about Linux history, and installation and focuses on the basic Linux commands you should know. You can get the book from the link below: ### The Ultimate Linux Newbie Guide This is a free-to-download eBook for Linux beginners. The book starts by explaining what Linux is and then goes on to provide **more practical usage of Linux as a desktop**. You can download the latest version of this eBook from the link below: ### Advanced Linux Programming As the name suggests, this is for advanced users who want to develop software for Linux. It deals with sophisticated features such as multiprocessing, multi-threading, interprocess communication, and interaction with hardware devices. Following the book will help you develop a faster, more reliable and more secure program that uses the full capability of a GNU/Linux system. ### Linux From Scratch If you think you know enough about Linux and are a pro, then why not create your own Linux distribution? Linux From Scratch (LFS) is a project that provides step-by-step instructions for building your own custom Linux system, entirely from source code. Call it DIY Linux but this is a great way to put your Linux expertise to the next level. There are various sub-parts of this project, you can check it out on its website and download the books from there. ### Linux books by Paul Cobbau of linux-training.be linux-training.be is an online portal run by senior Linux user Paul Cobbau. He has written several Linux books and all of them are available for free. What an excellent person. These books range from basic Linux commands to focus on servers, storage, and security. [Linux Fundamentals](http://linux-training.be/linuxfun.pdf) teaches you the fundamentals of Linux. This book is for beginners, novices, and anyone who wants to become a Linux developer or Linux system administrator. It contains essential knowledge, but advanced users will also benefit from this book. [System Administration](http://linux-training.be/linuxsys.pdf) teaches you Linux system administration. Anything related to Linux system management is introduced in this book. [Linux Servers](http://linux-training.be/linuxsrv.pdf) book shows how to set up common services like a web server, a name server, a database server, a DHCP server, a file server and more. [Linux Storage](http://linux-training.be/linuxsto.pdf) explains disk management on Linux in detail and introduces a lot of other storage-related technologies. [Linux Security](http://linux-training.be/linuxsec.pdf) covers topics related to security such as file permissions, acls, SELinux, users and passwords, and more. [Linux Networking](http://linux-training.be/linuxnet.pdf) focuses on all things related to Linux in a network. [Linux Fun](http://linux-training.be/linuxtraining_20211003.pdf) is a new book that goes over 600 pages and it covers the basics of Linux command line, networking, RAID, storage, block devices, systemd and whatnot. An excellent book for your collection. ### GNU/Linux Command−Line Tools Summary This eBook from The Linux Documentation Project is a good place to begin with Linux command line and get acquainted with Shell scripting. ### Bash Reference Manual from GNU This is a free eBook to download from [GNU](https://www.gnu.org/home.en.html). As the name suggests, it deals with Bash Shell (if I can call that). This book has over 175 pages and it covers a number of topics around Linux command line in Bash. ### Bash Guide for Beginners If you just want to get started with Bash scripting, this could be a good companion for you. The Linux Documentation Project is behind this eBook again and it’s the same author who wrote Introduction to Linux eBook (discussed earlier in this article). ### Advanced Bash-Scripting Guide If you think you already know the basics of Bash scripting and want to take your skills to the next level, this is what you need. This book has over 900+ pages of various advanced commands and their examples. ### The AWK Programming Language Not the prettiest book here but if you really need to go deeper with your scripts, this old-yet-gold book could be helpful. ### The Debian Administration’s Handbook If you use Debian Linux for your servers, this is your bible. The [Debian Administration’s Handbook](https://itsfoss.com/debian-administrators-handbook/) starts with Debian history, installation, package management etc and then moves on to cover topics like [LAMP](https://en.wikipedia.org/wiki/LAMP_(software_bundle)), virtual machines, storage management and other core sysadmin stuff. ### Advanced Linux System Administration This is an ideal book if you are preparing for [LPI certification](https://www.lpi.org/our-certifications/getting-started). The book deals straightway to the topics essential for sysadmins. So knowledge of Linux command line is a prerequisite in this case. ## Your favorite Linux learning material? If you have no idea about what Linux is and you want to get started with it, I suggest you to go ahead with the free video course provided by the [Linux Foundation](https://www.linuxfoundation.org/) on [edX](https://www.edx.org/). Consider it an official course by the organization that ‘maintains’ Linux. And yes, it is endorsed by [Linus Torvalds](https://www.youtube.com/watch?v=eE-ovSOQK0Y), the father of Linux himself. [Introduction to LinuxNever learned Linux? Want a refresh? Develop a good working knowledge of Linux using both the graphical interface and command line across the major Linux distribution families.](https://www.edx.org/course/introduction-to-linux)![](https://prod-discovery.edx-cdn.org/media/course/image/5a631d1c-cb20-4cfc-9b49-1cc9c8fc981e-5949e438d0ed.small.png) ![](https://prod-discovery.edx-cdn.org/media/course/image/5a631d1c-cb20-4cfc-9b49-1cc9c8fc981e-5949e438d0ed.small.png) If you are a casual desktop Linux user and want to learn the basics of the command line, explore the Linux Journey portal. The website is designed beautifully and is well organized based on the topics. It also has interactive quizzes you can take after reading a section or chapter. My advice, bookmark this website: If you are looking to build a career as a Linux SysAdmin, I recommend [getting professional certification from The Linux Foundation](https://itsfoss.com/recommends/linux-foundation-certified-sysadmin/), the organization that employs Linux creator Linus Torvalds. You can also check some inexpensive Linux courses on Udemy. So you now have plenty of reading materials. If you want to practice, you can [use one of the online Linux terminals that allow you to run Linux and Bash commands](https://itsfoss.com/online-linux-terminals/). I know that this is a good collection of free Linux eBooks. But this could always be made better. If you have some other resources that could be helpful in [learning Linux](https://itsfoss.com/free-linux-training-courses/), do share with us. Please note to share only the legal downloads so that I can update this article with your suggestion(s) without any problem. [Recommended Books to Learn and Master Linux [For Beginners to Advanced Linux Users]I have written about free Linux books in the past. That article has some good collection of Linux books that are available for free. The saying goes that best things in life are free. That might not be entirely true when it comes to books. There are many excellent Linux](https://itsfoss.com/best-linux-books/)![](https://itsfoss.com/content/images/wordpress/2020/06/best-linux-books-featured-1.jpg) ![](https://itsfoss.com/content/images/wordpress/2020/06/best-linux-books-featured-1.jpg) I hope you find this article helpful in learning Linux. Your feedback is welcome :)
9,360
2018 年度最佳 Linux 笔记本电脑:来自一位 RHCE 的选购指南
https://www.hecticgeek.com/2017/12/best-linux-laptop/
2018-02-18T22:41:00
[ "笔记本" ]
https://linux.cn/article-9360-1.html
![](/data/attachment/album/201802/18/224641tx51k5224x4twxvw.png) 如果你不具备相关的知识和经验,挑选出最适合 Linux 的笔记本电脑,可能是件很困难的事。并且,看上去你买了一台配置、功能、性能都很棒的电脑,但是,却疲于处理各种 Linux 的问题,太难堪了!因此,作为一个 **RedHat 认证工程师**,这篇文章的作者兼博主,也是一个 **有 14 年以上 Linux 使用经验的用户**,我用我掌握的一些知识去为你推荐一些笔记本电脑,我可以保证我推荐的这些电脑,Linux 在它上面会跑的很好。我研究了 20 多个小时之后(通过认真了解硬件详细情况和用户反馈),我选择 [Dell XP S9360-3591-SLV](https://www.amazon.com/gp/product/B01LQTXED8?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B01LQTXED8) 作为我的首选推荐。如果你希望笔记本电脑装备最新的功能特性,并且 **能够在使用 Linux 工作** 时有极好的性能,那么,这台笔记本电脑将是你的最佳选择。 它使用铝合金机身,很轻(2.7 磅重),有强劲的硬件性能,待机时间较长,使用康宁大猩猩玻璃的 QHD 显示屏,分辨率为 3200×1800、并且还具备触控功能,可以为你带来清晰的图像表现,即便是很小的细节也可以很好的展现出来,有一个带橡皮掌托的、面积很大的并且非常好用的触摸板(早期版本上触摸板有几个小问题,但是,最新的机器已经修复了),并且也有一个很好用的带背光的键盘(按键的行程很短,这一点有些像 Thinkpad 笔记本),两个 USB 3.0 端口。最重要的是,两个最让 Linux 用户头痛的问题,无线网卡和 GPU (Intel HD Graphics 620 **播放 4K 视频可以达到 60 fps**),在这台 Dell 电脑上,它们都 **超级兼容 Linux**。 ![](/data/attachment/album/201802/18/224731yo88lqhhwf0hwszn.png)![](/data/attachment/album/201802/18/224731nuc1q1nnnnq7cnqu.png) 有一个缺点是,它没有 HDMI 端口。在这个位置,Dell 增加了一个 Thunderbolt 3 端口。因此,你唯一的选择是使用一个 Thunderbolt 到 HDMI 的转换器(它很便宜)。第二,在购买之后,你不能升级它的 8GB 的内存(在采购之前你可以改变硬件配置 —— CPU、RAM & SSD),但是,在我的选择中,8GB 的内存运行任何 Linux 发行版做任何工作都足够了。我有一台 Asus 笔记本电脑(它是我收到的一份礼物)使用第五代的 Core i7 的 CPU,4GB 内存,它是我主要使用的计算机。使用 Chrome 可以打开 15-20 个标签,在后台运行 VLC ,打开文件管理和一个代码编辑器,这种情况下,它工作的很好。如果我减少一些浏览器标签(减少到 4-5 个),然后,即便是其它的应用程序都打开的情况下,我都可以在 Virtualbox 上使用虚拟机工作。这些都是在 4GB 内存的情况下,因此,有 8GB 内存和其它更强劲的硬件的情况下,它绝对会工作的非常好。 > > **注意:** 虽然我为你选择了一套非常可靠的 [硬件](https://www.amazon.com/gp/product/B01LQTXED8?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B01LQTXED8),但是,如果你愿意,你仍然可以进一步去定制它。即便你不去选择 ‘8GB RAM/128GB SSD’ 这个选项。因为,那个版本也提供 1920×1080 的 FHD 显示屏,并且,在 13.3″ 的显示屏上让菜单看起来更小一些,看起来稍微有点困难。 > > > ### 最便宜的 Linux 笔记本电脑 ![](/data/attachment/album/201802/18/224807g1cjs1jwzgsj7llh.png) 如果你觉得这台 Dell 笔记本电脑有点贵,买不起,但是还想拥有类似的非常好的性能,并且与 Linux 的兼容性很好,那么,第二个最佳选择是这台 [Acer Aspire E 15 E5-575G-57D4](https://www.amazon.com/gp/product/B01LD4MGY4?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B01LD4MGY4)。它 15.6″ 的显示屏,无疑能提供像前面的 Dell 笔记本一样的显示表现,但是,在 15.6” 上的 1920×1080 的全高清分辨率显示屏,也可以让任何细节都显示的非常清晰。其它的硬件与前面介绍的很贵的 Dell 笔记本电脑很相似,但是,**因此它的电池很重,整机重达 5.2 磅。** 你实际上可以去做一些定制。基本的配置包括一个第七代 Core i5 CPU,15.6“ 的全高清显示屏(1920 x 1080),8GB DDR4 内存,256GB 固态硬盘,Intel HD Graphics 620 GPU 和一个独立的 Nvidia 940 MX GPU,端口方面:HDMI 2 USB 3.0,1 x USB 2.0 & 1 USB 3.1。对于 $549 的售价,它竟然 **包含一个 DVD 刻录机** … [**它是一个特价商品**](https://www.amazon.com/gp/product/B01LD4MGY4?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B01LD4MGY4)。 至于 Linux 的兼容性,它真的很好。虽然它不像顶级的 Dell XPS,但是,至少在我看来,如果它能够解决 Nvidia GPU 的问题,它就是一个很好的选择。除了一个用户以外,所有其它的用户都反馈,它的 Linux 兼容性非常好。唯一的一个用户抱怨说,在 Linux Mint 上安装了 Nvidia 的专用驱动以后,出现了一个小问题,并且他说,他决对不是故意 “抹黑” 它。这个反馈与我在使用移动版的 Nvidia GPU 所遇到的情况一样。 例如,现在我使用一台 Asus 笔记本电脑,并且它除了集成的 Intel GPU 以外,它也有一个独立的 Nvidia 920M GPU。这台笔记本电脑我大概已经用了一年半时间了。[我在它上面运行了一些 Linux 发行版](https://www.hecticgeek.com/gnu-linux/),并且,遇到的唯一的问题是,[在 Ubuntu 17.10 上](https://www.hecticgeek.com/2017/11/ubuntu-17-10-review/) 安装完它的专用驱动程序后,如果激活 Nvidia 作为默认的 GPU,自动用户登入功能会停止工作。因此,每次进入桌面我都要输入我的登录凭据。这虽然不是一个大问题,但是,我确信,它可以通过编辑一些登录管理器的配置设定来修复它,但是,我根本就没有去理它,因为我很少使用 Nvidia GPU。因此,我只是简单地改变默认 GPU 为 Intel,所有的一切就会正常。因此,前段时间,我在 [Ubuntu 16.04 LTS](https://www.hecticgeek.com/2016/04/ubuntu-16-04-lts-review/) 上 [的同一个 Nvidia GPU 上启用了‘运动插值’](https://www.hecticgeek.com/2016/06/motion-interpolation-linux-svp/),并且它处理的非常好! 我想说的是,GPU 驱动,比如 Nvidia & AMD/ATI 提供的,给用户带来困扰只是在过去的 Linux 上,但是,现在随着进一步的处理,已经不是什么困难的事情了,或者说,至少没有像以前那样困难了。除非你使用的是一个非常新的高端 GPU,Linux 的运行不遇到大的问题还是很有可能的。 ### Linux 游戏笔记本 ![](/data/attachment/album/201802/18/224835itwrk1rt0aqxxzjq.png) 很多时候,玩游戏的笔记本电脑,你需要去手动调整一些东西。并且,这些 “东西” 大部分都是与 GPU 相关的。它可能只是简单地安装一些专用的驱动程序,去处理一个拒绝引导到 CD/USB 中的系统。但是,如果有足够的耐心,大多数情况下,它们都是可以修复的。如果你的游戏笔记本有一个非常新的 Nvidia/AMD GPU 驱动,并且,这个驱动有问题,那么,修复它意味着只需要等待它更新驱动程序。有时候,可能需要等待很长的时间。但是,如果你买了一台安装有几个月前发布的 GPU 的笔记本电脑,那么,仅此一点,就大大增加你解决现有问题的机会。 因此,考虑到这一点,我选择了 [Dell Inspiron i5577-7342BLK-PUS](https://www.amazon.com/gp/product/B06XFC44CL?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B06XFC44CL),作为一个游戏笔记本电脑的最佳选择。它是一台强大的游戏笔记本电脑,售价低于 1000 美元。主要原因是它有一个 15.6″ 的全高清(1920 x 1080)显示屏。因为,在你查看其它配置的时候你会发现(也可以进一步定制它),它包含一个第七代 Core i7 CPU(四核心),16GB DDR4 内存(最高可到 32GB),512GB SSD 驱动器,并且有一块 Nvidia GTX 1050 GPU,它有很多积极的评价。你只可以在 QHD 或者 4K 下,使用外接显示器去玩高端游戏,尽管如此,它也可以在 15.6″ 的全高清分辨率下玩一些游戏。 我选择 Dell 的另外原因是,大多数的 Dell 笔记本电脑(或者一般用途的计算机)都是非常兼容 Linux 系统的。我在 Dell 网站上手工检查了硬件配置的详细情况,虽然我不能保证使用 Nvidia GPU 不会有任何问题,其它的硬件在主流的 Linux 发行版上都工作的很好(比如 Ubuntu)。 ### 哪个才是你需要的? 实际上,我相信越少越好。 我可以在这里给你 ‘推荐’ 很多很多的笔记本电脑,但是,那样的话,我需要写一系列的博客文章。因此,我并不打算 ‘推荐’ 10-12 台笔记本电脑,除非我确信它们都在 Linux 上运行的非常好。而目前为止,这个推荐清单上只有 3 台。我能确信它们在 Linux 上运行的非常好(而且,甚至是游戏笔记本电脑,除了 Nvidia GPU,其它的硬件部分应该工作的很好),再加上,这三个型号都有很多的可选项。换句话说就是,随着时间的推移,如果我从其它的制造商的产品中找到一些笔记本电脑,我相信它们在 Linux 上也运行的很好,然后,我也会推荐它们。但是,现在,就这三台笔记本电脑是我所推荐的。你可能不喜欢这些推荐的电脑,那么,下面我告诉你如何去查找你心仪的笔记本电脑。一旦你有了基本的概念,你可以非常容易地去预测,一台笔记本电脑是否能够运行 Linux 而不会出现问题。上面我已经提到了大部分,但是,我还在这里再说一下。 #### 查找关于硬件的更多信息 当你拿到一个笔记本电脑时,记下它的型号。现在,在大多数的网站上,都提供硬件的详细情况,比如,无线网卡或者声卡芯片的制造商。在大多数的情况下,使用一些简单的技巧就可以拿到这些信息。我通常是这样做的。 如果你知道笔记本电脑的制造商和型号,可以在 Google 中搜索它的驱动程序。我以前面的 Dell 游戏笔记本电脑为例。如果你知道它的名字,然后在 Google 上去搜索它的驱动程序(`Dell Inspiron i5577-7342BLK-PUS drivers`),Google 并不会显示一个 Dell 的官方的驱动程序页面。这并不奇怪,因为 Dell (以及其它制造商)在一个通用的型号名字下面,销售很多种装有各种不同的(2 到 3 种)硬件的笔记本电脑。因此,要缩小搜索目标,从左侧开始,我们首先来使用名字的前三个字段,并且用它在 Google(`Dell Inspiron i5577 drivers`)中搜索驱动程序,然后,如下所显示,并且,Google 也列出了不同的所属网站,对于 Inspiron 5577(没有 ‘i’),列出了一个 Dell 的官方驱动程序页面。 ![](/data/attachment/album/201802/18/224916vaa2231z1hx3zzwh.png) 如果你进入这个页面,去查看各种我们感兴趣的型号的驱动程序和硬件列表,那么,你将看到在 ‘Dell Inspiron i5577-7342BLK-PUS’ 中的硬件也在这里列出来了。我通常只喜欢查看 ‘audio’ 和 ‘network’ 下面列出的内容,因为从购买网站上去获得这些芯片的准确的型号名一般很困难,其它的一些硬件如 GPU、CPU 等等也列了出来。因此,如果你查看在 ‘network’ 下显示的内容,你将看到 Dell 提供的一些驱动程序。其中一个就是 Realtek 以太网适配器(以太网适配器通常都支持 Linux ),Qualcomm QCA61x4A-QCA9377 无线网络适配器(如果你进一步研究,需要对 `QCA61x4A` 和 `QCA9377` 分别进行,因为它们之间用 ‘-’ 分隔,你就会发现,它们实际上是来自高通的两种不同的无线芯片。这个关键字表示,Dell 在一个包中包含了两种驱动程序),和一组 Intel 无线网络适配器(Intel 硬件在 Linux 中也支持的非常好)。 但是,高通的设备有时候可能会有些问题。我遇到过一两个,但是,它们都不是什么严重的问题。也就是说,当有问题时,去查找就是解决的一个好办法。因此,使用 `Qualcomm QCA61x4A-QCA9377` 做为关键字(使用一个适配器或者使用一个芯片名字的组合去查询这并不重要),并且增加一个像 `linux` 或者 `ubuntu` 这样的关键字在 Google 中去搜索它。如果像 `Qualcomm QCA61x4A-QCA9377 ubuntu` 这样去搜索,然后,Google 会列出很多结果。我收到的第一个结果是自来 [AskUbuntu](https://askubuntu.com/)(一个社区驱动的网站,专门回答终端用户提出的问题,是一个解决 Ubuntu 相关问题的极好的资源)。 ![](/data/attachment/album/201802/18/224944flccxau99vvx73qa.png) 如果你去看那个页面,你可以看到有用户报怨 Qualcomm QCA9377 无线网络适配器在它的 Ubuntu 15.10 不能正常工作。幸运的是,那个问题已经被回答了。这个问题看起来似乎是 Ubuntu 15.10 的问题,它发布于 2015 年 10 月,因此,这是两年前的问题了。所以,这个问题很可能在最新的 Ubuntu 发行版中已经修复了。我还记得,这个问题好像与 Qualcomm QCA9377 无线芯片有关,而不是 QCA61x4A。因此,如果我们的 Linux 游戏笔记本电脑使用的是后面型号的无线芯片,那么很有可能你不会遇到这个问题。 我希望我不要遇到上面报怨的所有事情。我只是想给你提供一个指南,告诉你如何去找到你希望去运行 Linux 的笔记本电脑上的关于硬件的详细情况,这样你就可以很好地去评估它。使用一些常识性的技巧和经验,你的工作效率将会更高。 #### 不要止步于 GPU 和网络适配器上 ![](/data/attachment/album/201802/18/225007zmurejnqan2n4xd5.jpg) 虽然,在你购买了一台笔记本电脑来运行 Linux 时,GPU 和网络适配器是大多数人遇到的最容易出现问题的硬件设备,但是,去研究音频、触控板、和键盘在 Linux 中的兼容性和它们相关的特性(例如,我的老 Dell 的背光键盘在 Linux 中也有一个小问题),也是一个很好的实践。 **搜索‘用户评论’(当你准备购买时)** 在诸如 Amazon.com 这样的网站上,你实际上可以搜索某些关键字的用户反馈 (‘审阅’)。这是非常有用的,因为你可以很容易地用几秒钟内在包括数以百计甚至数以千计的用户反馈中搜索一两个关键字。我建议你使用的关键字,如 `Linux` 或 `ubuntu` 或 `linux mint` 或任何其他 Linux 发行版,只要它是流行的发行版。如果已经购买了笔记本电脑的人试图在它上运行 Linux 发行版,使用此方法你总能找出发生了什么事。 在亚马逊这样的网站搜索用户反馈是很容易。一旦您访问了您感兴趣的产品页面,只需单击“客户评论”链接并向下滚动, 直到看到一个搜索框 (通常位于右下角)。 ![](/data/attachment/album/201802/18/225143nuaq6d77767uybwd.png) #### 如果它是一个 ‘热门’ 硬件,等待 2-3 个月 正如,计算机终端用户所担心的那样,Linux 的市场份额是非常小的。因此,硬件制造商并不会把 Linux 看的很重。因此,他们修复最新发布的硬件设备中已存在的主要问题需要很长的一段时间。即便是开源驱动程序,也是如此,当然,在我的经验中,开源的驱动程序的问题修复比专属的驱动程序要快。因此,如果你买的笔记本电脑的特色硬件设备(主要指 CPU 和 GPU)是最新发布的,那么,它通常需要等待 2 或 3 个月才能去修复在 Linux 上的主要的问题。并且,但愿在那个时候,你可以找到一个修复,或者,至少可以预测什么时候可以被修复。 #### 关于屏幕和 HiDPI 在 Linux 上支持的怎么样? ![](/data/attachment/album/201802/18/225206y4i8sfm94imf8sbx.png) ‘像素密度’ 或者 ‘高像素密度’ 显示是最近非常流行的术语。并且大多数人都认定,更高的像素意味着更好的质量。虽然在一般的认知和技术角度上,它可能是正确的,但是,它并不准确。这个主题理解起来很复杂,因此,我将只讲一些基本的概念,对于你理解这个主题已经足够了,以避免不必要的混乱。 任何显示在你的屏幕上的东西,比如文本或者图标,都被设计为某些固定的大小。而这些大小是通过被称为 “每英寸显示的像素点数” 或者简称为 DPI 来描述的。它基本上定义了每英寸应该显示多少个点(像素)才能正确显示这个东西。每英寸显示 72 个点是由 Apple 公司制定的标准,这是很重要的。我相信,你可能听说过,Windows 使用了一个不同的标准,每英寸 96 个点,但是,它不完全正确。我不去深入其中的细节,但是,如果你想进一步了解更多的内容,[阅读 Wikipedia](https://en.wikipedia.org/wiki/Dots_per_inch#Computer_monitor_DPI_standards)。在任何情况下,要确保显示在你的 Linux 笔记本电脑的屏幕上的内容看起来清晰可读,如果你想了解,按以下的内容去做。首先,确定它的显示大小(13.3″、15.6″、17″…)和分辨率。然后到 [PXCALC.com](http://pxcalc.com/) 网站,它提供一个非常好用的每英寸点数计算器。接着在上面输入正确的内容。计算完成后,它告诉你一个 DPI 的计算结果(在它的右上角,如下图所示)。然后将那个值简单地除以 72,这就是最重要的部分。 ![](/data/attachment/album/201802/18/225232a1ctux2ik1upu3ts.png) 如果你得到的结果是一个类似于整形增量,比如 2、3、4(+0.2 到 —0.2 的偏差还不错,最好是 +0.1 到 —0.1,最完美的是接近 0.0 的偏差及更大的整数—— 3 或更大,比如 iMac 27 5K),然后,你就没有什么可担心的了。整形增量越高(只要偏差保持在范围之内),屏幕越清晰。为了更好理解,我们举一个例子。 我以推荐给你的第一个笔记本电脑(使用 13.3″ 的 QHD 分辨率的 Dell XPS)为例。如果你使用这个计算器去计算,它的结果是 ‘3.83’,把它粗算为 ‘3.8’,它不是我们前面所说的那样一个整数,但是,它在偏差范围以内(-0.2),是安全的。如果你拿我推荐的 Acer 笔记本电脑做同样的计算,它得到的结果是 ‘1.95’,把它粗算为 ‘2.0’。因此,在不考虑它的其它特性(亮度,可视角度,等等)的情况下,Dell 笔记本电脑上的显示清晰度要好于 Acer 几乎两倍(相信我,这个显示效果已经看起来非常清晰了。但是,它相比分辨率为1366 x 768 的无论是 13.3″ 还是 15.6″ 的屏幕,看起来显示效果更好)。 #### 关于内存大小? ![](/data/attachment/album/201802/18/225301cpn1rnhi1bcx1hro.png) KDE 和 GNOME 是在 Linux 上的两种主流的桌面环境。虽然还有很多其它的选择,我建议你坚持使用其中的一个。目前来说,我比较偏爱 KDE。据我所知,KDE plasma 比 GNOME 更加轻量化,并且效果更好。如果你希望了解它们之间的比较数据,它在 [我的 Ubuntu 16.10 特点评估](https://www.hecticgeek.com/2016/11/ubuntu-16-10-flavors-comparison/) 中(它大概是在一年前做的),在 Ubuntu 上 KDE plasma 占用大约 369 MiB 内存,而 GNOME 大概占用了 781 MiB!减少了 **112% !** 现在我使用 Kubuntu 17.10,虽然我没有评估它,但是我可以告诉你,它的内存占用大约在 380-400 MiB左右。重新回到这个话题上,我建议你在为你的 Linux 笔记本电脑的内存选择上,**不要低于 8GB**。那样,我可以很自信地保证,在未来 4 年内你的笔记本电脑都运行的很好,而不用担心它会变慢,并且可以去很好的使用各种发行版和满足大多数终端用户的需求。 如果你是在寻找一台 **在 Linux 上玩游戏的笔记本电脑**,那么内存选择应该是 **使用 12GB 或者更多**。 除比之外,8GB 内存对于大多数终端用户来说是足够的。 #### 关于 SSD ![](/data/attachment/album/201802/18/225330ddtgtssygfsyyvyv.png) 不管你使用的是什么操作系统,增加一块 SSD 将能提升你的笔记本电脑的整体性能和反应速度,因为它比起普通的机械硬盘来说速度快很多,就这么简单。也就是说,在我的经验中,即便是高效和轻量化的 KDE 发行版,相比 GNOME 要花更多的启用时间。一些 Linux 发行版,比如 Ubuntu 和 Kubuntu 带着一个特别设计的被称为 'ureadahead' 的实用程序,它可以改善启动时间(有时可以达到 **30%** 甚至更多),不幸的是,并不是所有的发行版都有这类工具。在有些时候,**安装在 SATA 驱动器上的 KDE 的启动时间可能长达 50 秒以上**。[Manjaro 17.0.2 KDE](https://www.hecticgeek.com/2017/07/manjaro-17-0-2-kde-review/) 就是其中一个这样的例子(显示在上面的图表中)。 因此,最简单的方法就是购买一台带有 SSD 的笔记本电脑,它可以帮助改善启动时间。**我的 Kubuntu 17.10 上是一个小的 SSD 驱动器(20GB),它的启动时间在 13-15 秒内**。 #### 关于 GPU ? 正如上面多次提到过的,如果可能,尽量使用一个 Intel GPU。正如众所周知的那样,Dell 的产品在硬件上都是 ‘Linux 友好的’, Intel 也在开源项目上大量进行投资,并且,其中它的一些硬件也如此。选择它你不会后悔的。 #### 如何进行自动 GPU 切换(比如: Nvidia Optimus),它能正常工作吗? 如果你希望购买的笔记本电脑,显卡在各方面都考虑的比较周全,那么,在 Windows 中,Nvidia 有一个叫做 ‘Optimus’ 的特性,它自动在集成 GPU(性能较弱) 和独立 GPU(性能更强)之间切换。ATI 也有这个功能。在 Linux 中这个功能并没有被官方支持,但是,在那方面有一个创新性的工作,比如 [Bumblebee 项目](https://bumblebee-project.org/)。不过它并不总是按预期工作。我比较喜欢去安装专用的 GPU 驱动程序,并且在我需要的时候去手动切换它们。值得称赞的是,Fedora 团队已经做出了它们的解决方案,我并不知道他们做的怎么样,[最好问问 Christian 吧](https://blogs.gnome.org/uraeus/2016/11/01/discrete-graphics-and-fedora-workstation-25/)。 #### Linux 能给你更长的电池使用时间吗? 当然可以!只要你的硬件设备配置正确,我建议你安装电源使用优化器。现在有几个这方面的应用程序,但是,我建议使用 ‘[TLP](http://linrunner.de/en/tlp/docs/tlp-linux-advanced-power-management.html)’。它很容易安装,在我的经验中它可以使功耗降低,而且结果令人影响深刻,它不需要手动去调整什么就可以正常工作。 下面有两张我的最新的 Ubuntu 17.10 的评估截屏。第一张截屏展示了在安装 ‘tlp’ 之前的电源使用情况,而第二张展示了安装之后的(图片已经说明了一切): ![](/data/attachment/album/201802/18/225422wepqfffuqmeuzyxf.png) ![](/data/attachment/album/201802/18/225422yo266505mh511jr1.png) ‘tlp’ 可以在主要的 Linux 发行版上使用。在 Ubuntu 上,你可以通过执行下面的命令去安装它: ``` sudo apt update sudo apt install tlp ``` 现在重启动计算机,就可以了! #### 在 Linux 中能测量电源使用了多少吗? 很高兴你能这样问!它的名字叫 ‘[powerstat](https://www.hecticgeek.com/2012/02/powerstat-power-calculator-ubuntu-linux/)’。它是非常神奇的一个小实用程序(由 Colin King 设计,它是一位 Ubuntu 开发者),它采集电源消耗(和诊断)相关的使用数据,并将它们表示在屏幕上。在基于 Ubuntu 的系统上,输入下面的命令可以去安装它: ``` sudo apt update sudo apt install powerstat ``` 在大多数主流的 Linux 发行版上,它们的软件仓库中都有这个软件。 #### 你推荐的 Linux 操作系统是哪个? 很好的问题,到目前为止,我主要使用的操作系统是 Kubuntu 17.10。我没有评估过它,但是,长话短说,我喜欢它!它非常易于安装,并且对新手比较友好,稳定,漂亮,高效并且易于使用。到目前为止我不喜欢 GNOME!因此,如果你刚开始使用 Linux,那么,我建议你去尝试 [Kubuntu](https://kubuntu.org/) 或者 [Linux Mint](https://linuxmint.com/),首先,(‘Mint’ 可以有很多的桌面环境选择。要么使用 KDE,要么使用 ‘Cinnamon’)。 然后,在你掌握使用技巧后,你就可以转移到其它的发行版上了,这是 Linux 新手最好的方法。 ### 结束语 记住我一开始说的话,如果你在寻找一台能够轻松运行 Linux 的笔记本电脑,那么,[Dell XP S9360-3591-SLV](https://www.amazon.com/gp/product/B01LQTXED8?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B01LQTXED8) 将是你的最佳选择。它外观漂亮、功能强大、非常流行、超便携,不仅能够很轻松地运行 Linux,而且它还有一个非常棒的,并且得到很多人赞扬的显示屏。 如果,你希望有一个更便宜的选择,那么,[Acer Aspire E 15 E5-575G-57D4](https://www.amazon.com/gp/product/B01LD4MGY4?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B01LD4MGY4) 会满足你的要求。它也像前面的 Dell 一样,可以很好地兼容 Linux,再加上它的性价比,它也是一个非常好的选择。 第三,如果你在寻找一台能够在 Linux 上运行游戏的笔记本电脑,那么,[Dell Inspiron i5577-7342BLK-PUS](https://www.amazon.com/gp/product/B06XFC44CL?ie=UTF8&tag=flooclea01-20&camp=1789&linkCode=xm2&creativeASIN=B06XFC44CL) 看起来非常适合你。当然,还有许多其它的游戏笔记本,但是,我特别选择这一款的原因是,它的硬件特性与 Linux 兼容,虽然我不能保证它与 Nvidia GTX 1050 一样。换句话说,你不应该去买一台 Linux 笔记本去玩游戏,那样会“玷污”你的游戏水平。如果是那样的话,它的硬件性能(它的性能很强大了)并不会让你满意,如果你愿意去研究并找到其它的选择,那就去做吧。 祝你采购顺利,并感谢阅读! --- via: <https://www.hecticgeek.com/2017/12/best-linux-laptop/> 作者:[Gayan](https://www.hecticgeek.com/author/gayan/) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,361
如何在 Ubuntu 16.04 LTS 上用 Tomb 加密文件
https://www.howtoforge.com/tutorial/how-to-install-and-use-tomb-file-encryption-on-ubuntu-1604/
2018-02-18T23:43:00
[ "加密", "Tomb", "Veracrypt" ]
https://linux.cn/article-9361-1.html
![](/data/attachment/album/201802/18/234345rz1g9a15v97go1fg.png) 如今,大多数人都认为文件加密是必要的,甚至在 Linux 系统上也是如此。 如果你和我一样, 最初被 Ubuntu 所吸引是因为 Linux 系统强化的安全性,恐怕我有个坏消息要告诉你:Linux 已经成为它自身“成功”的受害者。 近年来,用户数量的大幅度增加导致了这类系统的攻击和盗窃活动呈指数级增长。 曾经有一个非常简单的解决方案来在像 Ubuntu 这样的 Linux 系统上加密文件:它叫做 [Truecrypt](https://www.fossmint.com/secure-encrypt-files-folders-with-truecrypt-in-linux/)。 直到 2015 年,它提供了不同程度的军事级别的加密,并且在大多数 Linux 系统中运行良好。不幸的是, 它已经停止开发了, 因此变得相当不安全。 ### 替代品 幸运的是,除了 Truecrypt,还有一些选择。 Truecrypt 的直接继承者是 [Veracrypt](https://www.fossmint.com/veracrypt-is-a-secure-alternative-encryption-tool-to-truecrypt-for-linux/) ,它由一群开发者从 Truecrypt 获取源代码并保持更新的。 该项目已经发展成为令人印象深刻的独立系统,但现在渐已老迈。旧系统,尤其是那些处理安全问题的系统,只能更新多次而才不会引入漏洞。 出于这个原因,在其他许多方面,应该寻找一个更外围一些的加密软件。我选择的是 Tomb。 ### 为什么是 Tomb 在某些方面,Tomb 与其他加密软件非常相似。它将加密文件存储在专用的“Tomb 文件夹”中,可以让你快速查看您已加密的文件。 它还使用与 Veracrypt 类似的 [AES-256](https://www.dyne.org/software/tomb/) 加密标准。这个标准适用于 NSA 、微软和 Apple,并被认为是最安全的加密算法之一。如果你不熟悉加密技术,则应该阅读一点[技术背景知识](https://thebestvpn.com/advanced-encryption-standard-aes/),但如果你只想快速、安全地加密,请不要担心, Tomb 将不负所望。 Tomb 也有一些很大的不同之处。首先,它是专门为 GNU/Linux 系统开发的,可以解决一些更广泛的加密软件的兼容性问题。 第二,尽管 Tomb 是开源的,但它使用的是静态链接库,以至于其源代码难以审计。 这意味着一些操作系统发行版开发者并不认为它是自由的,但是当涉及到安全软件时,这实际上是一件好事:这意味着与完全“自由”软件相比, Tomb 被黑客攻击的可能性更小。 最后,它有几个先进的功能,如<ruby> 隐写术 <rt> steganography </rt></ruby>,这使你可以将你的关键文件隐藏在其他文件中。 尽管 Tomb 主要是一个命令行工具,它也带有 GUI 界面—— gtomb,它允许初学者用图形化的方式使用它。 这是推销么? 好吧,在我告诉你如何使用 Tomb 之前,值得注意的是,没有一个加密软件能提供完全的保护。 Tomb 不会让你的计算机隐藏于你 ISP,也不会保护存储在云中的文件。如果你想对云存储进行完全加密,您需要使用 Tor 浏览器和零日志 VPN 登录到你喜欢的存储服务中。 这里有很多选项,但是 [Trust Zone](https://privacyaustralia.org/trust-zone-vpn-review/) 是一个很好的浏览器,而 [Tinc](https://www.howtoforge.com/tutorial/how-to-properly-set-up-tinc-vpn-on-ubuntu-linux/) 是一个很好的 VPN 工具。 说了这么多,如果你正在寻找 Ubuntu 16.04 上的快速、简单、安全的加密,Tomb 无疑是一条可行的路。让我们开始吧。 ### 在 Ubuntu 16.04 上安装 Tomb 因为 Tomb 是专门为 Linux 设计的, 所以安装非常简单。 几年前,SparkyLinux (它本身就是一个非常好的 Debian 衍生产品)的开发者们将 “Tomb” 添加到他们的官方存储库中。 你可以通过在 Ubuntu 系统上添加这些存储库来安装它。 要做到这一点, 打开一个终端并添加一个存储库文件: ``` sudo vi /etc/apt/sources.list.d/sparky-repo.list ``` 然后在文件中添加以下行: ``` deb https://sparkylinux.org/repo stable main deb-src https://sparkylinux.org/repo stable main deb https://sparkylinux.org/repo testing main deb-src https://sparkylinux.org/repo testing main ``` 保存并关闭该文件。 你现在需要安装 Sparky 公钥,使用下列步骤: ``` sudo apt-get install sparky-keyring ``` 或者: ``` wget -O - https://sparkylinux.org/repo/sparkylinux.gpg.key | sudo apt-key add - ``` 然后你需要使用标准的命令来更新你的存储库: ``` sudo apt-get update ``` 然后简单地使用 `apt` 安装 Tomb: ``` sudo apt-get install tomb ``` 如果你想要带有 GUI 的 Tomb,安装同样简单。只需使用 `apt` 来安装 gtomb: ``` sudo apt-get install gtomb ``` 就是这样,你现在应该安装好了一个可以工作的 Tomb。 让我们看看如何使用它。 ### 使用 Tomb #### 通过命令行使用 Tomb Tomb 主要是一个命令行工具,所以我将首先介绍这个用法。 如果你不喜欢使用终端,你可以跳过这节并查看下一部分。 实际上,不用说了。 如果你以前从来没有使用过命令行,那么 Tomb 是一个很好的开始,因为它使用简单的命令,只要你小心,那么你很少有机会把事情搞砸。 Tomb 实际上使用了一组以墓地为主题的非常有趣的命令集。 每个加密文件夹都被称为“tomb”(墓碑) ,而且(我很快就会讲到) ,它们可以使用类似的哥特式命令。 首先,让我们创造(挖)一个新的 tomb。你可以指定你的新 tomb 的名称和大小,所以让我们使用 “Tomb1”这个名称并指定大小为 100 MB。 你需要 root 权限,所以打开终端并键入(或复制) : ``` sudo tomb dig -s 100 Tomb1.tomb ``` 你应该会得到类似这样的输出: ``` tomb . Commanded to dig tomb Tomb1.tomb tomb (*) Creating a new tomb in Tomb1.tomb tomb . Generating Tomb1.tomb of 100MiB 100 blocks (100Mb) written. 100+0 records in 100+0 records out -rw------- 1 Tomb1 Tomb1 100M Jul 4 18:53 Tomb1.tomb tomb (*) Done digging Tomb1 tomb . Your tomb is not yet ready, you need to forge a key and lock it: tomb . tomb forge Tomb1.tomb.key tomb . tomb lock Tomb1.tomb -k Tomb1.tomb.key ``` 正如输出的帮助说明,你现在需要创建(打造)一个密钥文件来锁定你的 tomb: ``` sudo tomb forge Tomb1.tomb.key ``` 如果在此时出现提及“活动交换分区”的错误,则需要停用所有活动交换分区: ``` sudo swapoff -a ``` 然后再运行上面的 keyfile 命令。 生成密钥文件可能需要几分钟时间,这具体取决于系统的速度。然而,在完成后系统会要求你输入新密码以确保密钥的安全: [![](/data/attachment/album/201802/18/234347zkqq58hi4hzsq13g.png)](https://www.howtoforge.com/images/how_to_setup_and_install_tomb_on_ubuntu_1604/big/tomb1.png) 输入两次,然后你的新密钥文件就会被制作出来。 你现在需要用你的新密钥来锁定你的 tomb。你可以这样做: ``` sudo tomb lock Tomb1.tomb -k Tomb1.tomb.key ``` 你将被要求输入你的密码。 这样做, 你应该会得到如下的输出: ``` tomb . Commanded to lock tomb Tomb1.tomb [sudo] Enter password for user Tomb1 to gain superuser privileges tomb . Checking if the tomb is empty (we never step on somebody else's bones). tomb . Fine, this tomb seems empty. tomb . Key is valid. tomb . Locking using cipher: aes-xts-plain64:sha256 tomb . A password is required to use key Tomb1.tomb.key tomb . Password OK. tomb (*) Locking Tomb1.tomb with Tomb1.tomb.key tomb . Formatting Luks mapped device. tomb . Formatting your Tomb with Ext3/Ext4 filesystem. tomb . Done locking Tomb1 using Luks dm-crypt aes-xts-plain64:sha256 tomb (*) Your tomb is ready in Tomb1.tomb and secured with key Tomb1.tomb.key ``` 现在一切都安排好了,你可以开始使用你的新 tomb 了。 这里有一个注意事项:因为我只是在告诉你该怎么做,所以我把我的密钥文件和 tomb 存放在同一个目录中(在这里是 `$HOME`)。 你不应该这样做——把你的密钥存放在别的地方,最好是在除了你之外没有人能找到的地方。 然而,你需要记住你把它放在哪里,因为你需要用它来打开你的 tomb。 要做到这一点, 请输入: ``` sudo tomb open Tomb1.tomb -k path/to/your/Tomb1.tomb.key ``` 输入你的密码,然后你就可以进去了。 tomb 会输出一些类似以下的内容: ``` tomb (*) Success unlocking tomb Tomb1 tomb . Checking filesystem via /dev/loop0 fsck from util-linux 2.27.1 Tomb1: clean, 11/25168 files, 8831/100352 blocks tomb (*) Success opening Tomb1.tomb on /media/Tomb1 ``` 然后你应该看到你的新 tomb 挂载在了 finder 窗口。 你现在可以从 tomb 中保存和打开文件,但是请注意,你需要 root权限才能这样做。 在你使用完之后需要用以下方法卸载你的 tomb: ``` sudo tomb close ``` 或者,如果你想强制关闭所有的打开的 tomb, 你可以使用: ``` sudo tomb slam all ``` #### 使用带 GUI 的 Tomb 如果你不喜欢使用命令行,或者只是想要一个图形界面,你可以使用 gtomb。与许多图形用户界面包装器不同, gtomb 使用起来很容易。 让我们来看看如何使用 gtomb 建立一个新的 tomb。 首先,从菜单中启动 gtomb。 它可能会是这 样的: [![](/data/attachment/album/201802/18/234350m92dlwxsmr8srw0r.png)](https://www.howtoforge.com/images/how_to_setup_and_install_tomb_on_ubuntu_1604/big/tomb2.png) 所有的事情都是一目了然的,但为了完整起见,我将详细介绍如何建立你的第一个 tomb。 首先,点击第一个选项“dig”。 点击确定,然后选择一个位置。 接下来,输入你的 tomb 的大小: [![](/data/attachment/album/201802/18/234352wabaab6azagnfadk.png)](https://www.howtoforge.com/images/how_to_setup_and_install_tomb_on_ubuntu_1604/big/tomb3.png) 你现在有了一个新的 tomb,但是你需要在使用它之前做一把钥匙。 要做到这一点, 请在主菜单中 单击“forge”: [![](/data/attachment/album/201802/18/234356f24geojn5dvtj5ro.png)](https://www.howtoforge.com/images/how_to_setup_and_install_tomb_on_ubuntu_1604/big/tomb4.png) Tomb 会要求你输入两次密码,那就这样做。 然后通过点击来使用密钥锁定你的 tomb,你已经猜到了,“lock”。 要打开它, 请单击“open”并再次输入您的密码。 从上面的截图中你可以看到,使用 gtomb 是非常容易的,你不应该遇到任何问题。 大多数常见的任务都可以通过点击来完成,对于任何更复杂的事情,你可以使用命令行。 ### 最后的想法 就是这样!你现在应该准备好你的第一个 tomb 了,并存储任何你想在 tomb 中保密和安全的信息,这些信息会更加安全。 你可以同时使用多个 tomb,并将它们中的文件绑定到你的 `$HOME` 目录,这样你的程序就不会感到困惑。 我希望这本指南能帮助你开始。 就像使用一个标准的文件夹一样使用你的 Tomb,但是对于更复杂的命令,你总是可以查看 [Tomb 官方指南](https://www.dyne.org/software/tomb/)。 --- via: <https://www.howtoforge.com/tutorial/how-to-install-and-use-tomb-file-encryption-on-ubuntu-1604/> 作者: [Dan Fries](https://www.howtoforge.com/) 选题: [lujun9972](https://github.com/lujun9972) 译者: [Auk7F7](https://github.com/Auk7F7) 校对: [wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# How to Encrypt Files with Tomb on Ubuntu 16.04 LTS Most people regard file encryption as a necessity nowadays, even on Linux systems. If, like me, you were originally attracted to Ubuntu because of the enhanced security of Linux systems, I’m afraid I’ve got bad news for you: Linux has become a victim of its own success. The vast increase in the number of users over recent years has led to attacks and theft on such systems growing exponentially. There used to be a pretty easy solution to encrypting files on Linux systems like Ubuntu: it was called [Truecrypt](http://truecrypt.sourceforge.net/). Up until 2015, it offered varying levels of military-grade encryption, and worked well with most Linux systems. Unfortunately, it has since been discontinued, and has therefore become pretty insecure. ## The Alternatives Luckily, there are a few alternatives to Truecrypt. The direct successor of Truecrypt was [Veracrypt](https://www.veracrypt.fr/en/Downloads.html), made by a group of developers who took the source code from Truecrypt and kept it updated. The project has since grown into an impressive standalone system, but is now showing its age. Old systems, and especially those that deal with security, can only be updated so many times without introducing vulnerabilities. For this reason, among many others, it’s worth looking a bit further afield for encryption software. My choice would be Tomb. ## Why Tomb? In some ways, Tomb is pretty similar to other encryption software. It stores encrypted files in dedicated “Tomb Folders”, allowing you to quickly see which files you have encrypted. It also uses a similar encryption standard to Veracrypt, [AES-256](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard). This standard is Applied by everyone from the NSA to Microsoft to Apple, and is regarded as one of the most secure encryption ciphers available. If you’re new to encryption, it’s worth reading a bit of the background behind the technology, but if you just want fast, secure encryption, don’t worry: Tomb will deliver. There are a couple of big differences with Tomb. The first is that it has been developed specifically for GNU/Linux systems, cutting out some of the compatibility issues of broader encryption software. The second is that, although Tomb is open source, it makes use of statically linked libraries so that its source code is hard to audit. That means that it is not considered free by some OS distributors, but when it comes to security software this is actually a good thing: it means that Tomb is less likely to be hacked than completely “free” software. Lastly, it has several advanced features like **steganography**, which allows you to hide your key files within another file. And though Tomb is primarily a command-line tool, it also comes with a GUI interface, gtomb, which allows beginners to use it graphically. Sold? Well, before I take you through how to use Tomb, it’s worth noting that no encryption software can offer total protection. Tomb will not hide your online computing from your ISP, and nor does it protect files stored in the cloud. If you want to fully encrypt cloud storage, you’ll need to log into your preferred storage service using the Tor browser and a zero-logging VPN. There are plenty of options available here, but Trust Zone is a good browser, and [Tinc](https://www.howtoforge.com/tutorial/how-to-properly-set-up-tinc-vpn-on-ubuntu-linux/) is a good VPN tool. All that said, if you are looking for fast, easy, secure encryption for Ubuntu 16.04, Tomb is undoubtedly the way to go. Let’s get you started. ## Installing Tomb on Ubuntu 16.04 Because Tomb was made especially for Linux, install is super easy. A couple of years back, the guys over at SparkyLinux (which is a pretty good Debian derivative in its own right) added Tomb to their official repositories. You can install it on your Ubuntu system by adding these repositories. To do this, open a terminal and add a repository file: `sudo vi /etc/apt/sources.list.d/sparky-repo.list` And then add the following lines to the file: ``` deb https://sparkylinux.org/repo stable main deb-src https://sparkylinux.org/repo stable main deb https://sparkylinux.org/repo testing main deb-src https://sparkylinux.org/repo testing main ``` Save and close that file. You now need to install the Sparky public key, using either: `sudo apt-get install sparky-keyring` Or: `wget -O - https://sparkylinux.org/repo/sparkylinux.gpg.key | sudo apt-key add -` You then need to update your repositories, using the standard command: `sudo apt-get update` And then simply install Tomb using apt: `sudo apt-get install tomb` If you want the GUI, install is just as easy. Just use apt to install gtomb: `sudo apt-get install gtomb` And that’s it: you should now have a working version of Tomb installed. Let’s look at how to use it. ## Using Tomb ### Using Tomb Through The Command Line Tomb is primarily a command line tool, so I’ll cover this usage first. If you are not comfortable with using a terminal, you can skip this section and look below. Actually, scratch that. If you’ve never used the command line before, Tomb is a great place to start, because it uses simple commands and there is little chance of you messing something up as long as you are careful. Tomb actually uses a pretty amusing set of commands, all graveyard-themed. Each encrypted folder is referred to as a “tomb”, and (as I’ll come to shortly) they can be worked with using similarly Gothic commands. First, let’s make a new tomb. You can specify the name and the size of your new tomb, so let’s use “Tomb1”, and make it 100mb. You need root privileges, so open a terminal and type (or copy): sudo tomb dig -s 100 Tomb1.tomb This should give you output similar to: ``` tomb . Commanded to dig tomb Tomb1.tomb tomb (*) Creating a new tomb in Tomb1.tomb tomb . Generating Tomb1.tomb of 100MiB 100 blocks (100Mb) written. 100+0 records in 100+0 records out -rw------- 1 Tomb1 Tomb1 100M Jul 4 18:53 Tomb1.tomb tomb (*) Done digging Tomb1 tomb . Your tomb is not yet ready, you need to forge a key and lock it: tomb . tomb forge Tomb1.tomb.key tomb . tomb lock Tomb1.tomb -k Tomb1.tomb.key ``` As the output helpfully states, you now need to create a keyfile to lock your tomb: `sudo tomb forge Tomb1.tomb.key` If, at this point, you get an error that mentions “an active swap partition”, you need to deactivate all of your active swap partititions: `sudo swapoff -a` And then run the keyfile command above. It might take a few minutes to generate a keyfile, depending on the speed of your system. After it is done, however, you’ll be asked to enter a new password to secure the key: Enter it twice, and your new keyfile will be made. You now need to lock your tomb using your new key. You can do this like this: sudo tomb lock Tomb1.tomb -k Tomb1.tomb.key You will be asked to enter your password. Do this, and you should get something like the following output: tomb . Commanded to lock tomb Tomb1.tomb [sudo] Enter password for user Tomb1 to gain superuser privileges tomb . Checking if the tomb is empty (we never step on somebody else's bones). tomb . Fine, this tomb seems empty. tomb . Key is valid. tomb . Locking using cipher: aes-xts-plain64:sha256 tomb . A password is required to use key Tomb1.tomb.key tomb . Password OK. tomb (*) Locking Tomb1.tomb with Tomb1.tomb.key tomb . Formatting Luks mapped device. tomb . Formatting your Tomb with Ext3/Ext4 filesystem. tomb . Done locking Tomb1 using Luks dm-crypt aes-xts-plain64:sha256 tomb (*) Your tomb is ready in Tomb1.tomb and secured with key Tomb1.tomb.key Now everything is set up, you can start using your new tomb. A note here: because I’m just showing you what to do, I’ve stored my key and tomb in the same directory (in this case $HOME). You shouldn’t do this – store your key somewhere else, preferably where no-one but you is going to find it. You’ll need to remember where you stored it, however, because you need it to unlock your tomb. To do this, enter: sudo tomb open Tomb1.tomb -k path/to/your/Tomb1.tomb.key Enter your password, and you should be in. Tomb will generate something like: tomb (*) Success unlocking tomb Tomb1 tomb . Checking filesystem via /dev/loop0 fsck from util-linux 2.27.1 Tomb1: clean, 11/25168 files, 8831/100352 blocks tomb (*) Success opening Tomb1.tomb on /media/Tomb1 And then you should see your new tomb, mounted in the finder window. You can now save and open files from the tomb, but note that you will need root privileges in order to do so. To unmount your tomb after you have finished using it, close it by using: sudo tomb close Or, if you want to force close all open tombs, you can use: sudo tomb slam all **Using Tomb Through The GUI** If you are uncomfortable using the command line, or simply just want a graphical interface, you can use gtomb. Unlike a lot of GUI wrappers, gtomb is pretty straightforward to use. Let’s look at how to set up a new tomb using gtomb. First, launch gtomb from the Menu. It will probably look like this: Everything is pretty self-explanatory, but for the sake of completeness I’ll run through how to set up your first tomb. To start, click on the first option, “dig”. Click OK, and then choose a location. Next, enter the size of your tomb: You’ve now got a new tomb, but you need to make a key before you can use it. To do this, click “forge” from the main menu: Tomb will ask you to enter a passcode twice, so do that. Then lock your tomb using the key by clicking, you’ve guessed it, “lock”. To open it, click “open” and enter your passcode again. As you can see from the screenshot above, usage of gtomb is really easy, and you shouldn’t encounter any problems. Most common tasks can be done with a few clicks, and for anything more complicated you can use the command line. ## Final Thoughts That’s it! You should now have your first tomb set up and ready to go. Store anything you want to keep secret and secure in tombs, and this information will be much more secure. You can use multiple tombs at the same time, and bind the files in them to your $HOME directory, so your programs don’t get confused. I hope this guide has helped you get started. Using your tombs is just like using a standard folder, but for more complex commands you can always check the Tomb [Official Guide](https://www.dyne.org/software/tomb/).
9,362
脚本编程之骰子游戏
http://www.linuxjournal.com/content/shell-scripting-bunco-game
2018-02-20T13:21:00
[ "骰子", "游戏" ]
https://linux.cn/article-9362-1.html
> > Bunco:一个使你的“快艇”游戏看起来更复杂的掷骰子游戏。 > > > ![](/data/attachment/album/201802/20/132105bq9fgubptg9011yu.jpg) 我已经有段时间没有编写游戏了,所以我觉得现在正是做一些这方面事情的时候。起初,我想“用脚本编一个 Halo游戏?”(LCTT 译注:Halo,光晕系列游戏),但我后来意识到这不太可能。来编一个叫 Bunco 的简单骰子游戏吧。你也许没有听说过,不过你母亲绝对知道 —— 当一群年轻女孩聚在当地的酒吧或者小酒馆的时候,这是个很受欢迎的游戏。 游戏一共六轮,有三个骰子,规则很简单。每次投三个骰子,投出的点数要和当前的轮数数字一致。如果三个骰子都和当前的轮数一致,(比如,在第三轮三个骰子都是 3),你这一轮的分数就是 21。 如果三个骰子点数都相同但和轮数数字不同,你会得到最低的 Bunco 分数,只有 5 分。如果你投出的点数两者都不是,每一个和当前轮数相同的骰子得 1 分。 要想玩这个游戏,它还涉及到团队合作,每一队(包括赢的那队),每人付 5 美元现金,或赢家得到其他类似现金奖励,并规定什么样的情况下才是赢家,例如“最多 Buncos” 或“最大点数”的情况下胜利。在这里我会跳过这些,而只关注投骰子这一部分。 ### 关于数学逻辑部分 在专注于编程这方面的事之前,我先简单说说游戏背后的数学逻辑。要是有一个适当重量的骰子投骰子会变得很容易,任意一个值出现概率都是 1/6。 完全随机小提示:不确定你的骰子是否每个面都是一样重量? 把它们扔进盐水里然后掷一下。YouTube 上有一些有趣的 D&D 世界的视频向你展示了怎么来做这个测试。 所以三个骰子点数一样的几率有多大? 第一个骰子 100% 会有一个值 (这儿没什么可说的),所以很简单。第二个则有 16.66% 的概率和第一个骰子的值一样,接下来第三个骰子也是一样。 但当然,总概率是三个概率相乘的结果,所以最后,三个骰子值相等的概率是 2.7%。 接下来,每个骰子和当前轮数数字相同的概率都是 16.66%。从数学角度来说:0.166 \* 0.166 \* 0.166 = 0.00462 。 换句话说,你有 0.46% 的可能性投出 Bunco,比 200 次中出现一次的可能性还小一点。 实际上还可以更难。如果你有 5 个骰子,投出 Mini Bunco (也可以叫做 Yahtzee “快艇”) 的概率为 0.077%,如果你想所有的骰子的值都相同,假设都是 6,那概率就是 0.00012%,那就基本上没什么可能了。 ### 开始编程吧 和所有游戏一样,最难的部分是有一个能生成真正的随机数的随机数发生器。这一部分在 shell 脚本中还是很难实现的,所以我需要先回避这个问题,并假设 shell 内置的随机数发生器就够用了。 不过好在内置的随机数发生器很好用。用 `$RANDOM` 就能得到一个 `0` 到 `MAXINT(32767)` 之间的随机值: ``` $ echo $RANDOM $RANDOM $RANDOM 10252 22142 14863 ``` 为了确保产生的值一定是 `1` - `6` 之中的某个值,使用取余函数: ``` $ echo $(( $RANDOM % 6 )) 3 $ echo $(( $RANDOM % 6 )) 0 ``` 哦!我忘了要加 `1`,下面是另一次尝试: ``` $ echo $(( ( $RANDOM % 6 ) + 1 )) 6 ``` 下面要实现投骰子这一功能。这个函数中你可以声明一个局部变量来存储生成的随机值: ``` rolldie() { local result=$1 rolled=$(( ( $RANDOM % 6 ) + 1 )) eval $result=$rolled } ``` 使用 `eval` 确保生成的随机数被实际存储在变量中。这一部分也很容易: ``` rolldie die1 ``` 这会为第一个骰子生成一个 `1` - `6` 之间的随机值存储到 `die1` 中。要掷 3 个骰子,很简单: ``` rolldie die1 ; rolldie die2 ; rolldie die3 ``` 现在判断下生成的值。首先,判断是不是 Bunco(3 个骰子值相同),然后是不是和当前轮数值也相同: ``` if [ $die1 -eq $die2 ] && [ $die2 -eq $die3 ] ; then if [ $die1 -eq $round ] ; then echo "BUNCO!" score=25 else echo "Mini Bunco!" score=5 fi ``` 这可能是所有判断语句中最难的部分了,注意第一个条件语句中这种不常用的写法 : `[ cond1 ] && [ cond2 ]`。如果你想写成 `cond1 -a cond2` ,这样也可以。在 shell 编程中,解决问题的方法往往不止一种。 代码剩下的部分很直白,你只需要判断每个骰子的值是不是和本轮数字相同: ``` if [ $die1 -eq $round ] ; then score=1 fi if [ $die2 -eq $round ] ; then score=$(( $score + 1 )) fi if [ $die3 -eq $round ] ; then score=$(( $score + 1 )) fi ``` 唯一要注意的是当出现 Bunco/Mini Bunco 就不需要再统计本轮分数了。所以整个第二部分的判断语句都要写在第一个条件语句的 `else` 中(为了判断 3 个骰子值是否都相同)。 把所有的综合起来,然后在命令行中输入轮数,下面是现在的脚本执行后的结果: ``` $ sh bunco.sh 5 You rolled: 1 1 5 score = 1 $ sh bunco.sh 2 You rolled: 6 4 3 score = 0 $ sh bunco.sh 1 You rolled: 1 1 1 BUNCO! score = 25 ``` 竟然这么快就出现 Bunco 了? 好吧,就像我说的,shell 内置的随机数发生器在随机数产生这方面可能有些问题。 你可以再写个脚本测试一下,去运行上述脚本几百次,然后看看 Bunco/Mini Bunco 出现次数所占的百分比。但是我想把这部分作为练习,留给亲爱的读者你们。不过,也许我下次会抽时间完成剩下的部分。 让我们完成这一脚本吧,还有分数统计和一次性执行 6 次投骰子(这次不用再在命令行中手动输入当前轮数了)这两个功能。这也很容易,因为只是将上面的内容整个嵌套在里面,换句话说,就是将一个复杂的条件嵌套结构全部写在了一个函数中: ``` BuncoRound() { # roll, display, and score a round of bunco! # round is specified when invoked, score added to totalscore local score=0 ; local round=$1 ; local hidescore=0 rolldie die1 ; rolldie die2 ; rolldie die3 echo Round $round. You rolled: $die1 $die2 $die3 if [ $die1 -eq $die2 ] && [ $die2 -eq $die3 ] ; then if [ $die1 -eq $round ] ; then echo " BUNCO!" score=25 hidescore=1 else echo " Mini Bunco!" score=5 hidescore=1 fi else if [ $die1 -eq $round ] ; then score=1 fi if [ $die2 -eq $round ] ; then score=$(( $score + 1 )) fi if [ $die3 -eq $round ] ; then score=$(( $score + 1 )) fi fi if [ $hidescore -eq 0 ] ; then echo " score this round: $score" fi totalscore=$(( $totalscore + $score )) } ``` 我承认,我忍不住自己做了一点改进,包括判断当前是 Bunco、Mini Bunco 还是其他需要计算分数的情况这一部分 (这就是 `$hidescore` 这一变量的作用)。 实现这个简直是小菜一碟,只要一个循环就好了: ``` for round in {1..6} ; do BuncoRound $round done ``` 这就是现在所写的整个程序。让我们执行一下看看结果: ``` $ sh bunco.sh 1 Round 1\. You rolled: 2 3 3 score this round: 0 Round 2\. You rolled: 2 6 6 score this round: 1 Round 3\. You rolled: 1 2 4 score this round: 0 Round 4\. You rolled: 2 1 4 score this round: 1 Round 5\. You rolled: 5 5 6 score this round: 2 Round 6\. You rolled: 2 1 3 score this round: 0 Game over. Your total score was 4 ``` 嗯。并不是很令人满意,可能是因为它只是游戏的一次完整执行。不过,你可以将脚本执行几百几千次,记下“Game over”出现的位置,然后用一些快速分析工具来看看你在每 6 轮中有几次得分超过 3 分。(要让 3 个骰子值相同,这个概率大概在 50% 左右)。 无论怎么说,这都不是一个复杂的游戏,但是它是一个很有意思的小程序项目。现在,如果有一个 20 面的骰子,每一轮游戏有好几十轮,每轮都掷同一个骰子,情况又会发生什么变化呢? --- via: <http://www.linuxjournal.com/content/shell-scripting-bunco-game> 作者:[Dave Taylor](http://www.linuxjournal.com/users/dave-taylor) 译者:[wenwensnow](https://github.com/wenwensnow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,363
菜鸟们,通过这几个例子,包你学会 uptime 命令的用法
https://www.howtoforge.com/linux-uptime-command/
2018-02-20T14:35:23
[ "uptime", "启动" ]
https://linux.cn/article-9363-1.html
![](/data/attachment/album/201802/20/143517d5vkxnsiziu5lqbu.jpg) Linux 小白,若对系统管理有兴趣,或想成为资深用户,就需要对命令行有扎实的功底。你需要知道很多命令,其中一个就是 `uptime`。文本我们会通过一些容易理解的案例来讲解一下这个命令的基本用法。 再开始前有必要说一下,文中的所有案例都在 Ubuntu 16.04 上测试过了。 ### Linux uptime 命令 望名生义,`uptime` 命令告诉你系统<ruby> 启动 <rt> up </rt></ruby>了(运行了)多长时间。这是语法: ``` uptime [options] ``` 这个工具的 man 页是这么说的: > > `uptime`会在一行中显示下列信息:当前时间、系统运行了多久时间、当前登录的用户有多少,以及前 1、5 和 15 分钟系统的平均负载。 > > > 下面这些问答形式的案例应该会让你对 `uptime` 命令有更好的了解。 ### Q1、如何使用 uptime 命令 `uptime` 的基础用法很简单 —— 只需要输入命令名称然后按下回车就行。 ``` uptime ``` 这是输出: [![How to use the uptime command](/data/attachment/album/201802/20/143526ahnt5s5bhp7n75z3.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/uptime-basic-usage1.png) 这里,第一项是当前时间,`up` 表示系统正在运行,`5:53` 是系统启动的总时间,最后是系统的<ruby> 负载 <rt> load </rt></ruby>信息。若你想深入了解,这里是 uptime man 页中关于最后一项信息的说明: > > 系统负载是处于<ruby> 可运行 <rt> runnable </rt></ruby>或<ruby> 不可中断 <rt> uninterruptable </rt></ruby>状态的进程的平均数。可运行状态的进程要么正在使用 CPU 要么在等待使用 CPU。 不可中断状态的进程则正在等待某些 I/O 访问,例如等待磁盘 IO。 > > > 有三个时间间隔的平均值。负载均值的意义根据系统中 CPU 的数量不同而不同,负载为 1 对于一个只有单 CPU 的系统来说意味着负载满了,而对于一个拥有 4 CPU 的系统来说则意味着 75% 的时间里都是空闲的。 > > > ### Q2、如何以更人性化的格式现实时间 若你只想知道系统运行了多长时间,而且希望以更人性化的格式来显示,那么可以使用 `-p` 项。 ``` uptime -p ``` 这是输出: [![make the tool show up time in pretty format](/data/attachment/album/201802/20/143528r94ojuekjy5uyejm.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/uptime-p-option.png) ### Q3、如何让 uptime 显示系统启动的日期/时间 你也可以指定 `uptme` 显示系统开始运行的时间和日期。方法是使用 `-s` 命令项。 ``` uptime -s ``` 这是输出: [![make uptime display date/time since when system is up](/data/attachment/album/201802/20/143529h21w9yi51bcziwie.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/uptime-s.png) ### Q4、如何获取版本信息和帮助信息 `-V` 获取版本信息,`-h` 获取帮助信息。 ``` uptime -V uptime -h ``` [![How to get version information and help](/data/attachment/album/201802/20/143531r8bxo18fobfwk65d.png)](https://www.howtoforge.com/images/usage_of_pfsense_to_block_dos_attack_/big/uptime-v-h.png) ### 结论 你可以看到,uptime 命令很容易理解也很容易使用。它没有提供很多的功能(命令选项也很少)。这里已经覆盖了它的所有功能了。因此只需要练习一下这些选项你就能在日常工作中使用它了。如果需要的话,你也可以查看它的 [man 页](https://linux.die.net/man/1/uptime)。 --- via: <https://www.howtoforge.com/linux-uptime-command/> 作者:[Himanshu Arora](https://www.howtoforge.com) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Linux uptime Command Explained for Beginners with Examples If you are a Linux newbie, and have interest in system administration, or you want to become a power user, then you need to have a solid knowledge of the command line. There are several commands that you should know about, and one of them is **uptime**. In this article, we will discuss the basics of this command using some easy to understand examples. But before that, it's worth mentioning that all examples used in this tutorial have been tested on an Ubuntu 18.04 LTS machine. ## Linux uptime command As the name suggests, the uptime command gives you the time for which the system has been up (or running). Here's its syntax: uptime [options] And here's is the way the tool's man page explains it: uptime gives a one line display of the following information. The current time, how long the system has been running, how many users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes. The following Q&A-styled examples should give you a better idea on how the uptime command works. ## Q1. How to use the uptime command Uptime's basic usage is very easy - just write the command's name and press enter. uptime Here's the kind of output the tool produces: So the first entry is the current time, then 'up' shows the system is running, 5:53 is the total time for which the system has been up, and then finally are the system load averages. Just in case you want to know more, here's what the uptime man page says about the last entry: System load averages is the average number of processes that are either in a runnable or uninterruptable state. A process in a runnable state is either using the CPU or waiting to use the CPU. A process in uninterruptable state is waiting for some I/O access, eg waiting for disk. The averages are taken over the three time intervals. Load averages are not normalized for the number of CPUs in a system, so a load average of 1 means a single CPU system is loaded all the time while on a 4 CPU system it means it was idle 75% of the time. ## Q2. How to make the tool show up time in pretty format In case you just want to know the time for which the system has been up, and that too in a more human-readable format, use the **-p** command line option. uptime -p Here's the output this command produced in our case: ## Q3. How to make uptime display date/time since when the system is up You can also make uptime specifically display the time/date since when the system has been running. This can be done using the **-s** command line option. uptime -s Here's the output the command produced in our case: ## Q4. How to get version information and help in general Use the -V option to get version information, and -h for general help. uptime -V uptime -h ## Conclusion As you'd have observed, the uptime command is easy to understand and use. It doesn't offer many features (or command line options). What all it offers have been discussed here. So just practice these options and you should be ready to use uptime in your day-to-day work. Just in case you require, here's the tool's [man page](https://linux.die.net/man/1/uptime).
9,364
什么是网络爬虫?网络爬虫如何工作?
http://www.theitstuff.com/web-crawler-web-crawlers-work
2018-02-20T14:42:16
[ "爬虫", "蜘蛛" ]
https://linux.cn/article-9364-1.html
![](/data/attachment/album/201802/20/144220dz8isfp9ebsede8d.jpg) 作为一个狂热的互联网人,你在生活中一定遇到过<ruby> 网络爬虫 <rt> Web Crawler </rt></ruby>这个词。那么什么是网络爬虫,谁使用网络爬虫?它是如何工作的?让我们在本文中讨论这些。 ### 什么是网络爬虫? [![web crawler source code sync](/data/attachment/album/201802/20/144221he4yp9n94l9svim9.jpg)](http://www.theitstuff.com/wp-content/uploads/2017/12/crawler.jpeg) <ruby> 网络爬虫 <rt> Web Crawler </rt></ruby>也被称为<ruby> 网络蜘蛛 <rt> web-spider </rt></ruby>是一个在互联网中访问不同网站的各个页面的互联网软件或者机器人。网络爬虫从这些网页中检索各种信息并将其存储在其记录中。这些抓取工具主要用于从网站收集内容以改善搜索引擎的搜索。 ### 谁使用网络爬虫? 大多数搜索引擎使用爬虫来收集来自公共网站的越来越多的内容,以便它们可以向用户提供更多相关内容。 [![search engines use web crawlers](/data/attachment/album/201802/20/144221y2ne1ndmn4dx1mk1.png)](http://www.theitstuff.com/wp-content/uploads/2017/12/sengine.png) 许多商业机构使用网络爬虫专门搜索人们的电子邮件地址和电话号码,以便他们可以向你发送促销优惠和其他方案。这基本上是垃圾邮件,但这是大多数公司创建邮件列表的方式。 黑客使用网络爬虫来查找网站文件夹中的所有文件,主要是 HTML 和 Javascript。然后他们尝试通过使用 XSS 来攻击网站。 ### 网络爬虫如何工作? 网络爬虫是一个自动化脚本,它所有行为都是预定义的。爬虫首先从要访问的 URL 的初始列表开始,这些 URL 称为种子。然后它从初始的种子页面确定所有其他页面的超链接。网络爬虫然后将这些网页以 HTML 文档的形式保存,这些 HTML 文档稍后由搜索引擎处理并创建一个索引。 ### 网络爬虫和 SEO 网络爬虫对 SEO,也就是<ruby> 搜索引擎优化 <rt> Search Engine Optimization </rt></ruby>有很大的影响。由于许多用户使用 Google,让 Google 爬虫为你的大部分网站建立索引非常重要。这可以通过许多方式来完成,包括不使用重复的内容,并在其他网站上具有尽可能多的反向链接。许多网站被认为是滥用这些技巧,最终被引擎列入黑名单。 ### robots.txt `robots.txt` 是爬虫在抓取你的网站时寻找的一种非常特殊的文件。该文件通常包含有关如何抓取你的网站的信息。一些网站管理员故意不希望他们的网站被索引也可以通过使用 `robots.txt` 文件阻止爬虫。 ### 总结 爬虫是一个小的软件机器人,可以用来浏览很多网站,并帮助搜索引擎从网上获得最相关的数据。 --- via: <http://www.theitstuff.com/web-crawler-web-crawlers-work> 作者:[Rishabh Kandari](http://www.theitstuff.com/author/reevkandari) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
520
null
9,365
在 Linux 中如何编写基本的 udev 规则
https://linuxconfig.org/tutorial-on-how-to-write-basic-udev-rules-in-linux
2018-02-20T15:06:32
[ "udev" ]
https://linux.cn/article-9365-1.html
![](/data/attachment/album/201802/20/150625yjhjrmmrzvsmmy6e.jpg) ### 读者对象 理解 udev 背后的基本概念,学习如何写简单的规则。 ### 要求 * root 权限 ### 难度 中等 ### 约定 * `#` - 要求给定的命令使用 root 权限或者直接以一个 root 用户或者使用 `sudo` 命令去运行。 * `$` - 要求给定的命令以一个普通的非特权用户运行。 ### 介绍 在 GNU/Linux 系统中,虽然设备的底层支持是在内核层面处理的,但是,它们相关的事件管理是在用户空间中通过 `udev` 来管理的。确切地说是由 `udevd` 守护进程来完成的。学习如何去写规则,并应用到发生的这些事件上,将有助于我们修改系统的行为并使它适合我们的需要。 ### 规则如何组织 udev 规则是定义在一个以 `.rules` 为扩展名的文件中。那些文件主要放在两个位置:`/usr/lib/udev/rules.d`,这个目录用于存放系统安装的规则;`/etc/udev/rules.d/` 这个目录是保留给自定义规则的。 定义那些规则的文件的命名惯例是使用一个数字作为前缀(比如,`50-udev-default.rules`),并且以它们在目录中的词汇顺序进行处理的。在 `/etc/udev/rules.d` 中安装的文件,会覆盖安装在系统默认路径中的同名文件。 ### 规则语法 如果你理解了 udev 规则的行为逻辑,它的语法并不复杂。一个规则由两个主要的节构成:`match` 部分,它使用一系列用逗号分隔的键定义了规则应用的条件,而 `action` 部分,是当条件满足时,我们执行一些动作。 ### 测试案例 讲解可能的选项的最好方法莫过于配置一个真实的案例,因此,我们去定义一个规则作为演示,当鼠标被连接时禁用触摸板。显然,在该规则定义中提供的属性将反映我的硬件。 我们将在 `/etc/udev/rules.d/99-togglemouse.rules` 文件中用我们喜欢的文本编辑器来写我们的规则。一条规则定义允许跨多个行,但是,如果是这种情况,必须在一个换行字符之前使用一个反斜线(`\`)表示行的延续,就和 shell 脚本一样。这是我们的规则: ``` ACTION=="add" \ , ATTRS{idProduct}=="c52f" \ , ATTRS{idVendor}=="046d" \ , ENV{DISPLAY}=":0" \ , ENV{XAUTHORITY}="/run/user/1000/gdm/Xauthority" \ , RUN+="/usr/bin/xinput --disable 16" ``` 我们来分析一下这个规则。 ### 操作符 首先,对已经使用以及将要使用的操作符解释如下: #### == 和 != 操作符 `==` 是相等操作符,而 `!=` 是不等于操作符。通过使用它们,我们可以确认规则上应用的键是否匹配各自的值。 #### 分配操作符 = 和 := `=` 是赋值操作符,是用于为一个键赋值。当我们想要赋值,并且想确保它不会被其它规则所覆盖,我们就需要使用 `:=` 操作符来代替,使用这个操作符分配的值,它就不能被改变。 #### += 和 -= 操作符 `+=` 和 `-=` 操作符各自用于从一个指定的键定义的值列表中增加或者移除一个值。 ### 我们使用的键 现在,来分析一下在这个规则中我们使用的键。首先,我们有一个 `ACTION` 键:通过使用它,当在一个设备上发生了特定的事件,我们将指定我们要应用的规则的具体内容。有效的值有 `add`、`remove` 以及 `change`。 然后,我们使用 `ATTRS` 关键字去指定一个属性去匹配。我们可以使用 `udevadm info` 命令去列出一个设备属性,提供它的名字或者 `sysfs` 路径即可: ``` udevadm info -ap /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.1/0003:046D:C52F.0010/input/input39 Udevadm info starts with the device specified by the devpath and then walks up the chain of parent devices. It prints for every device found, all possible attributes in the udev rules key format. A rule to match, can be composed by the attributes of the device and the attributes from one single parent device. looking at device '/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.1/0003:046D:C52F.0010/input/input39': KERNEL=="input39" SUBSYSTEM=="input" DRIVER=="" ATTR{name}=="Logitech USB Receiver" ATTR{phys}=="usb-0000:00:1d.0-1.2/input1" ATTR{properties}=="0" ATTR{uniq}=="" looking at parent device '/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.1/0003:046D:C52F.0010': KERNELS=="0003:046D:C52F.0010" SUBSYSTEMS=="hid" DRIVERS=="hid-generic" ATTRS{country}=="00" looking at parent device '/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.1': KERNELS=="2-1.2:1.1" SUBSYSTEMS=="usb" DRIVERS=="usbhid" ATTRS{authorized}=="1" ATTRS{bAlternateSetting}==" 0" ATTRS{bInterfaceClass}=="03" ATTRS{bInterfaceNumber}=="01" ATTRS{bInterfaceProtocol}=="00" ATTRS{bInterfaceSubClass}=="00" ATTRS{bNumEndpoints}=="01" ATTRS{supports_autosuspend}=="1" looking at parent device '/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2': KERNELS=="2-1.2" SUBSYSTEMS=="usb" DRIVERS=="usb" ATTRS{authorized}=="1" ATTRS{avoid_reset_quirk}=="0" ATTRS{bConfigurationValue}=="1" ATTRS{bDeviceClass}=="00" ATTRS{bDeviceProtocol}=="00" ATTRS{bDeviceSubClass}=="00" ATTRS{bMaxPacketSize0}=="8" ATTRS{bMaxPower}=="98mA" ATTRS{bNumConfigurations}=="1" ATTRS{bNumInterfaces}==" 2" ATTRS{bcdDevice}=="3000" ATTRS{bmAttributes}=="a0" ATTRS{busnum}=="2" ATTRS{configuration}=="RQR30.00_B0009" ATTRS{devnum}=="12" ATTRS{devpath}=="1.2" ATTRS{idProduct}=="c52f" ATTRS{idVendor}=="046d" ATTRS{ltm_capable}=="no" ATTRS{manufacturer}=="Logitech" ATTRS{maxchild}=="0" ATTRS{product}=="USB Receiver" ATTRS{quirks}=="0x0" ATTRS{removable}=="removable" ATTRS{speed}=="12" ATTRS{urbnum}=="1401" ATTRS{version}==" 2.00" [...] ``` 上面截取了运行这个命令之后的输出的一部分。正如你从它的输出中看到的那样,`udevadm` 从我们提供的指定路径开始,并且提供了所有父级设备的信息。注意设备的属性都是以单数的形式报告的(比如,`KERNEL`),而它的父级是以复数形式出现的(比如,`KERNELS`)。父级信息可以做为规则的一部分,但是同一时间只能有一个父级可以被引用:不同父级设备的属性混合在一起是不能工作的。在上面我们定义的规则中,我们使用了一个父级设备属性:`idProduct` 和 `idVendor`。 在我们的规则中接下来做的事情是,去使用 `ENV` 关键字:它既可以用于设置也可以用于去匹配环境变量。我们给 `DISPLAY` 和 `XAUTHORITY` 分配值。当我们使用 X 服务器程序进行交互去设置一些需要的信息时,这些变量是非常必要的:使用 `DISPLAY` 变量,我们指定服务器运行在哪个机器上,用的是哪个显示和屏幕;使用 `XAUTHORITY` 提供了一个文件路径,其包含了 Xorg 认证和授权信息。这个文件一般位于用户的家目录中。 最后,我们使用了 `RUN` 字:它用于运行外部程序。非常重要:这里没有立即运行,但是一旦所有的规则被解析,将运行各种动作。在这个案例中,我们使用 `xinput` 实用程序去改变触摸板的状态。我不想解释这里的 `xinput` 的语法,它超出了本文的范围,只需要注意这个触摸板的 ID 是 `16`。 规则设置完成之后,我们可以通过使用 `udevadm test` 命令去调试它。这个命令对调试非常有用,它并不真实去运行 `RUN` 指定的命令: ``` $ udevadm test --action="add" /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.1/0003:046D:C52F.0010/input/input39 ``` 我们提供给命令的是使用 `--action` 选项,以及设备的 sysfs 路径的模拟动作。如果没有报告错误,说明我们的规则运行的很好。要在真实的环境中去使用它,我们需要重新加载规则: ``` # udevadm control --reload ``` 这个命令将重新加载规则文件,但是,它只对重新加载之后发生的事件有效果。 我们通过创建一个 udev 规则了解了基本的概念和逻辑,这只是 udev 规则中众多的选项和可能的设置中的一小部分。udev 手册页提供了一个详尽的列表,如果你想深入了解,请参考它。 --- via: <https://linuxconfig.org/tutorial-on-how-to-write-basic-udev-rules-in-linux> 作者:[Egidio Docile](https://disqus.com/by/egidiodocile/) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,366
用一些超酷的功能使 Vim 变得更强大
http://www.linuxandubuntu.com/home/making-vim-even-more-awesome-with-these-cool-features
2018-02-21T09:21:00
[ "Vim" ]
https://linux.cn/article-9366-1.html
![](/data/attachment/album/201802/21/092153sxdxup1o8xoxqlks.jpg) Vim 是每个 Linux 发行版]中不可或缺的一部分,也是 Linux 用户最常用的工具(当然是基于终端的)。至少,这个说法对我来说是成立的。人们可能会在利用什么工具进行程序设计更好方面产生争议,的确 Vim 可能不是一个好的选择,因为有很多不同的 IDE 或其它类似于 Sublime Text 3,Atom 等使程序设计变得更加容易的成熟的文本编辑器。 ### 我的感想 但我认为,Vim 应该从一开始就以我们想要的方式运作,而其它编辑器让我们按照已经设计好的方式工作,实际上不是我们想要的工作方式。我不会过多地谈论其它编辑器,因为我没有过多地使用过它们(我对 Vim 情有独钟)。 不管怎样,让我们用 Vim 来做一些事情吧,它完全可以胜任。 ### 利用 Vim 进行程序设计 #### 执行代码 考虑一个场景,当我们使用 Vim 设计 C++ 代码并需要编译和运行它时,该怎么做呢。 (a). 我们通过 `Ctrl + Z` 返回到终端,或者利用 `:wq` 保存并退出。 (b). 但是任务还没有结束,接下来需要在终端上输入类似于 `g++ fileName.cxx` 的命令进行编译。 (c). 接下来需要键入 `./a.out` 执行它。 为了让我们的 C++ 代码在 shell 中运行,需要做很多事情。但这似乎并不是利用 Vim 操作的方法( Vim 总是倾向于把几乎所有操作方法利用一两个按键实现)。那么,做这些事情的 Vim 的方式究竟是什么? #### Vim 方式 Vim 不仅仅是一个文本编辑器,它是一种编辑文本的编程语言。这种帮助我们扩展 Vim 功能的编程语言是 “VimScript”(LCTT 译注: Vim 脚本)。 因此,在 VimScript 的帮助下,我们可以只需一个按键轻松地将编译和运行代码的任务自动化。 [![create functions in vim .vimrc](/data/attachment/album/201802/21/092153qfitt02ftv2ppz0u.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/vim_orig.png) 以上是在我的 `.vimrc` 配置文件里创建的一个名为 `CPP()` 函数的片段。 #### 利用 VimScript 创建函数 在 VimScript 中创建函数的语法非常简单。它以关键字 `func` 开头,然后是函数名(在 VimScript 中函数名必须以大写字母开头,否则 Vim 将提示错误)。在函数的结尾用关键词 `endfunc`。 在函数的主体中,可以看到 `exec` 语句,无论您在 `exec` 关键字之后写什么,都会在 Vim 的命令模式上执行(记住,就是在 Vim 窗口的底部以 `:` 开始的命令)。现在,传递给 `exec` 的字符串是(LCTT 译注:`:!clear && g++ % && ./a.out`) - [![vim functions commands & symbols](/data/attachment/album/201802/21/092153w9ll2l5glc2332cr.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/vim_1_orig.png) 当这个函数被调用时,它首先清除终端屏幕,因此只能看到输出,接着执行 `g++` 处理你工作的文件,然后运行由前一步编译而形成的 `a.out` 文件。 #### 将 ctrl+r 映射为运行 C++ 代码 我将语句 `call CPP()` 映射到键组合 `Ctrl+r`,以便我现在可以按 `Ctrl+r` 来执行我的 C++ 代码,无需手动输入 `:call CPP()`,然后按 `Enter` 键。 #### 最终结果 我们终于找到了 Vim 方式的操作方法。现在,你只需按一个(组合)键,你编写的 C++ 代码就输出在你的屏幕上,你不需要键入所有冗长的命令了。这也节省了你的时间。 我们也可以为其他语言实现这类功能。 [![create function in vim for python](/data/attachment/album/201802/21/092154p3t3b1eweh761g13.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/vim_2_orig.png) 对于Python:您可以按下 `Ctrl+e` 解释执行您的代码。 [![create function in vim for java](/data/attachment/album/201802/21/092154idydnd723dunqeve.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/vim_3_orig.png) 对于Java:您现在可以按下 `Ctrl+j`,它将首先编译您的 Java 代码,然后执行您的 Java 类文件并显示输出。 ### 进一步提高 所以,这就是如何在 Vim 中操作的方法。现在,我们来看看如何在 Vim 中实现所有这些。我们可以直接在 Vim 中使用这些代码片段,而另一种方法是使用 Vim 中的自动命令 `autocmd`。`autocmd` 的优点是这些命令无需用户调用,它们在用户所提供的任何特定条件下自动执行。 我想用 autocmd 实现这个,而不是对每种语言使用不同的映射,执行不同程序设计语言编译出的代码。 [![autocmd in vimrc](/data/attachment/album/201802/21/092154u3lkcdqwoohw6r60.png)](http://www.linuxandubuntu.com/uploads/2/1/1/5/21152474/vim_4_orig.png) 在这里做的是,为所有的定义了执行相应文件类型代码的函数编写了自动命令。 会发生什么?当我打开任何上述提到的文件类型的缓冲区, Vim 会自动将 `Ctrl + r` 映射到函数调用,而 `<CR>` 表示回车键,这样就不需要每完成一个独立的任务就按一次回车键了。 为了实现这个功能,您只需将函数片段添加到 `.vimrc` 文件中,然后将所有这些 `autocmd` 也一并添加进去。这样,当您下一次打开 Vim 时,Vim 将拥有所有相应的功能来执行所有具有相同绑定键的代码。 ### 总结 就这些了。希望这些能让你更爱 Vim 。我目前正在探究 Vim 中的一些内容,正阅读文档,补充 `.vimrc` 文件,当我研究出一些成果后我会再次与你分享。 如果你想看一下我现在的 `.vimrc` 文件,这是我的 Github 账户的链接: [MyVimrc](https://github.com/phenomenal-ab/VIm-Configurations/blob/master/.vimrc)。 期待你的好评。 --- via: <http://www.linuxandubuntu.com/home/making-vim-even-more-awesome-with-these-cool-features> 作者:[LINUXANDUBUNTU](http://www.linuxandubuntu.com) 译者:[stevenzdg988](https://github.com/stevenzdg988) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,367
会话与 Cookie:用户登录的原理是什么?
http://www.theitstuff.com/sessions-cookies-user-login-work
2018-02-21T11:54:00
[ "会话", "登录", "cookie" ]
https://linux.cn/article-9367-1.html
![](/data/attachment/album/201802/21/115419r2ix9xosmaqminbx.jpg) Facebook、 Gmail、 Twitter 是我们每天都会用的网站(LCTT 译注:才不是呢)。它们的共同点在于都需要你登录进去后才能做进一步的操作。只有你通过认证并登录后才能在 twitter 发推,在 Facebook 上评论,以及在 Gmail上处理电子邮件。 [![gmail, facebook login page](/data/attachment/album/201802/21/115432ezu3wuucuuupsdt3.jpg)](http://www.theitstuff.com/wp-content/uploads/2017/10/Untitled-design-1.jpg) 那么登录的原理是什么?网站是如何认证的?它怎么知道是哪个用户从哪儿登录进来的?下面我们来对这些问题进行一一解答。 ### 用户登录的原理是什么? 每次你在网站的登录页面中输入用户名和密码时,这些信息都会发送到服务器。服务器随后会将你的密码与服务器中的密码进行验证。如果两者不匹配,则你会得到一个错误密码的提示。如果两者匹配,则成功登录。 ### 登录时发生了什么? 登录后,web 服务器会初始化一个<ruby> 会话 <rt> session </rt></ruby>并在你的浏览器中设置一个 cookie 变量。该 cookie 变量用于作为新建会话的一个引用。搞晕了?让我们说的再简单一点。 ### 会话的原理是什么? 服务器在用户名和密码都正确的情况下会初始化一个会话。会话的定义很复杂,你可以把它理解为“关系的开始”。 [![session beginning of a relationship or partnership](/data/attachment/album/201802/21/115432xboligovi3ylyrlg.png)](http://www.theitstuff.com/wp-content/uploads/2017/10/pasted-image-0-9.png) 认证通过后,服务器就开始跟你展开一段关系了。由于服务器不能象我们人类一样看东西,它会在我们的浏览器中设置一个 cookie 来将我们的关系从其他人与服务器的关系标识出来。 ### 什么是 Cookie? cookie 是网站在你的浏览器中存储的一小段数据。你应该已经见过他们了。 [![theitstuff official facebook page cookies](/data/attachment/album/201802/21/115433rxip79d1957z0bk1.png)](http://www.theitstuff.com/wp-content/uploads/2017/10/pasted-image-0-1-4.png) 当你登录后,服务器为你创建一段关系或者说一个会话,然后将唯一标识这个会话的会话 id 以 cookie 的形式存储在你的浏览器中。 ### 什么意思? 所有这些东西存在的原因在于识别出你来,这样当你写评论或者发推时,服务器能知道是谁在发评论,是谁在发推。 当你登录后,会产生一个包含会话 id 的 cookie。这样,这个会话 id 就被赋予了那个输入正确用户名和密码的人了。 [![facebook cookies in web browser](/data/attachment/album/201802/21/115433jpxxfhxlz02fbcrv.png)](http://www.theitstuff.com/wp-content/uploads/2017/10/pasted-image-0-2-3-e1508926255472.png) 也就是说,会话 id 被赋予给了拥有这个账户的人了。之后,所有在网站上产生的行为,服务器都能通过他们的会话 id 来判断是由谁发起的。 ### 如何让我保持登录状态? 会话有一定的时间限制。这一点与现实生活中不一样,现实生活中的关系可以在不见面的情况下持续很长一段时间,而会话具有时间限制。你必须要不断地通过一些动作来告诉服务器你还在线。否则的话,服务器会关掉这个会话,而你会被登出。 [![websites keep me logged in option](/data/attachment/album/201802/21/115434bwn14z1wudgptrgo.png)](http://www.theitstuff.com/wp-content/uploads/2017/10/pasted-image-0-3-3-e1508926314117.png) 不过在某些网站上可以启用“保持登录”功能,这样服务器会将另一个唯一变量以 cookie 的形式保存到我们的浏览器中。这个唯一变量会通过与服务器上的变量进行对比来实现自动登录。若有人盗取了这个唯一标识(我们称之为 cookie stealing),他们就能访问你的账户了。 ### 结论 我们讨论了登录系统的工作原理以及网站是如何进行认证的。我们还学到了什么是会话和 cookies,以及它们在登录机制中的作用。 我们希望你们以及理解了用户登录的工作原理,如有疑问,欢迎提问。 --- via: <http://www.theitstuff.com/sessions-cookies-user-login-work> 作者:[Rishabh Kandari](http://www.theitstuff.com/author/reevkandari) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
520
null
9,368
如何 Docker 化编译的软件
https://tianon.github.io/post/2017/12/26/dockerize-compiled-software.html
2018-02-21T12:12:36
[ "编译", "Docker" ]
https://linux.cn/article-9368-1.html
![](/data/attachment/album/201802/21/121232xxx3wsf642xwv62m.jpg) 我最近在 [docker-library/php](https://github.com/docker-library/php) 仓库中关闭了大量问题,最老的(并且是最长的)讨论之一是关于安装编译扩展的依赖关系,我写了一个[中等篇幅的评论](https://github.com/docker-library/php/issues/75#issuecomment-353673374)解释了我如何用常规的方式为我想要的软件进行 Docker 化的。 我要在这里复制大部分的评论内容,或许扩展一点点,以便有一个更好的/更干净的链接! 我第一步是编写 `Dockerfile` 的原始版本:下载源码,运行 `./configure && make` 等,清理。然后我尝试构建我的原始版本,并希望在这过程中看到错误消息。(对,真的!) 错误信息通常以 `error: could not find "xyz.h"` 或 `error: libxyz development headers not found` 的形式出现。 如果我在 Debian 中构建,我会输入 `https://packages.debian.org/file:xyz.h`(用错误信息中头文件的名称替换 “xyz.h”),或者在谷歌中搜索像 “xyz.h debian” 这样的东西,找出我需要的包的名称。 如果我在 Alpine 中构建,我将使用 <https://pkgs.alpinelinux.org/contents> 进行类似的搜索。 “libxyz development headers” 在某种程度上也是一样的,但是根据我的经验,对于这些用 Google 对开发者来说效果更好,因为不同的发行版和项目会以不同的名字来调用这些开发包,所以有时候更难确切的知道哪一个是“正确”的。 当我得到包名后,我将这个包名称添加到我的 `Dockerfile` 中,清理之后,然后重复操作。最终通常会构建成功。偶尔我发现某些库不在 Debian 或 Alpine 中,或者是不够新的,由此我必须从源码构建它,但这些情况在我的经验中很少见 —— 因人而异。 我还会经常查看 Debian(通过 <https://sources.debian.org>)或 Alpine(通过 <https://git.alpinelinux.org/cgit/aports/tree>)我要编译的软件包源码,特别关注 `Build-Depends`(如 [`php7.0=7.0.26-1` 的 `debian/control` 文件](https://sources.debian.org/src/php7.0/7.0.26-1/debian/control/))以及/或者 `makedepends` (如 [`php7` 的 `APKBUILD` 文件](https://git.alpinelinux.org/cgit/aports/tree/community/php7/APKBUILD?id=d0ca197f031f96d4664cafaa618aeccf94640a1e))用于包名线索。 就我个人而言,我觉得这种侦探工作很有趣,也很有收获,但我意识到我可能是一个独特的生物。我偶尔使用的另一个技术是看是否有人已经 Docker 化了我想要的东西,这样我可以直接从他们的 `Dockerfile` 中知道我需要安装的东西。 对于特定的 PHP 扩展,几乎总是有人已经想出对于这个或那个模块需要的依赖,而我所要做的就是做一些轻量的工作找出它们。 不管怎样,这就是我的方法!希望这个有帮助,玩得愉快! --- via: <https://tianon.github.io/post/2017/12/26/dockerize-compiled-software.html> 作者:[Tianon Gravi](https://tianon.github.io) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,369
Telnet,爱一直在
https://bash-prompt.net/guides/telnet/
2018-02-22T10:59:32
[ "telnet" ]
https://linux.cn/article-9369-1.html
![](/data/attachment/album/201802/22/105938exdcxkgw6hccg772.jpg) Telnet,是系统管理员登录远程服务器的一种协议和工具。然而,由于所有的通信都没有加密,包括密码,都是明文发送的。Telnet 在 SSH 被开发出来之后就基本弃用了。 登录远程服务器,你可能不会也从未考虑过它。但这并不意味着 `telnet` 命令在调试远程连接问题时不是一个实用的工具。 本教程中,我们将探索使用 `telnet` 解决所有常见问题:“我怎么又连不上啦?” 这种讨厌的问题通常会在安装了像 Web服务器、邮件服务器、ssh 服务器、Samba 服务器等诸如此类的事之后遇到,用户无法连接服务器。 `telnet` 不会解决问题但可以很快缩小问题的范围。 `telnet` 用来调试网络问题的简单命令和语法: ``` telnet <hostname or IP> <port> ``` 因为 `telnet` 最初通过端口建立连接不会发送任何数据,适用于任何协议,包括加密协议。 连接问题服务器有四个可能会遇到的主要问题。我们会研究这四个问题,研究它们意味着什么以及如何解决。 本教程默认已经在 `samba.example.com` 安装了 [Samba](https://www.samba.org/) 服务器而且本地客户无法连上服务器。 ### Error 1 - 连接挂起 首先,我们需要试着用 `telnet` 连接 Samba 服务器。使用下列命令 (Samba 监听端口445): ``` telnet samba.example.com 445 ``` 有时连接会莫名停止: ``` telnet samba.example.com 445 Trying 172.31.25.31... ``` 这意味着 `telnet` 没有收到任何回应来建立连接。有两个可能的原因: 1. 你和服务器之间有个路由器宕掉了。 2. 防火墙拦截了你的请求。 为了排除第 1 点,对服务器上进行一个快速 [`mtr samba.example.com`](https://www.systutorials.com/docs/linux/man/8-mtr/) 。如果服务器是可达的,那么便是防火墙(注意:防火墙总是存在的)。 首先用 `iptables -L -v -n` 命令检查服务器本身有没有防火墙,没有的话你能看到以下内容: ``` iptables -L -v -n Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination ``` 如果你看到其他东西那可能就是问题所在了。为了检验,停止 `iptables` 一下并再次运行 `telnet samba.example.com 445` 看看你是否能连接。如果你还是不能连接看看你的提供商或企业有没有防火墙拦截你。 ### Error 2 - DNS 问题 DNS 问题通常发生在你正使用的主机名没有解析到 IP 地址。错误如下: ``` telnet samba.example.com 445 Server lookup failure: samba.example.com:445, Name or service not known ``` 第一步是把主机名替换成服务器的 IP 地址。如果你可以连上那么就是主机名的问题。 有很多发生的原因(以下是我见过的): 1. 域名注册了吗?用 `whois` 来检验。 2. 域名过期了吗?用 `whois` 来检验。 3. 是否使用正确的主机名?用 `dig` 或 `host` 来确保你使用的主机名解析到正确的 IP。 4. 你的 **A** 记录正确吗?确保你没有偶然创建类似 `smaba.example.com` 的 **A** 记录。 一定要多检查几次拼写和主机名是否正确(是 `samba.example.com` 还是 `samba1.example.com`)?这些经常会困扰你,特别是比较长、难记或其它国家的主机名。 ### Error 3 - 服务器没有侦听端口 这种错误发生在 `telnet` 可达服务器但是指定端口没有监听。就像这样: ``` telnet samba.example.com 445 Trying 172.31.25.31... telnet: Unable to connect to remote host: Connection refused ``` 有这些原因: 1. 你 **确定** 连接的是正确的服务器? 2. 你的应用服务器没有侦听预期的端口。在服务器上运行 `netstat -plunt` 来查看它究竟在干什么并看哪个端口才是对的,实际正在监听中的。 3. 应用服务器没有运行。这可能突然而又悄悄地发生在你启动应用服务器之后。启动服务器运行 `ps auxf` 或 `systemctl status application.service` 查看运行。 ### Error 4 - 连接被服务器关闭 这种错误发生在连接成功建立但是应用服务器建立的安全措施一连上就将其结束。错误如下: ``` telnet samba.example.com 445 Trying 172.31.25.31... Connected to samba.example.com. Escape character is '^]'. Connection closed by foreign host. ``` 最后一行 `Connection closed by foreign host.` 意味着连接被服务器主动终止。为了修复这个问题,需要看看应用服务器的安全设置确保你的 IP 或用户允许连接。 ### 成功连接 成功的 `telnet` 连接如下: ``` telnet samba.example.com 445 Trying 172.31.25.31... Connected to samba.example.com. Escape character is '^]'. ``` 连接会保持一段时间只要你连接的应用服务器时限没到。 输入 `CTRL+]` 中止连接,然后当你看到 `telnet>` 提示,输入 `quit` 并按回车: ``` telnet samba.example.com 445 Trying 172.31.25.31... Connected to samba.example.com. Escape character is '^]'. ^] telnet> quit Connection closed. ``` ### 总结 客户程序连不上服务器的原因有很多。确切原因很难确定,特别是当客户是图形用户界面提供很少或没有错误信息。用 `telnet` 并观察输出可以让你很快确定问题所在节约很多时间。 --- via: <https://bash-prompt.net/guides/telnet/> 作者:[Elliot Cooper](https://bash-prompt.net) 译者:[XYenChi](https://github.com/XYenChi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
Telnet, the protocol and the command line tool, were how system administrators used to log into remote servers. However, due to the fact that there is no encryption all communication, including passwords, are sent in plaintext meant that Telnet was abandoned in favour of SSH almost as soon as SSH was created. For the purposes of logging into a remote server, you should never, and probably have never considered it. This does not mean that the `telnet` command is not a very useful tool when used for debugging remote connection problems. In this guide, we will explore using `telnet` to answer the all too common question, “Why can’t I ###### connect‽”. This frustrated question is usually encountered after installing a application server like a web server, an email server, an ssh server, a Samba server etc, and for some reason, the client won’t connect to the server. `telnet` isn’t going to solve your problem but it will, very quickly, narrow down where you need to start looking to fix your problem. `telnet` is a very simple command to use for debugging network related issues and has the syntax: ``` telnet <hostname or IP> <port> ``` Because `telnet` will initially simply establish a connection to the port without sending any data it can be used with almost any protocol including encrypted protocols. There are four main errors that you will encounter when trying to connect to a problem server. We will look at all four, explore what they mean and look at how you should fix them. For this guide we will assume that we have just installed a [Samba](https://www.samba.org/) server at `samba.example.com` and we can’t get a local client to connect to the server. ### Error 1 - The connection that hangs forever First, we need to attempt to connect to the Samba server with `telnet` . This is done with the following command (Samba listens on port 445): ``` telnet samba.example.com 445 ``` Sometimes, the connection will get to this point stop and hang indefinitely: ``` telnet samba.example.com 445 Trying 172.31.25.31... ``` This means that `telnet` has not received any response to its request to establish a connection. This can happen for two reasons: - There is a router down between you and the server. - There is a firewall dropping your request. In order to rule out **1.** run a quick [ mtr samba.example.com](https://www.systutorials.com/docs/linux/man/8-mtr/) to the server. If the server is accessible then it’s a firewall (note: it’s almost always a firewall). Firstly, check if there are any firewall rules on the server itself with the following command `iptables -L -v -n` , if there are none then you will get the following output: ``` iptables -L -v -n Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination ``` If you see anything else then this is likely the problem. In order to check, stop `iptables` for a moment and run `telnet samba.example.com 445` again and see if you can connect. If you still can’t connect see if your provider and/or office has a firewall in place that is blocking you. ### Error 2 - DNS problems A DNS issue will occur if the hostname you are using does not resolve to an IP address. The error that you will see is as follows: ``` telnet samba.example.com 445 Server lookup failure: samba.example.com:445, Name or service not known ``` The first step here is to substitute the IP address of the server for the hostname. If you can connect to the IP but not the hostname then the problem is the hostname. This can happen for many reasons (I have seen all of the following): - Is the domain registered? Use `whois` to find out if it is. - Is the domain expired? Use `whois` to find out if it is. - Are you using the correct hostname? Use `dig` or`host` to ensure that the hostname you are using resolves to the correct IP. - Is your **A**record correct? Check that you didn’t accidentally create an**A**record for something like`smaba.example.com` . Always double check the spelling and the correct hostname (is it `samba.example.com` or `samba1.example.com` ) as this will often trip you up especially with long, complicated or foreign hostnames. ### Error 3 - The server isn’t listening on that port This error occurs when `telnet` is able to reach to the server but there is nothing listening on the port you specified. The error looks like this: ``` telnet samba.example.com 445 Trying 172.31.25.31... telnet: Unable to connect to remote host: Connection refused ``` This can happen for a couple of reasons: - Are you **sure**you’re connecting to the right server? - Your application server is not listening on the port you think it is. Check exactly what it’s doing by running `netstat -plunt` on the server and see what port it is, in fact, listening on. - The application server isn’t running. This can happen when the application server exits immediately and silently after you start it. Start the server and run `ps auxf` or`systemctl status application.service` to check it’s running. ### Error 4 - The connection was closed by the server This error happens when the connection was successful but the application server has a built in security measure that killed the connection as soon as it was made. This error looks like: ``` telnet samba.example.com 445 Trying 172.31.25.31... Connected to samba.example.com. Escape character is '^]'. Connection closed by foreign host. ``` The last line `Connection closed by foreign host.` indicates that the connection was actively terminated by the server. In order to fix this, you need to look at the security configuration of the application server to ensure your IP or user is allowed to connect to it. ### A successful connection This is what a successful `telnet` connection attempt looks like: ``` telnet samba.example.com 445 Trying 172.31.25.31... Connected to samba.example.com. Escape character is '^]'. ``` The connection will stay open for a while depending on the timeout of the application server you are connected to. A telnet connection is closed by typing `CTRL+]` and then when you see the `telnet>` prompt, type “quit” and hit ENTER i.e.: ``` telnet samba.example.com 445 Trying 172.31.25.31... Connected to samba.example.com. Escape character is '^]'. ^] telnet> quit Connection closed. ``` ### Conclusion There are a lot of reasons that a client application can’t connect to a server. The exact reason can be difficult to establish especially when the client is a GUI that offers little or no error information. Using `telnet` and observing the output will allow you to very rapidly narrow down where the problem lies and save you a whole lot of time.
9,370
containerd 1.0 探索之旅
https://blog.docker.com/2017/12/containerd-ga-features-2/
2018-02-22T12:47:00
[]
https://linux.cn/article-9370-1.html
![](/data/attachment/album/201802/22/124722gibtz0ag72azo442.jpg) 我们在过去的文章中讨论了一些 containerd 的不同特性,它是如何设计的,以及随着时间推移已经修复的一些问题。containerd 被用于 Docker、Kubernetes CRI、以及一些其它的项目,在这些平台中事实上都使用了 containerd,而许多人并不知道 containerd 存在于这些平台之中,这篇文章就是为这些人所写的。我将来会写更多的关于 containerd 的设计以及特性集方面的文章,但是现在,让我们从它的基础知识开始。 ![](/data/attachment/album/201802/22/124733dmzlyg59eg0i3rmh.jpg) 我认为容器生态系统有时候可能很复杂。尤其是我们所使用的术语。它是什么?一个运行时,还是别的?一个运行时 … containerd(它的发音是 “container-dee”)正如它的名字,它是一个容器守护进程,而不是一些人忽悠我的“<ruby> 收集 <rt> contain </rt></ruby><ruby> 迷 <rt> nerd </rt></ruby>”。它最初是作为 OCI 运行时(就像 runc 一样)的集成点而构建的,在过去的六个月中它增加了许多特性,使其达到了像 Docker 这样的现代容器平台以及像 Kubernetes 这样的编排平台的需求。 那么,你使用 containerd 能去做些什么呢?你可以拥有推送或拉取功能以及镜像管理。可以拥有容器生命周期 API 去创建、运行、以及管理容器和它们的任务。一个完整的专门用于快照管理的 API,以及一个其所依赖的开放治理的项目。如果你需要去构建一个容器平台,基本上你不需要去处理任何底层操作系统细节方面的事情。我认为关于 containerd 中最重要的部分是,它有一个版本化的并且有 bug 修复和安全补丁的稳定 API。 ![](/data/attachment/album/201802/22/124741loyjfe3oyqbew3la.jpg) 由于在内核中没有一个 Linux 容器这样的东西,因此容器是多种内核特性捆绑在一起而成的,当你构建一个大型平台或者分布式系统时,你需要在你的管理代码和系统调用之间构建一个抽象层,然后将这些特性捆绑粘接在一起去运行一个容器。而这个抽象层就是 containerd 的所在之处。它为稳定类型的平台层提供了一个客户端,这样平台可以构建在顶部而无需进入到内核级。因此,可以让使用容器、任务、和快照类型的工作相比通过管理调用去 clone() 或者 mount() 要友好的多。与灵活性相平衡,直接与运行时或者宿主机交互,这些对象避免了常规的高级抽象所带来的性能牺牲。结果是简单的任务很容易完成,而困难的任务也变得更有可能完成。 ![containerd](/data/attachment/album/201802/22/125521kllr1slfonf58qd2.jpg) containerd 被设计用于 Docker 和 Kubernetes、以及想去抽象出系统调用或者在 Linux、Windows、Solaris 以及其它的操作系统上特定的功能去运行容器的其它容器系统。考虑到这些用户的想法,我们希望确保 containerd 只拥有它们所需要的东西,而没有它们不希望的东西。事实上这是不太可能的,但是至少我们想去尝试一下。虽然网络不在 containerd 的范围之内,它并不能做成让高级系统可以完全控制的东西。原因是,当你构建一个分布式系统时,网络是非常中心的地方。现在,对于 SDN 和服务发现,相比于在 Linux 上抽象出 netlink 调用,网络是更特殊的平台。大多数新的网络都是基于路由的,并且每次一个新的容器被创建或者删除时,都会请求更新路由表。服务发现、DNS 等等都需要及时被通知到这些改变。如果在 containerd 中添加对网络的管理,为了能够支持不同的网络接口、钩子、以及集成点,将会在 containerd 中增加很大的一块代码。而我们的选择是,在 containerd 中做一个健壮的事件系统,以便于多个消费者可以去订阅它们所关心的事件。我们也公开发布了一个 [任务 API](https://github.com/containerd/containerd/blob/master/api/services/tasks/v1/tasks.proto),它可以让用户去创建一个运行任务,也可以在一个容器的网络命名空间中添加一个接口,以及在一个容器的生命周期中的任何时候,无需复杂的钩子来启用容器的进程。 在过去的几个月中另一个添加到 containerd 中的领域是完整的存储,以及支持 OCI 和 Docker 镜像格式的分布式系统。有了一个跨 containerd API 的完整的目录地址存储系统,它不仅适用于镜像,也适用于元数据、检查点、以及附加到容器的任何数据。 我们也花时间去 [重新考虑如何使用 “图驱动” 工作](https://blog.mobyproject.org/where-are-containerds-graph-drivers-145fc9b7255)。这些是叠加的或者允许镜像分层的块级文件系统,可以使你执行的构建更加高效。当我们添加对 devicemapper 的支持时,<ruby> 图驱动 <rt> graphdrivers </rt></ruby>最初是由 Solomon 和我写的。Docker 在那个时候仅支持 AUFS,因此我们在叠加文件系统之后,对图驱动进行了建模。但是,做一个像 devicemapper/lvm 这样的块级文件系统,就如同一个堆叠文件系统一样,从长远来看是非常困难的。这些接口必须基于时间的推移进行扩展,以支持我们最初认为并不需要的那些不同的特性。对于 containerd,我们使用了一个不同的方法,像快照一样做一个堆叠文件系统而不是相反。这样做起来更容易,因为堆叠文件系统比起像 BTRFS、ZFS 以及 devicemapper 这样的快照文件系统提供了更好的灵活性。因为这些文件系统没有严格的父/子关系。这有助于我们去构建出 [快照的一个小型接口](https://github.com/containerd/containerd/blob/master/api/services/snapshots/v1/snapshots.proto),同时还能满足 [构建者](https://blog.mobyproject.org/introducing-buildkit-17e056cc5317) 的要求,还能减少了需要的代码数量,从长远来看这样更易于维护。 ![](/data/attachment/album/201802/22/125526ewawwyyyywtvl7gl.jpg) 你可以在 [Stephen Day 2017/12/7 在 KubeCon SIG Node 上的演讲](https://speakerdeck.com/stevvooe/whats-happening-with-containerd-and-the-cri)找到更多关于 containerd 的架构方面的详细资料。 除了在 1.0 代码库中的技术和设计上的更改之外,我们也将 [containerd 管理模式从长期 BDFL 模式转换为技术委员会](https://github.com/containerd/containerd/pull/1748),为社区提供一个独立的可信任的第三方资源。 --- via: <https://blog.docker.com/2017/12/containerd-ga-features-2/> 作者:[Michael Crosby](https://blog.docker.com/author/michael/) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,371
如何使用 Ansible 创建 AWS ec2 密钥
https://www.cyberciti.biz/faq/how-to-create-aws-ec2-key-using-ansible/
2018-02-22T13:48:09
[ "Ansible" ]
https://linux.cn/article-9371-1.html
![](/data/attachment/album/201802/22/134813ljp54nphdoucnldd.jpg) **我想使用 Ansible 工具创建 Amazon EC2 密钥对。不想使用 AWS CLI 来创建。可以使用 Ansible 来创建 AWS ec2 密钥吗?** 你需要使用 Ansible 的 ec2\_key 模块。这个模块依赖于 python-boto 2.5 版本或者更高版本。 boto 是亚马逊 Web 服务的一个 Python API。你可以将 boto 用于 Amazon S3、Amazon EC2 等其他服务。简而言之,你需要安装 Ansible 和 boto 模块。我们一起来看下如何安装 boto 并结合 Ansible 使用。 ### 第一步 - 在 Ubuntu 上安装最新版本的 Ansible 你必须[给你的系统配置 PPA 来安装最新版的 Ansible](https://www.cyberciti.biz/faq/ubuntu-sudo-add-apt-repository-command-not-found-error/)。为了管理你从各种 PPA(Personal Package Archives)安装软件的仓库,你可以上传 Ubuntu 源码包并编译,然后通过 Launchpad 以 apt 仓库的形式发布。键入如下命令 [apt-get 命令](https://www.cyberciti.biz/tips/linux-debian-package-management-cheat-sheet.html "See Linux/Unix apt-get command examples for more info")或者 [apt 命令](https://www.cyberciti.biz/faq/ubuntu-lts-debian-linux-apt-command-examples/ "See Linux/Unix apt command examples for more info"): ``` $ sudo apt update $ sudo apt upgrade $ sudo apt install software-properties-common ``` 接下来给你的系统的软件源中添加 `ppa:ansible/ansible`。 ``` $ sudo apt-add-repository ppa:ansible/ansible ``` 更新你的仓库并安装 Ansible: ``` $ sudo apt update $ sudo apt install ansible ``` 安装 boto: ``` $ pip3 install boto3 ``` #### 关于在CentOS/RHEL 7.x上安装 Ansible 的注意事项 你[需要在 CentOS 和 RHEL 7.x 上配置 EPEL 源](https://www.cyberciti.biz/faq/installing-rhel-epel-repo-on-centos-redhat-7-x/)和 [yum命令](https://www.cyberciti.biz/faq/rhel-centos-fedora-linux-yum-command-howto/ "See Linux/Unix yum command examples for more info") ``` $ cd /tmp $ wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm $ ls *.rpm $ sudo yum install epel-release-latest-7.noarch.rpm $ sudo yum install ansible ``` 安装 boto: ``` $ pip install boto3 ``` ### 第二步 2 – 配置 boto 你需要配置 AWS credentials/API 密钥。参考 “[AWS Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)” 文档如何创建 API key。用 `mkdir` 命令创建一个名为 `~/.aws` 的目录,然后配置 API key: ``` $ mkdir -pv ~/.aws/ $ vi ~/.aws/credentials ``` ``` [default] aws_access_key_id = YOUR-ACCESS-KEY-HERE aws_secret_access_key = YOUR-SECRET-ACCESS-KEY-HERE ``` 还需要配置默认 [AWS 区域](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html): ``` $ vi ~/.aws/config ``` 输出样例如下: ``` [default] region = us-west-1 ``` 通过创建一个简单的名为 `test-boto.py` 的 Python 程序来测试你的 boto 配置是否正确: ``` #!/usr/bin/python3 # A simple program to test boto and print s3 bucket names import boto3 t = boto3.resource('s3') for b in t.buckets.all(): print(b.name) ``` 按下面方式来运行该程序: ``` $ python3 test-boto.py ``` 输出样例: ``` nixcraft-images nixcraft-backups-cbz nixcraft-backups-forum ``` 上面输出可以确定 Python-boto 可以使用 AWS API 正常工作。 ### 步骤 3 - 使用 Ansible 创建 AWS ec2 密钥 创建一个名为 `ec2.key.yml` 的剧本,如下所示: ``` --- - hosts: local connection: local gather_facts: no tasks: - name: Create a new EC2 key ec2_key: name: nixcraft-key region: us-west-1 register: ec2_key_result - name: Save private key copy: content="{{ ec2_key_result.key.private_key }}" dest="./aws.nixcraft.pem" mode=0600 when: ec2_key_result.changed ``` 其中, * `ec2_key:` – ec2 密钥对。 * `name: nixcraft_key` – 密钥对的名称。 * `region: us-west-1` – 使用的 AWS 区域。 * `register: ec2_key_result` – 保存生成的密钥到 ec2*key*result 变量。 * `copy: content="{{ ec2_key_result.key.private_key }}" dest="./aws.nixcraft.pem" mode=0600` – 将 `ec2_key_result.key.private_key` 的内容保存到当前目录的一个名为 `aws.nixcraft.pem` 的文件中。设置该文件的权限为 `0600` (unix 文件权限)。 * `when: ec2_key_result.changed` – 仅仅在 `ec2_key_result` 改变时才保存。我们不想覆盖你的密钥文件。 你还必须创建如下 `hosts` 文件: ``` [local] localhost ``` 如下运行你的剧本: ``` $ ansible-playbook -i hosts ec2.key.yml ``` ![](/data/attachment/album/201802/22/134816pd989drucghpzg8c.jpg) 最后你应该有一个名为 `aws.nixcraft.pem 私钥,该私钥可以和 AWS EC2 一起使用。使用 [cat 命令](https://www.cyberciti.biz/faq/linux-unix-appleosx-bsd-cat-command-examples/ "See Linux/Unix cat command examples for more info")查看你的密钥: ``` $ cat aws.nixcraft.pem ``` 如果你有 EC2 虚拟机,请按如下方式使用: ``` $ ssh -i aws.nixcraft.pem user@ec2-vm-dns-name ``` **查看有关 python 数据结构变量名的信息,比如 ec2*key*result.changed 和 ec2*key*result.key.private\_key** 你一定在想我是如何使用变量名的,比如 `ec2_key_result.changed` 和 `ec2_key_result.key.private_key`。它们在哪里定义过吗?变量的值是通过 API 调用返回的。简单地使用 `-v` 选项运行 `ansible-playbook` 命令来查看这样的信息: ``` $ ansible-playbook -v -i hosts ec2.key.yml ``` ![](/data/attachment/album/201802/22/134816lzu6iy99q7u9ndiu.jpg) ### 我该如何删除一个密钥? 使用如下 `ec2-key-delete.yml`: ``` --- - hosts: local connection: local gather_facts: no tasks: - name: Delete a EC2 key ec2_key: name: nixcraft-key region: us-west-1 # absent means delete keypair state: absent ``` 按照如下方式运行: ``` $ ansible-playbook -i hosts ec2-key-delete.yml ``` ### 关于作者 作者是 nixCraft 的创始人,是一个经验丰富的系统管理员,DevOps 工程师,同时是一个 Linux 操作系统/Unix shell 脚本培训师。**通过 [RSS/XML 提要](https://www.cyberciti.biz/atom/atom.xml)或[每周邮件简讯](https://www.cyberciti.biz/subscribe-to-weekly-linux-unix-newsletter-for-sysadmin/)获得关于系统管理,Linux/Unix和开放源码主题的最新教程。** --- via: <https://www.cyberciti.biz/faq/how-to-create-aws-ec2-key-using-ansible/> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[qianghaohao](https://github.com/qianghaohao) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,372
使用 Python 的 urllib.parse 库解析 URL
https://github.com/lujun9972/lujun9972.github.com/blob/source/%E7%BC%96%E7%A8%8B%E4%B9%8B%E6%97%85/%E4%BD%BF%E7%94%A8urlliib.parse%E5%BA%93%E8%A7%A3%E6%9E%90url.org
2018-02-22T23:51:00
[ "Python", "URL" ]
https://linux.cn/article-9372-1.html
![](/data/attachment/album/201802/22/235511q1pbibaabi5cx6xf.jpg) Python 中的 `urllib.parse` 模块提供了很多解析和组建 URL 的函数。 ### 解析url `urlparse()` 函数可以将 URL 解析成 `ParseResult` 对象。对象中包含了六个元素,分别为: * 协议(scheme) * 域名(netloc) * 路径(path) * 路径参数(params) * 查询参数(query) * 片段(fragment) ``` from urllib.parse import urlparse url='http://user:pwd@domain:80/path;params?query=queryarg#fragment' parsed_result=urlparse(url) print('parsed_result 包含了',len(parsed_result),'个元素') print(parsed_result) ``` 结果为: ``` parsed_result 包含了 6 个元素 ParseResult(scheme='http', netloc='user:pwd@domain:80', path='/path', params='params', query='query=queryarg', fragment='fragment') ``` `ParseResult` 继承于 `namedtuple`,因此可以同时通过索引和命名属性来获取 URL 中各部分的值。 为了方便起见, `ParseResult` 还提供了 `username`、 `password`、 `hostname`、 `port` 对 `netloc` 进一步进行拆分。 ``` print('scheme :', parsed_result.scheme) print('netloc :', parsed_result.netloc) print('path :', parsed_result.path) print('params :', parsed_result.params) print('query :', parsed_result.query) print('fragment:', parsed_result.fragment) print('username:', parsed_result.username) print('password:', parsed_result.password) print('hostname:', parsed_result.hostname) print('port :', parsed_result.port) ``` 结果为: ``` scheme : http netloc : user:pwd@domain:80 path : /path params : params query : query=queryarg fragment: fragment username: user password: pwd hostname: domain port : 80 ``` 除了 `urlparse()` 之外,还有一个类似的 `urlsplit()` 函数也能对 URL 进行拆分,所不同的是, `urlsplit()` 并不会把 `路径参数(params)` 从 `路径(path)` 中分离出来。 当 URL 中路径部分包含多个参数时,使用 `urlparse()` 解析是有问题的: ``` url='http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment' parsed_result=urlparse(url) print(parsed_result) print('parsed.path :', parsed_result.path) print('parsed.params :', parsed_result.params) ``` 结果为: ``` ParseResult(scheme='http', netloc='user:pwd@domain:80', path='/path1;params1/path2', params='params2', query='query=queryarg', fragment='fragment') parsed.path : /path1;params1/path2 parsed.params : params2 ``` 这时可以使用 `urlsplit()` 来解析: ``` from urllib.parse import urlsplit split_result=urlsplit(url) print(split_result) print('split.path :', split_result.path) # SplitResult 没有 params 属性 ``` 结果为: ``` SplitResult(scheme='http', netloc='user:pwd@domain:80', path='/path1;params1/path2;params2', query='query=queryarg', fragment='fragment') split.path : /path1;params1/path2;params2 ``` 若只是要将 URL 后的 `fragment` 标识拆分出来,可以使用 `urldefrag()` 函数: ``` from urllib.parse import urldefrag url = 'http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment' d = urldefrag(url) print(d) print('url :', d.url) print('fragment:', d.fragment) ``` 结果为: ``` DefragResult(url='http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg', fragment='fragment') url : http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg fragment: fragment ``` ### 组建URL `ParsedResult` 对象和 `SplitResult` 对象都有一个 `geturl()` 方法,可以返回一个完整的 URL 字符串。 ``` print(parsed_result.geturl()) print(split_result.geturl()) ``` 结果为: ``` http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment ``` 但是 `geturl()` 只在 `ParsedResult` 和 `SplitResult` 对象中有,若想将一个普通的元组组成 URL,则需要使用 `urlunparse()` 函数: ``` from urllib.parse import urlunparse url_compos = ('http', 'user:pwd@domain:80', '/path1;params1/path2', 'params2', 'query=queryarg', 'fragment') print(urlunparse(url_compos)) ``` 结果为: ``` http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment ``` ### 相对路径转换绝对路径 除此之外,`urllib.parse` 还提供了一个 `urljoin()` 函数,来将相对路径转换成绝对路径的 URL。 ``` from urllib.parse import urljoin print(urljoin('http://www.example.com/path/file.html', 'anotherfile.html')) print(urljoin('http://www.example.com/path/', 'anotherfile.html')) print(urljoin('http://www.example.com/path/file.html', '../anotherfile.html')) print(urljoin('http://www.example.com/path/file.html', '/anotherfile.html')) ``` 结果为: ``` http://www.example.com/path/anotherfile.html http://www.example.com/path/anotherfile.html http://www.example.com/anotherfile.html http://www.example.com/anotherfile.html ``` ### 查询参数的构造和解析 使用 `urlencode()` 函数可以将一个 dict 转换成合法的查询参数: ``` from urllib.parse import urlencode query_args = { 'name': 'dark sun', 'country': '中国' } query_args = urlencode(query_args) print(query_args) ``` 结果为: ``` name=dark+sun&country=%E4%B8%AD%E5%9B%BD ``` 可以看到特殊字符也被正确地转义了。 相对的,可以使用 `parse_qs()` 来将查询参数解析成 dict。 ``` from urllib.parse import parse_qs print(parse_qs(query_args)) ``` 结果为: ``` {'name': ['dark sun'], 'country': ['中国']} ``` 如果只是希望对特殊字符进行转义,那么可以使用 `quote` 或 `quote_plus` 函数,其中 `quote_plus` 比 `quote` 更激进一些,会把 `:`、`/` 一类的符号也给转义了。 ``` from urllib.parse import quote, quote_plus, urlencode url = 'http://localhost:1080/~hello!/' print('urlencode :', urlencode({'url': url})) print('quote :', quote(url)) print('quote_plus:', quote_plus(url)) ``` 结果为: ``` urlencode : url=http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F quote : http%3A//localhost%3A1080/%7Ehello%21/ quote_plus: http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F ``` 可以看到 `urlencode` 中应该是调用 `quote_plus` 来进行转义的。 逆向操作则使用 `unquote` 或 `unquote_plus` 函数: ``` from urllib.parse import unquote, unquote_plus encoded_url = 'http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F' print(unquote(encoded_url)) print(unquote_plus(encoded_url)) ``` 结果为: ``` http://localhost:1080/~hello!/ http://localhost:1080/~hello!/ ``` 你会发现 `unquote` 函数居然能正确地将 `quote_plus` 的结果转换回来。
200
OK
python中的urllib.parse module提供了很多解析和组建URL的函数。 `urlparse()` 函数可以将url解析成 `ParseResult` 对象. 对象中包含了六个元素,分别为: - 协议(scheme) - 域名(netloc) - 路径(path) - 路径参数(params) - 查询参数(query) - 片段(fragment) ``` from urllib.parse import urlparse url='http://user:pwd@domain:80/path;params?query=queryarg#fragment' parsed_result=urlparse(url) print('parsed_result包含了',len(parsed_result),'个元素') print(parsed_result) ``` 结果为: ``` parsed_result包含了 6 个元素 ParseResult(scheme='http', netloc='user:pwd@domain:80', path='/path', params='params', query='query=queryarg', fragment='fragment') ``` `ParseResult` 继承于 `namedtuple` , 因此既可以同时通过索引和命名属性来获取URL中各部分的值 为了方便起见, `ParseResult` 还提供了 `username` , `password` , `hostname` , `port` 对 `netloc` 进一步进行拆分。 ``` print('scheme :', parsed_result.scheme) print('netloc :', parsed_result.netloc) print('path :', parsed_result.path) print('params :', parsed_result.params) print('query :', parsed_result.query) print('fragment:', parsed_result.fragment) print('username:', parsed_result.username) print('password:', parsed_result.password) print('hostname:', parsed_result.hostname) print('port :', parsed_result.port) ``` 结果为: ``` scheme : http netloc : user:pwd@domain:80 path : /path params : params query : query=queryarg fragment: fragment username: user password: pwd hostname: domain port : 80 ``` 除了 `urlparse()` 之外,还有一个类似的 `urlsplit()` 函数也能对URL进行拆分,所不同的是, `urlsplit()` 并不会把 `路径参数(params)` 从 `路径(path)` 中分离出来。 当URL中path部分包含多个参数时,使用 `urlparse()` 解析是有问题的 ``` url='http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment' parsed_result=urlparse(url) print(parsed_result) print('parsed.path :', parsed_result.path) print('parsed.params :', parsed_result.params) ``` 结果为: ``` ParseResult(scheme='http', netloc='user:pwd@domain:80', path='/path1;params1/path2', params='params2', query='query=queryarg', fragment='fragment') parsed.path : /path1;params1/path2 parsed.params : params2 ``` 这时可以使用 `urlsplit()` 来解析 ``` from urllib.parse import urlsplit split_result=urlsplit(url) print(split_result) print('split.path :', split_result.path) # SplitResult 没有params属性 ``` 结果为: ``` SplitResult(scheme='http', netloc='user:pwd@domain:80', path='/path1;params1/path2;params2', query='query=queryarg', fragment='fragment') split.path : /path1;params1/path2;params2 ``` 若只是要将URL后的fragment标识拆分出来,可以使用 `urldefrag()` 函数 ``` from urllib.parse import urldefrag url = 'http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment' d = urldefrag(url) print(d) print('url :', d.url) print('fragment:', d.fragment) ``` 结果为: ``` DefragResult(url='http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg', fragment='fragment') url : http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg fragment: fragment ``` ParsedResult对象和SplitResult对象都有一个 `geturl()` 方法,可以返回一个完整的URL字符串 ``` print(parsed_result.geturl()) print(split_result.geturl()) ``` 结果为: ``` http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment ``` 但是 `geturl()` 只在ParsedResult和SplitResult对象中有,若想将一个普通的元组组成URL,则需要使用 `urlunparse()` 函数 ``` from urllib.parse import urlunparse url_compos = ('http', 'user:pwd@domain:80', '/path1;params1/path2', 'params2', 'query=queryarg', 'fragment') print(urlunparse(url_compos)) ``` 结果为: ``` http://user:pwd@domain:80/path1;params1/path2;params2?query=queryarg#fragment ``` 除此之外,urllib.parse 还提供了一个 `urljoin()` 函数,来将相对路径转换成绝对路径的URL ``` from urllib.parse import urljoin print(urljoin('http://www.example.com/path/file.html', 'anotherfile.html')) print(urljoin('http://www.example.com/path/', 'anotherfile.html')) print(urljoin('http://www.example.com/path/file.html', '../anotherfile.html')) print(urljoin('http://www.example.com/path/file.html', '/anotherfile.html')) ``` 结果为: ``` http://www.example.com/path/anotherfile.html http://www.example.com/path/anotherfile.html http://www.example.com/anotherfile.html http://www.example.com/anotherfile.html ``` 使用 `urlencode()` 函数可以将一个dict转换成合法的查询参数: ``` from urllib.parse import urlencode query_args = { 'name': 'dark sun', 'country': '中国' } query_args = urlencode(query_args) print(query_args) ``` 结果为: ``` name=dark+sun&country=%E4%B8%AD%E5%9B%BD ``` 可以看到特殊字符也被正确地转义了。 相对的,可以使用 `parse_qs()` 来将查询参数解析成dict ``` from urllib.parse import parse_qs print(parse_qs(query_args)) ``` 结果为: ``` {'name': ['dark sun'], 'country': ['中国']} ``` 如果只是希望对特殊字符进行转义,那么可以使用 `quote` 或 `quote_plus` 函数,其中 `quote_plus` 比 `quote` 更激进一些,会把 `:/` 一类的符号也给转义了 ``` from urllib.parse import quote, quote_plus, urlencode url = 'http://localhost:1080/~hello!/' print('urlencode :', urlencode({'url': url})) print('quote :', quote(url)) print('quote_plus:', quote_plus(url)) ``` 结果为: ``` urlencode : url=http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F quote : http%3A//localhost%3A1080/%7Ehello%21/ quote_plus: http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F ``` 可以看到 `urlencode` 中应该是调用 `quote_plus` 来进行转义的 逆向操作则使用 `unquote` 或 `unquote_plus` 函数 ``` from urllib.parse import unquote, unquote_plus encoded_url = 'http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F' print(unquote(encoded_url)) print(unquote_plus(encoded_url)) ``` 结果为: ``` http://localhost:1080/~hello!/ http://localhost:1080/~hello!/ ``` 你会发现 `unquote` 函数居然能正确地将 `quote_plus` 的结果转换回来。
9,373
每个系统管理员都要知道的 30 个 Linux 系统监控工具
https://www.cyberciti.biz/tips/top-linux-monitoring-tools.html
2018-02-23T00:36:00
[ "监控" ]
https://linux.cn/article-9373-1.html
![](/data/attachment/album/201802/23/003604wd2215mdgd5i1g2y.jpg) 您需要监控 Linux 服务器的性能吗?试试用这些内置命令和附加工具吧!大多数 Linux 发行版都附带了大量的监控工具。这些工具提供了获取系统活动的相关指标。您可以使用这些工具来查找性能问题的可能原因。本文提到的是一些基本的命令,用于系统分析和服务器调试等,例如: 1. 找出系统瓶颈 2. 磁盘(存储)瓶颈 3. CPU 和内存瓶颈 4. 网络瓶颈 ### 1. top - 进程活动监控命令 `top` 命令会显示 Linux 的进程。它提供了一个运行中系统的实时动态视图,即实际的进程活动。默认情况下,它显示在服务器上运行的 CPU 占用率最高的任务,并且每五秒更新一次。 ![](/data/attachment/album/201802/23/003617yrapgeguzhzegrjm.jpg) *图 01:Linux top 命令* #### top 的常用快捷键 常用快捷键列表: | 快捷键 | 用法 | | --- | --- | | `t` | 是否显示汇总信息 | | `m` | 是否显示内存信息 | | `A` | 根据各种系统资源的利用率对进程进行排序,有助于快速识别系统中性能不佳的任务。 | | `f` | 进入 `top` 的交互式配置屏幕,用于根据特定的需求而设置 `top` 的显示。 | | `o` | 交互式地调整 `top` 每一列的顺序。 | | `r` | 调整优先级(`renice`) | | `k` | 杀掉进程(`kill`) | | `z` | 切换彩色或黑白模式 | 相关链接:[Linux 如何查看 CPU 利用率?](https://www.cyberciti.biz/tips/how-do-i-find-out-linux-cpu-utilization.html) ### 2. vmstat - 虚拟内存统计 `vmstat` 命令报告有关进程、内存、分页、块 IO、中断和 CPU 活动等信息。 ``` # vmstat 3 ``` 输出示例: ``` procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------ r b swpd free buff cache si so bi bo in cs us sy id wa st 0 0 0 2540988 522188 5130400 0 0 2 32 4 2 4 1 96 0 0 1 0 0 2540988 522188 5130400 0 0 0 720 1199 665 1 0 99 0 0 0 0 0 2540956 522188 5130400 0 0 0 0 1151 1569 4 1 95 0 0 0 0 0 2540956 522188 5130500 0 0 0 6 1117 439 1 0 99 0 0 0 0 0 2540940 522188 5130512 0 0 0 536 1189 932 1 0 98 0 0 0 0 0 2538444 522188 5130588 0 0 0 0 1187 1417 4 1 96 0 0 0 0 0 2490060 522188 5130640 0 0 0 18 1253 1123 5 1 94 0 0 ``` #### 显示 Slab 缓存的利用率 ``` # vmstat -m ``` #### 获取有关活动和非活动内存页面的信息 ``` # vmstat -a ``` 相关链接:[如何查看 Linux 的资源利用率从而找到系统瓶颈?](https://www.cyberciti.biz/tips/linux-resource-utilization-to-detect-system-bottlenecks.html) ### 3. w - 找出登录的用户以及他们在做什么 [w 命令](https://www.cyberciti.biz/faq/unix-linux-w-command-examples-syntax-usage-2/ "See Linux/Unix w command examples for more info") 显示了当前登录在该系统上的用户及其进程。 ``` # w username # w vivek ``` 输出示例: ``` 17:58:47 up 5 days, 20:28, 2 users, load average: 0.36, 0.26, 0.24 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root pts/0 10.1.3.145 14:55 5.00s 0.04s 0.02s vim /etc/resolv.conf root pts/1 10.1.3.145 17:43 0.00s 0.03s 0.00s w ``` ### 4. uptime - Linux 系统运行了多久 `uptime` 命令可以用来查看服务器运行了多长时间:当前时间、已运行的时间、当前登录的用户连接数,以及过去 1 分钟、5 分钟和 15 分钟的系统负载平均值。 ``` # uptime ``` 输出示例: ``` 18:02:41 up 41 days, 23:42, 1 user, load average: 0.00, 0.00, 0.00 ``` `1` 可以被认为是最佳负载值。不同的系统会有不同的负载:对于单核 CPU 系统来说,`1` 到 `3` 的负载值是可以接受的;而对于 SMP(对称多处理)系统来说,负载可以是 `6` 到 `10`。 ### 5. ps - 显示系统进程 `ps` 命令显示当前运行的进程。要显示所有的进程,请使用 `-A` 或 `-e` 选项: ``` # ps -A ``` 输出示例: ``` PID TTY TIME CMD 1 ? 00:00:02 init 2 ? 00:00:02 migration/0 3 ? 00:00:01 ksoftirqd/0 4 ? 00:00:00 watchdog/0 5 ? 00:00:00 migration/1 6 ? 00:00:15 ksoftirqd/1 .... ..... 4881 ? 00:53:28 java 4885 tty1 00:00:00 mingetty 4886 tty2 00:00:00 mingetty 4887 tty3 00:00:00 mingetty 4888 tty4 00:00:00 mingetty 4891 tty5 00:00:00 mingetty 4892 tty6 00:00:00 mingetty 4893 ttyS1 00:00:00 agetty 12853 ? 00:00:00 cifsoplockd 12854 ? 00:00:00 cifsdnotifyd 14231 ? 00:10:34 lighttpd 14232 ? 00:00:00 php-cgi 54981 pts/0 00:00:00 vim 55465 ? 00:00:00 php-cgi 55546 ? 00:00:00 bind9-snmp-stat 55704 pts/1 00:00:00 ps ``` `ps` 与 `top` 类似,但它提供了更多的信息。 #### 显示长输出格式 ``` # ps -Al ``` 显示完整输出格式(它将显示传递给进程的命令行参数): ``` # ps -AlF ``` #### 显示线程(轻量级进程(LWP)和线程的数量(NLWP)) ``` # ps -AlFH ``` #### 在进程后显示线程 ``` # ps -AlLm ``` #### 显示系统上所有的进程 ``` # ps ax # ps axu ``` #### 显示进程树 ``` # ps -ejH # ps axjf # pstree ``` #### 显示进程的安全信息 ``` # ps -eo euser,ruser,suser,fuser,f,comm,label # ps axZ # ps -eM ``` #### 显示指定用户(如 vivek)运行的进程 ``` # ps -U vivek -u vivek u ``` #### 设置用户自定义的输出格式 ``` # ps -eo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,wchan:14,comm # ps axo stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,pcpu,comm # ps -eopid,tt,user,fname,tmout,f,wchan ``` #### 显示某进程(如 lighttpd)的 PID ``` # ps -C lighttpd -o pid= ``` 或 ``` # pgrep lighttpd ``` 或 ``` # pgrep -u vivek php-cgi ``` #### 显示指定 PID(如 55977)的进程名称 ``` # ps -p 55977 -o comm= ``` #### 找出占用内存资源最多的前 10 个进程 ``` # ps -auxf | sort -nr -k 4 | head -10 ``` #### 找出占用 CPU 资源最多的前 10 个进程 ``` # ps -auxf | sort -nr -k 3 | head -10 ``` 相关链接:[显示 Linux 上所有运行的进程](https://www.cyberciti.biz/faq/show-all-running-processes-in-linux/) ### 6. free - 内存使用情况 `free` 命令显示了系统的可用和已用的物理内存及交换内存的总量,以及内核用到的缓存空间。 ``` # free ``` 输出示例: ``` total used free shared buffers cached Mem: 12302896 9739664 2563232 0 523124 5154740 -/+ buffers/cache: 4061800 8241096 Swap: 1052248 0 1052248 ``` 相关链接: 1. [获取 Linux 的虚拟内存的内存页大小(PAGESIZE)](https://www.cyberciti.biz/faq/linux-check-the-size-of-pagesize/) 2. [限制 Linux 每个进程的 CPU 使用率](https://www.cyberciti.biz/faq/cpu-usage-limiter-for-linux/) 3. [我的 Ubuntu 或 Fedora Linux 系统有多少内存?](https://www.cyberciti.biz/tips/how-much-ram-does-my-linux-system.html) ### 7. iostat - CPU 平均负载和磁盘活动 `iostat` 命令用于汇报 CPU 的使用情况,以及设备、分区和网络文件系统(NFS)的 IO 统计信息。 ``` # iostat ``` 输出示例: ``` Linux 2.6.18-128.1.14.el5 (www03.nixcraft.in) 06/26/2009 avg-cpu: %user %nice %system %iowait %steal %idle 3.50 0.09 0.51 0.03 0.00 95.86 Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn sda 22.04 31.88 512.03 16193351 260102868 sda1 0.00 0.00 0.00 2166 180 sda2 22.04 31.87 512.03 16189010 260102688 sda3 0.00 0.00 0.00 1615 0 ``` 相关链接:[如何跟踪 Linux 系统的 NFS 目录或磁盘的 IO 负载情况](https://www.cyberciti.biz/faq/howto-linux-track-nfs-client-disk-metrics/) ### 8. sar - 监控、收集和汇报系统活动 `sar` 命令用于收集、汇报和保存系统活动信息。要查看网络统计,请输入: ``` # sar -n DEV | more ``` 显示 24 日的网络统计: `# sar -n DEV -f /var/log/sa/sa24 | more` 您还可以使用 `sar` 显示实时使用情况: ``` # sar 4 5 ``` 输出示例: ``` Linux 2.6.18-128.1.14.el5 (www03.nixcraft.in) 06/26/2009 06:45:12 PM CPU %user %nice %system %iowait %steal %idle 06:45:16 PM all 2.00 0.00 0.22 0.00 0.00 97.78 06:45:20 PM all 2.07 0.00 0.38 0.03 0.00 97.52 06:45:24 PM all 0.94 0.00 0.28 0.00 0.00 98.78 06:45:28 PM all 1.56 0.00 0.22 0.00 0.00 98.22 06:45:32 PM all 3.53 0.00 0.25 0.03 0.00 96.19 Average: all 2.02 0.00 0.27 0.01 0.00 97.70 ``` 相关链接: * [如何将 Linux 系统资源利用率的数据写入文件中](https://www.cyberciti.biz/tips/howto-write-system-utilization-data-to-file.html) * [如何使用 kSar 创建 sar 性能图以找出系统瓶颈](https://www.cyberciti.biz/tips/identifying-linux-bottlenecks-sar-graphs-with-ksar.html) ### 9. mpstat - 监控多处理器的使用情况 `mpstat` 命令显示每个可用处理器的使用情况,编号从 0 开始。命令 `mpstat -P ALL` 显示了每个处理器的平均使用率: ``` # mpstat -P ALL ``` 输出示例: ``` Linux 2.6.18-128.1.14.el5 (www03.nixcraft.in) 06/26/2009 06:48:11 PM CPU %user %nice %sys %iowait %irq %soft %steal %idle intr/s 06:48:11 PM all 3.50 0.09 0.34 0.03 0.01 0.17 0.00 95.86 1218.04 06:48:11 PM 0 3.44 0.08 0.31 0.02 0.00 0.12 0.00 96.04 1000.31 06:48:11 PM 1 3.10 0.08 0.32 0.09 0.02 0.11 0.00 96.28 34.93 06:48:11 PM 2 4.16 0.11 0.36 0.02 0.00 0.11 0.00 95.25 0.00 06:48:11 PM 3 3.77 0.11 0.38 0.03 0.01 0.24 0.00 95.46 44.80 06:48:11 PM 4 2.96 0.07 0.29 0.04 0.02 0.10 0.00 96.52 25.91 06:48:11 PM 5 3.26 0.08 0.28 0.03 0.01 0.10 0.00 96.23 14.98 06:48:11 PM 6 4.00 0.10 0.34 0.01 0.00 0.13 0.00 95.42 3.75 06:48:11 PM 7 3.30 0.11 0.39 0.03 0.01 0.46 0.00 95.69 76.89 ``` 相关链接:[多处理器的 Linux 上单独显示每个 CPU 的使用率](https://www.cyberciti.biz/faq/linux-mpstat-command-report-processors-related-statistics/). ### 10. pmap - 监控进程的内存使用情况 `pmap` 命令用以显示进程的内存映射,使用此命令可以查找内存瓶颈。 ``` # pmap -d PID ``` 显示 PID 为 47394 的进程的内存信息,请输入: ``` # pmap -d 47394 ``` 输出示例: ``` 47394: /usr/bin/php-cgi Address Kbytes Mode Offset Device Mapping 0000000000400000 2584 r-x-- 0000000000000000 008:00002 php-cgi 0000000000886000 140 rw--- 0000000000286000 008:00002 php-cgi 00000000008a9000 52 rw--- 00000000008a9000 000:00000 [ anon ] 0000000000aa8000 76 rw--- 00000000002a8000 008:00002 php-cgi 000000000f678000 1980 rw--- 000000000f678000 000:00000 [ anon ] 000000314a600000 112 r-x-- 0000000000000000 008:00002 ld-2.5.so 000000314a81b000 4 r---- 000000000001b000 008:00002 ld-2.5.so 000000314a81c000 4 rw--- 000000000001c000 008:00002 ld-2.5.so 000000314aa00000 1328 r-x-- 0000000000000000 008:00002 libc-2.5.so 000000314ab4c000 2048 ----- 000000000014c000 008:00002 libc-2.5.so ..... ...... .. 00002af8d48fd000 4 rw--- 0000000000006000 008:00002 xsl.so 00002af8d490c000 40 r-x-- 0000000000000000 008:00002 libnss_files-2.5.so 00002af8d4916000 2044 ----- 000000000000a000 008:00002 libnss_files-2.5.so 00002af8d4b15000 4 r---- 0000000000009000 008:00002 libnss_files-2.5.so 00002af8d4b16000 4 rw--- 000000000000a000 008:00002 libnss_files-2.5.so 00002af8d4b17000 768000 rw-s- 0000000000000000 000:00009 zero (deleted) 00007fffc95fe000 84 rw--- 00007ffffffea000 000:00000 [ stack ] ffffffffff600000 8192 ----- 0000000000000000 000:00000 [ anon ] mapped: 933712K writeable/private: 4304K shared: 768000K ``` 最后一行非常重要: * `mapped: 933712K` 映射到文件的内存量 * `writeable/private: 4304K` 私有地址空间 * `shared: 768000K` 此进程与其他进程共享的地址空间 相关链接:[使用 pmap 命令查看 Linux 上单个程序或进程使用的内存](https://www.cyberciti.biz/tips/howto-find-memory-used-by-program.html) ### 11. netstat - Linux 网络统计监控工具 `netstat` 命令显示网络连接、路由表、接口统计、伪装连接和多播连接等信息。 ``` # netstat -tulpn # netstat -nat ``` ### 12. ss - 网络统计 `ss` 命令用于获取套接字统计信息。它可以显示类似于 `netstat` 的信息。不过 `netstat` 几乎要过时了,`ss` 命令更具优势。要显示所有 TCP 或 UDP 套接字: ``` # ss -t -a ``` 或 ``` # ss -u -a ``` 显示所有带有 SELinux <ruby> 安全上下文 <rt> Security Context </rt></ruby>的 TCP 套接字: ``` # ss -t -a -Z ``` 请参阅以下关于 `ss` 和 `netstat` 命令的资料: * [ss:显示 Linux TCP / UDP 网络套接字信息](https://www.cyberciti.biz/tips/linux-investigate-sockets-network-connections.html) * [使用 netstat 命令获取有关特定 IP 地址连接的详细信息](https://www.cyberciti.biz/tips/netstat-command-tutorial-examples.html) ### 13. iptraf - 获取实时网络统计信息 `iptraf` 命令是一个基于 ncurses 的交互式 IP 网络监控工具。它可以生成多种网络统计信息,包括 TCP 信息、UDP 计数、ICMP 和 OSPF 信息、以太网负载信息、节点统计信息、IP 校验错误等。它以简单的格式提供了以下信息: * 基于 TCP 连接的网络流量统计 * 基于网络接口的 IP 流量统计 * 基于协议的网络流量统计 * 基于 TCP/UDP 端口和数据包大小的网络流量统计 * 基于二层地址的网络流量统计 ![Fig.02: General interface statistics: IP traffic statistics by network interface ](/data/attachment/album/201802/23/003617vegee3q22m51fng5.png "Fig.02: General interface statistics: IP traffic statistics by network interface ") *图 02:常规接口统计:基于网络接口的 IP 流量统计* ![Fig.03 Network traffic statistics by TCP connection](/data/attachment/album/201802/23/003617afed2848vd2dfufw.png "Fig.03 Network traffic statistics by TCP connection") *图 03:基于 TCP 连接的网络流量统计* 相关链接:[在 Centos / RHEL / Fedora Linux 上安装 IPTraf 以获取网络统计信息](https://www.cyberciti.biz/faq/install-iptraf-centos-redhat-fedora-linux/) ### 14. tcpdump - 详细的网络流量分析 `tcpdump` 命令是简单的分析网络通信的命令。您需要充分了解 TCP/IP 协议才便于使用此工具。例如,要显示有关 DNS 的流量信息,请输入: ``` # tcpdump -i eth1 'udp port 53' ``` 查看所有去往和来自端口 80 的 IPv4 HTTP 数据包,仅打印真正包含数据的包,而不是像 SYN、FIN 和仅含 ACK 这类的数据包,请输入: ``` # tcpdump 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' ``` 显示所有目标地址为 202.54.1.5 的 FTP 会话,请输入: ``` # tcpdump -i eth1 'dst 202.54.1.5 and (port 21 or 20' ``` 打印所有目标地址为 192.168.1.5 的 HTTP 会话: ``` # tcpdump -ni eth0 'dst 192.168.1.5 and tcp and port http' ``` 使用 [wireshark](https://www.cyberciti.biz/faq/linux-unix-bsd-apache-tcpdump-http-packets-sniffing/) 查看文件的详细内容,请输入: ``` # tcpdump -n -i eth1 -s 0 -w output.txt src or dst port 80 ``` ### 15. iotop - I/O 监控 `iotop` 命令利用 Linux 内核监控 I/O 使用情况,它按进程或线程的顺序显示 I/O 使用情况。 ``` $ sudo iotop ``` 输出示例: ![iotop monitoring linux disk read write IO](/data/attachment/album/201802/23/003617v0k9dgp548dgwd0t.jpg) 相关链接:[Linux iotop:什么进程在增加硬盘负载](https://www.cyberciti.biz/hardware/linux-iotop-simple-top-like-io-monitor/) ### 16. htop - 交互式的进程查看器 `htop` 是一款免费并开源的基于 ncurses 的 Linux 进程查看器。它比 `top` 命令更简单易用。您无需使用 PID、无需离开 `htop` 界面,便可以杀掉进程或调整其调度优先级。 ``` $ htop ``` 输出示例: ![htop process viewer for Linux](/data/attachment/album/201802/23/003618lfboctxr5s1zoash.jpg) 相关链接:[CentOS / RHEL:安装 htop——交互式文本模式进程查看器](https://www.cyberciti.biz/faq/centos-redhat-linux-install-htop-command-using-yum/) ### 17. atop - 高级版系统与进程监控工具 `atop` 是一个非常强大的交互式 Linux 系统负载监控器,它从性能的角度显示最关键的硬件资源信息。您可以快速查看 CPU、内存、磁盘和网络性能。它还可以从进程的级别显示哪些进程造成了相关 CPU 和内存的负载。 ``` $ atop ``` ![atop Command Line Tools to Monitor Linux Performance](/data/attachment/album/201802/23/003618uffd9f955nz8mc9n.jpg) 相关链接:[CentOS / RHEL:安装 atop 工具——高级系统和进程监控器](https://www.cyberciti.biz/faq/centos-redhat-linux-install-atop-command-using-yum/) ### 18. ac 和 lastcomm 您一定需要监控 Linux 服务器上的进程和登录活动吧。`psacct` 或 `acct` 软件包中包含了多个用于监控进程活动的工具,包括: 1. `ac` 命令:显示有关用户连接时间的统计信息 2. [lastcomm 命令](https://www.cyberciti.biz/faq/linux-unix-lastcomm-command-examples-usage-syntax/ "See Linux/Unix lastcomm command examples for more info"):显示已执行过的命令 3. `accton` 命令:打开或关闭进程账号记录功能 4. `sa` 命令:进程账号记录信息的摘要 相关链接:[如何对 Linux 系统的活动做详细的跟踪记录](https://www.cyberciti.biz/tips/howto-log-user-activity-using-process-accounting.html) ### 19. monit - 进程监控器 `monit` 是一个免费且开源的进程监控软件,它可以自动重启停掉的服务。您也可以使用 Systemd、daemontools 或其他类似工具来达到同样的目的。[本教程演示如何在 Debian 或 Ubuntu Linux 上安装和配置 monit 作为进程监控器](https://www.cyberciti.biz/faq/how-to-install-and-use-monit-on-ubuntudebian-linux-server/)。 ### 20. NetHogs - 找出占用带宽的进程 NetHogs 是一个轻便的网络监控工具,它按照进程名称(如 Firefox、wget 等)对带宽进行分组。如果网络流量突然爆发,启动 NetHogs,您将看到哪个进程(PID)导致了带宽激增。 ``` $ sudo nethogs ``` ![nethogs linux monitoring tools open source](/data/attachment/album/201802/23/003618dnv8ux8nukoo5nvv.jpg) 相关链接:[Linux:使用 Nethogs 工具查看每个进程的带宽使用情况](https://www.cyberciti.biz/faq/linux-find-out-what-process-is-using-bandwidth/) ### 21. iftop - 显示主机上网络接口的带宽使用情况 `iftop` 命令监听指定接口(如 eth0)上的网络通信情况。[它显示了一对主机的带宽使用情况](https://www.cyberciti.biz/tips/linux-display-bandwidth-usage-on-network-interface-by-host.html)。 ``` $ sudo iftop ``` ![iftop in action](/data/attachment/album/201802/23/003618eekdbv23qho62fdk.gif) ### 22. vnstat - 基于控制台的网络流量监控工具 `vnstat` 是一个简单易用的基于控制台的网络流量监视器,它为指定网络接口保留每小时、每天和每月网络流量日志。 ``` $ vnstat ``` ![vnstat linux network traffic monitor](/data/attachment/album/201802/23/003619j0qz1eb3gqv43pq3.jpg) 相关链接: * [为 ADSL 或专用远程 Linux 服务器保留日常网络流量日志](https://www.cyberciti.biz/tips/linux-display-bandwidth-usage-on-network-interface-by-host.html) * [CentOS / RHEL:安装 vnStat 网络流量监控器以保留日常网络流量日志](https://www.cyberciti.biz/faq/centos-redhat-fedora-linux-install-vnstat-bandwidth-monitor/) * [CentOS / RHEL:使用 PHP 网页前端接口查看 Vnstat 图表](https://www.cyberciti.biz/faq/centos-redhat-fedora-linux-vnstat-php-webinterface-frontend-config/) ### 23. nmon - Linux 系统管理员的调优和基准测量工具 `nmon` 是 Linux 系统管理员用于性能调优的利器,它在命令行显示 CPU、内存、网络、磁盘、文件系统、NFS、消耗资源最多的进程和分区信息。 ``` $ nmon ``` ![nmon command](/data/attachment/album/201802/23/003619wvfjn0m0fjsmgxwl.jpg) 相关链接:[安装并使用 nmon 工具来监控 Linux 系统的性能](https://www.cyberciti.biz/faq/nmon-performance-analyzer-linux-server-tool/) ### 24. glances - 密切关注 Linux 系统 `glances` 是一款开源的跨平台监控工具。它在小小的屏幕上提供了大量的信息,还可以工作于客户端-服务器模式下。 ``` $ glances ``` ![Glances](/data/attachment/album/201802/23/003619rlt3p5pp3ge5jg45.jpg) 相关链接:[Linux:通过 Glances 监控器密切关注您的系统](https://www.cyberciti.biz/faq/linux-install-glances-monitoring-tool/) ### 25. strace - 查看系统调用 想要跟踪 Linux 系统的调用和信号吗?试试 `strace` 命令吧。它对于调试网页服务器和其他服务器问题很有用。了解如何利用其 [追踪进程](https://www.cyberciti.biz/tips/linux-strace-command-examples.html) 并查看它在做什么。 ### 26. /proc 文件系统 - 各种内核信息 `/proc` 文件系统提供了不同硬件设备和 Linux 内核的详细信息。更多详细信息,请参阅 [Linux 内核 /proc](https://www.cyberciti.biz/files/linux-kernel/Documentation/filesystems/proc.txt) 文档。常见的 `/proc` 例子: ``` # cat /proc/cpuinfo # cat /proc/meminfo # cat /proc/zoneinfo # cat /proc/mounts ``` ### 27. Nagios - Linux 服务器和网络监控 [Nagios](http://www.nagios.org/) 是一款普遍使用的开源系统和网络监控软件。您可以轻松地监控所有主机、网络设备和服务,当状态异常和恢复正常时它都会发出警报通知。[FAN](http://fannagioscd.sourceforge.net/drupal/) 是“全自动 Nagios”的缩写。FAN 的目标是提供包含由 Nagios 社区提供的大多数工具包的 Nagios 安装。FAN 提供了标准 ISO 格式的 CD-Rom 镜像,使安装变得更加容易。除此之外,为了改善 Nagios 的用户体验,发行版还包含了大量的工具。 ### 28. Cacti - 基于 Web 的 Linux 监控工具 Cacti 是一个完整的网络图形化解决方案,旨在充分利用 RRDTool 的数据存储和图形功能。Cacti 提供了快速轮询器、高级图形模板、多种数据采集方法和用户管理功能。这些功能被包装在一个直观易用的界面中,确保可以实现从局域网到拥有数百台设备的复杂网络上的安装。它可以提供有关网络、CPU、内存、登录用户、Apache、DNS 服务器等的数据。了解如何在 CentOS / RHEL 下 [安装和配置 Cacti 网络图形化工具](https://www.cyberciti.biz/faq/fedora-rhel-install-cacti-monitoring-rrd-software/)。 ### 29. KDE 系统监控器 - 实时系统报告和图形化显示 KSysguard 是 KDE 桌面的网络化系统监控程序。这个工具可以通过 ssh 会话运行。它提供了许多功能,比如可以监控本地和远程主机的客户端-服务器模式。前端图形界面使用传感器来检索信息。传感器可以返回简单的值或更复杂的信息,如表格。每种类型的信息都有一个或多个显示界面,并被组织成工作表的形式,这些工作表可以分别保存和加载。所以,KSysguard 不仅是一个简单的任务管理器,还是一个控制大型服务器平台的强大工具。 ![Fig.05 KDE System Guard](/data/attachment/album/201802/23/003619r9blsmq55lgw1uss.png "Fig.05 KDE System Guard KDE task manager and performance monitor.") *图 05:KDE System Guard {图片来源:维基百科}* 详细用法,请参阅 [KSysguard 手册](https://docs.kde.org/stable5/en/kde-workspace/ksysguard/index.html)。 ### 30. GNOME 系统监控器 系统监控程序能够显示系统基本信息,并监控系统进程、系统资源使用情况和文件系统。您还可以用其修改系统行为。虽然不如 KDE System Guard 强大,但它提供的基本信息对新用户还是有用的: * 显示关于计算机硬件和软件的各种基本信息 * Linux 内核版本 * GNOME 版本 * 硬件 * 安装的内存 * 处理器和速度 * 系统状况 * 可用磁盘空间 * 进程 * 内存和交换空间 * 网络使用情况 * 文件系统 * 列出所有挂载的文件系统及其基本信息 ![Fig.06 The Gnome System Monitor application](/data/attachment/album/201802/23/003620wb8m90lmmp8e4wex.png "Fig.06 The Gnome System Monitor application") *图 06:Gnome 系统监控程序* ### 福利:其他工具 更多工具: * [nmap](https://www.cyberciti.biz/tips/linux-scanning-network-for-open-ports.html) - 扫描服务器的开放端口 * [lsof](https://www.cyberciti.biz/tips/tag/lsof-command) - 列出打开的文件和网络连接等 * [ntop](https://www.cyberciti.biz/faq/debian-ubuntu-install-ntop-network-traffic-monitoring-software/ "Debian / Ubuntu Linux Install ntop To See Network Usage / Network Status") 基于网页的工具 - `ntop` 是查看网络使用情况的最佳工具,与 `top` 命令之于进程的方式类似,即网络流量监控工具。您可以查看网络状态和 UDP、TCP、DNS、HTTP 等协议的流量分发。 * [Conky](https://github.com/brndnmtthws/conky) - X Window 系统下的另一个很好的监控工具。它具有很高的可配置性,能够监视许多系统变量,包括 CPU 状态、内存、交换空间、磁盘存储、温度、进程、网络接口、电池、系统消息和电子邮件等。 * [GKrellM](http://gkrellm.srcbox.net/) - 它可以用来监控 CPU 状态、主内存、硬盘、网络接口、本地和远程邮箱及其他信息。 * [mtr](https://www.cyberciti.biz/tips/finding-out-a-bad-or-simply-overloaded-network-link-with-linuxunix-oses.html) - `mtr` 将 `traceroute` 和 `ping` 程序的功能结合在一个网络诊断工具中。 * [vtop](https://www.cyberciti.biz/faq/how-to-install-and-use-vtop-graphical-terminal-activity-monitor-on-linux/) - 图形化活动监控终端 如果您有其他推荐的系统监控工具,欢迎在评论区分享。 ### 关于作者 作者 Vivek Gite 是 nixCraft 的创建者,也是经验丰富的系统管理员,以及 Linux 操作系统和 Unix shell 脚本的培训师。他的客户遍布全球,行业涉及 IT、教育、国防航天研究以及非营利部门等。您可以在 [Twitter](https://twitter.com/nixcraft)、[Facebook](https://facebook.com/nixcraft) 和 [Google+](https://plus.google.com/+CybercitiBiz) 上关注他。 --- via: <https://www.cyberciti.biz/tips/top-linux-monitoring-tools.html> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[jessie-pang](https://github.com/jessie-pang) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,375
Kali Linux 是什么,你需要它吗?
https://www.maketecheasier.com/what-is-kali-linux-and-do-you-need-it/
2018-02-23T18:48:18
[ "Kali", "黑客" ]
https://linux.cn/article-9375-1.html
![](/data/attachment/album/201802/23/184821kb93jm96a6d3a31m.jpg) 如果你听到一个 13 岁的黑客吹嘘他是多么的牛逼,是有可能的,因为有 Kali Linux 的存在。尽管有可能会被称为“脚本小子”,但是事实上,Kali 仍旧是安全专家手头的重要工具(或工具集)。 Kali 是一个基于 Debian 的 Linux 发行版。它的目标就是为了简单:在一个实用的工具包里尽可能多的包含渗透和审计工具。Kali 实现了这个目标。大多数做安全测试的开源工具都被囊括在内。 **相关** : [4 个极好的为隐私和安全设计的 Linux 发行版](https://www.maketecheasier.com/linux-distros-designed-for-privacy-security/ "4 Great Linux Distros Designed for Privacy and Security") ### 为什么是 Kali? ![Kali Linux Desktop](/data/attachment/album/201802/23/184825od5kpbwkbgwwu5ca.jpg "Kali Linux Desktop") [Kali](https://www.offensive-security.com/kali-linux-vmware-virtualbox-image-download/) 是由 [Offensive Security](https://www.offensive-security.com/) 公司开发和维护的。它在安全领域是一家知名的、值得信赖的公司,它甚至还有一些受人尊敬的认证,来对安全从业人员做资格认证。 Kali 也是一个简便的安全解决方案。Kali 并不要求你自己去维护一个 Linux 系统,或者你自己去收集软件和依赖项。它是一个“交钥匙工程”。所有这些繁杂的工作都不需要你去考虑,因此,你只需要专注于要审计的真实工作上,而不需要去考虑准备测试系统。 ### 如何使用它? Kali 是一个 Linux 发行版。与任何一个其它的 Linux 发行版一样,你可以将它永久安装到一个硬盘上。那样它会工作的更好,但是你不能将它作为一个日常使用的操作系统。因为它是为渗透测试构建的,这就是你使用它的全部理由。 最好是将 Kali 制作为自启动发行版。你可以将 Kali 刻录到一张 DVD 或者是制作到一个自启动 U 盘上来运行它。你没有必要在一个 Kali 上安装任何软件或者保存任何文件。你可以在需要测试一个系统时随时来启动它。它也有非常好的灵活性,可以让运行 Kali 的机器随时运行在想要测试的网络上。 ### Kali 可以做什么? Kali 里面有很多的安全工具而不是别的。这就是它能做的事。不管怎么说,Kali 就是一个安全工具。 ![Kali Zenmap](/data/attachment/album/201802/23/184835rphy1t6pro066gow.jpg "Kali Zenmap") 它有像 NMap 和 Wireskark 这样的经典信息采集工具。 ![Kali Linux Wireshark](/data/attachment/album/201802/23/184843eixdd6dviol34tn3.jpg "Kali Linux Wireshark") Kali 也有面向 WiFi 的工具,像 Aircrack-ng、Kismet、以及 Pixie。 对于破解密码,它也有像 Hydra、Crunch、Hashcat、以及 John the Ripper 这样的工具。 ![Kali Metasploit](/data/attachment/album/201802/23/184858ir255on00mlmnozn.jpg "Kali Metasploit") 还有更多的成套工具,包括 Metasploit 和 Burp Suite。 这些只是 Kali 缺省内置的一小部分安全工具。完整的了解这些工具需要很多的时间,但是,你可以清楚地看到许多非常流行的工具它都有。 ### Kali 是为你准备的吗? Kali 并不是为普通用户准备的。它并不是一个运行在你的笔记本电脑上的普通 Linux 发行版,而是一个很酷的“黑客操作系统“。如果你使用这个操作系统,那么你将会运行着一个缺乏安全保障的系统,因为 Kali 被设计为以 root 权限运行。它自身并不安全,并且它的配置也与普通的 Linux 发行版不一样。它是一个攻击型工具,而不是一个防御型工具。 Kali 并不是个玩具。你可以使用它内置的工具去做一些会产生真实伤害的危险的事(你懂的),那将给你带来很多真实的麻烦。对于一个未受到严格教育的用户来说,做一些严重违法的事情是很容易的,并且之后你就会发现自己被陷入很无助的境地。 说了这么多,但是,Kali 对于一个专业用户来说,它是一个极好的工具。如果你是一个网络管理员,想对你的网络做一个真实的测试,Kali 可以做到你所希望的一切事情。Kali 也有一些优秀的开发工具,用于去实时审计它们的应用程序。 当然,如果你正好有兴趣学习关于安全的知识,你可以在某些受控环境中去使用 Kali,它可以教你学习很多的非常优秀的知识。 Kali Linux 是许多优秀的安全工具的集合。对于专业用户来说,它有难以置信的好处,但是对于一些不怀好意的人来说,也可以产生很多大麻烦。小心地使用 Kali,充分利用它的巨大优势。如果不这样的话,你将在某个地方(你懂的)度过你的余生。 --- via: <https://www.maketecheasier.com/what-is-kali-linux-and-do-you-need-it/> 作者:[Nick Congleton](https://www.maketecheasier.com/author/nickcongleton/) 译者:[qhwdw](https://github.com/qhwdw) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Install Kali Linux 00 Featured Image](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-00-featured-image.jpg) If you have heard a young would-be hacker talking about penetration testing, chances are, you would inevitably hear what Kali Linux is. It is a Debian-based Linux distribution that aims to be a complete toolkit for security professionals. Kali Linux includes a lot of penetration testing and security auditing tools by default. In that regard, Kali delivers, too. Many of the best open-source tools for conducting security tests are in here and ready to use. ## Why Use Kali Linux? One of the biggest selling points of [Kali Linux](https://www.kali.org/) is that it is a convenient all-in-one solution. For the most part, Kali doesn’t require you to maintain a Linux machine and collect your own software. All of the set-up work is out of the way, and you can fully focus on testing the system you’ve set out to audit. ![Kali Linux Desktop Install Kali Linux 01 Default Desktop](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-01-default-desktop.jpg) Aside from that, Kali is also being developed and maintained by Offensive Security. They’re a well-known and trusted institution in cybersecurity. You can be confident that the tools that Kali Linux provides are both trustworthy and highly effective. ## What Tools Are Available in Kali Linux? Kali Linux has many security tools. It has classic information-gathering tools, like NMap, Wireshark and [dig](https://www.maketecheasier.com/use-dig-command-linux/). ![Kali Zenmap Install Kali Linux 02 Zenmap Sample](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-02-zenmap-sample.jpg) ![Kali Linux Wireshark Install Kali Linux 03 Wireshark Sample](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-03-wireshark-sample.png) Kali also has WiFi-centered tools like Aircrack-ng, Kismet, and Pixie. For attacking passwords, there are tools like Hydra, Crunch, Hashcat, and John the Ripper. ![Kali Metasploit Install Kali Linux 04 Metasploit Sample](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-04-metasploit-sample.png) Then there are more complete suites of tools. For example, you can [use the Metasploit Framework](https://www.maketecheasier.com/install-metasploit-framework-ubuntu-linux/) and Burp Suite out of the box. That’s only a small percentage of the [security tools available in Kali](https://www.maketecheasier.com/penetration-tools-kali-linux/). It would take a long time to go through all of them, but you can clearly see that many of the more popular tools are represented. ## Installing Kali Linux Kali is a Linux distribution. Like any other, you can install it permanently on a hard drive or virtual machine. That works fine, but you don’t want to use Kali as a daily driver operating system. It’s purposely built for penetration testing, and that’s about all that you should use it for. **Note**: you can also [install Kali Linux on your Android phone](https://www.maketecheasier.com/install-kali-linux-nethunter-android-phone/). ### Kali’s System Requirements Before you can install Kali Linux, have the following resources available: [Ample amount of disk space](https://www.maketecheasier.com/using-du-free-up-disk-space-linux/)in your machine. In most cases, Kali should work well on a 32 GB flash disk.- 64-bit processor and 2 to 4 GB of onboard memory, as Kali Linux uses a number of resource-intensive programs in its toolkit. - Your machine needs to have the ability to either do virtualization or external media booting. It is important to note that Kali works best as a live distribution. You can either burn it to a USB driver or run it off of a virtual machine. You don’t need to install anything on Kali or save any files, so spinning it up on the occasion where you need to test a system is great. It also affords the flexibility to get a Kali machine running anywhere on whichever network you’re looking to test. This article focuses on installing Kali Linux on VirtualBox as a live system in Ubuntu 22.04 LTS. ![Install Kali Linux 05 Ubuntu Neofetch](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-05-ubuntu-neofetch.png) ### Installing Kali Linux on VirtualBox To install Kali Linux, obtain the [virtualization client you want to use](https://www.maketecheasier.com/virtualbox-vs-vmware/). In this case, I am installing VirtualBox: sudo apt install virtualbox p7zip ![Install Kali Linux 06 Install Virtualbox](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-06-install-virtualbox.png) Obtain a copy of Kali Linux from its official website. For example, you can run the following command to download it from the terminal: wget https://kali.download/virtual-images/kali-2022.3/kali-linux-2022.3-virtualbox-amd64.7z p7zip -d ./kali-linux-2022.3-virtualbox-amd64.7z ![Install Kali Linux 07 Extract Kali Files](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-07-extract-kali-files.png) Install Kali Linux as a virtual machine by pressing `Win`, then typing “virtualbox.” ![Install Kali Linux 08 Virtualbox Run](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-08-virtualbox-run.png) Once VirtualBox is up and running, import the Kali Linux virtual machine to the client by either clicking “Add” or pressing `Ctrl` + `A`. ![Install Kali Linux 09 Virtualbox Add Vm](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-09-virtualbox-add-vm.png) VirtualBox will open a small file browser where you can look for the virtual machine definition for Kali. In my case, I am saving this file to my Downloads folder. ![Install Kali Linux 10 File Browser Select](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-10-file-browser-select.png) ## Using Kali Linux Run Kali as a virtual environment in your machine. Double-click on the Kali Linux entry on VirtualBox’s left sidebar. ![Install Kali Linux 11 Run Kali Vm](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-11-run-kali-vm.jpg) A small window will open and immediately boot the virtual machine in your system. ![Install Kali Linux 12 Bootloader Menu](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-12-bootloader-menu.jpg) Kali will load to a simple login screen. By default, the username and password for the system should be “kali.” ![Install Kali Linux 13 Logging In](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-13-logging-in.jpg) **Tips**: learn how you can [access an Android phone using Kali Linux](https://www.maketecheasier.com/access-android-phone-using-kali-linux/). ### Finding and Running Tools in Kali Once you are logged in, use the tools available in Kali to conduct security auditing. For example, press the Kali logo on the desktop’s upper-left corner to get an organized list of programs in the system. ![Install Kali Linux 14 Main Menu](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-14-main-menu.jpg) One of the most basic tools you will use in Kali is nmap ([more details on using nmap here](https://www.maketecheasier.com/use-nmap-check-linux-open-ports/)). This is a small utility that allows you to do a comprehensive scan of machines in a network. To use this, click the “Terminal Emulator” entry in the Kali menu. ![Install Kali Linux 15 Run Terminal Emulator](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-15-run-terminal-emulator.png) Run `nmap -h` to print a brief overview of the available options and flags for the program. Knowing that, run the following command to scan the entire subnet for any online clients: nmap -sP 192.168.68.0/24 ![Install Kali Linux 16 Run Nmap Sample](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-16-run-nmap-sample.jpg) Lastly, Kali Linux also provides powerful data processing tools, such as Hashcat, that you can use to crack hashes. For example, you can run `hashcat -h` to look at some of the program’s options. ![Install Kali Linux 17 Run Hashcat Sample](https://www.maketecheasier.com/assets/uploads/2022/11/install-kali-linux-17-run-hashcat-sample.jpg) Aside from that, you can also run the following command to test whether your machine can run Hashcat on a reasonable speed: `hashcat -b` ## Is Kali Linux For You? Kali is not for everyone. It’s not a regular Linux distribution to run on your laptop to think you’re cool for running a “hacker OS.” If you do so, you’re running a potentially insecure system. Kali is designed to run as root. It’s not secured and configured like a regular Linux distribution. It’s an offensive tool, not a defensive one. Kali isn’t a joke, either. You can do some real damage with the tools that it comes bundled with and can get you into real trouble. It’s all too easy for an uneducated user to do something seriously illegal and find themselves in a situation no one wants to be in. With all that having been said, Kali is a great tool for professional use. If you’re a network admin and want to conduct real-world tests on your network, Kali might be just what you need. Kali also has some excellent tools for developers (especially web devs) to audit their applications before they go live. Of course, if you want to learn more about security the right way, you can certainly use Kali in a virtual environment to teach yourself or follow any number of great courses. Kali Linux is a bundle of many of the best security tools. It’s an incredible asset for professionals, but it can also be a big problem in the hands of the uninitiated. Use Kali with care and take advantage of its awesome potential. If you don’t, you’re going to end up having a really bad time. ## Frequently Asked Questions ### Is it safe to browse the internet using Kali Linux? While you can use the Internet in Kali, the developers of the distribution did not design the system for casual Web browsing, so there are many missing multimedia tools and codecs in the default install, and some websites may not function properly when viewed in Kali Linux. ### Is it possible to install third-party programs in Kali? Similar to a regular Debian installation, you can install any third-party application through the `apt` program. Aside from that, you can also use both snap and flatpak packages in Kali. ### Are there any disadvantages to installing Kali Linux on a virtual machine? One of the biggest issues with running Kali on a virtual machine is that it will not have any direct hardware access. Any program that depends on hardware acceleration will either run poorly or not work at all. For example, both Hashcat and John the Ripper are tools that heavily rely on direct hardware access. Image credit: [Unsplash](https://unsplash.com/photos/vJP-wZ6hGBg). All alterations and screenshots by Ramces Red. Our latest tutorials delivered straight to your inbox
9,376
如何在终端输入密码时显示星号
https://www.ostechnix.com/display-asterisks-type-password-terminal/
2018-02-23T19:13:34
[ "密码", "星号" ]
https://linux.cn/article-9376-1.html
![](/data/attachment/album/201802/23/191336nsn3g23xsm20gi3g.png) 当你在 Web 浏览器或任何 GUI 登录中输入密码时,密码会被标记成星号 `********` 或圆点符号 `•••••••••••••` 。这是内置的安全机制,以防止你附近的用户看到你的密码。但是当你在终端输入密码来执行任何 `sudo` 或 `su` 的管理任务时,你不会在输入密码的时候看见星号或者圆点符号。它不会有任何输入密码的视觉指示,也不会有任何光标移动,什么也没有。你不知道你是否输入了所有的字符。你只会看到一个空白的屏幕! 看看下面的截图。 ![](/data/attachment/album/201802/23/191339wwqfqdrgryzwwesw.png) 正如你在上面的图片中看到的,我已经输入了密码,但没有任何指示(星号或圆点符号)。现在,我不确定我是否输入了所有密码。这个安全机制也可以防止你附近的人猜测密码长度。当然,这种行为可以改变。这是本指南要说的。这并不困难。请继续阅读。 ### 当你在终端输入密码时显示星号 要在终端输入密码时显示星号,我们需要在 `/etc/sudoers` 中做一些小修改。在做任何更改之前,最好备份这个文件。为此,只需运行: ``` sudo cp /etc/sudoers{,.bak} ``` 上述命令将 `/etc/sudoers` 备份成名为 `/etc/sudoers.bak`。你可以恢复它,以防万一在编辑文件后出错。 接下来,使用下面的命令编辑 `/etc/sudoers`: ``` sudo visudo ``` 找到下面这行: ``` Defaults env_reset ``` ![](/data/attachment/album/201802/23/191341ye0nt9f0ovitb5nc.png) 在该行的末尾添加一个额外的单词 `,pwfeedback`,如下所示。 ``` Defaults env_reset,pwfeedback ``` ![](/data/attachment/album/201802/23/191344hx02kemz5ztkdxvb.png) 然后,按下 `CTRL + x` 和 `y` 保存并关闭文件。重新启动终端以使更改生效。 现在,当你在终端输入密码时,你会看到星号。 ![](/data/attachment/album/201802/23/191346z2xjshjkwxx5bobb.png) 如果你对在终端输入密码时看不到密码感到不舒服,那么这个小技巧会有帮助。请注意,当你输入输入密码时其他用户就可以预测你的密码长度。如果你不介意,请按照上述方法进行更改,以使你的密码可见(当然,显示为星号!)。 现在就是这样了。还有更好的东西。敬请关注! 干杯! --- via: <https://www.ostechnix.com/display-asterisks-type-password-terminal/> 作者:[SK](https://www.ostechnix.com/author/sk/) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,377
如何在 Ubuntu 16.04 上安装和使用 Encryptpad
https://www.howtoforge.com/tutorial/how-to-install-and-use-encryptpad-on-ubuntu-1604/
2018-02-24T11:15:21
[ "EncryptPad", "加密", "PGP" ]
https://linux.cn/article-9377-1.html
![](/data/attachment/album/201802/24/111516b0a0arbn8b4bbir7.jpg) EncryptPad 是一个自由开源软件,它通过简单方便的图形界面和命令行接口来查看和修改加密的文本,它使用 OpenPGP RFC 4880 文件格式。通过 EncryptPad,你可以很容易的加密或者解密文件。你能够像保存密码、信用卡信息等私人信息,并使用密码或者密钥文件来访问。 ### 特性 * 支持 windows、Linux 和 Max OS。 * 可定制的密码生成器,可生成健壮的密码。 * 随机的密钥文件和密码生成器。 * 支持 GPG 和 EPD 文件格式。 * 能够通过 CURL 自动从远程远程仓库下载密钥。 * 密钥文件的路径能够存储在加密的文件中。如果这样做的话,你不需要每次打开文件都指定密钥文件。 * 提供只读模式来防止文件被修改。 * 可加密二进制文件,例如图片、视频、归档等。 在这份教程中,我们将学习如何在 Ubuntu 16.04 中安装和使用 EncryptPad。 ### 环境要求 * 在系统上安装了 Ubuntu 16.04 桌面版本。 * 在系统上有 `sudo` 的权限的普通用户。 ### 安装 EncryptPad 在默认情况下,EncryPad 在 Ubuntu 16.04 的默认仓库是不存在的。你需要安装一个额外的仓库。你能够通过下面的命令来添加它 : ``` sudo apt-add-repository ppa:nilaimogard/webupd8 ``` 下一步,用下面的命令来更新仓库: ``` sudo apt-get update -y ``` 最后一步,通过下面命令安装 EncryptPad: ``` sudo apt-get install encryptpad encryptcli -y ``` 当 EncryptPad 安装完成后,你可以在 Ubuntu 的 Dash 上找到它。 ### 使用 EncryptPad 生成密钥和密码 现在,在 Ubunntu Dash 上输入 `encryptpad`,你能够在你的屏幕上看到下面的图片 : [![Ubuntu DeskTop](/data/attachment/album/201802/24/111525uhuy09qw0e9n072k.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-dash.png) 下一步,点击 EncryptPad 的图标。你能够看到 EncryptPad 的界面,它是一个简单的文本编辑器,带有顶部菜单栏。 [![EncryptPad screen](/data/attachment/album/201802/24/111528njkvrqh3w35tt8qw.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-dashboard.png) 首先,你需要生成一个密钥文件和密码用于加密/解密任务。点击顶部菜单栏中的 “Encryption->Generate Key”,你会看见下面的界面: [![Generate key](/data/attachment/album/201802/24/111531jq1iqerx3avxkj6e.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-generate-key.png) 选择文件保存的路径,点击 “OK” 按钮,你将看到下面的界面: [![select path](/data/attachment/album/201802/24/111533fqccm7m88981v9z9.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-generate-passphrase.png) 输入密钥文件的密码,点击 “OK” 按钮 ,你将看到下面的界面: [![last step](/data/attachment/album/201802/24/111536pjvnqhi2xivqvlek.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-use-key-file.png) 点击 “yes” 按钮来完成该过程。 ### 加密和解密文件 现在,密钥文件和密码都已经生成了。可以执行加密和解密操作了。在这个文件编辑器中打开一个文件文件,点击 “encryption” 图标 ,你会看见下面的界面: [![Encry operation](/data/attachment/album/201802/24/111539g03x0cff96f36w6v.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-start-encryption.png) 提供需要加密的文件和指定输出的文件,提供密码和前面产生的密钥文件。点击 “Start” 按钮来开始加密的进程。当文件被成功的加密,会出现下面的界面: [![Success Encrypt](/data/attachment/album/201802/24/111542i2332g2z3wzgww6b.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-file-encrypted-successfully.png) 文件已经被该密码和密钥文件加密了。 如果你想解密被加密后的文件,打开 EncryptPad ,点击 “File Encryption” ,选择 “Decryption” 操作,提供加密文件的位置和你要保存输出的解密文件的位置,然后提供密钥文件地址,点击 “Start” 按钮,它将要求你输入密码,输入你先前加密使用的密码,点击 “OK” 按钮开始解密过程。当该过程成功完成,你会看到 “File has been decrypted successfully” 的消息 。 [![decrypt ](/data/attachment/album/201802/24/111545ff6v73pin3qmfzni.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/Screenshot-of-encryptpad-decryption-passphrase.png) [![](/data/attachment/album/201802/24/111549u56ky6655dkn6dqo.png)](https://www.howtoforge.com/images/how_to_install_and_use_encryptpad_on_ubuntu_1604/big/Screenshot-of-encryptpad-decryption-passphrase.png) [![](/data/attachment/album/201802/24/111542i2332g2z3wzgww6b.png)] **注意:** 如果你遗忘了你的密码或者丢失了密钥文件,就没有其他的方法可以打开你的加密信息了。对于 EncrypePad 所支持的格式是没有后门的。 --- via: <https://www.howtoforge.com/tutorial/how-to-install-and-use-encryptpad-on-ubuntu-1604/> 作者:[Hitesh Jethva](https://www.howtoforge.com) 译者:[singledo](https://github.com/singledo) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# How to Install and Use Encryptpad on Ubuntu 16.04 EncryptPad is a free and open source software application that can be used for viewing and editing encrypted text using a simple and convenient graphical and command line interface. It uses OpenPGP RFC 4880 file format. You can easily encrypt and decrypt file using EncryptPad. Using EncryptPad, you can save your private information like, password, credit card information and access the file using a password or key files. ### Features - Supports Windows, Linux and Mac OS - Customisable passphrase generator helps create strong random passphrases. - Random key file and password generator. - Supports GPG and EPD file formats. - You can download key automatically from remote storage using CURL. - Path to a key file can be stored in an encrypted file. If enabled, you do not need to specify the key file every time you open files. - Provide read only mode to prevent file modification. - Encrypt binary files such as, images, videos, archives. In this tutorial, we will learn how to install and use the software EncryptPad on Ubuntu 16.04. ## Requirements - Ubuntu 16.04 desktop version installed on your system. - A normal user with sudo privileges setup on your system. ## Install EncryptPad By default, EncryptPad is not available in Ubuntu 16.04 default repository. So you will need to install an additional repository for EncryptPad first. You can add it with the following command: sudo apt-add-repository ppa:nilarimogard/webupd8 Next, update the repository using the following command: sudo apt-get update -y Finally, install EncryptPad by running the following command: sudo apt-get install encryptpad encryptcli -y Once the installation is completed, you should locate it under Ubuntu dashboard. ## Access EncryptPad and Generate Key and Passphrase Now, go to the **Ubuntu Dash** and type **encryptpad**, you should see the following screen: Next, click on the **EncryptPad** icon, you should see the first screen of the EncryptPad in following screen. It is a simple text editor and has a menu bar on the top. First, you will need to generate a key and passphrase for future encryption/decryption tasks. To do so, click on **Encryption > Generate Key** option from the top menu, you should see the following screen: Here, select the path where you want to save the file and click on the **Ok** button, you should see the following screen: Now, enter passphrase for the key file and click on the **Ok** button, you should see the following screen: Now, click on the yes button to finish the process. ## Encrypt and Decrypt File Now, the key file and passphrase are generated, it's time to perform encryption and decryption operation. To do so, open any text file in this editor and click on the **encryption** icon, you should see the following screen: Here, provide input file which you want to encrypt and specify the output file, provide passphrase and the path of the key file which we have generated earlier, then click on the Start button to start the process. Once the file has been encrypted successfully, you should see the following screen: Your file is now encrypted with key and passphrase. If you want to decrypt this file, open **EncryptPad**, click on **File Encryption**, choose **Decryptio** option, provide the path of your encrypted file and path of the output file where you want to save the decrypted file, then provide path of the key file and click on the Start button, it will ask you for passphrase, enter your passphrase and click on Ok button to start the Decryption process. Once the process is completed successfully, you should see the "File has been decrypted successfully message". **Note:** If you forgot your passphrase or lost a key file, there is no way that can be done to open your encrypted information. There are no backdoors in the formats that EncryptPad supports.
9,378
Torrent 提速为什么总是无济于事
http://www.theitstuff.com/increase-torrent-speed-will-never-work
2018-02-24T11:36:08
[ "BT", "网络" ]
https://linux.cn/article-9378-1.html
![](/data/attachment/album/201802/24/113610t63c21c660hpz0df.jpg) 是不是总是想要 **更快的 torrent 速度**?不管现在的速度有多块,但总是无法对此满足。我们对 torrent 速度的痴迷使我们经常从包括 YouTube 视频在内的许多网站上寻找并应用各种所谓的技巧。但是相信我,从小到大我就没发现哪个技巧有用过。因此本文我们就就来看看,为什么尝试提高 torrent 速度是行不通的。 ### 影响速度的因素 #### 本地因素 从下图中可以看到 3 台电脑分别对应的 A、B、C 三个用户。A 和 B 本地相连,而 C 的位置则比较远,它与本地之间有 1、2、3 三个连接点。 [![](/data/attachment/album/201802/24/113610mvc014kvkdc3qcqq.png)](http://www.theitstuff.com/wp-content/uploads/2017/11/A.png) 若用户 A 和用户 B 之间要分享文件,他们之间直接分享就能达到最大速度了而无需使用 torrent。这个速度跟互联网什么的都没有关系。 * 网线的性能 * 网卡的性能 * 路由器的性能 当谈到 torrent 的时候,人们都是在说一些很复杂的东西,但是却总是不得要点。 [![LAN wire,network cards,router](/data/attachment/album/201802/24/113610ldsv855995vm55fb.png)](http://www.theitstuff.com/wp-content/uploads/2017/11/A-1-e1509773618549.png) 现在我们谈论的是本地文件分享,目前较新一点的网卡速率大约 1 Gigabit 左右。常见的路由器大约 300 Megabits 而网线大概能达到 100 Megabits。当然具体的配置可能不一样,我这里只是给一个一般性的例子。 由于你有一个 1 Gigabit 的网卡,你可能会觉得你的下载速度应该达到 125 Megabytes。但是路由器只允许传输 300 Megabits 也就是 30 Megabyte。 即使你把目标降到 30 Megabytes,然而你连接到路由器的电缆/网线的性能最多只有 100 megabits 也就是 10 MegaBytes。这是一个纯粹的瓶颈问题,由一个薄弱的环节影响到了其他强健部分,也就是说这个传输速率只能达到 10 Megabytes,即电缆的极限速度。现在想象有一个 torrent 即使能够用最大速度进行下载,那也会由于你的硬件不够强大而导致瓶颈。 #### 外部因素 现在再来看一下这幅图。用户 C 在很遥远的某个地方。甚至可能在另一个国家。 [![how torrent works](/data/attachment/album/201802/24/113610mvc014kvkdc3qcqq.png)](http://www.theitstuff.com/wp-content/uploads/2017/11/A.png) 假设这个用户创建了一个 torrent 而你想去下载它。第一个问题就是我们刚才讨论过的,你不可能跨越 10 Megabyte 这道坎。 第二,由于 C 与本地之间多个有连接点,其中一个点就有可能成为瓶颈所在,可能由于繁重的流量和相对薄弱的硬件导致了缓慢的速度。 #### 做种者与吸血者 关于此已经有了太多的讨论,总的想法就是搜索更多的种子,但要注意上面的那些因素,有一个很好的种子提供者,但是跟我之间的连接不好的话那也是无济于事的。通常,这不可能发生,因为我们也不是唯一下载这个资源的人,一般都会有一些在本地的人已经下载好了这个文件并已经在做种了。 ### 结论 我们尝试搞清楚哪些因素影响了 torrent 速度的好坏。不管我们如何用软件进行优化,大多数时候是这是由于物理瓶颈导致的。我从来不关心那些软件,使用默认配置对我来说就够了。 希望你会喜欢这篇文章,有什么想法敬请留言。 --- via: <http://www.theitstuff.com/increase-torrent-speed-will-never-work> 作者:[Rishabh Kandari](http://www.theitstuff.com/author/reevkandari) 译者:[lujun9972](https://github.com/lujun9972) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
520
null
9,379
6 个 Linux 平台下最好的替代 MS Office 的开源办公软件
https://itsfoss.com/best-free-open-source-alternatives-microsoft-office/
2018-02-24T21:09:00
[ "Office" ]
https://linux.cn/article-9379-1.html
> > 概要:还在 Linux 中寻找 Microsoft Office 吗? 这里有一些最好的在 Linux 平台下替代 Microsoft Office 的开源软件。 > > > 办公套件是任何操作系统的必备品。很难想象没有 Office 软件的桌面操作系统。虽然 Windows 有 MS Office 套件,Mac OS X 也有它自己的 iWork,但其他很多办公套件都是专门针对这些操作系统的,Linux 也有自己的办公套件。 在本文中,我会列举一些在 Linux 平台替代 Microsoft Office 的办公软件。 ### Linux 最好的 MS Office 开源替代软件 ![Best Microsoft office alternatives for Linux](/data/attachment/album/201802/24/210910ry1c2pcv4vssm6sm.jpg) 在我们看 MS Office 的替代软件之前,我们先来看看在一个像样的办公套件中有一些什么: * 文字处理器 * 电子表格 * 演示功能 我知道 Microsoft Office 提供了比上述三种工具更多的工具,但事实上,您主要使用这三个工具。开源办公套件并不限于只有这三种产品。其中有一些套件提供了一些额外的工具,但我们的重点将放在上述工具上。 让我们看看在 Linux 上有什么办公套件: #### 6. Apache OpenOffice ![OpenOffice Logo](/data/attachment/album/201802/24/210911gtytfzfvf6yeefk3.jpg) [Apache OpenOffice](http://www.openoffice.org/) 或简单的称为 OpenOffice 有一段名称/所有者变更的历史。 它于 1999 年由 Sun Microsystems 公司开发,后来改名为 OpenOffice,将它作为一个与 MS Office 对抗的自由开源的替代软件。 当 Oracle 在 2010 年收购 Sun 公司后,一年之后便停止开发 OpenOffice。 最后是 Apache 支持它,现在被称为 Apache OpenOffice。 Apache OpenOffice 可用于多种平台,包括 Linux、Windows、Mac OS X、Unix、BSD。 除了 OpenDocument 格式外,它还支持 MS Office 文件。 办公套件包含以下应用程序:Writer、Calc、Impress、Base、Draw、Math。 安装 OpenOffice 是一件痛苦的事,因为它没有提供一个友好的安装程序。另外,有传言说 OpenOffice 开发可能已经停滞。 这是我不推荐的两个主要原因。 出于历史目的,我在这里列出它。 #### 5. Feng Office ![Feng Office logo](/data/attachment/album/201802/24/210911xlrnglltnuptkmxx.jpg) [Feng Office](http://www.fengoffice.com/web/index.php?lang=en) 以前被称为 OpenGoo。 这不是一个常规的办公套件。 它完全专注于在线办公,如 Google 文档一样。 换句话说,这是一个开源[协作平台](https://en.wikipedia.org/wiki/Collaborative_software)。 Feng Office 不支持桌面使用,因此如果您想在单个 Linux 桌面上使用它,这个可能无法实现。 另一方面,如果你有一个小企业、一个机构或其他组织,你可以尝试将其部署在本地服务器上。 #### 4. Siag Office ![SIAG Office logo](/data/attachment/album/201802/24/210912f1ltt9uk98kpm1x5.jpg) [Siag](http://siag.nu/) 是一个非常轻量级的办公套件,适用于类 Unix 系统,可以在 16MB 的系统上运行。 由于它非常轻便,因此缺少标准办公套件中的许多功能。 但小即是美,不是吗? 它具有办公套件的所有必要功能,可以在[轻量级 Linux 发行版](https://itsfoss.com/lightweight-linux-beginners/)上“正常工作”。它是 [Damn Small Linux](http://www.damnsmalllinux.org/) 默认安装软件。(LCTT 译注:根据官网,现已不是默认安装软件) #### 3. Calligra Suite ![Calligra free and Open Source office logo](/data/attachment/album/201802/24/210912f6jeerooe3ylj32r.jpg) [Calligra](http://www.calligra.org/),以前被称为 KOffice,是 KDE 中默认的 Office 套件。 它支持 Mac OS X、Windows、Linux、FreeBSD 系统。 它也曾经推出 Android 版本。 但不幸的是,后续没有继续支持 Android。 它拥有办公套件所需的必要应用程序以及一些额外的应用程序,如用于绘制流程图的 Flow 和用于项目管理的 Plane。 Calligra 最近的发展产生了相当大的影响,很有可能成为 [LibreOffice 的替代品](http://maketecheasier.com/is-calligra-a-great-alternative-to-libreoffice/2012/06/18)。 #### 2. ONLYOFFICE ![ONLYOFFICE is Linux alternative to Microsoft Office](/data/attachment/album/201802/24/210913lhoxoa4m6kmmoadd.png) [ONLYOFFICE](https://www.onlyoffice.com/) 是办公套件市场上的新玩家,它更专注于协作部分。 企业(甚至个人)可以将其部署到自己的服务器上,以获得类似 Google Docs 之类的协作办公套件。 别担心,您不是必须将其安装在服务器上。有一个免费的开源[桌面版本](https://itsfoss.com/review-onlyoffice-desktop-editors-linux/) ONLYOFFICE。 您甚至可以获取 .deb 和 .rpm 二进制文件,以便将其安装在 Linux 桌面系统上。 #### 1. LibreOffice ![LibreOffice logo](/data/attachment/album/201802/24/210913jmfml8zf2my2xfz8.jpg) 当 Oracle 决定停止 OpenOffice 的开发时,是[文档基金会](http://www.documentfoundation.org/)将其复制分发,这就是我们所熟知的 [Libre-Office](http://www.libreoffice.org/)。从那时起,许多 Linux 发行版都将 OpenOffice 替换为 LibreOffice 作为它们的默认办公应用程序。 它适用于 Linux,Windows 和 Mac OS X,这使得在跨平台环境中易于使用。 和 Apache OpenOffice 一样,这也包括了除了 OpenDocument 格式以外的对 MS Office 文件的支持。 它还包含与 Apache OpenOffice 相同的应用程序。 您还可以使用 LibreOffice 作为 [Collabora Online](https://www.collaboraoffice.com/collabora-online/) 的协作平台。 基本上,LibreOffice 是一个完整的软件包,无疑是 Linux、Windows 和 MacOS 的**最佳 Microsoft Office 替代品**。 ### 你认为呢? 我希望 Microsoft Office 的这些开源替代软件可以节省您的资金。 您会使用哪种开源生产力办公套件? --- via: <https://itsfoss.com/best-free-open-source-alternatives-microsoft-office/> 作者:[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 译者:[amwps290](https://github.com/amwps290) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
![Warp Terminal](/assets/images/warp-terminal.webp) ![Warp Terminal](/assets/images/warp-terminal.webp) Office Suites are a mandatory part of any operating system. It is difficult to imagine using a desktop OS without office software. While Windows offers Microsoft Office Suite and macOS got iWork. What about Linux? There are [ways to use Microsoft Office on Linux](https://itsfoss.com/use-microsoft-office-linux/), however, it is not a native Linux app. So, do we have open-source replacements for Microsoft Office? I'll answer that questions in this article. ## Best open source alternatives to Microsoft Office for Linux Before we see the MS Office alternatives, let’s first see what you look for in a decent office suite: - Word processor - Spreadsheet - Presentation I’m aware that the Microsoft Office suite includes more tools as part of its offering, like OneDrive (cloud storage), and Outlook (email client). However, you can choose to use a different mail client and cloud storage service. So, we shall focus only on the basic offerings, i.e., Word, Excel, and PowerPoint [open-source](https://itsfoss.com/what-is-foss/) replacement. Let’s see what office suits for Linux have we got here: ### 6. Apache OpenOffice ![OpenOffice Logo](https://itsfoss.com/content/images/wordpress/2012/06/open-office-logo-wide.jpg) [Apache OpenOffice](https://www.openoffice.org/) or simply OpenOffice has a history of name/owner change. It was born as Star Office in 1999 by Sun Microsystems, which later renamed it OpenOffice to pit it against MS Office as a free and open-source alternative. When Oracle bought Sun in 2010, it discontinued the development of OpenOffice after a year. And finally, it was Apache that supported it, and it is now known as Apache OpenOffice. Apache OpenOffice is available for many platforms that include Linux, Windows, macOS, Unix, BSD. It also includes support for MS Office files, apart from its own OpenDocument format. The office suite contains the following applications: Writer, Calc, Impress, Base, Draw, Math. [Installing OpenOffice](https://itsfoss.com/install-openoffice-ubuntu-linux/) is a pain as it doesn’t provide a decent installer. Unless you rely on OpenOffice and do not want to break compatibility or any modern features, there may not be enough reasons to use OpenOffice. ### 5. Feng Office ![Feng Office logo](https://itsfoss.com/content/images/wordpress/2012/06/feng-office-logo-wide-800x240.jpg) [Feng Office](http://www.fengoffice.com/web/index.php?lang=en) was formerly known as OpenGoo. It is not your regular office suite. It is entirely focused on being an online office suite like Google Docs. In other words, it’s an open-source [collaboration platform](https://en.wikipedia.org/wiki/Collaborative_software). There is no desktop version available, so if you are looking to use it on a single Linux desktop, you are out of luck here. On the other hand, if you have a small business, an institution, or some other organization, you may attempt to deploy it on the local server. ### 4. CrypPad ![Cryptpad Features](https://itsfoss.com/content/images/wordpress/2020/08/cryptpad-features.png) [CryptPad](https://itsfoss.com/cryptpad/) is an end-to-end encrypted collaboration suite that features a word processor, spreadsheet, and slides as well. Not just as an encrypted alternative, but it also focuses on privacy, meaning, the service does not record any of your activity, unlike the Office 365 service by Microsoft. It may not be as feature-rich as you’d expect, but it should be a good pick for basic usage. You can sign up for an account and use it for free, or opt to self-host an instance if you require. There are no desktop clients for this. For more information, you can head to its [GitHub page](https://github.com/xwiki-labs/cryptpad) or the [official website](https://cryptpad.fr/). ### 3. Calligra Suite ![Calligra free and Open Source office logo](https://itsfoss.com/content/images/wordpress/2012/06/calligra-office-logo-wide-800x240.jpg) [Calligra](https://www.calligra.org/), formerly known as KOffice, is the default Office suite in KDE. It is available for Linux and FreeBSD systems with support for macOS and Windows. It was also [launched for Android](https://itsfoss.com/calligra-android-app-coffice/). But unfortunately, it’s not available for Android anymore. It has all the applications needed for an office suite along with some extra applications such as Flow for flow charts and plane for project management. Calligra offers some useful features that make it an interesting alternative to LibreOffice. ### 2. ONLYOFFICE ![ONLYOFFICE is Linux alternative to Microsoft Office](https://itsfoss.com/content/images/wordpress/2012/06/only-office-logo-wide-800x240.png) Relatively a new player in the market, is an office suite more focused on the [collaborative](https://en.wikipedia.org/wiki/Collaborative_software) part. Enterprises (and even individuals) can deploy it on their server to have a Google Docs-like collaborative office suite. Don’t worry. You don’t have to bother about installing it on a server. There is a free and [open source desktop version of ONLYOFFICE](https://itsfoss.com/review-onlyoffice-desktop-editors-linux/). You can even get .deb and .rpm binaries to easily [install it on your desktop Linux system](https://itsfoss.com/go/onlyoffice-download/). A flatpak package is also available on Flathub. If you are using [Nextcloud](https://itsfoss.com/nextcloud/) as a collaboration platform, you can also use OnlyOffice as an online office suite. ### 1. LibreOffice ![LibreOffice logo](https://itsfoss.com/content/images/wordpress/2012/06/LibreOffice-logo-wide-800x240.jpg) When Oracle decided to discontinue the development of OpenOffice, it was [The Document Foundation](https://www.documentfoundation.org/) who forked it and gave us what is known as [LibreOffice](https://www.libreoffice.org/). Since then, several Linux distributions have [replaced OpenOffice for LibreOffice](https://itsfoss.com/libreoffice-vs-openoffice/) as their default office application. It is available for Linux, Windows, and macOS, making it easy to use in a cross-platform environment. Same as Apache OpenOffice, this too includes support for MS Office files apart from its own OpenDocument format. It also contains the same applications as Apache OpenOffice. You can also use LibreOffice as a collaborative platform using [Collabora Online](https://www.collaboraoffice.com/collabora-online/). Basically, LibreOffice is a complete package and undoubtedly the best **Microsoft Office alternative for Linux**, Windows, and macOS. ### What do you think? If you only want an application to write documents, not spreadsheets and presentation slides, you may check out the [list of open source word processors](https://itsfoss.com/best-open-source-word-processors/). It has some additional options that have not been mentioned here. I hope these Open Source alternatives to Microsoft Office save your money. Which open source productivity suite do you use?
9,380
如何使用 lftp 来加速 ftp/https 下载速度
https://www.cyberciti.biz/tips/linux-unix-download-accelerator.html
2018-02-26T09:11:00
[ "lftp" ]
https://linux.cn/article-9380-1.html
![](/data/attachment/album/201802/24/212144zq1cldcoqrcl1eqe.jpg) `lftp` 是一个文件传输程序。它可以用于复杂的 FTP、 HTTP/HTTPS 和其他连接。如果指定了站点 URL,那么 `lftp` 将连接到该站点,否则会使用 `open` 命令建立连接。它是所有 Linux/Unix 命令行用户的必备工具。我目前写了一些关于 [Linux 下超快命令行下载加速器](https://www.cyberciti.biz/tips/download-accelerator-for-linux-command-line-tools.html),比如 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' ``` ### 关于并行下载的说明 请注意,通过使用下载加速器,你将增加远程服务器负载。另请注意,`lftp` 可能无法在不支持多点下载的站点上工作,或者防火墙阻止了此类请求。 其它的命令提供了更多功能。有关更多信息,请参考 [lftp](https://lftp.yar.ru/) 的 man 页面: ``` man lftp ``` ### 关于作者 作者是 nixCraft 的创建者,经验丰富的系统管理员,也是 Linux 操作系统/Unix shell 脚本的培训师。他曾与全球客户以及IT、教育、国防和太空研究以及非营利部门等多个行业合作。在 [Twitter][9]、[Facebook][10]、[Google +][11] 上关注他。通过 [RSS/XML 订阅](https://plus.google.com/+CybercitiBiz)获取最新的系统管理、Linux/Unix 以及开源主题教程。 --- via: <https://www.cyberciti.biz/tips/linux-unix-download-accelerator.html> 作者:[Vivek Gite](https://www.cyberciti.biz) 译者:[geekpi](https://github.com/geekpi) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
403
Forbidden
null
9,381
如何使用 cloud-init 来预配置 LXD 容器
https://blog.simos.info/how-to-preconfigure-lxd-containers-with-cloud-init/
2018-02-24T21:25:37
[ "LXD", "容器" ]
https://linux.cn/article-9381-1.html
![](/data/attachment/album/201802/24/212520cj6y0lj9jj49nvz4.jpg) 当你正在创建 LXD 容器的时候,你希望它们能被预先配置好。例如在容器一启动就自动执行 `apt update`来安装一些软件包,或者运行一些命令。 这篇文章将讲述如何用 [cloud-init](http://cloudinit.readthedocs.io/en/latest/index.html) 来对 [LXD 容器进行进行早期初始化](https://github.com/lxc/lxd/blob/master/doc/cloud-init.md)。 接下来,我们将创建一个包含cloud-init指令的LXD profile,然后启动一个新的容器来使用这个profile。 ### 如何创建一个新的 LXD profile 查看已经存在的 profile: ``` $ lxc profile list +---------|---------+ | NAME | USED BY | +---------|---------+ | default | 11 | +---------|---------+ ``` 我们把名叫 `default` 的 profile 复制一份,然后在其内添加新的指令: ``` $ lxc profile copy default devprofile $ lxc profile list +------------|---------+ | NAME | USED BY | +------------|---------+ | default | 11 | +------------|---------+ | devprofile | 0 | +------------|---------+ ``` 我们就得到了一个新的 profile: `devprofile`。下面是它的详情: ``` $ lxc profile show devprofile config: environment.TZ: "" description: Default LXD profile devices: eth0: nictype: bridged parent: lxdbr0 type: nic root: path: / pool: default type: disk name: devprofile used_by: [] ``` 注意这几个部分: `config:` 、 `description:` 、 `devices:` 、 `name:` 和 `used_by:`,当你修改这些内容的时候注意不要搞错缩进。(LCTT 译注:因为这些内容是 YAML 格式的,缩进是语法的一部分) ### 如何把 cloud-init 添加到 LXD profile 里 [cloud-init](http://cloudinit.readthedocs.io/en/latest/index.html) 可以添加到 LXD profile 的 `config` 里。当这些指令将被传递给容器后,会在容器第一次启动的时候执行。 下面是用在示例中的指令: ``` package_upgrade: true packages: - build-essential locale: es_ES.UTF-8 timezone: Europe/Madrid runcmd: - [touch, /tmp/simos_was_here] ``` `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 命令](http://cloudinit.readthedocs.io/en/latest/topics/modules.html#runcmd)。 我们需要关注如何将 `cloud-init` 指令插入 LXD profile。 我首选的方法是: ``` $ lxc profile edit devprofile ``` 它会打开一个文本编辑器,以便你将指令粘贴进去。[结果应该是这样的](https://paste.ubuntu.com/26313399/): ``` $ lxc profile show devprofile config: environment.TZ: "" user.user-data: | #cloud-config package_upgrade: true packages: - build-essential locale: es_ES.UTF-8 timezone: Europe/Madrid runcmd: - [touch, /tmp/simos_was_here] description: Default LXD profile devices: eth0: nictype: bridged parent: lxdbr0 type: nic root: path: / pool: default type: disk name: devprofile used_by: [] ``` ### 如何使用 LXD profile 启动一个容器 使用 profile `devprofile` 来启动一个新容器: ``` $ lxc launch --profile devprofile ubuntu:x mydev ``` 然后访问该容器来查看我们的指令是否生效: ``` $ lxc exec mydev bash root@mydev:~# ps ax PID TTY STAT TIME COMMAND 1 ? Ss 0:00 /sbin/init ... 427 ? Ss 0:00 /usr/bin/python3 /usr/bin/cloud-init modules --mode=f 430 ? S 0:00 /bin/sh -c tee -a /var/log/cloud-init-output.log 431 ? S 0:00 tee -a /var/log/cloud-init-output.log 432 ? S 0:00 /usr/bin/apt-get --option=Dpkg::Options::=--force-con 437 ? S 0:00 /usr/lib/apt/methods/http 438 ? S 0:00 /usr/lib/apt/methods/http 440 ? S 0:00 /usr/lib/apt/methods/gpgv 570 ? Ss 0:00 bash 624 ? S 0:00 /usr/lib/apt/methods/store 625 ? R+ 0:00 ps ax root@mydev:~# ``` 如果我们连接得够快,通过 `ps ax` 将能够看到系统正在更新软件。我们可以从 `/var/log/cloud-init-output.log` 看到完整的日志: ``` Generating locales (this might take a while)... es_ES.UTF-8... done Generation complete. ``` 以上可以看出 `locale` 已经被更改了。root 用户还是保持默认的 `C.UTF-8`,只有非 root 用户 `ubuntu` 使用了新的`locale` 设置。 ``` Hit:1 http://archive.ubuntu.com/ubuntu xenial InRelease 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`。 ``` The following packages will be upgraded: libdrm2 libseccomp2 squashfs-tools unattended-upgrades 4 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 211 kB of archives. ``` 以上是在执行 `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` 执行的结果如何? ``` root@mydev:~# ls -l /tmp/ total 1 -rw-r--r-- 1 root root 0 Jan 3 15:23 simos_was_here root@mydev:~# ``` 可见它已经生效了! ### 结论 当我们启动 LXD 容器的时候,我们常常需要默认启用一些配置,并且希望能够避免重复工作。通常解决这个问题的方法是创建 LXD profile,然后把需要的配置添加进去。最后,当我们启动新的容器时,只需要应用该 LXD profile 即可。 --- via: <https://blog.simos.info/how-to-preconfigure-lxd-containers-with-cloud-init/> 作者:[Simos Xenitellis](https://blog.simos.info/author/simos/) 译者:[kaneg](https://github.com/kaneg) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
The original post here is now obsolete and it has been replaced by the following: Jan 03 2018 # How to preconfigure LXD containers with cloud-init **Permanent link to this article: **https://blog.simos.info/how-to-preconfigure-lxd-containers-with-cloud-init/ ## 6 comments ## 1 pings Skip to comment form Cloud-init works only image ubuntu: How to use images: or other OS (Cetnos, Debian, etc)& Author Here is the relevant bug report and discussion on adding cloud-init on Debian, https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850790 The Debian image from images:debian/stretch does not have cloud-init pre-installed. The Centos image is 73MB and I doubt it has cloud-init. I suppose you have checked already. I think it is important for different distributions to add cloud-init support to their images. If you are interested in smaller Ubuntu images (but still have cloud-init), see the Ubuntu Minimal, https://blog.simos.info/a-closer-look-at-minimal-ubuntu-for-lxd/ I tried install cloud-init in centos container and create image from container. Not work. lxc exec c2 bash yum install python2.7-minimal cloud-init exit lxc stop c2 lxc publish c2 –alias centos-7 Author Ideally, you would use distrobuilder (https://github.com/lxc/distrobuilder) to create a new container for your distribution. There is a template already for Centos. I do not know why in your published image, cloud-init is not working. It should be easy to debug this by following the boot-up sequence of the runtime. Can’t seem to get this to work on Ubuntu Bionic LTS. I have this in my LXD profile definition: config: environment.TZ: America/New_York user.user-data: | #cloud-init config package_upgrade: true package_reboot_if_required: true locale: es_US.UTF-8 timezone: America/New_York And in the container in `/var/lib/cloud/seed/nocloud-net/user-data` , I have:#cloud-init config package_upgrade: true package_reboot_if_required: true locale: es_US.UTF-8 timezone: America/New_York But none of the packages are updated and there is no mention in the cloud-init logs of an attempt. Any ideas? Does not work for ‘ubuntu:focal’ Where is it stated which images have cloud-init enabled. This changed and I had all sorts of trouble, and looked in all the wrong places to try and fix it. 🙂 […] How to preconfigure LXD containers with cloud-init […]
9,382
Python 中最快解压 zip 文件的方法
https://www.peterbe.com/plog/fastest-way-to-unzip-a-zip-file-in-python
2018-02-28T09:27:00
[ "zip" ]
https://linux.cn/article-9382-1.html
![](/data/attachment/album/201802/24/213511kqgmemzlqmcbw15n.jpg) 假设现在的上下文(LCTT 译注:context,计算机术语,此处意为业务情景)是这样的:一个 zip 文件被上传到一个[Web 服务](https://symbols.mozilla.org)中,然后 Python 需要解压这个 zip 文件然后分析和处理其中的每个文件。这个特殊的应用查看每个文件各自的名称和大小,并和已经上传到 AWS S3 上的文件进行比较,如果文件(和 AWS S3 上的相比)有所不同或者文件本身更新,那么就将它上传到 AWS S3。 [![Uploads today](/data/attachment/album/201802/24/213540t8v50jgvvtt8vqgg.png)](https://cdn-2916.kxcdn.com/cache/e6/dc/e6dc20acd37d94239edbbc0727721e4a.png) 挑战在于这些 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%** ### 第二步尝试 所以可能是 GIL(LCTT 译注: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](https://www.peterbe.com/) 译者:[Leemeans](https://github.com/leemeans) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
So the context is this; a zip file is uploaded into a [web service](https://symbols.mozilla.org) and Python then needs extract that and analyze and deal with each file within. In this particular application what it does is that it looks at the file's individual name and size, compares that to what has already been uploaded in AWS S3 and if the file is believed to be different or new, it gets uploaded to AWS S3. The challenge is that these zip files that come in are huuuge. The average is 560MB but some are as much as 1GB. Within them, there are mostly plain text files but there are some binary files in there too that are huge. It's not unusual that each zip file contains 100 files and 1-3 of those make up 95% of the zip file size. At first I tried unzipping the file, in memory, and deal with one file at a time. That failed spectacularly with various memory explosions and EC2 running out of memory. I guess it makes sense. First you have the 1GB file in RAM, then you unzip each file and now you have possibly 2-3GB all in memory. So, the solution, after much testing, was to dump the zip file to disk (in a temporary directory in `/tmp` ) and then iterate over the files. This worked much better but I still noticed the whole unzipping was taking up a huge amount of time. **Is there perhaps a way to optimize that?** ### Baseline function First it's these common functions that simulate actually doing something with the files in the zip file: ``` 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 ``` Here's the simplest one possible: ``` 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 ``` If I analyze it a bit more carefully, I find that it spends about 40% doing the `extractall` and 60% doing the looping over files and reading their full length. ### First attempt My first attempt was to try to use threads. You create an instance of `zipfile.ZipFile` , extract every file name within and start a thread for each name. Each thread is given a function that does the "meat of the work" (in this benchmark, iterating over the file and getting its total size). In reality that function does a bunch of complicated S3, Redis and PostgreSQL stuff but in my benchmark I just made it a function that figures out the total length of file. The thread pool function: ``` 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 ``` **Result: ~10% faster** ### Second attempt So perhaps the GIL is blocking me. The natural inclination is to try to use multiprocessing to spread the work across multiple available CPUs. But doing so has the disadvantage that you can't pass around a non-pickleable object so you have to send just the filename to each future function: ``` 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 ``` **Result: ~300% faster** ### That's cheating! The problem with using a pool of processors is that it requires that the original `.zip` file exists on disk. So in my web server, to use this solution, I'd first have to save the in-memory ZIP file to disk, then invoke this function. Not sure what the cost of that it's not likely to be cheap. Well, it doesn't hurt to poke around. Perhaps, it could be worth it if the extraction was significantly faster. But remember! This optimization depends on using up as many CPUs as it possibly can. What if some of those other CPUs are needed for something else going on in `gunicorn` ? Those other processes would have to patiently wait till there's a CPU available. Since there's other things going on in this server, I'm not sure I'm willing to let on process take over all the other CPUs. ### Conclusion Doing it serially turns out to be quite nice. You're bound to one CPU but the performance is still pretty good. Also, just look at the difference in the code between `f1` and `f2` ! With `concurrent.futures` pool classes you can cap the number of CPUs it's allowed to use but that doesn't feel great either. What if you get the number wrong in a virtual environment? Of if the number is too low and don't benefit any from spreading the workload and now you're just paying for overheads to move the work around? I'm going to stick with `zipfile.ZipFile(file_buffer).extractall(temp_dir)` . It's good enough for this. ### Want to try your hands on it? I did my benchmarking using a `c5.4xlarge` EC2 server. The files can be downloaded from: 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 The `.zip` file there is 34MB which is relatively small compared to what's happening on the server. The `hack.unzip-in-parallel.py` is a hot mess. It contains a bunch of terrible hacks and ugly stuff but hopefully it's a start. ## Comments Post your own commentFebruary 1, 2018AnonymousConsider using bzip2, xz or something similar which can be both compressed and decompressed in parallel. See pbzip2 and pixz. (Zip does not lend itself to this, so pigz would not help you too much under most circumstances.) Choose the right UNIX tool, subprocesses and pipes are the way to go here and pipes can go across network boundaries as well - rely on the deep history of computing. Peter BengtssonFebruary 1, 2018Zip files can be decompressed in parallel too. You first ask the zip file for its file contents (fast), then you start parallel processes (or threads or whatever) that each get a file name to extract. My multiprocess example above is a proof of that. Martin BammerFebruary 1, 2018You should not use ThreadPoolExecutor, because it has a relatively high overhead and is very slow. Especially if you use submit. Use a different thread pool implementation or if you want to stick with ThreadPoolExecutor use map. A much faster solution is the good old multiprocessing.pool.ThreadPool. Or you could also try my fastthreadpool module (https://github.com/brmmm3/fastthreadpool). This module is faster than ThreadPool and much faster than ThreadPoolExecutor. It also has the advantage that you can use generator functions as worker which is very useful in certain situations. For example code please look into benchmark.py. The doc directory contains some benchmark files which show the overhead difference between the 3 thread pool implementations. I'm also working on a fastprocesspool module but this is still not finished and buggy, First tests have shown that this module is also faster than multiprocessing.Pool and much fast than ProcessPoolExecutor. Peter BengtssonFebruary 4, 2018What's the alternative to submit? And multiprocessing.Pool might be marginally faster, but isn't the bulk of the computation still in the actual unzipping? Martin BammerFebruary 5, 2018The bulk is indeed in unzipping. But if you've an archive with many small files the overhead of the pool can be 10% or more. And this is much for just handling a pool of threads. The alternative is to use map, where you have to prepare an iterable before calling map. Another alternative is to switch to a faster pool implementation. The module zipfile is completely written in Python, which comes with a relatively big overhead at Python level, which in turn means the GIL is locked relatively long. The result is a low level of parallelisation. I'm currently writing an archiving tool which uses msgpack and zstd. Both libraries have a very thin Python layer and parallelisation with threads is very good. I get nearly 100% CPU load. The results currently are ~4 faster than zip and compression ratio between zip and lzma. When the tool is finished I'll release it for the public. Peter BengtssonFebruary 6, 2018If you have an example of using fastthreadpool that I can use instead of concurrent.futures.ThreadPoolExecutor or concurrent.futures.ProcessPoolExecutor then I'll try to run a benchmark with that too. MasklinnFebruary 4, 2018Peter, if you don't need the entire content of the file in memory (which I guess you don't since you're apparently fine with reading it from disk despite in-memory decompression blowing up) *and* you don't need seekability, you may have missed the `open` method on zipfiles. You'll still be paying for the decompression work, and as noted previously you can only access data sequentially (no seeking backwards) but it *is* lazy, you ask for a 10k chunk of a file, you get 10k in memory (plus some overhead from Python). Peter BengtssonFebruary 4, 2018Doing an open requires all things to be in-memory. It's a bit faster but would require me to have a much beefier server, which might be the best course of action actually. MasklinnFebruary 5, 2018> Doing an open requires all things to be in-memory. It only requires that the zip file be accessible, either in-memory or on-disk. Your introduction says that you originally had the zip file *and* the decompressed files in memory, ZipFile.open avoids the latter. Furthermore the small bit of code you post in the conclusion seems to hint that you still have the zip file in memory when you do the extraction. And again, you can use ZipFile.open just fine if you have the zip file on-disk, it's still lazy. jfsFebruary 7, 2018It might be more efficient to count bytes by reading chunks instead of lines: `_count_file_object = lambda file: sum(map(len, iter(lambda: file.read(1<<15), b'')))` (assuming you don't want `os.path.getsize(filename)` or similar). Related: https://stackoverflow.com/questions/9371238/why-is-reading-lines-from-stdin-much-slower-in-c-than-python mikeSeptember 12, 2018awesome! thanks a lot! October 21, 2020AnonymousPeter, Can we do similar improvements with ZipFile.write() if it irequired to zip folders and files in parallel? Thanks. May 6, 2022AnonymousThanks for this code. I have something similar based on it running in production and I hit a wall. Decompressing archives containing 65688 files will result to be very very slow. To have a significant speed boost you can try something similar to this https://github.com/ITISFoundation/osparc-simcore/blob/cd9640c0072fcd2536a0ae11cd602e7b7a9ea3ee/packages/service-library/src/servicelib/archiving_utils.py#L45 It basically avoids reading the entire file list from the zipfile inside the background process! ViolaOctober 30, 2022How should I increase the instance number or thread number?because I have many zip file to extract. Peter BengtssonOctober 31, 2022From https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor "If max_workers is None or not given, it will default to the number of processors on the machine." So by default, it will use as many CPUs as your computer possibly has.
9,383
通过 ncurses 在终端创建一个冒险游戏
http://www.linuxjournal.com/content/creating-adventure-game-terminal-ncurses
2018-02-25T09:38:00
[ "ncurses" ]
https://linux.cn/article-9383-1.html
![](/data/attachment/album/201802/25/100828w9xu9oaiyptt8oah.jpg) > > 怎样使用 curses 函数读取键盘并操作屏幕。 > > > 我[之前的文章](/article-9348-1.html)介绍了 ncurses 库,并提供了一个简单的程序展示了一些将文本放到屏幕上的 curses 函数。在接下来的文章中,我将介绍如何使用其它的 curses 函数。 ### 探险 当我逐渐长大,家里有了一台苹果 II 电脑。我和我兄弟正是在这台电脑上自学了如何用 AppleSoft BASIC 写程序。我在写了一些数学智力游戏之后,继续创造游戏。作为 80 年代的人,我已经是龙与地下城桌游的粉丝,在游戏中角色扮演一个追求打败怪物并在陌生土地上抢掠的战士或者男巫,所以我创建一个基本的冒险游戏也在情理之中。 AppleSoft BASIC 支持一种简洁的特性:在标准分辨率图形模式(GR 模式)下,你可以检测屏幕上特定点的颜色。这为创建一个冒险游戏提供了捷径。比起创建并更新周期性传送到屏幕的内存地图,我现在可以依赖 GR 模式为我维护地图,我的程序还可以在玩家的角色(LCTT 译注:此处 character 双关一个代表玩家的角色,同时也是一个字符)在屏幕四处移动的时候查询屏幕。通过这种方式,我让电脑完成了大部分艰难的工作。因此,我的自顶向下的冒险游戏使用了块状的 GR 模式图形来展示我的游戏地图。 我的冒险游戏使用了一张简单的地图,上面有一大片绿地伴着山脉从中间蔓延向下和一个在左上方的大湖。我要粗略地为桌游战役绘制这个地图,其中包含一个允许玩家穿过到远处的狭窄通道。 ![](/data/attachment/album/201802/24/215504fa44evgot8t66fye.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环境并退出。 ### 开始玩 当你运行游戏时,玩家的字符在左下角初始化。当玩家在游戏区域四处移动的时候,程序创建了“一串”点。这样可以展示玩家经过了的点,让玩家避免经过不必要的路径。 ![](/data/attachment/album/201802/25/101020cy7yjhz2t7jptcwl.png) *图 2. 初始化在左下角的玩家* ![](/data/attachment/album/201802/25/101058bcgg5cydhksspdip.png) *图 3. 玩家可以在游戏区域四处移动,例如湖周围和山的通道* 为了创建上面这样的完整冒险游戏,你可能需要在他/她的角色在游戏区域四处移动的时候随机创建不同的怪物。你也可以创建玩家可以发现在打败敌人后可以掠夺的特殊道具,这些道具应能提高玩家的能力。 但是作为起点,这是一个展示如何使用 curses 函数读取键盘和操纵屏幕的好程序。 ### 下一步 这是一个如何使用 curses 函数更新和读取屏幕和键盘的简单例子。按照你的程序需要做什么,curses 可以做得更多。在下一篇文章中,我计划展示如何更新这个简单程序以使用颜色。同时,如果你想要学习更多 curses,我鼓励你去读位于 Linux 文档计划的 Pradeep Padala 写的[如何使用 NCURSES 编程](http://tldp.org/HOWTO/NCURSES-Programming-HOWTO)。 --- via: <http://www.linuxjournal.com/content/creating-adventure-game-terminal-ncurses> 作者:[Jim Hall](http://www.linuxjournal.com/users/jim-hall) 译者:[Leemeans](https://github.com/leemeans) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
301
Moved Permanently
null
9,384
为初学者介绍 Linux whereis 命令(5个例子)
https://www.howtoforge.com/linux-whereis-command/
2018-02-25T13:22:09
[ "whereis", "find" ]
https://linux.cn/article-9384-1.html
![](/data/attachment/album/201802/25/132156q2n3h3be03tn33ax.jpg) 有时,在使用命令行的时候,我们需要快速找到某一个命令的二进制文件所在位置。这种情况下可以选择 [find](https://www.howtoforge.com/tutorial/linux-find-command/) 命令,但使用它会耗费时间,可能也会出现意料之外的情况。有一个专门为这种情况设计的命令:`whereis`。 在这篇文章里,我们会通过一些便于理解的例子来解释这一命令的基础内容。但在这之前,值得说明的一点是,下面出现的所有例子都在 Ubuntu 16.04 LTS 下测试过。 ### Linux whereis 命令 `whereis` 命令可以帮助用户寻找某一命令的二进制文件,源码以及帮助页面。下面是它的格式: ``` whereis [options] [-BMS directory... -f] name... ``` 这是这一命令的 man 页面给出的解释: > > `whereis` 可以查找指定命令的二进制文件、源文件和帮助文件。 被找到的文件在显示时,会去掉主路径名,然后再去掉文件的(单个)尾部扩展名 (如: `.c`),来源于源代码控制的 `s.` 前缀也会被去掉。接下来,`whereis` 会尝试在标准的 Linux 位置里寻找具体程序,也会在由 `$PATH` 和 `$MANPATH` 指定的路径中寻找。 > > > 下面这些以 Q&A 形式出现的例子,可以给你一个关于如何使用 whereis 命令的直观感受。 ### Q1. 如何用 whereis 命令寻找二进制文件所在位置? 假设你想找,比如说,`whereis` 命令自己所在位置。下面是你具体的操作: ``` whereis whereis ``` [![How to find location of binary file using whereis](/data/attachment/album/201802/25/132209hea1ryrzpw11faga.png)](https://www.howtoforge.com/images/command-tutorial/big/whereis-basic-usage.png) 需要注意的是,输出的第一个路径才是你想要的结果。使用 `whereis` 命令,同时也会显示帮助页面和源码所在路径。(如果能找到的情况下会显示,但是在这一例中没有找到)所以你在输出中看见的第二个路径就是帮助页面文件所在位置。 ### Q2. 怎么在搜索时规定只搜索二进制文件、帮助页面,还是源代码呢? 如果你想只搜索,假设说,二进制文件,你可以使用 `-b` 这一命令行选项。例如: ``` whereis -b cp ``` [![How to specifically search for binaries, manuals, or source code](/data/attachment/album/201802/25/132210x16gujmn1s8n0nzn.png)](https://www.howtoforge.com/images/command-tutorial/big/whereis-b-option.png) 类似的, `-m` 和 `-s` 这两个 选项分别对应 帮助页面和源码。 ### Q3.如何限制 whereis 命令搜索位置? 默认情况下,`whereis` 是从由匹配符所定义的硬编码路径来寻找文件的。但如果你想的话,你可以用命令行选项来限制搜索。例如,如果你只想在 `/usr/bin` 寻找二进制文件,你可以用 `-B` 这一选项来实现。 ``` whereis -B /usr/bin/ -f cp ``` 注意:使用这种方式时可以给出多个路径。使用 `-f` 这一选项来明确分隔目录列表和要搜索的文件名。 类似的,如果你想只搜索帮助文件或源码,你可以对应使用 `-M` 和 `-S` 这两个选项。 ### Q4. 如何查看 whereis 的搜索路径? 与此相对应的也有一个选项。只要在 `whereis` 后加上 `-l`。 ``` whereis -l ``` 这是例子的部分输出结果: [![How to see paths that whereis uses for search](/data/attachment/album/201802/25/132210kz0392d1fl1ndzgf.png)](https://www.howtoforge.com/images/command-tutorial/big/whereis-l.png) ### Q5. 如何找到一个有异常条目的命令? 对于 `whereis` 命令来说,如果一个命令对每个显式的请求类型都不止一项,则该命令被视为异常。例如,没有可用文档的命令,或者对应文档分散在各处的命令都可以算作异常命令。 当使用 `-u` 这一选项,`whereis` 就会显示那些有异常条目的命令。 例如,下面这一例子就显示,在当前目录中,没有对应文档或有多个文档的命令。 ``` whereis -m -u * ``` ### 总结 我觉得,`whereis` 不是那种你需要经常使用的命令行工具。但在遇到某些特殊情况时,它绝对会让你的生活变得轻松。我们已经涉及了这一工具提供的一些重要命令行选项,所以要注意练习。想了解更多信息,直接去看它的 [man](https://linux.die.net/man/1/whereis) 页面吧。 --- via: <https://www.howtoforge.com/linux-whereis-command/> 作者:[Himanshu Arora](https://www.howtoforge.com) 译者:[wenwensnow](https://github.com/wenwensnow) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
# Linux whereis Command Explained for Beginners (5 Examples) ### On this page [Linux whereis command](#linux-whereis-command)[Q1. How to find location of binary file using whereis?](#q-how-to-find-location-of-binary-file-using-whereis)[Q2. How to specifically search for binaries, manuals, or source code?](#q-how-to-specifically-search-for-binaries-manuals-or-source-code)[Q3. How to limit whereis search as per requirement?](#q-how-to-limit-whereis-search-as-per-requirement)[Q4. How to see paths that whereis uses for search?](#q-how-to-see-paths-that-whereis-uses-for-search)[Q5. How to find command names with unusual entries?](#q-how-to-find-command-names-with-unusual-entries)[Conclusion](#conclusion) Sometimes, while working on the command line, we just need to quickly find out the location of the binary file for a command. Yes, the [find](https://www.howtoforge.com/tutorial/linux-find-command/) command is an option in this case, but it's a bit time consuming and will likely produce some non-desired results as well. There's a specific command that's designed for this purpose: **whereis**. In this article, we will discuss the basics of this command using some easy to understand examples. But before we do that, it's worth mentioning that all examples in this tutorial have been tested on Ubuntu 16.04LTS. ## Linux whereis command The whereis command lets users locate binary, source, and manual page files for a command. Following is its syntax: whereis [options] [-BMS directory... -f] name... And here's how the tool's man page explains it: whereis locates the binary, source and manual files for the specified command names. The supplied names are first stripped of leading pathname components and any (single) trailing extension of the form .ext (for example: .c) Prefixes of s. resulting from use of source code control are also dealt with. whereis then attempts to locate the desired program in the standard Linux places, and in the places specified by $PATH and $MANPATH. The following Q&A-styled examples should give you a good idea on how the whereis command works. ## Q1. How to find location of binary file using whereis? Suppose you want to find the location for, let's say, the whereis command itself. Then here's how you can do that: whereis whereis Note that the first path in the output is what you are looking for. The whereis command also produces paths for manual pages and source code (if available, which isn't in this case). So the second path you see in the output above is the path to the whereis manual file(s). ## Q2. How to specifically search for binaries, manuals, or source code? If you want to search specifically for, say binary, then you can use the **-b** command line option. For example: whereis -b cp Similarly, the **-m** and **-s** options are used in case you want to find manuals and sources. ## Q3. How to limit whereis search as per requirement? By default whereis tries to find files from hard-coded paths, which are defined with glob patterns. However, if you want, you can limit the search using specific command line options. For example, if you want whereis to only search for binary files in /usr/bin, then you can do this using the **-B** command line option. whereis -B /usr/bin/ -f cp **Note**: Since you can pass multiple paths this way, the **-f** command line option terminates the directory list and signals the start of file names. Similarly, if you want to limit manual or source searches, you can use the **-M** and **-S** command line options. ## Q4. How to see paths that whereis uses for search? There's an option for this as well. Just run the command with **-l**. whereis -l Here is the list (partial) it produced for us: ## Q5. How to find command names with unusual entries? For whereis, a command becomes unusual if it does not have just one entry of each explicitly requested type. For example, commands with no documentation available, or those with documentation in multiple places are considered unusual. The **-u** command line option, when used, makes whereis show the command names that have unusual entries. For example, the following command should display files in the current directory which have no documentation file, or more than one. whereis -m -u * ## Conclusion Agreed, whereis is not the kind of command line tool that you'll require very frequently. But when the situation arises, it definitely makes your life easy. We've covered some of the important command line options the tool offers, so do practice them. For more info, head to its [man page](https://linux.die.net/man/1/whereis).
9,385
Opensource.com 的 2017 年最佳开源教程
https://opensource.com/article/18/1/best-tutorials
2018-02-26T12:27:00
[ "教程", "开源" ]
https://linux.cn/article-9385-1.html
2017 年,Opensource.com 发布了一系列用于帮助从初学者到专家的教程。让我们看看哪些最好。 ![](/data/attachment/album/201802/26/122704kdfp9g9coq9fp227.png) 精心编写的教程对于任何软件的官方文档来说都是一个很好的补充。如果官方文件写得不好,不完整或根本没有,那么这些教程也可以是个有效的替代品。 2017 年,Opensource.com 发布一些有关各种主题的优秀教程。这些教程不只是针对专家们的,它们是针对各种技能水平和经验的用户的。 让我们来看看其中最好的教程。 ### 关于代码 对许多人来说,他们第一次涉足开源是为一个项目或另一个项目贡献代码。你在哪里学习编码或编程的?以下两篇文章是很好的起点。 严格来说,VM Brasseur 的[如何开始学习编程](/article-8694-1.html)是新手程序员的一个很好的起点,而不是一个教程。它不仅指出了一些有助于你开始学习的优秀资源,而且还提供了了解你的学习方式和如何选择语言的重要建议。 如果您已经在一个 [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) 或文本编辑器中敲击了几个小时,那么您可能需要学习更多关于编码的不同方法。Fraser Tweedale 的[函数式编程简介](/article-8869-1.html)很好地介绍了可以应用到许多广泛使用的编程语言的范式。 ### 踏足 Linux Linux 是开源的典范。它运行了大量的 Web 站点,为世界顶级的超级计算机提供了动力。它让任何人都可以替代台式机上的专有操作系统。 如果你有兴趣深入 Linux,这里有三个教程供你参考。 Jason Baker 告诉你[设置 Linux $PATH 变量](https://opensource.com/article/17/6/set-path-linux)。他引导你掌握这一“任何 Linux 初学者的重要技巧”,使您能够告知系统包含了程序和脚本的目录。 感谢 David Both 的[建立一个 DNS 域名服务器](https://opensource.com/article/17/4/build-your-own-name-server)指南。他详细地记录了如何设置和运行服务器,包括要编辑的配置文件以及如何编辑它们。 想在你的电脑上更复古一点吗?Jim Hall 告诉你如何使用 [FreeDOS](http://www.freedos.org/)和 [qemu](https://www.qemu.org) [在 Linux 下运行 DOS 程序](/article-9014-1.html)。Hall 的文章着重于运行 DOS 生产力工具,但并不全是严肃的——他也谈到了运行他最喜欢的 DOS 游戏。 ### 3 片(篇)树莓派 廉价的单板计算机使硬件再次变得有趣,这并不是秘密。不仅如此,它们使更多的人更容易接近,无论他们的年龄或技术水平如何。 其中,[树莓派](https://en.wikipedia.org/wiki/Raspberry_Pi)可能是最广泛使用的单板计算机。Ben Nuttall 带我们一起[在树莓派上安装和设置 Postgres 数据库](/article-9056-1.html)。这样,你可以在任何你想要的项目中使用它。 如果你的品味包括文学和技术,你可能会对 Don Watkins 的[如何将树莓派变成电子书服务器](/article-8684-1.html)感兴趣。稍微付出一点努力和一份 [Calibre 电子书管理软件](https://calibre-ebook.com/)副本,你就可以得到你最喜欢的电子书,无论你在哪里。 树莓派并不是其中唯一有特点的。还有 [Orange Pi Pc Plus](http://www.orangepi.org/),这是一种开源的单板机。David Egts 告诉你[如何开始使用这个可编程的迷你电脑](/article-8308-1.html)。 ### 日常的计算机使用 开源并不仅针对技术专家,更多的普通人用它来做日常工作,而且更加效率。这里有三篇文章,可以使我们这些笨手笨脚的人(你可能不是)做任何事情变得优雅。 当你想到微博客的时候,你可能会想到 Twitter。但是 Twitter 的问题很多。[Mastodon](https://joinmastodon.org/) 是 Twitter 的开放的替代方案,它在 2016 年首次亮相。从此, Mastodon 就获得相当大的用户基数。Seth Kenlon 说明[如何加入和使用 Mastodon](https://opensource.com/article/17/4/guide-to-mastodon),甚至告诉你如何在 Mastodon 和 Twitter 间交替使用。 你需要一点帮助来维持开支吗?你所需要的只是一个电子表格和正确的模板。我关于[要控制你的财政状况](/article-8831-1.html)的文章,向你展示了如何用 [LibreOffice Calc](https://www.libreoffice.org/discover/calc/) (或任何其他电子表格编辑器)创建一个简单而有吸引力的财务跟踪。 ImageMagick 是强大的图形处理工具。但是,很多人不经常使用。这意味着他们在最需要它们时忘记了命令。如果你也是这样,Greg Pittman 的 [ImageMagick 入门教程](/article-8851-1.html)能在你需要一些帮助时候能派上用场。 你有最喜欢的 2017 Opensource.com 发布的教程吗?请随意留言与社区分享。 --- via: <https://opensource.com/article/18/1/best-tutorials> 作者:[Scott Nesbitt](https://opensource.com/users/scottnesbitt) 译者:[zjon](https://github.com/zjon) 校对:[wxy](https://github.com/wxy) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
200
OK
A well-written tutorial is a great supplement to any software's official documentation. It can also be an effective alternative if that official documentation is poorly written, incomplete, or non-existent. In 2017, Opensource.com published a number of excellent tutorials on a variety of topics. Those tutorials weren't just for experts. We aimed them at users of all levels of skill and experience. Let's take a look at the best of those tutorials. ## It's all about the code For many, their first foray into open source involved contributing code to one project or another. Where do you go to learn to code or program? The following two articles are great starting points. While not a tutorial in the strictest sense of the word, VM Brasseur's [How to get started learning to program](https://opensource.com/article/17/4/how-get-started-learning-program) is a good starting point for the neophyte coder. It doesn't merely point out some excellent resources that will help you get started, but also offers important advice about understanding your learning style and how to pick a language. If you've logged a more than a few hours in an [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) or a text editor, you'll probably want to learn a bit more about different approaches to coding. Fraser Tweedale's [Introduction to functional programming](https://opensource.com/article/17/4/introduction-functional-programming) does a fine job of introducing a paradigm that you can apply to many widely used programming languages. ## Going Linux Linux is arguably the poster child of open source. It runs a good chunk of the web and powers the world's top supercomputers. And it gives anyone an alternative to proprietary operating systems on their desktops. If you're interested in diving deeper into Linux, here are a trio of tutorials for you. Jason Baker looks at [setting the Linux $PATH variable](https://opensource.com/article/17/6/set-path-linux). He guides you through this "important skill for any beginning Linux user," which enables you to point the system to directories containing programs and scripts. Embrace your inner techie with David Both's guide to [building a DNS name server](https://opensource.com/article/17/4/build-your-own-name-server). He documents, in considerable detail, how to set up and run the server, including what configuration files to edit and how to edit them. Want to go a bit more retro in your computing? Jim Hall shows you how to [run DOS programs in Linux](https://opensource.com/article/17/10/run-dos-applications-linux) using [FreeDOS](http://www.freedos.org/) and [QEMU](https://www.qemu.org). Hall's article focuses on running DOS productivity tools, but it's not all serious—he talks about running his favorite DOS games, too. ## Three slices of Pi It's no secret that inexpensive single-board computers have made hardware hacking fun again. Not only that, but they've made it more accessible to more people, regardless of their age or their level of technical proficiency. The [Raspberry Pi](https://en.wikipedia.org/wiki/Raspberry_Pi) is probably the most widely used single-board computer out there. Ben Nuttall walks us through how to install and set up [a Postgres database on a Raspberry Pi](https://opensource.com/article/17/10/set-postgres-database-your-raspberry-pi). From there, you're ready to use it in whatever project you have in mind. If your tastes include both the literary and technical, you might be interested in Don Watkins' [How to turn a Raspberry Pi into an eBook server](https://opensource.com/article/17/6/raspberrypi-ebook-server). With a little work and a copy of the [Calibre eBook management software](https://calibre-ebook.com/), you'll be able to get to your favorite eBooks anywhere you are. Raspberry isn't the only flavor of Pi out there. There's also the [Orange Pi Pc Plus](http://www.orangepi.org/), an open-source single-board computer. David Egts looks at [getting started with this hackable mini-computer](https://opensource.com/article/17/1/how-to-orange-pi). ## Day-to-day computing Open source isn't just for techies. Mere mortals use it to do their daily work and be more productive. Here are a trio of articles for those of us who have 10 thumbs when it comes to anything technical (and for those who don't). When you think of microblogging, you probably think Twitter. But Twitter has more than its share of problems. [Mastodon](https://joinmastodon.org/) is an open alternative to Twitter that debuted in 2016. Since then, Mastodon has gained a sizeable base of users. Seth Kenlon explains [how to join and use Mastodon](https://opensource.com/article/17/4/guide-to-mastodon), and even shows you how to cross-post between Mastodon and Twitter. Do you need a little help staying on top of your expenses? All you need is a spreadsheet and the right template. My article on [getting control of your finances](https://opensource.com/article/17/8/budget-libreoffice-calc) shows you how to create a simple, attractive finance-tracking spreadsheet with [LibreOffice Calc](https://www.libreoffice.org/discover/calc/) (or any other spreadsheet editor). ImageMagick is a powerful tool for manipulating graphics. It's one, though, that many people don't use as often as they should. That means they forget the commands just when they need them the most. If that's you, then keep Greg Pittman's [introductory tutorial to ImageMagick](https://opensource.com/article/17/8/imagemagick) handy for those times you need some help. Do you have a favorite tutorial published by Opensource.com in 2017? Feel free to share it with the community by leaving a comment. ## Comments are closed.