linux shell 技巧

Posted 8 months, 3 weeks ago at 2:44 am. 0 comments

apropos ls

显示 ls 的相关信息

man -t ls | ps2pdf -> ls.pdf

输出 ls 手册为 postscript 然后转成 pdf

which ls

显示 ls 的完整路径

time ls 执行 ls 然后输出执行的时间

alias l=’ls -l’

定义 ls 别名,l 即可执行 ls -l 命令

cd -

回到刚才的目录

cd

进入 home 目录(等同于 cd ~)

cd 目录 && ls -l

进入“目录”,执行 ls -l 命令,然后返回当前目录

find -type f ! -perm -444

查找所有权限 444 以下的文件(不可读)

ls | pr -T9

9列显示

look fire

快速搜索字典中 fire 开头的单词

grep –color fire /usr/share/dict/words

在字典中高亮显示包含 fire 的单词

gpg -c file
gpg file.gpg

加(解)密文件

dd bs=1M if=/dev/sda | gzip | ssh user@remote ‘dd of=sda.gz’

备份硬盘数据到远程 ssh 主机

ssh -f -Y USER@HOSTNAME firefox

以 USER 身份登录 HOSTNAME 主机打开 GUI 程序(firefox)

wget -r -nd -np -l1 -A ‘*.jpg’ http://www.example.com/dir/

下载 http://www.example.com/dir/ 目录中的所有 jpg 图片(如果服务器允许目录浏览的话,否则返回 403 forbidden 错误)

wget –limit-rate=20k http://111.com

限制 wget 下载速度 20k/s

smbtree

寻找局域网中的 windows 主机

nmblookup -A 192.168.100.1

解析目标机器的 NetBIOS 名、组等

smbclient -L 192.168.100.97

查看 windows 主机的共享目录

mount -t smbfs -o fmask=666,guest //windows_box/share /mnt/share

挂接windows共享目录

Popularity: 31% [?]

Tags: ,

linux shell diary

Posted 11 months, 1 week ago at 11:32 am. 0 comments

sure,my ubuntu feisty amd64 is all ok now.though i have no scim to input chinese.But everything is ok include sound,updating and touring the web…

uname -a
Linux guoshuang-laptop 2.6.20-12-generic #2 SMP Wed Mar 21 19:34:23 UTC 2007 x86_64 GNU/Linux

rocinfo — Display system status gathered from /proc folder
Summary:
procinfo gathers system data from the /proc directory and prints it nicely formatted on the standard output device.
Example:
$ procinfo — Show MEM,CPU Usage and IRQ details.
$ procinfo -f — Run in Full screen mode and update will happen for every 5 Sec.
$ procinfo -n.1 — Run in […]

Popularity: 15% [?]

Tags: ,

passwd 密码修改命令

Posted 11 months, 1 week ago at 11:32 am. 0 comments

passwd
修改密码

passwd user1
更改user1的密码

passwd -l user1
锁定 user1 帐号

passwd -u user1
解锁 user1 帐号

passwd -d user1
删除 user1 密码

passwd -S user1
显示 user1 密码信息

passwd -n 30 user1
设置 user1 最小生命周期

Popularity: 13% [?]

Tags:

设置 firefox 2.x 强制在 tab 而不是 新窗口打开

Posted 11 months, 1 week ago at 11:32 am. 0 comments

firefox 2.x 强制在 tab 而不是 新窗口打开
about:config,设置 browser.link.open_newwindow 为 3 即可。

only now tab show close buton
browser.tabs.closeButtons -> 0

always show tabs
browser.tabs.autoHide false

其他资料

firefox 2.x 的 single window mode

about:config里面将
browser. block. target_new_window布尔值设置为true
browser. link. open_external整数值设置为3
browser. link. open_newwindow整数值设置为3
browser. link. open_newwindow. restriction整数值设置为0

wall 在终端中发信息给其它用户。ctrl+d 结束

tty 发,tty 和 x win 皆可收
x win shell 发,tty 收不到。

点击这里打开新窗口浏览此网页

Popularity: 21% [?]

Tags: , , ,

linux shell 快捷方式

Posted 11 months, 1 week ago at 11:32 am. 0 comments

原文来自 Bash Shell Keyboard Shortcuts For Linux Users,大部分快捷方式我以前一无所知…

# Ctrl + A - Go to the beginning of the line you are currently typing on
# Ctrl + E - Go to the end of the line you are currently typing on
切到命令行开始|结尾

# Ctrl + L - Clears the Screen, similar to the clear command
清屏,类似于 clear 命令

# Ctrl + U - Clears the line before the cursor position. If you are at the end of the line, clears the entire line.
清除光标以前

# Ctrl + H - Same as backspace
退格键 backspace

# Ctrl + R - Let’s you search through previously used commands
从命令历史中找

# Ctrl + C - Kill whatever you are running
终止命令

# Ctrl + D - Exit the current shell
退出 shell

# Ctrl + Z - Puts whatever you are running into a suspended background process. fg restores it.
??

# Ctrl + W - Delete the word before the cursor
清除光标之前

# Ctrl + K - Clear the line after the cursor
清除光标之后

# Ctrl + T - Swap the last two characters before the cursor
# Esc + T - Swap the last two words before the cursor
切换光标前最后两个字母(单词)

# Alt + F - Move cursor forward one word on the current line
# Alt + B - Move cursor backward one word on the current line
??在 ubuntu x windows终端中会切换到菜单!tty 可能可以

# Tab - Auto-complete files and folder names
自动补全

# Ctrl + Y - to paste it (as in delete and copy) all text in front of the cursor
粘贴(刚才 ctrl+w 或者 ctrl+k 的内容)

# Esc + . (or Esc + Underscore) - Insert Last Argument
??

# Ctrl + b - Move back a character
# Ctrl + f - Move forward a character
向前|后移动一个字母

# Ctrl + r - Search the history backwards
??
# Ctrl + xx - Move between EOL and current cursor position
光标在当前位置和 EOL 之间切换(EOL end of line?但我实验,是在开头和当前位置之间切换,怎么理解?谁知道?)

# Ctrl + x @ - Show possible hostname completions

# Alt +
# Alt + > - Move to the last line in the history

# Alt + ? - Show current completion list

# Alt + * - Insert all possible completions

# Alt + / - Attempt to complete filename

# Alt + . - Yank last argument to previous command

# Alt + c - Capitalize the word

# Alt + d - Delete word

# Alt + l - Make word lowercase

# Alt + n - Search the history forwards non-incremental

# Alt + p - Search the history backwards non-incremental

# Alt + r - Recall command

# Alt + t - Move words around

# Alt + u - Make word uppercase

# Alt + back-space - Delete backward from cursor

# Here “2T” means Press TAB twice

# $ 2T - All available commands(common)

# $ (string) 2T - All available commands starting with (string)

# $ /2T - Entire directory structure including Hidden one

# $ 2T - Only Sub Dirs inside including Hidden one

# $ *2T - Only Sub Dirs inside without Hidden one

# $ ~2T - All Present Users on system from “/etc/passwd”

# $ $2T - All Sys variables

# $ @2T - Entries from “/etc/hosts”

# $ =2T - Output like ls or dir

Popularity: 31% [?]

Tags: , , , , , , ,

提高 feisty 性能

Posted 11 months, 1 week ago at 11:32 am. 0 comments

原文来自 http://xlntsolution.blogspot.com/2007/03/feisty-performance-fly-like-butterfly.html

blogspt 似乎再次封掉了,:( 我是通过这个代理看到的

部分内容如下:

sudo gedit /etc/hosts

你会看到类似

127.0.0.1 localhost
127.0.1.1 guoshuang-laptop

这样的内容,在 localost 后面加上你的主机名,如guoshuang-laptop

127.0.0.1 localhost guoshuang-laptop
127.0.1.1 guoshuang-laptop

1. Disable IPv6
At least I dont need IPv6 yet so this is what I do to disable it.
sudo kate /etc/modprobe.d/aliases
And change the line:
alias net-pf-10 ipv6
to:
alias net-pf-10 off #ipv6
This will disable IPv6 on all network interfaces. You need to reboot.

2. Run boot processes in parallel
This will make upstart to run the boot processes in parallel and speed up the boot process.
sudo kate /etc/init.d/rc
Find and change the line:
CONCURRENCY=none
to:
CONCURRENCY=shell

3. Aliasing hostname to localhost
Right or wrong, you decide. But I picked this up in the Ubuntu forums the other day and it does improve the startup of some apps.
sudo kate /etc/hosts
and add you hostname to the first line after localhost like this:
127.0.0.1 localhost yourhost
127.0.1.1 yourhost

4. Disable pango
I know that this is already taken care of in firefox but it still makes a good performance boost to thunderbird and some other apps.
sudo kate /etc/environment
and add:
MOZ_DISABLE_PANGO=”1″

5. Preload
It does what you think. It preloads most common used libs and files = faster startup times on your applications.
sudo apt-get install preload

What about prelink?
Prelink is no longer necessary in feisty. Feisty uses a new linking mechanism called DT_GNU_HASH which speeds up the linking process without the need for continuously running prelink.

6. Swappiness
The default value for vm.swappiness is 60 in Ubuntu Feisty whic is a good default value but if you want to tweak the performance a little bit more you can change this value to a lower value to reduce the load of the swap. If you run the follwing command:
sysctl -q vm.swappiness
You will se that the value is set to 60. And by running:
sudo sysctl vm.swappiness=10
You will change the value from 60 to 10 which will make your system write to swap a lot less and I would recommend this to everyone that has 512 mb of memory or more. If you find that you have very little use of swap set the value to 0. This will not disable the swap but it will make your system write to the swap as little as possible and keep as much as possible in memory. This makes a huge improvment when switching between applications since they are now likley to be in physical ram instead of on the swap partition.

To set your value permanent you need to change the sysctl.conf file:
sudo kate /etc/sysctl.conf
Add the line
vm.swappiness=10
To the end of the file. This way it will be set upon boot.

I’ve found that the value of 5 works very good for my use and I have 1 GB of memory.

7. Profile grub
There is a option to grub called profile which will profile your startup. What it does is that it kind of indexing all the files read during boot/startup and later on it will find and read those files quicker.

Hit the escape button when booting to get to the grub menu.
Select your default boot kernel and hit the e button.
Go down to the second line and hit the e button again.
Add profile to the end of the line and press enter.
Hit the b button to boot with your new option.

The first time it will take a little bit longer to boot because it has to build the index (or whatever they want to call it) but every boot after this will be a lot smoother.
You need to do this every time you update your kernel or have made other huge changes to your system that might affect the files needed during boot.

The following could cause your system to be unstable or even unable to boot so please use them care…

8. sysv-rc-conf
Install sysv-rc-conf and disable the services you don’t need at startup.
As an example. On my computer I don’t have bluetooth so I don’t need to start it at boot time.
So simply disable what ever you don’t have or use.

sudo apt-get install sysv-rc-conf
and then run:
sudo sysv-rc-conf

9. Kernel hacking
Even thought the new kernel in feisty is very good and already tuned a bit there still are some things you can do to the kernel the will make your system snappier and boot up even faster.

Use this thread from the ubuntu forums as a guide on how to compile your own kernel.
master kernel thread

What I do is that I make sure to add my file systems I use to the kernel instead of loading them as modules. Take out whatever I don’t have or use and then compile my new and hopefully improved kernel ;)
10. Filesystem setup
The choice and use of the file system is a big issue when dealing with performance. Depending on your usage of your system you might need to configure your filesystem different.

For my usage I like to use the following setup (which I think is a good desktop setup)

Mountpoint

filesystem

Size

/boot

ext2

100 MB

/root

LVM, VG=system, xfs

6 GB

/swap

LVM, VG=system, swap

The size of RAM in your computer. Making it smaller and you will not be able to hibernate.

/home

LVM, VG=system, xfs

1 GB, or the rest of the space in that VG

/data

LVM, VG=data, xfs

The rest of the free space

Using the following options in fstab for all my xfs partitions:
noatime,nodiratime,logbufs=8

Using LVM can really speed up the disk performance. And you get a lot of other good stuff with it as well. Read more about LVM here.
I choose to have /root and /home on one VolumeGroup and /data on another simply because I can then split them up on diffrent physical disks and have them spanning over multiple physical disks witch really speeds up the reads and writes.

At the moment this is pretty much it but I will update this as soon as I discover more performance tunings…

Tuning applications

Not so much to add here but this what I like to do.

1. Firefox
Use swiftfox instead. It’s optimized for your CPU.
Install the fasterfox add-on
If it’s not already set, disable IPv6. In the url enter about:config and find the ipv6 entry and disable it.
Install adblock plus add-on
to disable ad’s it helps a lot :)
2. openoffice
If you don’t need that extras that java JRE provides then simply disable it openoffice. That’s what I do.

Once Feisty is released I will have a script done that all you brave people can run that will do most of this in one go :)
I will also write down the kernel options that I use to compile my kernel for those who are interested.

But until then, use this and enjoy a much faster and smoother running Feisty.

Popularity: 44% [?]

Tags: , , , , , , , , , , ,

ubuntu 软件安装包备份

Posted 11 months, 1 week ago at 11:32 am. 0 comments

原文来自 Backup installed packages on ubuntu,蛮有趣的,大约内容如下:

所有通过 synaptic(新立得)、apt-get、aptitude(shell 模式的新立得)安装的软件,都会在

/var/cache/apt/archives

留下 .deb 安装包。备份这些文件就可以很方便的重装或者新装ubuntu。另外,作者还介绍了一个图形化的刻盘工具—APTonCD

APTonCD is a tool with a graphical interface which allows you to create one or more CDs or DVDs (you choose the type of media) with all of the packages you’ve downloaded via APT-GET or APTITUDE, creating a removable repository that you can use on other computers.One thing you need to remember this will create backup all the packages installed using apt-get,synaptic because these package arcives are stored in /var/cache/apt/archives

APTonCD will also allow you to automatically create media with all of your .deb packages located in one especific repository, so that you can install them into your computers without the need for an internet conection.

Popularity: 32% [?]

Tags: , , , , , ,

ubuntu 启动器权限问题

Posted 11 months, 1 week ago at 11:32 am. 0 comments

这两天发现 azureus 和 virtulabox 不能直接在菜单中打开,在 shell 里 sudo+命令可以,估计就是权限的问题。但这样毕竟不方便啊,解决方法暂为

修改启动器,前面加上 gksudo。

BTW:我还常常使用 sudo nautilus 来修改权限或者删除一些主账号不能删除的文件。

You are not a member of the “vboxusers” group. Please add yourself to this
group before starting VirtualBox.

Popularity: 10% [?]

Tags: , ,

linux 服务器配置资料二

Posted 11 months, 1 week ago at 11:32 am. 0 comments

as4+postfix+cyrus-sasl+mysql+postfixadmin+courier-imap+courier-maildrop+squirrelmail+clamav+spamassassin+amavisd-new

转载请注明出处
最后更新日期:2006年8月3日
2004年10左右成稿

1.mysql

2.apache

3.php

4.cyrus-sasl

5.postfix

6.postfixadmin

7.courier-authlib

8.courier-imap

9.courier-maildrop

10.测试

11.webmail
11.1.squirrelmail

12.clamav

13.amavisd-new

14.spamassassin

15.附:启动脚本

本文用到的软件

MySQL 5.0.15
网站:http://www.mysql.com
下载
APACHE 2.0.55
网站:http://www.apache.org
下载
PHP 4.4.1
网站:http://www.php.net
下载
Cyrus-SASL 2.1.21
网站:http://asg.web.cmu.edu/sasl
下载
Postfix 2.2.5
网站:http://www.postfix.org
下载
PostfixAdmin 2.1.0
网站:http://www.postfixadmin.com
下载
Courier-authlib 0.57
网站:http://www.courier-mta.org/authlib
下载
Courier-IMAP 4.0.6
网站:http://www.courier-mta.org/imap
下载
Courier-maildrop 2.0.1
网站:http://www.courier-mta.org/maildrop
下载
SquirrelMail 1.4.5
网站:http://www.squirrelmail.org
下载
Extmail 0.20
网站:http://www.extmail.org
下载
clamav 0.87
网站:http://www.clamav.net
下载
amavisd-new 2.3.3
网站:http://www.ijs.si/software/amavisd
下载
Spamassassin 3.1.0
网站:http://spamassassin.apache.org
下载
我以前那篇文章中密码加密有问题(密码一加密,smtp认证就通不过),所以下定决心更新一下。这次sasl密码验证机制改为authdaemond(感谢网友606),并把测试部分单独列出来。很多人问起我的安装环境,我安装linux的时候,只选了开发工具,其他的都没选,还有,这些软件包安装的时候都没有依赖性问题,有的话,我也提出来了。

1.安装 mysql 5.0.15
# wget http://dev.mysql.com/get/Downloads/MySQL-5…ysql.new21.com/
# tar zxvf mysql-5.0.15.tar.gz
# cd cd mysql-5.0.15
# groupadd mysql
# useradd -g mysql mysql
# CFLAGS=”-O3″ CXX=gcc CXXFLAGS=”-O3 -felide-constructors -fno-exceptions -fno-rtti” \
./configure –prefix=/usr/local/mysql \
–enable-assembler –with-mysqld-ldflags=-all-static –with-charset=gbk
# make
# make install
# cp support-files/my-medium.cnf /etc/my.cnf

设置自启动
# cp support-files/mysql.server /etc/rc.d/init.d/mysqld
# chmod 755 /etc/rc.d/init.d/mysqld
# chkconfig –add mysqld

安装完以后要初始化数据库
# cd /usr/local/mysql
# /usr/local/mysql/bin/mysql_install_db –user=mysql
# chown -R root .
# chown -R mysql var
# chgrp -R mysql .

好了,至此mysql安装完毕,你可以这样起动你的mysql服务
# service mysqld start

为了能让系统找到mysql,请运行如下命令
# PATH=$PATH:/usr/local/mysql/bin
# export PATH
# echo “/usr/local/mysql/lib/mysql” >> /etc/ld.so.conf
# ldconfig

Go to top.

2.安装 apache 2.0.55
# wget http://apache.freelamp.com/httpd/httpd-2.0.55.tar.bz2
# tar jxvf httpd-2.0.55.tar.bz2
# cd httpd-2.0.55
# ./configure –prefix=/usr/local/apache
# make
# make install

设置自启动
# cp support/apachectl /etc/init.d/httpd

修改/etc/init.d/httpd
# vi /etc/init.d/httpd(前面几行改成如下样子)
#!/bin/sh
#
# Startup script for the Apache Web Server
# chkconfig: - 85 15
# description: Apache is a World Wide Web server. It is used to serve \
# HTML files and CGI.
# processname: httpd
# pidfile: /usr/local/apache/log/httpd.pid
# config: /usr/local/apache/conf/httpd.conf

# chkconfig –add httpd
# chmod 755 /etc/init.d/httpd
# chkconfig httpd on

创建网页根目录
# mkdir /var/www

修改apache配置文件
# vi /usr/local/apache/conf/httpd.conf
//存放网页的目录,原来为DocumentRoot “”,改成:
DocumentRoot “/var/www”
//这句应该和DocumentRoot 的目录保持一致,原来为,改成:

//Indexes:当在目录中找不到DirectoryIndex列表中指定的文件就生成当前目录的文件列表
//FollowSymlinks:允许符号链接跟随,访问不在本目录下的文件
Options Indexes FollowSymLinks
//禁止读取.htaccess配置文件的内容
AllowOverride None
//指定先执行Allow(允许)访问规则,再执行Deny(拒绝)访问规则
Order allow,deny
//设置Allow(允许)访问规则,允许所有连接
Allow from all

启动服务
# service httpd start

Go to top.

3.安装php 4.4.1
# wget http://cn.php.net/get/php-4.4.1.tar.bz2/fr…rom/this/mirror
# tar jxvf php-4.4.1.tar.bz2
# cd php-4.4.1
# ./configure \
–prefix=/usr/local/php \
–with-mysql=/usr/local/mysql \
–with-apxs2=/usr/local/apache/bin/apxs
# make
# make install
# cp php.ini-dist /usr/local/php/lib/php.ini

# vi /usr/local/php/lib/php.ini
;default_charset = “iso-8859-1″
在这行下面加一行
default_charset = “gbk”

# vi /usr/local/apache/conf/httpd.conf
找到#AddType application/x-tar .tgz 这行,在下面加两行
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
找到下面一行在后面加上index.php,这表示网站的默认页也能够为index.php
DirectoryIndex index.html index.html.var index.php
注意:改变了http.conf后,要重启apache服务

Go to top.

4.安装 cyrus-sasl 2.1.21
先关闭as4默认安装的sasl
# mv /usr/lib/sasl /usr/lib/sasl.OFF
# mv /usr/lib/sasl2 /usr/lib/sasl2.OFF

编译安装cyrus-sasl2.1.21
# wget http://ftp.andrew.cmu.edu/pub/cyrus-mail/c…l-2.1.21.tar.gz
# tar zxvf cyrus-sasl-2.1.21.tar.gz
# cd cyrus-sasl-2.1.21
# ./configure \
–disable-anon -enable-plain –enable-login \
–enable-sql –with-mysql=/usr/local/mysql \
–with-mysql-includes=/usr/local/mysql/include/mysql \
–with-mysql-libs=/usr/local/mysql/lib/mysql \
–with-authdaemond
# make
# make install

更新lib库
# echo “/usr/local/lib” >> /etc/ld.so.conf
# ldconfig

重要
# ln -s /usr/local/lib/sasl2 /usr/lib/sasl2

Go to top.

5.安装postfix 2.2.5
如果你的系统上原来有sendmail,先将其停止并将其文件改名
# /etc/init.d/sendmail stop
# chkconfig –level 0123456 sendmail off
# mv /usr/bin/newaliases /usr/bin/newaliases.orig
# mv /usr/bin/mailq /usr/bin/mailq.orig
# mv /usr/sbin/sendmail /usr/sbin/sendmail.orig

开始安装
# groupadd -g 12345 postfix
# useradd -u 12345 -g 12345 -c postfix -d/dev/null -s/sbin/nologin postfix
# groupadd -g 54321 postdrop
# wget ftp://postfix.cn99.com/postfix/official/p…ix-2.2.5.tar.gz
# tar zxvf postfix-2.2.5.tar.gz
# cd postfix-2.2.5
(Building Postfix with SASL authentication and mysql support)
# make -f Makefile.init makefiles \
‘CCARGS=-DHAS_MYSQL -I/usr/local/mysql/include/mysql -DUSE_SASL_AUTH -I/usr/local/include/sasl’ \
‘AUXLIBS=-L/usr/local/mysql/lib/mysql -lmysqlclient -lz -lm -L/usr/local/lib -lsasl2′
# make install

注意:
本例中Mysql安装在/usr/lcoal/mysql,sasl2安装在/usr/lib/sasl2。如果安装路径不同,请自行修改编译时CCARGS和AUXLIBS选项。
在执行make install的时候可能会得到如下的提示:
/usr/libexec/ld-elf.so.1: Shared object “libmysqlclient.so.12″ not found
这是因为mysql不是安装在默认目录中的,所以需要告诉postfix应该到哪里去找libmysqlclient.so.12,使用ldconfig就可以达到这个目的
# echo /usr/local/mysql/lib/mysql >> /etc/ld.so.conf
# ldconfig

Go to top.

6.安装postfixadmin 2.1.0
建立apache和maildrop的用户和组
# groupadd vmail -g 1001
# useradd vmail -u 1001 -g 1001 -s/sbin/nologin -d/dev/null

# vi /usr/local/apache/conf/httpd.conf

User nobody
Group #-1
改为
User vmail
Group vmail

# wget http://high5.net/postfixadmin/download.php…admin-2.1.0.tgz
# tar -zxvf postfixadmin-2.1.0.tgz
# mv postfixadmin-2.1.0 /var/www/postfixadmin
更改权限,假定运行apache的用户和组为vmail
# chown -R vmail:vmail /var/www/postfixadmin
# cd /var/www/postfixadmin
# chmod 640 *.php *.css
# cd /var/www/postfixadmin/admin/
# chmod 640 *.php .ht*
# cd /var/www/postfixadmin/images/
# chmod *.png
# cd /var/www/postfixadmin/languages/
# chmod 640 *.lang
# cd /var/www/postfixadmin/templates/
# chmod 640 *.tpl
# cd /var/www/postfixadmin/users/
# chmod 640 *.php

建立mysql表
# cd /var/www/postfixadmin
# mysql -u root < DATABASE_MYSQL.TXT
# cp config.inc.php.sample config.inc.php
# vi config.inc.php
本例中的配置如下:
$CONF['default_language'] = 'cn';
$CONF['database_type'] = 'mysql';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfixadmin';
$CONF['database_password'] = 'postfixadmin';
$CONF['database_name'] = 'postfix';
$CONF['encrypt'] = 'md5crypt';
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';

邮箱的存储格式使用domain.ltd/username的形式,所以设置:
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';

然后打开浏览器,进入postfixadmin的欢迎界面,点击网页上的setup,看看检查是否通过,记得要删除setup.php文件。然后进入http://www.yourdomain.com/postfixadmin/admin/index.php,就可以新建域名、管理员以及邮箱了。

Go to top.

# vi /etc/postfix/main.cf
#=====================BASE=========================
myhostname = www.test.com
mydomain = test.com
myorigin = $mydomain
mydestination = $myhostname localhost localhost.$mydomain
mynetworks = 127.0.0.0/8
inet_interfaces = all

#=====================Vritual Mailbox settings=========================
virtual_mailbox_base = /var/mailbox
virtual_mailbox_maps = mysql:/etc/postfix/mysql/mysql_virtual_mailbox_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql/mysql_virtual_domains_maps.cf
virtual_alias_domains =
virtual_alias_maps = mysql:/etc/postfix/mysql/mysql_virtual_alias_maps.cf
virtual_uid_maps = static:1001
virtual_gid_maps = static:1001
virtual_transport = maildrop
maildrop_destination_recipient_limit = 1
maildrop_destination_concurrency_limit = 1

#====================QUOTA========================
message_size_limit = 14336000
virtual_mailbox_limit = 20971520
virtual_create_maildirsize = yes
virtual_mailbox_extended = yes
virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_limit_message = Sorry, the user's maildir has overdrawn his diskspace quota, please try again later.
virtual_overquota_bounce = yes

#====================SASL========================
broken_sasl_auth_clients = yes
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_hostname,
reject_non_fqdn_hostname,
reject_unknown_sender_domain,
reject_non_fqdn_sender,
reject_non_fqdn_recipient,
reject_unknown_recipient_domain,
reject_unauth_pipelining,
reject_unauth_destination,
permit
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_security_options = noanonymous
smtpd_sasl_application_name = smtpd
smtpd_banner=$myhostname ESMTP "Version not Available"

Go to top.

建立/var/mailbox并设置权限
# mkdir /var/mailbox
# chown -R vmail:vmail /var/mailbox
# chmod -R ug+rwx,o-rwx /var/mailbox

建立/etc/postfix/mysql文件夹和MySQL查询配置文件
# mkdir /etc/postfix/mysql
1、vi /etc/postfix/mysql/mysql_virtual_alias_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
table = alias
select_field = goto
where_field = address

2、vi /etc/postfix/mysql/mysql_virtual_domains_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
table = domain
select_field = description
where_field = domain
#additional_conditions = and backupmx = '0' and active = '1'

3、vi /etc/postfix/mysql/mysql_virtual_mailbox_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
table = mailbox
select_field = maildir
where_field = username
#additional_conditions = and active = '1'

4、vi /etc/postfix/mysql/mysql_virtual_mailbox_limit_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
table = mailbox
select_field = quota
where_field = username
#additional_conditions = and active = '1'

Go to top.

配置 /usr/local/lib/sasl2/smtpd.conf
sasl密码验证机制为authdaemond
# vi /usr/local/lib/sasl2/smtpd.conf
pwcheck_method:authdaemond
log_level:3
srp_mda:md5
password_format:crypt
mech_list:PLAIN LOGIN
authdaemond_path: /usr/local/var/spool/authdaemon/socket

Go to top.

7.安装Courier-authlib 0.57
新版本的imap不再包含authentication library,必须先安装 Courier authentication library
# wget http://www.courier-mta.org/beta/courier-au...0051004.tar.bz2
# tar jxvf courier-authlib-0.57.20051004.tar.bz2
# cd courier-authlib-0.57.20051004
# ./configure \
--with-redhat \
--with-authmysql=yes \
--with-mailuser=vmail --with-mailgroup=vmail \
--with-mysql-libs=/usr/local/mysql/lib/mysql --with-mysql-includes=/usr/local/mysql/include/mysql/
# make
# make install
# make install-configure

重要
# chmod +x /usr/local/var/spool/authdaemon/

# vi /usr/local/etc/authlib/authdaemonrc
authmodulelist="authmysql"

# vi /usr/local/etc/authlib/authmysqlrc
MYSQL_SERVER localhost
MYSQL_SOCKET /tmp/mysql.sock
MYSQL_DATABASE postfix
MYSQL_USERNAME postfix
MYSQL_PASSWORD postfix
MYSQL_USER_TABLE mailbox
MYSQL_LOGIN_FIELD username
MYSQL_CRYPT_PWFIELD password
MYSQL_UID_FIELD '1001'
MYSQL_GID_FIELD '1001'
MYSQL_HOME_FIELD '/var/mailbox/'
MYSQL_MAILDIR_FIELD maildir
MYSQL_NAME_FIELD name
MYSQL_QUOTA_FIELD concat(quota,'S')
MYSQL_WHERE_CLAUSE active='1'
DEFAULT_DOMAIN test.com
注意:确认在这个文件中不能用空格键(包括行尾),只能用tab键。
确认只使用单引号,比如:'/var/mailbox/','UID','GID'(本文为'1001')
localhost不能用单引号
确认你的/etc/hosts文件中有localhost
编译时如果支持Ipv6可能导致错误
MYSQL_GID_FIELD 和MYSQL_UID_FIELD是maildrop的UID和GID,而不是MySQL的

启动服务
自启动:
# cp courier-authlib.sysvinit /etc/rc.d/init.d/courier-authlib
# chmod 755 /etc/rc.d/init.d/courier-authlib
# chkconfig --level 0123456 courier-authlib on
手动启动服务:
# authdaemond start

Go to top.

8.安装Courier-imap 4.0.6
# wget http://www.courier-mta.org/beta/imap/couri...0051004.tar.bz2
# tar jxvf courier-imap-4.0.6.20051004.tar.bz2
# cd courier-imap-4.0.6.20051004
# ./configure \
--prefix=/usr/local/imap \
--with-redhat \
--disable-root-check \
--enable-unicode=utf-8,iso-8859-1,gb2312,gbk,gb18030 \
--with-trashquota \
--with-dirsync
# make
# make install-strip (先install-strip,如果失败,再make install)
# make install-configure

# vi /usr/local/imap/etc/pop3d
POP3DSTART=YES

# vi /usr/local/imap/etc/imapd
IMAPDSTART=YES

让imap自启动:
# cp courier-imap.sysvinit /etc/rc.d/init.d/courier-imap
# chmod 755 /etc/rc.d/init.d/courier-imap
# chkconfig --level 0123456 courier-imap on

Go to top.

9.安装Courier-maildrop 2.0.1
先装pcre
# wget http://optusnet.dl.sourceforge.net/sourcef...cre-6.3.tar.bz2
# tar jxvf pcre-6.3.tar.bz2
# cd pcre-6.3
# ./configure
# make
# make install

# wget http://optusnet.dl.sourceforge.net/sourcef...p-2.0.1.tar.bz2
# tar jxvf maildrop-2.0.1.tar.bz2
# cd maildrop-2.0.1
# ./configure \
--prefix=/usr/local/maildrop \
--enable-sendmail=/usr/sbin/sendmail \
--enable-trusted-users='root vmail' \
--enable-syslog=1 \
--enable-maildirquota \
--enable-maildrop-uid=1001 \
--enable-maildrop-gid=1001 \
--with-trashquota \
--with-dirsync
# make
# make install
# cp /usr/local/maildrop/bin/maildrop /usr/bin
# chmod a+rx /usr/bin/maildrop

运行maildrop -v应该有如下提示信息:
maildrop 2.0.0 Copyright 1998-2005 Double Precision, Inc.
GDBM extensions enabled.
Courier Authentication Library extension enabled.
Maildir quota extension enabled.
This program is distributed under the terms of the GNU General Public
License. See COPYING for additional information.

新建/etc/maildroprc文件
# vi /etc/maildroprc
logfile "/var/mailbox/maildrop.log"
to "$HOME/$DEFAULT"

# chmod a+r /etc/maildroprc

配置Postfix
# vi /etc/postfix/master.cf
maildrop unix - n n - - pipe
flags=DRhu user=vmail:vmail argv=/usr/local/maildrop/bin/maildrop -w 90 -d ${recipient}

由于maildrop没有建立及删除maildir的功能,因此由脚本实现(是否有什么安全隐患?)
# vi /etc/sudoers
vmail ALL = NOPASSWD: /usr/sbin/maildirmake.sh , /usr/sbin/maildirdel.sh

新建/usr/sbin/maildirmake.sh文件
# vi /usr/sbin/maildirmake.sh
#!/bin/bash
set -e
if [ ! -d /var/mailbox/$1 ]
then
mkdir /var/mailbox/$1
fi
chown -R vmail:vmail /var/mailbox/$1
cd "/var/mailbox/$1"
/usr/local/imap/bin/maildirmake $2
chown -R vmail:vmail /var/mailbox/$1/$2

新建/usr/sbin/maildirdel.sh文件
# vi /usr/sbin/maildirmake.sh
#!/bin/bash
rm -rf /var/mailbox/$1/$2

# chmod 755 /usr/sbin/maildirmake.sh
# chmod 755 /usr/sbin/maildirdel.sh

更改postfixadmin目录及postfixadmin/admin目录下的create-mailbox.php文件
在这两个文件的$tQuota = $CONF['maxquota'];行后加一行(postfixadmin/admin目录下的大概在200行,postfixadmin目录下的大概在?行):
# vi /var/www/postfixadmin/admin/create-mailbox.php (vi /var/www/postfixadmin/create-mailbox.php)
system("sudo /usr/sbin/maildirmake.sh $fDomain ".$_POST['fUsername']);

更改postfixadmin目录及postfixadmin/admin目录下的delete.php文件
在这两个文件的$result = db_query ("SELECT * FROM mailbox WHERE username='$fDelete' AND domain='$fDomain'");行后加几行:
# vi /var/www/postfixadmin/admin/delete.php (vi /var/www/postfixadmin/delete.php)
$userarray=explode("@",$fDelete);
$user=$userarray[0];
$domain=$userarray[1];
system("sudo /usr/sbin/maildirdel.sh $domain $user");

10.测试
启动所有服务
# service httpd start
# service mysqld start
# postfix start
# service courier-authlib start
# service courier-imap start

# netstat -ant | grep "LISTEN"
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN
tcp 0 0 :::110 :::* LISTEN
tcp 0 0 :::143 :::* LISTEN
tcp 0 0 :::80 :::* LISTEN

在postfixadmin中建立一测试帐户test@test.com

测试smtp
# perl -MMIME::Base64 -e 'print encode_base64("test\@test.com");'
dGVzdEB0ZXN0LmNvbQ==
# perl -MMIME::Base64 -e 'print encode_base64("test");'
dGVzdA==

# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
220 www.test.com ESMTP "Version not Available"
ehlo www.test.com
250-www.test.com
250-PIPELINING
250-SIZE 14336000
250-VRFY
250-ETRN
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250 8BITMIME
auth login
334 VXNlcm5hbWU6
dGVzdEB0ZXN0LmNvbQ==
334 UGFzc3dvcmQ6
dGVzdA==
235 Authentication successful

测试POP3和IMAP
# telnet localhost 110
+OK Hello there
user test@test.com
+OK Password required.
pass test
+OK Logged in.
quit
+OK bye-bye

测试maildrop
# maildrop -V 9 -d test@test.com
maildrop: authlib: groupid=1001
maildrop: authlib: userid=1001
maildrop: authlib: logname=test@test.com, home=/var/mailbox/, mail=test.com/test/
maildrop: Changing to /var/mailbox/

ctrl+c退出

Go to top.

11.webmail

11.1.安装squirrelmail 1.4.5
下载squirrelmail及中文包
# wget http://keihanna.dl.sourceforge.net/sourcef...l-1.4.5.tar.bz2
# wget http://optusnet.dl.sourceforge.net/sourcef...0050904.tar.bz2
把squirreelmail解压到/var/www目录下。
# tar jxvf squirrelmail-1.4.5.tar.bz2 -C /var/www/
# mv /var/www/squirrelmail-1.4.5/ /var/www/squirrelmail
解压中文包
# tar jxvf zh_CN-1.4.5-20050904.tar.bz2 -C /var/www/squirrelmail/

在配置squirrelmail之前先下载三个插件:
Quota Usage Version 1.3
# wget http://www.squirrelmail.org/countdl.php?fi....3-1.2.7.tar.gz
Compatibility Version 2.0.2
# wget http://www.squirrelmail.org/countdl.php?fi...ty-2.0.2.tar.gz
Change MySQL Password Version 3.2
# wget http://www.squirrelmail.org/countdl.php?fi....2-1.2.8.tar.gz

把这三个插件解压到squirrelmail的plugin目录下
# tar zxvf quota_usage-1.3-1.2.7.tar.gz -C /var/www/squirrelmail/plugins/
# tar zxvf compatibility-2.0.2.tar.gz -C /var/www/squirrelmail/plugins/
# tar zxvf change_mysqlpass-3.2-1.2.8.tar.gz -C /var/www/squirrelmail/plugins/
第一个插件是用来显示邮箱的使用情况的;第二个和第三个插件是用来修改密码的。
如果不想装这些插件,请跳过。

配置Quota Usage
# cd /var/www/squirrelmail/plugins/quota_usage
# cp config.php.sample config.php

配置Change MySQL Password
# cd /var/www/squirrelmail/plugins/change_mysqlpass
# cp config.php.sample config.php
# vi config.php
更改如下几个变量:
$mysql_database = 'postfix';
$mysql_table = 'mailbox';
$mysql_userid_field = 'username';
$mysql_password_field ='password';
$mysql_manager_id = 'postfix';
$mysql_manager_pw = 'postfix';
$mysql_unixcrypt = 0;
$mysql_MD5crypt = 1;
$use_ssl_for_password_change = 0;

配置squirrelmail
# cd /var/www/squirrelmail
# ./configure
进入10. Languages
把1. Default Language : 的en_US改成zh_CN。
进入8. Plugins,添加这三个插件

# chown -R vmail:vmail /var/www/squirrelmail/data/
# chmod -R 730 /var/www/squirrelmail/data/

打开浏览器输入http://192.168.0.5/squirrelmail/,用test@test.com登陆,你将会在屏幕的左上角看到邮箱的使用情况,你还会看到一条警告信息:
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /var/www/squirrelmail/plugins/change_mysqlpass/functions.php on line 129
这是由于数据库结构不一致造成的,你只要把functions.php中的129行注释调即可(在行首加//)

Go to top.

12.安装clamav 0.87
# wget http://optusnet.dl.sourceforge.net/sourcef...mav-0.87.tar.gz
# tar zxvf clamav-0.87.tar.gz
# cd clamav-0.87
# groupadd clamav
# useradd -g clamav -s/sbin/nologin -d/dev/null clamav
# ./configure --prefix=/usr/local/clamav --with-dbdir=/usr/local/share/clamav --disable-zlib-vcheck
# make
# make check
# make install

编辑/usr/local/clamav/etc/clamd.conf
# vi /usr/local/clamav/etc/clamd.conf
#Verbose logging with syslog
LogSyslog
LogVerbose
LogFacility LOG_MAIL
LogFile /var/log/clamav/clamd.log
#Change pid file location
PidFile /var/run/clamav/clamd.pid
DatabaseDirectory /usr/local/share/clamav
#Set the clamav socket
LocalSocket /var/run/clamav/clamd
#Close the connection when this limit is exceeded
StreamMaxLength 10M
#Don't run clamd as root
User amavis
#Newer versions require you to uncomment this
ScanMail
ScanArchive

编辑/usr/local/clamav/etc/freshclam.conf
# vi /usr/local/clamav/etc/freshclam.conf
DatabaseDirectory /usr/local/share/clamav
UpdateLogFile /var/log/clamav/freshclam.log
LogSyslog
LogVerbose
DatabaseOwner amavis
#Check for updates every two hours. That is the official recommendation
Checks 12
DatabaseMirror db.CN.clamav.net
DatabaseMirror database.clamav.net
NotifyClamd

注意:一定要注释掉上面两个文件中Example那行

添加amavis用户和组
# groupadd amavis
# useradd -g amavis -s /sbin/nologin -d /dev/null amavis

创建日志文件夹并设置权限
# mkdir /var/log/clamav
# chmod -R 744 /var/log/clamav
# chown -R amavis:amavis /var/log/clamav

# chown -R amavis.amavis /usr/local/share/clamav
# mkdir /var/run/clamav
# chmod 700 /var/run/clamav
# chown amavis.amavis /var/run/clamav

手动更新病毒库
# /usr/local/clamav/bin/freshclam

启动
# /usr/local/clamav/sbin/clamd

Go to top.

13.安装amavisd-new 2.3.3

# wget http://www.ijs.si/software/amavisd/amavisd...ew-2.3.3.tar.gz
# tar zxvf amavisd-new-2.3.3.tar.gz
# cd amavisd-new-2.3.3

# mkdir -p /var/amavis /var/amavis/tmp /var/amavis/var /var/amavis/db
# chown -R amavis:amavis /var/amavis
# chmod -R 750 /var/amavis

# cp amavisd /usr/local/sbin/
# chown root /usr/local/sbin/amavisd
# chmod 755 /usr/local/sbin/amavisd

# cp amavisd.conf /etc/
# chown root /etc/amavisd.conf
# chmod 644 /etc/amavisd.conf

# cp amavisd_init.sh /etc/rc.d/init.d/amavisd
# chmod 744 /etc/rc.d/init.d/amavisd
# chkconfig --add amavisd
# chkconfig amavisd on
# vi /etc/rc.d/init.d/amavisd
prog="/usr/local/sbin/amavisd"

病毒邮件存放目录
# mkdir /var/virusmails
# chown amavis:amavis /var/virusmails
# chmod 750 /var/virusmails

Go to top.

编辑/etc/amavisd.conf,修改下面这几行
# vi /etc/amavisd.conf
$max_servers=8;
$daemon_user = 'amavis';
$daemon_group = 'amavis';
$mydomain = 'test.com';
$db_home = "$MYHOME/db";
$inet_socket_port = 10024;
$sa_tag_level_deflt = -100;
$sa_tag2_level_deflt = 6.3;
$sa_kill_level_deflt = $sa_tag2_level_deflt;
$virus_admin = "virusalert\@$mydomain";
$sa_spam_subject_tag = '***SPAM*** ';
$notify_method = $forward_method;
$forward_method = 'smtp:127.0.0.1:10025';
$final_virus_destiny = D_DISCARD;
$final_banned_destiny = D_DISCARD;
$final_spam_destiny = D_DISCARD;
['ClamAV-clamd',
\&ask_daemon, ["CONTSCAN {}\n", "/var/run/clamav/clamd"],
qr/\bOK$/, qr/\bFOUND$/,
qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],

测试amavis
# /usr/local/sbin/amavisd debug
ERROR: MISSING REQUIRED BASIC MODULES:
Time::HiRes
IO::Wrap
Unix::Syslog
Mail::Field
MIME::Words
Net::Server
BEGIN failed--compilation aborted at /usr/local/sbin/amavisd line 141.
根据出错提示,缺什么装什么,我的LANG变量为en_US.UTF-8
# perl -MCPAN -e shell
cpan> install Time::HiRes
cpan> install IO::Wrap
cpan> install Unix::Syslog
cpan> install Mail::Field
cpan> install Compress::Zlib
cpan> install MIME::Words
cpan> install Net::Server
cpan> install BerkeleyDB
cpan> install Convert::TNEF
cpan> install Convert::UUlib
cpan> install Archive::Tar
cpan> install Archive::Zip
cpan> install HTML::Parser
cpan> install DB_File
cpan> install Net::DNS (提示是否test, 选择no)
cpan> install Digest::SHA1
cpan> install Mail::SpamAssassin (# export LANG=en_US)

期间MIME安装会失败,只好手动安装,跳过测试
# cd /root/.cpan/build/MIME-tools-5.418/
# perl Makefile.PL
# make install

启动
# /usr/local/sbin/amavisd start 或
# service amavisd start

Go to top.

设置postfix
修改/etc/postfix/main.cf
# vi /etc/postfix/main.cf (加入一行)
content_filter = amavis:127.0.0.1:10024
修改/etc/postfix/master.cf
# vi /etc/postfix/master.cf (在最后加上)
# amavisd-new
amavis unix - - n - 2 smtp
-o smtp_data_done_timeout=1200
-o smtp_send_xforward_command=yes
-o disable_dns_lookups=yes

localhost:10025 inet n - n - - smtpd
-o content_filter=
-o local_recipient_maps=
-o relay_recipient_maps=
-o mynetworks=127.0.0.0/8
-o smtpd_helo_restrictions=
-o smtpd_client_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o strict_rfc821_envelopes=yes
-o smtpd_error_sleep_time=0
-o smtpd_soft_error_limit=1001
-o smtpd_hard_error_limit=1000

重新服务
# service postfix restart
# service clamd restart
# service amavisd restart

# netstat -ant | grep LISTEN (应该可以看到这两个端口在监听)
127.0.0.1.10024 *.* 0 0 49152 0 LISTEN
127.0.0.1.10025 *.* 0 0 49152 0 LISTEN

Go to top.

14.安装Spamassassin
前面装amavis的时候已经装好了,如果没装,请按如下方式安装

启动spamd
# /usr/bin/spamd –daemonize –pidfile /var/run/spamd.pid

下载中文垃圾垃圾邮件过滤规则Chinese_rules.cf
# wget -N -P /usr/share/spamassassin www.ccert.edu.cn/spam/sa/Chinese_rules.cf

每次更新Chinese_rules.cf需要重启spamd方法如下
# kill -HUP `cat /var/run/spamd.pid`

自动更新中文垃圾垃圾邮件过滤规则
# vi /etc/crontab (加一行)
0 0 1 * * root wget -N -P /usr/share/spamassassin www.ccert.edu.cn/spam/sa/Chinese_rules.cf;kill -HUP `cat /var/run/spamd.pid`

测试病毒扫描
给该test@test.com用户发送邮件,包含以下内容:
X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*
查看日志,如果出现类似如下提示,则表明成功
Nov 6 22:06:20 localhost postfix/smtp[18276]: 9CEB657E22: to=, relay=127.0.0.1[127.0.0.1], delay=2, status=sent (250 2.7.1 Ok, discarded, id=18262-01 - VIRUS: Eicar-Test-Signature)
邮件病毒扫描日志将被记录在/var/log/clamav/clamav.log中!

测试垃圾邮件扫描
给test@test.com用户发送邮件,包含以下内容:
XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X
查看日志,如果出现类似如下提示,表明成功
Nov 6 22:10:51 localhost amavis[18263]: (18263-01) Blocked SPAM, LOCAL [127.0.0.1] [127.0.0.1] -> , quarantine: spam-JH2LSCT1MLYg.gz, Message-ID: <1451.192.168.1.10.1131286248.squirrel@192.168.1.21>, mail_id: JH2LSCT1MLYg, Hits: 1005.902, 3591 ms

Go to top.

15.启动脚本
postfix的启动脚本:
# cat /etc/rc.d/init.d/postfix
=================================================================
#!/bin/bash
#
# mailsys This shell script takes care of starting and stopping Postfix
# author : xingyu.wang 2004/1/28
#
# chkconfig: 2345 80 30
# description: Postfix is a Mail Transport Agent, which is the program
# that moves mail from one machine to another.
#
# processname: mailsys
# pidfile: /var/run/postfix.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -f /usr/sbin/postfix ] || exit 0
RETVAL=0
prog=”Postfix”

start() {
# Start daemons.
echo -n $”Starting $prog: ”
/usr/sbin/postfix start > /dev/null 2>&1 &

RETVAL=$?

if [ $RETVAL -eq 0 ]; then
touch /var/lock/subsys/postfix
success $”$prog start”
else
failure $”$prog start failure”
fi

echo
return $RETVAL
}

stop() {
# Stop daemons.
echo -n $”Shutting down $prog: ”
/usr/sbin/postfix stop > /dev/null 2>&1 &
RETVAL=$?

if [ $RETVAL -eq 0 ]; then
rm -f /var/lock/subsys/postfix
success $”$prog stop”
else
failure $”$prog stop failure”
fi

echo
return $RETVAL
}

# See how we were called.
case “$1″ in
start)
start
;;
stop)
stop
;;
restart|reload)
stop
start
RETVAL=$?
;;
*)
echo $”Usage: $0 {start|stop|restart}”
exit 1
esac
exit $RETVA

# chmod 755 /etc/rc.d/init.d/postfix
# chkconfig –level 2345 postfix on

clamav的启动脚本
# vi /etc/rc.d/init.d/clamd
=================================================================
#! /bin/bash
#
# crond Start/Stop the clam antivirus daemon.
#
# chkconfig: 2345 90 60
# description: clamdis a standard UNIX program that scans for Viruses.
# processname: clamd
# config: /usr/local/clamav/etc/clamd.conf
# pidfile: /var/run/clamav/clamd.pid

# Source function library.
. /etc/rc.d/init.d/functions

RETVAL=0

# See how we were called.

prog=”clamd”
progdir=”/usr/local/clamav/sbin”

# Source configuration
if [ -f /etc/sysconfig/$prog ] ; then
. /etc/sysconfig/$prog
fi

start() {
echo -n $”Starting $prog: ”
daemon $progdir/$prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch /var/run/clamav/clamd.pid
return $RETVAL
}

stop() {
echo -n $”Stopping $prog: ”
killproc $prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f /var/run/clamav/clamd.pid
return $RETVAL
}

rhstatus() {
status clamd
}

restart() {
stop
start
}

reload() {
echo -n $”Reloading clam daemon configuration: ”
killproc clamd -HUP
retval=$?
echo
return $RETVAL
}

case “$1″ in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
reload)
reload
;;
status)
rhstatus
;;
condrestart)
[ -f /var/lock/subsys/clamd ] && restart || :
;;
*)
echo $”Usage: $0 {start|stop|status|reload|restart|condrestart}”
exit 1
esac

exit 0

# chmod 755 /etc/rc.d/init.d/clamd
# chkconfig –add clamd
# chkconfig clamd on

Go to top.

Popularity: 26% [?]

Tags: , , , , , , , , ,

10 个 unix 好习惯

Posted 11 months, 1 week ago at 11:32 am. 0 comments

这篇 Learn 10 good UNIX usage habits挺有趣,全摘如下:

Adopt 10 good habits

Ten good habits to adopt are:

1. Make directory trees in a single swipe.
2. Change the path; do not move the archive.
3. Combine your commands with control operators.
4. Quote variables with caution.
5. Use escape sequences to manage long input.
6. Group your commands together in a list.
7. Use xargs outside of find.
8. Know when grep should do the counting — and when it should step aside.
9. Match certain fields in output, not just lines.
10. Stop piping cats.

Make directory trees in a single swipe

Listing 1 illustrates one of the most common bad UNIX habits around: defining directory trees one at a time.
Listing 1. Example of bad habit #1: Defining directory trees individually

~ $ mkdir tmp
~ $ cd tmp
~/tmp $ mkdir a
~/tmp $ cd a
~/tmp/a $ mkdir b
~/tmp/a $ cd b
~/tmp/a/b/ $ mkdir c
~/tmp/a/b/ $ cd c
~/tmp/a/b/c $

It is so much quicker to use the -p option to mkdir and make all parent directories along with their children in a single command. But even administrators who know about this option are still caught stepping through the subdirectories as they make them on the command line. It is worth your time to conscientiously pick up the good habit:

Listing 2. Example of good habit #1: Defining directory trees with one command
一次建立目录树

~ $ mkdir -p tmp/a/b/c

You can use this option to make entire complex directory trees, which are great to use inside scripts; not just simple hierarchies. For example:
Listing 3. Another example of good habit #1: Defining complex directory trees with one command

~ $ mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

In the past, the only excuse to define directories individually was that your mkdir implementation did not support this option, but this is no longer true on most systems. IBM, AIX??, mkdir, GNU mkdir, and others that conform to the Single UNIX Specification now have this option.
For the few systems that still lack the capability, use the mkdirhier script (see Resources), which is a wrapper for mkdir that does the same function:

~ $ mkdirhier project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

Change the path; do not move the archive

Another bad usage pattern is moving a .tar archive file to a certain directory because it happens to be the directory you want to extract it in. You never need to do this. You can unpack any .tar archive file into any directory you like — that is what the -C option is for. Use the -C option when unpacking an archive file to specify the directory to unpack it in:
Listing 4. Example of good habit #2: Using option -C to unpack a .tar archive file
使用 -C 参数直接解压文件到需要的目录

~ $ tar xvf -C tmp/a/b/c newarc.tar.gz

Making a habit of using -C is preferable to moving the archive file to where you want to unpack it, changing to that directory, and only then extracting its contents — especially if the archive file belongs somewhere else.

Combine your commands with control operators

You probably already know that in most shells, you can combine commands on a single command line by placing a semicolon (;) between them. The semicolon is a shell control operator, and while it is useful for stringing together multiple discrete commands on a single command line, it does not work for everything. For example, suppose you use a semicolon to combine two commands in which the proper execution of the second command depends entirely upon the successful completion of the first. If the first command does not exit as you expected, the second command still runs — and fails. Instead, use more appropriate control operators (some are described in this article). As long as your shell supports them, they are worth getting into the habit of using them.
Run a command only if another command returns a zero exit status
Use the && control operator to combine two commands so that the second is run only if the first command returns a zero exit status. In other words, if the first command runs successfully, the second command runs. If the first command fails, the second command does not run at all. For example:

Listing 5. Example of good habit #3: Combining commands with control operators
使用 && 控制符控制:第一个命令成功后执行下一个

~ $ cd tmp/a/b/c && tar xvf ~/archive.tar

In this example, the contents of the archive are extracted into the ~/tmp/a/b/c directory unless that directory does not exist. If the directory does not exist, the tar command does not run, so nothing is extracted.
Run a command only if another command returns a non-zero exit status
Similarly, the || control operator separates two commands and runs the second command only if the first command returns a non-zero exit status. In other words, if the first command is successful, the second command does not run. If the first command fails, the second command does run. This operator is often used when testing for whether a given directory exists and, if not, it creates one:

Listing 6. Another example of good habit #3: Combining commands with control operators
使用 || 控制符:第一个失败执行下一个

~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c

You can also combine the control operators described in this section. Each works on the last command run:

Listing 7. A combined example of good habit #3: Combining commands with control operators
也可以组合使用

~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c && tar xvf -C tmp/a/b/c ~/archive.tar

Quote variables with caution

Always be careful with shell expansion and variable names. It is generally a good idea to enclose variable calls in double quotation marks, unless you have a good reason not to. Similarly, if you are directly following a variable name with alphanumeric text, be sure also to enclose the variable name in curly braces ({}) to distinguish it from the surrounding text. Otherwise, the shell interprets the trailing text as part of your variable name — and most likely returns a null value. Listing 8 provides examples of various quotation and non-quotation of variables and their effects.
Listing 8. Example of good habit #4: Quoting (and not quoting) a variable
~ $ ls tmp/
a b
~ $ VAR=”tmp/*”
~ $ echo $VAR
tmp/a tmp/b
~ $ echo “$VAR”
tmp/*
~ $ echo $VARa
~ $ echo “$VARa”
~ $ echo “${VAR}a”
tmp/*a
~ $ echo ${VAR}a
tmp/a
~ $

Use escape sequences to manage long input

You have probably seen code examples in which a backslash (\) continues a long line over to the next line, and you know that most shells treat what you type over successive lines joined by a backslash as one long line. However, you might not take advantage of this function on the command line as often as you can. The backslash is especially handy if your terminal does not handle multi-line wrapping properly or when your command line is smaller than usual (such as when you have a long path on the prompt). The backslash is also useful for making sense of long input lines as you type them, as in the following example:
Listing 9. Example of good habit #5: Using a backslash for long input
用 \ 断行很长的命令行

~ $ cd tmp/a/b/c || \
> mkdir -p tmp/a/b/c && \
> tar xvf -C tmp/a/b/c ~/archive.tar

Alternatively, the following configuration also works:

Listing 10. Alternative example of good habit #5: Using a backslash for long input

~ $ cd tmp/a/b/c \
> || \
> mkdir -p tmp/a/b/c \
> && \
> tar xvf -C tmp/a/b/c ~/archive.tar

However you divide an input line over multiple lines, the shell always treats it as one continuous line, because it always strips out all the backslashes and extra spaces.
Note: In most shells, when you press the up arrow key, the entire multi-line entry is redrawn on a single, long input line.

Group your commands together in a list

Most shells have ways to group a set of commands together in a list so that you can pass their sum-total output down a pipeline or otherwise redirect any or all of its streams to the same place. You can generally do this by running a list of commands in a subshell or by running a list of commands in the current shell.
Run a list of commands in a subshell
Use parentheses to enclose a list of commands in a single group. Doing so runs the commands in a new subshell and allows you to redirect or otherwise collect the output of the whole, as in the following example:

Listing 11. Example of good habit #6: Running a list of commands in a subshell

~ $ ( cd tmp/a/b/c/ || mkdir -p tmp/a/b/c && \
> VAR=$PWD; cd ~; tar xvf -C $VAR archive.tar ) \
> | mailx admin -S “Archive contents”

In this example, the content of the archive is extracted in the tmp/a/b/c/ directory while the output of the grouped commands, including a list of extracted files, is mailed to the admin address.
The use of a subshell is preferable in cases when you are redefining environment variables in your list of commands and you do not want those definitions to apply to your current shell.
Run a list of commands in the current shell
Use curly braces ({}) to enclose a list of commands to run in the current shell. Make sure you include spaces between the braces and the actual commands, or the shell might not interpret the braces correctly. Also, make sure that the final command in your list ends with a semicolon, as in the following example:
Listing 12. Another example of good habit #6: Running a list of commands in the current shell
~ $ { cp ${VAR}a . && chown -R guest.guest a && \
> tar cvf newarchive.tar a; } | mailx admin -S “New archive”

Use xargs outside of find
使用 xargs 而不是 find

Use the xargs tool as a filter for making good use of output culled from the find command. The general precept is that a find run provides a list of files that match some criteria. This list is passed on to xargs, which then runs some other useful command with that list of files as arguments, as in the following example:
Listing 13. Example of the classic use of the xargs tool

~ $ find some-file-criteria some-file-path | \
> xargs some-great-command-that-needs-filename-arguments

However, do not think of xargs as just a helper for find; it is one of those underutilized tools that, when you get into the habit of using it, you want to try on everything, including the following uses.
Passing a space-delimited list
In its simplest invocation, xargs is like a filter that takes as input a list (with each member on a single line). The tool puts those members on a single space-delimited line:

Listing 14. Example of output from the xargs tool

~ $ xargs
a
b
c
Control-D
a b c
~ $

You can send the output of any tool that outputs file names through xargs to get a list of arguments for some other tool that takes file names as an argument, as in the following example:

Listing 15. Example of using of the xargs tool

~/tmp $ ls -1 | xargs
December_Report.pdf README a archive.tar mkdirhier.sh
~/tmp $ ls -1 | xargs file
December_Report.pdf: PDF document, version 1.3
README: ASCII text
a: directory
archive.tar: POSIX tar archive
mkdirhier.sh: Bourne shell script text executable
~/tmp $

The xargs command is useful for more than passing file names. Use it any time you need to filter text into a single line:
Listing 16. Example of good habit #7: Using the xargs tool to filter text into a single line
~/tmp $ ls -l | xargs
-rw-r–r– 7 joe joe 12043 Jan 27 20:36 December_Report.pdf -rw-r–r– 1 \
root root 238 Dec 03 08:19 README drwxr-xr-x 38 joe joe 354082 Nov 02 \
16:07 a -rw-r–r– 3 joe joe 5096 Dec 14 14:26 archive.tar -rwxr-xr-x 1 \
joe joe 3239 Sep 30 12:40 mkdirhier.sh
~/tmp $

Be cautious using xargs
Technically, a rare situation occurs in which you could get into trouble using xargs. By default, the end-of-file string is an underscore (_); if that character is sent as a single input argument, everything after it is ignored. As a precaution against this, use the -e flag, which, without arguments, turns off the end-of-file string completely.

Know when grep should do the counting — and when it should step aside

Avoid piping a grep to wc -l in order to count the number of lines of output. The -c option to grep gives a count of lines that match the specified pattern and is generally faster than a pipe to wc, as in the following example:
Listing 17. Example of good habit #8: Counting lines with and without grep
~ $ time grep and tmp/a/longfile.txt | wc -l
2811
real 0m0.097s
user 0m0.006s
sys 0m0.032s
~ $ time grep -c and tmp/a/longfile.txt
2811
real 0m0.013s
user 0m0.006s
sys 0m0.005s
~ $

An addition to the speed factor, the -c option is also a better way to do the counting. With multiple files, grep with the -c option returns a separate count for each file, one on each line, whereas a pipe to wc gives a total count for all files combined.
However, regardless of speed considerations, this example showcases another common error to avoid. These counting methods only give counts of the number of lines containing matched patterns — and if that is what you are looking for, that is great. But in cases where lines can have multiple instances of a particular pattern, these methods do not give you a true count of the actual number of instances matched. To count the number of instances, use wc to count, after all. First, run a grep command with the -o option, if your version supports it. This option outputs only the matched pattern, one on each line, and not the line itself. But you cannot use it in conjunction with the -c option, so use wc -l to count the lines, as in the following example:
Listing 18. Example of good habit #8: Counting pattern instances with grep
~ $ grep -o and tmp/a/longfile.txt | wc -l
3402
~ $
In this case, a call to wc is slightly faster than a second call to grep with a dummy pattern put in to match and count each line (such as grep -c).

Match certain fields in output, not just lines

A tool like awk is preferable to grep when you want to match the pattern in only a specific field in the lines of output and not just anywhere in the lines.
The following simplified example shows how to list only those files modified in December:
Listing 19. Example of bad habit #9: Using grep to find patterns in specific fields
~/tmp $ ls -l /tmp/a/b/c | grep Dec
-rw-r–r– 7 joe joe 12043 Jan 27 20:36 December_Report.pdf
-rw-r–r– 1 root root 238 Dec 03 08:19 README
-rw-r–r– 3 joe joe 5096 Dec 14 14:26 archive.tar
~/tmp $

In this example, grep filters the lines, outputting all files with Dec in their modification dates as well as in their names. Therefore, a file such as December_Report.pdf is matched, even if it has not been modified since January. This probably is not what you want. To match a pattern in a particular field, it is better to use awk, where a relational operator matches the exact field, as in the following example:
Listing 20. Example of good habit #9: Using awk to find patterns in specific fields
~/tmp $ ls -l | awk ‘$6 == “Dec”‘
-rw-r–r– 3 joe joe 5096 Dec 14 14:26 archive.tar
-rw-r–r– 1 root root 238 Dec 03 08:19 README
~/tmp $

See Resources for more details about how to use awk.

Stop piping cats

A basic-but-common grep usage error involves piping the output of cat to grep to search the contents of a single file. This is absolutely unnecessary and a waste of time, because tools such as grep take file names as arguments. You simply do not need to use cat in this situation at all, as in the following example:
Listing 21. Example of good and bad habit #10: Using grep with and without cat

~ $ time cat tmp/a/longfile.txt | grep and
2811
real 0m0.015s
user 0m0.003s
sys 0m0.013s
~ $ time grep and tmp/a/longfile.txt
2811
real 0m0.010s
user 0m0.006s
sys 0m0.004s
~ $

This mistake applies to many tools. Because most tools take standard input as an argument using a hyphen (-), even the argument for using cat to intersperse multiple files with stdin is often not valid. It is really only necessary to concatenate first before a pipe when you use cat with one of its several filtering options.

Conclusion: Embrace good habits

It is good to examine your command-line habits for any bad usage patterns. Bad habits slow you down and often lead to unexpected errors. This article presents 10 new habits that can help you break away from many of the most common usage errors. Picking up these good habits is a positive step toward sharpening your UNIX command-line skills.

Popularity: 17% [?]

Tags: , , , ,

ad 468x60