关于作者

姓名:

性别:其他

出生日期:--

地区:

联系电话:

QQ:20020287婚否:保密
用户名:clay111
笔名:clay111
地区:
行业:其他

日历  

快速登录

+ 用户名:
+ 密 码:

在线留言



新华联锦园

访问统计:
文章个数:114
评论个数:14
留言条数:8




Powered by BlogDriver 2.1

clay111的备忘文章收集

 

所有文章大部分从网络上面收集,少部分为原创文章。收集的文章都是一些在工作当中对我帮助很大的文章,在这里首先对原创作者表示感谢,由于很多文章不知道具体的作者是谁,所以我一般在题目加上ZT字样,如果你是文章的原创作者,可以和我留言,我把文章的署名改成您自己。

文章

源码升级-(OpenSSL + OpenSSH) ZT

源码升级-(OpenSSL + OpenSSH)

 

升级OpenSSL

  CODE:[Copy to clipboard]  
cd /usr/local/src
wget http://www.openssl.org/source/openssl-0.9.7e.tar.gz
tar xzvf openssl-0.9.7e.tar.gz
cd openssl-0.9.7e
./config --prefix=/usr/local/openssl-0.9.7e
make
make test
make install

升级OpenSSH(依照最新的OpenSSL)

  CODE:[Copy to clipboard]  
cd /usr/local/src
wget http://gulus.usherbrooke.ca/pub/appl/ssh/OpenSSH/portable/openssh-3.9p1.tar.gz
tar xzvf openssh-3.9p1.tar.gz
cd openssh-3.9p1
./configure --prefix=/usr --with-pam --with-zlib=/usr/local/zlib --with-ssl-dir=/usr/local/openssl-0.9.7e --with-md5-passwords --mandir=/usr/share/man
(如果你自己编译安装了zlib,就加--with-zlib=DIR这个参数,如果默认安装,就换成--with-zlib)

make
make install

OK,现在ssh -V看一下版本吧

- 作者: clay111 2008年03月25日, 星期二 18:59  回复(0) |  引用(0) 加入博采

apache配置虚拟机

(总是忘,记下来)

 NameVirtualHost *:80
 <VirtualHost *:80>
    ServerAdmin webmaster@5zuiai.com
    DocumentRoot /usr/local/apache2/htdocs/lhjweb
    ServerName www.5zuiai.com
    <Directory "/usr/local/apache2/htdocs/lhjweb">
       Options -Indexes FollowSymLinks
       AllowOverride None
       Order allow,deny
       Allow from all
    </Directory>
 
    ErrorLog logs/5zuiai-error_log
    TransferLog logs/5zuiai-access_log
 </VirtualHost>

- 作者: clay111 2007年12月22日, 星期六 05:03  回复(0) |  引用(1) 加入博采

DL360服务器的SCSI安装gentoo(Z)

本文转自:http://blog.tom.com/blog/read.php?bloggerid=240728&blogid=59519

难点:DL360服务器的SCSI不是常见的adapter类型,所以设备里面没有sda这样的设备,貌似需要 modprobe cciss加载一下,加载以后,设备的名字也不是sda而是 /dev/cciss/c0d0

(以上未经验证,感谢瞿峰提供如此重要的线索)

转自http://yayami.spaces.live.com/blog/cns!AD65E5A17F330895!148.entry

dl360 gentoo 安装笔记

fdisk /dev/cciss/c0d0
tar xvjpf stage3-*.tar.bz2
tar xvjf /mnt/gentoo/portage-latest.tar.bz2 -C /mnt/gentoo/usr
nano -w /mnt/gentoo/etc/make.conf
CFLAGS="-march=nocona -O2 -pipe -fomit-frame-pointer"
CXXFLAGS="${CFLAGS}"
MAKEOPTS="-j2"
mirrorselect -i -o >> /mnt/gentoo/etc/make.conf
mirrorselect -i -r -o >> /mnt/gentoo/etc/make.conf
GENTOO_MIRRORS="http://linux.ntcu.net/ftp/dists/gentoo"
SYNC="rsync://linux.ntcu.net/gentoo-portage"

cp -L /etc/resolv.conf /mnt/gentoo/etc/resolv.conf
mount -t proc none /mnt/gentoo/proc
mount -o bind /dev /mnt/gentoo/dev
chroot
# chroot /mnt/gentoo /bin/bash
# env-update
>> Regenerating /etc/ld.so.cache...
# source /etc/profile
# export PS1="(chroot) $PS1"
emerge --sync
emerge portage
ls -FGg /etc/make.profile
emerge gentoo-sources
emerge genkernel

/dev/cciss/c0d0p1  /boot        ext2      defaults,noatime     1 2
/dev/cciss/c0d0p4   none         swap     sw                   0 0
/dev/cciss/c0d0p2  /             xfs       noatime              0 1
/dev/cciss/c0d0p3  /var/websquid/cache          reiserfs   noatime              0 0
proc        /proc        proc    nodev,nosuid,noexec  0 0
shm         /dev/shm     tmpfs   nodev,nosuid,noexec  0 0
/dev/cdrom  /mnt/cdrom   auto    noauto,user          0 0
cciss grub 安装
echo '(hd0)     /dev/cciss/c0d0' /boot/grub/device.map
grub --batch --device-map=/boot/grub/device.map --config-file=/boot/grub/grub.conf --no-floppy
grub >root (hd0,0)
grub >setup (hd0)
grub >quit
 
default 0
timeout 30
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
boot=/dev/cciss/c0d0
title=Gentoo Linux 2.6.20-r8
root (hd0,0)
kernel /boot/kernel-genkernel-x86-2.6.20-gentoo-r8 root=/dev/cciss/c0d0p2 vga=791
initrd /boot/initramfs-genkernel-x86-2.6.20-gentoo-r8
内核编译加入
device drivers->block derives->
compaq smart2 support(如果你使用HP smart2阵列卡)
compaq smart array 5XXX support (HP smart array系列阵列卡的支持)

- 作者: clay111 2007年11月1日, 星期四 12:22  回复(0) |  引用(1) 加入博采

让卡巴挂掉的代码
ping -n 45 localhost > nul是什么意思,回答“应该什么也没有吧”。确实,这个命令运行后就是什么显示也没有,除了能浪费时间。。。。
随后他给我看了如下的代码:

以下内容为程序代码:

@echo off
set date=%date%
date 1987-10-18
ping -n 45 localhost > nul
date %date%




很明显这个批处理是为了让卡巴斯基挂掉,先把当前的系统日期保存,然后将当前系统日期改为1987年10月18日(病毒作者的生日?或者是他GF的生日?呵呵),随后ping本机45次,并且将显示结果传到nul设备上,就是在屏幕上什么也不显示。这一句其实是起到延时的作用,目的是等卡巴挂掉。然后再恢复回系统时间。

由于卡巴斯基会实时检测系统日期,以判断软件是否已经超过授权的使用期限。当发现软件许可过期时会立即(这个过程需要几秒到几十秒,前面的那个ping就是为了等待这个)关闭所有的监控,同时主程序也无法扫描病毒,并且需要用户输入新的序列号。

目前,很多的病毒都会先运行一个批处理程序,先让卡巴关掉,然后再大摇大摆地入侵用户的计算机。由于这个批处理只是修改了系统日期,卡巴斯基几乎不太可能将这个批处理作为病毒进行处理。目前,越来越多的病毒通过修改系统时间来对卡巴斯基进行攻击,可以说这是它的一个比较严重的漏洞,目前最新卡巴斯基仍然存在这个问题。  

- 作者: clay111 2007年10月8日, 星期一 11:22  回复(0) |  引用(1) 加入博采

gentoo 安装NTPf服务
1、安装软件
emerge ntp
2、修改配置文件
vi /etc/ntp.conf
restrict default ignore
#restrict default nomodify notrap noquery

restrict 0.asia.pool.ntp.org
restrict 1.asia.pool.ntp.org
restrict 2.asia.pool.ntp.org
restrict 3.asia.pool.ntp.org

restrict 127.0.0.1 mask 255.0.0.0
restrict 192.168.1.0 mask 255.255.255.0 nomodify

server 0.asia.pool.ntp.org
server 1.asia.pool.ntp.org
server 2.asia.pool.ntp.org
server 3.asia.pool.ntp.org
broadcastdelay 0.008
logfile /var/log/ntp.log

3、查看ntp有没有工作

ntpq -p
remote refid st t when poll reach delay offset jitter
==============================================================================
+arteq.com.tw 220.130.158.51 3 u 29 64 377 93.116 38.782 7.695
211.22.55.116 .INIT. 16 u - 64 0 0.000 0.000 0.000
*203.116.5.254 130.207.244.240 2 u 33 64 377 82.320 31.845 11.375
+q037240.ppp.asa 200.23.51.205 2 u 221 64 150 405.989 -117.80 40.170

ntptrace xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx: stratum 3, offset -0.029005, synch distance 0.365843
203.116.5.254: timed out, nothing received
***Request timed out

4、查看log文件

tail -f /var/log/ntp.log

12 Jul 15:35:35 ntpd[2089]: synchronized to 59.124.71.8, stratum 3
12 Jul 15:35:35 ntpd[2089]: kernel time sync status change 0001

5、启动服务

/etc/init.d/ntpd start|stop|restart

6、注意事项

服务启动之后,大约5分钟左右才能进行时间服务。看到日志文件出现同步信息,基本服务就好了, 如果过了很长时间没有同步信息或者不能提供时间服务,请检查配置文件。

参考文档:

http://linux.vbird.org/linux_server/0440ntp.php#server_ntp.conf

- 作者: clay111 2007年07月12日, 星期四 16:01  回复(0) |  引用(1) 加入博采

Local time zone must be set--see zic

cp /usr/share/zoneinfo/Europe/Chongqing /etc/localtime

是因为没有设置localtime,也就是没有自己的时区,拷贝一个就好了。

- 作者: clay111 2007年07月11日, 星期三 16:23  回复(0) |  引用(1) 加入博采

shell date日期应用(ZT)
neo:
如果是linux上的date,直接用
date -d yesterday
date -d yesterday +%Y%m%d
另外如
date -d '3 days ago'
date -d tomorrow
date -d '3 days'
如果不是gnu/linux上的date命令,请往下看
----------------------------------------------------------------

好象有date 有-24 有+%y%m%d等,谢了。
还有有办法获得3天前的日期吗?

唉,在b shell没有这个用法了,要想用纯shell做几天前后的运算,只有自己想办法了,+%y%m%d用于控制输出格式,作用有限,要想做的话,参见这个帖子大家的发言:

我的确在哪儿看到用一条命令就可以取昨天或明天的日期,
参数中有-24或+24。没那么复杂

好象用到了参数TZ=-24;export TZ什么的

改变时区,应该可以实现,确实是个好方法。

不会吧,你说的俺都明白了,你自己还不懂?

date命令的显示是与环境变量TZ有关的
看以下的命令操作,你应该便明白了,

$#看当前时区
$echo $TZ
CST-8
$#显示当前时间
$date
Mon Apr 2 15:48:36 CST 2002
$#改变当前时区,
TZ=CST+16;export TZ
$#显示当前时间(中间未改变系统时间,但date命令的显示已为昨天)
Mon Apr 1 15:48:33 CST 2002



#!/bin/sh

# ydate: A Bourne shell script that
# prints yestarday's date
# Output form: Month Day Year
# From Focus on Unix: http://unix.about.com

# Set the current month day and year.
month=`date +%m`
day=`date +%d`
year=`date +%Y`

# Add 0 to month. This is a
# trick to make month an unpadded integer.
month=`expr $month + 0`

# Subtract one from the current day.
day=`expr $day - 1`

# If the day is 0 then determine the last
# day of the previous month.
if [ $day -eq 0 ]; then

# Find the preivous month.
month=`expr $month - 1`

# If the month is 0 then it is Dec 31 of
# the previous year.
if [ $month -eq 0 ]; then
month=12
day=31
year=`expr $year - 1`

# If the month is not zero we need to find
# the last day of the month.
else
case $month in
1|3|5|7|8|10|12) day=31;;
4|6|9|11) day=30;;
2)
if [ `expr $year % 4` -eq 0 ]; then
if [ `expr $year % 400` -eq 0 ]; then
day=29
elif [ `expr $year % 100` -eq 0 ]; then
day=28
else
day=29
fi
else
day=28
fi
;;
esac
fi
fi

# Print the month day and year.
echo $month $day $year
exit 0


时区转换实在是太精妙了!:-)

如果在shell中改了时区,执行完后,系统真正的时区还是正确的吗?

回楼上:最好你要把TZ的设置该回去了。
不过我在实践中用的方法是:
如果你的主机能够连接到数据库的话,比如可以连接到SYBASE数据库,那就可以利用数据库里面计算时间的丰富的函数了,比如
dateadd(day,getdate(),-1)
就能得到最天的日期了

因为这个贴子被版主盖过章,所以在此跟一下。
最近经常看到有网友关于相对日期问题的贴子,这在shell下进行解决时比较头疼。现将我作的几个程序贴出来与大家分享。虽然是用c写的,把它们贴在这里,我想大家也不会太反对的。其中一个程序以前发表在sco版下,现在早已淹没在汪洋大海中了,无从查找。
因为是早先刚学c时的作品,且英文又不行,故写出的程序比较难看,请大家别见笑。
相关链接:



date=`expr `date +%m%d` - 1`

这儿有一个我写的计算昨天的函数,可能是纯shell中唯一的简单解决方案吧,要想将其应用在计算任意天前后,恐怕还是不太方便的,看看,能否满足?
yesterday ()
{
_year=$1;_month=$2;_day=$3
if [ $_day -eq 1 ];then
if [ $_month -eq 1 ];then
_year=`expr $_year - 1`
_month=12
else
_month=`expr $_month - 1`
fi
_day=`echo `cal $_month $_year`|awk '{print $NF}'`
else
_day=`expr $_day - 1`
fi
echo "$_year $_month $_day"|awk '{if (length($2)==1) $2=0$2;if (length($3)==1) $3=0$3;print $1,$2,$3}'
}



unix 我没有试过,linux上可以用
date --date "1 days ago"


yy=`date +%Y` #Year yyyy
mm=`date +%m` #Month mm
dd=`date +%d` #Day dd

if [ $dd = "01" ] #如果为月初则计算上月末的日期
then
lm=`expr $mm - 1 ` #lm 上月
if [ $lm -eq 0 ]
then lm=12
fi
case $Fm in
1|3|5|7|8|10|12) Yesterday=31 ;;
4|6|9|11) Yesterday=30 ;;
2) #计算闰月
if [ ` expr $yy % 4 ` -eq 0 -a `expr $yy % 100 ` -ne 0 -o ` expr $yy % 400 ` -eq 0 ]
then Yesterday=29
else Yesterday=28
fi ;;
esac

else #如果不是月初的处理
Yesterday=`expr $dd - 1 `
if [ $Yesterday -lt 10 ] ###上旬日期处理
then Yesterday=0$Yesterday
fi
fi

结果: today=20020301 yesterday=28

- 作者: clay111 2007年07月11日, 星期三 11:23  回复(0) |  引用(1) 加入博采

无光驱安装gentoo

                                   无光驱安装gentoo
原理:服务器启动,通过网络从DHCP服务器获取TFTP服务器地址,服务器从TFTP服务器下载pxelinux并且执行,pxelinux读取配置文件,从网络下载gentoo内核和引导文件,从而引导gentoo系统,系统引导成功以后,可以正常安装gentoo。
1、环境介绍
   一台gentoo服务器(IP:192.168.1.251),一个交换机,一个需要安装系统的无光驱服务器
2、安装DHCP服务器
   首先配置gentoo服务器,gentoo服务器需要安装配置DHCP、TFTP服务。
   Emerge dhcp
   安装完成之后,修改DHCP配置文件
 
   Nano –w /etc/dhcp/dhcpd.conf
   文件内容如下所示:
    ddns-update-style interim;
ignore client-updates;
option space PXE;
option PXE.mtftp-ip code 1 = ip-address;
option PXE.mtftp-cport code 2 = unsigned integer 16;
option PXE.mtftp-sport code 3 = unsigned integer 16;
option PXE.mtftp-tmout code 4 = unsigned integer 8;
option PXE.mtftp-delay code 5 = unsigned integer 8;
option PXE.discovery-control code 6 = unsigned integer 8;
option PXE.discovery-mcast-addr code 7 = ip-address;
class "pxeclients" {
match if substring (option vendor-class-identifier, 0, 9) = "PXEClient";
option vendor-class-identifier "PXEClient";
vendor-option-space PXE;
option PXE.mtftp-ip 0.0.0.0;
filename "pxelinux.0";
next-server 192.168.1.251;
}
subnet 192.168.1.0 netmask 255.255.255.0 {
option routers 192.168.1.1;
option subnet-mask 255.255.255.0;
range  192.168.1.80 192.168.1.100;
}
启动DHCP服务
/etc/init.d/dhcpd start
3、配置TFTP服务器
   首先建立TFTP工作目录
   Mkdir  /diskless
   安装TFTP软件
   Emerge  tftp-hpa
   配置TFTP
   Nano –w /etc/conf.d/in.tftpd
   配置文件内容如下所示:
# /etc/init.d/in.tftpd
INTFTPD_PATH="/diskless"
INTFTPD_USER="nobody"
#INTFTPD_OPTS="-u ${INTFTPD_USER} -l -vvvvvv -p -c -s ${INTFTPD_PATH}"
INTFTPD_OPTS="-l -v -s ${INTFTPD_PATH}"

  启动TFTP
/etc/init.d/in.tftpd start

 
4、制作gentoo网络启动文件(关键步骤)
   首先下载
   LiveCD+PXE-0.0.1.tar.bz2 和 install-x86-universal-2004.2.iso
   Cp install-x86-universal-2004.2.iso /tmp

   解压文件 LiveCD+PXE
   Tar zxjpf LiveCD+PXE-0.0.1.tar.bz2
   Cd LiveCD+PXE-0.0.1

   修改LiveCD+PXE.sh
   Vi LiveCD+PXE.sh

   查找PXE_HOST和PXE_DIR 修改成自己的服务器地址
    PXE_HOST="192.168.1.251"
PXE_DIR="/diskless"

   . /LiveCD+PXE.sh smp init 
   ./ LiveCD+PXE.sh smp finish
  
   此步骤为制作gentoo网络启动文件的关键步骤(生成:smp和smp.igz文件),如果制作不成功,则无法通过网络启动gentoo
5、安装pxelinux
   Emerge syslinux
   cp /usr/lib/syslinux/pxelinux.0 /diskless
mkdir /diskless/pxelinux.cfg
   touch /diskless/pxelinux.cfg/default
  
   vi /diskless/pxelinux.cfg/default
  内容如下:
  prompt 1
timeout 10
default livecd

label livecd
        kernel smp
        append init=/linuxrc initrd=smp.igz ramdisk_size=80000 ip=dhcp root=/dev/ram0 looptype=squashfs loop=/livecd.squashfs cdroot PXE keymap=us

6、启动需要安装系统的服务器

启动服务器,选择通过PXE启动,尽情享受gentoo网络启动带来的乐趣吧。


注意事项:
1、启动文件为gentoo 2004版 ,linux内核是2.4,如果安装gentoo 2007 LiveCD,安装时会提示linux 内核版本太低,不能安装。只能用install-x86-universal-2004.2.iso进行安装,然后升级系统软件。
2、LiveCD+PXE-0.0.1.tar.bz2 和 install-x86-universal-2004.2.iso 安装包在192.168.1.251上面都有,有需要安装测试的可以从这上面拷贝安装。

另类安装gentoo

通过正常步骤安装gentoo
此处省略2000字安装步骤。注意事项:一定要用genkernel -all来生成系统内核,因为genkernel 生成的内核和liveCD比较类似,系统兼容性比较好。如果不用genkernel生成内核,

挂上需要安装系统的硬盘,用LiveCD启动系统
Fdisk /dev/hda
系统分区
livecd ~ # fdisk -l /dev/hda

Disk /dev/hda: 78 GB,
255 heads, 63 sectors/track, 72943 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hda1               1          12       96358+  83  Linux
/dev/hda2              13         110      787185   82  Linux swap / Solaris
/dev/hda3             111       72943   585031072+  83  Linux
   
/hda1目录为grub 和系统启动文件
/hda3为linux系统文件
我们知道linux一切都是文件,所以我们只要把所有的文件都拷贝过来就好了。
   
Fdisk –l /dev/hdb       (这个是需要安装系统的硬盘)
/dev/hdb1               1          12       96358+  83  Linux
/dev/hdb2              13         110      787185   82  Linux swap / Solaris
/dev/hdb3             111       72943   585031072+  83  Linux

Mkdir   /mnt/sroot     linux系统文件目录
Mkidr   /mnt/sboot     启动文件目录

Mkdir  /mnt/groot
Mkidr  /mnt/gboot

Mount /dev/hda3 /mnt/sroot     mount 原目录
Mount /dev/hda1 /mnt/sboot     mount 原目录

Mount /dev/hdb3 /mnt/groot     mount 目标目录
Mount /dev/hdb1 /mnt/gboot     mount 目标目录

Cp –a /mnt/sroot /mnt/groot   拷贝需要安装的文件到目标目录
Cp –a /mnt/sboot /mnt/gboot   拷贝系统启动文件到目标目录

拷贝完成以后,linux系统基本安装完成。只要在目标盘重新安装grub启动就好了。

3、摘下原盘,用liveCD启动。

重新安装grub就好了。

此方法与克隆安装互有优缺点:
克隆安装,只能在两个同等大小的硬盘之间克隆,如果原盘比目标盘大,则不能用克隆方法。
克隆安装比较方便,克隆完成之后,克隆盘可直接启动。
硬盘对拷方法适用于硬盘大小不统一之间的安装linux。


- 作者: clay111 2007年07月10日, 星期二 14:40  回复(0) |  引用(1) 加入博采

vmstat 说明(ZT )
实时查看内存使用情况

vmstat 2(秒数)
vmstat 5 40

vmstat 可用來紀錄 processes, memory, paging, block IO, traps, 與 cpu activity。

例如

$ vmstat 1 # 1 是更新速度,單位為秒
procs -----------memory---------- ---swap-- -----io---- --system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
1 0 549368 13316 102388 91992 12 6 9 8 2 12 72 3 25 0
2 0 549368 13316 102388 91992 0 0 0 0 156 1516 98 2 0 0
2 0 549368 13312 102388 91992 0 0 0 0 125 534 99 1 0 0

....

第一列與第二列所代表是執行程式的資訊,接下來的是記憶體、swap、io、systm 與 cpu。

Procs
r: The number of processes waiting for run time.
b: The number of processes in uninterruptible sleep.

Memory
swpd: the amount of virtual memory used.
free: the amount of idle memory.
buff: the amount of memory used as buffers.
cache: the amount of memory used as cache.
inact: the amount of inactive memory. (-a option)
active: the amount of active memory. (-a option)

Swap
si: Amount of memory swapped in from disk (/s).
so: Amount of memory swapped to disk (/s).

IO
bi: Blocks received from a block device (blocks/s).
bo: Blocks sent to a block device (blocks/s).
System
in: The number of interrupts per second, including the clock.
cs: The number of context switches per second.

CPU
These are percentages of total CPU time.
us: Time spent running non-kernel code. (user time, including nice time)
sy: Time spent running kernel code. (system time)
id: Time spent idle. Prior to Linux 2.5.41, this includes IO-wait time.
wa: Time spent waiting for IO. Prior to Linux 2.5.41, shown as zero.

- 作者: clay111 2007年07月6日, 星期五 11:09  回复(0) |  引用(1) 加入博采

gentoo 没有加载网卡怎么办?

错误提示:

ERROR: problem starting needed services 

“netmount” was not started

查看网卡型号:

lspci   

察看编译了哪些模块:

ls /lib/modules/`uname -r`/kernel/drivers/net

动态加载模块:

modprobe e100

加入自动加载模块组:

nano -w /etc/modules.autoload.d/kernel-2.4

在文件里面直接写模块名字,例如:

e100  #(我这里是网卡的型号)

修改/etc/conf.modeles,没有效果。开始在google乱搜,最后仔细阅读gentoo文档,发现:
原始碼 10: 搜尋提供的模組

# ls /lib/modules/`uname -r`/kernel/drivers/net


如果您找到您的網路卡所用的驅動程式,使用 modprobe 載入這個核心模組:

原始碼 11: 使用 modprobe 載入核心模組

(舉例來說,我們將載入 pcnet32 模組)
# modprobe pcnet32


尝试modprobe不同文件,包括ne2k,8139cp。最后modprobe 8139too。安装成功!
但现在还是无法使用文档中说的net-setup,难道是目录不对,我find / 没有发现net-setup的文件名。

注册7年,首次发现一点和别人遇到的情况不同的,首次发帖。但最后解决方法还是在手册中,呵呵!还是那个道理多看手册,问题几乎都能解决。(不知道发在安装版还是gentoo,由斑竹定夺吧!)

- 作者: clay111 2007年06月25日, 星期一 01:51  回复(1) |  引用(1) 加入博采

gentoo syslog-ng的设置(ZT)

原文摘自:http://blog.sina.com.cn/u/4707c9270100075v

log对于一个系统的重要性是显而易见的,然而不幸的是我发现我的系统并没有很好地记录应该记录的东西,至少昨天半夜它自动重启了,我却找不到为什么。

安装的时候安装的syslog-ng,查了一下它的配置文件,似乎记录的东西很少,对于系统安全来说是很不够的,于是自己man了很多东西,修改了一下设置,过程如下:

1
man其实没什么用,大概我基础不好,里面说的东西我看不懂。

2
syslog-ng的配置文件在/etc/syslog-ng/syslog-ng.conf,里面似乎只记录了messeges,没有其他东西,不确信的话可以自己打开看看。

3
、安全起见,先将文件备份。

4
、查看syslog-ng的配置说明,参考这个例子:/usr/share/doc/syslog-ng-1.6.9/syslog-ng.conf.sample.gz,然后修改/etc/syslog-ng/syslog-ng.conf,按格式按自己的需要修改。我的修改后的文件如下:

# $Header: /var/cvsroot/gentoo-x86/app-admin/syslog-ng/files/syslog-ng.conf.gentoo,v 1.5 2005/05/12 05:46:10 mr_bones_ Exp $#
# Syslog-ng default configuration file for Gentoo Linux
# contributed by Michael Sterrett

options {
chain_hostnames(off);
sync(0);

# The default action of syslog-ng 1.6.0 is to log a STATS line
# to the file every 10 minutes. That's pretty ugly after a while.
# Change it to every 12 hours so you get a nice daily update of
# how many messages syslog-ng missed (0).
stats(43200);
};

source src { unix-stream("/dev/log"); internal(); pipe("/proc/kmsg"); };

destination authlog { file("/var/log/auth.log"); };
destination syslog { file("/var/log/syslog"); };
destination user { file("/var/log/user.log"); };
destination messages { file("/var/log/messages"); };

# By default messages are logged to tty12...
destination console_all { file("/dev/tty12"); };
# ...if you intend to use /dev/console for programs like xconsole
# you can comment out the destination line above that references /dev/tty12
# and uncomment the line below.
#destination console_all { file("/dev/console"); };


log { source(src); destination(authlog); };
log { source(src); destination(syslog); };
log { source(src); destination(user); };
log { source(src); destination(messages); };
log { source(src); destination(console_all); };

要注意的是sample文件里面有filter的内容,如果你不知道这个是干什么的,man一下syslog-ng。需要的话照sample里面的样子,先添加filter段,再在log段里面添加相应内容。如果你不需要,就象我这样,把需要log的内容直接cp进来,把filter段去掉。

修改:今天查了一下,似乎有几个log里面的内容是差不多的,syslogauth记录了重复的东西,想必是filter没定义的缘故,于是修改如下(增加了filter段):

# $Header: /var/cvsroot/gentoo-x86/app-admin/syslog-ng/files/syslog-ng.conf.gentoo,v 1.5 2005/05/12 05:46:10 mr_bones_ Exp $#
# Syslog-ng default configuration file for Gentoo Linux
# contributed by Michael Sterrett

options {
chain_hostnames(off);
sync(0);

# The default action of syslog-ng 1.6.0 is to log a STATS line
# to the file every 10 minutes. That's pretty ugly after a while.
# Change it to every 12 hours so you get a nice daily update of
# how many messages syslog-ng missed (0).
stats(43200);
};

source src { unix-stream("/dev/log"); internal(); pipe("/proc/kmsg"); };

destination authlog { file("/var/log/auth.log"); };
destination syslog { file("/var/log/syslog"); };
destination user { file("/var/log/user.log"); };
destination messages { file("/var/log/messages"); };

# By default messages are logged to tty12...
destination console_all { file("/dev/tty12"); };
# ...if you intend to use /dev/console for programs like xconsole
# you can comment out the destination line above that references /dev/tty12
# and uncomment the line below.
#destination console_all { file("/dev/console"); };
filter f_auth { facility(auth); };
filter f_authpriv { facility(auth, authpriv); };
filter f_syslog { not facility(authpriv, mail); };
filter f_user { facility(user); };

log { source(src); filter(f_authpriv); destination(authlog); };
log { source(src); filter(f_syslog); destination(syslog); };
log { source(src); filter(f_user); destination(user); };
log { source(src); destination(messages); };
log { source(src); destination(console_all); };

设置iptables log 如下所示:

vi  /etc/syslog-ng/syslog-ng.conf

destination kern { file("/var/log/iptables.log"); };

filter f_kern { facility(kern); };

log { source(src); filter(f_kern); destination(kern); };

保存退出

shell下面运行:

/etc/init.d/syslog-ng reload

iptables -A INPUT  -p icmp -j LOG  --log-level debug --log-prefix "This is a test!"

查看:

tail -f /var/log/iptables.log

输出类似如下:

Jun  8 19:42:02 localhost szkingrose test---------IN=eth0 OUT= MAC=00:15:58:10:6f:70:00:18:39:84:7a:bc:08:00 SRC=59.151.18.182 DST=192.168.1.251 LEN=84 TOS=0x00 PREC=0x00 TTL=51 ID=20409 PROTO=ICMP TYPE=0 CODE=0 ID=2371 SEQ=5
Jun  8 19:42:02 localhost szkingrose test---------IN=eth0 OUT= MAC=00:15:58:10:6f:70:00:1b:fc:1a:09:c7:08:00 SRC=192.168.1.122 DST=192.168.1.251 LEN=60 TOS=0x00 PREC=0x00 TTL=128 ID=59970 PROTO=ICMP TYPE=8 CODE=0 ID=512 SEQ=19727
Jun  8 19:42:03 localhost szkingrose test---------IN=eth0 OUT= MAC=00:15:58:10:6f:70:00:1b:fc:1a:09:c7:08:00 SRC=192.168.1.122 DST=192.168.1.251 LEN=60 TOS=0x00 PREC=0x00 TTL=128 ID=59973 PROTO=ICMP TYPE=8 CODE=0 ID=512 SEQ=19983
Jun  8 19:42:04 localhost szkingrose test---------IN=eth0 OUT= MAC=00:15:58:10:6f:70:00:1b:fc:1a:09:c7:08:00 SRC=192.168.1.122 DST=192.168.1.251 LEN=60 TOS=0x00 PREC=0x00 TTL=128 ID=59976 PROTO=ICMP TYPE=8 CODE=0 ID=512 SEQ=20239

 

- 作者: clay111 2007年06月8日, 星期五 19:46  回复(0) |  引用(1) 加入博采

博客中国实在是太滥了

用了这么长时间,也懒得搬家了,但是实在是不爽,我要骂两句。

你们的文章总数准么?  你们的文章年度文件夹文章数对么?

你们怎么测试的产品,就拿着东西出来唬人了?

博客中国实在是太滥了,什么时候新浪推出博客中国的搬家工具,我搬到新浪去。

- 作者: clay111 2007年06月7日, 星期四 19:20  回复(0) |  引用(1) 加入博采

c与mysql连接和一个简单查询的例子(ZT)
(此程序经过编译验证,没有问题,确实可用,如果在你的环境不能工作,也许是你的环境问题)

今天给新来的同事做mysql培训,用到的一个例子:
连接数据库test 用户名root密码abc
在里面有一个username的表,describe username结果如下
mysql> describe username;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(10)     | YES  |     | NULL    |       |
| username | varchar(32) |      | PRI |         |       |
+----------+-------------+------+-----+---------+-------+

mysql> select * from username;
+------+----------+ 
| id   | username |
+------+----------+
|    1 | sfs      |
+------+----------+
1 row in set (0.00 sec)


[b:f09d522785]本文目的查找执行select id from username这个语句并打印结果[/b:f09d522785]
[code:1:f09d522785]
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#include <signal.h>
#include <errno.h>
#include <syslog.h>
MYSQL mysql;
main()
{
char host[32]="localhost";
char user[32]="root";
char passwd[32]="abc";
char dbname[32]="test";

if( mysql_init(&mysql) == NULL )
{
syslog(LOG_USER|LOG_INFO,"inital mysql handle error\n");
return 1;
}
if (mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)
{
syslog(LOG_USER|LOG_INFO, "Failed to connect to database: Error: %s\n",mysql_error(&mysql));
return 1;
}
else syslog(LOG_USER|LOG_INFO, "connect to database: \n");
find_ps();
db_close();
return 0;
}
int db_close()
{
       mysql_close(&mysql);
        return 0;
}


int  find_ps ()
{
MYSQL_ROW m_row;
MYSQL_RES *m_res;
char sql[1024],username[32];
int res=1;
int *id;
sprintf(sql,"select id from username");
if(mysql_query(&mysql,sql) != 0)
{
syslog(LOG_USER|LOG_INFO, "select ps_info Error: %s\n",mysql_error(&mysql));
return res;
}
m_res = mysql_store_result(&mysql);
if(m_res==NULL)
{
syslog(LOG_USER|LOG_INFO, "select username Error: %s\n",mysql_error(&mysql));
res = 3;
return res;
}
if(m_row = mysql_fetch_row(m_res))
{
printf("m_row=%d\n",atoi(m_row[0]));
res = 0;
}
mysql_free_result(m_res);
return res;
}
[/code:1:f09d522785]
编译命令
gcc -g connect_db.c -L/usr/lib/mysql -lmysqlclient -lz
注意:
如果/tmp/ccTGmMS21.o: In function `main':
/tmp/ccTGmMS21.o(.text+0x11): undefined reference to `mysql_init'
那么参数增加-L/usr/lib/mysql -lmysqlclient  
如果
usr/lib/mysql/libmysqlclient.a(my_compress.o): In function `my_uncompress':
my_compress.o(.text+0xaa): undefined reference to `uncompress'
那么增加-lz参数

我自己是这么编译的  呵呵

gcc -o ttmysql ttmysql.c -L /usr/lib/mysql/lib -lmysqlclient -lz

- 作者: clay111 2007年06月7日, 星期四 19:15  回复(0) |  引用(1) 加入博采

C语言中关于时间的函数
本文摘自:

C语言中关于时间的函数

     逍遥天子 发表于 2007-2-27 16:13:00

本文从介绍基础概念入手,探讨了在C/C++中对日期和时间操作所用到的数据结构和函数,并对计时、时间的获取、时间的计算和显示格式等方面进行了阐述。本文还通过大量的实例向你展示了time.h头文件中声明的各种函数和数据结构的详细使用方法。

关键字:UTC(世界标准时间),Calendar Time(日历时间),epoch(时间点),clock tick(时钟计时单元)

1.概念
在C/C++中,对字符串的操作有很多值得注意的问题,同样,C/C++对时间的操作也有许多值得大家注意的地方。最近,在技术群中有很多网友也多次问到过C++语言中对时间的操作、获取和显示等等的问题。下面,在这篇文章中,笔者将主要介绍在C/C++中时间和日期的使用方法.

通过学习许多C/C++库,你可以有很多操作、使用时间的方法。但在这之前你需要了解一些“时间”和“日期”的概念,主要有以下几个:

Coordinated Universal Time(UTC):协调世界时,又称为世界标准时间,也就是大家所熟知的格林威治标准时间(Greenwich Mean Time,GMT)。比如,中国内地的时间与UTC的时差为+8,也就是UTC+8。美国是UTC-5。

Calendar Time:日历时间,是用“从一个标准时间点到此时的时间经过的秒数”来表示的时间。这个标准时间点对不同的编译器来说会有所不同,但对一个编译系统来说,这个标准时间点是不变的,该编译系统中的时间对应的日历时间都通过该标准时间点来衡量,所以可以说日历时间是“相对时间”,但是无论你在哪一个时区,在同一时刻对同一个标准时间点来说,日历时间都是一样的。

epoch:时间点。时间点在标准C/C++中是一个整数,它用此时的时间和标准时间点相差的秒数(即日历时间)来表示。

clock tick:时钟计时单元(而不把它叫做时钟滴答次数),一个时钟计时单元的时间长短是由CPU控制的。一个clock tick不是CPU的一个时钟周期,而是C/C++的一个基本计时单位。

我们可以使用ANSI标准库中的time.h头文件。这个头文件中定义的时间和日期所使用的方法,无论是在结构定义,还是命名,都具有明显的C语言风格。下面,我将说明在C/C++中怎样使用日期的时间功能。

2. 计时

C/C++中的计时函数是clock(),而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下:

clock_t clock( void );

这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。其中clock_t是用来保存时间的数据类型,在time.h文件中,我们可以找到对它的定义:

#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif

很明显,clock_t是一个长整形数。在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,其定义如下:

#define CLOCKS_PER_SEC ((clock_t)1000)

可以看到每过千分之一秒(1毫秒),调用clock()函数返回的值就加1。下面举个例子,你可以使用公式clock()/CLOCKS_PER_SEC来计算一个进程自身的运行时间:

void elapsed_time()
{
printf("Elapsed time:%u secs.\n",clock()/CLOCKS_PER_SEC);
}

当然,你也可以用clock函数来计算你的机器运行一个循环或者处理其它事件到底花了多少时间:

#i nclude “stdio.h”
#i nclude “stdlib.h”
#i nclude “time.h”

int main( void )
{
long i = 10000000L;
clock_t start, finish;
double duration;
/* 测量一个事件持续的时间*/
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- ) ;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%f seconds\n", duration );
system("pause");
}

在笔者的机器上,运行结果如下:

Time to do 10000000 empty loops is 0.03000 seconds

上面我们看到时钟计时单元的长度为1毫秒,那么计时的精度也为1毫秒,那么我们可不可以通过改变CLOCKS_PER_SEC的定义,通过把它定义的大一些,从而使计时精度更高呢?通过尝试,你会发现这样是不行的。在标准C/C++中,最小的计时单位是一毫秒。

3.与日期和时间相关的数据结构

在标准C/C++中,我们可通过tm结构来获得日期和时间,tm结构在time.h中的定义如下:

#ifndef _TM_DEFINED
struct tm {
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值等于实际年份减去1900 */
int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
};
#define _TM_DEFINED
#endif

ANSI C标准称使用tm结构的这种时间表示为分解时间(broken-down time)。

而日历时间(Calendar Time)是通过time_t数据类型来表示的,用time_t表示的时间(日历时间)是从一个时间点(例如:1970年1月1日0时0分0秒)到此时的秒数。在time.h中,我们也可以看到time_t是一个长整型数:

#ifndef _TIME_T_DEFINED
typedef long time_t; /* 时间值 */
#define _TIME_T_DEFINED /* 避免重复定义 time_t */
#endif

大家可能会产生疑问:既然time_t实际上是长整型,到未来的某一天,从一个时间点(一般是1970年1月1日0时0分0秒)到那时的秒数(即日历时间)超出了长整形所能表示的数的范围怎么办?对time_t数据类型的值来说,它所表示的时间不能晚于2038年1月18日19时14分07秒。为了能够表示更久远的时间,一些编译器厂商引入了64位甚至更长的整形数来保存日历时间。比如微软在Visual C++中采用了__time64_t数据类型来保存日历时间,并通过_time64()函数来获得日历时间(而不是通过使用32位字的time()函数),这样就可以通过该数据类型保存3001年1月1日0时0分0秒(不包括该时间点)之前的时间。

在time.h头文件中,我们还可以看到一些函数,它们都是以time_t为参数类型或返回值类型的函数:

double difftime(time_t time1, time_t time0);
time_t mktime(struct tm * timeptr);
time_t time(time_t * timer);
char * asctime(const struct tm * timeptr);
char * ctime(const time_t *timer);

此外,time.h还提供了两种不同的函数将日历时间(一个用time_t表示的整数)转换为我们平时看到的把年月日时分秒分开显示的时间格式tm:

struct tm * gmtime(const time_t *timer);
struct tm * localtime(const time_t * timer);

通过查阅MSDN,我们可以知道Microsoft C/C++ 7.0中时间点的值(time_t对象的值)是从1899年12月31日0时0分0秒到该时间点所经过的秒数,而其它各种版本的Microsoft C/C++和所有不同版本的Visual C++都是计算的从1970年1月1日0时0分0秒到该时间点所经过的秒数。

4.与日期和时间相关的函数及应用
在本节,我将向大家展示怎样利用time.h中声明的函数对时间进行操作。这些操作包括取当前时间、计算时间间隔、以不同的形式显示时间等内容。

4.1 获得日历时间

我们可以通过time()函数来获得日历时间(Calendar Time),其原型为:

time_t time(time_t * timer);

如果你已经声明了参数timer,你可以从参数timer返回现在的日历时间,同时也可以通过返回值返回现在的日历时间,即从一个时间点(例如:1970年1月1日0时0分0秒)到现在此时的秒数。如果参数为空(NUL),函数将只通过返回值返回现在的日历时间,比如下面这个例子用来显示当前的日历时间:

#i nclude "time.h"
#i nclude "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(NUL);
printf("The Calendar Time now is %d\n",lt);
return 0;
}

运行的结果与当时的时间有关,我当时运行的结果是:

The Calendar Time now is 1122707619

其中1122707619就是我运行程序时的日历时间。即从1970年1月1日0时0分0秒到此时的秒数。

4.2 获得日期和时间

这里说的日期和时间就是我们平时所说的年、月、日、时、分、秒等信息。从第2节我们已经知道这些信息都保存在一个名为tm的结构体中,那么如何将一个日历时间保存为一个tm结构的对象呢?

其中可以使用的函数是gmtime()和localtime(),这两个函数的原型为:

struct tm * gmtime(const time_t *timer);
struct tm * localtime(const time_t * timer);

其中gmtime()函数是将日历时间转化为世界标准时间(即格林尼治时间),并返回一个tm结构体来保存这个时间,而localtime()函数是将日历时间转化为本地时间。比如现在用gmtime()函数获得的世界标准时间是2005年7月30日7点18分20秒,那么我用localtime()函数在中国地区获得的本地时间会比世界标准时间晚8个小时,即2005年7月30日15点18分20秒。下面是个例子:

#i nclude "time.h"
#i nclude "stdio.h"
int main(void)
{
struct tm *local;
time_t t;
t=time(NUL);
local=localtime(&t);
printf("Local hour is: %d\n",local->tm_hour);
local=gmtime(&t);
printf("UTC hour is: %d\n",local->tm_hour);
return 0;
}

运行结果是:

Local hour is: 15
UTC hour is: 7

4.3 固定的时间格式

我们可以通过asctime()函数和ctime()函数将时间以固定的格式显示出来,两者的返回值都是char*型的字符串。返回的时间格式为:

星期几 月份 日期 时:分:秒 年\n\0
例如:Wed Jan 02 02:03:55 1980\n\0

其中\n是一个换行符,\0是一个空字符,表示字符串结束。下面是两个函数的原型:

char * asctime(const struct tm * timeptr);
char * ctime(const time_t *timer);

其中asctime()函数是通过tm结构来生成具有固定格式的保存时间信息的字符串,而ctime()是通过日历时间来生成时间字符串。这样的话,asctime()函数只是把tm结构对象中的各个域填到时间字符串的相应位置就行了,而ctime()函数需要先参照本地的时间设置,把日历时间转化为本地时间,然后再生成格式化后的字符串。在下面,如果t是一个非空的time_t变量的话,那么:

printf(ctime(&t));

等价于:

struct tm *ptr;
ptr=localtime(&t);
printf(asctime(ptr));

那么,下面这个程序的两条printf语句输出的结果就是不同的了(除非你将本地时区设为世界标准时间所在的时区):

#i nclude "time.h"
#i nclude "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(NUL);
ptr=gmtime(<);
printf(asctime(ptr));
printf(ctime(<));
return 0;
}

运行结果:

Sat Jul 30 08:43:03 2005
Sat Jul 30 16:43:03 2005

4.4 自定义时间格式

我们可以使用strftime()函数将时间格式化为我们想要的格式。它的原型如下:

size_t strftime(
char *strDest,
size_t maxsize,
const char *format,
const struct tm *timeptr
);

我们可以根据format指向字符串中格式命令把timeptr中保存的时间信息放在strDest指向的字符串中,最多向strDest中存放maxsize个字符。该函数返回向strDest指向的字符串中放置的字符数。

函数strftime()的操作有些类似于sprintf():识别以百分号(%)开始的格式命令集合,格式化输出结果放在一个字符串中。格式化命令说明串strDest中各种日期和时间信息的确切表示方法。格式串中的其他字符原样放进串中。格式命令列在下面,它们是区分大小写的。

%a 星期几的简写
%A 星期几的全称
%b 月分的简写
%B 月份的全称
%c 标准的日期的时间串
%C 年份的后两位数字
%d 十进制表示的每月的第几天
%D 月/天/年
%e 在两字符域中,十进制表示的每月的第几天
%F 年-月-日
%g 年份的后两位数字,使用基于周的年
%G 年分,使用基于周的年
%h 简写的月份名
%H 24小时制的小时
%I 12小时制的小时
%j 十进制表示的每年的第几天
%m 十进制表示的月份
%M 十时制表示的分钟数
%n 新行符
%p 本地的AM或PM的等价显示
%r 12小时的时间
%R 显示小时和分钟:hh:mm
%S 十进制的秒数
%t 水平制表符
%T 显示时分秒:hh:mm:ss
%u 每周的第几天,星期一为第一天 (值从0到6,星期一为0)
%U 第年的第几周,把星期日做为第一天(值从0到53)
%V 每年的第几周,使用基于周的年
%w 十进制表示的星期几(值从0到6,星期天为0)
%W 每年的第几周,把星期一做为第一天(值从0到53)
%x 标准的日期串
%X 标准的时间串
%y 不带世纪的十进制年份(值从0到99)
%Y 带世纪部分的十进制年份
%z,%Z 时区名称,如果不能得到时区名称则返回空字符。
%% 百分号

如果想显示现在是几点了,并以12小时制显示,就象下面这段程序:

#i nclude “time.h”
#i nclude “stdio.h”
int main(void)
{
struct tm *ptr;
time_t lt;
char str[80];
lt=time(NUL);
ptr=localtime(<);
strftime(str,100,"It is now %I %p",ptr);
printf(str);
return 0;
}

其运行结果为:
It is now 4PM

而下面的程序则显示当前的完整日期:

#i nclude <stdio.h>
#i nclude <time.h>

void main( void )
{
struct tm *newtime;
char tmpbuf[128];
time_t lt1;
time( <1 );
newtime=localtime(<1);
strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.\n", newtime);
printf(tmpbuf);
}

运行结果:

Today is Saturday, day 30 of July in the year 2005.

4.5 计算持续时间的长度

有时候在实际应用中要计算一个事件持续的时间长度,比如计算打字速度。在第1节计时部分中,我已经用clock函数举了一个例子。Clock()函数可以精确到毫秒级。同时,我们也可以使用difftime()函数,但它只能精确到秒。该函数的定义如下:

double difftime(time_t time1, time_t time0);

虽然该函数返回的以秒计算的时间间隔是double类型的,但这并不说明该时间具有同double一样的精确度,这是由它的参数觉得的(time_t是以秒为单位计算的)。比如下面一段程序:

#i nclude "time.h"
#i nclude "stdio.h"
#i nclude "stdlib.h"
int main(void)
{
time_t start,end;
start = time(NUL);
system("pause");
end = time(NUL);
printf("The pause used %f seconds.\n",difftime(end,start));//<-
system("pause");
return 0;
}

运行结果为:
请按任意键继续. . .
The pause used 2.000000 seconds.
请按任意键继续. . .

可以想像,暂停的时间并不那么巧是整整2秒钟。其实,你将上面程序的带有“//<-”注释的一行用下面的一行代码替换:

printf("The pause used %f seconds.\n",end-start);

其运行结果是一样的。

4.6 分解时间转化为日历时间

这里说的分解时间就是以年、月、日、时、分、秒等分量保存的时间结构,在C/C++中是tm结构。我们可以使用mktime()函数将用tm结构表示的时间转化为日历时间。其函数原型如下:

time_t mktime(struct tm * timeptr);

其返回值就是转化后的日历时间。这样我们就可以先制定一个分解时间,然后对这个时间进行操作了,下面的例子可以计算出1997年7月1日是星期几:

#i nclude "time.h"
#i nclude "stdio.h"
#i nclude "stdlib.h"
int main(void)
{
struct tm t;
time_t t_of_day;
t.tm_year=1997-1900;
t.tm_mon=6;
t.tm_mday=1;
t.tm_hour=0;
t.tm_min=0;
t.tm_sec=1;
t.tm_isdst=0;
t_of_day=mktime(&t);
printf(ctime(&t_of_day));
return 0;
}
运行结果:
Tue Jul 01 00:00:01 1997
现在注意了,有了mktime()函数,是不是我们可以操作现在之前的任何时间呢?你可以通过这种办法算出1945年8月15号是星期几吗?答案是否定的。因为这个时间在1970年1月1日之前,所以在大多数编译器中,这样的程序虽然可以编译通过,但运行时会异常终止。

- 作者: clay111 2007年05月24日, 星期四 14:53  回复(0) |  引用(1) 加入博采

freebsd安装及安全设置


yeye2005-05-02 12:39
内容简介:本文将详细介绍一个网站服务器的系统安装、针对安全因素的系统调整。该服务器通过Apache+PHP4+MySQL提供动态网站服务,通过自带的FTPD提供网页上传服务,通过自带的OpenSSH提供管理维护服务。本文将不涉及Apache和MySQL的管理。
  一、安装操作系统

  1.选择发行版本

  安装生产服务器,应当尽量选择最新的稳定版本。本文将采用FreeBSD 4.8 RELEASE。

  4.8-RELEASE是成文时候最新的-STABLE版本。5.0-RELEASE和即将推出的5.1-RELEASE都是-CURRENT分支的发行版本,其稳定性和性能可能不如-STABLE,仅适合于开发者和发烧友。对于生产服务器来说,miniinst或disc1就足够了。请下载4.8-RELEASE-i386-mini.iso这个文件,刻录成安装光盘。
本文所叙述操作系统的安装就将采用光盘安装方式。

  2.安装要点

  通过安装向导可以很轻松的完成系统安装,这里不加详细叙述,仅仅指出如下两点:

  (1)硬盘分区的注意事项:

  分区的大小根据应用的实际情况而异,特别指出的是,网站文件、数据库文件、日志文件、临时文件应当单独分区存储,以防止攻击者滥用磁盘空间导致系统崩溃。下面是一块容量为18G SCSI硬盘的分区例子:

分区 大小 备注
/ 128M
SWAP 1008M 至少是内存数量的2倍(本系统采用512M内存)
/tmp 256M
/usr 3G 系统和Apache等应用软件、源码存储于这个分区
/usr/home 7G 网站文件存储于此
/var 3G 数据库将使用这个分区
/var/log 2811M 日志文件单独分区

  (2)选择要安装的文件(distributions):

  只安装必要的基本系统即可,绝对不要安装全部软件。在custom项目中,选取如下安装内容:

  bin,基本的FreeBSD系统文件;
  man,系统帮助文件;
  src—》sys,操作系统核心源码,定制内核时候将使用到。

  接下来,安装程序询问是否安装PORTS,为了方便安装软件,我们选择安装。但在高安全要求的系统上,最好不要使用ports或者packages,尽量自己下载源代码在本地编译,手动安装。

  提示:有时,安全和易用是相互矛盾的。

  然后是拷贝文件,直至安装完毕。

  3.安装后的初步设置

  安装完之后,建议您安装cvsup-without-gui(从bento.freebsd.org可以下在最新版本),并同步代码。对系统进行初步设置:

  增加用户帐号;
  设置网络参数,将主机连接到网络上(全部设置完成后移动到Internet);
  配置网络服务,打开FTP、SSH服务,后续的配置工作都将远程进行。


  二、定制系统内核

  定制系统内核内容:

  支持特定硬件,如SMP、RAID、大容量内存;
  删除多余硬件驱动支持;
  增强系统安全性,增加IP过滤防火墙支持。

  编辑内核设置文件,为增强安全特性,增添或修改如下内容:

  #启用ipfw过滤
  options IPFIREWALL #打开IPFW过滤功能
  options IPFIREWALL_VERBOSE #设置过滤日志记录
  options IPFIREWALL_VERBOSE_LIMIT=100 #设置日志记录限制
  options IPFIREWALL_DEFAULT_TO_ACCEPT #设置缺省行为
  options NOLKM#关闭LKM
  options TCP_DROP_SYNFIN #丢弃SYNFIN包,需要在rc.conf中打开

  #关于虚拟终端
  #取消历史记录,在登出系统后刷新虚拟终端缓冲中的内容
  SC_NO_HISTORY
  #取消debug键
  SC_DISABLE_DDBKEY
  #取消ctl+alt+del键
  SC_DISABLE_REBOOT


  重新编译系统内核并使之生效。

  三、系统配置

  1.修改/etc/inetd.conf文件内容,配置inetd服务

  (1)telnet服务

  我们将使用SSH远程管理这台服务器,因此禁止telnet服务:在行前加"#"标记。

  (2)FTP服务

  使用系统自带的FTP服务,并作如下设置:

  ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l -l -h

  -l 参数,记录每个成功或者失败的FTP登录尝试;
  -l -l 参数,所有的下载、上传、删除更动作和文件名都会被记录下来(设置syslog.conf)
  -h参数,将禁止主机相关信息的输出,例如ftpd版本、主机名等;
  -P参数,指定FTPD进程监听端口号

  FTP服务其他安全方面的设置:

  把网站编辑帐号放到/etc/ftpchroot文件中,把他们限制在自己的HOME目录,防止浏览其他目录。
  编辑/etc/hosts.allow 文件,限制对FTPD的访问。
  可以编辑/etc/ftpwelcome,防止泄露系统信息。

  2.修改/etc/rc.conf文件,配置系统初始参数

  #配置开机器后自动启动或关闭的守护进程
  #可以关闭inetd,使用SSH代替了telnet服务,使用其他的FTP服务程序代替系统的ftpd。
  inetd_enable="NO"

  #如果决定使用inetd则启动inetd的日志选项,并提高一个服务每分钟启动的上限数目(默认是256,建议提高到1024),防止DoS攻击;

  inetd_enable="YES"
  inetd_flags="-l -R 1024"

  #打开SSHD
  sshd_enable="YES"

  #禁止syslogd记录其他主机日志(关闭端口514)
  syslogd_enable="YES"
  syslogd_flags="-s -s"

  #关闭不必要的服务。本服务器没有NFS、NIS登需要,可以关闭portmap (关闭端口111)
  portmap_enable="NO"
  nfs_server_enable="NO"
  nfs_client_enable="NO"

  #使sendmail只监听localhost,允许邮件客户程序发送邮件
  sendmail_enable="NO"
  #设置为"NONE",将彻底关闭25端口

  #设置内核安全级别(Securelevels)
  #内核安全级别从-1到3,-1和0级别是非安全级别。
  #系统在多用户模式下,安全级别只能提升不能降低。
  #Securelevel -1,永久不安全模式
  #Securelevel 0,不安全模式
  #Securelevel 1,安全模式
  #Securelevel 2,高安全模式
  kern_securelevel_enable="YES"
  kern_securelevel="2"

  #计算机启动时候发现文件系统失效,将以-y参数运行fsck

  fsck_y_enable="YES"

  #打开磁盘配额
  enable_quotas="YES"
  check_quotas="YES"

  #在系统启动时清空/tmp
  clear_tmp_enable="YES"

  #防止系统自动加入信息到motd
  update_motd="NO"

  #启动防火墙设置
  firewall_enable="YES"
  firewall_logging="YES"
  firewall_script="/etc/firewall.rules"

  #丢弃SYNFIN信息包。缺省时设置为”NO”,当设置为”YES”的时候,系统内核将忽略同时设置了syn和fin位的TCP桢(需要内核的支持:options tcp_drop_synfin)
  tcp_drop_synfin="YES"

  #丢弃ICMP重定向。可以防止DOS攻击或劫持进程(hijack sessions)
  icmp_drop_redirect="YES"
  icmp_log_redirect="YES" #记录ICMP重定向
  #在CISCO路由器上关闭重定向:no ip send-redirects

  log_in_vain="YES" #记录每一个到关闭端口的连接企图。
  accounting_enable="YES" #打开系统审计功能


  3.修改/etc/sysctl.conf文件,调整IP堆栈


  #关闭对广播类型的响应,过滤ICMP响应后,服务器无法ping 通,可以提高部分安全性能
net.inet.icmp.bmcastecho=0
  #对UDP包的校验和进行计算,防止不正确的UDP包的攻击
  net.inet.udp.checksum=1

  #在默认情况下,操作系统在关闭的端口上接受到TCP SYN段的时候,会发送RST信息包,告诉攻击者这个端口关闭了,导致攻击者继续扫描下一个端口,使端口扫描简单化,浪费了本机CPU时间在DOS上。我们可以使用blackhole来控制对没有socket监听的TCP或者UDP端口接受到连接请求时的行为。
  #当设置这个选项后,系统将马上丢弃这个包而不发RST包,连接端将看到"Connection reset by peer."

  net.inet.tcp.blackhole=2
  net.inet.udp.blackhole=1

  4.防火墙规则设置

  尽管按照上面的叙述已经能够形成一定的防护,但是若要实现安全程度更高的主机系统,就要借助于IPFW这样的包过滤软件,通过设置防火墙规则,严格限制对服务器的访问。

  过滤ICMP服务,命令格式:

  ipfw add pass log icmp from $ip to any [要处理的协议]

  icmp是使用类型规定出站的信息。
  0 echo-reply ping
  3 destination unreachable Any TCP/UDP traffic(主机不可到达)
  5 redirect routing if not running routing daemon(如果未运行路由守护程序,复位向路由)
  8 echo-request ping (入站信息)
  11 time-exceeded traceroute (traceroute 超时)

  配置文件的例子:
  ip="你自己的IP"

  #强制清除所有规则
  ipfw -f flush

  ipfw add pass log udp from $ip to any
  ipfw add pass log icmp from $ip to any icmp 8#接受回答
  ipfw add pass log icmp from not $ip to $ip icmp 0#拒绝请求
  ipfw add pass log icmp from not $ip to any icmp 11# traceroute 超时
  ipfw add pass log icmp from not $ip to any icmp 3#目标主机不可到达

  #SYN、FIN组合的包一般是nmap、queso扫描器使用,所以过滤。
  ipfw add deny log tcp from any to any in tcpflags syn,fin

  #检查通信状态
  ipfw add check-state
  ipfw add deny tcp from any to any in established
  ipfw add allow ip from any to any out keep-state

  #允许ident请求
  ipfw add allow tcp from any to any 113 keep-state setup

  5.日志管理

  (1)启动日志
  修改/etc/rc.conf文件。使用 "-s -s"标志启动syslogd,防止打开UDP 514端口;

  (2)修改/etc/syslog.conf文件,配置syslogd

  #可以将本地日志记录到其他主机loghost上:
  *.*@loghost

  #为FTP增加日志条目:
  ftp.* /var/log/ftpd
  #相关命令:touch /var/log/ftpd

  #记录SSH连接记录
  security.*;auth.info /var/log/security #记录连接到SSH的日志信息
  auth.* /var/log/authlog

  #使ipfw能够用syslog记录
  !ipfw
  *.* /var/log/ipfw.log

  (3)使用newsyslog压缩日志
  newsyslog程序能够定时压缩日志文件并清除旧的文件是,freebsd默认安装的,它是从crontab启动的:

  #grep newsyslog /etc/crontab
  0 * * * * root /usr/sbin/newsyslog

  可以修改/etc/newsyslog.conf以符合你的需求。通常把文件属性从664变为640,不让一般用户查看系统记录。

  /var/log/authlog root.wheel 640 7 100 * Z
  /var/log/ipfw.log root.wheel 640 3 100 * Z
  #这会在日志文件达到100K时将它压缩并编号,将mode改成640,chown成root.wheel,并删除旧的日志文件。

  #相关操作:
  #cd /var/log
  #chmod g-w,o-r *;chmod a+r wtmp
  #把所有文件的组属性改为wheel的。

  #防止一般用户读日志配置文件
  #chmod 600 /etc/syslog.conf
  #chmod 600 /etc/newsyslog.conf

  四、用户管理


  1.限制登录条件

  (1)把个人用户放到/etc/ftpchroot文件中,把他们限制在自己的HOME目录

  (2)修改/etc/shells文件,增加不能用来登录的shell,如passwd或者nologin,赋予仅需要FTP功能的用户以/usr/bin/passwd的shell 阻止他们使用SHELL命令。

  (3)拒绝直接以root身份登录:

  在/etc/ttys文件中,将"secure"标记改为"insecure"标记,使系统在进入单用户模式时会要求root密码。但是这样以来也为恢复root密码制造了障碍——安全和易用再次形成了矛盾的两个对立面。

  console none unknown off insecure

  (4)使用 tcp wrapper (/etc/hosts.allow)允许/拒绝访问特定的TCP服务。

  tcp_wrappers 可以在访问者要求服务前先检查/etc/hosts.allow 文件中设定的规则,符合放行规则的才会去启动服务程序,可以达到有条件开放系统服务的目的。

  在/etc/host.allow文件中,注释掉"ALL:ALL:allow",去掉其他无关服务访问,增加如下内容:

  sshd: localhost : allow
  sshd: friendlycomputer : allow
  sshd: all : deny

  另外需要注意的是:

  注意规则的先后顺序,因为tcp_wrappers的规则有first match 的特性,最好把放行的规则写在前面,然后在后面加一条全部禁止的规则;

  为避免 DNS 欺骗,规则尽量使用IP表示;

  FreeBSD缺省的/etc/hosts.allow中第一条规则是 ALL : ALL : allow,自己的规则一定要放在他前面才有效。

  (5)使用 allowuser/allowgroup SSH配置选项以允许特定的用户和组使用SSH连接。

  (6)限制登录的用户、组以及登录地方,修改/etc/login.access。

  (7)利用login.conf对用户的登录环境和资源许可进行设置。

  FreeBSD系统使用/etc/login.conf中描述的数据将用户按照登录环境、强制性的资源限制以及记帐管理登分为不同的登录类别,每个用户的登录类别记录在/etc/master.passwd中该用户的设置中。

  每次修改login.conf后,都要进行更新登录数据库的操作:

  #cap_mkdb /etc/login.conf

  由于登录类别保存在master.passwd文件中,通常在使用adduser添加用户的时候设置用户的登录类别,如果要进行修改,必须使用vipw来修改/etc/master.passwd文件中的5个域。


  2.登录环境


  (1)编辑/etc/motd文件,阻止计算机泄露系统信息

  (2)删除版权信息
  #touch /etc/COPYRIGHT

  (3)防止系统自动加入信息,修改/etc/rc.conf
  update_motd="NO"

  (4)修改登录提示,编辑/etc/gettytab,找到default:小节,他以下面的文字开头:
  :cb:ce:ck:lc

  小心的修改r:之间的文字来适应自己的需要。

  3.crontab的问题

  建议 www、nobody、bind等用户不能使用crontab,建立/etc/cron/allow文件把需要使用的用户放进去,如:
  #echo root>/var/cron/allow
  #chmod 600 /var/cron/allow

  如果不使用at命令,就关闭这个服务,在/etc/crontab文件中注释掉
  # */5 * * * * root /usr/libexec/atrun

  4.保护文件系统

  (1)锁住文件系统

  A.修改/etc/fstab文件,设置系统启动时自动挂接的文件系统,使用nosuid参数挂接/usr 或 /(目的是/sbin)文件系统,尤其是一般用户可以写入的文件系统,应单独划分分区:

  /home or /usr/home
  /tmp or /var/tmp

  /etc/fstab文件内容:
  /dev/sd0s1e /var/tmp ufs rw,nosuid 2 2

  B.搜寻并去除不用的二进制文件的suid位,(尤其是uucp——setgid)
  C.使用chflags设置变量,例如,给日志文件设置sappnd,给系统二进制文件设置schg标志;

  #相关命令:
  #找出你所有的可写入目录,
  #find / -perm -0777 -type d -ls

  找出那些程序是suid 或者sgid的命令:

  #find / -perm -2000 -ls
  #find / -perm -4000 –ls

  (2)文件保护,严格限制系统配置文件权限,只对root用户开放读写权利:

  #chflags schg /bin/*
  #chflags schg /sbin/*

  #chmod 600 /etc/firewall.rules
  #chmod 600 /etc/crontab
  #chmod 600 /etc/newsyslog.conf
  #chmod 600 /etc/rc.sysctl
  #chmod 600 /etc/rc.conf
  #chmod 600 /etc/syslog.conf
  #chmod 600 /etc/sysctl.conf
  #防止一般用户读日志文件
  # chmod 640 /var/log/httpd-access.log

  (3)可以把不是很有用的程序 chmod 000,如uustat,uucico。如果你从来不碰uucp或是PPP和PPPD的话,你绝不会用到他们。如果不用打印机的话,把lpr lprd也chmod 000了吧。

  5.其他相关

  修改计算机相关设置,如BIOS,不允许软盘启动、CDROM启动,即在装载硬盘驱动之前不允许其他媒介启动,设置BIOS密码,保护机器物理安全。

  五、配置SSH


  修改/etc/ssh/ssh_config文件

  (1)使用protocol 2代替protocol 1,SSH2更加安全,可以防止攻击者通过修改携带的版本banner来劫持(hijacking)启动会话进程并降低到protocol 1。注释掉protocol 2,1 改用下面语句代替:

  protocol 2

  (2)合理设置最大连接数量, 防止DOS攻击

  MaxStartups 5:50:10

  (3)禁止远程root和空密码登录,建议关闭X11forwording

  X11Forwarding no

  (4)强烈建议不使用静态密码,而使用DSA 或RSA KEY,修改如下内容可以关闭使用密码认证:

  PasswordAuthentication no

  (5)可以限制组或光是单个用户访问shell

  AllowGroups wheel
  AllowUsers xundi

  (6)使用TCP wrappers来限制一些访问,修改/etc/hosts.allow文件,注释掉"ALL : ALL : allow",增加如下内容:

  sshd:localhost:allow
  sshd:friendlcomputer:allow
  sshd:all : deny

  #相关命令:
  #chsh -s /sbin/nologin user

  六、总结和补充

  使用最新版本的操作系统;推荐使用STABLE或者最新RELEASE分支。
  修改系统前,首先备份系统。
  修改/etc/inetd.conf和rc.conf关闭可有可无和不必要的服务。
  立即禁用telnet,使用SSH代替之——OpenSSH在freebsd安装时即被包括。
  使用SSH2协议中内建的sftp服务代替标准的ftp
  建立SSH公钥防止口令传输。
  使用包过滤软件类如ipfw或者ipfilter限制服务的获取。
  禁止不需要的帐户
  应用组和用户的概念
  设置正确的文件权限
  以chroot环境运行具有潜在危险的程序,例如bind
  使用sudo,非严格root级访问
  限制某些强大命令的访问
  如何检查你的安全性

  /usr/ports/security/nmap 对自己进行端口扫描,以发现异常服务
  /usr/ports/security/whisker 对WEB服务器进行审计,防止潜在破坏
  /usr/ports/security/tripwire-
  /usr/ports/security/snort

  日常操作

  (1)经常查看http://www.freebsd.org/security/index.html的安全公告;
  (2)订阅security bugtraq和freebsd官方安全邮件列表了解安全动态;
  (3)每天查看系统日志,关于检查系统日志,你可以通过其他工具增加多信息的捕获,如snort可以比较完全的记录信息;
  (4)如果你的硬盘够大,信息处理够快,可以定时使用 netstat -an >> /.../.../netstat.log来记录信息,因为netstat能记录连接信息,所以如有些后门日志不能记录,但netstat却在一定时间里总有连接记录。
  (5)如果你对文件系统有原始的记录,可以定时使用一些系统完整性检查工具进行检验;
  (6)如果你有防火墙,经常查看防火墙信息。


另一相关帖子内容

http://www.jgwy.net/bbs/read.php?tid=103238&keyword=

闲趣---转自金光


- 作者: clay111 2007年05月24日, 星期四 12:18  回复(0) |  引用(1) 加入博采

vsftp配置大全
原文摘自:
http://bbs.bitscn.com/64783

环境 vmware+solaris9+vsftpd 2.0.3

1.从哪里下载vsftp的安装包
2.如何编译vsftp安装包
前两步就不赘述了,坛子里有好多帖里都有,search一下就能找到。

3.编译完成的文件需要如何安装到系统中去?
需要将编译完成的哪些文件拷贝到系统的哪些目录下
      编译完后将产生vsftp文件,其他的配置文件,帮助文件(man)应该是编译前已经存在的了
     。应此需要拷贝的文件有:
      vsftpd
      vsftpd.conf.5
      vsftpd.8
      vsftpd.conf
     拷贝路径为:
      vsftpd          /usr/local/sbin/
      vsftpd.conf.5   /usr/local/man/man5/
      vsftpd.8        /usr/local/man/man8/
      vsftpd.conf     /etc/
      (ps 安装文档中说可以用make install,但是我运行时,总是不成功)

4.运行vsftpd的最小设置:
  4.1 需要系统中有一个nobody用户,如果没有自己创建。
  4.2 需要系统中有一个ftp用户(作为vsftpd的匿名用户),要修改宿主目录为其他用户所有,
       并去掉改目录og的可写属性,例如,ftp的宿主目录是/var/ftp/,修改宿主目录属性:
       chown root:root /var/ftp
       chmod og-w /var/ftp
  4.3 需要创建/usr/share/empty/目录,这是vsftpd要求的默认配置,我也不知道做什么用的,:)

5.运行方式的选择:
5.1 standalone 方式:
     独立运行模式,不需要inetd作为"中间人"的方式:
     在/etc/vsftpd.conf 最后添加一行:
     listen=YES (注意,vsftpd.conf中的所有"="两边不能有空格。)
5.2 inetd 方式:
      把/etc/inetd.conf 中的ftp stream....  中in.ftpd 改成vsftpd,最后是启动参数vsftpd /etc/vsftpd.conf(替换掉 in.ftpd -a)就可以了
      设置/etc/vsftpd.conf中的listen=NO(如果不改的话,第一次ftp会失败,ctrl+c中止后,再ftp时,就可以用了,我试了两次,是这个结果)


在5.1后,vsftpd最小配置已经完成,就可以使用/usr/local/sbin/vsftp & 直接运行vsftpd,尝试用
ftp用户来登录,感受一把,呵呵。

6.增加自启动功能:

   将/etc/inetd.conf中的 ftp stream ..... in.ftpd 用#注释掉
   /etc/services 中的ftp  21/tcp 不要注释,否则无法连接到服务器上。

   vi /etc/rc3.d/S83vsftpd

     #!/sbin/sh
     case "$1" in
     start)
            /usr/local/bin/vsftpd &
     ;;
     stop)
            pkill vsftpd
     ;;
     *)
            echo "Usage: $0 { start | stop }"
            exit 1
     ;;
     esac
     exit 0  
    这个应该是standalone的自启动脚本,inted方式则不用。
    写好脚本后,将脚本增加执行权限:u+x,如果愿意可以把用户和组都改为和系统默认一致:root:sys


7.vsftp功能详细配置:

  先假设一下需求:
  7.1 需要能匿名登录vsftp server,只允许下载公开的内容,不允许匿名用户上传和和其他操作。

    根据需求,在vsftpd.conf中加入
     anonymous_enable=YES
     anon_world_readable_only=YES
     non_upload_enable=NO
     anon_mkdir_write_enable=NO
     anon_other_write_enable=NO
    其实这些采用默认值就可以了,也就是说,对于匿名用户,采用默认的设置已经可以实现7.1的需求了。
    只要在/var/ftp/放入给匿名用户下载的文件就可以了。

   
                 


以下时匿名用户和本地用户配置文件的主要参数值。

加入你想配置匿名ftp,把如下的参数存成vsftpd.conf,放到/etc下,不用安装包提供的那个示例配置文件(vsftpd.conf)

匿名ftp的以上控制分别为:
用户控制

anonymous_enable=YES         启用匿名用户
no_anon_password=YES         需要密码
anon_root=/var/ftp           匿名用户的主目录(默认为/var/ftp)
local_enable=NO              禁用本地用户
guest_enable=NO              禁用gust用户
ftp_username=ftp             匿名用户的用户名(默认还有anonymous可使用)

权限控制

write_enable=NO                 匿名用户不可写
local_umask=022                 上传文件的umask
file_open_mode=0666             上传文件的总权限,与umask共同决定了上传文件的实际权限
anon_upload_enable=NO           匿名用户不可以上传
anon_mkdir_write_enable=NO      匿名用户不可以建目录等写操作
anon_other_write_enable=NO      匿名用户不可以做其他的写操作
anon_world_readable_only=YES    匿名用户可以读文件
#chown_uploads=YES               修改上传的文件的属主
#chown_username=ftpadmin         修改上传的文件的属主为XXX
ascii_upload_enable=NO          不使用ascii上传文件
ascii_download_enable=NO        不使用ascii下载文件

secure_chroot_dir=/usr/share/empty  默认值

超时控制

idle_session_timeout=600          空闲超时600秒
data_connection_timeout=120       传输超时120秒
accept_timeout=60                 pasv模式等待时间60秒
connect_timeout=60                port模式等待时间60秒

服务控制

xferlog_enable=YES                 启动日志功能
xferlog_std_format=YES             使用标准日志格式
xferlog_file=/var/log/vsftpd.log   日志默认的位置
pasv_enable=YES                    启用被动模式
#port_enable=YES                    启用主动模式
tcp_wrappers=YES                   启用tcp_wrappers功能
nopriv_user=nobody                 最低权限用户

listen=YES                         使用standalone 模式(推荐的)

显示信息

ftpd_banner=welcome to ftp.        登录时的欢迎信息
dirmessage_enable=YES              启动切换目录时提示目录信息的功能
message_file=.message              目录提示信息的内容文件



连接选项
max_clients=100                       最大连接数
max_per_ip=5                          每个ip最大连接数
connect_from_port_20=YES              启用20端口传输数据
#listen_address=192.168.0.2            限制只有此ip地址可以访问
listen_port=21                        监听的端口号
ftp_data_port=20                      数据传输端口号

pasv_max_port=0                       被动模式的端口号的上限(0为不限)
pasv_min_port=0                       被动模式的端口号的下限(0为不限)

数据传输速度

anon_max_rate=51200                   匿名用户最大传输率
local_max_rate=5120000                本地用户最大传输率

************************************************************************


加入你想配置本地用户ftp,把如下的参数存成vsftpd.conf,放到/etc下,不用安装包提供的那个示例配置文件(vsftpd.conf)

本地用户的各部分功能设置为:(注意,本地用户模式编译不要选择pam模块)
用户控制

anonymous_enable=NO                           禁用匿名用户
no_anon_password=YES                          需要密码
anon_root=/var/ftp                            匿名用户的默认主目录
local_enable=NO                               禁用本地用户
local_root=webdisk                            本地用户的主目录(相对路径是相对于用户的家目录,绝对路径是所有用户都只能登录到这个目录下比如:/localftp)
guest_enable=NO                               禁用gust用户
ftp_username=ftp                              匿名用户的用户名(默认还有anonymous可使用)

权限控制

write_enable=YES                                 本地用户可写
local_umask=022                                  上传文件的umask
file_open_mode=0666                              使用文件的方式
anon_upload_enable=NO                            匿名用户不可以上传
anon_mkdir_write_enable=NO                       匿名用户不可以建目录等写操作
anon_other_write_enable=NO                       匿名用户不可以做其他的写操作
anon_world_readable_only=YES                     匿名用户可以读文件
#chown_uploads=YES                               修改上传的文件的属主
#chown_username=ftpadmin                         修改上传的文件的属主为XXX
ascii_upload_enable=NO                           不使用ascii上传文件
ascii_download_enable=NO                         不使用ascii下载文件

secure_chroot_dir=/usr/share/empty                   默认值

超时控制
                 
idle_session_timeout=600                           空闲超时600秒
data_connection_timeout=120                        传输超时120秒
accept_timeout=60                                  pasv模式等待时间60秒
connect_timeout=60                                 port模式等待时间60秒

服务控制

xferlog_enable=YES                                  启动日志功能
xferlog_std_format=YES                              使用标准日志格式
xferlog_file=/var/log/vsftpd.log                    日志默认的位置
pasv_enable=YES                                     启用被动模式
#port_enable=YES                                     启用主动模式
#注意此处pasv和port只能写一个,不能一个YES,另一个NO,要想让另一个不起作用,只能用#注释掉,否则会出错。
tcp_wrappers=YES                                    启用tcp_wrappers功能
nopriv_user=nobody                                  最低权限用户


listen=YES                                          使用standalone 模式(推荐的)

显示信息

ftpd_banner=welcome to ftp.                         登录时的欢迎信息
dirmessage_enable=YES                               启动切换目录时提示目录信息的功能
message_file=.message                               目录提示信息的内容文件


文件权限设置
chroot_list_enable=YES                            启动用户目录限制功能
chroot_list_file=/etc/vsftpd/vsftpd.chroot_list   此文件中的用户不能改变到其他外层目录中。

userlist_enable=YES                                启动用户限制功能
userlist_deny=YES                                  userlist文件中的用户禁止登录,NO的话则只有userlist中用户可以登录
userlist_file=/etc/vsftpd/vsftpd.user_list         禁止登录用户列表文件名和位置(可自定义)

user_config_dir=/etc/vsftpd/userconf/             对个别用户特殊设置的配置文件的目录(在此目录下建立对应“用户名”的文件,文件里写
                                                   write_enable=YES
                                                   anon_world_readable_only=NO
                                                   anon_upload_enable=YES
                                                   anon_mkdir_write_enable=YES
                                                   anon_other_write_enable=YES 等权限信息,此用户将有这里所写的权限)



连接选项
max_clients=100                                          最大连接数
max_per_ip=5                                              每个ip最大连接数
connect_from_port_20=YES                               启用20端口传输数据
#listen_address=192.168.0.2                             指定监听的ip地址,如果你有多个ip的话
listen_port=21                                         监听的端口号
ftp_data_port=20                                       数据传输端口号

pasv_max_port=40000                                    被动模式的端口号的上限(0为不限)
pasv_min_port=30000                                    被动模式的端口号的下限(0为不限)

数据传输速度

anon_max_rate=51200                                    匿名用户最大传输率
local_max_rate=5120000                                 本地用户最大传输率

(具体ip限制可以在/etc/hosts.allow,/etc/hosts.deny中设置
  还可以对每个用户进行磁盘限额,这里就不做了)




********************实   例******************************************

采用本地用户实现ftp功能,虚拟用户的设置太复杂了,又涉及到pam和db,这两个东东都没搞过,影响vsftp的学习,再说localuser基本能满足需要了
假设要实现如下功能:

系统中存在如下用户:
拒绝登录的用户:  denyuser1
不能chroot的用户:unchrootuser
不允许上传的用户:deny_upload
普通用户:        normaluser
(用户名设的过长了,不过还能用)



普通用户可以ftp登录到各自的HOME目录中,可以转到其他目录,允许上传下载,
不允许上传的用户,需要单独的配置文件来限制其不能上传;(/etc/vsftpd/deny_upload)
不能chroot的用户,只能登录限定的目录中。(/etc/vsftpd/unchroot)
拒绝登录的用户在拒绝登录列表中(/etc/vsftpd/denyuser)

权限设置部分:

write_enable=YES
anon_mkdir_write_enable=YES                       匿名用户不可以建目录等写操作
anon_other_write_enable=YES                       匿名用户不可以做其他的写操作
anon_world_readable_only=YES                      匿名用户可以读文件

userlist_enable=YES                                启动用户限制功能
userlist_deny=YES                                  userlist文件中的用户禁止登录,NO的话则只有userlist中用户可以登录
userlist_file=/etc/vsftpd/denyuser                 禁止登录用户列表文件名和位置(在denyuser文件中加入一行denyuser1)

chroot_list_enable=YES                            启动用户目录限制功能
chroot_list_file=/etc/vsftpd/unchroot             此文件中的用户不能改变到其他外层目录中。(加入一行unchrootuser)


user_config_dir=/etc/vsftpd/userconf/             对个别用户特殊设置的配置文件的目录(在此目录下建立deny_upload的文件,文件里写
                                                   write_enable=NO
                                                   anon_world_readable_only=NO
                                                   anon_upload_enable=NO
                                                   anon_mkdir_write_enable=NO
                                                   anon_other_write_enable=NO 我觉得只要把write_enable设成NO,下边的不用管就行了,不过考虑到安全还是都改成NO了)

然后就是建立相应的用户,修改配置文件,启动vsftpd,测试一把了。

- 作者: clay111 2007年05月8日, 星期二 20:43  回复(0) |  引用(1) 加入博采

LAMP优化(ZT)
原文出处:http://blog.saycoo.com/14


I started to write this post many weeks ago and finally publish it even if it’s not totally finish. It is just a little feedback about tuning a full LAMP server with some user traffic and services load. Important thing to notice is that all stuff in this post is NOT THE SOLUTION. You will probably have to tune little more for adapt all this to your personal server usage, server load, development & architecture. So, use those tips as a kind of inspiration instead of an “how to”. Don’t forget that when you do such tuning, take care to keep a backup of your previous configuration files.

We will try to tune the following server :

  • Current OS : Debian GNU Linux Kernel 2.4.32 ipv4 + GRSEC
  • 1Go RAM DDR
  • Intel(R) Celeron(R) CPU 2.66GHz
  • SWAP 512Mo
  • 3Go on / and 226Go on /home
  • Running services are Qmail, Bind9, mrtg, Apache 2.2.2, PHP 5.1.4, MySQL 5.0.21


The best way for tuning a server is to have dedicated services on one server and so, having multiple server especially for MySQL and Apache.

We were runing a heavy website with DotClear and the heavy PhpADS with all its stuff (geoip, all counters, etc.)
The server up to a load of 114 in some peak with a swap totally used ! And so.. a big freeze of services… 70k mails/day , 110k pv/day, 12k v/day, 47 sql queries/sec

In fact, services weren’t so loaded but the box was crashing a lot and swapping often without using too much CPU.

First things that I do was to change the Linux Kernel from a 2.4.32 to a 2.6.18. Lot of things were improves in 2.6. I convey you to take a look at this post on IBM :
http://www-128.ibm.com/developerworks/linux/library/l-web26/

After this update, I take the time to update all version software for using a MySQL 5.0.27, PHP 5.2 etc. Without looking at the changelogs, bugfixes will still help us :-)
After this, we will tune our software configuration that still use default values (this is really bad ! :) then we will tune a little the kernel without recompile a new one.

  • Apache 2.2.2 Prefork

Our HTTPD is using some modules as url rewriting, server info, php5, GeoIP and other basic modules. We could optimize much more by using an Apache 2.2.3 Worker and only useful modules or even more delivering static pages and using proxy for dynamic pages. All this depend on your developments and your server usage. Here we will only focus on the Apache Prefork.
Nowadays, it’s important to keep active the KEEPALIVE functionality. This will increase the speed of delivring pages for lot of modern browsers (it’s supported by ie, firefox, safari, opera, etc.). The only thing is to touch a little to the default value. In fact, if your keepalive time out is too big, you will keep an entire apache slot open for a user that is probably gone ! A 4 seconds timeout is enough for delivering a full web page and take care of any network congestion. MaxKeepAliveRequests is used to define the maximum number of request manage by an apache slot during a keepalive session. Except if you have lot of pictures to load on your web pages you don’t really need to have a big value at this state.

KeepAlive On
KeepAliveTimeout 4
MaxKeepAliveRequests 500

As I don’t have lot of memory available on the server I ‘m constraint to decrease drastically the number of running servers from 150 to 60. As I have an apache using approximatly 13Mo of memory (withdraw 3Mo of shared memory), I need approximately 600 Mo of available memory when all the apache child process are running. We have to consider, for our further tuning, that this memory is used. It’s really important in our case to dedicate memory for avoid to swap too much and lost the box in a freeze. you can follow your memory usage by using TOP and looking for your apache/httpd process. (Do a quick “man top” for know more). If you have little more free memory you can take a look to the apache documentation for further tuning.

ServerLimit 60
MaxClients 60

Our server is often overload, with lot of traffic. When I need to restart the apache, or in case of any crashes the apache server start with only 5 Child server process and will add new one 1 second later, 2 new child 2 second later, 4 new at the third second, etc. It’s really too long when you are in a peak ! So, I configured StartServers for let us start directly with 30 child Server process. That will help us to deliver quickly the clients and minimize the impact of the server restart.

MinSpareServers and MaxSpareServers is used in same way as StartServer. When your apache server isn’t load, there is idle child waiting for connection. It’s not usefull to have all your child still open but, In case of a new peak the best way to minimize its impact on your server is to deliver web pages as quick as possible. So keeping some idle Child Process still waiting for client isn’t so stupid. Furthermore in case of our touchy server we consider to be able to allocate 600Mo of RAM. So, We can use it even if it’s for idle Child Process as we dedicate this RAM for apache. For avoid any module Memory Leak, and having fully available Child I set the MaxRequestPerChild to 1000, that mean that each 1000 request, the child will be kill and Apache Server will spare a new one. You’ll probably have to set this value to a higher number. It’s depend of the structure of your web page. You will have to monitor a little your server after those change for being sure to don’t have too much child kill/spare instead of delivering web pages.

StartServers 30
MinSpareServers 30
MaxSpareServers 30
MaxRequestsPerChild 1000

Follow some security issue, we don’t display too much information about our server. As we don’t need the reverse lookup on the client ip, we keep the default value of HostnameLookups to Off and by this way we save some network traffic and server load.

ServerTokens Prod
ServerSignature Off
HostnameLookups Off

  • PHP 5.1.4

For perform our page generation and save some cpu we use the php extension eaccelerator. Take a look at the documentation for install it.
We dedicate 32Mo of our RAM for eaccelerator (shm_size) and will use it with shared memory and file cache (”shm_and_disk” value for keys, sessions and content variable). (Memory is really useful in our case, because of all the mails, apache log and MySQL disk access that generate too much i/o and slow down considerably all the server). As we don’t change often the php script on the server we don’t need to use the check_mtime functionality. When set to “1″, that will do a stat on the php script for checking of last modification date We don’t need this because we want to save disk access and we don’t have so many updates on the running scripts. We just have to clean the cache directory after an update.

eaccelerator.shm_size=”32″
eaccelerator.cache_dir=”/www/tmp/eaccelerator”
eaccelerator.enable=”1″
eaccelerator.optimizer=”1″
eaccelerator.check_mtime=”0″
eaccelerator.debug=”0″
eaccelerator.filter=”"
eaccelerator.shm_max=”0″
eaccelerator.shm_ttl=”3600″
eaccelerator.shm_prune_period=”1″
eaccelerator.shm_only=”0″
eaccelerator.compress=”1″
eaccelerator.compress_level=”9″
eaccelerator.keys = “shm_and_disk”
eaccelerator.sessions = “shm_and_disk”
eaccelerator.content = “shm_and_disk”

  • MySQL 5.0.24

As I don’t manage how has been coding many of running script, I decrease all the timeout MySQL connection for avoid congestion. Then I increase the number off simultaneous MySQL connection as we had lot of “Too many connection” error message.

wait_timeout=6
connect_timeout=5
interactive_timeout=120
max_connections = 500
max_user_connections = 500

Now we change the touchiest part of the MySQL configuration : The RAM usage. It’s touchy because a bad value can really decrease your server performance and result in a big server swap. After some test I decrease the table cache and the key buffer cache to 256Mo. In fact we don’t have so many available ram as we had 600Mo for our HTTPD and we have lot of other services running. I tried to set it up little higher, hopping that the swap won’t be to big, but in fact, due to our i/o load the swap were totaly not a good thing for MySQL :-)

If you are using MYISAM tables I suggest you to use the “concurrent_insert=2” that will really increase your server performance in many case. MYISAM use table lock, with concurrent insert, the engine will sometime bypass the lock and allow INSERT and SELECT to run concurrently. We also disable all engine that is not used (innodb, bdb). Take a look at the MySQL documentation for better tuning.

join_buffer_size=1M
sort_buffer_size=1M
read_buffer_size=1M
read_rnd_buffer_size=1M
table_cache=256M
max_allowed_packet=4M

key_buffer=256M
key_buffer_size=256M
thread_cache=256M
thread_concurrency=2
thread_cache_size=40
thread_stack=128K

concurrent_insert=2

query_cache_limit=1M
query_cache_size=256M
query_cache_type=1
skip-bdb
skip-innodb

  • Linux Kernel 2.6.18

Here is a touchy part of our tuning, we will try to perform the Linux Kernel behavior with our server load for save some memory and avoid too much swap. Furthermore, has we done a great stuff above this part, we have to manage more TCP connection and support correctly the peak. We will use the command “sysctl” for doing our update on values.

# display value of a variable or group of variable
sysctl [-n] [-e] variable …
# set a new value toe the specified variable
sysctl [-n] [-e] [-q] -w variable=value …
# display all the variable
sysctl [-n] [-e] -a
# load a sysctl config file
sysctl [-n] [-e] [-q] -p (default /etc/sysctl.conf)

For our test we will create a test config file “/etc/sysctl.conf.testing” and we will load it by using the following command line :

sysctl -p /etc/sysctl.conf.testing

When you will be glad of your change you could rename the file for “/etc/sysctl.conf”. All the sysctl variable are documented with the Kernel Sources. I suggest you to download the documentation corresponding to your kernel version and read it carefully if you decide to change some values.
A really good article on Security Focus give us some key for minimize the impact of a SYN ATTACK / SYN SPOOFING. In this goal we activate the syncookies and the route validation

net.ipv4.conf.default.rp_filter=1
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_synack_retries=3
net.ipv4.tcp_syn_retries=3

As we had some swap troubles, important thing to do is to change the value of vm.swappiness where the default value is 60. This variable control how much the kernel should favor swapping out applications, its value can be 0 to 100. I set it to 10 for minimize the swap.

vm.swappiness=10

We upgrade the max backlog for support more TCP traffic and we change the congestion control algorithm to BIC. The Linux Kernel support lot of congestion algorithm like Reno (default one), htcp, vegas, westwood, etc.

net.core.netdev_max_backlog=2500 # Interface buffering
net.ipv4.tcp_max_syn_backlog=4096
net.core.somaxconn=1024 # Limit of socket listen() backlog. Default is 128.
net.ipv4.tcp_congestion_control=bic

For avoid to have a big TCP queue and so memory usage for not really active connection I decrease some TCP timeout and force the kernel to recycle quickly tcp connection. We don’t cache the value of ssthresh (Slow Start Threshold) for avoid to impact a given host to have a reduced ssthresh for all is next connections.

net.ipv4.tcp_keepalive_time=900
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_max_orphans=16384
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.tcp_rfc1337=1
net.ipv4.tcp_no_metrics_save=1

It’s critical to use the optimal SEND and RECEIVE socket buffer size for the link you are using. In our case we have a 100Mbits link connection. So for a better TCP connection and congestion control we had to increase the TCP Buffer. You can read more about this here.

net.core.rmem_max=16777216
net.core.wmem_max=16777216
net.ipv4.tcp_rmem=4096 87380 16777216
net.ipv4.tcp_wmem=4096 65536 16777216

  • That’s all folks !

Now, this server support twice more traffic load. Technical aspect was our traffic growth bottleneck. Lot of other tuning could be done for better performance (on i/o and disk access, other kernel options, compile a new kernel, using apache worker, etc.). This post was just some clues about how to tune your servers. One important thing to don’t forget is whatever you tune on your server, that will never be enough if you have a bloody developed programs running on it !

- 作者: clay111 2007年04月29日, 星期日 18:43  回复(0) |  引用(1) 加入博采

gentoo安装手册

step by step amd64 installation :
http://www.gentoo.org/doc/en/handbook/handbook-amd64.xml

attached our installation notes for w1 & w2.

a few more important notes for you :

- we don't install X-window, only terminal based

- take special care to the "CFLAGS" setting in make.conf , this discussion
suggested use "-march=nocona -O2 -pipe" http://forums.gentoo.org/viewtopic.php?t=225828

- we should use the "sys-kernel/hardened-sources" instead of general sys-kernel/gentoo-sources

- for file system , i think we should use reiser4 instead of ext3

- at /usr/src/linux, when you select kernal configuration,
in "Processor type and features" -> High Memory Support ->
you should choose the value higher than 4GB

========================================================


Gentoo setup

1. boot from CD-ROM
2. Testing the network
3. using the DHCP "dhcpcd eth0"
4. fdisk "fdisk /dev/sda"
       3 paritions (32M sda1, 8G sda2, remaining sda3)
5. Making filesystem
# mke2fs /dev/hda1
# mke2fs -j /dev/hda3
# mkswap /dev/hda2
# swapon /dev/hda2
6. Mount the system
# mount /dev/hda3 /mnt/gentoo
# mkdir /mnt/gentoo/boot
# mount /dev/hda1 /mnt/gentoo/boot
7. Deploy stageTar
#links2 http://www.gentoo.org/main/en/mirrors.xml    选择下载一个stage3包
cd /mnt/gentoo
# tar xvjpf /mnt/cdrom/stages/stage3--2006.0.tar.bz2 -C /mnt/gentoo
8. Deploy portage
# tar xvjpf /mnt/gentoo/portage-.tar.bz2 -C /mnt/gentoo/usr
9. vi /mnt/gentoo/etc/make.conf
add CFLAGS="-march=k8 -pipe -O2"
add MAKEOPTS="-j3"
10. chroot
# mirrorselect -i -o >> /mnt/gentoo/etc/make.conf
# mirrorselect -i -r -o >> /mnt/gentoo/etc/make.conf
11. Copy DNS
# cp -L /etc/resolv.conf /mnt/gentoo/etc/resolv.conf
# mount -t proc none /mnt/gentoo/proc
# mount -o bind /dev /mnt/gentoo/dev
12. chroot
chroot /mnt/gentoo /bin/bash
# env-update
# source /etc/profile
# export PS1="(chroot) $PS1"
13. emerge --sync   or  emerge --sync --quiet     后面选项可以加速
14. vi /etc/make.conf
add USE="-X" #remove X
15. get Hardened Kernel/Gentoo Kernel
USE="-doc symlink" emerge hardened-sources/gentoo-sources

16. Compile kernel
cd /usr/src/linux
make menuconfig
make && make modules_install

cp arch/x86_64/boot/bzImage /boot/kernel-2.6.17-gentoo-r5

17. update filesystem
nano -w /etc/fstab
----------------------------------------------------------------
/dev/sda1   /boot     ext2    defaults,noatime     1 2
/dev/sda2   none      swap    sw                   0 0
/dev/sda3   /         ext3    noatime              0 1

none        /proc     proc    defaults             0 0
none        /dev/shm  tmpfs   nodev,nosuid,noexec  0 0

/dev/cdroms/cdrom0    /mnt/cdrom    auto      noauto,user    0 0
----------------------------------------------------------------
18. update hostname
nano -w /etc/conf.d/hostname
nano -w /etc/conf.d/domainname
rc-update add domainname default
nano -w /etc/conf.d/net
add >> config_eth0=( "dhcp" )
add >> config_eth1=( "dhcp" )
# rc-update add net.eth0 default
# cd /etc/init.d
# ln -s net.eth0 net.eth1
# rc-update add net.eth1 default

19. System tools
emerge app-admin/mcelog
# emerge syslog-ng
# rc-update add syslog-ng default
rc-update add sshd default
emerge sys-apps/slocate
emerge dhcpcd
emerge app-admin/sudo
emerge vim
emerge grub
# grub
grub> root (hd0,0)          (指出你的/boot分区的位置)
grub> setup (hd0)           (安装GRUB到MBR)
grub> quit                  (退出GRUB shell

20.
nano -w /boot/grub/grub.conf
--------------------------------------------
# Which listing to boot as default. 0 is the first, 1 the second etc.
default 0
# How many seconds to wait before the default listing is booted.
timeout 30
# Nice, fat splash-image to spice things up :)
# Comment out if you don't have a graphics card installed
splashimage=(hd0,0)/boot/grub/splash.xpm.gz

title=Gentoo Linux 2.6.17-r5
# Partition where the kernel image (or operating system) is located
root (hd0,0)
kernel /boot/kernel-2.6.17-gentoo-r5 root=/dev/hda3

title=Gentoo Linux 2.6.17-r5 (rescue)
# Partition where the kernel image (or operating system) is located
root (hd0,0)
kernel /boot/kernel-2.6.17-gentoo-r5 root=/dev/hda3 init=/bin/bb
--------------------------------------------
21.
grub

grub> root (hd0,0)          (指出你的/boot分区的位置)
grub> setup (hd0)           (安装GRUB到MBR)
grub> quit                  (退出GRUB shell)

22. passwd for root
23. exit
cd
umount /mnt/gentoo/boot /mnt/gentoo/dev /mnt/gentoo/proc /mnt/gentoo
reboot

24. add user
# useradd -m -G users,wheel,audio -s /bin/bash john
# passwd john
Change default editor
vi /etc/rc.conf

25. vi /etc/make.conf
add USE="-X -alsa -avi -cups -fortran -gnome -gtk -gtk2 -ipv6 -kde -mp3 -mpeg -opengl -quicktime -xv apache2"


26. emerge apache

27. enable usertrack and rewrite modules
vi /etc/conf.d/apache2
add "-D REWRITE -D USERTRACK"

28.

USE="sockets mysql cjk ctype curl apache2 berkdb cli crypt gdbm iconv ipv6 ncurses nls pcre readline reflection session spl ssl unicode zlib exif xml json snmp gd" emerge -av dev-lang/php

ACCEPT_KEYWORDS="~x86" emerge -av dev-php5/pecl-memcache

emerge -v dev-lang/php


29. install apachetop
emerge app-admin/apachetop

30. install qmail
emerge --unmerge mail-mta/ssmtp
emerge mail-mta/qmail
 * To start qmail at boot you have to add svscan to your startup
 * and create the following links:
 * ln -s /var/qmail/supervise/qmail-send /service/qmail-send
 * ln -s /var/qmail/supervise/qmail-smtpd /service/qmail-smtpd
 rc-update add svscan default


31. compile ado extension
-remember to add "-march=k8" at the compilation

32. install ADO library code
emerge dev-php/adodb

33. install imagemagick
emerge media-gfx/imagemagick



所有碰到的问题,基本都是编译内核的问题.编译内核需要非常小心.

- 作者: clay111 2007年04月29日, 星期日 17:31  回复(0) |  引用(1) 加入博采

用rsync实现网站镜像和备份(ZT)
本文摘自:
http://hi.baidu.com/finet/blog/item/e43dd8f2df3fb412b07ec5ca.html

简介
对于选择Linux 作为应用平台的的中小型企业或网站来说,往往面临如何实现数据远程备份或者网站镜象的问题,虽然有商业化的备份和镜象产品可供选择,但这些产品的价格往往过于昂贵。因此如何利用自由软件高效实现远程备份和网站镜象就成为一个值得讨论的话题。

通过网络进行远程数据备份或者网站镜象的最简单的方法就是使用wget,但是这种方式每次都需要将所有数据都重新在网络上传输一遍,而不考虑哪些文件是经过更新的,因此效率非常低下。尤其在需要备份的数据量很大的时候,往往需要花费数个小时来在网络上进行数据传输。

因此这里就介绍一种高效的网络远程备份和镜象工具-rsync,它可以满足绝大多数要求不是特别严格的备份需求。

rsync是类unix系统下的数据镜像备份工具,从软件的命名上就可以看出来了——remote sync。它的特性如下:

可以镜像保存整个目录树和文件系统。
可以很容易做到保持原来文件的权限、时间、软硬链接等等。
无须特殊权限即可安装。
优化的流程,文件传输效率高。
可以使用rcp、ssh等方式来传输文件,当然也可以通过直接的socket连接。
支持匿名传输,以方便进行网站镜象。
软件下载
rysnc的主页地址为:

http://rsync.samba.org/

目前最新版本为2.4.6。可以选择从原始网站下载:http://rsync.samba.org/ftp/rsync/。也可以选择从本站下载:rsync 2.4.6。

编译安装
rsync的编译安装非常简单,只需要以下简单的几步:

[root@www rsync-2.4.6]# ./configure
[root@www rsync-2.4.6]# make
[root@www rsync-2.4.6]# make install

但是需要注意的是必须在服务器A和B上都安装rsync,其中A服务器上是以服务器模式运行rsync,而B上则以客户端方式运行rsync。这样在web服务器A上运行rsync守护进程,在B上定时运行客户程序来备份web服务器A上需要备份的内容。

rsync服务器
1、rsync服务器的启动

在web服务器A上需要以守护进程方式来启动rsync服务器,只需要运行:

[root@www rsync-2.4.6]# /usr/local/bin/rsync --daemon

即可启动。rsync默认服务端口为873,服务器在该端口接收客户的匿名或者认证方式的备份请求。

如果要在启动时把服务起来,有几种不同的方法,比如:

a、加入inetd.conf

编辑/etc/services,加入rsync 873/tcp,指定rsync的服务端口是873。编加/etc/inetd.conf,加入rsync stream tcp nowait root /bin/rsync rsync --daemon

注:对于xinetd,设置方法类似。

b、加入rc.local

编辑/etc/rc.d/rc.local,在最后添加:

/usr/local/bin/rsync --daemon

2、rsync的配置

对于rsync服务器来说,最重要和复杂的就是它的配置了。rsync服务器的配置文件为/etc/rsyncd.conf,其控制认证、访问、日志记录等等。

该文件是由一个或多个模块结构组成。一个模块定义以方括弧中的模块名开始,直到下一个模块定义开始或者文件结束,模块中包含格式为name = value的参数定义。每个模块其实就对应需要备份的一个目录树,比方说在我们的实例环境中,有三个目录树需要备份:/www/、 /home/web_user1/和/home/web_user2/,那么就需要在配置文件中定义三个模块,分别对应三个目录树。

配置文件是行为单位的,也就是每个新行都表示一个新的注释、模块定义或者参数赋值。以#开始的行表示注释,以"\"结束的行表示下面一行是该行的继续。参数赋值中等号后可能是一个大小写不敏感的字符串、一个以trure/false表示的布尔值。

全局参数

在文件中[modlue]之前的所有参数都是全局参数,当然也可以在全局参数部分定义模块参数,这时候该参数的值就是所有模块的默认值。

motd file

"motd file"参数用来指定一个消息文件,当客户连接服务器时该文件的内容显示给客户,默认是没有motd文件的。

log file

"log file"指定rsync的日志文件,而不将日志发送给syslog。

pid file

指定rsync的pid文件。

syslog facility

指定rsync发送日志消息给syslog时的消息级别,常见的消息级别是:uth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, sys-log, user, uucp, local0, local1, local2, local3,local4, local5, local6和local7。默认值是daemon。

模块参数

在全局参数之后就需要定义一个或多个模块了,模块中可以定义以下参数:

comment

给模块指定一个描述,该描述连同模块名在客户连接得到模块列表时显示给客户。默认没有描述定义。

path

指定该模块的供备份的目录树路径,该参数是必须指定的。

use chroot

如果"use chroot"指定为true,那么rsync在传输文件以前首先chroot到path参数所指定的目录下。这样做的原因是实现额外的安全防护,但是缺 点是需要以roots权限,并且不能备份指向外部的符号连接所指向的目录文件。默认情况下chroot值为true。

max connections

指定该模块的最大并发连接数量以保护服务器,超过限制的连接请求将被告知随后再试。默认值是0,也就是没有限制。

lock file

指定支持max connections参数的锁文件,默认值是/var/run/rsyncd.lock。

read only

该选项设定是否允许客户上载文件。如果为true那么任何上载请求都会失败,如果为false并且服务器目录读写权限允许那么上载是允许的。默认值为true。

list

该选项设定当客户请求可以使用的模块列表时,该模块是否应该被列出。如果设置该选项为false,可以创建隐藏的模块。默认值是true。

uid

该选项指定当该模块传输文件时守护进程应该具有的uid,配合gid选项使用可以确定哪些可以访问怎么样的文件权限,默认值是"nobody"。

gid

该选项指定当该模块传输文件时守护进程应该具有的gid。默认值为"nobody"。

exlude

用来指定多个由空格隔开的多个模式列表,并将其添加到exclude列表中。这等同于在客户端命令中使用--exclude来指定模式,不过配置文件中指 定的exlude模式不会传递给客户端,而仅仅应用于服务器。一个模块只能指定一个exlude选项,但是可以在模式前面使用"-"和"+"来指定是 exclude还是include。

但是需要注意的一点是该选项有一定的安全性问题,客户很有可能绕过exlude列表,如果希望确保特定的文件不能被访问,那就最好结合uid/gid选项一起使用。

exlude from

指定一个包含exclude模式的定义的文件名,服务器从该文件中读取exlude列表定义。

include

用来指定多个由空格隔开的多个rsync并应该exlude的模式列表。这等同于在客户端命令中使用--include来指定模式,结合 include和 exlude可以定义复杂的exlude/include规则。一个模块只能指定一个include选项,但是可以在模式前面使用"-"和"+"来指定是 exclude还是include。

include from

指定一个包含include模式的定义的文件名,服务器从该文件中读取include列表定义。

auth users

该选项指定由空格或逗号分隔的用户名列表,只有这些用户才允许连接该模块。这里的用户和系统用户没有任何关系。如果"auth users"被设置,那么客户端发出对该模块的连接请求以后会被rsync请求challenged进行验证身份这里使用的 challenge/response认证协议。用户的名和密码以明文方式存放在"secrets file"选项指定的文件中。默认情况下无需密码就可以连接模块(也就是匿名方式)。

secrets file

该选项指定一个包含定义用户名:密码对的文件。只有在"auth users"被定义时,该文件才有作用。文件每行包含一个username:passwd对。一般来说密码最好不要超过8个字符。没有默认的 secures file名,需要限式指定一个。(例如:/etc/rsyncd.secrets)

strict modes

该选项指定是否监测密码文件的权限,如果该选项值为true那么密码文件只能被rsync服务器运行身份的用户访问,其他任何用户不可以访问该文件。默认值为true。

hosts allow

该选项指定哪些IP的客户允许连接该模块。客户模式定义可以是以下形式:

o xxx.xxx.xxx.xxx,客户主机只有完全匹配该IP才允许访问。例如:192.167.0.1

o a.b.c.d/n,属于该网络的客户都允许连接该模块。例如:192.168.0.0/24

o a.b.c.d/e.f.g.h,属于该网络的客户都允许连接该模块。例如:192.168.0.0/255.255.255.0

o 一个主机名,客户主机只有拥有该主机名才允许访问,例如:backup.linuxaid.com.cn。


o *.linuxaid.com.cn,所有属于该域的主机都允许。

默认是允许所有主机连接。

hosts deny

指定不允许连接rsync服务器的机器,可以使用hosts allow的定义方式来进行定义。默认是没有hosts deny定义。

ignore errors

指定rsyncd在判断是否运行传输时的删除操作时忽略server上的IP错误,一般来说rsync在出现IO错误时将将跳过--delete操作,以防止因为暂时的资源不足或其它IO错误导致的严重问题。

ignore nonreadable

指定rysnc服务器完全忽略那些用户没有访问权限的文件。这对于在需要备份的目录中有些文件是不应该被备份者得到的情况是有意义的。

transfer logging

使rsync服务器使用ftp格式的文件来记录下载和上载操作在自己单独的日志中。

log format

通过该选项用户在使用transfer logging可以自己定制日志文件的字段。其格式是一个包含格式定义符的字符串,可以使用的格式定义符如下所示:

o %h 远程主机名

o %a 远程IP地址

o %l 文件长度字符数

o %p 该次rsync会话的进程id

o %o 操作类型:"send"或"recv"

o %f 文件名

o %P 模块路径

o %m 模块名

o %t 当前时间

o %u 认证的用户名(匿名时是null)

o %b 实际传输的字节数

o %c 当发送文件时,该字段记录该文件的校验码

默认log格式为:"%o %h [%a] %m (%u) %f %l",一般来说,在每行的头上会添加"%t [%p] "。在源代码中同时发布有一个叫rsyncstats的perl脚本程序来统计这种格式的日志文件。

timeout

通过该选项可以覆盖客户指定的IP超时时间。通过该选项可以确保rsync服务器不会永远等待一个崩溃的客户。超时单位为秒钟,0表示没有超时定义,这也是默认值。对于匿名rsync服务器来说,一个理想的数字是600。

refuse options

通过该选项可以定义一些不允许客户对该模块使用的命令参数列表。这里必须使用命令全名,而不能是简称。但发生拒绝某个命令的情况时服务器将报告错误信息然后退出。如果要防止使用压缩,应该是:"dont compress = *"。

dont compress

用来指定那些不进行压缩处理再传输的文件,默认值是

*.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz

rsync客户命令
在对rsync服务器配置结束以后,下一步就需要在客户端发出rsync命令来实现将服务器端的文件备份到客户端来。rsync是一个功能非常强大的工具,其命令也有很多功能特色选项,我们下面就对它的选项一一进行分析说明。

首先,rsync的命令格式可以为:

rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST

rsync [OPTION]... [USER@]HOST:SRC DEST

rsync [OPTION]... SRC [SRC]... DEST

rsync [OPTION]... [USER@]HOST::SRC [DEST]

rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST

rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]
rsync有六种不同的工作模式:

拷贝本地文件;当SRC和DES路径信息都不包含有单个冒号":"分隔符时就启动这种工作模式。

使用一个远程shell程序(如rsh、ssh)来实现将本地机器的内容拷贝到远程机器。当DST路径地址包含单个冒号":"分隔符时启动该模式。

使用一个远程shell程序(如rsh、ssh)来实现将远程机器的内容拷贝到本地机器。当SRC地址路径包含单个冒号":"分隔符时启动该模式。

从远程rsync服务器中拷贝文件到本地机。当SRC路径信息包含"::"分隔符时启动该模式。

从本地机器拷贝文件到远程rsync服务器中。当DST路径信息包含"::"分隔符时启动该模式。

列远程机的文件列表。这类似于rsync传输,不过只要在命令中省略掉本地机信息即可。
1、用法

在使用rsync传输文件时,需要指定一个源和一个目的,其中一个可能是远程机器的资源信息。例如:

rsync *.c foo:src/

表示将传输当前目录下所有以.c结尾的文件到机器foo的src目录下。如果任何文件已经存在于远程系统,则会调用远程更新协议来实现仅仅传输那些更新过的文件。

rsync -avz foo:src/bar /data/tmp

该命令则递归地传输机器foo上的src/bar目录下的所有内容到本地/data/tmp/bar目录中。文件以归档模式进行传输,以确保符号链结、属性、权限、属主等信息在传输中都被保存。此外,可以使用压缩技术来加快数据传输:

rsync -avz foo:src/bar/ /data/tmp

路径信息以"/"结尾时表示拷贝该目录,而不以"/"结尾表示拷贝该目录。当配合使用--delete选项时这两种情况的区别将会表现出来。

也可以以本地模式来使用rsync,如果SRC和DST路径中都没有任何":"符号则表示该命令运行在本地模式,等同于cp命令。

rsync somehost.mydomain.com::

这种模式则将会列出somehost.mydomain.com.可以访问的所有模块信息。

选项说明

-v, --verbose 详细模式输出
-q, --quiet 精简输出模式
-c, --checksum 打开校验开关,强制对文件传输进行校验
-a, --archive 归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD
-r, --recursive 对子目录以递归模式处理
-R, --relative 使用相对路径信息

rsync foo/bar/foo.c remote:/tmp/

则在/tmp目录下创建foo.c文件,而如果使用-R参数:

rsync -R foo/bar/foo.c remote:/tmp/

则会创建文件/tmp/foo/bar/foo.c,也就是会保持完全路径信息。

-b, --backup 创建备份,也就是对于目的已经存在有同样的文件名时,将老的文件重新命名为~filename。可以使用--suffix选项来指定不同的备份文件前缀。
--backup-dir 将备份文件(如~filename)存放在在目录下。
-suffix=SUFFIX 定义备份文件前缀
-u, --update 仅仅进行更新,也就是跳过所有已经存在于DST,并且文件时间晚于要备份的文件。(不覆盖更新的文件)
-l, --links 保留软链结
-L, --copy-links 想对待常规文件一样处理软链结
--copy-unsafe-links 仅仅拷贝指向SRC路径目录树以外的链结
--safe-links 忽略指向SRC路径目录树以外的链结
-H, --hard-links 保留硬链结
-p, --perms 保持文件权限
-o, --owner 保持文件属主信息
-g, --group 保持文件属组信息
-D, --devices 保持设备文件信息
-t, --times 保持文件时间信息
-S, --sparse 对稀疏文件进行特殊处理以节省DST的空间
-n, --dry-run现实哪些文件将被传输
-W, --whole-file 拷贝文件,不进行增量检测
-x, --one-file-system 不要跨越文件系统边界
-B, --block-size=SIZE 检验算法使用的块尺寸,默认是700字节
-e, --rsh=COMMAND 指定替代rsh的shell程序
--rsync-path=PATH 指定远程服务器上的rsync命令所在路径信息
-C, --cvs-exclude 使用和CVS一样的方法自动忽略文件,用来排除那些不希望传输的文件
--existing 仅仅更新那些已经存在于DST的文件,而不备份那些新创建的文件
--delete 删除那些DST中SRC没有的文件
--delete-excluded 同样删除接收端那些被该选项指定排除的文件
--delete-after 传输结束以后再删除
--ignore-errors 及时出现IO错误也进行删除
--max-delete=NUM 最多删除NUM个文件
--partial 保留那些因故没有完全传输的文件,以是加快随后的再次传输
--force 强制删除目录,即使不为空
--numeric-ids 不将数字的用户和组ID匹配为用户名和组名
--timeout=TIME IP超时时间,单位为秒
-I, --ignore-times 不跳过那些有同样的时间和长度的文件
--size-only 当决定是否要备份文件时,仅仅察看文件大小而不考虑文件时间
--modify-window=NUM 决定文件是否时间相同时使用的时间戳窗口,默认为0
-T --temp-dir=DIR 在DIR中创建临时文件
--compare-dest=DIR 同样比较DIR中的文件来决定是否需要备份
-P 等同于 --partial
--progress 显示备份过程
-z, --compress 对备份的文件在传输时进行压缩处理
--exclude=PATTERN 指定排除不需要传输的文件模式
--include=PATTERN 指定不排除而需要传输的文件模式
--exclude-from=FILE 排除FILE中指定模式的文件
--include-from=FILE 不排除FILE指定模式匹配的文件
--version 打印版本信息
--address 绑定到特定的地址
--config=FILE 指定其他的配置文件,不使用默认的rsyncd.conf文件
--port=PORT 指定其他的rsync服务端口
--blocking-io 对远程shell使用阻塞IO
-stats 给出某些文件的传输状态
--progress 在传输时现实传输过程
--log-format=FORMAT 指定日志文件格式
--password-file=FILE 从FILE中得到密码
--bwlimit=KBPS 限制I/O带宽,KBytes per second
-h, --help 显示帮助信息
实例分析
这里假设有两台服务器:A和B。其中A是主web服务器,具有域名www.linuxaid.com.cn(202.99.11.120),B服务器是备 份机,其域名为backup.linuxaid.com.cn(202.99.11.121)。其中A的web内容存放在以下几个地方: /www/和 /home/web_user1/和/home/web_user2/。我们需要在备份机B上建立对这几个目录内容的备份。

服务器配置实例

那么在www.linuxaid.com.cn上创建rsyncd的配置文件/etc/rsyncd.conf,内容如下:

uid = nobody
gid = nobody
use chroot = no
max connections = 4
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log

[www]
path = /www/
ignore errors
read only = true
list = false
hosts allow = 202.99.11.121
hosts deny = 0.0.0.0/32
auth users = backup
secrets file = /etc/backserver.pas

[web_user1]
path = /home/web_user1/
ignore errors
read only = true
list = false
hosts allow = 202.99.11.121
hosts deny = 0.0.0.0/32
uid = web_user1
gid = web_user1
auth users = backup
secrets file = /etc/backserver.pas

[web_user2]
path = /home/web_user2/
ignore errors
read only = true
list = false
hosts allow = 202.99.11.121
hosts deny = 0.0.0.0/32
uid = web_user2
gid = web_user2
auth users = backup
secrets file = /etc/backserver.pas

这里定义有四个三个模块,分别对应于三个需要备份的目录树。这里只允许202.99.11.121备份本机的数据,并且需要认证。三个模块授权的备份用户都为backup,并且用户信息保存在文件/etc/backserver.pas中,其内容如下:

backup:bk_passwd

并且该文件只能是root用户可读写的,否则rsyncd启动时会出错。这些文件配置完毕以后,就需要在A服务器上启动rsyncd服务器:

rsync --daemon

客户命令示例

/usr/local/bin/rsync -vzrtopg --delete --exclude "logs/" --exclude "conf/ssl.*/" --progress backup@202.99.11.120::www /backup/www/ --password-file=/etc/rsync.pass

上面这个命令行中-vzrtopg里的v是verbose,z是压缩,r是recursive,topg都是保持文件原有属性如属主、时间的参数。-- progress是指显示出详细的进度情况,--delete是指如果服务器端删除了这一文件,那么客户端也相应把文件删除,保持真正的一致。-- exclude "logs/" 表示不对/www/logs目录下的文件进行备份。--exclude "conf/ssl.*/"表示不对/www/conf/ssl.*/目录下的文件进行备份。

backup@202.99.11.120::www 表示对该命令是对服务器202.99.11.120中的www模块进行备份,backup表示使用backup来对该模块进行备份。

--password-file=/etc/rsync.pass来指定密码文件,这样就可以在脚本中使用而无需交互式地输入验证密码了,这里需要注意的是这份密码文件权限属性要设得只有root可读。

这里将备份的内容存放在备份机的/backup/www/目录下。

[root@linuxaid /]# /usr/local/bin/rsync -vzrtopg --delete --exclude "logs/" --exclude "conf/ssl.*/" --progress backup@202.99.11.120::www /backup/www/ --password-file=/etc/rsync.pass
receiving file list ... done
./
1
785 (100%)
1.py
4086 (100%)
2.py
10680 (100%)
a
0 (100%)
ip
3956 (100%)
./
wrote 2900 bytes read 145499 bytes 576.34 bytes/sec
total size is 2374927 speedup is 45.34

对其它两个模块操作的命令分别为:

/usr/local/bin/rsync -vzrtopg --delete --progress backup@202.99.11.120::web_user1 /backup/web_user1/ --password-file=/etc/rsync.pass

/usr/local/bin/rsync -vzrtopg --delete --progress backup@202.99.11.120::web_user2 /backup/web_user2/ --password-file=/etc/rsync.pass

可以将客户命令通过crontab -e命令来实现自动备份,如crontab -e:

 

一些示例脚本
这里这些脚本都是rsync网站上的例子:

1、每隔七天将数据往中心服务器做增量备份

#!/bin/sh

# This script does personal backups to a rsync backup server. You will end up
# with a 7 day rotating incremental backup. The incrementals will go
# into subdirectories named after the day of the week, and the current
# full backup goes into a directory called "current"
# tridge@linuxcare.com

# directory to backup
BDIR=/home/$USER

# excludes file - this contains a wildcard pattern per line of files to exclude
EXCLUDES=$HOME/cron/excludes

# the name of the backup machine
BSERVER=owl

# your password on the backup server
export RSYNC_PASSWORD=XXXXXX


########################################################################

BACKUPDIR=`date +%A`
OPTS="--force --ignore-errors --delete-excluded --exclude-from=$EXCLUDES
--delete --backup --backup-dir=/$BACKUPDIR -a"

export PATH=$PATH:/bin:/usr/bin:/usr/local/bin

# the following line clears the last weeks incremental directory
[ -d $HOME/emptydir ] || mkdir $HOME/emptydir
rsync --delete -a $HOME/emptydir/ $BSERVER::$USER/$BACKUPDIR/
rmdir $HOME/emptydir

# now the actual transfer
rsync $OPTS $BDIR $BSERVER::$USER/current

2、备份至一个空闲的硬盘

#!/bin/sh

export PATH=/usr/local/bin:/usr/bin:/bin

LIST="rootfs usr data data2"

for d in $LIST; do
mount /backup/$d
rsync -ax --exclude fstab --delete /$d/ /backup/$d/
umount /backup/$d
done

DAY=`date "+%A"`

rsync -a --delete /usr/local/apache /data2/backups/$DAY
rsync -a --delete /data/solid /data2/backups/$DAY

3、对vger.rutgers.edu的cvs树进行镜像

#!/bin/bash

cd /var/www/cvs/vger/
PATH=/usr/local/bin:/usr/freeware/bin:/usr/bin:/bin

RUN=`lps x | grep rsync | grep -v grep | wc -l`
if [ "$RUN" -gt 0 ]; then
echo already running
exit 1
fi

rsync -az vger.rutgers.edu::cvs/CVSROOT/ChangeLog $HOME/ChangeLog

sum1=`sum $HOME/ChangeLog`
sum2=`sum /var/www/cvs/vger/CVSROOT/ChangeLog`

if [ "$sum1" = "$sum2" ]; then
echo nothing to do
exit 0
fi

rsync -az --delete --force vger.rutgers.edu::cvs/ /var/www/cvs/vger/
exit 0

FAQ
Q:如何通过ssh进行rsync,而且无须输入密码?
A:可以通过以下几个步骤

1. 通过ssh-keygen在server A上建立SSH keys,不要指定密码,你会在~/.ssh下看到identity和identity.pub文件
2. 在server B上的home目录建立子目录.ssh
3. 将A的identity.pub拷贝到server B上
4. 将identity.pub加到~[user b]/.ssh/authorized_keys
5. 于是server A上的A用户,可通过下面命令以用户B ssh到server B上了
e.g. ssh -l userB serverB
这样就使server A上的用户A就可以ssh以用户B的身份无需密码登陆到server B上了。

Q:如何通过在不危害安全的情况下通过防火墙使用rsync?
A:解答如下:

这通常有两种情况,一种是服务器在防火墙内,一种是服务器在防火墙外。无论哪种情况,通常还是使用ssh,这时最好新建一个备份用户,并且配置 sshd仅允许这个用户通过RSA认证方式进入。如果服务器在防火墙内,则最好限定客户端的IP地址,拒绝其它所有连接。如果客户机在防火墙内,则可以简 单允许防火墙打开TCP端口22的ssh外发连接就ok了。

Q:我能将更改过或者删除的文件也备份上来吗?
A:当然可以:

你可以使用如:rsync -other -options -backupdir = ./backup-2000-2-13 ...这样的命令来实现。
这样如果源文件:/path/to/some/file.c改变了,那么旧的文件就会被移到./backup-2000-2-13/path/to/some/file.c,
这里这个目录需要自己手工建立起来

Q:我需要在防火墙上开放哪些端口以适应rsync?
A:视情况而定

rsync可以直接通过873端口的tcp连接传文件,也可以通过22端口的ssh来进行文件传递,但你也可以通过下列命令改变它的端口:

rsync --port 8730 otherhost::
或者
rsync -e 'ssh -p 2002' otherhost:

Q:我如何通过rsync只复制目录结构,忽略掉文件呢?
A:rsync -av --include '*/' --exclude '*' source-dir dest-dir

Q:为什么我总会出现"Read-only file system"的错误呢?
A:看看是否忘了设"read only = no"了

Q:为什么我会出现'@ERROR: invalid gid'的错误呢?
A:rsync使用时默认是用uid=nobody;gid=nobody来运行的,如果你的系统不存在nobody组的话,就会出现这样的错误,可以试试gid = nogroup或者其它

Q:绑定端口873失败是怎么回事?
A:如果你不是以root权限运行这一守护进程的话,因为1024端口以下是特权端口,会出现这样的错误。你可以用--port参数来改变。

Q:为什么我认证失败?
A:从你的命令行看来:

你用的是:
>; bash$ rsync -a 144.16.251.213::test test
>; Password:
>; @ERROR: auth failed on module test
>;
>; I dont understand this. Can somebody explain as to how to acomplish this.
>; All suggestions are welcome.

应该是没有以你的用户名登陆导致的问题,试试rsync -a max@144.16.251.213::test test

重要:
可以用–password-file=/password/path/file来指定密码文件,这样就可以在脚本中使用而无需交互式地输入验证密码了,这里需要注意的是这份密码文件权限属性要设得只有属主可读。

#/usr/local/rsync/bin/rsync -vzrtopg –progress –delete rsync_user@192.168.0.2::rsync_module_name1 /tmp/
Password:
或者你也可以制定password文件
由于需要系统crontab执行,所以这里采用读入密码文件的方式,
这个时候就成功了。

#vi /etc/rsyncd.pas
加入
rsync_user:rsyncofpass
注意,客户端的密码文件只需要密码,而不需要用户名!


- 作者: clay111 2007年04月24日, 星期二 17:26  回复(0) |  引用(1) 加入博采

mysql的open file limit(ZT)

原文出处:http://haka.sharera.com/blog/BlogTopic/23115.htm

在某几个月黑风高的晚上某个项目的MYSQL服务器在无数疯狂爬虫的折磨下,无奈的拒绝了他们,报出了这样的错误。

060907  2:45:26 [ERROR] /usr/××××/mysql5/bin/mysqld: Can't open file: './datab/abc.frm' (errno: 24)

一般来说,出现这种错误的MYSQL意味着他再也没有权限打开更多的文件了。意味着超出了运行这个程序的用户

即MYSQL这个用户的最大文件句柄数。可以查看如下

#ulimit -a

一般的LINUX安装缺省是1024个句柄。那么一个MYSQL服务器需要用到多少文件句柄呢?

和文件句柄数相关的MYSQL变量有table_cache, max_connectionsmax_tmp_tables

每个表的打开需要两个文件描述符,一个数据文件一个索引文件。一个表在同一或者多个线程中多次被访问的话那么将多次

被打开。每次打开还将在缓冲中请求一个表目。

假如我们的table_cache=128,max_connections=1000,那么如果每个最大的情况下我们有12万的表缓冲。当然实际情况不

一定那么糟糕,我们还是计算实际情况好一点。

假设有1000个并发链接,每个连接平均打开5个表,那么共需要10个文件描述符。总共需要1万个文件描述符。如果某个操作

过多,那么肯定超出1万个。

解决方案就是修改ULIMIT.

#vi /etc/secrity/limits.conf

增加

*                soft   nofile          100000
*                hard   nofile          200480

LINUX 系统的文件限制是

# cat /proc/sys/fs/file-max
386560

也可以用ulimit -n 来设置一下,不过不能超过上面的软限制100000。

设置好这些后,重起MYSQL。MYSQL的文档里边自己说的系统变量open_files_limit

好像是不能设置的。只能通过命令行的方式来。

- 作者: clay111 2007年04月21日, 星期六 03:41  回复(0) |  引用(1) 加入博采

apache安全模块 mod_security (ZT)

原文出处:

http://www.modsecurity.or/download/index.html

Introducing mod_security

ModSecurity is an Apache module that adds intrusion detection and prevention features to the Web server. In principle it is similar to an IDS you would use to analyse your network traffic, except that it works on the HTTP level and understands it really well. Because of this it allows you to do things that are normal from the HTTP point of view but are difficult to do from an classical IDS. This difference will become clearer later when we examine several examples of what mod_security can do.

In addition to detection, mod_security also supports attack prevention. Because it stands between the client and the server, if it finds that the request contains a malicious payload it can reject the request, performing any of a number of built-in actions.

As it is a module like any other, you can use mod_security as part of any Apache installation. The overhead that comes from additional processing can be negligible when it is configured properly. However, if you take into account that an incident is much more costly and that mod_security can also protect you from attacks the overhead becomes insignificant.

So, how is mod_security helpful? We can't go into exhaustive detail on all the capabilities, but here is a short overview of what is happening on every request (for more details go to the mod_security Website and download the reference manual):

  1. Parse the request. This is mostly straightforward, except when you have to deal with a POST request where getting the body of the request can be difficult.
  2. Perform canonization and anti-evasion actions. A series of transformations is performed to transform the input into a form that is suitable for analysis. This step will fight against various evasive techniques attackers may use: null byte attacks, self-referencing directories, multiple slash characters, using backslash characters on Windows, etc.
  3. Perform special built-in checks. This step contains more complicated validations such URL encoding validation and Unicode encoding validation. You can also choose to allow only certain byte values in the request to fight shellcode.
  4. Execute input rules. This is where your custom rules come into action. They work by allowing you to analyse every aspect of a request using regular expressions. In addition to this, several rules can be combined for more complex analysis.

The request is then allowed to reach the handler where it executes. After the request:

  1. Execute output rules. Output rules are applied to the response body. They are very useful to prevent information leaks.
  2. Log the request. Log the complete request consisting of input and output headers, and the request body. To prevent excessive logging, mod_security can be configured to log only what's relevant, such as requests that have triggered a response from mod_security.

Installation and configuration

Installation is surprisingly simple. We will assume that the server you want to protect is using the private address 192.168.254.10, and that you have configured the public domain name (www.modsecurity.org) to point to the reverse proxy server.

On the reverse proxy you need to install the Apache 2 Web server, making sure you compile in mod_proxy, mod_proxy_http, and mod_security. We will not spend time on this step assuming you are already familiar with it. If not, have a look at the related links section where you will find links to a couple of very good articles covering the Apache installation process. It would also be a good idea to add mod_rewrite to the module mix since it can work in tandem in mod_proxy significantly increasing what you can do.

Although any Web server can become a reverse proxy simply by adding the modules I mentioned above it is not recommended to mix the two roles together. The reverse proxy will be the only server exposed to the public and you will want to minimize the amount of code it contains, to minimize the risk of exploitable vulnerabilities.

Apache 2.x is a better choice for a reverse proxy because it contains the new filtering API, allowing modules to see and interact with the request body as it comes in and with the response as it comes out. This is important for an application gateway since it must check the information that passes through before it reaches the recipient.

Once you have the proxy installed here is how you will configure a virtual host:

<VirtualHost www.modsecurity.org>

# Just the bare minimum of directives
ServerName www.modsecurity.org
DocumentRoot /rproxy/nowhere

# While the following line is not strictly necessary it's here to emphasize
# the fact that the reverse proxy does not use this directive. In fact, turning
# it On without proper access control creates an open proxy!
ProxyRequests Off
ProxyPass / http://192.168.254.10/
ProxyPassReverse / http://192.168.254.10/

# Yes, we want to use mod_security
SecFilterEngine On

# Scan request body
SecFilterScanPOST On

# Scan response body
SecFilterScanOutput On

# Check URL encoding
SecFilterCheckURLEncoding On

# This setting should be set to On only if the Web site is
# using the Unicode encoding. Otherwise it may interfere with
# the normal Web site operation.
SecFilterCheckUnicodeEncoding Off

# Only allow certain byte values to be a part of the request.
# This is pretty relaxed, most applications where only English
# is used will happily work with a range 32 - 126.
SecFilterForceByteRange 1 255

# Audit log logs complete requests. Configured as below it
# will only log invalid requests for further analysis.
SecAuditEngine RelevantOnly
SecAuditLog logs/audit_log
# You may need this later but we don't log anything
# here for now. Excessive debug logging may slow down
# the server.
SecFilterDebugLevel 0 
SecFilterDebugLog logs/modsec_debug_log

# By default, deny requests with status 500
SecFilterDefaultAction "deny,log,status:500"

# Put your mod_security rules here
# ...

</VirtualHost>

Practical examples

In this section I will demonstrate what the typical mod_security rule set looks like. You should always start with rules that have a broad scope, leading to more specific issues. All mod_security rules (and configuration options) can be applied on the per-virtual host or per-directory basis so you can have areas with completely different security configurations.

Detecting common attacks

These rules will target the common Web application attacks:

# Command execution attacks
SecFilter /etc/password
SecFilter /bin/ls
# Directory traversal attacks
SecFilter "\.\./"
# XSS attacks
SecFilter "<(.|\n)+>"
SecFilter "<[[:space:]]*script"

# SQL injection attacks
SecFilter "delete[[:space:]]+from"
SecFilter "insert[[:space:]]+into"
SecFilter "select.+from"

# MS SQL specific SQL injection attacks
SecFilter xp_enumdsn
SecFilter xp_filelist
SecFilter xp_availablemedia
SecFilter xp_cmdshell
SecFilter xp_regread
SecFilter xp_regwrite
SecFilter xp_regdeletekey

Protecting a vulnerable script

Some PHP applications are vulnerable when a register_globals configuration option is turned on, allowing attackers to set an internal variable to a value of their choice. This usually leads to attacker executing some code on the server. Here is an example from the real world (Cafelog b2, http://www.securityfocus.com/bid/7786):

SecFilterSelective ARG_b2inc "!^$"

Protecting from XSS attacks through the PHP session cookie

PHP versions prior to 4.3.2 are vulnerable to XSS attacks carried out through the session identifier (http://www.securityfocus.com/bid/7761). If you can't upgrade your PHP version to the latest version you can still protect yourself:

SecFilterSelective ARG_PHPSESSID "!^[0-9a-z]*$"
SecFilterSelective COOKIE_PHPSESSID "!^[0-9a-z]*$"

Stop FormMail from being used to send spam

Some versions of FormMail can be used to send email to arbitrary email addresses. The following rule demonstrates how you can have a filter applied only to certain locations, in this case just the FormMail script. The request will be rejected if the email is intended to any address except the one ending in "@modsecurity.org":

<Location /cgi-bin/FormMail>
    SecFilterSelective "ARG_recipient" "!@modsecurity\.org$"
</Location>

Restrict administrative login to an IP address

Here is a nice one. I have this application where the administrator logs in through the same log in panel as other users, but I still wanted to restrict administration login to certain IP addresses. So I used two chained rules. The second rule will apply only if the first rule matches; in this case - if the incoming username is "admin".

SecFilterSelective ARG_username admin chain
SecFilterSelective REMOTE_ADDR "!^ADMIN_IP_ADDRESS_HERE$"

Preventing information leak

In all versions of PHP, if a fatal error occurs the script will be terminated immediately (standard error handling routine will not be invoked). Information leak through these problems can be prevented by scanning the output and preventing it from reaching the user if it contains error messages.

SecFilterSelective OUTPUT "Fatal error:"

Detecting intrusions

Output filtering can also be used to detect successful intrusions. These rules will monitor output and detect typical keywords resulting from a command execution on the server.

SecFilterSelective OUTPUT "Volume Serial Number"

SecFilterSelective OUTPUT "Command completed"

SecFilterSelective OUTPUT "Bad command or filename"

SecFilterSelective OUTPUT "file(s) copied"

SecFilterSelective OUTPUT "Index of /cgi-bin/"
 
SecFilterSelective OUTPUT ".*uid\=\("

Other

What other rules you may find useful depends on the types of applications and Web servers you have behind the reverse proxy. On the mod_security Website you can find a large number of rules automatically converted from Snort rules. Download the list and simply remove the rules that do not apply.

Conclusion

This article has just scratched the surface of a complex issue. I suggest that you browse through the related links section, as it contains a list of Websites, tools, and papers that you can use to familiarize yourself with other aspects we did not cover here, such as reverse proxy load balancing and clustering or transparent reverse proxy configuration. Going the other way, download the mod_security reference manual and get to know its features. It also contains other features not mentioned here. Finally, contact me to request new mod_security features if you have a need that is not covered by what already exists.


Relevant Links

Apache Software Foundation, "Apache Web server"

Apache Software Foundation, "Apache module mod_proxy"

Ivan Ristic, "Apache Module mod_security"

Apache Software Foundation, "Apache module mod_rewrite"

Artur Maj, "Securing Apache: Step-by-Step"

Lynda L. Morrison, "Perimeter Defense-in-Depth: Using Reverse Proxies and other tools to protect our internal assets" (PDF)

Peter Sommerlad, "Reverse Proxy Patterns"



SecurityFocus accepts Infocus article submissions from members of the security community. Articles are published based on outstanding merit and level of technical detail. Full submission guidelines can be found at http://www.securityfocus.com/static/submissions.html.

- 作者: clay111 2007年04月20日, 星期五 13:27  回复(0) |  引用(1) 加入博采

MySQL 自带的 slow log 分析工具 mysqldumpslow(ZT)
徐永久 发表于 2004年12月09日 23:13。
摘自:http://www.freelamp.com/1102605188/index_html
MySQL 自带 slow log 的分析工具 mysqldumpslow ,但是没有说明。本文通过分析该脚本,介绍了其用法。
slow log 是 MySQL 根据 SQL 语句的执行时间设定,写入的一个文件,用于分析执行较慢的语句。

只要在 my.cnf 文件中配置好:
log-slow-queries = [slow_query_log_filename]
即可记录超过默认的 10s 执行时间的 SQL 语句。
如果要修改默认设置,可以添加:
long_query_time = 5
设定为 5s 。

如果要记录所有 SQL 语句,可以写入:
log-long-format



# t=time, l=lock time, r=rows
# at, al, 以及 ar 是对应的平均值

mysqldumpslow 可以接受的参数有:
'v+', # verbose
'd+', # debug
's=s', # 排序 (t, at, l, al, r, ar etc)
'r!', # 倒排序 (largest last instead of first)
't=i', # 显示最高的 n 个查询
'a!', # 不把所有的数字以 N ,字符串以 'S' 显示
'n=i', # abstract numbers with at least n digits within names
'g=s', # grep: only consider stmts that include this string
'h=s', # hostname of db server for *-slow.log filename (can be wildcard)
'i=s', # name of server instance (if using mysql.server startup script)
'l!', # don't subtract lock time from total time

- 作者: clay111 2007年04月12日, 星期四 01:22  回复(0) |  引用(1) 加入博采

Adodb 官方介绍
我们不要放弃

当你需要确保你程序的可移植性的时候,一个叫做 ADODB 的数据库封包链接库已经出现了。它提供了共通的应用程序接口来跟所有支持的数据库沟通,因此你无须放弃!

ADODB是Active Data Object DataBase的缩写(很抱歉!玩计算机的有时候不是很有原创性)。ADODB目前支持MySQL、PostgreSQL、Oracle、Interbase、Microsoft SQL Server、Access、FoxPro、Sybase、ODBC及ADO,你可以从 http://php.weblogs.com/adodb下载 ADODB。

MySQL的例子
PHP中最通用的数据库是MySQL,所以我想你会喜欢下面的程序代码,它连结到 localhost 的 MySQL 服务器,数据库名称是 mydab,并且执行一个 SQL 的 select 指令查询,查询结果会一列列地印出来。

$db = mysql_connect("localhost", "root", "password");
mysql_select_db("mydb",$db);

$result = mysql_query("SELECT * FROM employees",$db);
if ($result === false) die("failed");

while ($fields = mysql_fetch_row($result)) {
 for ($i=0, $max=sizeof($fields); $i < $max; $i++) {
        print $fields[$i].' ';
 }
 print "<br>n";
}

上列的程序代码用颜色标出分段,第一段是连结的部分,第二段是执行SQL指令,最后一段则是显示字段,while循环扫描结果的每一列,而for循环扫描到每列的字段。

接下来是以ADODB的程序代码得到同样的结果:

 include("adodb.inc.php");
 $db = NewADOConnection('mysql');
 $db->Connect("localhost", "root", "password", "mydb");

 $result = $db->Execute("SELECT * FROM employees");
 if ($result === false) die("failed");
 
 while (!$result->EOF) {
    for ($i=0, $max=$result->FieldCount(); $i < $max; $i++)
           print $result->fields[$i].' ';
    $result->MoveNext();
    print "<br>n";
 }

现在改成指向Oracle数据库,程序代码只要修改第二行成为 NewADOConnection('oracle'),让我们看一下完整的程序代码...

与数据库连结

include("adodb.inc.php");
$db = NewADOConnection('mysql');
$db->Connect("localhost", "root", "password", "mydb");

连结的程序代码比起原来MySQL的程序代码有老练一些,因为我们正是需要更老练些。在ADODB我们使用对象导向的方法来管理多样数据库的复杂性,我们用不同类(class)来控制不同数据库。假如你不熟悉对象导向程序设计,别担心!所有的复杂事情都隐藏在 NewADOConnection() 函数之后。

为了节省内存,我们只加载与你所连结数据库相关的PHP程序代码,我们通过调用NewADOConnection(databasedriver)来完成这件事,合法的数据库驱动程序包含 mysql,mssql,oracle,oci8,postgres,sybase,vfp,access,ibase 以及许多其它的驱动程序。

接着我们通过调用 NewADOConnection() 来从连结类别产生一个新的对象实体,最后我们使用 $db->Connect() 来连结数据库。

执行SQL指令

$result = $db->Execute("SELECT * FROM employees");
if ($result === false) die("failed");

直接传送SQL指令到服务器,当成功执行之后,Execute()将传回一个recordset对象,你可以如同上面所列来检查$result。

一个初学者容易混淆的议题是,在ADODB有两种类型的对象,连结对象以及recordset对象,我们何时用这些对象呢?

连结对象($db)是负责连结数据库,格式化你的SQL查询。而recordset对象($result)则是负责撷取结果并将响应数据规格化成文字或数组。

唯一我需要增加的事情是,ADODB提供许多有用的函数来让INSERT及UPDATE指令更容易些,这点我们在进阶的章节会提到。

撷取资料

while (!$result->EOF) {
   for ($i=0, $max=$result->FieldCount(); $i < $max; $i++)
       print $result->fields[$i].' ';
   $result->MoveNext();
   print "<br>n";
}

前面取得数据的范例很像从档案读数据,在每一行我们首先检查是否到了档案的结尾(EOF),若还没到结尾,循环扫过每列中的字段,然后移到下一行(MoveNext)接着重复同样的事情。

$result->fields[]数组是由PHP数据库延伸系统所产生的,有些数据库延伸系统并不会以字段名称建立该数组的索引,要强迫以名称排序索引该数组,使用$ADODB_FETCH_MODE的通用变量。

        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
        $rs1 = $db->Execute('select * from table');
        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
        $rs2 = $db->Execute('select * from table');
        print_r($rs1->fields); // shows array([0]=>'v0',[1] =>'v1')
        print_r($rs2->fields); // shows array(['col1']=>'v0',['col2'] =>'v1')

如同你所见的上面例子,两个recordset储存并使用不同的取用模式,当recordset由Execute()产生后再设定$ADODB_FETCH_MODE。

ADOConnection

连结到数据库的对象,执行SQL指令并且有一组工具函数来标准格式化SQL指令,比如关联与日期格式等指令。

其它有用的函数

$recordset->Move($pos)卷动目前的数据列,ADODB支持整个数据库往前卷动,有一些数据库并不支持往后的卷动,这倒不会是个问题,因为你能够用暂存纪录到快取来仿真往后卷动。

$recordset->RecordCount()传回SQL指令存取到的纪录笔数,有些数据库会因为不支持而传回-1。

$recordset->GetArray()以数组的方式传回结果。

rs2html($recordset)函数将传进的recordset转为HTML的表格格式。下例中以粗体字显示相关用法:

include('adodb.inc.php');
include('tohtml.inc.php'); /* includes the rs2html function */
$conn = &ADONewConnection('mysql');
$conn->PConnect('localhost','userid','password','database');
$rs = $conn->Execute('select * from table');
rs2html($rs); /* recordset to html table */

还有许多其它有用的函数列示在文件之中,可从下列网址查得 http://php.weblogs.com/adodb_manual

进阶题材

新增及更新

假设你要新增下列数据到数据库中。

ID = 3
TheDate=mktime(0,0,0,8,31,2001) /* 31st August 2001 */
Note= sugar why don't we call it off

当你改用别的数据库,可能就没办法新增数据。

第一个问题是,每一个数据库各自有不同的内定日期格式,MySQL使用 YYYY-MM-DD 格式,而其它数据库则有不同的内定格式,ADODB提供DBDate()函数来转换不同数据库之间的日期内定格式。

次一个问题是单引号(don't)的表示法,在MySQL可以直接使用单引号(don't),但在其它数据库如Sybase、Access、 Microsoft SQL Server,则用两个单引号表示(don''t),qstr()函数可以解决此问题。

我们如何使用这些函数?就像这样:

$sql = "INSERT INTO table (id, thedate,note) values ("
   . $ID . ','
   . $db->DBDate($TheDate) .','
   . $db->qstr($Note).")";
$db->Execute($sql);

ADODB还有$connection->Affected_Rows()函数,传回受最后update或delete指令影响的数据列数,及$recordset->Insert_ID()函数,传回最后因insert指令而自动产生的数据列编号,预先提醒大家,没有任何数据库有提供这两个函数。

MetaTypes

你可以得到关于字段的更多信息,透过recordset的方法FetchField($fieldoffset)传回对象的3个属性:name,type,max_length。

举例说明:

$recordset = $conn->Execute("select adate from table");
$f0 = $recordset->FetchField(0);

结果$f0->name的内容是'adata',$f0->type将是'date',假如max_length不知道,其内容将会是-1。

处理不同数据库的一个问题是,每一个数据库对于相同的数据型态会有不同的称呼,比如timestamp型态在某数据库中称为datetime,而另一个数据库则称为time,所以ADODB提供MetaType($type,$max_length)函数来标准化下列的数据型态:

C: character and varchar types
X: text or long character (eg. more than 255 bytes wide).
B: blob or binary image
D: date
T: timestamp
L: logical (boolean)
I: integer
N: numeric (float, double, money)

在前面的例子中,

$recordset = $conn->Execute("select adate from table");
$f0 = $recordset->FetchField(0);
$type = $recordset->MetaType($f0->type, $f0->max_length);
print $type; /* should print 'D' */

Select指令的Limit及Top支持

ADODB有个$connection->SelectLimit($sql,$nrows,$offset)函数让你撷取recordset的部分集合,这是采用Microsoft产品中的SELECT TOP用法,及PostgreSQL与MySQL中的SELECT...LIMIT用法的优点,即使原来的数据库并没有提供此用法,本函数也仿真提供该使用方式。

快取支援

ADODB允许你在你的档案系统中暂存recordset的数据,并且在$connection->CacheExecute($secs2cache,$sql)及 $connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset)等设定的时间间隔到达之后,才真正去做数据库的查询以节省时间。

PHP4 Session支持

ADODB也支持PHP4 session handler,你可以存放你的session变量在数据库中,相关功能请参考 http://php.weblogs.com/adodb-sessions

鼓励商业使用

假如你计划写商用的PHP应用软件来销售,你也可以使用ADODB,我们依据GPL来出版ADODB,也就是说你可以合法地在商用应用软件中引用,并保有你程序代码的所有权。强烈地鼓励ADODB的商业应用,我们自己内部也正以这个理由如此使用中。

结论

为了感谢你看完这篇文章,下面就是 let's call the whole thing off 的完整歌词。

Refrain
 
You say eether and I say eyether,
You say neether and I say nyther;
Eether, eyether, neether, nyther -
Let's call the whole thing off !

You like potato and I like po-tah-to,
You like tomato and I like to-mah-to;
Potato, po-tah-to, tomato, to-mah-to -
Let's call the whole thing off !
 
But oh, if we call the whole thing off, then we must part.
And oh, if we ever part, then that might break my heart.
 
So, if you like pajamas and I like pa-jah-mas,
I'll wear pajamas and give up pa-jah-mas.
For we know we
Need each other, so we
Better call the calling off off.
Let's call the whole thing off !
 
Second Refrain
 
You say laughter and I say lawfter,
You say after and I say awfter;
Laughter, lawfter, after, awfter -
Let's call the whole thing off !

You like vanilla and I like vanella,
You, sa's'parilla and I sa's'parella;
Vanilla, vanella, choc'late, strawb'ry -
Let's call the whole thing off !
 
But oh, if we call the whole thing off, then we must part.
And oh, if we ever part, then that might break my heart.
 
So, if you go for oysters and I go for ersters,
I'll order oysters and cancel the ersters.
For we know we
Need each other, so we
Better call the calling off off.
Let's call the whole thing off ! 

Song and lyrics by George and Ira Gershwin, introduced by Fred Astaire and Ginger Rogers in the film "Shall We Dance?"

- 作者: clay111 2007年04月11日, 星期三 12:56  回复(0) |  引用(1) 加入博采

freebsd 的 mysqld got signal 10 错误

freebsd: v6.0

mysql: v5.0.18

错误提示:

Version: '5.0.18-log'  socket: '/tmp/mysql.sock'  port: 3306  FreeBSD port: mysql-server-5.0.18_1
mysqld got signal 10;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help diagnose
the problem, but since we have already crashed, something is definitely wrong
and this may fail.

key_buffer_size=16384
read_buffer_size=126976
max_used_connections=64
max_connections=1024
threads_connected=17
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_connections = 192520 K
bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

解决方法:

1、增加系统内核可用内存

vi /boot/loader.conf

增加如下内容:

kern.maxdsiz="1773741824"
kern.dfldsiz="1773741824"
kern.maxssiz="134217728"

我的系统为2G内存,mysql 可以用到大概1.5G左右。

2、替换lib

vi /etc/libmap.conf

增加如下内容

[mysqld]
libpthread.so.2 libthr.so.2
libpthread.so libthr.so

确保以上动态库在系统中都存在

- 作者: clay111 2007年04月10日, 星期二 10:42  回复(0) |  引用(1) 加入博采

利用Snooper下载流媒体和mp3

这时我们打开 Project URL Snooper ,要注意的是如果你是第一次运行这个软件的话请先到 [General Options] 选单那里选择驱动模块(请务必确认你已经正确的安装了 WINPCAP 这个数据嗅探驱动软件)如下图:



选择完毕后(不管是拨号上网或者是 ADSL 上网,只要你正确安装了 WINPCAP ,那么都能出现和上图基本相似的选项,ADSL 拨号的话驱动那里选那个由相应拨号软件建立的选项,简单电说一般就是拨号软件的名字啦。) 回到 [Search] 选单,按下 [Sniff Network] 按钮启动嗅探,然后返回浏览器窗口在地址栏输入 rtsp://140.247.24.29:554/chem17/Lecture04/4-01.smil?cloakport=8080,554,7070 。很快 RealPlayer 自动运行并经过一番连接后开始播放节目。这个时候 Project URL Snooper 正在后台监视着数据包的一举一动,从它的结果窗口我们可以明显的看见,我们想要的东西出现了。如下图:



如箭头所指,Project URL Snooper 已经从杂乱的数据包里面帮我们把真实的地址找出来了,在这个地址上按鼠标右键可以把这个地址复制到剪帖版或者直接调用 StreamBox vcr 进行下载,如下图:



如果你想调用另外的外部程序来对这个连接地址处理可以在 [ External Links] 选单里面选择,如下图:



得到真实地址后再调用 StreamBox vcr 就可以正常下载流节目了

 

- 作者: clay111 2007年03月14日, 星期三 11:56  回复(0) |  引用(1) 加入博采

关于java.lang.OutofMemory Exception 的错误!(ZT)
Supersizing Java: Large Pages on the Opteron Processor, Part 2
Learn how to use large memory pages under 32-bit and 64-bit Windows and Linux, and configure three advanced Java Virtual Machines to take advantage of them. 

原文出自:http://www.devx.com/amd/article/30785

Applications need memory. The processor provides access to memory through memory pages; applications request memory using virtual addresses, and the processor translates that to physical addresses on-the-fly. The mapping between the physical and virtual addresses is maintained in the page table; speeding access to that large table is a cache, called the Translation Lookaside Buffer.

By default, the pages are small, only 4KB in size; on AMD's Opteron and Athlon 64 processors, the TLB caches the translations to 512 of these 4K pages. Thus, the TLB can only provide high-speed access to the mappings for a tiny fraction of the memory used in a modern server or workstation.

However, as we explained in Part 1, you can configure AMD64-based systems to use large memory pages, which are 2MB in size, and thereby provide a more efficient TLB caching system and, in many cases, faster application performance. In Part 2, we'll talk about how to use those large memory pages under 32-bit and 64-bit Windows and Linux, and configure three advanced Java Virtual Machines to take advantage of them.

Setting Up Linux and Windows
Before we get started, note that configuring a JVM for large pages will require the operating system to reserve, or pin, large blocks of continuous memory. In other words, for each 2MB large page you request, Linux or Windows must find 2MB of contiguous memory, which is then pinned so that it will not be paged out.

Therefore, it's best to set up the JVM when your PC or server has just been rebooted; that way, big blocks of contiguous memory are available to be reserved. If you wait until the machine has been running for some time, memory will become fragmented, and the operating system may not be able to find as many 2MB contiguous blocks are you require—thereby giving your JVM less memory, and somewhat reducing the effectiveness of the techniques.

The procedures for setting up Linux and Windows are quite different.

Linux: To set Linux for large pages, there are two steps: first, make sure your kernel supports large pages, and then, allocate those pages. log in as root.

To check to make sure that your kernel support large pages, go to the shell and issue the command:

cat /proc/meminfo

If the output has lines that say "HugePage_Total," "HugePages_Free" and "Hugepagesize," then you're in business. Also, the /proc/filesystems should show a file system of type "hugetlbfs," which means "huge translation lookaside buffer file system." (Remember, Linux uses the word "huge" instead of "large.")

Once you've determined that your system supports large pages, you'll have to allocate them. Think about how much memory your JVM will need, because once you've allocated those pages, they're not available for any other purpose until you reboot, unless you deallocate them using:

echo 0 > /proc/sys/vm/nr_hugepages

Remember, each page is 2MB in size, so if your application will require 2GB of memory, you will need to allocate 1000 large pages. From the shell, issue the command:

Figure 1.
echo 1000 > /proc/sys/vm/nr_hugepages

Now, you may not get all those pages. To see how many large pages were actually allocated, use:

cat /proc/sys/vm/nr_hugepages

Windows: What about Windows XP or Windows Server 2003? The process is, as you'd expect, entirely different. The first step is to authorize a specific user to be able to lock pages in memory. This is a one-time configuration change.

Make sure you're logged in with administrative privileges, and run Start > Control Pages > Administrative Tools > Local Security Policy > Local Policies > User Rights Assignment, and then select Lock pages in memory (see Figure 1).

From that page, click on "Add User or Group" (see Figure 2), and put in your appropriate authorized user or admin account (see Figure 3). Then close all this out and logout/login or reboot to free up memory. Now, applications running as this user can access large pages merely by reserving the number of pages that they need.

Wasn't that easy? Remember, this is different than with Linux, where you'll need to reallocate those pages each time you reboot. With Windows, this is a one-time change

Note that on Windows, you can't reserve pages the way you can with Linux. So, for this reason, the best policy is to start your JVM as soon as you can after rebooting.

Figure 2.

Setting Up Java Virtual Machines
To the best of my knowledge, the only JVMs that currently support large pages under Linux or Windows are from BEA, IBM, and Sun. If you know of others—please let me know! Here are the directions for setting them up.

Before we dive in, here's an important note: a JVM can't mix large pages and small pages. Even if you provide the appropriate "large page" option, if the JVM can't allocate the whole thing using large 2MB pages, it will revert to using small 4KB pages. Thus, you should explicitly allocate the maximum heap size using the -Xmx option—and make sure it's a multiple of 2MB—rather than leave it unbounded.

(The -Xmx flag specifies the maximum heap size. The flag -Xms sets the minimum. If you want to lock in a specific heap size, you can set -Xms and -Xmx to be the same size. So, for example, for the 2GB heap size used above, the command would be -Xmx2G on the JVM command line.)

BEA JRockit: You set up the BEA Java Virtual Machine by using the switch --XXlargepages. You can learn more about this in BEA's documentation.

If you're running Windows, this is the only step you have to do (assuming that you made the "Lock pages in memory" policy change earlier). If you're running Linux, your root account will also need to create a mount point for mapping the large pages, and assign permissions to that mount point. This is also a one-time change:

mkdir /mnt/hugepages
mount -t hugetblfs nodev /mnt/hugepages
chmod 777 /mnt/hugepage
Figure 3.

IBM's SDK and JRE: The IBM solution for Linux has a different mechanism for doing large pages: the -Xlp switch. Before you start the JVM, however, you'll need to log in as root and change the SHMMAX value; that value defines the maximum size (in bytes) for a shared memory segment. You should set it to be the number of bytes (less one) you'll want in your shared memory. Using our example earlier, we wanted 1000 2MB shared pages to provide 2GB of memory. The size for the SHHMAX should thus be:

2 x 1024 x 1024 x 1024 - 1 
2,147,483,648 - 1
2,147,483,647

To set that value:

echo 2147483647 > /proc/sys/kernel/shmmax

Before you run the process to allocate pages described earlier:

echo 1000 > /proc/sys/vm/nr_hugepages

Then use the -Xlp switch to launch the JVM.

If you're using the IBM SDK and JRE for Windows using Eclipse, just use the -Xlp parameter on JVM startup.

Sun's HotSpot JRE for Linux and Windows: The process for using the Sun JVM is similar to the IBM one, except that you use the flag XX:+UseLargePages. Use this flag for both Linux and Windows.

With Linux, as with the IBM process above, you'll need to set the SHMMAX capacity. Follow the procedure describe above.

YMMV
When it comes to any performing tuning technique, it's important to test to see that the results pay off for your specific application, usage patterns, hardware, operating system, etc. Thus, you should benchmark your own critical applications using both large and small pages—as well as, possibly, different amounts of allocated space under Linux.

However, it doesn't take a full enterprise app to begin experimenting with the technique. To that end, Listing 1 contains a sample app, LinkedListTest, that runs through a large linked list three times, and then prints out the elapsed time for the operation. Each element in the linked list spans 4K of memory. Because the linked lists span a lot of memory, the code exercises the translation lookahead buffer.

To compile the code, use BEA's JRocket 5.0 or later, IBM's JRE 1.4.2 or later, or Sun's 5.0 Update 5 or later. Be sure the jdk bin directory is in your path, since you'll need javac and java. Compile with javac -source 1.4 linklisttest.java. You can then use different command-line arguments to launch JVMs.

Figure 4.

For this test, we'll take advantage of the fact that the test application looks at the heap size and uses three-quarters of it to create the linked-list elements. To see the benefit of large pages, let's use a heap of 64MB.

To run the application with small pages, start the JVM and launch the application with:

java -Xms64m -Xmx64m linklisttest

Now, run it again using large pages. Here's the startup code for our three JVMs:

BEA  java -Xms64m -Xmx64m -XXLargePages linklisttest
IBM:  java -Xms64m -Xmx64m -Xlp linklisttest
Sun:  java -Xms64m -Xmx64m -XX:+UseLargePages linklisttest

Try running the code with small and large pages, and with different heap sizes. The results should be strikingly different! (If you get the exact same results, or close enough, then something didn't configure properly; the application may still be using small pages, even if you want otherwise. In that case, please consult the JVM maker's support section or documentation; unfortunately, I don't have the bandwidth or resources to help troubleshoot.)

Let's conclude with an exercise for the reader: When you're running the tests, either with the sample program or with your own applications, use AMD's CodeAnalyst performance analyzer to watch for specific processor events. The event to watch for would be 0x46, "L1 and L2 DTLB Miss" (see Figure 4). This event fires whenever the processor requests a page that's not cached in the TLB. The fewer of those cache misses, the better!



Page 1 of 1
A former mainframe software developer and systems analyst, Alan Zeichick is principal analyst at Camden Associates, an independent technology research firm focusing on networking, storage, and software development. Read his blog at http://ztrek.blogspot.com.

- 作者: clay111 2007年03月12日, 星期一 17:07  回复(0) |  引用(1) 加入博采

windows 的awstats安装

日志文件分析工具—AWStats在IIS中的配置步骤

AWStats是sourceforge.net上很有名的Web/Mail/FTP服务器日志文件分析工具。
安装配置步骤(适用于分析IIS日志文件)
1、下载AWStats, 下载地址:http://sourceforge.net/projects/awstats/
2、由于AWStats是Pertl写的,所以要下载Perl 解释器, 下载地址: http://activestate.com/Products/ActivePerl/
3、安装Perl 解释器ActivePerl
4、安装AWStats(这里假设安装在C:\Program Files), 出现命令提示时,第一次输入none, 第二次输入你的主机的域名
5、配置IIS日志
      5.1 活动日志格式选用默认的“W3C扩充扩展日志文件格式”
      5.2 点击“属性”,再选择“扩展属性”,选中下列项目:
     date
     time
     c-ip
     cs-username
     cs-method
     cs-uri-stem
     cs-uri-query
     sc-status
     sc-bytes
     cs-version
     cs(User-Agent)
     cs(Referer)
     其他都不要选中。
6、建立虚拟目录cgi-bin,映射到C:\Program Files\AWStats\wwwroot\cgi-bin。
      建立虚拟目录ico, 映射到C:\Program Files\AWStats\wwwroot\icon
7、修改C:\Program Files\AWStats\wwwroot\cgi-bin中的相应的配置文件:awstats.myvirtualhostname.conf(myvirtualhostname为你第4步中输入的域名, 比如www.cnblogs.com)。修改下列项目:

LogFile="C:\WINDOWS\System32\LogFiles\W3SVC1\ex%YY-0%MM-0%DD-0.log" 
LogFormat
="date time c-ip cs-username cs-method cs-uri-stem cs-uri-query sc-status sc-bytes cs-version cs(User-Agent) cs(Referer)" 
AllowToUpdateStatsFromBrowser
=1 
LoadPlugin
="timezone +8" 

8、重启IIS, 删除C:\WINDOWS\System32\LogFiles\W3SVC1下的所有日志文件
9、使配置生效: awstats.pl -config=myvirtualhostname -update
10、配置完成,通过Web访问日志http://www.myserver.mydomain/cgi-bin/awstats.pl?config=myvirtualhostname,点击“立即更新”。
页面截图:

11、通过任务计划自动更新:
       创建批处理文件AwstatsUpate.bat,内容为 :

c:
cd C:\Program Files\AWStats\wwwroot\cgi
-bin
awstats.pl 
-config=www.cnblogs.com -update

    
     在任务计划调度运行该批处理文件。
   
更详细的步骤,请查看帮助文件C:\Program Files\AWStats\docs\awstats_setup.html
参考文章:
    1、http://briandesmond.com/blog/archive/2003/09/08/176.aspx
    2、http://www.cnblogs.com/Files/dudu/InstallingAWStatsOnIIS6.rar(pdf文件)

- 作者: clay111 2007年03月2日, 星期五 11:45  回复(0) |  引用(1) 加入博采

关于不能往yahoo,sina等地址发邮件的问题(ZT)
转自:http://www.5dmail.cn/bbs/viewthread.php?tid=8907&extra=page%3D1&page=1

该问题是由于反垃圾邮件软件引起的,已经和sina 确认过,他们最近部署了一套反垃圾邮件的系统在默认条件下,邮件服务器在发出helo命令与远端的邮件服务器通过25端口建立会话时还会送出自己的FQDN名字。目前流行的一些反垃圾邮件软件可能会通过邮件服务器送出的FQDN名字对其进行反向解析,对于反向解析失败的连接将断开该连接。

反向解析失败的原因如下:

在国内,很多管理员在做域名解析时没严格按要求做,认为通了就行。建议的做法是:对域名abc.com要做这些解析(根据需要增减)
1、主机A记录abc.com
2、主机A记录mail.abc.com
3、主机A记录www.abc.com
4、主机A记录ftp.abc.com
5、abc.com 到 mail.abc.com的MX记录
6、反向解析记录
  很多人在做邮件服务器时会忘掉做MX记录和反向解析记录,abc.com和mail.abc.com不是同一台主机的话,忘了MX记录会出很多这样那样的问题,过后在解决故障的过程中把它加上。但愿意做反向解析的管理员是少之又少,在国外,很多UNIX主机会检查你发邮件时使用的域名,如果反向解析不通,你的邮件就会被“咔嚓”。
  那么我们做了这些解析是不是发邮件给新浪、网易、搜狐、163.net和263就没问题了?当然不是!!!!
  用新浪来说吧,新浪的邮件是两套系统:收费和免费,两套系统的MX地址也不一样。免费的后缀为@sina.com,收费的为@vip.sina.com。免费邮件系统除了在邮箱容量上的限制,还会在邮件数目做做出限制:即在一段时间范围内,如果从同一IP发到新浪免费邮箱的邮件数量超过了一定的数目限制,该IP地址将会被免费邮件系统封锁,封锁时间内就无法发送邮件到新浪免费邮件系统。
  大概过15-20分钟之后,如果该IP地址没有再往它那发送邮件,该IP地址将会自动从IP地址列表中删除。另:这个问题是在8月初总结的,现在新浪的收费邮件系统有没有这个规则没问过新浪。
  如果你的IP在规定的时间内没有解除封锁,那就边哭边给新浪的管理员打电话吧,给他说:大哥,我求你了,你就当我是个屁,把我放了吧……
  这个规则不仅新浪有,搜狐、163、263等都有。这是一个防止垃圾邮件的好方法,但也造成邮件列表无法正常发送。用以上邮箱收不到很多服务商的邮件列表就是这个原因。
  这个规则是管理员在服务器上做的设置,普通用户暂时别想。使用IMail的管理员可以让你的老板花银子买Declude插件来实现这个功能。


尝试以下排错方法:
1. Ping 邮件服务器的FQDN名字,并确认是否可以解析出所对
应的IP地址。
如果不能,在Internet DNS服务器上是否有邮件服务器的
A记录

2.通过NSlookup查询是否为所有能够向外直接发送邮件的
邮件服务器添加了MX记录



一.发到 sina.com 的邮件会被退回

我发到 sina 的邮件会被退回,并提示"remote server said: 553 Spam Mail http://mail.sina.com.cn/FAQ.html";错误,怎么办?

访问http://mail.sina.com.cn/FAQ.html我们可以得知,sina进行了helo域验证。请注意设置邮件系统中的HELO域,如果按照上述操作后,还是无法发往新浪的邮箱,则有以下几种可能:
1) MX指向可能有误,请仔细检查MX指向是否正确
2) 您的服务器IP地址可能被新浪屏蔽了,您需要与新浪客服联系,新浪客服联系邮件:antispam@staff.sina.com.cn 新浪客服联系电话:010-82624488-5602,与对方联系时,请提供您的服务器信息:主机IP/域名/退信内容/发信地址/收信地址/发送时间,以便及时解决您的问题。同时务必留下对方的工号,这样方便督促解决问题。

http://mail.sina.com.cn/FAQ.html#q3
1.为什么新浪服务器会产生553的退信信息?
这是由于邮件发送方服务器的HELO域设置不规范造成的。如果新浪服务器无法对该域进行正确的DNS解析, 将会导致新浪反垃圾系统认为该服务器是垃圾邮件发送者从而拒收. 不规范的HELO域的示例如下:

HELO office
HELO mailserver
HELO localhost.localdomain

解决方法: 参考本文档后半部分提供的设置方法,正确设置贵方SMTP服务器的HELO域, 使新浪能过对该域名进行正确的DNS解析

2.SMTP服务器能否设置为公司内网的域名?
请设置贵公司的服务器对外发送的HELO域为正确的贵公司域名,否则将因为和第一条同样的原因造成新浪拒收。


3.SMTP服务器的HELO域已设置正确,怎么还产生553的退信信息?
这是由于发邮件服务器在内网的某个网段中。如果邮件经防火墙发送, 而防火墙没有对邮件的源IP地址进行映射, 新浪的服务器就会认为防火墙的IP是发件方SMTP服务器的IP地址,而邮件源IP地址与HELO域名MX解析不一致. 这种情况也会使新浪拒收邮件。解决方法: 使HELO后面的域名MX解析为防火墙的IP地址, 或者使防火墙把经过它的邮件的IP映射为其真正的IP地址, 即不要改变邮件的源IP地址.


4.SMTP服务器的HELO域能否包含特殊字符?
不可以。如果发邮件服务器的HELO域中包含有无法识别的字符, 就会导致新浪对其DNS解析失败, 从而拒绝接收其邮件.
包含有无法识别字符的HELO域示例: eev?bj?md02.vatech


5.国外网站应如何正确设置SMTP服务器?
新浪要求所有中国大陆境外的CMTP服务器必须提供反向DNS解析。对于中国境外的CMTP服务器,如果不提供反向DNS解析,新浪将认为该服务器为垃圾邮件发送者的服务器并拒收该地址发来的邮件。
解决方法: 注册SMTP服务器公网IP地址的RDNS服务, 并把它对应的域名写到服务器的HELO域中.


6.MS Exchange2000服务器HELO域的设置方法
具体位置在: SERVER---主名---SMTP---DEFAULT SMTP VIRTUAL---属性---DELIVERY---ADVANCED---MASQUERADE NAME


7.Notes服务器HELO域的设置方法
具体位置在:服务器---基本---全限定的Internet主机名

8.imail的HELO应该是 localhost 的general面板上的 Host Name
如Host Name这里是HI.com 那么imail 所用的就是helo HI.com
另外 Imail管理面板-》服务-》SMTP-》advance->Hello Message->HIi.com 只不过修改是smtp的banner信息

9.MDaemon Server的HELO在Setup-》Primary Domain-》HELO Domain Name中设定。

10Winmail Server的设定:管理工具->系统设置->SMTP设置->基本参数->HELO/EHLO 主机名。可用nslookup命令查找,YourDomain MX preference = 10, mail exchanger =后面的内容即为正确的HELO/EHLO 主机名。



如满足以上要求,发到 sina 还是被退回相同的信件,请和 sina 联系。联系方式如下:
邮箱地址:antispam@staff.sina.com.cn 或 lanjiang@staff.sina.com.cn
联系电话:010-82624488 转 5602
也可以申请个 sina 的邮箱,邮件系统中递送失败后启用中继递送,中继服务器: smtp.sina.com.cn, 再输入您在 sina 注册的用户名和密码。

------------------------------------------------------------------------------------------------
日前,新浪邮件根据国际通行标准,对新浪邮件的反垃圾策略进行调整。
在此期间,如出现发信到新浪情况异常或收到来自新浪的退信提示,请参考日志或错误代码,按照RFC标准调整您的发信机制,谢谢您的合作!

首先,请检查发信服务器的HELO信息是否为完整的域名,如不是将会被系统默认为垃圾邮件,相关设置问题可参考系统返回信息和服务器基本

设置的帮助文档:http://antispam.sina.com.cn/

其次,在发信服务器上做telnet测试,将telnet的结果保存并发送到antispam@staff.sina.com.cn邮箱,同时请附上发送方的服务器IP地址、

域名、单位名称、联系电话、联络人等信息,以便进行具体的技术咨询。

telnet测试格式如下:

telnet sinamx.sina.com.cn 25
220 sinamail.sina.com,cn ESMTP Postfix <Postfix Rulse!>
helo xx.com (您的正确HELO信息)
250 sinamail.sina.com.cn
mail from:<xxx@xxx.com>(您的企业邮箱名)
250 ok
rcpt to:<xxx@sina.com>(您的测试邮箱,必须为新浪邮箱)
250 ok
rcpt to:<emai_test@sina.com>(我们的测试邮箱)
250 ok
data
354 请继续 - go ahead
From: xxx@xxx.com
To: xxx@sina.com
Subject: abc
Date: Thu, 18 Mar 2004 14:50:55 +0800
MIME-Version: 1.0
Content-Type: multipart/alternative
这是一封telnet的测试信件
.(“.”不可忽略)
quit


如果能够出现220 sina.com ESMTP这条语句,则可判断您并不是因为被视为垃圾邮件而被拒收,且查询时不在黑名单中。
请注意:如果您使用的是WINDOWS服务器,注意在以上操作的时候不要使用DELETE、后退等键修改。如输入错误,请退出并按步骤重新进行telnet测试。

附件一:错误代码的含义及解决办法

首先,发送方邮件服务器必须严格按照RFC821(Simple Mail Transfer Protocol)国际标准,同时要符合RFC1035(Domain names -implementation and specification)国际标准所指定的域名命名法。
其次,因不符合目前新浪的反垃圾策略被拒,得到的错误代码为以下几种,请投诉方根据日志或错误代码进行修改。
如果投诉方是普通用户,则请投诉方向他的邮件服务提供商提供相关资料,由其管理员进行修改操作。

3.1        错误代码:450 4.7.1 Client host rejected: cannot find your hostname
错误原因:对方服务器未设置反向解析
处理方式:请参考http://www.5dmail.net/html/2006-1-20/2006120225656.htm

3.2        错误代码:450 4.7.1 Helo command rejected: Host not found
错误原因:对方服务器在HELO命令中提供的域名不能被解析
处理方式:请检查其HELO命令提供的域名信息,且保证其符合RFC1035国际标准的规定。

3.3        错误代码:504 5.5.2 Helo command rejected: need fully-qualified hostname
错误原因:对方服务器的HELO信息不是完整的域名
处理方式:请对方检查其HELO命令提供的域名信息,且保证其符合RFC1035国际标准的规定。

3.4        错误代码:501 5.5.2 Helo command rejected: Invalid name
错误原因:对方服务器的HELO信息包含非法的字符
处理方式:RFC规定,HELO命令提供的信息不得包含中文字符。
请对方按照RFC1035国际标准规定,对其HELO信息设置进行修改。

3.5        错误代码:554 5.7.1 Recipient address rejected: Dynamic IP
错误原因:对方服务器使用动态IP处理方式:请对方查看中华人民共和国信息产业部令第38号《互联网电子邮件服务管理办法》中的第四条:第四条        提供互联网电子邮件服务,应当事先取得增值电信业务经营许可或者依法履行非经营性互联网信息服务备案手续。未取得增值电信业务经营许可或者未履行非经营性互联网信息服务备案手续,任何组织或者个人不得在中华人民共和国境内开展互联网电子邮件服务。

3.6        错误代码:554 5.7.1 Service unavailable; See http://antispam.sina.com.cn/denyip.php?IP=*.*.*.*
错误原因:对方服务器IP被国际权威的反垃圾组织列入黑名单处理方式:请对方访问http://www.dnsstuff.com/tools/ip4r.ch?ip=查询并申请解封。解封后即恢复正常。



二.发到 tom.com 的邮件会被退回

1.确认您邮件系统使用的域名是合法的,而不是随意填写的。
2.确认您的邮件服务器使用的IP地址是固定的,而不是动态的IP地址。
3.正确设置HELO/EHLO 主机名。(方式见Sina部份)(可用nslookup命令查找,YourDomain MX preference = 10, mail exchanger =后面的内容即为正确的HELO/EHLO 主机名。 )
4.如满足以上三点,发送到 TOM.COM 还是被退回相同的信件:
A>请到http://whitelist.mail.tom.com/tom/whitelist/register.html申请加入到TOM.COM的白名单。
B>也可向whitelist@tom.com咨询。

三.发到 aol.com 的邮件会被退回
我发到AOL.COM的邮件会被退回,并提示"554- (RTR:DU) http://postmaster.info.aol.com/errors/554rtrdu.html";错误,怎么办?
AOL.COM除了要求您的邮件服务器使用合法的域名,固定公网IP地址,还需要该IP地址能够作反向解析。但国内要申请作反向解析比较困难,所以我们可以使用中继服务器转发,例如:
可以申请个免费邮箱(比如Sina),邮件系统外发递送 中设置递送失败后启用中继递送,中继服务器: smtp.sina.com.cn, 再输入您在 sina 注册的用户名和密码

四.发到 163 的邮件会被退回
http://mail.163.com/news/helo.htm

  从2004年3月30日起,@163.com电子邮箱增加HELO检查。

  向163.com信箱投递信件的发送方服务器必须设置规范的HELO域,即:
与网易服务器 连接的 IP 必须在 HELO 后面跟的域名的 A纪录和MX纪录里面。否则认为该服务器是垃圾发送者而拒收。


  如果您有任何疑问,请联系24小时客服电话:020-83568090-4


 若你的邮件仍无法到达网易邮箱,并收到退信,请根据退信的返回字段,在下面的表单查询具体的退信原因。


退信代码

说 明

554 HL:IHU

该IP的发送行为触犯了网易的服务条款,被临时挂起。请检查是否有用户不正当的发送行为。

554 HL:IPB

该IP不在网易允许的发送地址列表里。

450 HL:MEP

该IP发送行为异常,被临时禁止连接。

450 HL:REP

该IP发送行为异常,被临时禁止连接。

554 HL:ICC

该IP短期内发送了大量信件,超过了网易的限制,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件。

554 HL:IFQ

该IP短期内发送了大量信件,超过了网易的限制,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件。

554 HL:ITC

该IP短期内发送了大量信件,超过了网易的限制,被临时禁止连接。请检查是否有用户发送病毒或者垃圾邮件。

554 MI:SPB

此用户不在网易允许的发信用户列表里。

550 MI:NHD

HELO命令不允许为空。

550 MI:IMF

发信人电子邮件地址不合规范。请参考http://www.rfc-editor.org/关于电子邮件规范的定义。

550 MI:SPF

发信IP未被发送域的SPF许可。请参考http://www.openspf.org/关于SPF规范的定义。

450 MI:CEL

发送行为异常,该发件人被临时禁止发信。

450 MI:DMC

发送行为异常,该发件人被临时禁止发信。

450 MI:CCL

发送行为异常,该发件人被临时禁止发信。

554 MI:SFQ

短期内发送了大量信件,超过了网易的限制,该发件人被临时禁止发信。

550 MI:STC

短期内发送了大量信件,超过了网易的限制,该发件人被临时禁止发信。

550 RP:FRL

禁止发信到非网易用户。

550 RP:RCL

群发收件人数量超过了限额。

550 RP:CEL

发件人发送行为异常。

450 RP:DRC

群发收件人数量超过了限额。

450 RP:CCL

发件人发送行为异常。

550 RP:QRC

该用户短期内发送了大量信件,超过了网易的限制,被临时禁止发信。

550 RP:TRC

该用户短期内发送了大量信件,超过了网易的限制,被临时禁止发信。

450 DT:SPM

发送的邮件内容包含了未被网易许可的信息,或违背了网易的反垃圾服务条款。

550 DT:SPM

发送的邮件内容包含了未被网易许可的信息,或违背了网易的反垃圾服务条款。

450 DT:RBL

发信IP位于一个或多个RBL里。请参考http://www.rbls.org/关于RBL的相关信息。

554 IP in blacklist

该IP不在网易允许的发送地址列表里。

552 Requested mail action aborted: exceeded mailsize limit

发送的信件大小超过了网易邮箱允许接收的最大限制。

500 Error: bad syntaxU

发送的smtp命令语法有误。

550 Invalid User

请求的用户不存在。

550 User in blacklist

该用户不被允许给网易用户发信。

550 User suspended

请求的用户处于禁用或者冻结状态。

451 Requested action aborted: local error in processing

系统暂时出现故障,请稍后再次尝试发送。
  如果帮助中心仍不能解答你的问题,请仔细填写以下表单。我们的工作人员接到请求后,会在三个工作日内给您答复。http://feedback.mail.126.com/antispam/feedback.htm

五. 收到退信错误提示为"554 5.7.1 Rejected xxx.xxx.xxx.xxx found in dnsbl.sorbs.net",怎么办?
这是因为收件人所在的邮件服务器使用RBL过滤垃圾邮件,而您的邮件服务器IP地址在RBL列表中,因此被拒绝了。一般此类的退信会包含一个连接,可以按网站上面的要求来申请把您的邮件服务器IP地址从列表中移除。

六。为什么直接发新邮件到 hotmail.com 不成功,而回复 hotmail.com 的邮件可以成功?
近期不能向 hotmail.com 发信是因为 hotmail.com 仅接收可信任域名发来的邮件,比如象 163.com, yahoo.com, 21cn.com 等大的邮局系统。您可能需要和 hotmail.com 联系以确保您的域名被加入到其信任列表中。

解决办法1:在每一封发往 hotmail.com 邮件的正文中包含:
http://www.hotmail.com
http://g.msn.com
http://explorer.msn.com
以上任一内容时,您发送的邮件才可以通过 hotmail.com 的过滤。

解决办法2:只要附带2k以上的附件,邮件就可以通过 hotmail.com 的过滤。

其它需要检查的:

1、检查您的hotmail邮箱选项->防止垃圾邮件->垃圾邮件过滤器:没有选择“专用”。
2、检查您的hotmail邮箱选项->防止垃圾邮件->删除垃圾邮件:没有选择“立即删除垃圾邮件”。
3、如果您的邮件里包含了可执行文件,hotmail有可能会限制打开。Hotmail 已经永久地阻止具有潜在不安全因素的附件。

下列扩展名的文件不能附加到邮件中:
.ade
.adp
.asp
.bas
.bat
.chm
.cmd
.com
.cpl
.crt
.exe
.hlp
.hta
.inf
.ins
.isp
.its
.js
.jse
.lnk
.mdb
.mde
.mdt
.mdw
.msc
.msi
.msp
.mst
.pcd
.pif
.reg
.scr
.sct
.shb
.shs
.tmp
.url
.vb
.vbe
.vbs
.vsd
.vsmacros
.vss
.vst
.vsw
.ws
.wsc
.wsf
.wsh

详细信息可以参考 hotmail受限文件(http://help.msn.com/!data/zh_cn/data/HotmailPIMv10.its51/$content$/PIM_REF_RESTRICTEDATTACHMTS.HTM?H_APP=MSN+Hotmail)。如果要发送这些扩展名附件,建议先压缩成zip文件。

5、确认邮件大小没有超过hotmail邮箱大小限制。

6.如果以上方法不可用,请直接使用以下连接填写反馈,就跟美国方面联系了 让他把你的邮箱域名加入他们的白名单。你进入这个页面把该填的都填下,发过去就可以了 。他们处理了以后会给你回信的。
http://support.msn.com/eform.aspx?productKey=edfsmsbl&page=support_home_options_form_byemail&ct=eformts


七.发给Yahoo的邮件出现"553 Mail from 61.185.81.172 not allowed - VS99-IP1 deferred - see help.yahoo.com/help/us/mail/defer/defer-02.html "的退信及处理办法
(P.S:此点内容转自winwebmail 版主rayer 贴)
下面我贴出我私人翻译的有关YAHOO方面的退信内容
英文不好,不好意思
来自YAHOO方面的错误内容和下面提及的方面都是差不多
请自行参考(Q群共享里面也有本文档)

无法将您的邮件投递至以下指定地址:
xxb1977@yahoo.com.cn :

553 Mail from 61.185.81.172 not allowed - VS99-IP1 deferred - see help.yahoo.com/help/us/mail/defer/defer-02.html


see help.yahoo.com/help/us/mail/defer/defer-02.html (针对退信为 553 not allowed - VS99-IP1 deferred的错误)

网页概要:
1、Open proxies and open relays
开放代理以及启用匿名转发的邮件可能会被YAHOO邮件所拒绝接收

If an IP address is determined to be an open relay or open proxy, Yahoo! reserves the right to reject all SMTP traffic from that IP address for a minimum period of 60 days.

YAHOO方面一般认为邮件来源IP启用了open relay or open proxy,将会禁止所有来自于此IP的 SMTP数据流,最少60天

2、open relay(连接地址http://www.abuse.net/relay.html
检测邮件系统是否可以使用匿名转发的功能
(WINWEBMAIL版本里面,建议使用SMTP身份验证功能,开启启用匿名转发的功能,我测试过,在3.6.3.1版本,以上两个功能开通的情况下,是可以通过OPEN RELAY的测试的,邮件服务器一般情况不会轻易给人利用成为垃圾邮件转发中转点)

如果得到的测试结果是:
Relay test result
All tests performed, no relays accepted.(证明邮件系统是不存在OPEN RELAY的情况的)


3、Open proxies(http://www.unicom.com/sw/pxytest/
我看了半天还是没有明白里面的含义(英文水平有限)
网页里面的内容是在LINUX或者UNIX下面进行有关的操作,检测服务器是否存在成为代理跳板或作为代理服务器的问题
估计在WINWEBMAIL的邮件系统下,作为服务器,大家应该不会使用邮件系统的同时也开放PROXY的服务吧

4、How to remove your server

You should check (and secure) your server for open relays (such as http://www.abuse.net/relay.html) and open proxies (such as http://www.unicom.com/sw/pxytest/ -- these may require installing software on servers outside your network for proper testing). After you are reasonably sure your network is secure, please submit your IP addresses to Yahoo! for retesting

关键的一步了:如果是你已经比较确认你的邮件系统没有开放REPLY以及PROXY的话(当然你的域名设置,邮件MX设置,HELO方面设置需要正确,并没有进入有关的黑名单的情况下)please submit your IP addresses to Yahoo! for retesting

http://add.yahoo.com/fast/help/us/mail/cgi_retest(这个网页就是向YAHOO方面申述自己的IP)

1. What is your name? (自己填吧)

Name:

2. What is your email address? (自己

Email address:
For example: example_email@yahoo.com

3. IPs in the form 255.255.255.255 (separate multiple IP submissions by new lines):

Please check these for open proxies and open relays and ensure they have been removed from all open proxy and open relay DNSbls before resubmitting.

(for example: 255.255.255.255)

输入需要RETEST的IP地址,例如是61.144.56.101(多个IP的话,需要一个IP地址占用一行)

4. Indicate the error message(s) you have received. (提交你所收到的错误信息)

553 Mail from 61.185.81.172 not allowed - VS99-IP1 deferred - see help.yahoo.com/help/us/mail/defer/defer-02.html



5. Optionally, add a comment to your submission.

你需要补充的说明

6. Send the form to us:

点击“SEND”

Yahoo!, and survey partners working on behalf of Yahoo!, may contact me to participate in customer satisfaction surveys.
(这句弄不懂是什么意思,接下来估计一段时间以后,对方会发送邮件到你上面填写的邮件地址,说明有关的情况,或者24小时以后自己做有关的测试,看能否发送邮件到YAHOO.COM)

隔段时间yahoo会有回信(回信内容如下):
Hello,

Thank you for contacting Yahoo! Customer Care.

We would appreciate it if you could provide more information to help us
troubleshoot the issue.  Please note that if you are not the system
administrator for the mail server(s) affected, we encourage you to
contact the administrator so they can address the possible issues
regarding mailings from the mail server.  Please reply to this email
with the following information:

* Explain the details of one event with the delivery problems to Yahoo!
Mail. Please provide the entire message, including the full text of the
error message returned, and full header information.

Within a Yahoo! Mail account, you can display this information by
clicking the "Full Headers" link located within the message in the
bottom right-hand corner.

* The specific server_domain name and IP address of the email server(s)
that have the delivery issue to Yahoo! Mail.

   IP Address:  xxx.xxx.xxx.xxx
   Mail Server Domain Name:  server_name.domain.com

* Log messages from your mail server showing which IP you connected to
and what responses you got from the remote server at the time you
received the corresponding failures/timeouts for the event you are
reporting.

* The results from a plain text message, sent to Yahoo! Mail, without
HTML, links, graphics or attachments, from the server having delivery
issues. Is the email delivered to Yahoo! Inbox?  

We appreciate your assistance. This information will be helpful in
determining the reason why you are having issues when delivering mail
to
Yahoo! Mail accounts.

Thank you again for contacting Yahoo! Customer Care.

Regards,

Thomas Immer

Yahoo! Customer Care
27861806


然后你按他们的要求回复一下就可以了:

内容如下:

   IP Address:  服务器的IP
   Mail Server Domain Name:  邮箱的域名,我的是mail.xxxx.com

我上次问了一下yahoo中国的朋友,他告诉我,将以上的内容填写在下面的页面“问题描述”处:
http://help.cn.yahoo.com/feedback.html?product=mail
Yahoo中国邮箱客户服务部电话:010-65833721

八.为什么发附件到gmail返回552 5.7.0 Illegal Attachment错误信息?

作为预防可能存在的病毒的一种安全手段,Gmail 不允许用户接收可能包含破坏性可执行代码的可执行文件(例如文件名以 .exe 结束的文件)。即使这些类型的文件以压缩格式(.zip、.tar、.tgz、.taz、.z、.gz、.rar)发送,Gmail 也不会接收。如果有任何这种类型的邮件发送到了您的 Gmail 帐户,该邮件会退回发送方。

解决办法:将exe文件改名,或者将压缩文件改名。
比如test.ex_,或者test.zip_

九.为什么发往21cn的邮件会被退回?并且包含这样的类似退信信息“553 Mail data refused by AISP, rule [2640449].”

1.如果您的邮件里包含了可执行文件,21cn会拒收。如果要发送可执行文件附件,建议先压缩成zip文件。详细信息请咨询21cn(http://free.21cn.com/huodong/email.html)

2.21CN的反垃圾邮件措施是什么?
  a) 系统要求smtp身份认证,以确认发信人身份
  b) 接收外域邮件时,当每封收件人超过20个,系统将拒收该邮件
  c) 邮件软件中加入反垃圾邮件模块
  d) 针对用户投诉和管理员搜集的与垃圾邮件有关的IP和关键字,经技术分析后加以拒收

3.21cn已对动态域名如(3322.org)建立的邮件服务器进行了拒收。请注意。

- 作者: clay111 2007年02月27日, 星期二 12:02  回复(0) |  引用(1) 加入博采

AWStats Installation Configuration(ZT备用)

AWStats logfile analyzer 6.6 Documentation

 


AWStats Installation, Configuration and Reporting

There are 3 steps to begin using AWStats:


I. Setup: Installation and configuration using awstats_configure.pl


A) Setup for an Apache or compatible web server (on Unix/Linux, Windows, MacOS...)

* Step 1:

(if you use a package provided with a Linux distribution or Windows installer, step 1 might have already been done; if you don't know, you can run this step again)

After downloading and extracting the AWStats package, you should run the awstats_configure.pl script to do several setup actions. You will find it in the AWStats tools directory (If using the Windows installer, the script is automatically launched):
perl awstats_configure.pl

    This is what the script does/asks (you can do all these steps manually instead of running awstats_configure.pl if you prefer):

    A) awstats_configure.pl tries to determine your current log format from your Apache web server configuration file httpd.conf (it asks for the path if not found). If you use a common log, awstats_configure.pl will suggest changing it to the NCSA combined/XLF/ELF format (you can use your own custom log format but this predefined log format is often the best choice and makes setup easier).
    If you answer yes, awstats_configure.pl will modify your httpd.conf, changing the following directive:
    from
    CustomLog /yourlogpath/yourlogfile common

    to
    CustomLog /yourlogpath/yourlogfile combined

    See the Apache manual for more information on this directive (possibly installed on your server as www.mysite.com/manual).

    B) awstats_configure.pl will then add, if not already present, the following directives to your Apache configuration file (note that the "/usr/local/awstats/wwwroot" path might differ according to your distribution or OS:

    #
    # Directives to add to your Apache conf file to allow use of AWStats as a CGI.
    # Note that path "/usr/local/awstats/" must reflect your AWStats Installation path.
    #
    Alias /awstatsclasses "/usr/local/awstats/wwwroot/classes/"
    Alias /awstatscss "/usr/local/awstats/wwwroot/css/"
    Alias /awstatsicons "/usr/local/awstats/wwwroot/icon/"
    ScriptAlias /awstats/ "/usr/local/awstats/wwwroot/cgi-bin/"
    #
    # This is to permit URL access to scripts/files in AWStats directory.
    #

    Options None
    AllowOverride None
    Order allow,deny
    Allow from all


    C) if changes were made as indicated in parts A and B, awstats_configure.pl restarts Apache to apply the changes.  To be sure the log format change is effective, go to your homepage. This is an example of the type of records you should see inserted in your new log file after Apache was restarted:

    62.161.78.75 - - [dd/mmm/yyyy:hh:mm:ss +0000] "GET / HTTP/1.1" 200 1234 "http://www.from.com/from.html" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"

    D) awstats_configure.pl will ask you for a name for the configuration profile file. Enter an appropriate name such as that of your web server or the virtual domain to be analyzed, i.e. mysite.

    awstats_configure.pl will create a new file called awstats.mysite.conf by copying the template file awstats.model.conf. The new file location is:
    - For Linux/BSD/Unix users: /etc/awstats.
    - For Mac OS X, Windows and other operating systems: the same directory as awstats.pl (cgi-bin).

    E) awstats_configure.pl ends.

* Step 2:

Once a configuration file has been created (by awstats_configure.pl, by your package installer or just by a manual copy of awstats.model.conf), it's important to verify that the "MAIN PARAMETERS" match your needs.  Open awstats.mysite.conf in your favorite text editor (i.e. notepad.exe, vi, gedit, etc) - don´t use a word processor - and make changes as required.

Particular attention should be given to these parameters:
- Verify the LogFile value.  It should be the full path of your server log file (You can also use a relative path from your awstats.pl directory, but a full path avoids errors).
- Verify the LogType value.  It should be "W" for analyzing web log files.
- Check if LogFormat is set to "1" (for "NCSA apache combined/ELF/XLF log format") or use a custom log format if you don't use the combined log format.
- Set the SiteDomain parameter to the main domain name or the intranet web server name used to reach the web site to analyze (Example: www.mysite.com). If you have several possible names for same site, use the main domain name and add the others to the list in the HostAlias parameter.
- You can also change other parameters if you want. The full list is described in Configurations/Directives options page.

Installation and configuration is finished. You can jump to the Process logs: Building/updating statistics database section.



B) Setup for Microsoft's IIS server

* Step 1:

Configure IIS to create logs in the "Extended W3C log format" (You can still use your own custom log format but setup is easier if you use the standard extended format). To do so, start the IIS management console snap-in, select the appropriate web site and open its Properties. Choose "W3C Extended Log Format", then Properties, then the Tab "Extended Properties" and uncheck everything under Extended Properties. Once they are all cleared, check just the following fields:
date
time
c-ip
cs-username
cs-method
cs-uri-stem
cs-uri-query
sc-status
sc-bytes
cs-version
cs(User-Agent)
cs(Referer)

To be sure the log format change is effective, you must stop IIS, backup it up (if you desire) and remove all of the old log files, restart IIS and go to your homepage. This is an example of the type of records you should find in the new log file:
2000-07-19 14:14:14 62.161.78.73 - GET / 200 1234 HTTP/1.1 Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0) http://www.from.com/from.htm

* Step 2:

Copy the contents of the AWStats provided cgi-bin folder, from where the AWStats package put it on your local hard drive, to your server's cgi-bin directory (this includes awstats.pl, awstats.model.conf, and the lang, lib and plugins sub-directories).

* Step 3:

Move AWStats icon sub-directories and its content into a directory readable by your web server, for example C:\yourwwwroot\icon.

* Step 4:

Create a configuration file by copying awstats.model.conf to a new file named awstats.mysite.conf where "mysite" is a value of your choice but usually is the domain or virtual host name. This new file must be saved in the same directory as awstats.pl (i.e. cgi-bin).

* Step 5:

Edit your new awstats.mysite.conf file to match your specific environment:
- Change the LogFile value to the full path of your web server log file (You can also use a relative path from your awstats.pl (cgi-bin) directory).
- Change the LogType value to "W" for analyzing web log files.
- Change the LogFormat to 2 if you are using the "Extended W3C log format" described in step 1; in the case of a custom format, list the IIS fields being logged, for example:
LogFormat="date time c-ip cs-username cs-method cs-uri-stem cs-uri-query sc-status sc-bytes cs-version cs(User-Agent) cs(Referer)"
- Change the DirIcons parameter to reflect relative path of icon directory.
- Set the SiteDomain parameter to the main domain name or the intranet web server name used to reach the web site being analyzed (Example: www.mydomain.com).
- Set the AllowToUpdateStatsFromBrowser parameter to 1 if you don't have command line access and have only cgi access.
- Review and change other parameters if appropriate.

Installation and configuration is finished. You can jump to the Process logs: Building/Updating statistics database section.

C) Setup for other web servers

The setup process is similar to the setup for Apache or IIS.
Use LogFormat to value "3" if you have WebStar native log format. Use a personalized LogFormat if your log format is other.

D) Setup for other Internet servers, i.e. FTP, Mail, Streaming media

The setup process for other file formats is described in the relevant FAQ topics:  FAQ-COM090: FTP  FAQ-COM100: Mail and FAQ-COM110: Streaming media.


II. Process logs: Building/updating statistics database


* Update from command line (recommanded):

The first log analysis should be done manually from the command line since the process may be long and it's easier to solve problems when you can see the command output (if you don't have Command Line access, skip to Step 2). The AWStats create (and update) statistics database command is:

perl awstats.pl -config=mysite -update

where mysite must be substituted with the domain/virtual host name you selected earlier during AWStats configuration.

AWStats will read the configuration file awstats.mysite.conf (or if not found, awstats.conf) and create/update its database with all summary information issued from analyzed log file.

AWStats statistics database files are saved in directory defined by the DirData parameter in configuration file.
When the create/update is finished, you should see a similar result on your screen:

Update for config "/etc/awstats/awstats.mysite.conf"
With data in log file "/pathtoyourlog/yourlog.log"...
Phase 1 : First bypass old records, searching new record...
Searching new records from beginning of log file...
Phase 2 : Now process new records (Flush history on disk after 20000 hosts)...
Jumped lines in file: 0
Parsed lines in file: 225730
 Found 122 dropped records,
 Found 87 corrupted records,
 Found 0 old records,
 Found 225521 new qualified records.

Dropped records are records discarded because they were not "user HTTP requests" or were requests matching AWStats filters (See the SkipHosts, SkipUserAgents, SkipFiles, OnlyHosts, OnlyUserAgents and OnlyFiles parameters). If you want to see which lines were dropped, you can add the -showdropped option on the command line.

Corrupted records are records that do not match the log format defined by the "LogFormat" parameter in the AWStats configuration file. All web servers will typically have a few corrupted records (<5%) even when everything works correctly. This can result for several reasons: 1) Web server internal bugs, 2) bad requests made by buggy browsers, 3) a dirty web server shutdown, such as unplugging the server... 

If all of your lines are corrupted and the LogFormat parameter in AWStats configuration file is correct, then there may be a setup problem with your web server log format. Don't forget that your LogFormat parameter in the AWStats configuration file MUST match the log file format you analyze.  If you want to see which lines are corrupted, you can add the -showcorrupted option on the command line.

Old records are simply records that were already processed by a previous update session. Although it is not necessary to purge your log file after each update process, it is highly recommended that you do so as often as possible.

New records are records in your log file that were successfully used to build/update the statistics database.

Note: A log analysis process might be slow (one second for each 4500 lines of your logfile with an Athlon 1Ghz, plus DNS resolution time for each different IP address in your logfile if DNSLookup is set to 1 and not already done in your log file).  See the Benchmarks page for more detailed information.


* Update from a browser:

AWStats statistics can also be updated from a browser, providing real-time statistics, by clicking the "Update now" link that appears when AWStats is used as a CGI (The URL is described in the next section 'Run reports: Building and reading reports').

Warning!!
To enable this link, the configuration file parameter AllowToUpdateStatsFromBrowser must be set to 1 (The link is not enabled by default).
Using the on-line update does not prevent you from running the update process automatically on a scheduled basis (the command is same as that of the first update process above).
For this, you have two choices:
- Include the update command in your logrotate process. See FAQ-COM120 for details.
- Or add instructions in your crontab (Unix/Linux) or your task scheduler (Windows), to regularly launch the Awstats update process. See FAQ-COM130 for details.

See the AWStats Benchmarks page for the recommended update/logrotate frequency.


III. Run reports: Building and reading reports


To see the analysis results, you have several options depending on your security policy.

Note: you must have created a statistics data base for the analysis period by processing your log files before you try to create reports.  See the previous section.

1. The first option is to build the main reports, in a static HTML page, from the command line, using the following syntax (skip to the second option if you only have CGI access):

perl awstats.pl -config=mysite -output -staticlinks > awstats.mysite.html

where mysite must be substituted with the domain/virtual host name you selected earlier during AWStats configuration.

To create specific individual reports, specify the report name on the command line as follows¹:
perl awstats.pl -config=mysite -output=alldomains -staticlinks > awstats.mysite.alldomains.html
perl awstats.pl -config=mysite -output=allhosts -staticlinks > awstats.mysite.allhosts.html
perl awstats.pl -config=mysite -output=lasthosts -staticlinks > awstats.mysite.lasthosts.html
perl awstats.pl -config=mysite -output=unknownip -staticlinks > awstats.mysite.unknownip.html
perl awstats.pl -config=mysite -output=alllogins -staticlinks > awstats.mysite.alllogins.html
perl awstats.pl -config=mysite -output=lastlogins -staticlinks > awstats.mysite.lastlogins.html
perl awstats.pl -config=mysite -output=allrobots -staticlinks > awstats.mysite.allrobots.html
perl awstats.pl -config=mysite -output=lastrobots -staticlinks > awstats.mysite.lastrobots.html
perl awstats.pl -config=mysite -output=urldetail -staticlinks > awstats.mysite.urldetail.html
perl awstats.pl -config=mysite -output=urlentry -staticlinks > awstats.mysite.urlentry.html
perl awstats.pl -config=mysite -output=urlexit -staticlinks > awstats.mysite.urlexit.html
perl awstats.pl -config=mysite -output=browserdetail -staticlinks > awstats.mysite.browserdetail.html
perl awstats.pl -config=mysite -output=osdetail -staticlinks > awstats.mysite.osdetail.html
perl awstats.pl -config=mysite -output=unknownbrowser -staticlinks > awstats.mysite.unknownbrowser.html
perl awstats.pl -config=mysite -output=unknownos -staticlinks > awstats.mysite.unknownos.html
perl awstats.pl -config=mysite -output=refererse -staticlinks > awstats.mysite.refererse.html
perl awstats.pl -config=mysite -output=refererpages -staticlinks > awstats.mysite.refererpages.html
perl awstats.pl -config=mysite -output=keyphrases -staticlinks > awstats.mysite.keyphrases.html
perl awstats.pl -config=mysite -output=keywords -staticlinks > awstats.mysite.keywords.html
perl awstats.pl -config=mysite -output=errors404 -staticlinks > awstats.mysite.errors404.html

¹If you prefer, you can use the awstats_buildstaticpages tool to build all these pages in one command, or to generate PDF files.

Notes:

a) You can also add a filter on the following reports: urldetail, urlentry, urlexit, allhosts, refererpages.  The filter can be a regexp (regular expression) on the full key you want AWStats to report on and is appended to the output parameter separated by a ":".

For example, to output the urldetail report, including only pages which contain /news in their URL, you can use the following command line:
perl awstats.pl -config=mysite -output=urldetail:/news -staticlinks > awstats.mysite.urldetailwithfilter.html

b) If you want to build a report for a particular month, add the options -month=MM -year=YYYY where MM is the month expressed as two digits, i.e. 03, and year is the four digit year.  To build a report for a full year, add the options -month=all -year=YYYY (warning: this is often resource intensive and might use a lot of memory and CPU.  Unix/Linux like operating systems might benefit from use of the "nice" command.)


2) The second option is to dynamically view your statistics from a browser.  To do this, use the URL:
http://www.myserver.mydomain/awstats/awstats.pl?config=mysite

where mysite specifies the configuration file to use (AWStats will use the file awstats.mysite.conf).

All output command line options (except -staticlinks and -logfile) are also available when using AWStats with a browser. Just use them as URL parameters: change "-option" to "&option", i.e.  http://www.myserver.mydomain/awstats/awstats.pl?month=MM&year=YYYY&output=unknownos

Reports are generated in real time from the statistics data base.  If this is slow, or putting too much load on your server, consider generating static reports instead.

If the AllowToUpdateStatsFromBrowser parameter is set to 1 in AWStats configuration file, you will also be able to run the update process from your browser. Just click on the link "Update now".



- 作者: clay111 2007年02月5日, 星期一 13:51  回复(0) |  引用(1) 加入博采