Normal view

There are new articles available, click to refresh the page.
Before yesterdayPolitics & Thinking

Linux 学习笔记(1): Linux Shell Powerful Tools

By: Onlyone
15 December 2011 at 17:46
Linux Shell Powerful Tools


Connecting and expanding commands
A truly powerful feature of the shell is the capability to redirect the input and output of commands to and from other commands and files. To allow commands to be strung together,the shell uses metacharacters. As noted earlier, a metacharacter is a typed character that has special meaning to the shell for connecting commands or requesting expansion.

Piping commands


The pipe (|) metacharacter connects the output from one command to the input of another command. This lets you have one command work on some data, and then have the next command deal with the results. Here is an example of a command line that includes pipes:


$ cat /etc/passwd | sort | cut -f1,5 -d: | less


This command lists the contents of the /etc/passwd file and pipes the output to the sort command. The sort command takes the user names that begin each line of the /etc/passwd file, sorts them alphabetically, and pipes the output to the cut command. The cut command takes fields 1 and 5, with the fields delimited by a colon (:), then pipes the output to the less command. The less command displays the output one page at a time, so that you can go through page by page.


Using file-matching metacharacters
To save you some keystrokes and to be able to refer easily to a group of files, the bash shell lets you use metacharacters. Anytime you need to refer to a file or directory, such as to list it, open it, or remove it, you can use metacharacters to match the files you want. Here are some useful metacharacters for matching filenames:

• * — This matches any number of characters.
• ? — This matches any one character.
• [...] — This matches any one of the characters between the brackets, which can
include a dash-separated range of letters or numbers.

Sample Examples:








Using file-redirection metacharacters
Commands receive data from standard input and send it to standard output. Standard input is normally user input from the keyboard, and standard output is normally displayed on the screen. Using pipes (described earlier), you can direct standard output from one command to the standard input of another. With files, you can use less than (<) and greater than (>) signs to direct data to and from files. Here are the file redirection characters:
• < — Direct the contents of a file as input to the command (because many commands take a file name as an option, the < key is not usually needed).
• > — Direct the output of a command to a file, overwriting any existing file.
• >> — Direct the output of a command to a file, adding the output to the end of the existing file.
Here are some examples of command lines where information is directed to and from files.









Managing background and foreground processes
If you are using Linux over a network or from a dumb terminal (a monitor that allows only text input with no GUI support), your shell may be all that you have. You may be used to a windowing environment where you have a lot of programs active at the same time so that you can switch among them as needed. This shell thing can seem pretty limited.


There are several ways to place an active program in the background. One mentioned earlier is to add an ampersand (&) to the end of a command line. Another way is to use the at command to run commands in a way in which they are not connected to the shell. (See Chapter 12 for more information about the at command.)
To stop a running command and put it in the background, press Ctrl+z. After the command is stopped, you can either bring it to the foreground to run (the fg command) or start it running in the background (the bg command).







Linux文件查找命令find,xargs详述

By: Onlyone
14 December 2011 at 12:40

Linux文件查找命令find,xargs详述

总结:zhy2111314
来自:LinuxSir.Org
整理:北南南北
摘要: 本文是find 命令的详细说明,可贵的是针对参数举了很多的实例,大量的例证,让初学者更为容易理解;本文是zhyfly兄贴在论坛中;我对本文进行了再次整理,为方便大家阅读;
目录

+++++++++++++++++++++++++++++++++++++++++++++++++
正文
+++++++++++++++++++++++++++++++++++++++++++++++++

版权声明
本文是zhyfly兄贴在LinuxSir.Org 的一个帖子而整理出来的,如果您对版权有疑问,请在本帖后面跟帖。谢谢;本文的HTML版本由北南南北整理;修改了整篇文档的全角及说明文字中的单词中每个字母空格的问题;为标题加了编号,方便大家阅读;
前言:关于find命令
由于find具有强大的功能,所以它的选项也很多,其中大部分选项都值得我们花时间来了解一下。即使系统中含有网络文件系统( NFS),find命令在该文件系统中同样有效,只你具有相应的权限。
在运行一个非常消耗资源的find命令时,很多人都倾向于把它放在后台执行,因为遍历一个大的文件系统可能会花费很长的时间(这里是指30G字节以上的文件系统)。

一、find 命令格式

1、find命令的一般形式为;
find pathname -options [-print -exec -ok ...]

2、find命令的参数;
pathname: find命令所查找的目录路径。例如用.来表示当前目录,用/来表示系统根目录。
-print: find命令将匹配的文件输出到标准输出。
-exec: find命令对匹配的文件执行该参数所给出的shell命令。相应命令的形式为'command' {} \;,注意{}和\;之间的空格。
-ok: 和-exec的作用相同,只不过以一种更为安全的模式来执行该参数所给出的shell命令,在执行每一个命令之前,都会给出提示,让用户来确定是否执行。

3、find命令选项
-name 

按照文件名查找文件。

-perm 
按照文件权限来查找文件。

-prune 
使用这一选项可以使find命令不在当前指定的目录中查找,如果同时使用-depth选项,那么-prune将被find命令忽略。

-user 
按照文件属主来查找文件。

-group 
按照文件所属的组来查找文件。

-mtime -n +n 
按照文件的更改时间来查找文件, - n表示文件更改时间距现在n天以内,+ n表示文件更改时间距现在n天以前。find命令还有-atime和-ctime 选项,但它们都和-m time选项。

-nogroup 
查找无有效所属组的文件,即该文件所属的组在/etc/groups中不存在。

-nouser 
查找无有效属主的文件,即该文件的属主在/etc/passwd中不存在。
-newer file1 ! file2 

查找更改时间比文件file1新但比文件file2旧的文件。
-type 

查找某一类型的文件,诸如:

b - 块设备文件。
d - 目录。
c - 字符设备文件。
p - 管道文件。
l - 符号链接文件。
f - 普通文件。

-size n:[c] 查找文件长度为n块的文件,带有c时表示文件长度以字节计。
-depth:在查找文件时,首先查找当前目录中的文件,然后再在其子目录中查找。
-fstype:查找位于某一类型文件系统中的文件,这些文件系统类型通常可以在配置文件/etc/fstab中找到,该配置文件中包含了本系统中有关文件系统的信息。

-mount:在查找文件时不跨越文件系统mount点。
-follow:如果find命令遇到符号链接文件,就跟踪至链接所指向的文件。
-cpio:对匹配的文件使用cpio命令,将这些文件备份到磁带设备中。
另外,下面三个的区别:
   -amin n
  查找系统中最后N分钟访问的文件

  -atime n
  查找系统中最后n*24小时访问的文件

  -cmin n
  查找系统中最后N分钟被改变文件状态的文件

  -ctime n
  查找系统中最后n*24小时被改变文件状态的文件

    -mmin n
  查找系统中最后N分钟被改变文件数据的文件

  -mtime n
  查找系统中最后n*24小时被改变文件数据的文件

4、使用exec或ok来执行shell命令
使用find时,只要把想要的操作写在一个文件里,就可以用exec来配合find查找,很方便的
在有些操作系统中只允许-exec选项执行诸如l s或ls -l这样的命令。大多数用户使用这一选项是为了查找旧文件并删除它们。建议在真正执行rm命令删除文件之前,最好先用ls命令看一下,确认它们是所要删除的文件。
exec选项后面跟随着所要执行的命令或脚本,然后是一对儿{},一个空格和一个\,最后是一个分号为了使用exec选项,必须要同时使用print选项。如果验证一下find命令,会发现该命令只输出从当前路径起的相对路径及文件名。
例如:为了用ls -l命令列出所匹配到的文件,可以把ls -l命令放在find命令的-exec选项中
# find . -type f -exec ls -l {} \;
-rw-r--r--    1 root     root        34928 2003-02-25  ./conf/httpd.conf
-rw-r--r--    1 root     root        12959 2003-02-25  ./conf/magic
-rw-r--r--    1 root     root          180 2003-02-25  ./conf.d/README
上面的例子中,find命令匹配到了当前目录下的所有普通文件,并在-exec选项中使用ls -l命令将它们列出。
在/logs目录中查找更改时间在5日以前的文件并删除它们:
$ find logs -type f -mtime +5 -exec rm {} \;
记住:在shell中用任何方式删除文件之前,应当先查看相应的文件,一定要小心!当使用诸如mv或rm命令时,可以使用-exec选项的安全模式。它将在对每个匹配到的文件进行操作之前提示你。
在下面的例子中, find命令在当前目录中查找所有文件名以.LOG结尾、更改时间在5日以上的文件,并删除它们,只不过在删除之前先给出提示。
$ find . -name "*.conf"  -mtime +5 -ok rm {} \;
< rm ... ./conf/httpd.conf > ? n
按y键删除文件,按n键不删除。
任何形式的命令都可以在-exec选项中使用。
在下面的例子中我们使用grep命令。find命令首先匹配所有文件名为“ passwd*”的文件,例如passwd、passwd.old、passwd.bak,然后执行grep命令看看在这些文件中是否存在一个sam用户。
# find /etc -name "passwd*" -exec grep "sam" {} \;
sam:x:501:501::/usr/sam:/bin/bash

二、find命令的例子;

1、查找当前用户主目录下的所有文件:
下面两种方法都可以使用
$ find $HOME -print
$ find ~ -print


2、让当前目录中文件属主具有读、写权限,并且文件所属组的用户和其他用户具有读权限的文件;
$ find . -type f -perm 644 -exec ls -l {} \;

3、为了查找系统中所有文件长度为0的普通文件,并列出它们的完整路径;
$ find / -type f -size 0 -exec ls -l {} \;

4、查找/var/logs目录中更改时间在7日以前的普通文件,并在删除之前询问它们;
$ find /var/logs -type f -mtime +7 -ok rm {} \;

5、为了查找系统中所有属于root组的文件;
$find . -group root -exec ls -l {} \;
-rw-r--r--    1 root     root          595 10月 31 01:09 ./fie1

6、find命令将删除当目录中访问时间在7日以来、含有数字后缀的admin.log文件。
该命令只检查三位数字,所以相应文件的后缀不要超过999。先建几个admin.log*的文件 ,才能使用下面这个命令
$ find . -name "admin.log[0-9][0-9][0-9]" -atime -7  -ok rm {} \;
< rm ... ./admin.log001 > ? n
< rm ... ./admin.log002 > ? n
< rm ... ./admin.log042 > ? n
< rm ... ./admin.log942 > ? n

7、为了查找当前文件系统中的所有目录并排序;
$ find . -type d | sort

8、为了查找系统中所有的rmt磁带设备;
$ find /dev/rmt -print

三、xargs
xargs - build and execute command lines from standard input
在使用find命令的-exec选项处理匹配到的文件时, find命令将所有匹配到的文件一起传递给exec执行。但有些系统对能够传递给exec的命令长度有限制,这样在find命令运行几分钟之后,就会出现溢出错误。错误信息通常是“参数列太长”或“参数列溢出”。这就是xargs命令的用处所在,特别是与find命令一起使用。
find命令把匹配到的文件传递给xargs命令,而xargs命令每次只获取一部分文件而不是全部,不像-exec选项那样。这样它可以先处理最先获取的一部分文件,然后是下一批,并如此继续下去。
在有些系统中,使用-exec选项会为处理每一个匹配到的文件而发起一个相应的进程,并非将匹配到的文件全部作为参数一次执行;这样在有些情况下就会出现进程过多,系统性能下降的问题,因而效率不高;
而使用xargs命令则只有一个进程。另外,在使用xargs命令时,究竟是一次获取所有的参数,还是分批取得参数,以及每一次获取参数的数目都会根据该命令的选项及系统内核中相应的可调参数来确定。
来看看xargs命令是如何同find命令一起使用的,并给出一些例子。
下面的例子查找系统中的每一个普通文件,然后使用xargs命令来测试它们分别属于哪类文件
#find . -type f -print | xargs file
./.kde/Autostart/Autorun.desktop: UTF-8 Unicode English text
./.kde/Autostart/.directory:      ISO-8859 text\
......
在整个系统中查找内存信息转储文件(core dump) ,然后把结果保存到/tmp/core.log 文件中:
$ find / -name "core" -print | xargs echo "" >/tmp/core.log
上面这个执行太慢,我改成在当前目录下查找
#find . -name "file*" -print | xargs echo "" > /temp/core.log
# cat /temp/core.log
./file6
在当前目录下查找所有用户具有读、写和执行权限的文件,并收回相应的写权限:
# ls -l
drwxrwxrwx    2 sam      adm          4096 10月 30 20:14 file6
-rwxrwxrwx    2 sam      adm             0 10月 31 01:01 http3.conf
-rwxrwxrwx    2 sam      adm             0 10月 31 01:01 httpd.conf

# find . -perm -7 -print | xargs chmod o-w
# ls -l
drwxrwxr-x    2 sam      adm          4096 10月 30 20:14 file6
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 http3.conf
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf
用grep命令在所有的普通文件中搜索hostname这个词:
# find . -type f -print | xargs grep "hostname"
./httpd1.conf:#     different IP addresses or hostnames and have them handled by the
./httpd1.conf:# VirtualHost: If you want to maintain multiple domains/hostnames
on your
用grep命令在当前目录下的所有普通文件中搜索hostnames这个词:
# find . -name \* -type f -print | xargs grep "hostnames"
./httpd1.conf:#     different IP addresses or hostnames and have them handled by the
./httpd1.conf:# VirtualHost: If you want to maintain multiple domains/hostnames
on your
注意,在上面的例子中, \用来取消find命令中的*在shell中的特殊含义。
find命令配合使用exec和xargs可以使用户对所匹配到的文件执行几乎所有的命令。

四、find 命令的参数
下面是find一些常用参数的例子,有用到的时候查查就行了,像上面前几个贴子,都用到了其中的的一些参数,也可以用man或查看论坛里其它贴子有find的命令手册

1、使用name选项
文件名选项是find命令最常用的选项,要么单独使用该选项,要么和其他选项一起使用。
可以使用某种文件名模式来匹配文件,记住要用引号将文件名模式引起来。
不管当前路径是什么,如果想要在自己的根目录$HOME中查找文件名符合*.txt的文件,使用~作为 'pathname'参数,波浪号~代表了你的$HOME目录。
$ find ~ -name "*.txt" -print
想要在当前目录及子目录中查找所有的‘ *.txt’文件,可以用:
$ find . -name "*.txt" -print
想要的当前目录及子目录中查找文件名以一个大写字母开头的文件,可以用:
$ find . -name "[A-Z]*" -print
想要在/etc目录中查找文件名以host开头的文件,可以用:
$ find /etc -name "host*" -print
想要查找$HOME目录中的文件,可以用:
$ find ~ -name "*" -print 或find . -print
要想让系统高负荷运行,就从根目录开始查找所有的文件。
$ find / -name "*" -print
如果想在当前目录查找文件名以两个小写字母开头,跟着是两个数字,最后是.txt的文件,下面的命令就能够返回名为ax37.txt的文件:
$find . -name "[a-z][a-z][0--9][0--9].txt" -print

2、用perm选项
按照文件权限模式用-perm选项,按文件权限模式来查找文件的话。最好使用八进制的权限表示法。
如在当前目录下查找文件权限位为755的文件,即文件属主可以读、写、执行,其他用户可以读、执行的文件,可以用:
$ find . -perm 755 -print
还有一种表达方法:在八进制数字前面要加一个横杠-,表示都匹配,如-007就相当于777,-006相当于666
# ls -l
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 http3.conf
-rw-rw-rw-    1 sam      adm         34890 10月 31 00:57 httpd1.conf
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf
drw-rw-rw-    2 gem      group        4096 10月 26 19:48 sam
-rw-rw-rw-    1 root     root         2792 10月 31 20:19 temp

# find . -perm 006
# find . -perm -006
./sam
./httpd1.conf
./temp
-perm mode:文件许可正好符合mode
-perm +mode:文件许可部分符合mode
-perm -mode: 文件许可完全符合mode

3、忽略某个目录
如果在查找文件时希望忽略某个目录,因为你知道那个目录中没有你所要查找的文件,那么可以使用-prune选项来指出需要忽略的目录。在使用-prune选项时要当心,因为如果你同时使用了-depth选项,那么-prune选项就会被find命令忽略。
如果希望在/apps目录下查找文件,但不希望在/apps/bin目录下查找,可以用:
$ find /apps -path "/apps/bin" -prune -o -print

4、使用find查找文件的时候怎么避开某个文件目录
比如要在/usr/sam目录下查找不在dir1子目录之内的所有文件
find /usr/sam -path "/usr/sam/dir1" -prune -o -print
find [-path ..] [expression] 在路径列表的后面的是表达式
-path "/usr/sam" -prune -o -print 是 -path "/usr/sam" -a -prune -o
-print 的简写表达式按顺序求值, -a 和 -o 都是短路求值,与 shell 的 && 和 || 类似如果 -path "/usr/sam" 为真,则求值 -prune , -prune 返回真,与逻辑表达式为真;否则不求值 -prune,与逻辑表达式为假。如果 -path "/usr/sam" -a -prune 为假,则求值 -print ,-print返回真,或逻辑表达式为真;否则不求值 -print,或逻辑表达式为真。
这个表达式组合特例可以用伪码写为
if -path "/usr/sam"  then
          -prune
else
          -print
避开多个文件夹
find /usr/sam \( -path /usr/sam/dir1 -o -path /usr/sam/file1 \) -prune -o -print
圆括号表示表达式的结合。
\ 表示引用,即指示 shell 不对后面的字符作特殊解释,而留给 find 命令去解释其意义。
查找某一确定文件,-name等选项加在-o 之后
#find /usr/sam  \(-path /usr/sam/dir1 -o -path /usr/sam/file1 \) -prune -o -name "temp" -print

5、使用user和nouser选项
按文件属主查找文件,如在$HOME目录中查找文件属主为sam的文件,可以用:
$ find ~ -user sam -print
在/etc目录下查找文件属主为uucp的文件:
$ find /etc -user uucp -print
为了查找属主帐户已经被删除的文件,可以使用-nouser选项。这样就能够找到那些属主在/etc/passwd文件中没有有效帐户的文件。在使用-nouser选项时,不必给出用户名; find命令能够为你完成相应的工作。
例如,希望在/home目录下查找所有的这类文件,可以用:
$ find /home -nouser -print

6、使用group和nogroup选项
就像user和nouser选项一样,针对文件所属于的用户组, find命令也具有同样的选项,为了在/apps目录下查找属于gem用户组的文件,可以用:
$ find /apps -group gem -print
要查找没有有效所属用户组的所有文件,可以使用nogroup选项。下面的find命令从文件系统的根目录处查找这样的文件
$ find / -nogroup-print

7、按照更改时间或访问时间等查找文件
如果希望按照更改时间来查找文件,可以使用mtime,atime或ctime选项。如果系统突然没有可用空间了,很有可能某一个文件的长度在此期间增长迅速,这时就可以用mtime选项来查找这样的文件。
用减号-来限定更改时间在距今n日以内的文件,而用加号+来限定更改时间在距今n日以前的文件。
希望在系统根目录下查找更改时间在5日以内的文件,可以用:
$ find / -mtime -5 -print
为了在/var/adm目录下查找更改时间在3日以前的文件,可以用:
$ find /var/adm -mtime +3 -print

8、查找比某个文件新或旧的文件
如果希望查找更改时间比某个文件新但比另一个文件旧的所有文件,可以使用-newer选项。它的一般形式为:
newest_file_name ! oldest_file_name
其中,!是逻辑非符号。
查找更改时间比文件sam新但比文件temp旧的文件:
例:有两个文件
-rw-r--r--    1 sam      adm             0 10月 31 01:07 fiel
-rw-rw-rw-    1 sam      adm         34890 10月 31 00:57 httpd1.conf
-rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf
drw-rw-rw-    2 gem      group        4096 10月 26 19:48 sam
-rw-rw-rw-    1 root     root         2792 10月 31 20:19 temp

# find -newer httpd1.conf  ! -newer temp -ls
1077669    0 -rwxrwxr-x   2 sam      adm             0 10月 31 01:01 ./httpd.conf
1077671    4 -rw-rw-rw-   1 root     root         2792 10月 31 20:19 ./temp
1077673    0 -rw-r--r--   1 sam      adm             0 10月 31 01:07 ./fiel
查找更改时间在比temp文件新的文件:
$ find . -newer temp -print


9、使用type选项
在/etc目录下查找所有的目录,可以用:
$ find /etc -type d -print
在当前目录下查找除目录以外的所有类型的文件,可以用:
$ find . ! -type d -print
在/etc目录下查找所有的符号链接文件,可以用
$ find /etc -type l -print

10、使用size选项
可以按照文件长度来查找文件,这里所指的文件长度既可以用块(block)来计量,也可以用字节来计量。以字节计量文件长度的表达形式为N c;以块计量文件长度只用数字表示即可。
在按照文件长度查找文件时,一般使用这种以字节表示的文件长度,在查看文件系统的大小,因为这时使用块来计量更容易转换。
在当前目录下查找文件长度大于1 M字节的文件:
$ find . -size +1000000c -print
在/home/apache目录下查找文件长度恰好为100字节的文件:
$ find /home/apache -size 100c -print
在当前目录下查找长度超过10块的文件(一块等于512字节):
$ find . -size +10 -print

11、使用depth选项
在使用find命令时,可能希望先匹配所有的文件,再在子目录中查找。使用depth选项就可以使find命令这样做。这样做的一个原因就是,当在使用find命令向磁带上备份文件系统时,希望首先备份所有的文件,其次再备份子目录中的文件。
在下面的例子中, find命令从文件系统的根目录开始,查找一个名为CON.FILE的文件。
它将首先匹配所有的文件然后再进入子目录中查找。
$ find / -name "CON.FILE" -depth -print

12、使用mount选项
在当前的文件系统中查找文件(不进入其他文件系统),可以使用find命令的mount选项。
从当前目录开始查找位于本文件系统中文件名以XC结尾的文件:
$ find . -name "*.XC" -mount -print


五、关于本文
本文是find 命令的详细说明,可贵的是针对参数举了很多的实例,大量的例证,让初学者更为容易理解;本文是zhy2111314兄贴在论坛中;我对本文进行了再次整理,为方便大家阅读; ── 北南南北
六、相关文档

Linux:Apache配置文件httpd.conf详细说明

By: Onlyone
13 December 2011 at 22:53
# mime.types文件的位置(mod_mime)

<IfModule mpm_winnt_module>
TypesConfig conf/mime.types
</IfModule>
<IfModule mpm_prefork_module>
TypesConfig /etc/httpd/mime.types
</IfModule>
#检查服务器发送的 nonce 计数(尚未实现)(mod_auth_digest)
#AuthDigestNcCheck On
#为了跟踪客户端而分配的共享内存字节数(mod_auth_digest),每链接需要128字节。
AuthDigestShmemSize 25600
#禁止在内存中缓冲日志(mod_log_config)
BufferedLogs Off
#为了和RewriteMap*程序*通讯而使用的同步锁文件的名称(mod_rewrite)
#RewriteLock file-path

#为每个请求记录扩展的状态信息
ExtendedStatus On
##############################################################################
#####第二部分 主服务器配置[这些指令的作用域含同时含有"server config"和"virtual host"] 
##############################################################################
## 本配置文件将所有主机都当作虚拟主机,并不存在真正的"主服务器",因此这部分配置只
## 是所有虚拟主机的默认设置而已 ##

##### 适用于主服务器配置的核心(Core)指令 #####
#### 虚拟主机必须重新设定的指令
#文档树的根目录(没有真正的主服务器,因此不设置此值)(不能包含结尾斜杠)
#DocumentRoot directory-path
#当没有指定ServerName时,服务器会尝试对IP地址进行反向查询来推断主机名。
#所以,必须胡乱设置一个默认的主服务器主机名
ServerName xx.xx.xx.xx
#### 目录相关
#分布式配置文件的名字
AccessFileName .htaccess
#目录仅可以使用符号链接的特性
Options FollowSymLinks
#### 应答头相关
#当应答内容是text/plain或text/html时在HTTP应答头中加入的默认字符集
AddDefaultCharset utf-8
#无法由其他方法确定内容类型时,发送的默认MIME内容类型
DefaultType application/octet-stream
#禁止生成Content-MD5应答头
ContentDigest Off
#用以创建ETag应答头的文件的属性
FileETag All
#### 貌似安全相关
#仅当一个请求映射到一个真实存在的路径时才会被接受
AcceptPathInfo Off
#禁止URL中使用经过编码的路径分割符
AllowEncodedSlashes Off
#指定内部重定向和嵌套子请求的最大数量(至少是5)
LimitInternalRecursion 10
#限制客户端发送的HTTP请求体的最大字节长度(1.2M)
LimitRequestBody 1300000
#限制基于XML的请求体的最大字节长度(1.2M)
LimitXMLRequestBody 1300000

#限制apache子进程派生的进程占用CPU的最大秒数
RLimitCPU 1 1
#限制由apache子进程派生的进程占用的最大内存字节数
RLimitMEM 1 1
#限制由Apache子进程派生的进程所派生的进程数目
RLimitNPROC 0 1
#禁止生成服务器端生成文档的页脚
ServerSignature Off
#### 性能相关
#在递送中使用内存映射来读取文件(某些情况下需要禁用)
EnableMMAP On
#使用操作系统内核的sendfile支持来将文件发送到客户端
EnableSendfile On
#禁用对客户端IP的DNS查找
HostnameLookups Off
#持久链接(禁用)
KeepAlive Off
KeepAliveTimeout 1
MaxKeepAliveRequests 1
#### 错误应答与错误日志
#自定义错误响应
#400 错误的请求
ErrorDocument 400 /error/http|ErrCode=400.htm
#403 禁止访问
ErrorDocument 403 /error/http|ErrCode=403.htm
#404 未找到
ErrorDocument 404 /error/http|ErrCode=404.htm
#405 方法不被允许
ErrorDocument 405 /error/http|ErrCode=405.htm
#406 资源已经找到但MIME类型与Accpet头中所指不兼容
ErrorDocument 406 /error/http|ErrCode=406.htm
#408 在服务器许可的等待时间内客户一直没有发出任何请求
ErrorDocument 408 /error/http|ErrCode=408.htm
#409 由于请求和资源的当前状态相冲突因此不能成功(通常和PUT有关)
ErrorDocument 409 /error/http|ErrCode=409.htm
#410 所请求的文档已经不再可用而且服务器不知道应该重定向到哪一个地址
ErrorDocument 410 /error/http|ErrCode=410.htm
#411 必须发送Content-Length头否则无法处理
ErrorDocument 411 /error/http|ErrCode=411.htm
#412 指定的一些前提条件失败
ErrorDocument 411 /error/http|ErrCode=412.htm
#413 请求实体太大
ErrorDocument 413 /error/http|ErrCode=413.htm
#414 请求URI太长
ErrorDocument 414 /error/http|ErrCode=414.htm
#415 不支持的MIME类型
ErrorDocument 415 /error/http|ErrCode=415.htm
#416 Range头所请求的范围无法满足
ErrorDocument 416 /error/http|ErrCode=416.htm
#417 执行失败
ErrorDocument 417 /error/http|ErrCode=417.htm
#423 锁定的错误
ErrorDocument 423 /error/http|ErrCode=423.htm
#500 内部服务器错误
ErrorDocument 500 /error/http|ErrCode=500.htm
#501 服务器不支持实现请求所需要的功能
ErrorDocument 501 /error/http|ErrCode=501.htm
#502 服务器用作网关或代理服务器时收到了无效响应
ErrorDocument 502 /error/http|ErrCode=502.htm
#503 服务器由于维护或者负载过重暂时不能提供服务
ErrorDocument 503 /error/http|ErrCode=503.htm
#504 不能及时地从远程服务器获得应答(作为代理或网关的服务器)
ErrorDocument 504 /error/http|ErrCode=504.htm
#505 服务器不支持请求中所指明的HTTP版本
#ErrorDocument 505 /error/http|ErrCode=505.htm
#返回给客户端的错误信息中包含的管理员邮件地址
ServerAdmin [email]webmaster@oklaoshi.org[/email]
#错误日志(未使用滚动)
<IfModule mpm_winnt_module>
ErrorLog log/error.log
LogLevel info
</IfModule>
<IfModule mpm_prefork_module>
ErrorLog /var/log/httpd/error.log
LogLevel warn
</IfModule>
#### 处理器

#定位CGI脚本解释器(仅用于Win32)
ScriptInterpreterSource Script
#强制所有匹配的文件被一个指定的处理器处理
#SetHandler handler-name|None
#### 输入输出过滤器
#压缩输出所有文本内容(目前反对使用该指令,但因其简单故而使用)
AddOutputFilterByType DEFLATE application/x-javascript application/xhtml+xml application/xslt+xml application/xml application/xml-dtd text/css text/html text/plain text/richtext text/rtf text/xml
#设置处理客户端请求和POST输入时使用的过滤器
#SetInputFilter filter[;filter...]
#设置用于处理服务器输出应答的过滤器
#SetOutputFilter filter[;filter...]
#### 规范化
#使用客户端提供的主机名和端口构建自引用URL
#可以巧妙解决双线机房以及同目录多站点的问题
#还可以巧妙解决同时运行产品环境和开发环境的问题(本配置未使用该技巧)
UseCanonicalName Off
UseCanonicalPhysicalPort Off
##### 适用于主服务器配置的动态加载模(DSO)块指令 #####
#### mod_deflate ####
#用于zlib一次压缩的片断大小(字节)(20K),一般等于较大页面的大小
DeflateBufferSize 20240
#压缩程度,取值范围在 1(最低压缩率) 到 9(最高压缩率)之间
DeflateCompressionLevel 3
#在日志中将一个指示压缩率标记附加在请求之后(关闭)
#DeflateFilterNote Input instream
#DeflateFilterNote Output outstream
#DeflateFilterNote Ratio ratio
#压缩时最多可以使用多少内存(取值范围在1到9之间)
DeflateMemLevel 9
#压缩窗口的大小(取值范围在1到15之间,越大压缩效果越好)
DeflateWindowSize 15
#目录结尾斜线(/)自动补全功能(通过重定向,强烈建议打开)
#默认的目录索引文件(强烈建议按此顺序设置)
<IfModule mpm_prefork_module>
DirectorySlash On
DirectoryIndex index.html index.htm index.php
</IfModule>
<IfModule mpm_winnt_module>
DirectorySlash Off
DirectoryIndex none
</IfModule>
#### mod_env #####
#### mod_setenvif #####
#传送shell中的环境变量
#PassEnv env-variable [env-variable] ...
#强制gzip输出[建议不要这样,会让机器人头晕]
#SetEnv force-gzip 1
#删除环境变量(默认不记录任何访问日志)
UnsetEnv AccessLog
#根据客户端请求属性设置环境变量(仅记录对txt/php/html的访问)
SetEnvIf Request_URI "\.(txt|php|html?)$" AccessLog=1
##### mod_expires #####
#启用"Expires:"和"Cache-Control:"头
ExpiresActive On
#由MIME类型配置的Expires头的值
#ExpiresByType MIME-type code seconds
#默认所有文档的有效期为30天
ExpiresDefault "access plus 30 days"
#但是php文档默认不存在有效期(随后应当根据实际情况详细设置)

ExpiresActive Off
##### mod_log_config #####
#访问日志(虚拟主机+组合日志格式)(有条件的记录)
<IfModule mpm_winnt_module>
CustomLog log/access.log "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" env=AccessLog
</IfModule>
<IfModule mpm_prefork_module>
CustomLog /var/log/httpd/access.log "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" env=AccessLog
</IfModule>
##### mod_mime #####
#在文件扩展名与特定的编码方式之间建立映射关系
#AddEncoding MIME-enc extension [extension] ...
#将所有 .html.gz .css.gz 之类经过压缩的静态内容使用"Content-Encoding: gzip"头发送,
#这样既节约带宽又比使用mod_deflate的实时压缩节约CPU
#但只适用于静态内容并且要结合内容协商模块的类型表功能才能实现,而且不利于搜索引擎机器人收录,
#考虑到mod_expires的作用,这份配置放弃这种方法
#不过这样也可能和 AddOutputFilterByType DEFLATE .... 指令冲突,需要进一步实验或寻找其他有效方法
#AddEncoding gzip .gz
#为所有文件设定特定的默认语言(简体中文)
DefaultLanguage zh-CN
#在使用MultiViews查询所匹配的文件时要包含的文件类型
#NegotiatedOnly选项规定每个跟在基础名字后面的扩展名必须关联到一个在内容协商时已知的mod_mime扩展名,
#例如:字符集、内容类型、语言、编码方式。这是一种最严格也是副作用最少的实现方法,它是默认的处理方式。
MultiviewsMatch NegotiatedOnly
#在给定的文件扩展名与特定的字符集之间建立映射
#AddCharset charset extension [extension] ...
#在文件扩展名与特定的语言之间建立映射
#AddLanguage MIME-lang extension [extension] ...
#在文件扩展名与特定的处理器之间建立映射
#AddHandler handler-name extension [extension] ...
#在文件扩展名与特定的输入过滤器之间建立映射
#AddInputFilter filter[;filter...] extension [extension] ...
#在文件扩展名与特定的输出过滤器之间建立映射关系
#AddOutputFilter filter[;filter...] extension [extension] ...
#在给定的文件扩展名与特定的内容类型之间建立映射
#AddType MIME-type extension [extension] ...
##### mod_rewrite #####
#关闭重写引擎(不可继承,必须在每个需要的虚拟主机中单独开启)
RewriteEngine Off
#重写引擎日志的详细程度(9-最详细,0-关闭)
RewriteLogLevel 0
#强制当前配置继承其父配置(映射表、条件、规则)
#RewriteOptions inherit
#定义重写发生的条件(为了提高匹配效率)和规则(不需要考虑#..内容,因为浏览器并不发送)
RewriteCond %{REQUEST_URI} \.htm$
RewriteRule ^(.+)\.htm$ $1.php [NE,C]
RewriteRule ^([^|]+)\|(.+)\.php$ $1.php?$2 [NE,L]

#为server-info处理器显示的模块增加额外信息
#AddModuleInfo module-name string

#开启带宽限制(默认是关闭的,也就是不做任何限制)
BandWidthModule On
#强制对所有请求进行限制
ForceBandWidthModule On
#连接数上限。必须与BandWidth的子网范围对应,当然也可以不使用该指令。
MaxConnection 127.0.0.0/8 2
#带宽上限(B/s)。这里限制为16Kbps
BandWidth 127.0.0.0/8 2048
#带宽下限(B/s),设为"-1"表示仅使用上限。
MinBandWidth all -1
#将数据包分割成每小块1024字节进行延迟发送,可用值为1024-131072,默认为8192。
BandWidthPacket 1024
#将所有大于50kB的文件下载速度限制压低到8Kbps
#LargeFileLimit * 50 1024
#默认到达MaxConnection限制后将发送"503"错误代码(HTTP_SERVICE_UNAVAILABLE),
#该指令允许你自定义一个未使用的错误代码(300~599)并结合ErrorDocument指令实现自定义的错误代码说明。
#BandWidthError 510
#################################################################################
##第三部分 默认目录特性/认证/授权/访问控制[这些指令的作用域含有"directory"] #####
#################################################################################
## 默认特性穷尽限制与封闭之能事,因此必须在随后的配置中按需"放水" ##
## 此部分并不包含所有作用域含有"directory"的指令 ##
<Directory />
#禁用.htaccess文件(仅可用于目录)
AllowOverride None
#目录仅可以使用符号链接的特性(仅可用于目录)
Options FollowSymLinks
#必须同时通过认证并且满足访问控制条件
Satisfy all
#使用摘要认证
AuthType Digest
AuthDigestAlgorithm MD5
AuthDigestNonceLifetime 1200
AuthDigestQop auth
AuthDigestProvider file
AuthDefaultAuthoritative On
#所有认证共用一个用户名/密码文件
<IfModule mpm_winnt_module>
AuthUserFile conf/authn.md5
</IfModule>
<IfModule mpm_prefork_module>
AuthUserFile /etc/httpd/authn.md5
</IfModule>
AuthzUserAuthoritative On
AuthzDefaultAuthoritative On
#拒绝所有访问(mod_authz_host)
#Allow from 127.0.0.1
Deny from all
Order Allow,Deny
</Directory>
#因为在所有之后合并,所以下面可以确保拒绝访问任何"secret"目录
<DirectoryMatch /secret/>
AllowOverride None
Options FollowSymLinks
Satisfy all
Deny from all
Order Allow,Deny
</DirectoryMatch>
##下面是一段非常愚蠢的做法,完全推翻了上述默认的访问控制,因为在最后合并
##实际效果变成允许GET和POST访问一切目录和文件!!!
#
#企图仅仅允许GET和POST方法(实际上行不通)
#
# Order Allow,Deny
# Deny from all
#
#
############################################################################
#### 第四部分 默认虚拟主机[这些指令的作用域都含有"virtual host"] #####
############################################################################

#(共享服务器,存放与特定子站无关或无法在子站内部统一的内容)
#文档树根目录、主机名和别名
DocumentRoot /www/oklaoshi/www
ServerName oklaoshi.org
ServerAlias oklaoshi.net oklaoshi.com oklaoshi.cn
ServerAlias [url]www.oklaoshi.org[/url] [url]www.oklaoshi.net[/url] [url]www.oklaoshi.com[/url] [url]www.oklaoshi.cn[/url]
#开启重写引擎并继承主服务器配置(映射表、条件、规则)
RewriteEngine On
RewriteOptions inherit
#传送shell中指定的加密密钥(最好只传递到特定目录下的特定文件)
#PassEnv ENCRYPT_KEY
#重新设置PHP针对每个站点的不同特性
php_admin_value open_basedir "/www/oklaoshi/"
php_admin_flag file_uploads Off
php_admin_value include_path "/www/oklaoshi/secret"
php_admin_value session.name "OKLAOSHISESSIONID"
php_admin_value session.referer_check "oklaoshi."
#默认为非本地引用
UnsetEnv Local_Referer
#判断是否为本地引用
SetEnvIf Referer "oklaoshi\.(org|net|com|cn)" Local_Referer
<Directory "/www/oklaoshi/www">
Order Allow,Deny
Allow from all
#防止盗链(必须放在<Directory>内部)
<FilesMatch "\.(js|css|gif|jpe?g|png|swf)$">
Order Allow,Deny
Allow from env=Local_Referer
</FilesMatch>
</Directory>

Recover MySQL Database root password

By: Onlyone
13 December 2011 at 22:42
Recover MySQL Database root password




By default, MySQL Server will be installed with root superuser without any password. You can connect to MySQL server as root without requiring password or by keying in blank password. However, if you have set the password for root and forget or unable to recall the password, then you will need to reset the root password for MySQL.
Login as root to the Unix-like (Unix, Linux or BSD) machine with the MySQL server.
Stop the MySQL server by using either of the following command
#/etc/init.d/mysql stop
Now you need to Start MySQL server without password
mysqld_safe --skip-grant-tables &
Connect to mysql server using mysql client with the following command
# mysql -u root
Now you should be having mysql prompt
mysql>
Now you need to Setup new MySQL root user password
mysql> use mysql;
mysql> update user set password=PASSWORD(“newrootpassword”) where user=’root’;
mysql> flush privileges;
mysql> quit
Note: Replace newrootpassword with the new root password for MySQL server. Flush Privileges is needed to making the password change effect immediately.
Now you need to Stop MySQL Server using the following command
# /etc/init.d/mysql stop
Test Your New Mysql root password
First you need to start mysql server using the following command
# /etc/init.d/mysql start
# mysql -u root -p
Now it will prompt for root password and enter your new root password

Linux Command Line Reference for Common Operations (2)

By: Onlyone
13 December 2011 at 12:54

My previous reference for practical Linux commands was surprisingly popular
with over 3.5 million hits in nearly 5 years. So I've decided to start compiling
another list of somewhat more involved/esoteric commands.
Examples marked with • are valid/safe to paste without modification into a terminal, so
you may want to keep a terminal window open while reading this so you can cut & paste.
CommandDescription
grep . /proc/sys/net/ipv4/*List the contents of flag files
set | grep $USERSearch current environment
tr '\0' '\n' < /proc/$$/environDisplay the startup environment for any process
echo $PATH | tr : '\n'Display the $PATH one per line
kill -0 $$ && echo process exists and can accept signalsCheck for the existence of a process (pid)
find /etc -readable | xargs less -K -p'*ntp' -j $((${LINES:-25}/2))Search paths and data with full context. Use n to iterate
Low impact admin
#apt-get install "package" -o Acquire::http::Dl-Limit=42 \
-o Acquire::Queue-mode=access
Rate limit apt-get to 42KB/s
 echo 'wget url' | at 01:00Download url at 1AM to current dir
#apache2ctl configtest && apache2ctl gracefulRestart apache if config is OK
nice openssl speed sha1Run a low priority command (openssl benchmark)
chrt -i 0 openssl speed sha1Run a low priority command (more effective than nice)
renice 19 -p $$; ionice -c3 -p $$Make shell (script) low priority. Use for non interactive tasks
Interactive monitoring
watch -t -n1 uptimeClock with system load
htop -d 5Better top (scrollable, tree view, lsof/strace integration, ...)
iotopWhat's doing I/O
#watch -d -n30 "nice ps_mem.py | tail -n $((${LINES:-12}-2))"What's using RAM
#iftopWhat's using the network. See also iptraf
#mtr www.pixelbeat.orgping and traceroute combined
Useful utilities
pv < /dev/zero > /dev/nullProgress Viewer for data copying from files and pipes
wkhtml2pdf http://.../linux_commands.html linux_commands.pdfMake a pdf of a web page
timeout 1 sleep 3run a command with bounded time. See also timeout
Networking
python -m SimpleHTTPServerServe current directory tree at http://$HOSTNAME:8000/
openssl s_client -connect www.google.com:443 </dev/null 2>&0 |
openssl x509 -dates -noout
Display the date range for a site's certs
curl -I www.pixelbeat.orgDisplay the server headers for a web site
#lsof -i tcp:80What's using port 80
#httpd -SDisplay a list of apache virtual hosts
vim scp://user@remote//path/to/fileEdit remote file using local vim. Good for high latency links
curl -s http://www.pixelbeat.org/pixelbeat.asc | gpg --importImport a gpg key from the web
tc qdisc add dev lo root handle 1:0 netem delay 20msecAdd 20ms latency to loopback device (for testing)
tc qdisc del dev lo rootRemove latency added above
Notification
echo "DISPLAY=$DISPLAY xmessage cooker" | at "NOW +30min"Popup reminder
notify-send "subject" "message"Display a gnome popup notification
 echo "mail -s 'go home' P@draigBrady.com < /dev/null" | at 17:30Email reminder
 uuencode file name | mail -s subject P@draigBrady.comSend a file via email
 ansi2html.sh | mail -a "Content-Type: text/html" P@draigBrady.comSend/Generate HTML email
Better default settings (useful in your .bashrc)
#tail -s.1 -f /var/log/messagesDisplay file additions more responsively
seq 100 | tail -n $((${LINES:-12}-2))Display as many lines as possible without scrolling
#tcpdump -s0Capture full network packets
Useful functions/aliases (useful in your .bashrc)
md () { mkdir -p "$1" && cd "$1"; }Change to a new directory
strerror() { python -c "import os; print os.strerror($1)"; }Display the meaning of an errno
plot() { { echo 'plot "-"' "$@"; cat; } | gnuplot -persist; }Plot stdin. (e.g: • seq 1000 | sed 's/.*/s(&)/' | bc -l | plot)
hili() { e="$1"; shift; grep --col=always -Eih "$e|$" "$@"; }highlight occurences of expr. (e.g: • env | hili $USER)
alias hd='od -Ax -tx1z -v'Hexdump. (usage e.g.: • hd /proc/self/cmdline | less)
alias realpath='readlink -f'Canonicalize path. (usage e.g.: • realpath ~/../$USER)
ord() { printf "0x%x\n" "'$1"; }shell version of the ord() function
chr() { printf $(printf '\\%03o\\n' "$1"); }shell version of the chr() function
Multimedia
DISPLAY=:0.0 import -window root orig.pngTake a (remote) screenshot
convert -filter catrom -resize '600x>' orig.png 600px_wide.pngShrink to width, computer gen images or screenshots
 mplayer -ao pcm -vo null -vc dummy /tmp/Flash*Extract audio from flash video to audiodump.wav
 ffmpeg -i filename.aviDisplay info about multimedia file
ffmpeg -f x11grab -s xga -r 25 -i :0 -sameq demo.mpgCapture video of an X display
DVD
 for i in $(seq 9); do ffmpeg -i $i.avi -target pal-dvd $i.mpg; doneConvert video to the correct encoding and aspect for DVD
 dvdauthor -odvd -t -v "pal,4:3,720xfull" *.mpg;dvdauthor -odvd -TBuild DVD file system. Use 16:9 for widescreen input
 growisofs -dvd-compat -Z /dev/dvd -dvd-video dvdBurn DVD file system to disc
Unicode
python -c "import unicodedata as u; print u.name(unichr(0x2028))"Lookup a unicode character
uconv -f utf8 -t utf8 -x nfcNormalize combining characters
printf '\300\200' | iconv -futf8 -tutf8 >/dev/nullValidate UTF-8
printf 'ŨTF8\n' | LANG=C grep --color=always '[^ -~]\+'Highlight non printable ASCII chars in UTF-8
fc-match -s "sans:lang=zh"List font match order for language and style
Development
gcc -march=native -E -v -</dev/null 2>&1|sed -n 's/.*-mar/-mar/p'Show autodetected gcc tuning params. See also gcccpuopt
for i in $(seq 4); do { [ $i = 1 ] && wget http://url.ie/6lko -qO-||
./a.out; } | tee /dev/tty | gcc -xc - 2>/dev/null; done
Compile and execute C code from stdin
cpp -dM /dev/nullShow all predefined macros
echo "#include <features.h>" | cpp -dN | grep "#define __USE_"Show all glibc feature macros
 gdb -tuiDebug showing source code context in separate windows
udev
udevadm info -a -p $(udevadm info -q path -n /dev/input/mouse0)List udev attributes of a device, for matching rules etc.
udevadm test /sys/class/input/mouse0See how udev rules are applied for a device
#udevadm control --reload-rulesReload udev rules after modification
Extended Attributes (Note you may need to (re)mount with "acl" or "user_xattr" options)
getfacl .Show ACLs for file
setfacl -m u:nobody:r .Allow a specific user to read file
setfacl -x u:nobody .Delete a specific user's rights to file
 setfacl --default -m group:users:rw- dir/Set umask for a for a specific dir
 getcap fileShow capabilities for a program
 setcap cap_net_raw+ep your_gtk_progAllow gtk program raw access to network
stat -c%C .Show SELinux context for file
 chcon ... fileSet SELinux context for file (see also restorecon)
getfattr -m- -d .Show all extended attributes (includes selinux,acls,...)
setfattr -n "user.foo" -v "bar" .Set arbitrary user attributes
BASH specific
echo 123 | tee >(tr 1 a) | tr 1 bSplit data to 2 commands (using process substitution)
 meld local_file <(ssh host cat remote_file)Compare a local and remote file (using process substitution)
Multicore
taskset -c 0 nprocRestrict a command to certain processors
find -type f -print0 | xargs -r0 -P$(nproc) -n10 md5sumProcess files in parallel over available processors
 sort -m <(sort data1) <(sort data2) >data.sortedSort separate data files over 2 processors

Linux Command Line Reference for Common Operations

By: Onlyone
13 December 2011 at 11:45

This is a linux command line reference for common operations.
Examples marked with • are valid/safe to paste without modification into a terminal, so
you may want to keep a terminal window open while reading this so you can cut & paste.
All these commands have been tested both on Fedora and Ubuntu.
See also more linux commands.
CommandDescription
apropos whatisShow commands pertinent to string. See also threadsafe
man -t ascii | ps2pdf - > ascii.pdfmake a pdf of a manual page
which commandShow full path name of command
time commandSee how long a command takes
time catStart stopwatch. Ctrl-d to stop. See also sw
dir navigation
cd -Go to previous directory
cdGo to $HOME directory
(cd dir && command)Go to dir, execute command and return to current dir
pushd .Put current dir on stack so you can popd back to it
file searching
alias l='ls -l --color=auto'quick dir listing
ls -lrtList files by date. See also newest and find_mm_yyyy
ls /usr/bin | pr -T9 -W$COLUMNSPrint in 9 columns to width of terminal
find -name '*.[ch]' | xargs grep -E 'expr'Search 'expr' in this dir and below. See also findrepo
find -type f -print0 | xargs -r0 grep -F 'example'Search all regular files for 'example' in this dir and below
find -maxdepth 1 -type f | xargs grep -F 'example'Search all regular files for 'example' in this dir
find -maxdepth 1 -type d | while read dir; do echo $dir; echo cmd2; doneProcess each item with multiple commands (in while loop)
find -type f ! -perm -444Find files not readable by all (useful for web site)
find -type d ! -perm -111Find dirs not accessible by all (useful for web site)
locate -r 'file[^/]*\.txt'Search cached index for names. This re is like glob *file*.txt
look referenceQuickly search (sorted) dictionary for prefix
grep --color reference /usr/share/dict/wordsHighlight occurances of regular expression in dictionary
archives and compression
gpg -c fileEncrypt file
gpg file.gpgDecrypt file
tar -c dir/ | bzip2 > dir.tar.bz2Make compressed archive of dir/
bzip2 -dc dir.tar.bz2 | tar -xExtract archive (use gzip instead of bzip2 for tar.gz files)
tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg'Make encrypted archive of dir/ on remote machine
find dir/ -name '*.txt' | tar -c --files-from=- | bzip2 > dir_txt.tar.bz2Make archive of subset of dir/ and below
find dir/ -name '*.txt' | xargs cp -a --target-directory=dir_txt/ --parentsMake copy of subset of dir/ and below
(tar -c /dir/to/copy) | ( cd /where/to/ && tar -x -p )Copy (with permissions) copy/ dir to /where/to/ dir
(cd /dir/to/copy && tar -c .) | ( cd /where/to/ && tar -x -p )Copy (with permissions) contents of copy/ dir to /where/to/
(tar -c /dir/to/copy ) | ssh -C user@remote 'cd /where/to/ && tar -x -p'Copy (with permissions) copy/ dir to remote:/where/to/ dir
dd bs=1M if=/dev/sda | gzip | ssh user@remote 'dd of=sda.gz'Backup harddisk to remote machine
rsync (Network efficient file copier: Use the --dry-run option for testing)
rsync -P rsync://rsync.server.com/path/to/file fileOnly get diffs. Do multiple times for troublesome downloads
rsync --bwlimit=1000 fromfile tofileLocally copy with rate limit. It's like nice for I/O
rsync -az -e ssh --delete ~/public_html/ remote.com:'~/public_html'Mirror web site (using compression and encryption)
rsync -auz -e ssh remote:/dir/ . && rsync -auz -e ssh . remote:/dir/Synchronize current directory with remote one
ssh (Secure SHell)
ssh $USER@$HOST commandRun command on $HOST as $USER (default command=shell)
ssh -f -Y $USER@$HOSTNAME xeyesRun GUI command on $HOSTNAME as $USER
scp -p -r $USER@$HOST: file dir/Copy with permissions to $USER's home directory on $HOST
scp -c arcfour $USER@$LANHOST: bigfileUse faster crypto for local LAN. This might saturate GigE
ssh -g -L 8080:localhost:80 root@$HOSTForward connections to $HOSTNAME:8080 out to $HOST:80
ssh -R 1434:imap:143 root@$HOSTForward connections from $HOST:1434 in to imap:143
ssh-copy-id $USER@$HOSTInstall public key for $USER@$HOST for password-less log in
wget (multi purpose download tool)
(cd dir/ && wget -nd -pHEKk http://www.pixelbeat.org/cmdline.html)Store local browsable version of a page to the current dir
wget -c http://www.example.com/large.fileContinue downloading a partially downloaded file
wget -r -nd -np -l1 -A '*.jpg' http://www.example.com/dir/Download a set of files to the current directory
wget ftp://remote/file[1-9].iso/FTP supports globbing directly
wget -q -O- http://www.pixelbeat.org/timeline.html | grep 'a href' | headProcess output directly
echo 'wget url' | at 01:00Download url at 1AM to current dir
wget --limit-rate=20k urlDo a low priority download (limit to 20KB/s in this case)
wget -nv --spider --force-html -i bookmarks.htmlCheck links in a file
wget --mirror http://www.example.com/Efficiently update a local copy of a site (handy from cron)
networking (Note ifconfig, route, mii-tool, nslookup commands are obsolete)
ethtool eth0Show status of ethernet interface eth0
ethtool --change eth0 autoneg off speed 100 duplex fullManually set ethernet interface speed
iwconfig eth1Show status of wireless interface eth1
iwconfig eth1 rate 1Mb/s fixedManually set wireless interface speed
iwlist scanList wireless networks in range
ip link showList network interfaces
ip link set dev eth0 name wanRename interface eth0 to wan
ip link set dev eth0 upBring interface eth0 up (or down)
ip addr showList addresses for interfaces
ip addr add 1.2.3.4/24 brd + dev eth0Add (or del) ip and mask (255.255.255.0)
ip route showList routing table
ip route add default via 1.2.3.254Set default gateway to 1.2.3.254
host pixelbeat.orgookup DNS ip address for name or vice versaL
hostname -iLookup local ip address (equivalent to host `hostname`)
whois pixelbeat.orgLookup whois info for hostname or ip address
netstat -tuplList internet services on a system
netstat -tupList active connections to/from system
windows networking (Note samba is the package that provides all this windows specific networking support)
smbtreeFind windows machines. See also findsmb
nmblookup -A 1.2.3.4Find the windows (netbios) name associated with ip address
smbclient -L windows_boxList shares on windows machine or samba server
mount -t smbfs -o fmask=666,guest //windows_box/share /mnt/shareMount a windows share
echo 'message' | smbclient -M windows_boxSend popup to windows machine (off by default in XP sp2)
text manipulation (Note sed uses stdin and stdout. Newer versions support inplace editing with the -i option)
sed 's/string1/string2/g'Replace string1 with string2
sed 's/\(.*\)1/\12/g'Modify anystring1 to anystring2
sed '/ *#/d; /^ *$/d'Remove comments and blank lines
sed ':a; /\\$/N; s/\\\n//; ta'Concatenate lines with trailing \
sed 's/[ \t]*$//'Remove trailing spaces from lines
sed 's/\([`"$\]\)/\\\1/g'Escape shell metacharacters active within double quotes
seq 10 | sed "s/^/      /; s/ *\(.\{7,\}\)/\1/"Right align numbers
sed -n '1000{p;q}'Print 1000th line
sed -n '10,20p;20q'Print lines 10 to 20
sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q'Extract title from HTML web page
sed -i 42d ~/.ssh/known_hostsDelete a particular line
sort -t. -k1,1n -k2,2n -k3,3n -k4,4nSort IPV4 ip addresses
echo 'Test' | tr '[:lower:]' '[:upper:]'Case conversion
tr -dc '[:print:]' < /dev/urandomFilter non printable characters
tr -s '[:blank:]' '\t' </proc/diskstats | cut -f4cut fields separated by blanks
history | wc -lCount lines
set operations (Note you can export LANG=C for speed. Also these assume no duplicate lines within a file)
sort file1 file2 | uniqUnion of unsorted files
sort file1 file2 | uniq -dIntersection of unsorted files
sort file1 file1 file2 | uniq -uDifference of unsorted files
sort file1 file2 | uniq -uSymmetric Difference of unsorted files
join -t'\0' -a1 -a2 file1 file2Union of sorted files
join -t'\0' file1 file2Intersection of sorted files
join -t'\0' -v2 file1 file2Difference of sorted files
join -t'\0' -v1 -v2 file1 file2Symmetric Difference of sorted files
math
echo '(1 + sqrt(5))/2' | bc -lQuick math (Calculate φ). See also bc
seq -f '4/%g' 1 2 99999 | paste -sd-+ | bc -lCalculate π the unix way
echo 'pad=20; min=64; (100*10^6)/((pad+min)*8)' | bcMore complex (int) e.g. This shows max FastE packet rate
echo 'pad=20; min=64; print (100E6)/((pad+min)*8)' | pythonPython handles scientific notation
echo 'pad=20; plot [64:1518] (100*10**6)/((pad+x)*8)' | gnuplot -persistPlot FastE packet rate vs packet size
echo 'obase=16; ibase=10; 64206' | bcBase conversion (decimal to hexadecimal)
echo $((0x2dec))Base conversion (hex to dec) ((shell arithmetic expansion))
units -t '100m/9.58s' 'miles/hour'Unit conversion (metric to imperial)
units -t '500GB' 'GiB'Unit conversion (SI to IEC prefixes)
units -t '1 googol'Definition lookup
seq 100 | (tr '\n' +; echo 0) | bcAdd a column of numbers. See also add and funcpy
calendar
cal -3Display a calendar
cal 9 1752Display a calendar for a particular month year
date -d friWhat date is it this friday. See also day
[ $(date -d '12:00 +1 day' +%d) = '01' ] || exitexit a script unless it's the last day of the month
date --date='25 Dec' +%AWhat day does xmas fall on, this year
date --date='@2147483647'Convert seconds since the epoch (1970-01-01 UTC) to date
TZ='America/Los_Angeles' dateWhat time is it on west coast of US (use tzselect to find TZ)
date --date='TZ="America/Los_Angeles" 09:00 next Fri'What's the local time for 9AM next Friday on west coast US
locales
printf "%'d\n" 1234Print number with thousands grouping appropriate to locale
BLOCK_SIZE=\'1 ls -lUse locale thousands grouping in ls. See also l
echo "I live in `locale territory`"Extract info from locale database
LANG=en_IE.utf8 locale int_prefixLookup locale info for specific country. See also ccodes
locale -kc $(locale | sed -n 's/\(LC_.\{4,\}\)=.*/\1/p') | lessList fields available in locale database
recode (Obsoletes iconv, dos2unix, unix2dos)
recode -l | lessShow available conversions (aliases on each line)
recode windows-1252.. file_to_change.txtWindows "ansi" to local charset (auto does CRLF conversion)
recode utf-8/CRLF.. file_to_change.txtWindows utf8 to local charset
recode iso-8859-15..utf8 file_to_change.txtLatin9 (western europe) to utf8
recode ../b64 < file.txt > file.b64Base64 encode
recode /qp.. < file.qp > file.txtQuoted printable decode
recode ..HTML < file.txt > file.htmlText to HTML
recode -lf windows-1252 | grep euroLookup table of characters
echo -n 0x80 | recode latin-9/x1..dumpShow what a code represents in latin-9 charmap
echo -n 0x20AC | recode ucs-2/x2..latin-9/xShow latin-9 encoding
echo -n 0x20AC | recode ucs-2/x2..utf-8/xShow utf-8 encoding
CDs
gzip < /dev/cdrom > cdrom.iso.gzSave copy of data cdrom
mkisofs -V LABEL -r dir | gzip > cdrom.iso.gzCreate cdrom image from contents of dir
mount -o loop cdrom.iso /mnt/dirMount the cdrom image at /mnt/dir (read only)
cdrecord -v dev=/dev/cdrom blank=fastClear a CDRW
gzip -dc cdrom.iso.gz | cdrecord -v dev=/dev/cdrom -Burn cdrom image (use dev=ATAPI -scanbus to confirm dev)
cdparanoia -BRip audio tracks from CD to wav files in current dir
cdrecord -v dev=/dev/cdrom -audio -pad *.wavMake audio CD from all wavs in current dir (see also cdrdao)
oggenc --tracknum='track' track.cdda.wav -o 'track.ogg'Make ogg file from wav file
disk space (See also FSlint)
ls -lSrShow files by size, biggest last
du -s * | sort -k1,1rn | headShow top disk users in current dir. See also dutop
du -hs /home/* | sort -k1,1hSort paths by easy to interpret disk usage
df -hShow free space on mounted filesystems
df -iShow free inodes on mounted filesystems
fdisk -lShow disks partitions sizes and types (run as root)
rpm -q -a --qf '%10{SIZE}\t%{NAME}\n' | sort -k1,1nList all packages by installed size (Bytes) on rpm distros
dpkg-query -W -f='${Installed-Size;10}\t${Package}\n' | sort -k1,1nList all packages by installed size (KBytes) on deb distros
dd bs=1 seek=2TB if=/dev/null of=ext3.testCreate a large test file (taking no space). See also truncate
> filetruncate data of file or create an empty file
monitoring/debugging
tail -f /var/log/messagesMonitor messages in a log file
strace -c ls >/dev/nullSummarise/profile system calls made by command
strace -f -e open ls >/dev/nullList system calls made by command
strace -f -e trace=write -e write=1,2 ls >/dev/nullMonitor what's written to stdout and stderr
ltrace -f -e getenv ls >/dev/nullList library calls made by command
lsof -p $$List paths that process id has open
lsof ~List processes that have specified path open
tcpdump not port 22Show network traffic except ssh. See also tcpdump_not_me
ps -e -o pid,args --forestList processes in a hierarchy
ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed '/^ 0.0 /d'List processes by % cpu usage
ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNSList processes by mem (KB) usage. See also ps_mem.py
ps -C firefox-bin -L -o pid,tid,pcpu,stateList all threads for a particular process
ps -p 1,$$ -o etime=List elapsed wall time for particular process IDs
last rebootShow system reboot history
free -mShow amount of (remaining) RAM (-m displays in MB)
watch -n.1 'cat /proc/interrupts'Watch changeable data continuously
udevadm monitorMonitor udev events to help configure rules
system information (see also sysinfo) ('#' means root access is required)
uname -aShow kernel version and system architecture
head -n1 /etc/issueShow name and version of distribution
cat /proc/partitionsShow all partitions registered on the system
grep MemTotal /proc/meminfoShow RAM total seen by the system
grep "model name" /proc/cpuinfoShow CPU(s) info
lspci -tvShow PCI info
lsusb -tvShow USB info
mount | column -tList mounted filesystems on the system (and align output)
grep -F capacity: /proc/acpi/battery/BAT0/infoShow state of cells in laptop battery
#dmidecode -q | lessDisplay SMBIOS/DMI information
#smartctl -A /dev/sda | grep Power_On_HoursHow long has this disk (system) been powered on in total
#hdparm -i /dev/sdaShow info about disk sda
#hdparm -tT /dev/sdaDo a read speed test on disk sda
#badblocks -s /dev/sdaTest for unreadable blocks on disk sda
interactive (see also linux keyboard shortcuts)
readlineLine editor used by bash, python, bc, gnuplot, ...
screenVirtual terminals with detach capability, ...
mcPowerful file manager that can browse rpm, tar, ftp, ssh, ...
gnuplotInteractive/scriptable graphing
linksWeb browser
xdg-open .open a file or url with the registered desktop application
© Jan 7 2008   [Comments] | [Add link to ...] |

Linux系统信息查看命令大全

By: Onlyone
13 December 2011 at 11:41

最近看了一些Linux命令行的文章,在系统信息查看方面学到不少命令。发现这些系统信息查看命令也可以总结出一篇小小的东西来了。

另外这里还有非常多的命令, 可以作为参考。


系统
# uname -a               # 查看内核/操作系统/CPU信息
# head -n 1 /etc/issue   # 查看操作系统版本
# cat /proc/cpuinfo      # 查看CPU信息
# hostname               # 查看计算机名
# lspci -tv              # 列出所有PCI设备
# lsusb -tv              # 列出所有USB设备
# lsmod                  # 列出加载的内核模块
# env                    # 查看环境变量
资源
# free -m                # 查看内存使用量和交换区使用量
# df -h                  # 查看各分区使用情况
# du -sh <目录名>        # 查看指定目录的大小
# grep MemTotal /proc/meminfo   # 查看内存总量
# grep MemFree /proc/meminfo    # 查看空闲内存量
# uptime                 # 查看系统运行时间、用户数、负载
# cat /proc/loadavg      # 查看系统负载
磁盘和分区
# mount | column -t      # 查看挂接的分区状态
# fdisk -l               # 查看所有分区
# swapon -s              # 查看所有交换分区
# hdparm -i /dev/hda     # 查看磁盘参数(仅适用于IDE设备)
# dmesg | grep IDE       # 查看启动时IDE设备检测状况
网络
# ifconfig               # 查看所有网络接口的属性
# iptables -L            # 查看防火墙设置
# route -n               # 查看路由表
# netstat -lntp          # 查看所有监听端口
# netstat -antp          # 查看所有已经建立的连接
# netstat -s             # 查看网络统计信息
进程
# ps -ef                 # 查看所有进程
# top                    # 实时显示进程状态
用户
# w                      # 查看活动用户
# id <用户名>            # 查看指定用户信息
# last                   # 查看用户登录日志
# cut -d: -f1 /etc/passwd   # 查看系统所有用户
# cut -d: -f1 /etc/group    # 查看系统所有组
# crontab -l             # 查看当前用户的计划任务
服务
# chkconfig --list       # 列出所有系统服务
# chkconfig --list | grep on    # 列出所有启动的系统服务
程序
# rpm -qa                # 查看所有安装的软件包

附加一张总结的很好Linux常用命定的图片:
Linux 文件结构大全

❌
❌