Ubuntu下的计划任务 — cron的基本知识

正文

cron是一个Linux下的后台进程,用来定期的执行一些任务。因为我用的是Ubuntu,所以这篇文章中的所有命令也只能保证在Ubuntu下有效,但其他系统应该也差不多。

 

想要让cron执行你指定的任务,首先就要编辑crontab文件。crontab是一个文本文件,用来存放你要运行的命令。你可以以下命令

 

Shell代码
crontab -e

来打开你的用户所属的crontab文件。第一次用这个命令,会让你选择文本编辑器,我选的是vim。选定的编辑器也可以使用

 

Shell代码
select-editor

命令来更改。这点命令行中已经有足够的提示,就不多说了。

 

打开后的crontab文件类似这种样子:

 

Shell代码
# m h dom mon dow command
*/2 * * * * date >> ~/time.log

第二行是我为了测试写的一个定期任务,它的意思是,每隔两分钟就执行 date >> ~/time.log 命令(记录当前时间到time.log文件)。你可以把它加入你的crontab中,然后保存退出。

 

保存了crontab之后,我们还需要重启cron来应用这个计划任务。使用以下命令:

 

Shell代码
sudo service cron restart

下面稍微解释下crontab中每行的含义。crontab中的每一行代表一个定期执行的任务,分为6个部分。前5个部分表示何时执行命令,最后一个部分表示执行的命令。每个部分以空格分隔,除了最后一个部分(命令)可以在内部使用空格之外,其他部分都不能使用空格。前5个部分分别代表:分钟,小时,天,月,星期,每个部分的取值范围如下:

 

分钟 0 – 59

小时 0 – 23

天 1 – 31

月 1 – 12

星期 0 – 6 0表示星期天

 

除了这些固定值外,还可以配合星号(*),逗号(,),和斜线(/)来表示一些其他的含义:

 

星号 表示任意值,比如在小时部分填写 * 代表任意小时(每小时)

逗号 可以允许在一个部分中填写多个值,比如在分钟部分填写 1,3 表示一分钟或三分钟

斜线 一般配合 * 使用,代表每隔多长时间,比如在小时部分填写 */2 代表每隔两分钟。所以 */1 和 * 没有区别

*/2 可以看成是能被2整除的任意值。

 

以下是一些例子(省略了命令部分):

 

Crontab代码
* * * * * # 每隔一分钟执行一次任务
0 * * * * # 每小时的0点执行一次任务,比如6:00,10:00
6,10 * 2 * * # 每个月2号,每小时的6分和10分执行一次任务
*/3,*/5 * * * * # 每隔3分钟或5分钟执行一次任务,比如10:03,10:05,10:06

以上就是在cron中加入计划任务的基本知识。因为cron中的任务基本就是执行命令行,所以当然也会有权限问题。以上例子中的任务就是以你当前登录用户的权限执行的,如果你需要以root用户执行某个任务,可以在crontab前加上sudo。

 

Shell代码
sudo crontab -e

顺带一提,crontab文件对每个用户都是不同的,所以刚才设置的定期看时间的任务,在这里是看不到的。因为我们没有为root用户增加这样的计划任务。

 

再顺带一提,不喜欢命令行的童鞋可以去 Ubuntu软件中心 下一个 计划任务 程序。在软件中心中搜索 schedule 就可以搜到。它是一个GUI的程序,做的还蛮傻瓜化的。不过好像没办法设置成使用root用户运行任务。而且,对于要ssl到服务器上进行操作的童鞋来说,命令行还是最好(唯一)的工具。

 

因为我目前就用到这些知识,所以对cron也没有更多了解。想了解Ubuntu下的cron的童鞋,可以去看看Ubuntu官方的这篇 CronHowTo ,个人觉得讲的还是蛮详细的。

 

什么是Cron?

Cron是一个[守护程序]用于在指定的时间内执行行程类的任务,每一个用户都有一个 crontab 文件,来允许他们指定需要执行的内容和时间,此外,系统也有一个 crontab ,用来允许像交替日志和更新本地数据这样有规则的任务。
[编辑]使用 Cron

使用 Cron, 只要在 crontab 文件中添加一些项目,一个 crontab 项目详细说明执行的过程和时间,如:

5 3 * * * /usr/bin/apt-get update
在crontab 项目里的第一个部分描述了执行任务的时间。它用空格分开成五个区域,每个只能用数字、“*”、或适当的字。这个区域依次说明 “分”,“时”,“每月几日”、“月”、“每周星期几”,月和星期可以用缩写,如 “jan”代替“January” 、”thu” 代替”Thursday”。

上面的例子将在每天的03:05执行“/usr/bin/apt-get update”(cron采用24小时制)

你要让cron在所有工作日中每5分钟显示干扰的消息,(上午9点到下午5点)请用

*/5 9-17 * * mon,tue,wed,thur,fri wall “Are we there yet?”
或者想使你想起一个生日,在每年正月十日的上午9点,用:

0 9 10 jan * echo “It’s your mother’s birthday today!” > ~/readme
查看 crontab 文件当今的内容,输入:

crontab -l
要使用系统环境默认的编辑器(一般是指vim)更改这个文件,输入: To edit the file, with the editor specified in your environment (which defaults to vim – :q! is the command to escape without saving if you get stuck and need to read up on it or change your editor), use:

crontab -e
ps: vim中使用命令“:q!”退出且不保存文件。如果你在编辑这个文件时遇到了麻烦需要重新读取这个文件或是想换一个编辑器,就可以输入这个命令。

当你关闭编辑器后,新的 crontab 文件将被安装上。用 crontab 命令编辑的文件保存在/var/spool/cron/crontabs
[编辑]更多的内容

下面的命令保存 crontab 文件需要你的用户有要许可。如果你想要定期运行更大权限的命令, 请设置根 crontab 文件:

sudo crontab -e
取决于要运行的命令,你可能需要扩大根用户的 PATH 变量,请在他们的 crontab 文件的顶部输入下面的内容:

PATH=/usr/sbin:/usr/bin:/sbin:/bin
你最好先测试一下你将要采用的cron任务。一种办法是是设定任务在几分钟内运行,这就提前可以知道任务的结果。你也可以写一些命令到脚本里,以便记录其成功或失败,如下

echo “Nightly Backup Successful: $(date)” >> /tmp/mybackup.log
For more information, see the man pages for cron and crontab (man is detailed on the BasicCommands page). If your machine is regularly switched off, you may also be interest in at (part of the Ubuntu base install) and anacron (found in the Universe repository) that provide other approaches to scheduled tasks. For example, anacron offers simple system-wide directories for running commands hourly, daily, weekly, and monthly. Scripts to be executed in said times can be placed in /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/. All scripts in each directory are run as root, and a specific order to running the scripts can be specified by prefixing the scripts’ file names with numbers (see the man page for run-parts for more details).

FIXME 翻译以上部分和以下部分
[编辑]提示

crontab -e 使用编辑器环境的可变性。通过恰当的设置,使编辑器具有你自己的风格。你想要设置基于你自己的编辑器。ba shrc 因为许多命令使用可变性,让我们设置nano 一个使用简单的编辑器。

export EDITOR=nano
也有你能够为系统广义cron工作编辑的文件。大部分常见的文件位于“/etc/crontab“,而且这些文件的语法跟普通的aroncab的文件有细微的不同。

minute(s) hour(s) day(s)_of_month month(s) day(s)_of_week user command
It is recommended, however, that you try to avoid using /etc/crontab unless you need the flexibility offered by it, or if you’d like to create your own simplified anacron-like system using run-parts for example. For all cron jobs that you want to have run under your own user account, you should stick with using crontab -e to edit your local cron jobs rather than editting the system-wide /etc/crontab.

斗铠300-303

孟聚身躯微微一震:自己与叶剑心的约定是秘密,自己一直守口如瓶的,没对任何人说过,北府怎么就知道了?这些特务们也太神通广大了吧?

孟聚低头喝了口茶,这才答道:“易先生,你这是从何说起呢?我跟叶家联姻?你们是从哪得到的消息?”

尽管孟聚装得十分自然,但易先生这种北府的老鹰侯,眼睛利得能拿去当菜刀用。那一瞬间,孟聚脸上的惊愕表情已是落到他眼中了,他心中立即便是有了底:十有**,上头传来的消息该是真的了。

他深深注视孟聚,良久,他叹气道:“怎么会是这样的呢?先是叶迦南,现在又来了个叶梓君。。。天下那么多的好女子,孟聚你怎么就一直跟叶家纠缠不清呢?不妨告诉你,消息是北府断事官萧何我大人亲口跟我说的。”

孟聚马上又问:“那萧大人又是从何而知这消息的呢?”

“呃?孟大人您今年贵庚了?”

易先生用一种看白痴的眼神看着孟聚,孟聚立即意识到,自己问了个蠢问题:北府的消息来源,自然是卧底弄来的。这种消息渠道,那肯定是机密中的机密了,怎可能轻易泄露给自己?

他自嘲地笑笑:“是我笨了。。。那,易先生,北府派你过来,就是为了让你问我这个事的吗?”

易先生摇头道:“上头派我来来联络你,是想查证下这个消息是否真的。如果是真的话,朝廷希望,你能以大局为重。取消与叶家的婚约。”

“为什么?我跟叶家联姻,又碍着朝廷什么事了?”

“孟聚啊,咱们也是老相识了,咱们就不说多余的废话了,你也别跟我装傻。你是我们北府的人。又是北边的大军阀,你跟叶家那帮国贼联了姻,这让朝廷怎么看你?咱们也不说那些虚的,你将来回归朝廷,以你今日的身份和实力。朝廷怎么也得封你个‘都督六镇军事’,但你跟这帮鲜卑的余孽们纠缠不清,朝廷怎能放心把北边防务的重任交给你?”

孟聚眨巴着眼睛,眼神显得天真又无辜,他说:“这是我的私人事务。。。朝廷没必要多事吧?”

“胡说八道,朝廷重臣的婚姻,怎会是私人事务?世家大族的联姻。历来是朝廷关注的重中之重。”

“老易,从什么时候起,鹰扬校尉这种一抓一箩筐的从五品武官——也能算朝廷重臣了?”

易先生被梗得说不出话来,他喊道:“我不跟你嚼那舌头。反正,叶家是国贼。你不能跟他们联姻——这是命令!”

“命令?老易啊,我现在严重怀疑你假传朝廷旨意了。”

“胡说八道,咱什么时候假传过朝廷旨令了?”

孟聚似笑非笑望着他,也不说话。

易先生有些狼狈:“——呃,上次你赞助我的银子的,那次不算——呃。再上次那次也不算——你不要这样瞪着我,上上上次那次,让你去天香楼找美女陪我过夜。确实是朝廷的命令。。。呃,北府让你保护我嘛,我选了菲菲姑娘当晚间护卫——反正也没违背朝廷旨意不是?我哪有假传朝廷旨意了?”

“好吧,老易,你说没有就没有吧。若是朝廷的意思,让朝廷或者北府给我发个文来。我再考虑考虑。”

易先生气得跳了起来:“孟聚,你是故意要气我不是?这种事。怎么可能摆到明面上说?朝廷要阻止臣属结婚,这事有失体面,不可能摆开来说,只能让你自己领会就是了。”

孟聚把头摇得飞快:“老易,我们别搞什么领会了,大家摆明了说:若是我娶了叶家女,朝廷打算怎样?”

易先生一愣:“我不知道。但你跟国贼世家联姻,肯定会失去陛下和朝廷的信任和倚重,将来你重归我朝之后——圣恩如海,圣威难测,你这种外系的镇边大将,若是没了陛下的信任,将来如何下场,那委实难说了。

孟聚,大丈夫何患无妻?以你今日地位,无论垂意哪家的名门淑女,有何不得?你年青权重,只要你流露出愿意结亲之意,我朝的公侯名门世家想来定有不少人愿意与你结缘的。哪怕便是我朝皇室公主,你也不是没有可能啊!

天下好女子何其之多,孟聚你又何必非跟叶家这个臭名昭著的国贼家族攀连在一起呢?

孟聚啊,你也得为朝廷想想啊。将来你回归我朝后,朝廷要拿叶家怎么办?对这种满手血腥的汉奸国贼世家,若不明正典刑严加惩治,则朝廷无法对天下仁人志士交代,所以,对叶家,朝廷势必有个清算;但若惩治太过的话,你那时也是朝廷重将了,事情牵连到你。。。朝廷也很是为难啊,你就当是体谅朝廷吧?

只要你回绝了叶家,你的婚事包在我身上——你不要用这种眼神看着我,你信不过我,还信不过萧大人吗?萧大人亲口说的,到时候你看中了那家的千金,他愿为你亲自上门说媒去,他拍胸膛保证的!

孟聚,你多年效忠北府,咱们都是自己人。我也好,萧大人也好,大伙都是关心你,不想你将来落个没下场啊。”

孟聚不得不承认,易先生的劝告入情入理,确实很有说服力。只是很可惜,他不明白自己对叶迦南的那份感情,那是不会被任何事情动摇的。易先生一番苦口婆心的劝导,结果换来的只是孟聚的“嗯嗯哦哦”的敷衍。

眼见劝说半天,孟聚半点不肯松口,易先生也灰了心,他望着孟聚,神情有点黯然。

接触易先生的目光,孟聚一愣:在易先生的眼神中,他看不到多少愤怒,倒是有一种让孟聚说不清道不明的东西——是落寞?是失望?是黯然?还是解脱?

易先生慢吞吞地说:“是啊,孟聚,你确实要好好想想了。”

易先生走了,走的时候,他显得苍老了很多。临走时,他没再说什么,但他的眼神已深深刺痛了孟聚——对易先生来说,自己一手培养起来、视之如子的部下,自己眼看着长大的孩子,自己却失去了对他的影响力——此时此刻,他的心情又是如何的呢?

想到这里,孟聚怅然若失。

人的世界太过脆弱,很多我们本来以为是天经地义的事情,会永远一直保持下去的,却常常会很突然地失去,然后,我们所熟悉的世界会忽然间变得面目全非了。

孟聚疲惫地揉了一把脸,感觉心神俱疲。他站到窗前,看着窗外的蓝天久久出神,眼前的浮现的,却是易先生临走时的眼神——孟聚知道,继叶迦南、王柱和慕容毅之后,自己又失去了一位可以信任的朋友了。

孟聚发了一阵呆,忽然想到一件事,他陡然怒气勃发,转身就向外走。侍从快步追上来,帮着孟聚披上了斗篷,问道:“大人,您要去哪?如果要出城的话,要通知卫队的。”

“去前街的陆府,找柳空琴去!”

叶剑心嘴巴不牢,向南朝泄露了机密,让易先生气冲冲地跑来向孟聚兴师问罪,这件事弄得孟聚很是不爽,一怒之下,他也跟着照样学,向叶家也来个兴师问罪。

出门走过了半条街,被那凉飕飕的寒风一吹,孟聚渐渐地冷静下来了。他的脚步越走越慢,最后,在陆府的门口,他停下了脚步:自己这样气势汹汹地跑去责问叶家,万一叶家来个反问:“南朝那边的事,孟大都督您又是怎么知道的?”那时候,自己又怎样回答呢?

让叶家知道自己跟南朝有联系秘密,孟聚倒不是很在意。现在这风雨飘摇的年头,为留一条后路,哪个大魏的权贵不在暗通南朝。自己是大魏北方的实力军阀,又是正经的汉人,南朝不派人来跟自己联络,这反倒是不正常了——但问题是,自己这样冲叶家发一通火,对事情有什么帮助吗?

毫无意义。

站在陆府前的树荫下,孟聚呆呆站了好久。最后,他沮丧地摇摇头,回转了身,侍卫惊讶地看着他:“大人,您不去找柳大师了?”

“不去了,我们马上回府去!”

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

雨季过去了,天佑二年的夏天,来得特别迟缓。在那渐渐炙热起来的阳光里,人们逐渐感觉到了战争的气息,南方的平叛战事正在逐渐北移。

每日每夜,都有大批衣衫褴褛、疲惫不堪的溃兵途经楚南府。他们都是来自边军各部的逃兵,有的甚至还是军官。这些具有先见之明的人们已经预见到了,边军掀起的这场叛乱已不可能成功。为了逃避朝廷和金吾卫的追杀,他们正在日夜兼程地向北逃难。 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
虽然被东平军拦截的时候,这些衣衫褴褛、面黄肌瘦的逃兵显得非常可怜,他们向着盘查的东平军连连磕头求饶,显得人畜无害、很可怜的样子,但东平军并没有因此就放松了对他们的警惕。

孟聚深知这点:边军曾是大魏朝最强大的战斗部队。在这支狼虎之师中磨砺出来,这些久经战事、已经习惯杀戮的战士,他们除了杀人以外再无所长。这些人,心志坚定又心狠手辣,现在,他们已经失去了军纪和长官的束缚,一旦让这帮人成群结队地窜入民间,势必蜕化成土匪和山贼,这些精于厮杀又一无所有的人会比任何匪帮更凶残、更嗜血,这是对东平军辖区治安的巨大威胁。

孟聚发布警告,命令冀州、中山、朔州、定州等地驻军和官府都要全力动员,全力拦截、收编那些从前线溃逃回来的边军溃兵,绝不能让他们窜入民间。尤其是冀州,这个正在军屯的新州兵力薄弱,孟聚已下令从左路军中抽调李赤眉所部驰援冀州,镇压和安定地方。

当然,作为拦截溃兵的第一道防线,孟聚亲自坐镇的楚南府承担了最大的重任。在各处道口、关卡和要害地段,东平军设立了大量的检查站和盘查哨卡,派遣武装铠斗士坐镇盘查。除此以外,还派出了大批斥候队巡查荒原野林,遇到路过的行人便上前盘查问询。凡是操北疆口音的,一律当场扣下。

大部分时候,被盘查的边军溃兵都会听命服从,放下武器接受东平军的指挥。但也有不少时候,他们会逃跑、抗拒甚至是攻击盘查人员。随着战线逐渐北移,逃兵的数量也越来越多,规模越来越大,甚至出现了由军官带领的成百上千的大规模逃兵队伍。

对于敢于负隅顽抗的溃兵,东平军的态度是十分严厉的。孟聚颁布命令。凡是敢于顽抗的溃兵。一律予以格杀。于是战斗随之爆发,白天黑夜,在荒野或者道边,拦截的东平兵马与急于逃命的边军逃兵常常展开不期而遇的厮杀。逃兵们为生存而战斗,但东平军却是拥有组织和装备上的优势,每个搜查队和盘查岗都配备有着装的铠斗士,在对上那些连兵器都配不齐的逃兵们,东平军总是获胜的。

天佑二年的五月初,在孟聚翘首以待的期待中。押运物资的舒州都督张全终于抵达了济州楚南府。听到这消息,最高兴的人不是孟聚,而是那位一直被软禁的钦差马贵——他终于可以从被抓去祭旗的噩梦中逃脱中了。

对不远千里给自己送来好处的张全都督,孟聚还是心存谢意的。他亲自出城迎接,双方见过礼后,还没来得及互致寒暄和问候呢,张全都督就直截告诉孟聚:“大都督,有个坏消息要向您禀报:末将在道上得到消息。叛军人马正朝济州楚南而来。大都督还请早作准备了。”

这些日子,驻扎在楚南的东平军无日无夜不在清剿过路的叛军逃兵,交战每日都有,孟聚打仗都打得麻木了。听到张全都督示警,孟聚也不甚在意,笑道:“有劳张都督牵挂了。这事我知道了。不过些许几个毛贼,我们也不必太过在意。张都督远道过来辛苦了,请进城安心歇息就好了。”

听孟聚这么说。张全露出诧异的神情。他怪异地望着孟聚好一阵,良久,他点点头,说道:“久闻大都督武勇过人,乃我大魏第一勇将,果然名不虚传。原来伪皇叔拓跋所率领的五万叛军精锐,在大都督眼里不过几个区区毛贼而已。此等豪迈气魄,末将不得不甘拜下风了。”

孟聚:“。。。。。。”

边军的动向,张全了解的也不多,他只在路上遭遇一支边军的小部队,交战后俘虏了对方的几个军官,拷问后才知道了消息:皇叔拓跋雄率领着边军主力北上,直奔济州而来。目前所知的边军主力兵马约有五万。现在,边军的主力距离济州约莫还有四百多里。

不知是否有什么顾虑,或者是害怕被直扑而来的边军主力给堵在楚南府里了,张全在楚南府只呆了一天,把押运的物资跟孟聚交接完就匆匆走人了。孟聚也没心思挽留他了,他现在忙着全力备战,向四处乡野征集粮秣,派遣斥候,示警各方。

现在,边军的目标已经很明显了。他们向是济州拼死一搏,就是要打开归家之路。

兵法有云,归师勿遏——孟聚很清楚,那些急于逃生的军队,总是能爆发出比平常更强大的战力。虽然以前屡胜边军,但对于边军的这次濒死一击,孟聚丝毫不敢掉以轻心。

他一边在楚南府本地征集了三千民壮担当辅兵,一边向后方颁发军令,命令王北星的西路军、易小刀的东路军迅速派出有力部队向孟聚靠拢——东西两路兵马已经完成了预定的征伐任务,但要赶到济州估计起码要一个月,但孟聚估计,这次的济州战役不会很快结束的。

三天后,东平军向南边派出的斥候终于回头了。他们不但证实了张全都督的警告,还带回来了更确切的消息:边军残部的主力兵马确实正朝济州直奔而来,兵力约莫在四万到五万之间,斗铠数目不详。而尾随拓跋雄其后的,则是由皇帝慕容破统率的金吾卫主力兵马,兵马多达十三万之多。

根据斥候观察,尽管是追逐战,但金吾卫追得并不是十分紧,两边始终保持着两天的行程——那种行军速度,与其说是追赶,倒不如说是相送。

楚南府的知府衙门,现在已成了战时的指挥中心。东平军的高级军官会聚于此,听取斥候报告。听到这通报,王虎、齐鹏等人顿时嚷声大作:“慕容家心思歹毒,他们想引祸水东流!”

“他们就是想把边军给逼过来,跟我们来个你死我活!”

“五万边军精锐啊!他们一人一口都要把我们咬死了!”

“慕容家这帮王八蛋,他们就是要借刀杀人,然后来个渔翁得利啊!”

将军们争先恐后地说着,七嘴八舌地嚷成了一片,结果是谁都听不清谁的话。

孟聚坐在座位上低头喝茶,比起义愤填膺的部下,他显得平静了很多,甚至还有余暇手托着下巴观察着众人的表情——倘若愤怒和谩骂有用的话,大家还用练斗铠干什么?而且,他的心态也很平衡:出来混,总是要还的。自己趁火打劫了慕容家那么多次,他们还以一报,这倒也是正常的。

看着众将嚷得差不多了,孟聚举手示意,立即,将军们都停了口,所有人的目光都集中在孟聚身上,屋子里静得鸦雀无声。

孟聚环视众人一圈,最后却是望向了文先生:“先生,我军遭遇强敌,面临极大危机。不知先生有何可以教我呢?”

这么多的文臣武将聚集,孟聚却是第一个就点了文先生的名,这份看重令在场众将都是诧异。文先生站起身,躬身道:“主公在上,在座群英荟萃,众贤云集,学生一点浅薄之见,委实登不得大雅之堂,怕是让主公和群贤见笑了。”

“先生但说无妨,不必顾虑。”

“如此,学生就莽撞了,便当是抛砖引玉吧。学生看来,拓跋皇叔大兵压境,我军的应对之策无非‘战、避、和’三策罢了。”

孟聚沉思片刻,问道:“所谓‘战’策之意,吾已明了,无非兵来将挡罢了。但先生所谓‘避’、‘和’二策又是何意呢?”

“皇叔匆匆北上,无非是想重据北方罢了。主公骁勇善战之名,举世皆知,倘若可能,拓跋皇叔亦不愿与主公死拼的。只要主公让开一条路,让皇叔重返北上,料来朝廷也不会眼看着皇叔在北方苟延残喘重新坐大吧?”

“放皇叔进冀州?”

孟聚微微蹙眉,他起身,缓缓走到窗前。此时,正值落日西下,整个庭院和府邸,都被深沉的暮色所笼罩。落日最后的红霞,把厅堂照得一片炫红。孟聚从窗前转过身来,他的半边脸也是赤红的,犹如刚从血泊中浸泡过一般。

孟聚低沉地说:“此事,断无可能。”

冀州以北都是东平军的辖区,倘若放拓跋雄进去,着急的人就不是朝廷而是孟聚了。

拓跋雄要重新崛起,他势必要从孟聚手上夺回地盘。坐山观虎斗的计谋又不是只有孟聚会玩,那时候,朝廷会很快活地坐在洛京看孟聚跟拓跋雄打个头破血流的。

孟聚环视众将,沉声说:“楚南府是冀州的门户,我军将坚守此地,绝不后退半步。无论是何方之敌,我们绝不允许他们踏足冀州。”

众将轰然喝彩:“大都督威武,就该如此!”

孟聚微微颌首,他转头望向文先生:“文先生,回避之策,不必再说了。我军绝不后退,也是无路可退了,还是请说说‘战’与‘和’两策吧?”

文先生神情凝重:“主公明鉴。皇叔率叛军直冲在前,朝廷大军尾随在后——我军之敌,并非仅仅只有皇叔的叛军而已。。。倘若我军全力与叛军交战,露出薄弱侧翼的话,朝廷会不会对我军下手,委实难以预料。

所以,此战,我军必以‘战’、‘和’二策并用,缺一不可。我军要与叛军战,又不能全力死战;又要与叛军‘和’,但又不能真‘和’。

诸位需知,‘战’为‘和’之本,古人有云,非战不能言和;‘和’又乃‘战’之用。。。”

听文先生在那文绉绉地解释‘战’与‘和’两个字拗口死了,说了半天还说不到重点,孟聚听得不耐烦,打断他说:“我猜先生的意思,是咱们对拓跋雄来个一手硬,一手软?”

“一手硬,一手软?”文先生愣了下,然后,他由衷地赞叹道:“主公所言,比学生更为精妙简练。叛军狼奔兔逐,便如那决堤之洪水。他们欲夺路而逃,必然要选择包围圈中最薄弱的一面。咱们必先得显示战力,让叛军知道,他们在我们这边占不到便宜。然后,咱们再对叛军怀柔,因势利导,使之不再为我所害。。。”

在后半段,文先生说得含含糊糊,就说了个因势利导,但这次,孟聚和众将都明白他的意思了。

王虎咧嘴笑道:“先生方才说了那么多,又是战又是和什么的,咱是一头雾水听得不明白。还是镇督厉害,一句话就说明白了,一手硬一手软嘛!无非就是咱们先把拓跋雄那龟孙揍一顿,让他知道咱们不好惹,然后再哄他掉头去找朝廷麻烦就是了。多简单的事,文先生你扯那么多干嘛啊!”

众将轰笑,文先生也跟着笑。半点没有被取笑的不好意思。他向四面拱手行礼道:“惭愧,惭愧。酸腐书生,确实比不得诸位将军豪气。”

日子一天天过去,楚南府天天整顿兵马备战,战争气氛日益浓厚。

五月二十一日,消息传来,一部边军兵马进入济州,正沿着驿道一路北上。

孟聚立即召集众将。早已做过动员了,济州一地。已被孟聚自说自话地当成了自家领地,听闻边军入寇,众人再无别话,只有一个字:“打!”

王虎、齐鹏、徐浩杰等诸人多次跟随孟聚南征北战,多次征战中跟孟聚配合得十分默契,孟聚指挥起他们来也是得心应手,肯定要全部带走的。只是原先的中军官江海被留在冀州屯田了,一时也找不到能统筹全局的中军指挥。孟聚只能自领中军。坐镇主营了,这让一向喜欢冲杀在前的孟聚大感不爽。他曾一度考虑过,从冀州把江海给调回来担当中军指挥,但被文先生劝阻,再加上时间上也确实来不及了,此事只能作罢。

次日清晨,低沉的号角呜鸣声中,东平军出战了。阳光丽日下。兵马浩浩荡荡地出城,沿着官道一路南下。

队伍中旌旗如海,队列整齐,盔甲鲜亮,人欢马跃。整路大军行进,犹如那江河前涌,铁流奔腾。将士们兴高采烈。雄壮的战歌从队伍前头唱到了队尾。队列中,不时响起了军官整饬的喝令声、马蹄声,士兵们的喝嚷声,轰然如雷。

此次出战兵力共计四旅兵马,总兵力约莫一万三千余人,其中铠斗士一千一百名,骑兵五千三百余人,是中路军的主力所在。虽然历经长途跋涉,但在楚南府休整了一个多月,好吃好喝地休养着,出征将士疲惫尽去,精神抖擞。

看到麾下士气高昂,孟聚也是深感振奋:在此乱世,手握一路强兵,自己还是大有可为的。这番意气风发,可是当年的六镇边陲小军官能想象的?

大军从楚南府出发的第三天,进抵了济州的安平府。黄昏时候,兵马刚到城边,前方斥候就来通报,说是发现了边军的痕迹,约莫五千多边军兵马正在急速朝安平府方向前进着,距离城池已不到十里了。

听到报告,孟聚并没有在意。相距不到十里了,按常理来说,正如自己发现对方一样,对方也该发现自己了,东平军一路沿官道前行,并没有刻意隐藏自己的旗号。自己也算薄有武名了,等对方知道自己在此,他们肯定就会停步了。

但事情往往就是这样出人预料,夜里子时,孟聚得到消息,说是那路五千人的边军人马连夜急行军,已经赶到了安平府的城郊。现在,他们正忙着在城外安营扎寨呢!

在城头看着城外的那片营火,孟聚迷惑不解:“他们要找死吗?”

他怎么也想不通,只有区区五千边军而已,既然明知自己在此,居然真的敢急行军跑来,然后几乎是毫无戒备地在自己眼皮下安营扎寨。

碰上自己,没有三倍以上的兵力,边军居然敢来?孟聚还真不知该评价对方是勇气可嘉还是不知死活好了。

望着城外的那片营火,孟聚幽幽地说:“看来,咱们真是太久没打仗了,边军已经忘记咱们的名头了——哪位将军愿意出城与敌军一战?”他的瞳孔反映着远处的火光,在黑暗中灼灼发亮。

将军们环在孟聚身边,同样脸色阴沉。王虎第一个嚷道:“镇督,末将愿率本部兵马,今晚就出城袭营。”

徐浩杰、齐鹏等部将也是不甘落伍,纷纷出声求战,孟聚正要答应,但这时文先生出声道:“主公莫急,敌人这样做,很像要诱我军出战。主公,能确定周边没有边军的伏兵吗?”

徐浩杰代孟聚做了回答:“军师,我部斥候已经查探过了,周边二十里以内,再无边军的大部兵马。他们的主力离他们还远着呢,足足三十里开外。”

文先生蹙眉苦思,最后摇头:“主公,恕学生浅薄,实在看不懂他们想干什么。”

孟聚也不搞不懂边军在干什么,不过他知道,战争中常常会出现很多匪夷所思、不合常理的荒诞事情来,这次自己估计是又碰上一桩了。

“想不明白,那就不必去想了。既然皇叔送上门的这盘菜,那我们就却之不恭了!传令,今晚我们就出城袭营去,趁着敌人的主力没到,今晚就把他们的前锋吃掉了。今晚我亲自统兵出击,其余兵马。。。”

“大人,那边有情况!敌营那边好像有些动静!”

敌人的阵头点着火把,火光映照下,众人都能把情景看得清楚:从敌人营中奔出了一小队骑兵,正朝城头直奔而来。夜色明朗,星光灿烂,那小队的骑兵奔到离城头百步开外就停下了脚步,只有一名军官模样的骑手越众而出,一直奔到了城头前。在众人瞩目之下,他冲着城头喊话道:“东平军的弟兄们,我是使者,有要事跟你们的长官商议。”

城头众将面面相觑,孟聚吩咐道:“放下吊篮,拉他上来。”

很快,这名边军军官被带了过来。侍卫搜查了他的身体,发现并无武器,于是放了他进来。猎猎飞舞的火把光亮中,众人都把他看得清楚,这是一个四十出头的中年武官,穿着一身薄甲,眉目端正,气色很好,只是神情有些惊惶。

他进来,见到众位将军众星环月般围着孟聚,立即知道眼前的肯定是东平军的要员了。他躬身行了个礼:“诸位将军,末将有礼了。”

“不必客气。阁下深夜前来,是何用意,要跟我们下战书的吗?”

“战书?”那军官脸色一变,他急切地说:“不敢,孟大都督在此,他的虎威,吾等不敢冒犯。末将求见大都督阁下本人,是有十万火急的要事与大都督本人商议,不知诸位大人能否通报一声?”

“阁下何人,有何要事求见大都督?”

军官犹豫了一下,最后,像是下了很大的决心,他说:“末将是沃野边军雷霆旅的旅帅史文庭,有要事求见大都督本人。还请诸位将军行个方便,帮忙向大帅通报一声。”

“咦!”众人齐齐发出了惊叹声。两军对峙,大战在即,这时候互派使者并不是很稀奇的事,但把旅帅级别的高级将领当做使者派到敌营去,这种事还真是闻所未闻。

“我就是孟聚。史旅帅,你有何要事,在这里便说了吧。”

听到眼前的将军自承是孟聚,史文庭明显地松了口气。他单膝跪倒,说道:“参见大都督。方才一见,末将便觉得大都督英武逼人,气度非凡,末将还想着东平军名将如云,难怪能连战告捷呢,没想到却是大都督本人——难怪了,大都督号称天下第一猛将,盛名之下果然无虚,此等英武气概,怕是天下也找不到第二个了。”

“史帅过奖了。将军深夜到访,想来定是有要事吧?有事就直说了吧。”

听出了孟聚话中的不耐之意,史文庭也不敢再啰嗦,他道:“是,末将就直言了:末将受军中袍泽委托,前来向大都督请降。”

孟聚一愣,他还以为自己听错了:“你是要——请降?”

史文庭摘下了头上的头盔,双膝跪倒,匍匐在地:“是。罪将当年一时糊涂,被国贼拓跋雄蛊惑了,跟着他一同举兵违抗朝廷。如今罪将等幡然醒悟,深感罪孽深重,愿率麾下兵马反正,归降于大都督麾下,恳求大都督能宽恕末将等往昔的罪过,给末将等一条出路。罪将愿忠心耿耿效忠大都督,为大都督效犬马之劳。”

史文庭连连磕头,额头撞上城墙的地砖发出“砰砰”的声音。当他抬起头时候,众人都是看得呆了:这位边军将领额头上已是青肿一片,眼中泪水流淌,神情悲戚。

孟聚茫然:自己不是没招降过敌人,但以前几次招降,自己计谋出尽,苦口婆心地劝说,表达诚意,哪次不是大费工夫?但现在,连谈判都不用,敌人刚见面就跪下来哭喊着求自己受降,这架势,像是自己只要开口说个“好”字事情就成了——好事得来得太轻易,孟聚倒有点不敢相信了。

“快扶史将军起来——将军莫急,我们慢慢说。将军弃暗投明,我们是欢迎的,只要你真有诚意,事情总能谈妥的。”

“罪将归降,绝对是诚心诚意的,大都督一定要相信啊!”

史文庭猛然跪倒,又是“通通通”磕了几个响头,那“通通通”的声音让孟聚听着都觉得头皮发麻——这家伙该不会觉得只要磕头声音够响就证明诚意足够了吧?

被这个二愣子旅帅搞得手足无措,孟聚退后一步,示意文先生上前问话。文先生干咳一声,站前一步:“史将军深明大义。弃暗投明,这很好。但不知将军此次归降,打算统带多少兵马过来呢?”

史旅帅磕头磕得头晕目眩,站立不稳,被搀扶着在石阶上坐下。他额头上鲜血直流,说话却还是口齿清晰:“末将此次归降,末将自家的雷霆旅自然是要过来的,雷霆旅现在的兵马约莫还有两千出头——但不止末将自己的兵马,军中还有不少弟兄也很仰慕大都督。托末将一同向大都督请降的。”

“哦?其他将军也有此意吗?”

“是,军中托我来问话的旅帅就有七、八个——这趟是因为我担当了先锋,大家都托我来跟大都督联系。”

“史将军,你说的大家是指谁呢?”

“前军的白虎旅旅帅洛小成、中军的熊霸旅旅帅熊罡、中军的猛禽旅旅帅高飞、后军的横山旅旅帅李澈,还有城下与我一同担当前锋的飞鹤旅旅帅黄旻。。。还有不少人,他们都托我向大都督递个话,想连人带兵马一同投过来。就是没得大都督的同意,他们不敢贸然行动。只要大都督您给罪将一个准信,末将传信回去,他们都会举义反正的。”

孟聚和文先生对视一眼,都看到了对方眼中的震惊。早先收容溃兵时候就知道边军士气低落军无斗志了。但不料竟到了这地步,旅帅一级的将领都纷纷想着叛变投敌。

但孟聚还有个疑问:这帮边军将领要投降的话,他们投靠慕容家那边不是更好吗?慕容家那边毕竟还有个正统朝廷的名分,无论地盘还是实力都远比自己雄厚得多,边军将领们为什么不肯叛去那边?

史文庭答道:“大都督垂询,罪将也不敢隐瞒:其实先前战况不利时候。也有一些弟兄归降了朝廷。但我们后来得到消息,他们都没得什么好下场。

刘渡旅帅是第一个投过去的,但他过去那边不久就被人吞掉了兵马。吃饭时莫名其妙地吐血死了;陈雨笋将军,他赴宴时候被一帮蒙面人乱刀砍死了;还有明阳旅帅,咱们都听说他哪天晚上就失踪了,有传言说是被人做掉抛尸湖里了。。。”

说着,史文庭打了个寒战,他摇头道:“反正。投朝廷那边去的,没一个好收场的。弟兄们都寒了心,不敢再试了。”

“这。。。不至于吧?归降时,既然保证既往不咎了,难道朝廷会出尔反尔吗?”

“这个。。。罪将私下跟亲近的弟兄也商议过,大家都觉得:皇上英明刚毅,气度恢宏,肯定是不会言而无信的。只是先前咱们跟朝廷打得太狠了,杀了金吾卫不少将官。虽然皇上答应咱们既往不咎的,但那些金吾卫的将门世家同气连枝,彼此沾亲带故的,他们怎肯放过这笔血仇?

而朝廷现在也是用兵之际,皇上不可能为了咱们这些降将去得罪金吾卫的宿将和元老,所以也只能是睁一眼闭一眼,任他们为所欲为了。

相比朝廷那边,大都督这边就好多了。罪将等都听说了,沃野李赤眉、东平易小刀、关山河、白御边等将军投了大都督这边,都得到大都督的信任和重用,不但让他们继续统带原来兵马,待遇甚至比从前更加优厚,甚至还被委以了方面重任。

大都督宽宏仁厚,信义昭著,罪将和众袍泽兄弟都是心悦诚服,所以甘冒巨险前来投靠,托庇于大都督麾下。”

孟聚和文先生对视一眼,都是恍然。文先生又问:“那,史将军,归降后,你想要什么样的条件和待遇?有什么条件吗?”

史文庭的态度表现得很谦逊,只说:“末将自知罪孽深重,不敢妄言条件。归降后,只要大都督给末将一碗饭吃就好,干啥都无所谓——呃,当然,末将这种行伍中人,这辈子除了厮杀以外,再无他长。倘若大都督信得过,让末将继续统带原来兵马的话,末将愿为大都督戍守边疆,护卫一方安宁,稍洗昔日罪孽,这是最好了。”

“原来如此,将军的心意,我们知道了。还请将军下去歇息,我们先商议一番再答复将军,如何?”

“是,罪将告退。”

史文庭鞠躬退下,但他犹豫了下,站住了脚步,哀求地望着孟聚:“大都督,请恕末将多嘴一句,此事十万火急,容不得拖延了。现在前锋兵马是由末将和黄旻旅帅统领,我们二人都是仰慕大都督,诚心愿意归降的。但倘若皇叔到了,在他积威之下,只怕军中有一些顽冥不化的死忠分子出来捣乱,那归降之事只怕要横生波折了。”

“拓跋雄还有多久抵达?”

“皇叔统领中军,离我们只有半天行程。按照皇叔的命令,我们前锋本该是在离城二十里外扎营的,等候中军抵达后再全师共进与大都督交战。但我们违抗命令,轻师急进,径直奔到了大都督军前,就是为了摆脱中军的控制。现在,中军那边应该已经发现不对了——恳请大都督体恤末将等的为难,从速决断,罪将和麾下全体将士皆感大都督再生盛德。”

史文庭退下了,孟聚望向文先生:“文先生,你怎么看?这位史将军,说的是真话还是假话呢?”

文先生沉吟着,望着远处那一片灿烂的营火,久久没有说话。

良久,他回转了身子,肃容道:“主公,史旅帅突然到访,此事太过突兀。但若按学生的看法,史将军说的该是真话,他不是诈降。”

“何以见得?”

“其一,学生昔日在元帅帐中,也听过史将军的名字。史将军是沃野的将领,并非元帅的嫡系和亲信。边军大势已去,史将军为寻出路来归降我军,此是合情合理的。”

孟聚微微颌首,没有出声,但王虎却是忍不住插口道:“说不定这是拓跋雄故意在使诈呢?他知道派嫡系将领来归降,咱们肯定是信不过的,于是就故意派一个外系的将军过来诈降,骗得我军的信任后再里应外合,偷袭我军?”

文先生望望王虎,笑道:“王将军此说倒也有些道理,但学生觉得,元帅此刻已没有施展计谋的余地了。”

“为何?”

“现在,边军末日已近,分崩之势已现,将领离心,士气低迷,士卒逃散——短短半月,单是咱们楚南府就抓获了三千多逃兵,甚至有管领一级的军官也当了逃兵,这就是边军人心不稳的明证了。

这种情形下,元帅怎么还敢派那些本就动摇不稳的外系将领来诈降咱们?即使他真的派人过来——那些外系将来本来就心怀二意了,得此机会脱离控制,只怕诈降也会变成真降了。元帅这样做,什么效果也没有,只会白白损折了兵马,这是原因其二了。”

文先生剖析得条理分明,孟聚不禁出声赞同:“先生言之甚是,王虎你不要吵,让先生好好说——先生,敢问还有其三吗?”

文先生捋着长须,微笑着说:“其三就是,这事太过仓促,太不合理,所以学生倒以为,这是真的。”

“这又是怎么说呢?”

“学生在元帅帐下多年,也揣摩到一点元帅的用谋风格。倘若元帅真要有心使人诈降,他会做得很周全,会事先设好伏笔,会显得非常合情合理。

比方说,元帅真要诈降的话,他会事先遣人来跟大都督您多次接触,双方经历多次谈判,约好归降各项事宜,显得非常有诚意的样子。

但象史将军这样,事先没有约定,也没打过招呼,这样直愣愣冲过来忽然就说要投降了,太突兀,太出人意料,令人没法接受——元帅以己度人,他觉得自己不可能相信的事,大都督您也不可能相信的。所以,先生觉得,这不会是元帅的诈降之计。”

孟聚一愣,拊掌大笑:“说得好!”

Ubuntu/Linux默认程序关联文件

 

1
2
3
/etc/gnome/default.list or /usr/share/applications/default.list
~/.local/share/applications/mimeapps.list
~/.local/share/applications/default.list

 

用文本编辑器更改上述三个文件中的信息,替换gedit.desktop为sublime-text-2.desktop(确认/usr/share/applications/下的名称)

最后重启nautilus

 

1
pkill nautilus

 

使用 .htaccess 提高 WordPress 的安全性和可用性

使用 .htaccess 提高 WordPress 的安全性和可用性

发布者:Burt Thomas,发布时间:2009111日 下午4:17

 

尽管 .htaccess 只是一个文件,但是它能改变你服务器上的设置和允许你做很多不同的东东,如最受欢迎的是它能让你定制化 404 错误页面。.htaccess 其实并不难,你可以认为它只是由一些简单命令或者用法说明组成的文本文件,不过他却能极大的提高你站点的安全性,所以没有借口不去用它。

创建 .htaccess 文件时可能给你带来一些问题。写入内容到这个文件是非常容易的,你只需输入合适的代码到文本编辑器中(如记事本)。但是你可能在保存文件的时候碰到问题。 因为 .htaccess 是一个非常奇怪的文件名(这个文件没有名字而只有一个8字符的扩展名)。这个可能在特定的系统中不能被接受(如 Windows 95)。在绝大多数的操作系统中,你可以尝试在保存文件的时候输入以下文件名:”.htaccess”(包括引号)。如果这不起作用,你可能需要先把它命 名为别的名字(如 htaccess.txt),然后上传到服务器。上传之后,在 FTP 工具中重命名它。

尽管通过 .htaccess 可以做很多事情,但是这篇日志主要关注的是如何提高 WordPress 的安全性和可用性。

保护 .htaccess 自身的安全性。阻止用户通过读取和写入 .htaceess 来更改安全性的设置。

<files .htaccess>

order allow,deny

deny from all

</files>

 

隐藏服务器的数字签名。隐藏服务器的数字签名之后,入侵者将很难找到有机会找到安全漏洞,因为他们不知道背后的服务器是什么。

ServerSignature Off

 

限制上传文件的大小。这个能够帮助阻止 DoS 攻击(用户通过上传巨大的文件来冲垮服务器)并且能够节约带宽。

LimitRequestBody 10240000

# limit file uploads to 10mb

 

停止 mod_security 过滤器。这是一个可选的设置并且要小心处理。这些指令告诉服务器不要使用 mod_security 过滤器,因为 mod_security 过滤器不允许用户发表含有这些单词 “curl”,“lynx” 或者 “wget” 等等单词的文章。这个看起来有点琐碎,但是这个让一些站点头痛,因为这些单词几乎那些站点每天都会用到。

SecFilterInheritance Off

 

保护 wp-config.php 文件。我们可以通过 .htaccess 文件阻止用户读取和写入 WordPress 的主配置文件。这个指令假设 WordPress 是安装在站带你的根目录。

<files wp-config.php>

order allow,deny

deny from all

</files>

 

指定自定义错误文档。这条指令做的更多是站点的可用性而不是安全性。它们指定了哪个页面将被显示,一旦服务器错误,如页面找不到(代码 404) 禁止访问(代码 403)等等。

ErrorDocument 404 /notfound.php

ErrorDocument 403 /forbidden.php

ErrorDocument 500 /error.php

 

禁止浏览目录。这将阻止服务器在没有找到 index 文件(如 index.htmlindex.php 等等)的情况下显示文件夹目录内容。这能阻止用户看到文件夹的内容使得更难对网站发动攻击。

# disable directory browsing

Options All -Indexes

 

防止图片盗链。这个能够阻止其他网站盗链本网站的图片,迫使他们 要么指向整个页面,或者其他存储图像的地方。这个保存了宝贵的带宽并且能够增加流量(虽然只是一点点)。下面的代码将会显示 stealingisbad.gif 这张图片,当有人试着热链到到你的网站来显示图片

#disable hotlinking of images

RewriteEngine on

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com/.*$ [NC]

#RewriteRule .(gif|jpg|png)$ http://www.yourdomain.com/stealingisbad.gif [R,L]

 

在你的站点给每个 URL 设置符合规定的或者“标准”的链接。这能够帮助提高网站的可用性和提高网站在搜索引擎中的排名。总之,它会把来自 http://yourdomain.com 的请求重定向到 http://www.yourdomain.com/.

# set the canonical url

RewriteEngine On

RewriteCond %{HTTP_HOST} ^yourdomain.com$ [NC]

RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

 

保护博客免受垃圾留言的侵扰(和普通方式提交的垃圾留言)。最后的那条指令将会阻止用户直接从其他网站的留言提交框发表留言,虽然这不是一个包罗万象的反垃圾留言的方法,但是它确实能够帮助你。

# protect from spam comments

RewriteEngine On

RewriteCond %{REQUEST_METHOD} POST

RewriteCond %{REQUEST_URI} .wp-comments-post.php*

RewriteCond %{HTTP_REFERER} !.*yourdomain.com.* [OR]

RewriteCond %{HTTP_USER_AGENT} ^$

RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

 

加入这些指令之后,你应该添加 WordPress 用于管理永久链接的代码。还有很多的指令和很多的方法可以提高网站的可用性和安全性,不过这里所列出的应该占了日常所需的大部分了。当你上传该文件到服务 器上之后,你应该一遍有一遍的测试直到你觉得所有的东西都工作正常,再测试一遍。检查下是否受保护的文件还能不能被访问,你依旧允许访问的文件和文件夹能 否还能访问。常规的经验可能是棘手的事情,它们可能导致看似随机的问题,所以在你发布你的网站之前务必完全的测试你的网站。

ssh指南

SSH使用指南
文章地址:http://www.ykzj.org/article.php?articleid=1149
介绍SSH
什么是SSH?
传统的网络服务程序,如:ftp、pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口
令和数据,别有用心的人非常容易就可以截获这些口令和数据。而且,这些服务程序的安全验证方式
也是有其弱点的,就是很容易受到”中间人”(man-in-the-middle)这种方式的攻击。所谓”中间人”的攻
击方式,就是”中间人”冒充真正的服务器接收你的传给服务器的数据,然后再冒充你把数据传给真正
的服务器。服务器和你之间的数据传送被”中间人”一转手做了手脚之后,就会出现很严重的问题。
SSH的英文全称是Secure
SHell。通过使用SSH,你可以把所有传输的数据进行加密,这样”中间人”这种攻击方式就不可能实现
了,而且也能够防止DNS和IP欺骗。还有一个额外的好处就是传输的数据是经过压缩的,所以可以加
快传输的速度。SSH有很多功能,它既可以代替telnet,又可以为ftp、pop、甚至ppp提供一个安全的”
通道”。
最初SSH是由芬兰的一家公司开发的。但是因为受版权和加密算法的限制,现在很多人都转而使
用OpenSSH。OpenSSH是SSH的替代软件,而且是免费的,可以预计将来会有越来越多的人使用它而
不是SSH。
SSH是由客户端和服务端的软件组成的,有两个不兼容的版本分别是:1.x和2.x。用SSH 2.x的客户程序
是不能连接到SSH
1.x的服务程序上去的。OpenSSH 2.x同时支持SSH 1.x和2.x。
SSH的安全验证是如何工作的
从客户端来看,SSH提供两种级别的安全验证。
第一种级别(基于口令的安全验证)只要你知道自己帐号和口令,就可以登录到远程主机。所有传输
的数据都会被加密,但是不能保证你正在连接的服务器就是你想连接的服务器。可能会有别的服务器
在冒充真正的服务器,也就是受到”中间人”这种方式的攻击。
第二种级别(基于密匙的安全验证)需要依靠密匙,也就是你必须为自己创建一对密匙,并把公用密
匙放在需要访问的服务器上。如果你要连接到SSH服务器上,客户端软件就会向服务器发出请求,请
求用你的密匙进行安全验证。服务器收到请求之后,先在你在该服务器的家目录下寻找你的公用密匙
,然后把它和你发送过来的公用密匙进行比较。如果两个密匙一致,服务器就用公用密匙加密”质询”
(challenge)并把它发送给客户端软件。客户端软件收到”质询”之后就可以用你的私人密匙解密再把它
发送给服务器。
用这种方式,你必须知道自己密匙的口令。但是,与第一种级别相比,第二种级别不需要在网络上传
送口令。
第二种级别不仅加密所有传送的数据,而且”中间人”这种攻击方式也是不可能的(因为他没有你的私
人密匙)。但是整个登录的过程可能需要10秒。
安装并测试OpenSSH
因为受到美国法律的限制,在很多Linux的发行版中都没有包括OpenSSH。但是,可以从网络上下载并
安装OpenSSH(有关OpenSSH的安装和配置请参考
:http://www.linuxaid.com.cn/engineer/brimmer/html/OpenSSH.htm)。
安装完OpenSSH之后,用下面命令测试一下:
ssh -l [your accountname on the remote host] [address of the remote host]
如果OpenSSH工作正常,你会看到下面的提示信息:
The authenticity of host [hostname] can t be established.
Key fingerprint is 1024 5f:a0:0b:65:d3:82:df:ab:44:62:6d:98:9c:fe:e9:52.
Are you sure you want to continue connecting (yes/no)?
OpenSSH告诉你它不知道这台主机,但是你不用担心这个问题,因为你是第一次登录这台主机。键
入”yes”。这将把这台主机的”识别标记”加到”~/.ssh/know_hosts”文件中。第二次访问这台主机的时候就
不会再显示这条提示信息了。
然后,SSH提示你输入远程主机上你的帐号的口令。输入完口令之后,就建立了SSH连接,这之后就
可以象使用telnet那样使用SSH了。
SSH的密匙
生成你自己的密匙对
生成并分发你自己的密匙有两个好处:
1) 可以防止”中间人”这种攻击方式
2) 可以只用一个口令就登录到所有你想登录的服务器上
用下面的命令可以生成密匙:
ssh-keygen
如果远程主机使用的是SSH 2.x就要用这个命令:
ssh-keygen -d
在同一台主机上同时有SSH1和SSH2的密匙是没有问题的,因为密匙是存成不同的文件的。
ssh-keygen命令运行之后会显示下面的信息:
Generating RSA keys: ……………………….ooooooO……ooooooO
Key generation complete.
Enter file in which to save the key (/home/[user]/.ssh/identity):
[按下ENTER就行了]
Created directory /home/[user]/.ssh .
Enter passphrase (empty for no passphrase):
[输入的口令不会显示在屏幕上]
Enter same passphrase again:
[重新输入一遍口令,如果忘记了口令就只能重新生成一次密匙了]
Your identification has been saved in /home/[user]/.ssh/identity.
[这是你的私人密匙]
Your public key has been saved in /home/[user]/.ssh/identity.pub.
The key fingerprint is: 2a:dc:71:2f:27:84:a2:e4:a1:1e:a9:63:e2:fa:a5:89
[user]@[local machine]
“ssh-keygen
-d”做的是几乎同样的事,但是把一对密匙存为(默认情况下)”/home/[user]/.ssh/id_dsa”(私人密匙)
和”/home/[user]/.ssh/id_dsa.pub”(公用密匙)。
现在你有一对密匙了:公用密匙要分发到所有你想用ssh登录的远程主机上去;私人密匙要好好地保管
防止别人知道你的私人密匙。用”ls -l
~/.ssh/identity”或”ls -l ~/.ssh/id_dsa”所显示的文件的访问权限必须是”-rw——-”。
如果你怀疑自己的密匙已经被别人知道了,不要迟疑马上生成一对新的密匙。当然,你还要重新分发
一次公用密匙。
分发公用密匙
在每一个你需要用SSH连接的远程服务器上,你要在自己的家目录下创建一个”.ssh”的子目录,把你的
公用密匙”identity.pub”
拷贝到这个目录下并把它重命名为”authorized_keys”。然后执行:
chmod 644 .ssh/authorized_keys
这一步是必不可少的。如果除了你之外别人对”authorized_keys”文件也有写的权限,SSH就不会工作。
如果你想从不同的计算机登录到远程主机,”authorized_keys”文件也可以有多个公用密匙。在这种情况
下,必须在新的计算机上重新生成一对密匙,然后把生成的”identify.pub”文件拷贝并粘贴到远程主机
的”authorized_keys”文件里。当然在新的计算机上你必须有一个帐号,而且密匙是用口令保护的。有一
点很重要,就是当你取消了这个帐号之后,别忘了把这一对密匙删掉。
配置SSH
配置客户端的软件
OpenSSH有三种配置方式:命令行参数、用户配置文件和系统级的配置文件(“/etc/ssh/ssh_config”)。
命令行参数优先于配置文件,用户配置文件优先于系统配置文件。所有的命令行的参数都能在配置文
件中设置。因为在安装的时候没有默认的用户配置文件,所以要把”/etc/ssh/ssh_config”拷贝并重新命名
为”~/.ssh/config”。
标准的配置文件大概是这样的:
[lots of explanations and possible options listed]
# Be paranoid by default
Host *
ForwardAgent no
ForwardX11 no
FallBackToRsh no
还有很多选项的设置可以用”man ssh”查看”CONFIGURATION FILES”这一章。
配置文件是按顺序读取的。先设置的选项先生效。
假定你在www.foobar.com上有一个名为”bilbo”的帐号。而且你要把”ssh-agent”和”ssh-add”结合起来使用
并且使用数据压缩来加快传输速度。因为主机名太长了,你懒得输入这么长的名字,用”fbc”作
为”www.foobar.com”的简称。你的配置文件可以是这样的:
Host *fbc
HostName www.foobar.com
User bilbo
ForwardAgent yes
Compression yes
# Be paranoid by default
Host *
ForwardAgent no
ForwardX11 no
FallBackToRsh no
你输入”ssh fbc”之后,SSH会自动地从配置文件中找到主机的全名,用你的用户名登录并且用”ssh-agent”
管理的密匙进行安全验证。这样很方便吧!
用SSH连接到其它远程计算机用的还是”paranoid(偏执)”默认设置。如果有些选项没有在配置文件或
命令行中设置,那么还是使用默认的”paranoid”设置。
在我们上面举的那个例子中,对于到www.foobar.com的SSH连接:”ForwardAgent”和”Compression”被设
置为”Yes”;其它的设置选项(如果没有用命令行参数)”ForwardX11″和”FallBackToRsh”都被设置成”No”

其它还有一些需要仔细看一看的设置选项是:
l CheckHostIP yes
这个选项用来进行IP地址的检查以防止DNS欺骗。
l CompressionLevel
压缩的级别从”1″(最快)到”9″(压缩率最高)。默认值为”6″。
l ForwardX11 yes
为了在本地运行远程的X程序必须设置这个选项。
l LogLevel DEBUG
当SSH出现问题的时候,这选项就很有用了。默认值为”INFO”。
配置服务端的软件
SSH服务器的配置使用的是”/etc/ssh/sshd_config”配置文件,这些选项的设置在配置文件中已经有了一些
说明而且用”man
sshd”也可以查看帮助。请注意OpenSSH对于SSH 1.x和2.x没有不同的配置文件。
在默认的设置选项中需要注意的有:
l PermitRootLogin yes
最好把这个选项设置成”PermitRootLogin
without-password”,这样”root”用户就不能从没有密匙的计算机上登录。把这个选项设置成”no”将禁
止”root”用户登录,只能用”su”命令从普通用户转成”root”。
l X11Forwarding no
把这个选项设置成”yes”允许用户运行远程主机上的X程序。就算禁止这个选项也不能提高服务器的安
全因为用户可以安装他们自己的转发器(forwarder),请参看”man
sshd”。
l PasswordAuthentication yes
把这个选项设置为”no”只允许用户用基于密匙的方式登录。这当然会给那些经常需要从不同主机登录
的用户带来麻烦,但是这能够在很大程度上提高系统的安全性。基于口令的登录方式有很大的弱点。
l # Subsystem /usr/local/sbin/sftpd
把最前面的#号去掉并且把路径名设置成”/usr/bin/sftpserv”,用户就能使用”sftp”(安全的FTP)了
(sftpserv在sftp软件包中)。因为很多用户对FTP比较熟悉而且”scp”用起来也有一些麻烦,所以”sftp”还
是很有用的。而且2.0.7版本以后的图形化的ftp工具”gftp”也支持”sftp”。
拷贝文件
用”scp”拷贝文件
SSH提供了一些命令和shell用来登录远程服务器。在默认情况下它不允许你拷贝文件,但是还是提供
了一个”scp”命令。
假定你想把本地计算机当前目录下的一个名为”dumb”的文件拷贝到远程服务器www.foobar.com上你的
家目录下。而且你在远程服务器上的帐号名为”bilbo”。可以用这个命令:
scp dumb [email protected]:.
把文件拷贝回来用这个命令:
scp [email protected]:dumb .
“scp”调用SSH进行登录,然后拷贝文件,最后调用SSH关闭这个连接。
如果在你的”~/.ssh/config”文件中已经为www.foobar.com做了这样的配置:
Host *fbc
HostName www.foobar.com
User bilbo
ForwardAgent yes
那么你就可以用”fbc”来代替”[email protected]”,命令就简化为”scp dumb fbc:.”。
“scp”假定你在远程主机上的家目录为你的工作目录。如果你使用相对目录就要相对于家目录。
用”scp”命令的”-r”参数允许递归地拷贝目录。”scp”也可以在两个不同的远程主机之间拷贝文件。
有时候你可能会试图作这样的事:用SSH登录到www.foobar.com上之后,输入命令”scp [local
machine]:dumb
.”想用它把本地的”dumb”文件拷贝到你当前登录的远程服务器上。这时候你会看到下面的出错信息:
ssh: secure connection to [local machine] refused
之所以会出现这样的出错信息是因为你运行的是远程的”scp”命令,它试图登录到在你本地计算机上运
行的SSH服务程序……所以最好在本地运行”scp”除非你的本地计算机也运行SSH服务程序。
用”sftp”拷贝文件
如果你习惯使用ftp的方式拷贝文件,可以试着用”sftp”。”sftp”建立用SSH加密的安全的FTP连接通道,
允许使用标准的ftp命令。还有一个好处就是”sftp”允许你通过”exec”命令运行远程的程序。从2.0.7版以
后,图形化的ftp客户软件”gftp”就支持”sftp”。
如果远程的服务器没有安装sftp服务器软件”sftpserv”,可以把”sftpserv”的可执行文件拷贝到你的远程的
家目录中(或者在远程计算机的$PATH环境变量中设置的路径)。”sftp”会自动激活这个服务软件,你
没有必要在远程服务器上有什么特殊的权限。
用”rsync”拷贝文件
“rsync”是用来拷贝、更新和移动远程和本地文件的一个有用的工具,很容易就可以用”-e
ssh”参数和SSH结合起来使用。”rsync”的一个优点就是,不会拷贝全部的文件,只会拷贝本地目录和远
程目录中有区别的文件。而且它还使用很高效的压缩算法,这样拷贝的速度就很快。
用”加密通道”的ftp拷贝文件
如果你坚持要用传统的FTP客户软件。SSH可以为几乎所有的协议提供”安全通道”。FTP是一个有一点
奇怪的协议(例如需要两个端口)而且不同的服务程序和服务程序之间、客户程序和客户程序之间还
有一些差别。
实现”加密通道”的方法是使用”端口转发”。你可以把一个没有用到的本地端口(通常大于1000)设置成
转发到一个远程服务器上,然后只要连接本地计算机上的这个端口就行了。有一点复杂是吗?
其实一个基本的想法就是,转发一个端口,让SSH在后台运行,用下面的命令:
ssh [user@remote host] -f -L 1234:[remote host]:21 tail -f /etc/motd
接着运行FTP客户,把它设置到指定的端口:
lftp -u [username] -p 1234 localhost
当然,用这种方法很麻烦而且很容易出错。所以最好使用前三种方法。
用SSH设置”加密通道”
“加密通道”的基础知识
SSH的”加密通道”是通过”端口转发”来实现的。你可以在本地端口(没有用到的)和在远程服务器上运
行的某个服务的端口之间建立”加密通道”。然后只要连接到本地端口。所有对本地端口的请求都被SSH
加密并且转发到远程服务器的端口。当然只有远程服务器上运行SSH服务器软件的时候”加密通道”才能
工作。可以用下面命令检查一些远程服务器是否运行SSH服务:
telnet [full name of remote host] 22
如果收到这样的出错信息:
telnet: Unable to connect to remote host: Connection refused
就说明远程服务器上没有运行SSH服务软件。
端口转发使用这样的命令语法:
ssh -f [username@remote host] -L [local port]:[full name of remote host]:[remote
port] [some command]
你不仅可以转发多个端口而且可以在”~/.ssh/config”文件中用”LocalForward”设置经常使用的一些转发端
口。
为POP加上”加密通道”
你可以用POP协议从服务器上取email。为POP加上”加密通道”可以防止POP的密码被网络监听器
(sniffer)监听到。还有一个好处就是SSH的压缩方式可以让邮件传输得更快。
假定你在pop.foobar.com上有一个POP帐号,你的用户名是”bilbo”你的POP口令是”topsecret”。用来建
立SSH”加密通道”的命令是:
ssh -f -C [email protected] -L 1234:pop.foobar.com:110 sleep 5
(如果要测试,可以把”sleep”的值加到500)。运行这个命令之后会提示你输入POP口令:
[email protected] s password:
输入口令之后就可以用”telnet”连接到本地的转发端口了。
telnet localhost 1234
你会收到远程mail服务器的”READY”消息。
当然,这个方法要求你手工输入所有的POP命令,这是很不方便的。可以用Fetchmail(参考how to
configure Fetchmail)。Secure
POP via SSH mini-HOWTO、man
fetchmail和在”/usr/doc/fetchmail-[…]“目录下的Fetchmail的FAQ都提供了一些具体的例子。
请注意IMAP协议使用的是不同的端口:IMAP v2的端口号为143而IMAP v3的端口号为220。
为X加上”加密通道”
如果你打算在本地计算机上运行远程SSH服务器上的X程序,那么登录到远程的计算机上,创建一个名
为”~/.ssh/environment”的文件并加上这一行:
XAUTHORITY=/home/[remote user name]/.Xauthority
(如果在远程主机上你的家目录下不存在”.Xauthority”这个文件,那么当用SSH登录的时候就会自动创
建)。
比如启动一个X程序(xterm)可以这个命令:
ssh -f -X -l [remote user name] [remote machine] xterm
这将在远程运行xterm这个程序。其它的X程序也是用相同的方法。
为linuxconf加上”加密通道”
Linuxconf(http://www.solucorp.qc.ca/linuxconf/)是Linux的配置工具,它支持远程管理。Linuxconf的FAQ
重说明了如何通过SSH使用linuxconf:
其命令为:
remadmin –exec [link_command] linuxconf –guiproto
如果你想在两台计算机之间用加密的方式传送信息,那么最好用ssh。命令是:
remadmin –exec ssh -l [account] linuxconf –guiproto
这是非常有效的而且运行用图形界面管理计算机。
这种方法需要在客户端安装linuxconf。其它的方法还有直接登录到服务器上用”X11Forwarding”或字符
界面运行linuxconf。
为Webmin加上”加密通道”
Webmin(http://www.webmin.com/webmin/)是一个新的基于浏览器的配置工具。它运行在1000端口。你
可以用SSH的”端口转发”对它进行加密:
ssh -f -l [remote user name] [remote host] -L 1234:[remote host]:10000 tail -f
/etc/motd
把浏览器指向

http://localhost:1234

版权说明
这篇文章翻译和改编自:http://www.mandrakeuser.org/secure/index.html。英文版的版权属
于”MandrakeSoft
SA and LSTB 1999/2000″。
中文版版权归译者brimmer([email protected])和www.linuxaid.com.cn站点所有。
本文遵循Open Content Public Licence。

vim

 

https://blog.csdn.net/cpainter/article/details/52702942

 

你想以最快的速度学习人类史上最好的文本编辑器VIM吗?你先得懂得如何在VIM幸存下来,然后一点一点地学习各种戏法。

Vim the Six Billion Dollar editor

Better, Stronger, Faster.

学习 vim 并且其会成为你最后一个使用的文本编辑器。没有比这个更好的文本编辑器了,非常地难学,但是却不可思议地好用。

我建议下面这四个步骤:

  1. 存活
  2. 感觉良好
  3. 觉得更好,更强,更快
  4. 使用VIM的超能力

当你走完这篇文章,你会成为一个vim的 superstar。

在开始学习以前,我需要给你一些警告:

  • 学习vim在开始时是痛苦的。
  • 需要时间
  • 需要不断地练习,就像你学习一个乐器一样。
  • 不要期望你能在3天内把vim练得比别的编辑器更有效率。
  • 事实上,你需要2周时间的苦练,而不是3天。

第一级 – 存活

  1. 安装 vim
  2. 启动 vim
  3. 什么也别干!请先阅读

当你安装好一个编辑器后,你一定会想在其中输入点什么东西,然后看看这个编辑器是什么样子。但vim不是这样的,请按照下面的命令操作:

  • 启 动Vim后,vim在 Normal 模式下。
  • 让我们进入 Insert 模式,请按下键 i 。(陈皓注:你会看到vim左下角有一个–insert–字样,表示,你可以以插入的方式输入了)
  • 此时,你可以输入文本了,就像你用“记事本”一样。
  • 如果你想返回 Normal 模式,请按 ESC 键。

现在,你知道如何在 Insert 和 Normal 模式下切换了。下面是一些命令,可以让你在 Normal 模式下幸存下来:

  • i → Insert 模式,按 ESC 回到 Normal 模式.
  • x → 删当前光标所在的一个字符。
  • :wq → 存盘 + 退出 (:w 存盘, :q 退出)   (陈皓注::w 后可以跟文件名)
  • dd → 删除当前行,并把删除的行存到剪贴板里
  • p → 粘贴剪贴板

推荐:

  • hjkl (强例推荐使用其移动光标,但不必需) →你也可以使用光标键 (←↓↑→). 注: j 就像下箭头。
  • :help <command> → 显示相关命令的帮助。你也可以就输入 :help 而不跟命令。(陈皓注:退出帮助需要输入:q)

你能在vim幸存下来只需要上述的那5个命令,你就可以编辑文本了,你一定要把这些命令练成一种下意识的状态。于是你就可以开始进阶到第二级了。

当是,在你进入第二级时,需要再说一下 Normal 模式。在一般的编辑器下,当你需要copy一段文字的时候,你需要使用 Ctrl 键,比如:Ctrl-C。也就是说,Ctrl键就好像功能键一样,当你按下了功能键Ctrl后,C就不在是C了,而且就是一个命令或是一个快键键了,在VIM的Normal模式下,所有的键就是功能键了。这个你需要知道。

标记:

  • 下面的文字中,如果是 Ctrl-λ我会写成 <C-λ>.
  • 以 : 开始的命令你需要输入 <enter>回车,例如 — 如果我写成 :q 也就是说你要输入 :q<enter>.

第二级 – 感觉良好

上面的那些命令只能让你存活下来,现在是时候学习一些更多的命令了,下面是我的建议:(陈皓注:所有的命令都需要在Normal模式下使用,如果你不知道现在在什么样的模式,你就狂按几次ESC键)

  1. 各种插入模式
    • a → 在光标后插入
    • o → 在当前行后插入一个新行
    • O → 在当前行前插入一个新行
    • cw → 替换从光标所在位置后到一个单词结尾的字符
  2. 简单的移动光标
    • 0 → 数字零,到行头
    • ^ → 到本行第一个不是blank字符的位置(所谓blank字符就是空格,tab,换行,回车等)
    • $ → 到本行行尾
    • g_ → 到本行最后一个不是blank字符的位置。
    • /pattern → 搜索 pattern 的字符串(陈皓注:如果搜索出多个匹配,可按n键到下一个)
  3. 拷贝/粘贴 (陈皓注:p/P都可以,p是表示在当前位置之后,P表示在当前位置之前)
    • P → 粘贴
    • yy → 拷贝当前行当行于 ddP
  4. Undo/Redo
    • u → undo
    • <C-r> → redo
  5. 打开/保存/退出/改变文件(Buffer)
    • :e <path/to/file> → 打开一个文件
    • :w → 存盘
    • :saveas <path/to/file> → 另存为 <path/to/file>
    • :x, ZZ 或 :wq → 保存并退出 (:x 表示仅在需要时保存,ZZ不需要输入冒号并回车)
    • :q! → 退出不保存 :qa! 强行退出所有的正在编辑的文件,就算别的文件有更改。
    • :bn 和 :bp → 你可以同时打开很多文件,使用这两个命令来切换下一个或上一个文件。(陈皓注:我喜欢使用:n到下一个文件)

花点时间熟悉一下上面的命令,一旦你掌握他们了,你就几乎可以干其它编辑器都能干的事了。但是到现在为止,你还是觉得使用vim还是有点笨拙,不过没关系,你可以进阶到第三级了。

第三级 – 更好,更强,更快

先恭喜你!你干的很不错。我们可以开始一些更为有趣的事了。在第三级,我们只谈那些和vi可以兼容的命令。

更好

下面,让我们看一下vim是怎么重复自己的:

  1. . → (小数点) 可以重复上一次的命令
  2. N<command> → 重复某个命令N次

下面是一个示例,找开一个文件你可以试试下面的命令:

  • 2dd → 删除2行
  • 3p → 粘贴文本3次
  • 100idesu [ESC] → 会写下 “desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu “
  • . → 重复上一个命令—— 100 “desu “.
  • 3. → 重复 3 次 “desu” (注意:不是 300,你看,VIM多聪明啊).
更强

你要让你的光标移动更有效率,你一定要了解下面的这些命令,千万别跳过

  1. NG → 到第 N 行 (陈皓注:注意命令中的G是大写的,另我一般使用 : N 到第N行,如 :137 到第137行)
  2. gg → 到第一行。(陈皓注:相当于1G,或 :1)
  3. G → 到最后一行。
  4. 按单词移动:
    1. w → 到下一个单词的开头。
    2. e → 到下一个单词的结尾。

    > 如果你认为单词是由默认方式,那么就用小写的e和w。默认上来说,一个单词由字母,数字和下划线组成(陈皓注:程序变量)

    > 如果你认为单词是由blank字符分隔符,那么你需要使用大写的E和W。(陈皓注:程序语句)

下面,让我来说说最强的光标移动:

  • % : 匹配括号移动,包括 ({[. (陈皓注:你需要把光标先移到括号上)
  • * 和 #:  匹配光标当前所在的单词,移动光标到下一个(或上一个)匹配单词(*是下一个,#是上一个)

相信我,上面这三个命令对程序员来说是相当强大的。

更快

你一定要记住光标的移动,因为很多命令都可以和这些移动光标的命令连动。很多命令都可以如下来干:

<start position><command><end position>

例如 0y$ 命令意味着:

  • 0 → 先到行头
  • y → 从这里开始拷贝
  • $ → 拷贝到本行最后一个字符

你可可以输入 ye,从当前位置拷贝到本单词的最后一个字符。

你也可以输入 y2/foo 来拷贝2个 “foo” 之间的字符串。

还有很多时间并不一定你就一定要按y才会拷贝,下面的命令也会被拷贝:

  • d (删除 )
  • v (可视化的选择)
  • gU (变大写)
  • gu (变小写)
  • 等等
(陈皓注:可视化选择是一个很有意思的命令,你可以先按v,然后移动光标,你就会看到文本被选择,然后,你可能d,也可y,也可以变大写等)

第四级 – Vim 超能力

你只需要掌握前面的命令,你就可以很舒服的使用VIM了。但是,现在,我们向你介绍的是VIM杀手级的功能。下面这些功能是我只用vim的原因。

在当前行上移动光标: 0 ^ $ f F t T , ;
  • 0 → 到行头
  • ^ → 到本行的第一个非blank字符
  • $ → 到行尾
  • g_ → 到本行最后一个不是blank字符的位置。
  • fa → 到下一个为a的字符处,你也可以fs到下一个为s的字符。
  • t, → 到逗号前的第一个字符。逗号可以变成其它字符。
  • 3fa → 在当前行查找第三个出现的a。
  • F 和 T → 和 f 和 t 一样,只不过是相反方向。

还有一个很有用的命令是 dt" → 删除所有的内容,直到遇到双引号—— "。

区域选择 <action>a<object> 或 <action>i<object>

在visual 模式下,这些命令很强大,其命令格式为

<action>a<object> 和 <action>i<object>

  • action可以是任何的命令,如 d (删除), y (拷贝), v (可以视模式选择)。
  • object 可能是: w 一个单词, W 一个以空格为分隔的单词, s 一个句字, p 一个段落。也可以是一个特别的字符:"、 '、 )、 }、 ]。

假设你有一个字符串 (map (+) ("foo")).而光标键在第一个 的位置。

  • vi" → 会选择 foo.
  • va" → 会选择 "foo".
  • vi) → 会选择 "foo".
  • va) → 会选择("foo").
  • v2i) → 会选择 map (+) ("foo")
  • v2a) → 会选择 (map (+) ("foo"))

块操作: <C-v>

块操作,典型的操作: 0 <C-v> <C-d> I-- [ESC]

  • ^ → 到行头
  • <C-v> → 开始块操作
  • <C-d> → 向下移动 (你也可以使用hjkl来移动光标,或是使用%,或是别的)
  • I-- [ESC] → I是插入,插入“--”,按ESC键来为每一行生效。

在Windows下的vim,你需要使用 <C-q> 而不是 <C-v> ,<C-v> 是拷贝剪贴板。

自动提示: <C-n> 和 <C-p>

在 Insert 模式下,你可以输入一个词的开头,然后按 <C-p>或是<C-n>,自动补齐功能就出现了……

宏录制: qa 操作序列 q@a@@
  • qa 把你的操作记录在寄存器 a。
  • 于是 @a 会replay被录制的宏。
  • @@ 是一个快捷键用来replay最新录制的宏。

示例

在一个只有一行且这一行只有“1”的文本中,键入如下命令:

  • qaYp<C-a>q
    • qa 开始录制
    • Yp 复制行.
    • <C-a> 增加1.
    • q 停止录制.
  • @a → 在1下面写下 2
  • @@ → 在2 正面写下3
  • 现在做 100@@ 会创建新的100行,并把数据增加到 103.

可视化选择: v,V,<C-v>

前面,我们看到了 <C-v>的示例 (在Windows下应该是<C-q>),我们可以使用 v 和 V。一但被选好了,你可以做下面的事:

  • J → 把所有的行连接起来(变成一行)
  • < 或 > → 左右缩进
  • = → 自动给缩进 (陈皓注:这个功能相当强大,我太喜欢了)

在所有被选择的行后加上点东西:

  • <C-v>
  • 选中相关的行 (可使用 j 或 <C-d> 或是 /pattern 或是 % 等……)
  • $ 到行最后
  • A, 输入字符串,按 ESC。

分屏: :split 和 vsplit.

下面是主要的命令,你可以使用VIM的帮助 :help split. 你可以参考本站以前的一篇文章VIM分屏

  • :split → 创建分屏 (:vsplit创建垂直分屏)
  • <C-w><dir> : dir就是方向,可以是 hjkl 或是 ←↓↑→ 中的一个,其用来切换分屏。
  • <C-w>_ (或 <C-w>|) : 最大化尺寸 (<C-w>| 垂直分屏)
  • <C-w>+ (或 <C-w>-) : 增加尺寸

结束语

  • 上面是作者最常用的90%的命令。
  • 我建议你每天都学1到2个新的命令。
  • 在两到三周后,你会感到vim的强大的。
  • 有时候,学习VIM就像是在死背一些东西。
  • 幸运的是,vim有很多很不错的工具和优秀的文档。
  • 运行vimtutor直到你熟悉了那些基本命令。
  • 其在线帮助文档中你应该要仔细阅读的是 :help usr_02.txt.
  • 你会学习到诸如  !, 目录,寄存器,插件等很多其它的功能。

学习vim就像学弹钢琴一样,一旦学会,受益无穷。

Tor manual

SYNOPSIS
tor [OPTION value]…

DESCRIPTION
tor is a connection-oriented anonymizing communication service. Users choose a source-routed path through a set of nodes, and negotiate a “virtual circuit” through the network, in which each node knows its predecessor and successor, but no others. Traffic flowing down the circuit is unwrapped by a symmetric key at each node, which reveals the downstream node.

Basically tor provides a distributed network of servers (“onion routers”). Users bounce their TCP streams — web traffic, ftp, ssh, etc — around the routers, and recipients, observers, and even the routers themselves have difficulty tracking the source of the stream.

COMMAND-LINE OPTIONS
-h, -help
Display a short help message and exit.
-f FILE
Specify a new configuration file to contain further Tor configuration options. (Default: $HOME/.torrc, or @CONFDIR@/torrc if that file is not found)
–defaults-torrc FILE
Specify a file in which to find default values for Tor options. The contents of this file are overridden by those in the regular configuration file, and by those on the command line. (Default: @CONFDIR@/torrc-defaults.)
–hash-password
Generates a hashed password for control port access.
–list-fingerprint
Generate your keys and output your nickname and fingerprint.
–verify-config
Verify the configuration file is valid.
–service install [–options command-line options]
Install an instance of Tor as a Windows service, with the provided command-line options. Current instructions can be found at https://trac.torproject.org/projects/tor/wiki/doc/TorFAQ#HowdoIrunmyTorrelayasanNTservice
–service remove|start|stop
Remove, start, or stop a configured Tor Windows service.
–nt-service
Used internally to implement a Windows service.
–list-torrc-options
List all valid options.
–version
Display Tor version and exit.
–quiet|–hush
Override the default console log. By default, Tor starts out logging messages at level “notice” and higher to the console. It stops doing so after it parses its configuration, if the configuration tells it to log anywhere else. You can override this behavior with the –hush option, which tells Tor to only send warnings and errors to the console, or with the –quiet option, which tells Tor not to log to the console at all.
Other options can be specified on the command-line in the format “–option value”, in the format “option value”, or in a configuration file. For instance, you can tell Tor to start listening for SOCKS connections on port 9999 by passing –SOCKSPort 9999 or SOCKSPort 9999 to it on the command line, or by putting “SOCKSPort 9999″ in the configuration file. You will need to quote options with spaces in them: if you want Tor to log all debugging messages to debug.log, you will probably need to say –Log debug file debug.log.

Options on the command line override those in configuration files. See the next section for more information.

THE CONFIGURATION FILE FORMAT
All configuration options in a configuration are written on a single line by default. They take the form of an option name and a value, or an option name and a quoted value (option value or option “value”). Anything after a # character is treated as a comment. Options are case-insensitive. C-style escaped characters are allowed inside quoted values. To split one configuration entry into multiple lines, use a single backslash character () before the end of the line. Comments can be used in such multiline entries, but they must start at the beginning of a line.

By default, an option on the command line overrides an option found in the configuration file, and an option in a configuration file overrides one in the defaults file.

This rule is simple for options that take a single value, but it can become complicated for options that are allowed to occur more than once: if you specify four SOCKSPorts in your configuration file, and one more SOCKSPort on the command line, the option on the command line will replace all of the SOCKSPorts in the configuration file. If this isn’t what you want, prefix the option name with a plus sign, and it will be appended to the previous set of options instead.

Alternatively, you might want to remove every instance of an option in the configuration file, and not replace it at all: you might want to say on the command line that you want no SOCKSPorts at all. To do that, prefix the option name with a forward slash.

GENERAL OPTIONS
BandwidthRate N bytes|KB|MB|GB
A token bucket limits the average incoming bandwidth usage on this node to the specified number of bytes per second, and the average outgoing bandwidth usage to that same value. If you want to run a relay in the public network, this needs to be at the very least 30 KB (that is, 30720 bytes). (Default: 5 MB)
BandwidthBurst N bytes|KB|MB|GB
Limit the maximum token bucket size (also known as the burst) to the given number of bytes in each direction. (Default: 10 MB)
MaxAdvertisedBandwidth N bytes|KB|MB|GB
If set, we will not advertise more than this amount of bandwidth for our BandwidthRate. Server operators who want to reduce the number of clients who ask to build circuits through them (since this is proportional to advertised bandwidth rate) can thus reduce the CPU demands on their server without impacting network performance.
RelayBandwidthRate N bytes|KB|MB|GB
If not 0, a separate token bucket limits the average incoming bandwidth usage for _relayed traffic_ on this node to the specified number of bytes per second, and the average outgoing bandwidth usage to that same value. Relayed traffic currently is calculated to include answers to directory requests, but that may change in future versions. (Default: 0)
RelayBandwidthBurst N bytes|KB|MB|GB
If not 0, limit the maximum token bucket size (also known as the burst) for _relayed traffic_ to the given number of bytes in each direction. (Default: 0)
PerConnBWRate N bytes|KB|MB|GB
If set, do separate rate limiting for each connection from a non-relay. You should never need to change this value, since a network-wide value is published in the consensus and your relay will use that value. (Default: 0)
PerConnBWBurst N bytes|KB|MB|GB
If set, do separate rate limiting for each connection from a non-relay. You should never need to change this value, since a network-wide value is published in the consensus and your relay will use that value. (Default: 0)
ClientTransportPlugin transport socks4|socks5 IP:PORT
ClientTransportPlugin transport exec path-to-binary [options]
In its first form, when set along with a corresponding Bridge line, the Tor client forwards its traffic to a SOCKS-speaking proxy on “IP:PORT”. It’s the duty of that proxy to properly forward the traffic to the bridge.

In its second form, when set along with a corresponding Bridge line, the Tor client launches the pluggable transport proxy executable in path-to-binary using options as its command-line options, and forwards its traffic to it. It’s the duty of that proxy to properly forward the traffic to the bridge.

ServerTransportPlugin transport exec path-to-binary [options]
The Tor relay launches the pluggable transport proxy in path-to-binary using options as its command-line options, and expects to receive proxied client traffic from it.
ConnLimit NUM
The minimum number of file descriptors that must be available to the Tor process before it will start. Tor will ask the OS for as many file descriptors as the OS will allow (you can find this by “ulimit -H -n”). If this number is less than ConnLimit, then Tor will refuse to start.

You probably don’t need to adjust this. It has no effect on Windows since that platform lacks getrlimit(). (Default: 1000)

DisableNetwork 0|1
When this option is set, we don’t listen for or accept any connections other than controller connections, and we don’t make any outbound connections. Controllers sometimes use this option to avoid using the network until Tor is fully configured. (Default: 0)
ConstrainedSockets 0|1
If set, Tor will tell the kernel to attempt to shrink the buffers for all sockets to the size specified inConstrainedSockSize. This is useful for virtual servers and other environments where system level TCP buffers may be limited. If you’re on a virtual server, and you encounter the “Error creating network socket: No buffer space available” message, you are likely experiencing this problem.

The preferred solution is to have the admin increase the buffer pool for the host itself via /proc/sys/net/ipv4/tcp_mem or equivalent facility; this configuration option is a second-resort.

The DirPort option should also not be used if TCP buffers are scarce. The cached directory requests consume additional sockets which exacerbates the problem.

You should not enable this feature unless you encounter the “no buffer space available” issue. Reducing the TCP buffers affects window size for the TCP stream and will reduce throughput in proportion to round trip time on long paths. (Default: 0)

ConstrainedSockSize N bytes|KB
When ConstrainedSockets is enabled the receive and transmit buffers for all sockets will be set to this limit. Must be a value between 2048 and 262144, in 1024 byte increments. Default of 8192 is recommended.
ControlPort PORT|auto
If set, Tor will accept connections on this port and allow those connections to control the Tor process using the Tor Control Protocol (described in control-spec.txt). Note: unless you also specify one or more ofHashedControlPassword or CookieAuthentication, setting this option will cause Tor to allow any process on the local host to control it. (Setting both authentication methods means either method is sufficient to authenticate to Tor.) This option is required for many Tor controllers; most use the value of 9051. Set it to “auto” to have Tor pick a port for you. (Default: 0)
ControlListenAddress IP[:PORT]
Bind the controller listener to this address. If you specify a port, bind to this port rather than the one specified in ControlPort. We strongly recommend that you leave this alone unless you know what you’re doing, since giving attackers access to your control listener is really dangerous. This directive can be specified multiple times to bind to multiple addresses/ports. (Default: 127.0.0.1)
ControlSocket Path
Like ControlPort, but listens on a Unix domain socket, rather than a TCP socket. (Unix and Unix-like systems only.)
ControlSocketsGroupWritable 0|1
If this option is set to 0, don’t allow the filesystem group to read and write unix sockets (e.g. ControlSocket). If the option is set to 1, make the control socket readable and writable by the default GID. (Default: 0)
HashedControlPassword hashed_password
Allow connections on the control port if they present the password whose one-way hash is hashed_password. You can compute the hash of a password by running “tor –hash-password password“. You can provide several acceptable passwords by using more than one HashedControlPassword line.
CookieAuthentication 0|1
If this option is set to 1, allow connections on the control port when the connecting process knows the contents of a file named “control_auth_cookie”, which Tor will create in its data directory. This authentication method should only be used on systems with good filesystem security. (Default: 0)
CookieAuthFile Path
If set, this option overrides the default location and file name for Tor’s cookie file. (See CookieAuthentication above.)
CookieAuthFileGroupReadable 0|1|Groupname
If this option is set to 0, don’t allow the filesystem group to read the cookie file. If the option is set to 1, make the cookie file readable by the default GID. [Making the file readable by other groups is not yet implemented; let us know if you need this for some reason.] (Default: 0)
ControlPortWriteToFile Path
If set, Tor writes the address and port of any control port it opens to this address. Usable by controllers to learn the actual control port when ControlPort is set to “auto”.
ControlPortFileGroupReadable 0|1
If this option is set to 0, don’t allow the filesystem group to read the control port file. If the option is set to 1, make the control port file readable by the default GID. (Default: 0)
DataDirectory DIR
Store working data in DIR (Default: @LOCALSTATEDIR@/lib/tor)
DirServer [nickname] [flags] address:port fingerprint
Use a nonstandard authoritative directory server at the provided address and port, with the specified key fingerprint. This option can be repeated many times, for multiple authoritative directory servers. Flags are separated by spaces, and determine what kind of an authority this directory is. By default, every authority is authoritative for current (“v2″)-style directories, unless the “no-v2″ flag is given. If the “v1″ flags is provided, Tor will use this server as an authority for old-style (v1) directories as well. (Only directory mirrors care about this.) Tor will use this server as an authority for hidden service information if the “hs” flag is set, or if the “v1″ flag is set and the “no-hs” flag isnot set. Tor will use this authority as a bridge authoritative directory if the “bridge” flag is set. If a flag “orport=port” is given, Tor will use the given port when opening encrypted tunnels to the dirserver. Lastly, if a flag “v3ident=fp” is given, the dirserver is a v3 directory authority whose v3 long-term signing key has the fingerprintfp.

If no dirserver line is given, Tor will use the default directory servers. NOTE: this option is intended for setting up a private Tor network with its own directory authorities. If you use it, you will be distinguishable from other users, because you won’t believe the same authorities they do.

DynamicDHGroups 0|1
If this option is set to 1, when running as a server, generate our own Diffie-Hellman group instead of using the one from Apache’s mod_ssl. This option may help circumvent censorship based on static Diffie-Hellman parameters. (Default: 0)
AlternateDirAuthority [nickname] [flags] address:port fingerprint

AlternateHSAuthority [nickname] [flags] address:port fingerprint

AlternateBridgeAuthority [nickname] [flags] address:port fingerprint
These options behave as DirServer, but they replace fewer of the default directory authorities. Using AlternateDirAuthority replaces the default Tor directory authorities, but leaves the default hidden service authorities and bridge authorities in place. Similarly, AlternateHSAuthority replaces the default hidden service authorities, but not the directory or bridge authorities; and AlternateBridgeAuthority replaces the default bridge authority, but leaves the directory and hidden service authorities alone.
DisableAllSwap 0|1
If set to 1, Tor will attempt to lock all current and future memory pages, so that memory cannot be paged out. Windows, OS X and Solaris are currently not supported. We believe that this feature works on modern Gnu/Linux distributions, and that it should work on *BSD systems (untested). This option requires that you start your Tor as root, and you should use the User option to properly reduce Tor’s privileges. (Default: 0)
DisableDebuggerAttachment 0|1
If set to 1, Tor will attempt to prevent basic debugging attachment attempts by other processes. It has no impact for users who wish to attach if they have CAP_SYS_PTRACE or if they are root. We believe that this feature works on modern Gnu/Linux distributions, and that it may also work on *BSD systems (untested). Some modern Gnu/Linux systems such as Ubuntu have the kernel.yama.ptrace_scope sysctl and by default enable it as an attempt to limit the PTRACE scope for all user processes by default. This feature will attempt to limit the PTRACE scope for Tor specifically – it will not attempt to alter the system wide ptrace scope as it may not even exist. If you wish to attach to Tor with a debugger such as gdb or strace you will want to set this to 0 for the duration of your debugging. Normal users should leave it on. Disabling this option while Tor is running is prohibited. (Default: 1)
FetchDirInfoEarly 0|1
If set to 1, Tor will always fetch directory information like other directory caches, even if you don’t meet the normal criteria for fetching early. Normal users should leave it off. (Default: 0)
FetchDirInfoExtraEarly 0|1
If set to 1, Tor will fetch directory information before other directory caches. It will attempt to download directory information closer to the start of the consensus period. Normal users should leave it off. (Default: 0)
FetchHidServDescriptors 0|1
If set to 0, Tor will never fetch any hidden service descriptors from the rendezvous directories. This option is only useful if you’re using a Tor controller that handles hidden service fetches for you. (Default: 1)
FetchServerDescriptors 0|1
If set to 0, Tor will never fetch any network status summaries or server descriptors from the directory servers. This option is only useful if you’re using a Tor controller that handles directory fetches for you. (Default: 1)
FetchUselessDescriptors 0|1
If set to 1, Tor will fetch every non-obsolete descriptor from the authorities that it hears about. Otherwise, it will avoid fetching useless descriptors, for example for routers that are not running. This option is useful if you’re using the contributed “exitlist” script to enumerate Tor nodes that exit to certain addresses. (Default: 0)
HTTPProxy host[:port]
Tor will make all its directory requests through this host:port (or host:80 if port is not specified), rather than connecting directly to any directory servers.
HTTPProxyAuthenticator username:password
If defined, Tor will use this username:password for Basic HTTP proxy authentication, as in RFC 2617. This is currently the only form of HTTP proxy authentication that Tor supports; feel free to submit a patch if you want it to support others.
HTTPSProxy host[:port]
Tor will make all its OR (SSL) connections through this host:port (or host:443 if port is not specified), via HTTP CONNECT rather than connecting directly to servers. You may want to set FascistFirewall to restrict the set of ports you might try to connect to, if your HTTPS proxy only allows connecting to certain ports.
HTTPSProxyAuthenticator username:password
If defined, Tor will use this username:password for Basic HTTPS proxy authentication, as in RFC 2617. This is currently the only form of HTTPS proxy authentication that Tor supports; feel free to submit a patch if you want it to support others.
Socks4Proxy host[:port]
Tor will make all OR connections through the SOCKS 4 proxy at host:port (or host:1080 if port is not specified).
Socks5Proxy host[:port]
Tor will make all OR connections through the SOCKS 5 proxy at host:port (or host:1080 if port is not specified).
Socks5ProxyUsername username

Socks5ProxyPassword password
If defined, authenticate to the SOCKS 5 server using username and password in accordance to RFC 1929. Both username and password must be between 1 and 255 characters.
KeepalivePeriod NUM
To keep firewalls from expiring connections, send a padding keepalive cell every NUM seconds on open connections that are in use. If the connection has no open circuits, it will instead be closed after NUM seconds of idleness. (Default: 5 minutes)
Log minSeverity[-maxSeverity] stderr|stdout|syslog
Send all messages between minSeverity and maxSeverity to the standard output stream, the standard error stream, or to the system log. (The “syslog” value is only supported on Unix.) Recognized severity levels are debug, info, notice, warn, and err. We advise using “notice” in most cases, since anything more verbose may provide sensitive information to an attacker who obtains the logs. If only one severity level is given, all messages of that level or higher will be sent to the listed destination.
Log minSeverity[-maxSeverity] file FILENAME
As above, but send log messages to the listed filename. The “Log” option may appear more than once in a configuration file. Messages are sent to all the logs that match their severity level.
Log [domain,…]minSeverity[-maxSeverity] … file FILENAME

Log [domain,…]minSeverity[-maxSeverity] … stderr|stdout|syslog
As above, but select messages by range of log severity and by a set of “logging domains”. Each logging domain corresponds to an area of functionality inside Tor. You can specify any number of severity ranges for a single log statement, each of them prefixed by a comma-separated list of logging domains. You can prefix a domain with ~ to indicate negation, and use * to indicate “all domains”. If you specify a severity range without a list of domains, it matches all domains.

This is an advanced feature which is most useful for debugging one or two of Tor’s subsystems at a time.

The currently recognized domains are: general, crypto, net, config, fs, protocol, mm, http, app, control, circ, rend, bug, dir, dirserv, or, edge, acct, hist, and handshake. Domain names are case-insensitive.

For example, “Log [handshake]debug [~net,~mm]info notice stdout” sends to stdout: all handshake messages of any severity, all info-and-higher messages from domains other than networking and memory management, and all messages of severity notice or higher.

LogMessageDomains 0|1
If 1, Tor includes message domains with each log message. Every log message currently has at least one domain; most currently have exactly one. This doesn’t affect controller log messages. (Default: 0)
OutboundBindAddress IP
Make all outbound connections originate from the IP address specified. This is only useful when you have multiple network interfaces, and you want all of Tor’s outgoing connections to use a single one. This setting will be ignored for connections to the loopback addresses (127.0.0.0/8 and ::1).
PidFile FILE
On startup, write our PID to FILE. On clean shutdown, remove FILE.
ProtocolWarnings 0|1
If 1, Tor will log with severity ‘warn’ various cases of other parties not following the Tor specification. Otherwise, they are logged with severity ‘info’. (Default: 0)
RunAsDaemon 0|1
If 1, Tor forks and daemonizes to the background. This option has no effect on Windows; instead you should use the –service command-line option. (Default: 0)
LogTimeGranularity NUM
Set the resolution of timestamps in Tor’s logs to NUM milliseconds. NUM must be positive and either a divisor or a multiple of 1 second. Note that this option only controls the granularity written by Tor to a file or console log. Tor does not (for example) “batch up” log messages to affect times logged by a controller, times attached to syslog messages, or the mtime fields on log files. (Default: 1 second)
SafeLogging 0|1|relay
Tor can scrub potentially sensitive strings from log messages (e.g. addresses) by replacing them with the string [scrubbed]. This way logs can still be useful, but they don’t leave behind personally identifying information about what sites a user might have visited.

If this option is set to 0, Tor will not perform any scrubbing, if it is set to 1, all potentially sensitive strings are replaced. If it is set to relay, all log messages generated when acting as a relay are sanitized, but all messages generated when acting as a client are not. (Default: 1)

User UID
On startup, setuid to this user and setgid to their primary group.
HardwareAccel 0|1
If non-zero, try to use built-in (static) crypto hardware acceleration when available. (Default: 0)
AccelName NAME
When using OpenSSL hardware crypto acceleration attempt to load the dynamic engine of this name. This must be used for any dynamic hardware engine. Names can be verified with the openssl engine command.
AccelDir DIR
Specify this option if using dynamic hardware acceleration and the engine implementation library resides somewhere other than the OpenSSL default.
AvoidDiskWrites 0|1
If non-zero, try to write to disk less frequently than we would otherwise. This is useful when running on flash memory or other media that support only a limited number of writes. (Default: 0)
TunnelDirConns 0|1
If non-zero, when a directory server we contact supports it, we will build a one-hop circuit and make an encrypted connection via its ORPort. (Default: 1)
PreferTunneledDirConns 0|1
If non-zero, we will avoid directory servers that don’t support tunneled directory connections, when possible. (Default: 1)
CircuitPriorityHalflife NUM1
If this value is set, we override the default algorithm for choosing which circuit’s cell to deliver or relay next. When the value is 0, we round-robin between the active circuits on a connection, delivering one cell from each in turn. When the value is positive, we prefer delivering cells from whichever connection has the lowest weighted cell count, where cells are weighted exponentially according to the supplied CircuitPriorityHalflife value (in seconds). If this option is not set at all, we use the behavior recommended in the current consensus networkstatus. This is an advanced option; you generally shouldn’t have to mess with it. (Default: not set)
DisableIOCP 0|1
If Tor was built to use the Libevent’s “bufferevents” networking code and you’re running on Windows, setting this option to 1 will tell Libevent not to use the Windows IOCP networking API. (Default: 1)
UserspaceIOCPBuffers 0|1
If IOCP is enabled (see DisableIOCP above), setting this option to 1 will tell Tor to disable kernel-space TCP buffers, in order to avoid needless copy operations and try not to run out of non-paged RAM. This feature is experimental; don’t use it yet unless you’re eager to help tracking down bugs. (Default: 0)
_UseFilteringSSLBufferevents 0|1
Tells Tor to do its SSL communication using a chain of bufferevents: one for SSL and one for networking. This option has no effect if bufferevents are disabled (in which case it can’t turn on), or if IOCP bufferevents are enabled (in which case it can’t turn off). This option is useful for debugging only; most users shouldn’t touch it. (Default: 0)
CountPrivateBandwidth 0|1
If this option is set, then Tor’s rate-limiting applies not only to remote connections, but also to connections to private addresses like 127.0.0.1 or 10.0.0.1. This is mostly useful for debugging rate-limiting. (Default: 0)
CLIENT OPTIONS
The following options are useful only for clients (that is, if SocksPort, TransPort, DNSPort, or NATDPort is non-zero):

AllowInvalidNodes entry|exit|middle|introduction|rendezvous|…
If some Tor servers are obviously not working right, the directory authorities can manually mark them as invalid, meaning that it’s not recommended you use them for entry or exit positions in your circuits. You can opt to use them in some circuit positions, though. The default is “middle,rendezvous”, and other choices are not advised.
ExcludeSingleHopRelays 0|1
This option controls whether circuits built by Tor will include relays with the AllowSingleHopExits flag set to true. If ExcludeSingleHopRelays is set to 0, these relays will be included. Note that these relays might be at higher risk of being seized or observed, so they are not normally included. Also note that relatively few clients turn off this option, so using these relays might make your client stand out. (Default: 1)
Bridge [transport] IP:ORPort [fingerprint]
When set along with UseBridges, instructs Tor to use the relay at “IP:ORPort” as a “bridge” relaying into the Tor network. If “fingerprint” is provided (using the same format as for DirServer), we will verify that the relay running at that location has the right fingerprint. We also use fingerprint to look up the bridge descriptor at the bridge authority, if it’s provided and if UpdateBridgesFromAuthority is set too.

If “transport” is provided, and matches to a ClientTransportPlugin line, we use that pluggable transports proxy to transfer data to the bridge.

LearnCircuitBuildTimeout 0|1
If 0, CircuitBuildTimeout adaptive learning is disabled. (Default: 1)
CircuitBuildTimeout NUM
Try for at most NUM seconds when building circuits. If the circuit isn’t open in that time, give up on it. If LearnCircuitBuildTimeout is 1, this value serves as the initial value to use before a timeout is learned. If LearnCircuitBuildTimeout is 0, this value is the only value used. (Default: 60 seconds)
CircuitIdleTimeout NUM
If we have kept a clean (never used) circuit around for NUM seconds, then close it. This way when the Tor client is entirely idle, it can expire all of its circuits, and then expire its TLS connections. Also, if we end up making a circuit that is not useful for exiting any of the requests we’re receiving, it won’t forever take up a slot in the circuit list. (Default: 1 hour)
CircuitStreamTimeout NUM
If non-zero, this option overrides our internal timeout schedule for how many seconds until we detach a stream from a circuit and try a new circuit. If your network is particularly slow, you might want to set this to a number like 60. (Default: 0)
ClientOnly 0|1
If set to 1, Tor will under no circumstances run as a relay or serve directory requests. This config option is mostly meaningless: we added it back when we were considering having Tor clients auto-promote themselves to being relays if they were stable and fast enough. The current behavior is simply that Tor is a client unless ORPort or DirPort are configured. (Default: 0)
ExcludeNodes node,node,…
A list of identity fingerprints, nicknames, country codes and address patterns of nodes to avoid when building a circuit. (Example: ExcludeNodes SlowServer, ABCD1234CDEF5678ABCD1234CDEF5678ABCD1234, {cc}, 255.254.0.0/8)

By default, this option is treated as a preference that Tor is allowed to override in order to keep working. For example, if you try to connect to a hidden service, but you have excluded all of the hidden service’s introduction points, Tor will connect to one of them anyway. If you do not want this behavior, set the StrictNodes option (documented below).

Note also that if you are a relay, this (and the other node selection options below) only affects your own circuits that Tor builds for you. Clients can still build circuits through you to any node. Controllers can tell Tor to build circuits through any node.

ExcludeExitNodes node,node,…
A list of identity fingerprints, nicknames, country codes and address patterns of nodes to never use when picking an exit node—that is, a node that delivers traffic for you outside the Tor network. Note that any node listed in ExcludeNodes is automatically considered to be part of this list too. See also the caveats on the “ExitNodes” option below.
ExitNodes node,node,…
A list of identity fingerprints, nicknames, country codes and address patterns of nodes to use as exit node—that is, a node that delivers traffic for you outside the Tor network.

Note that if you list too few nodes here, or if you exclude too many exit nodes with ExcludeExitNodes, you can degrade functionality. For example, if none of the exits you list allows traffic on port 80 or 443, you won’t be able to browse the web.

Note also that not every circuit is used to deliver traffic outside of the Tor network. It is normal to see non-exit circuits (such as those used to connect to hidden services, those that do directory fetches, those used for relay reachability self-tests, and so on) that end at a non-exit node. To keep a node from being used entirely, see ExcludeNodes and StrictNodes.

The ExcludeNodes option overrides this option: any node listed in both ExitNodes and ExcludeNodes is treated as excluded.

The .exit address notation, if enabled via AllowDotExit, overrides this option.

EntryNodes node,node,…
A list of identity fingerprints, nicknames, and country codes of nodes to use for the first hop in your normal circuits. Normal circuits include all circuits except for direct connections to directory servers. The Bridge option overrides this option; if you have configured bridges and UseBridges is 1, the Bridges are used as your entry nodes.

The ExcludeNodes option overrides this option: any node listed in both EntryNodes and ExcludeNodes is treated as excluded.

StrictNodes 0|1
If StrictNodes is set to 1, Tor will treat the ExcludeNodes option as a requirement to follow for all the circuits you generate, even if doing so will break functionality for you. If StrictNodes is set to 0, Tor will still try to avoid nodes in the ExcludeNodes list, but it will err on the side of avoiding unexpected errors. Specifically, StrictNodes 0 tells Tor that it is okay to use an excluded node when it is necessary to perform relay reachability self-tests, connect to a hidden service, provide a hidden service to a client, fulfill a .exit request, upload directory information, or download directory information. (Default: 0)
FascistFirewall 0|1
If 1, Tor will only create outgoing connections to ORs running on ports that your firewall allows (defaults to 80 and 443; see FirewallPorts). This will allow you to run Tor as a client behind a firewall with restrictive policies, but will not allow you to run as a server behind such a firewall. If you prefer more fine-grained control, use ReachableAddresses instead.
FirewallPorts PORTS
A list of ports that your firewall allows you to connect to. Only used when FascistFirewall is set. This option is deprecated; use ReachableAddresses instead. (Default: 80, 443)
ReachableAddresses ADDR[/MASK][:PORT]…
A comma-separated list of IP addresses and ports that your firewall allows you to connect to. The format is as for the addresses in ExitPolicy, except that “accept” is understood unless “reject” is explicitly provided. For example, ‘ReachableAddresses 99.0.0.0/8, reject 18.0.0.0/8:80, accept *:80′ means that your firewall allows connections to everything inside net 99, rejects port 80 connections to net 18, and accepts connections to port 80 otherwise. (Default: ‘accept *:*’.)
ReachableDirAddresses ADDR[/MASK][:PORT]…
Like ReachableAddresses, a list of addresses and ports. Tor will obey these restrictions when fetching directory information, using standard HTTP GET requests. If not set explicitly then the value of ReachableAddresses is used. If HTTPProxy is set then these connections will go through that proxy.
ReachableORAddresses ADDR[/MASK][:PORT]…
Like ReachableAddresses, a list of addresses and ports. Tor will obey these restrictions when connecting to Onion Routers, using TLS/SSL. If not set explicitly then the value of ReachableAddresses is used. If HTTPSProxy is set then these connections will go through that proxy.

The separation between ReachableORAddresses and ReachableDirAddresses is only interesting when you are connecting through proxies (see HTTPProxy and HTTPSProxy). Most proxies limit TLS connections (which Tor uses to connect to Onion Routers) to port 443, and some limit HTTP GET requests (which Tor uses for fetching directory information) to port 80.

HidServAuth onion-address auth-cookie [service-name]
Client authorization for a hidden service. Valid onion addresses contain 16 characters in a-z2-7 plus “.onion”, and valid auth cookies contain 22 characters in A-Za-z0-9+/. The service name is only used for internal purposes, e.g., for Tor controllers. This option may be used multiple times for different hidden services. If a hidden service uses authorization and this option is not set, the hidden service is not accessible. Hidden services can be configured to require authorization using the HiddenServiceAuthorizeClient option.
CloseHSClientCircuitsImmediatelyOnTimeout 0|1
If 1, Tor will close unfinished hidden service client circuits which have not moved closer to connecting to their destination hidden service when their internal state has not changed for the duration of the current circuit-build timeout. Otherwise, such circuits will be left open, in the hope that they will finish connecting to their destination hidden services. In either case, another set of introduction and rendezvous circuits for the same destination hidden service will be launched. (Default: 0)
CloseHSServiceRendCircuitsImmediatelyOnTimeout 0|1
If 1, Tor will close unfinished hidden-service-side rendezvous circuits after the current circuit-build timeout. Otherwise, such circuits will be left open, in the hope that they will finish connecting to their destinations. In either case, another rendezvous circuit for the same destination client will be launched. (Default: 0)
LongLivedPorts PORTS
A list of ports for services that tend to have long-running connections (e.g. chat and interactive shells). Circuits for streams that use these ports will contain only high-uptime nodes, to reduce the chance that a node will go down before the stream is finished. Note that the list is also honored for circuits (both client and service side) involving hidden services whose virtual port is in this list. (Default: 21, 22, 706, 1863, 5050, 5190, 5222, 5223, 6523, 6667, 6697, 8300)
MapAddress address newaddress
When a request for address arrives to Tor, it will transform to newaddress before processing it. For example, if you always want connections to www.example.com to exit via torserver (where torserver is the nickname of the server), use “MapAddress www.example.com www.example.com.torserver.exit”. If the value is prefixed with a “*.”, matches an entire domain. For example, if you always want connections to example.com and any if its subdomains to exit via torserver (where torserver is the nickname of the server), use “MapAddress *.example.com *.example.com.torserver.exit”. (Note the leading “*.” in each part of the directive.) You can also redirect all subdomains of a domain to a single address. For example, “MapAddress *.example.com www.example.com”.

NOTES:

When evaluating MapAddress expressions Tor stops when it hits the most recently added expression that matches the requested address. So if you have the following in your torrc, www.torproject.org will map to 1.1.1.1:
MapAddress www.torproject.org 2.2.2.2
MapAddress www.torproject.org 1.1.1.1
Tor evaluates the MapAddress configuration until it finds no matches. So if you have the following in your torrc, www.torproject.org will map to 2.2.2.2:
MapAddress 1.1.1.1 2.2.2.2
MapAddress www.torproject.org 1.1.1.1
The following MapAddress expression is invalid (and will be ignored) because you cannot map from a specific address to a wildcard address:
MapAddress www.torproject.org *.torproject.org.torserver.exit
Using a wildcard to match only part of a string (as in *ample.com) is also invalid.
NewCircuitPeriod NUM
Every NUM seconds consider whether to build a new circuit. (Default: 30 seconds)
MaxCircuitDirtiness NUM
Feel free to reuse a circuit that was first used at most NUM seconds ago, but never attach a new stream to a circuit that is too old. For hidden services, this applies to the last time a circuit was used, not the first. (Default: 10 minutes)
MaxClientCircuitsPending NUM
Do not allow more than NUM circuits to be pending at a time for handling client streams. A circuit is pending if we have begun constructing it, but it has not yet been completely constructed. (Default: 32)
NodeFamily node,node,…
The Tor servers, defined by their identity fingerprints or nicknames, constitute a “family” of similar or co-administered servers, so never use any two of them in the same circuit. Defining a NodeFamily is only needed when a server doesn’t list the family itself (with MyFamily). This option can be used multiple times. In addition to nodes, you can also list IP address and ranges and country codes in {curly braces}.
EnforceDistinctSubnets 0|1
If 1, Tor will not put two servers whose IP addresses are “too close” on the same circuit. Currently, two addresses are “too close” if they lie in the same /16 range. (Default: 1)
SOCKSPort [address:]port|auto [isolation flags]
Open this port to listen for connections from SOCKS-speaking applications. Set this to 0 if you don’t want to allow application connections via SOCKS. Set it to “auto” to have Tor pick a port for you. This directive can be specified multiple times to bind to multiple addresses/ports. (Default: 9050)

The isolation flags arguments give Tor rules for which streams received on this SOCKSPort are allowed to share circuits with one another. Recognized isolation flags are:

IsolateClientAddr
Don’t share circuits with streams from a different client address. (On by default and strongly recommended; you can disable it with NoIsolateClientAddr.)
IsolateSOCKSAuth
Don’t share circuits with streams for which different SOCKS authentication was provided. (On by default; you can disable it with NoIsolateSOCKSAuth.)
IsolateClientProtocol
Don’t share circuits with streams using a different protocol. (SOCKS 4, SOCKS 5, TransPort connections, NATDPort connections, and DNSPort requests are all considered to be different protocols.)
IsolateDestPort
Don’t share circuits with streams targetting a different destination port.
IsolateDestAddr
Don’t share circuits with streams targetting a different destination address.
SessionGroup=INT
If no other isolation rules would prevent it, allow streams on this port to share circuits with streams from every other port with the same session group. (By default, streams received on different SOCKSPorts, TransPorts, etc are always isolated from one another. This option overrides that behavior.)
SOCKSListenAddress IP[:PORT]
Bind to this address to listen for connections from Socks-speaking applications. (Default: 127.0.0.1) You can also specify a port (e.g. 192.168.0.1:9100). This directive can be specified multiple times to bind to multiple addresses/ports. (DEPRECATED: As of 0.2.3.x-alpha, you can now use multiple SOCKSPort entries, and provide addresses for SOCKSPort entries, so SOCKSListenAddress no longer has a purpose. For backward compatibility, SOCKSListenAddress is only allowed when SOCKSPort is just a port number.)
SocksPolicy policy,policy,…
Set an entrance policy for this server, to limit who can connect to the SocksPort and DNSPort ports. The policies have the same form as exit policies below.
SocksTimeout NUM
Let a socks connection wait NUM seconds handshaking, and NUM seconds unattached waiting for an appropriate circuit, before we fail it. (Default: 2 minutes)
TokenBucketRefillInterval NUM [msec|second]
Set the refill interval of Tor’s token bucket to NUM milliseconds. NUM must be between 1 and 1000, inclusive. Note that the configured bandwidth limits are still expressed in bytes per second: this option only affects the frequency with which Tor checks to see whether previously exhausted connections may read again. (Default: 100 msec)
TrackHostExits host,.domain,…
For each value in the comma separated list, Tor will track recent connections to hosts that match this value and attempt to reuse the same exit node for each. If the value is prepended with a ‘.’, it is treated as matching an entire domain. If one of the values is just a ‘.’, it means match everything. This option is useful if you frequently connect to sites that will expire all your authentication cookies (i.e. log you out) if your IP address changes. Note that this option does have the disadvantage of making it more clear that a given history is associated with a single user. However, most people who would wish to observe this will observe it through cookies or other protocol-specific means anyhow.
TrackHostExitsExpire NUM
Since exit servers go up and down, it is desirable to expire the association between host and exit server after NUM seconds. The default is 1800 seconds (30 minutes).
UpdateBridgesFromAuthority 0|1
When set (along with UseBridges), Tor will try to fetch bridge descriptors from the configured bridge authorities when feasible. It will fall back to a direct request if the authority responds with a 404. (Default: 0)
UseBridges 0|1
When set, Tor will fetch descriptors for each bridge listed in the “Bridge” config lines, and use these relays as both entry guards and directory guards. (Default: 0)
UseEntryGuards 0|1
If this option is set to 1, we pick a few long-term entry servers, and try to stick with them. This is desirable because constantly changing servers increases the odds that an adversary who owns some servers will observe a fraction of your paths. (Default: 1)
NumEntryGuards NUM
If UseEntryGuards is set to 1, we will try to pick a total of NUM routers as long-term entries for our circuits. (Default: 3)
SafeSocks 0|1
When this option is enabled, Tor will reject application connections that use unsafe variants of the socks protocol — ones that only provide an IP address, meaning the application is doing a DNS resolve first. Specifically, these are socks4 and socks5 when not doing remote DNS. (Default: 0)
TestSocks 0|1
When this option is enabled, Tor will make a notice-level log entry for each connection to the Socks port indicating whether the request used a safe socks protocol or an unsafe one (see above entry on SafeSocks). This helps to determine whether an application using Tor is possibly leaking DNS requests. (Default: 0)
WarnUnsafeSocks 0|1
When this option is enabled, Tor will warn whenever a request is received that only contains an IP address instead of a hostname. Allowing applications to do DNS resolves themselves is usually a bad idea and can leak your location to attackers. (Default: 1)
VirtualAddrNetwork Address/bits
When Tor needs to assign a virtual (unused) address because of a MAPADDRESS command from the controller or the AutomapHostsOnResolve feature, Tor picks an unassigned address from this range. (Default: 127.192.0.0/10)

When providing proxy server service to a network of computers using a tool like dns-proxy-tor, change this address to “10.192.0.0/10″ or “172.16.0.0/12″. The default VirtualAddrNetwork address range on a properly configured machine will route to the loopback interface. For local use, no change to the default VirtualAddrNetwork setting is needed.

AllowNonRFC953Hostnames 0|1
When this option is disabled, Tor blocks hostnames containing illegal characters (like @ and ::__IHACKLOG_REMOTE_IMAGE_AUTODOWN_BLOCK__::0 rather than sending them to an exit node to be resolved. This helps trap accidental attempts to resolve URLs and so on. (Default: 0)
AllowDotExit 0|1
If enabled, we convert “www.google.com.foo.exit” addresses on the SocksPort/TransPort/NATDPort into “www.google.com” addresses that exit from the node “foo”. Disabled by default since attacking websites and exit relays can use it to manipulate your path selection. (Default: 0)
FastFirstHopPK 0|1
When this option is disabled, Tor uses the public key step for the first hop of creating circuits. Skipping it is generally safe since we have already used TLS to authenticate the relay and to establish forward-secure keys. Turning this option off makes circuit building slower.

Note that Tor will always use the public key step for the first hop if it’s operating as a relay, and it will never use the public key step if it doesn’t yet know the onion key of the first hop. (Default: 1)

TransPort [address:]port|auto [isolation flags]
Open this port to listen for transparent proxy connections. Set this to 0 if you don’t want to allow transparent proxy connections. Set the port to “auto” to have Tor pick a port for you. This directive can be specified multiple times to bind to multiple addresses/ports. See SOCKSPort for an explanation of isolation flags.

TransPort requires OS support for transparent proxies, such as BSDs’ pf or Linux’s IPTables. If you’re planning to use Tor as a transparent proxy for a network, you’ll want to examine and change VirtualAddrNetwork from the default setting. You’ll also want to set the TransListenAddress option for the network you’d like to proxy. (Default: 0)

TransListenAddress IP[:PORT]
Bind to this address to listen for transparent proxy connections. (Default: 127.0.0.1). This is useful for exporting a transparent proxy server to an entire network. (DEPRECATED: As of 0.2.3.x-alpha, you can now use multiple TransPort entries, and provide addresses for TransPort entries, so TransListenAddress no longer has a purpose. For backward compatibility, TransListenAddress is only allowed when TransPort is just a port number.)
NATDPort [address:]port|auto [isolation flags]
Open this port to listen for connections from old versions of ipfw (as included in old versions of FreeBSD, etc) using the NATD protocol. Use 0 if you don’t want to allow NATD connections. Set the port to “auto” to have Tor pick a port for you. This directive can be specified multiple times to bind to multiple addresses/ports. See SOCKSPort for an explanation of isolation flags.

This option is only for people who cannot use TransPort. (Default: 0)

NATDListenAddress IP[:PORT]
Bind to this address to listen for NATD connections. (DEPRECATED: As of 0.2.3.x-alpha, you can now use multiple NATDPort entries, and provide addresses for NATDPort entries, so NATDListenAddress no longer has a purpose. For backward compatibility, NATDListenAddress is only allowed when NATDPort is just a port number.)
AutomapHostsOnResolve 0|1
When this option is enabled, and we get a request to resolve an address that ends with one of the suffixes inAutomapHostsSuffixes, we map an unused virtual address to that address, and return the new virtual address. This is handy for making “.onion” addresses work with applications that resolve an address and then connect to it. (Default: 0)
AutomapHostsSuffixes SUFFIX,SUFFIX,…
A comma-separated list of suffixes to use with AutomapHostsOnResolve. The “.” suffix is equivalent to “all addresses.” (Default: .exit,.onion).
DNSPort [address:]port|auto [isolation flags]
If non-zero, open this port to listen for UDP DNS requests, and resolve them anonymously. Set the port to “auto” to have Tor pick a port for you. This directive can be specified multiple times to bind to multiple addresses/ports. See SOCKSPort for an explanation of isolation flags. (Default: 0)
DNSListenAddress IP[:PORT]
Bind to this address to listen for DNS connections. (DEPRECATED: As of 0.2.3.x-alpha, you can now use multiple DNSPort entries, and provide addresses for DNSPort entries, so DNSListenAddress no longer has a purpose. For backward compatibility, DNSListenAddress is only allowed when DNSPort is just a port number.)
ClientDNSRejectInternalAddresses 0|1
If true, Tor does not believe any anonymously retrieved DNS answer that tells it that an address resolves to an internal address (like 127.0.0.1 or 192.168.0.1). This option prevents certain browser-based attacks; don’t turn it off unless you know what you’re doing. (Default: 1)
ClientRejectInternalAddresses 0|1
If true, Tor does not try to fulfill requests to connect to an internal address (like 127.0.0.1 or 192.168.0.1) unless a exit node is specifically requested (for example, via a .exit hostname, or a controller request). (Default: 1)
DownloadExtraInfo 0|1
If true, Tor downloads and caches “extra-info” documents. These documents contain information about servers other than the information in their regular router descriptors. Tor does not use this information for anything itself; to save bandwidth, leave this option turned off. (Default: 0)
FallbackNetworkstatusFile FILENAME
If Tor doesn’t have a cached networkstatus file, it starts out using this one instead. Even if this file is out of date, Tor can still use it to learn about directory mirrors, so it doesn’t need to put load on the authorities. (Default: None)
WarnPlaintextPorts port,port,…
Tells Tor to issue a warnings whenever the user tries to make an anonymous connection to one of these ports. This option is designed to alert users to services that risk sending passwords in the clear. (Default: 23,109,110,143)
RejectPlaintextPorts port,port,…
Like WarnPlaintextPorts, but instead of warning about risky port uses, Tor will instead refuse to make the connection. (Default: None)
AllowSingleHopCircuits 0|1
When this option is set, the attached Tor controller can use relays that have the AllowSingleHopExits option turned on to build one-hop Tor connections. (Default: 0)
OptimisticData 0|1|auto
When this option is set, and Tor is using an exit node that supports the feature, it will try optimistically to send data to the exit node without waiting for the exit node to report whether the connection succeeded. This can save a round-trip time for protocols like HTTP where the client talks first. If OptimisticData is set to auto, Tor will look at the UseOptimisticData parameter in the networkstatus. (Default: auto)
Tor2webMode 0|1
When this option is set, Tor connects to hidden services non-anonymously. This option also disables client connections to non-hidden-service hostnames through Tor. It must only be used when running a tor2web Hidden Service web proxy. To enable this option the compile time flag –enable-tor2webmode must be specified. (Default: 0)
UseMicrodescriptors 0|1|auto
Microdescriptors are a smaller version of the information that Tor needs in order to build its circuits. Using microdescriptors makes Tor clients download less directory information, thus saving bandwidth. Directory caches need to fetch regular descriptors and microdescriptors, so this option doesn’t save any bandwidth for them. If this option is set to “auto” (recommended) then it is on for all clients that do not set FetchUselessDescriptors. (Default: auto)
PathBiasCircThreshold NUM

PathBiasNoticeRate NUM

PathBiasDisableRate NUM

PathBiasScaleThreshold NUM

PathBiasScaleFactor NUM
These options override the default behavior of Tor’s (currently experimental) path bias detection algorithm. To try to find broken or misbehaving guard nodes, Tor looks for nodes where more than a certain fraction of circuits through that node fail after the first hop. The PathBiasCircThreshold option controls how many circuits we need to build through a guard before we make these checks. The PathBiasNoticeRate and PathBiasDisableRate options control what fraction of circuits must succeed through a guard so we won’t warn about it or disable it, respectively. When we have seen more than PathBiasScaleThreshold circuits through a guard, we divide our observations by PathBiasScaleFactor, so that new observations don’t get swamped by old ones.

By default, or if a negative value is provided for one of these options, Tor uses reasonable defaults from the networkstatus consensus document. If no defaults are available there, these options default to 20, .70, 0.0, 200, and 4 respectively.

SERVER OPTIONS
The following options are useful only for servers (that is, if ORPort is non-zero):

Address address
The IP address or fully qualified domain name of this server (e.g. moria.mit.edu). You can leave this unset, and Tor will guess your IP address. This IP address is the one used to tell clients and other servers where to find your Tor server; it doesn’t affect the IP that your Tor client binds to. To bind to a different address, use the *ListenAddress and OutboundBindAddress options.
AllowSingleHopExits 0|1
This option controls whether clients can use this server as a single hop proxy. If set to 1, clients can use this server as an exit even if it is the only hop in the circuit. Note that most clients will refuse to use servers that set this option, since most clients have ExcludeSingleHopRelays set. (Default: 0)
AssumeReachable 0|1
This option is used when bootstrapping a new Tor network. If set to 1, don’t do self-reachability testing; just upload your server descriptor immediately. If AuthoritativeDirectory is also set, this option instructs the dirserver to bypass remote reachability testing too and list all connected servers as running.
BridgeRelay 0|1
Sets the relay to act as a “bridge” with respect to relaying connections from bridge users to the Tor network. It mainly causes Tor to publish a server descriptor to the bridge database, rather than publishing a relay descriptor to the public directory authorities.
ContactInfo email_address
Administrative contact information for server. This line might get picked up by spam harvesters, so you may want to obscure the fact that it’s an email address.
ExitPolicy policy,policy,…
Set an exit policy for this server. Each policy is of the form “accept|reject ADDR[/MASK][:PORT]“. If /MASK is omitted then this policy just applies to the host given. Instead of giving a host or network you can also use “*” to denote the universe (0.0.0.0/0). PORT can be a single port number, an interval of ports “FROM_PORT-TO_PORT“, or “*”. If PORT is omitted, that means “*”.

For example, “accept 18.7.22.69:*,reject 18.0.0.0/8:*,accept *:*” would reject any traffic destined for MIT except for web.mit.edu, and accept anything else.

To specify all internal and link-local networks (including 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8, 192.168.0.0/16, 10.0.0.0/8, and 172.16.0.0/12), you can use the “private” alias instead of an address. These addresses are rejected by default (at the beginning of your exit policy), along with your public IP address, unless you set the ExitPolicyRejectPrivate config option to 0. For example, once you’ve done that, you could allow HTTP to 127.0.0.1 and block all other connections to internal networks with “accept 127.0.0.1:80,reject private:*”, though that may also allow connections to your own computer that are addressed to its public (external) IP address. See RFC 1918 and RFC 3330 for more details about internal and reserved IP address space.

This directive can be specified multiple times so you don’t have to put it all on one line.

Policies are considered first to last, and the first match wins. If you want to _replace_ the default exit policy, end your exit policy with either a reject *:* or an accept *:*. Otherwise, you’re _augmenting_ (prepending to) the default exit policy. The default exit policy is:

reject *:25
reject *:119
reject *:135-139
reject *:445
reject *:563
reject *:1214
reject *:4661-4666
reject *:6346-6429
reject *:6699
reject *:6881-6999
accept *:*
ExitPolicyRejectPrivate 0|1
Reject all private (local) networks, along with your own public IP address, at the beginning of your exit policy. See above entry on ExitPolicy. (Default: 1)
MaxOnionsPending NUM
If you have more than this number of onionskins queued for decrypt, reject new ones. (Default: 100)
MyFamily node,node,…
Declare that this Tor server is controlled or administered by a group or organization identical or similar to that of the other servers, defined by their identity fingerprints or nicknames. When two servers both declare that they are in the same ‘family’, Tor clients will not use them in the same circuit. (Each server only needs to list the other servers in its family; it doesn’t need to list itself, but it won’t hurt.) Do not list any bridge relay as it would compromise its concealment.
Nickname name
Set the server’s nickname to ‘name’. Nicknames must be between 1 and 19 characters inclusive, and must contain only the characters [a-zA-Z0-9].
NumCPUs num
How many processes to use at once for decrypting onionskins and other parallelizable operations. If this is set to 0, Tor will try to detect how many CPUs you have, defaulting to 1 if it can’t tell. (Default: 0)
ORPort [address:]PORT|auto [flags]
Advertise this port to listen for connections from Tor clients and servers. This option is required to be a Tor server. Set it to “auto” to have Tor pick a port for you. Set it to 0 to not run an ORPort at all. This option can occur more than once. (Default: 0)

Tor recognizes these flags on each ORPort:
**NoAdvertise**::
By default, we bind to a port and tell our users about it. If
NoAdvertise is specified, we don’t advertise, but listen anyway. This
can be useful if the port everybody will be connecting to (for
example, one that’s opened on our firewall) is somewhere else.
**NoListen**::
By default, we bind to a port and tell our users about it. If
NoListen is specified, we don’t bind, but advertise anyway. This
can be useful if something else (for example, a firewall’s port
forwarding configuration) is causing connections to reach us.
**IPv4Only**::
If the address is absent, or resolves to both an IPv4 and an IPv6
address, only listen to the IPv4 address.
**IPv6Only**::
If the address is absent, or resolves to both an IPv4 and an IPv6
address, only listen to the IPv6 address.
For obvious reasons, NoAdvertise and NoListen are mutually exclusive, and
IPv4Only and IPv6Only are mutually exclusive.
ORListenAddress IP[:PORT]
Bind to this IP address to listen for connections from Tor clients and servers. If you specify a port, bind to this port rather than the one specified in ORPort. (Default: 0.0.0.0) This directive can be specified multiple times to bind to multiple addresses/ports.

This option is deprecated; you can get the same behavior with ORPort now
that it supports NoAdvertise and explicit addresses.
PortForwarding 0|1
Attempt to automatically forward the DirPort and ORPort on a NAT router connecting this Tor server to the Internet. If set, Tor will try both NAT-PMP (common on Apple routers) and UPnP (common on routers from other manufacturers). (Default: 0)
PortForwardingHelper filename|pathname
If PortForwarding is set, use this executable to configure the forwarding. If set to a filename, the system path will be searched for the executable. If set to a path, only the specified path will be executed. (Default: tor-fw-helper)
PublishServerDescriptor 0|1|v1|v2|v3|bridge,…
This option specifies which descriptors Tor will publish when acting as a relay. You can choose multiple arguments, separated by commas.
If this option is set to 0, Tor will not publish its descriptors to any directories. (This is useful if you’re testing out your server, or if you’re using a Tor controller that handles directory publishing for you.) Otherwise, Tor will publish its descriptors of all type(s) specified. The default is “1″, which means “if running as a server, publish the appropriate descriptors to the authorities”.
ShutdownWaitLength NUM
When we get a SIGINT and we’re a server, we begin shutting down: we close listeners and start refusing new circuits. After NUM seconds, we exit. If we get a second SIGINT, we exit immedi- ately. (Default: 30 seconds)
HeartbeatPeriod N minutes|hours|days|weeks
Log a heartbeat message every HeartbeatPeriod seconds. This is a log level info message, designed to let you know your Tor server is still alive and doing useful things. Settings this to 0 will disable the heartbeat. (Default: 6 hours)
AccountingMax N bytes|KB|MB|GB|TB
Never send more than the specified number of bytes in a given accounting period, or receive more than that number in the period. For example, with AccountingMax set to 1 GB, a server could send 900 MB and receive 800 MB and continue running. It will only hibernate once one of the two reaches 1 GB. When the number of bytes gets low, Tor will stop accepting new connections and circuits. When the number of bytes is exhausted, Tor will hibernate until some time in the next accounting period. To prevent all servers from waking at the same time, Tor will also wait until a random point in each period before waking up. If you have bandwidth cost issues, enabling hibernation is preferable to setting a low bandwidth, since it provides users with a collection of fast servers that are up some of the time, which is more useful than a set of slow servers that are always “available”.
AccountingStart day|week|month [day] HH:MM
Specify how long accounting periods last. If month is given, each accounting period runs from the time HH:MMon the dayth day of one month to the same day and time of the next. (The day must be between 1 and 28.) Ifweek is given, each accounting period runs from the time HH:MM of the dayth day of one week to the same day and time of the next week, with Monday as day 1 and Sunday as day 7. If day is given, each accounting period runs from the time HH:MM each day to the same time on the next day. All times are local, and given in 24-hour time. (Default: “month 1 0:00″)
RefuseUnknownExits 0|1|auto
Prevent nodes that don’t appear in the consensus from exiting using this relay. If the option is 1, we always block exit attempts from such nodes; if it’s 0, we never do, and if the option is “auto”, then we do whatever the authorities suggest in the consensus. (Default: auto)
ServerDNSResolvConfFile filename
Overrides the default DNS configuration with the configuration in filename. The file format is the same as the standard Unix “resolv.conf” file (7). This option, like all other ServerDNS options, only affects name lookups that your server does on behalf of clients. (Defaults to use the system DNS configuration.)
ServerDNSAllowBrokenConfig 0|1
If this option is false, Tor exits immediately if there are problems parsing the system DNS configuration or connecting to nameservers. Otherwise, Tor continues to periodically retry the system nameservers until it eventually succeeds. (Default: 1)
ServerDNSSearchDomains 0|1
If set to 1, then we will search for addresses in the local search domain. For example, if this system is configured to believe it is in “example.com”, and a client tries to connect to “www”, the client will be connected to “www.example.com”. This option only affects name lookups that your server does on behalf of clients. (Default: 0)
ServerDNSDetectHijacking 0|1
When this option is set to 1, we will test periodically to determine whether our local nameservers have been configured to hijack failing DNS requests (usually to an advertising site). If they are, we will attempt to correct this. This option only affects name lookups that your server does on behalf of clients. (Default: 1)
ServerDNSTestAddresses address,address,…
When we’re detecting DNS hijacking, make sure that these valid addresses aren’t getting redirected. If they are, then our DNS is completely useless, and we’ll reset our exit policy to “reject :“. This option only affects name lookups that your server does on behalf of clients. (Default: “www.google.com, www.mit.edu, www.yahoo.com, www.slashdot.org”)
ServerDNSAllowNonRFC953Hostnames 0|1
When this option is disabled, Tor does not try to resolve hostnames containing illegal characters (like @ and ::__IHACKLOG_REMOTE_IMAGE_AUTODOWN_BLOCK__::1 rather than sending them to an exit node to be resolved. This helps trap accidental attempts to resolve URLs and so on. This option only affects name lookups that your server does on behalf of clients. (Default: 0)
BridgeRecordUsageByCountry 0|1
When this option is enabled and BridgeRelay is also enabled, and we have GeoIP data, Tor keeps a keep a per-country count of how many client addresses have contacted it so that it can help the bridge authority guess which countries have blocked access to it. (Default: 1)
ServerDNSRandomizeCase 0|1
When this option is set, Tor sets the case of each character randomly in outgoing DNS requests, and makes sure that the case matches in DNS replies. This so-called “0×20 hack” helps resist some types of DNS poisoning attack. For more information, see “Increased DNS Forgery Resistance through 0×20-Bit Encoding”. This option only affects name lookups that your server does on behalf of clients. (Default: 1)
GeoIPFile filename
A filename containing GeoIP data, for use with BridgeRecordUsageByCountry.
CellStatistics 0|1
When this option is enabled, Tor writes statistics on the mean time that cells spend in circuit queues to disk every 24 hours. (Default: 0)
DirReqStatistics 0|1
When this option is enabled, a Tor directory writes statistics on the number and response time of network status requests to disk every 24 hours. (Default: 1)
EntryStatistics 0|1
When this option is enabled, Tor writes statistics on the number of directly connecting clients to disk every 24 hours. (Default: 0)
ExitPortStatistics 0|1
When this option is enabled, Tor writes statistics on the number of relayed bytes and opened stream per exit port to disk every 24 hours. (Default: 0)
ConnDirectionStatistics 0|1
When this option is enabled, Tor writes statistics on the bidirectional use of connections to disk every 24 hours. (Default: 0)
ExtraInfoStatistics 0|1
When this option is enabled, Tor includes previously gathered statistics in its extra-info documents that it uploads to the directory authorities. (Default: 1)
ExtendAllowPrivateAddresses 0|1
When this option is enabled, Tor routers allow EXTEND request to localhost, RFC1918 addresses, and so on. This can create security issues; you should probably leave it off. (Default: 0)
DIRECTORY SERVER OPTIONS
The following options are useful only for directory servers (that is, if DirPort is non-zero):

AuthoritativeDirectory 0|1
When this option is set to 1, Tor operates as an authoritative directory server. Instead of caching the directory, it generates its own list of good servers, signs it, and sends that to the clients. Unless the clients already have you listed as a trusted directory, you probably do not want to set this option. Please coordinate with the other admins at [email protected] if you think you should be a directory.
DirPortFrontPage FILENAME
When this option is set, it takes an HTML file and publishes it as “/” on the DirPort. Now relay operators can provide a disclaimer without needing to set up a separate webserver. There’s a sample disclaimer in contrib/tor-exit-notice.html.
V1AuthoritativeDirectory 0|1
When this option is set in addition to AuthoritativeDirectory, Tor generates version 1 directory and running-routers documents (for legacy Tor clients up to 0.1.0.x).
V2AuthoritativeDirectory 0|1
When this option is set in addition to AuthoritativeDirectory, Tor generates version 2 network statuses and serves descriptors, etc as described in doc/spec/dir-spec-v2.txt (for Tor clients and servers running 0.1.1.x and 0.1.2.x).
V3AuthoritativeDirectory 0|1
When this option is set in addition to AuthoritativeDirectory, Tor generates version 3 network statuses and serves descriptors, etc as described in doc/spec/dir-spec.txt (for Tor clients and servers running at least 0.2.0.x).
VersioningAuthoritativeDirectory 0|1
When this option is set to 1, Tor adds information on which versions of Tor are still believed safe for use to the published directory. Each version 1 authority is automatically a versioning authority; version 2 authorities provide this service optionally. See RecommendedVersions, RecommendedClientVersions, andRecommendedServerVersions.
NamingAuthoritativeDirectory 0|1
When this option is set to 1, then the server advertises that it has opinions about nickname-to-fingerprint bindings. It will include these opinions in its published network-status pages, by listing servers with the flag “Named” if a correct binding between that nickname and fingerprint has been registered with the dirserver. Naming dirservers will refuse to accept or publish descriptors that contradict a registered binding. See approved-routers in theFILES section below.
HSAuthoritativeDir 0|1
When this option is set in addition to AuthoritativeDirectory, Tor also accepts and serves v0 hidden service descriptors, which are produced and used by Tor 0.2.1.x and older. (Default: 0)
HidServDirectoryV2 0|1
When this option is set, Tor accepts and serves v2 hidden service descriptors. Setting DirPort is not required for this, because clients connect via the ORPort by default. (Default: 1)
BridgeAuthoritativeDir 0|1
When this option is set in addition to AuthoritativeDirectory, Tor accepts and serves router descriptors, but it caches and serves the main networkstatus documents rather than generating its own. (Default: 0)
MinUptimeHidServDirectoryV2 N seconds|minutes|hours|days|weeks
Minimum uptime of a v2 hidden service directory to be accepted as such by authoritative directories. (Default: 25 hours)
DirPort [address:]PORT|auto [flags]
If this option is nonzero, advertise the directory service on this port. Set it to “auto” to have Tor pick a port for you. This option can occur more than once. (Default: 0)

The same flags are supported here as are supported by ORPort.
DirListenAddress IP[:PORT]
Bind the directory service to this address. If you specify a port, bind to this port rather than the one specified in DirPort. (Default: 0.0.0.0) This directive can be specified multiple times to bind to multiple addresses/ports.

This option is deprecated; you can get the same behavior with DirPort now
that it supports NoAdvertise and explicit addresses.
DirPolicy policy,policy,…
Set an entrance policy for this server, to limit who can connect to the directory ports. The policies have the same form as exit policies above.
FetchV2Networkstatus 0|1
If set, we try to fetch the (obsolete, unused) version 2 network status consensus documents from the directory authorities. No currently supported Tor version uses them. (Default: 0)
DIRECTORY AUTHORITY SERVER OPTIONS
RecommendedVersions STRING
STRING is a comma-separated list of Tor versions currently believed to be safe. The list is included in each directory, and nodes which pull down the directory learn whether they need to upgrade. This option can appear multiple times: the values from multiple lines are spliced together. When this is set thenVersioningAuthoritativeDirectory should be set too.
RecommendedClientVersions STRING
STRING is a comma-separated list of Tor versions currently believed to be safe for clients to use. This information is included in version 2 directories. If this is not set then the value of RecommendedVersions is used. When this is set then VersioningAuthoritativeDirectory should be set too.
RecommendedServerVersions STRING
STRING is a comma-separated list of Tor versions currently believed to be safe for servers to use. This information is included in version 2 directories. If this is not set then the value of RecommendedVersions is used. When this is set then VersioningAuthoritativeDirectory should be set too.
ConsensusParams STRING
STRING is a space-separated list of key=value pairs that Tor will include in the “params” line of its networkstatus vote.
DirAllowPrivateAddresses 0|1
If set to 1, Tor will accept router descriptors with arbitrary “Address” elements. Otherwise, if the address is not an IP address or is a private IP address, it will reject the router descriptor. (Default: 0)
AuthDirBadDir AddressPattern…
Authoritative directories only. A set of address patterns for servers that will be listed as bad directories in any network status document this authority publishes, if AuthDirListBadDirs is set.
AuthDirBadExit AddressPattern…
Authoritative directories only. A set of address patterns for servers that will be listed as bad exits in any network status document this authority publishes, if AuthDirListBadExits is set.
AuthDirInvalid AddressPattern…
Authoritative directories only. A set of address patterns for servers that will never be listed as “valid” in any network status document that this authority publishes.
AuthDirReject AddressPattern…
Authoritative directories only. A set of address patterns for servers that will never be listed at all in any network status document that this authority publishes, or accepted as an OR address in any descriptor submitted for publication by this authority.
AuthDirBadDirCCs CC,…

AuthDirBadExitCCs CC,…

AuthDirInvalidCCs CC,…

AuthDirRejectCCs CC,…
Authoritative directories only. These options contain a comma-separated list of country codes such that any server in one of those country codes will be marked as a bad directory/bad exit/invalid for use, or rejected entirely.
AuthDirListBadDirs 0|1
Authoritative directories only. If set to 1, this directory has some opinion about which nodes are unsuitable as directory caches. (Do not set this to 1 unless you plan to list non-functioning directories as bad; otherwise, you are effectively voting in favor of every declared directory.)
AuthDirListBadExits 0|1
Authoritative directories only. If set to 1, this directory has some opinion about which nodes are unsuitable as exit nodes. (Do not set this to 1 unless you plan to list non-functioning exits as bad; otherwise, you are effectively voting in favor of every declared exit as an exit.)
AuthDirRejectUnlisted 0|1
Authoritative directories only. If set to 1, the directory server rejects all uploaded server descriptors that aren’t explicitly listed in the fingerprints file. This acts as a “panic button” if we get hit with a Sybil attack. (Default: 0)
AuthDirMaxServersPerAddr NUM
Authoritative directories only. The maximum number of servers that we will list as acceptable on a single IP address. Set this to “0″ for “no limit”. (Default: 2)
AuthDirMaxServersPerAuthAddr NUM
Authoritative directories only. Like AuthDirMaxServersPerAddr, but applies to addresses shared with directory authorities. (Default: 5)
AuthDirFastGuarantee N bytes|KB|MB|GB
Authoritative directories only. If non-zero, always vote the Fast flag for any relay advertising this amount of capacity or more. (Default: 100 KB)
AuthDirGuardBWGuarantee N bytes|KB|MB|GB
Authoritative directories only. If non-zero, this advertised capacity or more is always sufficient to satisfy the bandwidth requirement for the Guard flag. (Default: 250 KB)
BridgePassword Password
If set, contains an HTTP authenticator that tells a bridge authority to serve all requested bridge information. Used by the (only partially implemented) “bridge community” design, where a community of bridge relay operators all use an alternate bridge directory authority, and their target user audience can periodically fetch the list of available community bridges to stay up-to-date. (Default: not set)
V3AuthVotingInterval N minutes|hours
V3 authoritative directories only. Configures the server’s preferred voting interval. Note that voting will actuallyhappen at an interval chosen by consensus from all the authorities’ preferred intervals. This time SHOULD divide evenly into a day. (Default: 1 hour)
V3AuthVoteDelay N minutes|hours
V3 authoritative directories only. Configures the server’s preferred delay between publishing its vote and assuming it has all the votes from all the other authorities. Note that the actual time used is not the server’s preferred time, but the consensus of all preferences. (Default: 5 minutes)
V3AuthDistDelay N minutes|hours
V3 authoritative directories only. Configures the server’s preferred delay between publishing its consensus and signature and assuming it has all the signatures from all the other authorities. Note that the actual time used is not the server’s preferred time, but the consensus of all preferences. (Default: 5 minutes)
V3AuthNIntervalsValid NUM
V3 authoritative directories only. Configures the number of VotingIntervals for which each consensus should be valid for. Choosing high numbers increases network partitioning risks; choosing low numbers increases directory traffic. Note that the actual number of intervals used is not the server’s preferred number, but the consensus of all preferences. Must be at least 2. (Default: 3)
V3BandwidthsFile FILENAME
V3 authoritative directories only. Configures the location of the bandwidth-authority generated file storing information on relays’ measured bandwidth capacities. (Default: unset)
V3AuthUseLegacyKey 0|1
If set, the directory authority will sign consensuses not only with its own signing key, but also with a “legacy” key and certificate with a different identity. This feature is used to migrate directory authority keys in the event of a compromise. (Default: 0)
RephistTrackTime N seconds|minutes|hours|days|weeks
Tells an authority, or other node tracking node reliability and history, that fine-grained information about nodes can be discarded when it hasn’t changed for a given amount of time. (Default: 24 hours)
VoteOnHidServDirectoriesV2 0|1
When this option is set in addition to AuthoritativeDirectory, Tor votes on whether to accept relays as hidden service directories. (Default: 1)
HIDDEN SERVICE OPTIONS
The following options are used to configure a hidden service.

HiddenServiceDir DIRECTORY
Store data files for a hidden service in DIRECTORY. Every hidden service must have a separate directory. You may use this option multiple times to specify multiple services. DIRECTORY must be an existing directory.
HiddenServicePort VIRTPORT [TARGET]
Configure a virtual port VIRTPORT for a hidden service. You may use this option multiple times; each time applies to the service using the most recent hiddenservicedir. By default, this option maps the virtual port to the same port on 127.0.0.1 over TCP. You may override the target port, address, or both by specifying a target of addr, port, or addr:port. You may also have multiple lines with the same VIRTPORT: when a user connects to that VIRTPORT, one of the TARGETs from those lines will be chosen at random.
PublishHidServDescriptors 0|1
If set to 0, Tor will run any hidden services you configure, but it won’t advertise them to the rendezvous directory. This option is only useful if you’re using a Tor controller that handles hidserv publishing for you. (Default: 1)
HiddenServiceVersion version,version,…
A list of rendezvous service descriptor versions to publish for the hidden service. Currently, only version 2 is supported. (Default: 2)
HiddenServiceAuthorizeClient auth-type client-name,client-name,…
If configured, the hidden service is accessible for authorized clients only. The auth-type can either be ‘basic’ for a general-purpose authorization protocol or ‘stealth’ for a less scalable protocol that also hides service activity from unauthorized clients. Only clients that are listed here are authorized to access the hidden service. Valid client names are 1 to 19 characters long and only use characters in A-Za-z0-9+-_ (no spaces). If this option is set, the hidden service is not accessible for clients without authorization any more. Generated authorization data can be found in the hostname file. Clients need to put this authorization data in their configuration file using HidServAuth.
RendPostPeriod N seconds|minutes|hours|days|weeks
Every time the specified period elapses, Tor uploads any rendezvous service descriptors to the directory servers. This information is also uploaded whenever it changes. (Default: 1 hour)
TESTING NETWORK OPTIONS
The following options are used for running a testing Tor network.

TestingTorNetwork 0|1
If set to 1, Tor adjusts default values of the configuration options below, so that it is easier to set up a testing Tor network. May only be set if non-default set of DirServers is set. Cannot be unset while Tor is running. (Default: 0)

ServerDNSAllowBrokenConfig 1
DirAllowPrivateAddresses 1
EnforceDistinctSubnets 0
AssumeReachable 1
AuthDirMaxServersPerAddr 0
AuthDirMaxServersPerAuthAddr 0
ClientDNSRejectInternalAddresses 0
ClientRejectInternalAddresses 0
CountPrivateBandwidth 1
ExitPolicyRejectPrivate 0
ExtendAllowPrivateAddresses 1
V3AuthVotingInterval 5 minutes
V3AuthVoteDelay 20 seconds
V3AuthDistDelay 20 seconds
MinUptimeHidServDirectoryV2 0 seconds
TestingV3AuthInitialVotingInterval 5 minutes
TestingV3AuthInitialVoteDelay 20 seconds
TestingV3AuthInitialDistDelay 20 seconds
TestingAuthDirTimeToLearnReachability 0 minutes
TestingEstimatedDescriptorPropagationTime 0 minutes
TestingV3AuthInitialVotingInterval N minutes|hours
Like V3AuthVotingInterval, but for initial voting interval before the first consensus has been created. Changing this requires that TestingTorNetwork is set. (Default: 30 minutes)
TestingV3AuthInitialVoteDelay N minutes|hours
Like TestingV3AuthInitialVoteDelay, but for initial voting interval before the first consensus has been created. Changing this requires that TestingTorNetwork is set. (Default: 5 minutes)
TestingV3AuthInitialDistDelay N minutes|hours
Like TestingV3AuthInitialDistDelay, but for initial voting interval before the first consensus has been created. Changing this requires that TestingTorNetwork is set. (Default: 5 minutes)
TestingAuthDirTimeToLearnReachability N minutes|hours
After starting as an authority, do not make claims about whether routers are Running until this much time has passed. Changing this requires that TestingTorNetwork is set. (Default: 30 minutes)
TestingEstimatedDescriptorPropagationTime N minutes|hours
Clients try downloading router descriptors from directory caches after this time. Changing this requires thatTestingTorNetwork is set. (Default: 10 minutes)
SIGNALS
Tor catches the following signals:

SIGTERM
Tor will catch this, clean up and sync to disk if necessary, and exit.
SIGINT
Tor clients behave as with SIGTERM; but Tor servers will do a controlled slow shutdown, closing listeners and waiting 30 seconds before exiting. (The delay can be configured with the ShutdownWaitLength config option.)
SIGHUP
The signal instructs Tor to reload its configuration (including closing and reopening logs), and kill and restart its helper processes if applicable.
SIGUSR1
Log statistics about current connections, past connections, and throughput.
SIGUSR2
Switch all logs to loglevel debug. You can go back to the old loglevels by sending a SIGHUP.
SIGCHLD
Tor receives this signal when one of its helper processes has exited, so it can clean up.
SIGPIPE
Tor catches this signal and ignores it.
SIGXFSZ
If this signal exists on your platform, Tor catches and ignores it.
FILES
@CONFDIR@/torrc
The configuration file, which contains “option value” pairs.
@LOCALSTATEDIR@/lib/tor/
The tor process stores keys and other data here.
DataDirectory/cached-status/
The most recently downloaded network status document for each authority. Each file holds one such document; the filenames are the hexadecimal identity key fingerprints of the directory authorities. Mostly obsolete.
DataDirectory/cached-consensus and/or cached-microdesc-consensus
The most recent consensus network status document we’ve downloaded.
DataDirectory/cached-descriptors and cached-descriptors.new
These files hold downloaded router statuses. Some routers may appear more than once; if so, the most recently published descriptor is used. Lines beginning with @-signs are annotations that contain more information about a given router. The “.new” file is an append-only journal; when it gets too large, all entries are merged into a new cached-descriptors file.
DataDirectory/cached-microdescs and cached-microdescs.new
These files hold downloaded microdescriptors. Lines beginning with @-signs are annotations that contain more information about a given router. The “.new” file is an append-only journal; when it gets too large, all entries are merged into a new cached-microdescs file.
DataDirectory/cached-routers and cached-routers.new
Obsolete versions of cached-descriptors and cached-descriptors.new. When Tor can’t find the newer files, it looks here instead.
DataDirectory/state
A set of persistent key-value mappings. These are documented in the file. These include:

The current entry guards and their status.
The current bandwidth accounting values (unused so far; see below).
When the file was last written
What version of Tor generated the state file
A short history of bandwidth usage, as produced in the router descriptors.
DataDirectory/bw_accounting
Used to track bandwidth accounting values (when the current period starts and ends; how much has been read and written so far this period). This file is obsolete, and the data is now stored in the ‘state’ file as well. Only used when bandwidth accounting is enabled.
DataDirectory/control_auth_cookie
Used for cookie authentication with the controller. Location can be overridden by the CookieAuthFile config option. Regenerated on startup. See control-spec.txt for details. Only used when cookie authentication is enabled.
DataDirectory/keys/*
Only used by servers. Holds identity keys and onion keys.
DataDirectory/fingerprint
Only used by servers. Holds the fingerprint of the server’s identity key.
DataDirectory/approved-routers
Only for naming authoritative directory servers (see NamingAuthoritativeDirectory). This file lists nickname to identity bindings. Each line lists a nickname and a fingerprint separated by whitespace. See your fingerprint file in the DataDirectory for an example line. If the nickname is !reject then descriptors from the given identity (fingerprint) are rejected by this server. If it is !invalid then descriptors are accepted but marked in the directory as not valid, that is, not recommended.
DataDirectory/router-stability
Only used by authoritative directory servers. Tracks measurements for router mean-time-between-failures so that authorities have a good idea of how to set their Stable flags.
HiddenServiceDirectory/hostname
The <base32-encoded-fingerprint>.onion domain name for this hidden service. If the hidden service is restricted to authorized clients only, this file also contains authorization data for all clients.
HiddenServiceDirectory/private_key
The private key for this hidden service.
HiddenServiceDirectory/client_keys
Authorization data for a hidden service that is only accessible by authorized clients.
SEE ALSO
privoxy(1), tsocks(1), torify(1)

https://www.torproject.org/

BUGS
Plenty, probably. Tor is still in development. Please report them.

AUTHORS
Roger Dingledine [arma at mit.edu], Nick Mathewson [nickm at alum.mit.edu].

如何为自己的网站生成SSL证书

如何为自己的网站生成SSL证书

1. 首先保证安装了Openssl,并且能够在在终端执行它。
2. 为你的Apache(三倍-DES加密,PEM格式) 创建一个RSA私钥。

$   openssl   genrsa   -des3   -out   server.key   1024

请将你的server.key文件备份,并且记住你输入得进入密码。能够通过以下的命令察看该文件:

$   openssl   rsa   -noout   -text   -in   server.key

你也可以通过以下的命令创建一个没有加密的版本(不建议):

$   openssl   rsa   -in   server.key   -out   server.key.unsecure

3. 通过RSA私钥文件来创建一个证书请求文件(PEM格式,CSR)

$   openssl   req   -new   -key   server.key   -out   server.csr

同样,你需要做一个备份,同时,在Openssl命令行提示输入CommonName的过程中,你必须输入一个FQDN(一个完全的有资格的域名),一个站点生成了一个CSR请求文件。可以通过以下的命令来查看CSR的详细内容:

$   openssl   req   -noout   -text   -in   server.csr

4. 现在,你已经有了一个证书请求文件(CSR)了,你可以将此文件发送给一个认证机构来进行认证,当然会等一段时间并且花上一些钱。或者通过自己的CA认证机构来进行认证。
§ Verisign
http://digitalid.verisign.com/server/apacheNotice.htm 
§ Thawte Consulting
http://www.thawte.com/certs/server/request.html 
§ CertiSign Certificadora Digital Ltda.
http://www.certisign.com.br 
§ IKS GmbH
http://www.iks-jena.de/produkte/ca/
§ Uptime Commerce Ltd.
http://www.uptimecommerce.com 
§ BelSign NV/SA
http://www.belsign.be
通过以下的命令来察看经过认证的证书信息。

$   openssl   x509   -noout   -text   -in   server.crt

5. 现在,我们有了两个文件,server.key和server.crt ,下面就是在Apache中的httpd.conf文件配置:

SSLCertificateFile         /path/to/this/server.crt
SSLCertificateKeyFile   /path/to/this/server.key

请求文件不再需要了。
· 使用自认证机构:
最简单的就是通过CA.pl或者是通过CA.sh来对请求文件签名。
1. 为你的CA创建一个RSA私钥(三DES加密并且是PEM格式):

$   openssl   genrsa   -des3   -out   ca.key   1024

备份并且记住你输入的访问密码。通过以下的命令可以查看私钥的详细信息:

$   openssl   rsa   -noout   -text   -in   ca.key

你也可以创建一个非加密的PEM格式的私钥:

$   openssl   rsa   -in   ca.key   -out   ca.key.unsecure

2. 创建一个自签名的证书文件(X.509 结构,输出为PEM格式):

$   openssl   req   -new   -x509   -days   365   -key   ca.key   -out   ca.crt

通过以下的命令查询:

$   openssl   x509   -noout   -text   -in   ca.crt

3. 准备一个脚本文件来对请求文件签名,Openssl不允许简单的通过openssl ca来对请求文件签名。所以一个名为sign.sh的脚本文件(mod_ssl的子目录pkg.contrib下),是用这个来进行签名,不过还是建议使 用下面的方法进行签名。

4. 现在可以用这个脚本来进行签名了(刚才生成的CA的私钥和证书必须在这个脚本的目录下):

$   ./sign.sh   server.csr

得到一个证书文件—〉server.crt.
· 怎样更改我的私钥的 pass-phrase 密码?
只需要简单的读取它并重新写入,同时指定它的pass-phrase ,通过以下的命令完成:

$   openssl   rsa   -des3   -in   server.key   -out   server.key.new
$   mv   server.key.new   server.key

这时,你被要求两次来输入一个PEM 的pass-phrase,第一次要求输入旧密码,第二次要求输入新密码。
· 怎样可以消除Apache启动的时候的密码(pass-phrase)提示对话框:
原因是保存在你的私钥文件中的RSA私钥是一个一加密格式保存的。密码是保证能够读取这个密钥文件,如果保证你的服务器足够的安全的话,可以通过以下的命令消除:
1. 从RSA私钥中移除密码(同时保留源文件):

$   cp   server.key   server.key.org
$   openssl   rsa   -in   server.key.org   -out   server.key

2. 保证私钥只能被root用户读取:

$   chmod   400   server.key

现在这是一个没有没有加密的密钥拷贝。在使用这个密钥文件的时候,将不会再提示你输入密码,然而,如果其他任何人的到这个私钥文件,他都可以在网络上模仿你。所以一定要保证这个密钥文件只能被root用户读取。
· 怎么验证私钥文件和我的证书文件是匹配的?
私钥文件包括一系列的数字。这些数字中的两个是“来自“公钥文件的,其他的是私钥的一部分。公钥的一些bit值被嵌入到你的证书中(我们可以从证书CSR中得到),通过以下的命令来查看输出的数字,同时比较这些数字:

$   openssl   x509   -noout   -text   -in   server.crt
$   openssl   rsa   -noout   -text   -in   server.key

他们必须一致,因为它们都是很长的串,所以可以通过下面的方法来查看:

$   openssl   x509   -noout   -modulus   -in   server.crt   |   openssl   md5
$   openssl   rsa   -noout   -modulus   -in   server.key   |   openssl   md5

这时比较两个短的数字串

$   openssl   req   -noout   -modulus   -in   server.csr   |   openssl   md5

SSL证书制作

证书签名方案

使用OpenSSL制作证书其实还蛮简单的,只是证书签名的部分有一点复杂,方法有三:

  1. 交由受浏览器信任的第三方证书颁发机构签名;
  2. 自签名;
  3. 自制CA证书并用其签名。

对于上线运营的网站来说,第一个方案是首选,因为只有这样浏览器才不会报警。过去买证书很贵,现在倒是有免费的了,比如IE和Firefox都内置的StartSSL

不同的证书颁发机构对于证书生成多少都会有自己的要求,所以本文主要讨论后两种方案。

自签名证书

注:下面提到的很多命令都需要一个openssl配置文件,该文件一般名为openssl.cnf。Linux里一般不用管,Windows可使用参数config指定路径,使用环境变量OPENSSL_CONF也可以。

使用如下命令即可生成自签名证书:

openssl req -x509 -newkey rsa:1024 -nodes -days 365 -out self.pem -keyout self.key

req命令表示创建证书,newkey参数表示创建私钥而不是从已存在的文件中读取,nodes参数表示不加密私钥。如果不添加nodes参数,以后每次使用私钥时都必须输入密码(如Apache每次重启)。

输入证书信息时,Common Name需要写域名,支持通配符,如*.domain.tld。

程序运行完成后,self.pem即为完成签名的证书,self.key则为私钥。

使用上述命令创建的证书只能写一个域名匹配字符串,如写了*.domain.tld之后,访问https://domain.tld仍然会报错。如果想在一个证书中指定多个域名匹配字符串,则需要打开openssl.cnf文件,在末尾处添加如下内容:

[ ca_x509v3_more_cn_ext ]
nsComment="OpenSSL Generated Certificate"
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints=CA:true
subjectAltName = DNS:domain.tld,DNS:*.domain.tld

将subjectAltName行修改为需要的内容后保存退出,使用如下命令重新生成自签名证书:

openssl req -x509 -newkey rsa:1024 -nodes -days 365 -out self.pem -keyout self.key -extensions ca_x509v3_more_cn_ext

自制CA证书并用其签名

如需要使用多个证书,每一个都自签名则意味着每一个都需要导入浏览器,这样就很麻烦。自制CA证书并用其签名后,无论制作了多少个证书,都只需要将自制的CA证书导入浏览器即可,相对来说方便些。

上例中用一条命令直接生成了私钥和证书,这次换个方法,分解为两步。

首先,生成自己的个人私钥:

openssl genrsa -des3 -out my.key 2048

des3参数表示使用该算法加密生成的私钥,以后每次使用私钥时都必须输入密码,去掉这个参数则不进行加密。

根据个人私钥生成自签名CA证书:

openssl req -x509 -key my.key -days 911 -new -out my.pem

输入证书信息时,Common Name可以写自己的名字。将该CA证书导入浏览器后,该名字会显示在证书管理器中。

接下来生成服务器的私钥和证书:

openssl req -newkey rsa:1024 -nodes -days 365 -out server_unsigned.pem -keyout server.key

再之后,就可以用个人证书签名服务器证书了:

openssl ca -days 365 -md sha1 -in server_unsigned.pem -out server.pem -cert my.pem -keyfile my.key

如该命令报错找不到index.txt之类的,视openssl.cnf中的配置,则需要做点准备工作:

mkdir demoCA
mkdir demoCAnewcerts
touch demoCAindex.txt
echo 11 > demoCAserial

index.txt为空,serial随便写一个两位的数字进去。

多个域名的支持问题,跟上面说的一样,添加extensions参数:

openssl ca -days 365 -md sha1 -in server_unsigned.pem -out server.pem -cert my.pem -keyfile my.key -extensions ca_x509v3_more_cn_ext

完成后,server.key和server.pem即为已签名的证书及私钥。如果用在Lighttpd中,将两个文件合并即可。

最后,将my.pem导入至浏览器中“受信任的根证书颁发机构”即可。

其他

如果要去掉私钥的密码保护,可以这样做:

openssl rsa -in my.key -out my_plain.key

如果需要根据私钥生成公钥,可以这样做:

openssl rsa -in my.key -pubout -out my_public.key

证书生成后,可以使用如下命令查看详细信息:

openssl x509 -fingerprint -text -in my.pem

使用证书加密信息:

openssl smime -encrypt -in ptest.txt -out etest.txt my.pem

使用私钥解密:

openssl smime -decrypt -in etest.txt -out dtest.txt -inkey my.key

若需要DER格式的证书,可使用如下命令进行转换:

openssl x509 -in my.pem -outform DER -out my.der

十个实用的WordPress安全技巧

     安全,又是安全问题,WordPress啦已经好几次谈到这个话题了,这是因为安全问题实在太重要了。家里的防盗窗、防盗门以及汽车报警器等一切也都是出于安全考虑,同样地,互联网上的安全也非常重要,特别对于我们这种以网站或博客为生的人们。这篇文章就跟大家介绍一些实用的技巧以保证WordPress博客的安全。

 

1. 阻止透露不必要的信息

 

问题

当登录WordPress博客失败的时候,系统会显示错误提示信息。如果你忘记密码了,这个提示会对你有所帮助,可是这却也让那些想要攻击你博客的人有机可乘。因此,为何不阻止WordPress显示这个登录失败时的错误提示呢?

 

解决办法

想要删除登录错误提示信息,只要打开你的functions.php文件,并粘贴下面的代码:

 

add_filter(‘login_errors’,create_function(‘$a’, “return null;”));

保存此文件,再次检查下你就会发现登录失败时就没有错误信息提示了。

 

代码解释

这段代码里,我们添加了一个简单的hook来覆盖login_errors()函数。由于创建的自定义函数返回null,因此就只会显示一个空白的字串。

 

来源

 

WordPress安全提示

WordPress安全性: 隐藏登录错误提示

2. 强制使用SSL

 

问题

如果你担心数据被拦截,你完全可以使用SSLSSL是什么?它是基于WEB应用的安全加密协议。

 

你是否知道也可以给WordPress博客添加SSL加密?但是也并非是所有的主机都允许你使用SSL加密证书,如果你的博客是由IXWebhosting或美国主机Hostease托管的,那么就可以启用SSL,而且这两个主机都有中文站。

 

解决办法

一旦确定你的web服务器可以处理SSL,那问题就简单了,只要打开你的配置文件wp-config.php (在安装WordPress的根目录下),然后粘贴下面的代码:

 

define(‘FORCE_SSL_ADMIN’, true);

保存文件即可。

 

代码解释

这个代码比较简单。 WordPress使用了很多常量来配置,在这里我们只是定义了FORCE_SSL_ADMIN 常量并将它的值设置为 true。这样一来,你的WordPress博客就实现SSL加密了。

 

来源

 

如何在 wp-admin目录使用SSL

3. 使用 .htaccess来保护配置文件wp-config

 

问题

作为一名 WordPress用户,你应该知道配置文件wp-config.php的重要性。 此文件包含了所有可访问数据库的信息:用户名、密码、服务器名称等。 保护 wp-config.php 配置文件是如此的关键,那么如何利用Apache来解决这个问题呢?

 

解决办法

.htaccess文件位于WordPress安装目录下,首先要对它做个备份(如此重要的文件,任何改动之前一定要先备份),打开它然后粘贴下面的代码:

 

<files wp-config.php> order allow,deny deny from all </files>

代码解释

.htaccess 文件非常强大,也是防止他人访问你的文件的最佳工具。这段代码里,我们只是创建了一个规则来阻止任何人访问 wp-admin.php文件,防止bots攻击。

 

来源

 

十个简单的方法来保护你的WordPress博客安全

4. 将不受欢迎用户和Bots列入黑名单

 

问题

这个是比较现实的问题:今天被某个人骚扰,他可能下一次还会继续骚扰你。你是否有注意到每天同个人/垃圾留言机器光顾你的博客无数次留下无数恼人的评论。处理这个问题的方法非常简单:直接禁止他们访问你的博客。

 

解决方法

.htaccess文件粘贴下面的代码,再次说明在修改之前,切记备份.htaccess文件。并记得将123.456.789 该成你想要禁止的IP地址。

 

<Limit GET POST PUT> order allow,deny allow from all deny from 123.456.789 </LIMIT>

来源

 

2007年开始禁止了150多个可恶IP

5. 防止WordPress博客的脚步侵入

 

问题

保护动态完全特别重要。大多数开发人员都只保护GETPOST的请求,但有时候这样并不够。我们应该注意防止脚步侵入以及任何试图修改PHP GLOBALS_REQUEST变量。

 

解决方法

下面的代码可以阻止脚步入侵以及任何试图修改PHP GLOBALS _REQUEST变量。将代码粘贴到你的 .htaccess文件 (WordPress安装目录下)

 

Options +FollowSymLinks

RewriteEngine On

RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]

RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]

RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})

RewriteRule ^(.*)$ index.php [F,L]

 

代码解释

利用 .htaccess文件,我们可以检查请求。在这里,我们检查该请求是否包含一个 <script> ,它是否有试图修改PHP GLOBALS_REQUEST的变量值。如果符合任何一个条件,该请求就会被阻止,返回403错误到客户端浏览器。

来源

 

Protéger Son Site Avec Un Fichier .htaccess

使用 .htaccess来保护你的WordPress博客

6. 回击内容剽窃者

 

问题

如果你的博客有点知名度,很有可能就会有一些人在未经你的同意下直接使用你的内容。除了侵犯你的版权之外,由于盗用你的图片,对你服务器带宽也是一个很大的损耗。

 

解决办法

.htaccess文件里粘贴下面的代码:

 

RewriteEngine On #Replace ?mysite.com/ with your blog url RewriteCond %{HTTP_REFERER} !^http://(.+.)?mysite.com/ [NC] RewriteCond %{HTTP_REFERER} !^$

#Replace /images/nohotlink.jpg with your “don’t hotlink” image url

RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L] 保存之后,只有你的网站网站才能链接到你的图片,而其它盗链网站就无法显示你的图片。

代码解释

在这段代码里,首先检查引荐人是否与自己博客的URL地址一致。如果不一致,那么以下扩展名的文件,JPG, GIF, BMPPNG就不会显示而用 nohotlink图片代替。

 

来源

 

如何防止别人剽窃你的博客内容

7. 创建一个插件来阻止恶意URL的请求

 

问题

黑客通常通过恶意查询来找出并攻击一个博客的薄弱点。

 

解决办法

将下面的代码粘贴在一个文本文件里并命名为blockbadqueries.php。保存此文件并将它上传到 wp-content/plugins 目录,然后像其他插件一样激活它。这样你的博客就不会遭受恶意的查询。

 

<?php

/*

Plugin Name: Block Bad Queries

Plugin URI: http://perishablepress.com/press/2009/12/22/protect-wordpress-against-ma…

Description: Protect WordPress Against Malicious URL Requests

Author URI: http://perishablepress.com/

Author: Perishable Press

Version: 1.0

*/

 

global $user_ID;

 

if($user_ID) {

if(!current_user_can(‘level_10’)) {

if (strlen($_SERVER[‘REQUEST_URI’]) > 255 ||

strpos($_SERVER[‘REQUEST_URI’], “eval(“) ||

strpos($_SERVER[‘REQUEST_URI’], “CONCAT”) ||

strpos($_SERVER[‘REQUEST_URI’], “UNION+SELECT”) ||

strpos($_SERVER[‘REQUEST_URI’], “base64”)) {

@header(“HTTP/1.1 414 Request-URI Too Long”);

@header(“Status: 414 Request-URI Too Long”);

@header(“Connection: Close”);

@exit;

}

}

}

?>

代码解释 这段代码非常简单,它检查特别长的请求字符串(超过255个字符) 以及URL中是否存在evalbase64 PHP 函数。如果符合其中的任何一个条件,该插件就会想客户端浏览器发送414错误。

来源

 

阻止恶意URL的请求

8. 删除你的 WordPress版本号

 

问题

大家都知道,WordPress会自动在你的博客文件的头部显示版本号。如果你的博客一直都是最新版的话问题不大。但是如果由于某些原因你的WordPress版本并没有更新,却仍然显示出来的话,就会被黑客利用。

 

解决方法

在主题的functions.php文件里粘贴下面的代码,保存,然后刷新你的博客,这样你的WordPress版本号就不会出现了。

 

remove_action(‘wp_head’, ‘wp_generator’);

代码解释

要执行某个行动时, WordPress是用“hook”机制,也就是说可以让你将一个函数hook到另一个函数里。显示WordPress版本号的 wp_generator函数被hook了。我们可以移除这个 hook并通过使用 remove_action() 函数来阻止其执行。

 

来源

 

如何正确地移除WordPress的版本号

9.更改默认的用户名“Admin”

 

问题

如果你使用的是默认的“admin”用户名,黑客只需要攻破你的密码即可入侵你的一切。这无疑让黑客更容易得手,所以我们一直强调你应该更改默认的用户名 “admin” ,用个别人比较难猜得出来的用户名。

 

不过还好WordPress 3.0安装时可以让你选择自己喜欢的用户名。 如果你还在使用旧版本并且你的用户名还没有更改过,那么现在该动手了。

 

解决方法

如果你还没有更改“admin”用户名,只要在数据库中运行下面的SQL查询就可以更改。

 

UPDATE wp_users SET user_login = ‘你的新用户名‘ WHERE user_login = ‘Admin’;

代码解释

用户名是保存在数据库中的。想要更改的话,只要一个简单的查询更新即可。注意:这个查询并不会将你先前用“admin”账户发布的文章的用户名变成新的用户名,如果需要的话,请查看下面的来源文章。

 

来源

 

相见恨晚的十三个 WordPress SQL查询

10.阻止浏览目录

 

问题

默认情况下,大多数主机允许显示目录列表。因此,如果你在浏览器地址栏输入 www.yourblog.com/wp-includes,你就看到所有在该目录下的文件,这无疑是一个很大的安全隐患。

 

解决方法

只需在Apache配置里添加:

 

Option -Indexes