Chinaunix

标题: 专家座谈——脚本分享与交流(大奖) [打印本页]

作者: yuhongchun    时间: 2011-09-14 15:18
提示: 作者被禁止或删除 内容自动屏蔽
作者: slient2010    时间: 2011-09-14 15:22
沙发...抢占先...等下发问...哈哈...
作者: xiaopan3322    时间: 2011-09-14 15:22
没抢到。。。
作者: yinyuemi    时间: 2011-09-14 15:23

作者: yjh625    时间: 2011-09-14 15:23
顶一个
作者: yuhongchun    时间: 2011-09-14 15:24
提示: 作者被禁止或删除 内容自动屏蔽
作者: xiaopan3322    时间: 2011-09-14 15:27
邀请嘉宾一栏,全是漏写:
邀请嘉宾:exper1    Sell版资深版主
         Shell_HAT     Sell版资深版主
         ning_lianjie   python版资深版主
         xinglu1983    PHP版资深版主

exper1 -> expert1
Sell -> Shell
作者: yuhongchun    时间: 2011-09-14 15:27
提示: 作者被禁止或删除 内容自动屏蔽
作者: waker    时间: 2011-09-14 15:37
洗洗
作者: 无风之谷    时间: 2011-09-14 15:41
回复 9# waker


    waker 这个活动你一定要多多参与啊。。。
作者: kns1024wh    时间: 2011-09-14 15:42
邀请嘉宾一栏,全是漏写:

exper1 -> expert1
Sell -> Shell
xiaopan3322 发表于 2011-09-14 15:27



    脚本出错 可以理解
作者: kns1024wh    时间: 2011-09-14 15:50
本帖最后由 kns1024wh 于 2011-09-22 11:37 编辑

回复 1# yuhongchun
  1. 1、初学者怎么入门SHELL脚本?               
  2. 初学应该以实用为主,要能够解决问题,如通过脚本访问mysql是实用shell好还是实用perl好,如果项目需要比较紧要实现实现功能需要,那实用mysql -e这个命令 放入到sh文件中就可以,有时间在通过perl或者其他的脚本技术来优化功能。
  3. shell脚本要能用的好,对于linux下的命令要是很清楚的,这个也是要平时积累的。
  4. 2、大家可以分享交流下自己工作的脚本。
  5. 积累、保存、修改、复制,这个是一个好的脚本提升的过程。
  6. 3、希望专家和高手能够交流下脚本提高的心得,方便大家。
  7. 平时多留意将一些手动操作的过程脚本话,规模化的服务器管理,都应使用脚本来控制为好,减少差错和问题。。
复制代码

作者: renxiao2003    时间: 2011-09-14 17:01
本帖最后由 renxiao2003 于 2011-09-18 22:32 编辑

这是个好活动。得参加。
1、初学者怎么入门SHELL脚本?               
说真的,到现在我还是SHELL脚本的初学者。虽然曾经也看过Linux、Unix的Shell编程,但不是很精通,倒是对Linux下的命令熟悉一些,但真的组合起来完成系统管理员的常用工作,还是差了很多。Linux是从Unix发展起来的,所以很多命令可以通用的,除非Unix厂商对命令做了个性化处理。我觉得(或者从我的经验看),初学者学习SHELL脚本,首先要对Linux、Unix的常用命令掌握一些(如果连常用命令都不清楚,那么在脚本中就更不明白了),而后是要掌握一些基本的SHELL语法,这样至少能看明白一些脚本,然后自己根据工作需要写一些脚本。最终看看高人们写的常用的系统管理脚本,然后尽量修改几个完成自己理想中的功能(当然是在自己的实验机上),这样能慢慢地进入精通的行列。
2、大家可以分享交流下自己工作的脚本。
我觉得最成功的就是在我写的备份PostgreSQL数据库的脚本,因为当时用的不是默认密码,面PostgreSQL不支持命令带参数,必须要手输入。当时一直没有找到好的办法,经过一通Google之后,终于发现用expect来完成输入功能。但这个脚本目前找不到了,这是我当时学习脚本比较成功的一次学习。等我有机会找到就帖出来给大家。
3、希望专家和高手能够交流下脚本提高的心得,方便大家。   
因为我不是高手,更不是专家,所以我没有什么心得,也不敢误导大家,在第1点中我已经分享了我的经验了。
作者: yahoon    时间: 2011-09-14 17:06
财神都成资深版主了
要请客啊
作者: 2gua    时间: 2011-09-14 17:13
来支持一下酒哥!
作者: ning_lianjie    时间: 2011-09-14 17:13
回复 6# yuhongchun


    可以记住两个选项与两个参数
首先两个选项:
1,bash -n ,检查语法
2,bash -x ,查看执行过程
两个参数在脚本中设置)
set -e ,变量检查
set -u ,遇到错误退出
作者: king_819    时间: 2011-09-14 17:13
奖品很丰厚咧,这个必须顶!
作者: ning_lianjie    时间: 2011-09-14 17:15
回复 14# yahoon


    啥时候变成资深了...兄弟捧场而已,哈哈
作者: yuhongchun    时间: 2011-09-14 17:15
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-14 17:24
本帖最后由 king_819 于 2011-09-15 10:21 编辑

先晒一个入门级的脚本吧,在通过cobbler批量布署centos后,各服务器的hostname、ip、mask、gateway、dns都需要初始化,在这我就提供一个入门级的初始化脚本

  1. #!/bin/sh
  2. # BY kerry (聆听未来)
  3. # BLOG:http://kerry.blog.51cto.com

  4. # set variable
  5. ip_mod=$1
  6. mask_mod=$2
  7. gw_mod=$3
  8. dns_mod=$4
  9. hostname_mod=$5

  10. hosts=/etc/hosts
  11. ifcfg=/etc/sysconfig/network-scripts/ifcfg-eth0
  12. network=/etc/sysconfig/network
  13. resolv=/etc/resolv.conf
  14. hwaddr=`grep -i HWADDR $ifcfg|awk -F "=" '{print $2}'`

  15. # mod ip、mask、gw、dns、hostname
  16. if [ $# != 5 ];then
  17. cat << EOF
  18. +-----------------------------------------------------------------------------------+
  19. ++++++                                                                                +++++
  20. | ====   这是一个自动修改网络ip、掩码、网关、DNS、主机名的脚本                  ====|
  21. | ====   使用方法:ip_mod ip mask gw dns hostname                                ====|
  22. | ====   例:ip_mod 10.10.10.5 255.255.255.0 10.10.10.1 8.8.8.8 kerry           ====|
  23. ++++++                                                                                +++++
  24. +-----------------------------------------------------------------------------------+
  25. EOF
  26. fi

  27. if [ $# == 5 ];then
  28. /bin/hostname $hostname_modf
  29. cp -r $hosts ${hosts}.bak
  30. echo -e "$ip_mod $hostname_mod" > $hosts

  31. cp -r $ifcfg ${ifcfg}.bak
  32. echo -ne "DEVICE=eth0
  33. BOOTPROTO=static
  34. HWADDR=$hwaddr
  35. IPADDR=$ip_mod
  36. NETMASK=$mask_mod
  37. ONBOOT=yes
  38. " > $ifcfg

  39. cp -r $network ${network}.bak
  40. echo -ne "NETWORKING=yes
  41. HOSTNAME=$hostname_mod
  42. GATEWAY=$gw_mod
  43. " > $network

  44. cp -r $resolv ${resolv}.bak
  45. echo -e "nameserver $dns_mod" > $resolv

  46. # restart network
  47. service network restart

  48. echo "ip、mask、gw、dns、hostname set OK .................!!!!!!!"
  49. fi
复制代码

作者: yuhongchun    时间: 2011-09-14 17:30
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-14 17:31
本帖最后由 king_819 于 2011-09-15 10:22 编辑

再来分享一个收集IP地址段的脚本
  1. #!/bin/sh
  2. # BY kerry (聆听未来)
  3. # BLOG:[url]http://kerry.blog.51cto.com[/url]

  4. FILE=./ip_apnic
  5. CNFILE=./hk_apnic
  6. ipinfo=./ipfile.txt
  7. rm -f $FILE
  8. rm -f $CNFILE
  9. wget [url]http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest[/url] -O $FILE
  10. grep 'apnic|HK|ipv4|' $FILE | while read text    #HK --香港地区
  11. do
  12.          echo $text>> $CNFILE
  13. done
  14. grep 'apnic|HK|ipv4|' $CNFILE | cut -f 4,5 -d'|'|sed -e 's/|/ /g' | while read ip cnt
  15. do
  16.          echo $ip:$cnt
  17.          mask=$(cat << EOF | bc | tail -1
  18. pow=32;
  19. define log2(x) {
  20. if (x<=1) return (pow);
  21. pow--;
  22. return(log2(x/2));
  23. }
  24. log2($cnt)
  25. EOF
  26. )

  27.         echo $ip/$mask>> ./hk.txt
  28.    echo $ip>> ./ip.txt
  29. done
复制代码

作者: king_819    时间: 2011-09-14 17:38
本帖最后由 king_819 于 2011-09-15 10:22 编辑

再来分享一个squid进程监控的脚本,因squid对多核支持不理想,所以在每台freebsd服务器上开启了3个squid进程,进行负载均衡,有时会发现其中一个squid进程会无故死掉,所以写了一个监控脚本,保证squid进程的正常运行
  1. #!/bin/sh
  2. # BY kerry (聆听未来)
  3. # BLOG:[url]http://kerry.blog.51cto.com[/url]

  4. Squid1_IP=`/bin/cat /etc/rc.conf | grep ifconfig_lo0_alias0 | awk '{print $2}'`
  5. Squid1Num=`netstat -an | grep $Squid1_IP | wc -l`      
  6. if [ $Squid1Num -lt 10 ] ; then   
  7.     /usr/local/etc/rc.d/squid1 start
  8.     /usr/local/etc/rc.d/squid1 restart
  9.     adddate=`date +%Y-%m-%d`" "`date +%H:%M:%S`   
  10.     echo "$adddate squid_1 started" >> /var/restart_squid.log   
  11. fi
  12. Squid2_IP=`/bin/cat /etc/rc.conf | grep ifconfig_lo0_alias1 | awk '{print $2}'`
  13. Squid2Num=`netstat -an | grep $Squid2_IP | wc -l`      
  14. if [ $Squid2Num -lt 10 ] ; then   
  15.     /usr/local/etc/rc.d/squid2 start
  16.     /usr/local/etc/rc.d/squid2 restart
  17.     adddate=`date +%Y-%m-%d`" "`date +%H:%M:%S`   
  18.     echo "$adddate squid_2 started" >> /var/restart_squid.log   
  19. fi
  20. Squid3_IP=`/bin/cat /etc/rc.conf | grep ifconfig_lo0_alias2 | awk '{print $2}'`
  21. Squid3Num=`netstat -an | grep $Squid3_IP | wc -l`      
  22. if [ $Squid3Num -lt 10 ] ; then   
  23.     /usr/local/etc/rc.d/squid3 start
  24.     /usr/local/etc/rc.d/squid3 restart
  25.     adddate=`date +%Y-%m-%d`" "`date +%H:%M:%S`   
  26.     echo "$adddate squid_3 started" >> /var/restart_squid.log   
  27. fi
复制代码

作者: yuhongchun    时间: 2011-09-14 17:41
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-14 17:46
while经典脚本之一:
#!/bin/bash
while :
do
status=`curl -s --head  | awk '/HTTP/ {print $2}'`
i ...
yuhongchun 发表于 2011-09-14 17:41



调用飞信接口   http://sms.api.bz/fetion.php
作者: yuhongchun    时间: 2011-09-14 17:51
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-14 17:53
准备下班了,明天再继续和大家一起探讨!
作者: crazyhadoop    时间: 2011-09-14 17:55
都是好书!怒赞
作者: wenzizone    时间: 2011-09-14 18:05
那我也斗胆来个吧
不排序排重
  1. #!/bin/perl
  2. open FH,'E:\test\perl\ip.txt';

  3. my %ip;
  4. while (<FH>) {
  5.     chomp;
  6.     if (!exists $ip{$_}) {
  7.         $ip{$_} = 1;
  8.         print "uni---$_\n";
  9.     } else {
  10.         print "dup---$_\n";
  11.     }
  12. }
复制代码
1,打开含有ip的文件,每个ip地址一行
2,定义一个名叫ip的hash
3,从文件中读取内容,每次一行
4,去掉每行最后的换行符
5,判断是否存在以ip为key的hash内容
6,不存在就将ip插入hash
7,打印唯一的内容
9,打印重复的内容
作者: m-scof    时间: 2011-09-14 18:27
这个一定要支持下.
作者: yuhongchun    时间: 2011-09-14 19:05
提示: 作者被禁止或删除 内容自动屏蔽
作者: ecjtubaowp    时间: 2011-09-14 23:00
打算看看python
作者: xiaopan3322    时间: 2011-09-14 23:17
先晒一个入门级的脚下本吧,在通过cobbler批量布署centos后,各服务器的hostname、ip、mask、gateway、dns都 ...
king_819 发表于 2011-09-14 17:24



    代码最好放code段里,不然大家看着费劲……呵呵
作者: wenzizone    时间: 2011-09-15 09:37
之前写的一个perl清除squid缓存的脚本

脚本设计思路:

1,遍历cache目录,拿到所有cache文件的名字
2,把cache文件内容和指定文件进行查找,取得对应的url地址
3,使用Net::HTTP模块模拟http请求purge掉对应的url

由于这个脚本使用了Net::HTTP模块,所以使用前,请先使用cpan安装此模块

脚本文件名:clear_cache.pl
  1. #! /bin/env perl

  2. use File::Find;
  3. use Net::HTTP;

  4. our @src_file_dir = ("/usr/local/squid/cache");
  5. our $grp_file = $ARGV[0];

  6. find(\&wanted, @src_file_dir);

  7. sub wanted {
  8.     !-d && search($File::Find::name);
  9. }

  10. sub search {
  11.     my $filename = shift;

  12.     open FH,"strings $filename |";

  13.     while(<FH>) {
  14.         chomp;
  15.         \&purge_cache($_) if (/$grp_file/i and /^http/);
  16.     }
  17. }

  18. sub purge_cache {
  19.     my $url = shift;
  20.     my $conn = Net::HTTP->new(Host => "127.0.0.1") or die $@;
  21.     $conn->write_request(PURGE => $url);
  22.     my($code, $mess, %h) = $conn->read_response_headers;
  23.     print $url,":",$code,"\n";
  24. }
复制代码
设置:
@src_file_dir= 设置squid缓存目录的路径

用法:
1、清除所有Flash缓存(扩展名.swf):
./clear_cache.pl swf

2、清除URL中包含wenzizone.cn的所有缓存:
./clear_cache.pl wenzizone.cn
作者: wenzizone    时间: 2011-09-15 09:40
在来个shell的

用shell写了个递归遍历目录的脚本,本脚本实现递归遍历指定目录,打印目录下的文件名(全路径)。不为别的,就为了以后用着方便。
  1. #!/bin/sh

  2. function scandir() {
  3.     local cur_dir parent_dir workdir
  4.     workdir=$1
  5.     cd ${workdir}
  6.     if [ ${workdir} = "/" ]
  7.     then
  8.         cur_dir=""
  9.     else
  10.         cur_dir=$(pwd)
  11.     fi

  12.     for dirlist in $(ls ${cur_dir})
  13.     do
  14.         if test -d ${dirlist};then
  15.             cd ${dirlist}
  16.             scandir ${cur_dir}/${dirlist}
  17.             cd ..
  18.         else
  19.             echo ${cur_dir}/${dirlist}
  20.         fi
  21.     done
  22. }

  23. if test -d $1
  24. then
  25.     scandir $1
  26. elif test -f $1
  27. then
  28.     echo "you input a file but not a directory,pls reinput and try again"
  29.     exit 1
  30. else
  31.     echo "the Directory isn't exist which you input,pls input a new one!!"
  32.     exit 1
  33. fi
复制代码

作者: king_819    时间: 2011-09-15 10:24
希望大家分享一些关于python的脚本!
作者: king_819    时间: 2011-09-15 10:51
代码最好放code段里,不然大家看着费劲……呵呵
xiaopan3322 发表于 2011-09-14 23:17


抱歉,没注意,已修改!!
作者: expert1    时间: 2011-09-15 14:04
啥时候成了senior moderator了?
作者: expert1    时间: 2011-09-15 14:09
本帖最后由 expert1 于 2011-09-15 14:14 编辑

自动改密码
  1. #!/usr/bin/python
  2. # -*- coding=utf-8 -*-
  3. #  author : xiaofu68@live.cn
  4. # Usage: change user's password automatically.As usual,you want to change root's password, you may do it as the following:
  5. # 1.open terminal ,and then type "password root "
  6. # 2. type new password twice.
  7. #but run this chg_pwd_auto.py ,you just need to type "python chg_pwd_auto.py root "! Enjoy it!
  8. # Dont't forget to you have to install "pexpect" modules ,on Centos platform ,just run "yum -y install pexpect "

  9. import pexpect
  10. import sys
  11. import string
  12. import time
  13. from random import Random

  14. def genpwd():

  15.         pwdchars=string.letters + string.digits +'~!@#$%^&*-_=+?' # password seed ,change it yourself.
  16.         pwdlength=16
  17.         return ''.join(Random().sample(pwdchars, pwdlength))

  18. def changepwd(user,newpwd):

  19.         passwd=pexpect.spawn("passwd %s" % user)
  20.         passwd.logfile = sys.stdout
  21.         for repeat in xrange(2):

  22.                 passwd.expect("password: ")
  23.                 passwd.delaybeforesend = 0.07
  24.                 passwd.sendline(newpwd)
  25.                
  26.                 time.sleep(0.1)
  27. def main():
  28.         user=sys.argv[1]
  29.         newpwd=genpwd()
  30.         print "change password for %s" %user
  31.         print "newpwd:%s" % newpwd
  32.         changepwd(user,newpwd)

  33. if __name__ == "__main__":

  34.         main()
复制代码

作者: dooros    时间: 2011-09-15 15:16
脚本好多,小弟不才啊,先占位。
作者: gawk    时间: 2011-09-15 15:42
最早在项目工程中熟悉了awk,发现脚本语言真是方便,后来便一发不可收拾,看了perl,python
目前觉得perl真是实用方便,和find结合起来真是好用
作者: 1jjk    时间: 2011-09-15 16:13
邀请嘉宾一栏,全是漏写:

exper1 -> expert1
Sell -> Shell
xiaopan3322 发表于 2011-09-14 15:27



sed -i s/exper1/expert1/g
sed -i s/Sell/Shell/g

是这么写吧?
作者: djfengqiang    时间: 2011-09-15 17:11
新手如何学习shell?
我也是一名shell新手,我最近看完鸟哥基础版的shell那一章,我发现我学的很有感觉,而且全部都理解了。但其实我发现我还是超级菜吧,我想有那样一种学习方式,就是书上写一个语法然后有很多有价值有水平的例子,而且例子是附带注释的,这样的话我想我们菜鸟会进步很快的。发现很多书籍自我感觉写的不是非常好。
作者: expert1    时间: 2011-09-15 17:34
awk的binary search ,折半查找。问题原本在这里http://bbs.chinaunix.net/viewthread.php?tid=1800295,太长了。自己看吧。
  1. awk '                       
  2. function ip2n(ip) { split(ip,a,"."); return a[1]*256^3+a[2]*256^2+a[3]*256+a[4] }

  3. BEGIN {FS="[-: ]+"}      

  4. NR==FNR {

  5.        fuck[k++] = $0;next }

  6.      {               

  7.         start = 0

  8.         end = k - 1        

  9.         while(start <= end) {

  10.               mid =int(start+ ((end - start)/2))
  11.                 split(fuck[mid], kao)

  12.                 if(ip2n($1) < ip2n(kao[1]))

  13.                         end = mid-1

  14.                 else if(ip2n($1) > ip2n(kao[2]))

  15.                         start = mid+1

  16.                 else {
  17.                        print $0 " in \t\t"fuck[mid]

  18.                         break

  19.                 }

  20.         }
  21. }'  ip_range ip
复制代码

作者: expert1    时间: 2011-09-15 17:36
个人精力有限更多请见个人博客,本人只分享高质量的awk,shell,python脚本。至于基础语法之类的,我是”不屑于“贴的,
作者: yuhongchun    时间: 2011-09-15 17:41
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-15 19:00
本帖最后由 king_819 于 2011-09-15 19:02 编辑
个人精力有限更多请见个人博客,本人只分享高质量的awk,shell,python脚本。至于基础语法之类的,我是”不屑 ...
expert1 发表于 2011-09-15 17:36



呵呵。。还得照顾一下大众!
作者: yuhongchun    时间: 2011-09-15 19:53
提示: 作者被禁止或删除 内容自动屏蔽
作者: angle4    时间: 2011-09-15 21:05
用到多了,写的多了就会了 ..
作者: expert1    时间: 2011-09-15 22:21
回复 47# king_819


    其实基础问题没什么可说的,相关资料自己看就可以了,而且脚本上手快,写多了就会了,这里只是交流学习别人的一些思想。所以恕我直言,基础知识还是看书。
不妥之处请见谅啊
作者: banggou    时间: 2011-09-15 23:20
脚本确实需要多接触多使用,如同编程一般,是一个熟练的过程,一般用脚本可以避免做一些重复劳动大大的减轻工作量。。

工作中主要还是接触shell脚本,个人感觉确实需要先看书,把基本的命令以及 for等控制语句了解清楚,进阶需要掌握正则表达式以及sed awk等这样的语句分析工具,同样可以从基础的小脚本开始编起,再慢慢功能复杂化,慢慢提升,慢慢会发现脚本的优势所在,相信有C C++的编程基础,学习脚本语言还是很快的,当然精通则又是一回事了。

目前准备专研下perl的。。。慢慢学习中。
作者: xiaopan3322    时间: 2011-09-16 10:05
个人精力有限更多请见个人博客,本人只分享高质量的awk,shell,python脚本。至于基础语法之类的,我是”不屑 ...
expert1 发表于 2011-09-15 17:36



    大拿,膜拜!
作者: yuhongchun    时间: 2011-09-16 10:07
提示: 作者被禁止或删除 内容自动屏蔽
作者: java_html    时间: 2011-09-16 10:57
其实对于初学者,首先是看一些基本的书,然后就是多练习。我个人觉得,经典的脚本来源于论坛的回复,UC的shell板块是最棒的,不只一次的看到让我惊讶的回复,这个是我常常驻足shell论坛的最根本的动力。
作者: king_819    时间: 2011-09-16 15:28
其实我觉得脚本这东西以解决生产环境中碰到的问题使工作更快捷、更方便为最终目的
作者: yuhongchun    时间: 2011-09-16 15:49
提示: 作者被禁止或删除 内容自动屏蔽
作者: crulat    时间: 2011-09-16 16:08
本帖最后由 crulat 于 2011-09-16 17:05 编辑

支持酒哥!

我几天前写的一个同时读取多个文件相同行的脚本,我觉得还是比较有用的:
http://bbs.chinaunix.net/thread-3595465-1-2.html

  1. #!/bin/bash


  2. (( $# == 0 )) && exit 1

  3. File=(${@})

  4. Len=$((${#File[@]}-1))

  5. l_oo_p()
  6. {

  7. for((i=0; i<${#File[@]}; ++i))
  8. do
  9.     FD=$((i+10))
  10.     ${1}
  11. done

  12. }

  13. create_fd()
  14. {
  15.      eval exec "${FD}<${File[$i]}"
  16.      Read=("${Read[@]}" read "-u" "${FD}" Line${i} "&&")
  17. }

  18. destroy_fd()
  19. {
  20.      eval exec "${FD}<&-"
  21. }

  22. l_oo_p create_fd

  23. while eval "${Read[@]:0:${#Read[@]}-1}"
  24. do
  25.     eval  echo $(eval echo \\\${Line{0..${Len}}} | sed -e 's#\$#\"\$#g; s#}#}\"#g')
  26. done

  27. l_oo_p destroy_fd
复制代码

作者: yuhongchun    时间: 2011-09-16 16:48
提示: 作者被禁止或删除 内容自动屏蔽
作者: Shell_HAT    时间: 2011-09-16 19:58
我觉得脚本这东西吧,一通百通。你学会了Windows的BAT、VBS,学UNIX的Shell肯定也是轻车熟路;你学会了Shell,学Perl神马的肯定也能很快上手。以下是我学Shell的一些经历,不见得适合其他人,仅供参考:

1、看《十二篇》,了解常用的命令有哪些。
http://bbs.chinaunix.net/thread-434579-1-1.html

2、在Shell版块尝试解答问题,比较自己的方案和别人的方案优劣之处在哪里。

3、看《十三问》,了解常见的问题有哪些。
http://bbs2.chinaunix.net/thread-218853-1-1.html

4、在Shell版块尝试解答问题,比较自己的方案和别人的方案优劣之处在哪里。

5、觉得sed和awk挺有意思,于是学习《sed1line》、《awkline》、《sed&awk》等。
http://bbs.chinaunix.net/thread-336126-1-1.html
http://bbs.chinaunix.net/thread-1635180-1-1.html
http://bbs.chinaunix.net/viewthread.php?tid=1588614#pid11286082

6、在Shell版块尝试解答问题,比较自己的方案和别人的方案优劣之处在哪里。

7、觉得Shell脚本挺有意思,于是学习《ABS》等。
http://bbs.chinaunix.net/thread-1610033-1-1.html

8、在Shell版块尝试解答问题,比较自己的方案和别人的方案优劣之处在哪里。

9、看Shell版每一个精华帖(顺手整理制作了一个电子书,此乃后话)。
http://bbs.chinaunix.net/thread-1640835-1-1.html

10、在Shell版块尝试解答问题,比较自己的方案和别人的方案优劣之处在哪里。
作者: Shell_HAT    时间: 2011-09-16 20:11
回复 20# king_819


每个cp命令后面的 -r 用意是什么呢?
作者: Shell_HAT    时间: 2011-09-16 20:21
回复 22# king_819


很多机器里面的grep不能直接查找多个关键字,加上 -E 会比较好。
作者: Shell_HAT    时间: 2011-09-16 20:28
回复 23# king_819


可以考虑把多条命令合并成一条,减少管道的使用,比如:
  1. Squid1_IP=`awk '/ifconfig_lo0_alias0/{print $2}' /etc/rc.conf`
  2. Squid1Num=`netstat -an | grep -c $Squid1_IP`
  3. adddate=`date "+%Y-%m-%d %H:%M:%S"`
复制代码
还有,三段代码从结构上来看基本一致,写成函数也学会简洁些。
作者: Shell_HAT    时间: 2011-09-16 20:36
回复 35# wenzizone


模拟tree功能的两个脚本也挺有意思的
http://bbs.chinaunix.net/thread-346943-1-1.html
作者: Shell_HAT    时间: 2011-09-16 20:53
回复 48# yuhongchun


replication的监控这样是不是更合适:
向master写(或更新)一条数据,几秒钟之后到slave里面去读。

我用MySQL不是很多,但是觉得你那个方法不能100%确定replication没问题。如有理解不当之处,望讲解。
作者: yuhongchun    时间: 2011-09-16 22:43
提示: 作者被禁止或删除 内容自动屏蔽
作者: yifangyou    时间: 2011-09-16 22:50
本帖最后由 yifangyou 于 2011-09-17 01:14 编辑

1、初学者怎么入门SHELL脚本?  
答:1.入门SHELL的话,首先要熟悉常用的linux系统命令,推荐大家看<linux命令大全>  或者鸟哥私房菜。
      记住最重要的是实践,不动手的话就算把书背熟了也不会。边看边动手。
      2.熟悉基本的linux命令后,建议看<高级shell编程>
         学习基本的循环,判断等等。

2、大家可以分享交流下自己工作的脚本。
答:
  1. #!/bin/bash
  2. ####################################################
  3. #作者:yifangyou
  4. #版本:v1
  5. #日期: 2011-09-17 00:51:00
  6. #系统环境:linux
  7. #编译环境:shell
  8. #执行:     findstr.sh aPath aPattern
  9. #功能:实现遍历某个目录下的文件里的文件内容,打印出包含指定字符串的文件路径
  10. #参数1:文件路径,可以是相对路径,也可绝对路径
  11. #参数2:一个字符串,可以是模式匹配字符串类似于 abc*   \d [0-9]
  12. #参数3..n:要查找的文件后缀,不支持模式匹配 一般就是 log conf 等等文本文件,缺省为 htm html txt log ini conf
  13. #运行:
  14. #[root@localhost ~]# ./findstr.sh . 386
  15. #./a/b/c/d/e/f/b.txt
  16. #./a/install.txt
  17. #./install.log
  18. #[root@localhost ~]# ./findstr.sh . 386 log jsp
  19. #./a/b/c/d/e/f/b.jsp
  20. #./install.log
  21. #[root@localhost ~]# ./findstr.sh . [0-9a-z]
  22. #./a/install.txt
  23. #./install.log
  24. ####################################################
  25. if [ -z "$1" ] || [ -z "$2" ]   # 检查传递给脚本的参数.
  26. then
  27.         echo "Usage: `basename $0` path pattern"
  28.         exit 1
  29. fi  
  30. suffixs=( htm html txt log ini conf )

  31. basepath=$1;
  32. str=$2;
  33. shift
  34. shift
  35. #若是参数中含有其他参数,则认为是查找指定后缀的文件
  36. suffixstr=${suffixs[@]}
  37. if [ $# -gt 0 ]
  38. then
  39.         suffixstr=$@
  40. fi


  41. findstr() {
  42.         local filename=$1;
  43.         if [ -f $filename ] && [ -r $filename ]
  44.         then
  45.                 for suffix in $suffixstr
  46.                 do
  47. #                        判断后缀
  48.       suffixpattern="*.$suffix"
  49.                         if [[ $filename == $suffixpattern ]]
  50.                         then
  51. #                                判断是文件
  52.                                 if [ "`egrep -c $str $filename`" -gt "0" ]
  53.                                 then
  54. #                                        输出结果
  55.                                         echo "$filename";                                       
  56.                                 fi
  57.                                 break;
  58.                         fi
  59.                 done
  60.   else
  61. #    判断是目录
  62.           if [ -d $filename ]
  63.                 then
  64.                         for entry in `ls -A $filename`
  65.                         do
  66. #                                echo $filename/$entry;
  67. #                          递归调用,但是不能超过ulimit -a|grep stack里设定的大小(默认为10240),极有可能产生段错误(这依赖于栈尺寸, 可以用ulimit -m来设置).
  68.                                 findstr $filename/$entry;
  69.                         done
  70.                 fi
  71.    fi
  72. }

  73. #调用函数查找字符
  74. findstr $basepath;
复制代码

作者: yuhongchun    时间: 2011-09-16 22:51
提示: 作者被禁止或删除 内容自动屏蔽
作者: yifangyou    时间: 2011-09-17 00:57
回复 67# yuhongchun
刚刚写了一个脚本,是遍历某个目录下所有子目录下所有指定类型文件,找出包含指定字符串的文件{:3_189:}
作者: Shell_HAT    时间: 2011-09-17 09:13
回复 68# yifangyou


一个grep命令就够了吧?
  1. grep -Erl --include=\*.txt "abc" /tmp
复制代码

作者: yuhongchun    时间: 2011-09-17 10:33
提示: 作者被禁止或删除 内容自动屏蔽
作者: crulat    时间: 2011-09-17 10:58
本帖最后由 crulat 于 2012-02-20 13:48 编辑

批量部署Nagios监控服务的脚本:

  1. #!/bin/bash

  2. # Check the parameters
  3. if [ $# -eq 0 ]; then
  4.    echo "please run with your file"
  5.    exit 1
  6. fi

  7. # Global variables

  8. # File is the list of ip addresses that map to hostnames for all  given servers
  9. file=$1
  10. cfg_path=/usr/local/nagios/etc

  11. # The four variables below need to be modified as your required.
  12. group_name=node
  13. host_cfg=${cfg_path}/hosts/node/node.cfg
  14. service_cfg=${cfg_path}/services/node.cfg
  15. monitor=(zombie_procs total_procs users load var swap)

  16. # The core configure files
  17. group_cfg=${cfg_path}/hostgroups.cfg
  18. nagios_cfg=${cfg_path}/nagios.cfg

  19. # Backup dir
  20. mkdir -p /root/backup
  21. BACKDIR=/root/backup

  22. # Backup the core configure files to /root/backup and define the filename by the current date
  23. [ ! -e ${group_cfg} ] || cp -a ${group_cfg} ${BACKDIR}/hostgroups.$(date +%F-%T).cfg
  24. [ ! -e ${nagios_cfg} ] || cp -a ${nagios_cfg} ${BACKDIR}/nagios.$(date +%F-%T).cfg

  25. base_host=$(basename ${host_cfg})
  26. base_service=$(basename ${service_cfg})
  27. back_host=${base_host%.cfg}
  28. back_service=${base_service%.cfg}

  29. # Backup the core configure files to /root/backup and define the filename by the current date
  30. [ ! -e ${host_cfg} ] || cp -a ${host_cfg} ${BACKDIR}/${back_host}.H.$(date +%F-%T).cfg
  31. [ ! -e ${service_cfg} ] || cp -a ${service_cfg} ${BACKDIR}/${back_service}.S.$(date +%F-%T).cfg

  32. # The host_fun function
  33. host_fun()
  34. {
  35. HOST="
  36. define host{
  37.        host_name                       ${name_host}
  38.        alias                           ${name_host}
  39.        address                         ${ip}
  40.        max_check_attempts              5
  41.        check_period                    24x7
  42.        contact_groups                  admins
  43.        notification_interval           10
  44.        notification_period             24x7
  45.        notification_options            d,u,r
  46.        }"
  47. }


  48. # The share function
  49. share()
  50. {

  51. echo "is_volatile              0
  52.     check_period             24x7
  53.     max_check_attempts       5
  54.     normal_check_interval    2
  55.     retry_check_interval     1
  56.     contact_groups           admins
  57.     notification_options     w,u,c,r
  58.     notification_interval    960
  59.     notification_period      24x7"
  60. }

  61. # The host_alive_fun function
  62. host_alive_fun()
  63. {
  64. SERVICE="

  65. define service{
  66.     use                      generic-service      
  67.     host_name                ${name_service}
  68.     service_description      check-host-alive
  69.     $(share)
  70.     check_command            check-host-alive
  71.     }
  72. "
  73. }

  74. # The check_tcp_fun function
  75. check_tcp_fun()
  76. {
  77. SERVICE="

  78. define service{
  79.     use                      generic-service     
  80.     host_name                ${name_service}
  81.     service_description      check_port80
  82.     $(share)
  83.     check_command            check_tcp!80
  84.     }
  85. "
  86. }

  87. # The service_fun function
  88. service_fun()
  89. {
  90. SERVICE="

  91. define service{
  92.     use                      generic-service      
  93.     host_name                ${name_service}
  94.     service_description      check_${1}
  95.     $(share)
  96.     check_command            check_nrpe!check_${1}
  97.     }
  98. "
  99. }

  100. # The read function
  101. WRL()
  102. {

  103. while read line
  104. do
  105.       ${1}
  106. done << EOF
  107. $(egrep -v "^#|^$" ${file})
  108. EOF

  109. }

  110. # Create ${host_cfg}
  111. CHC()
  112. {
  113.       name_host=$(echo ${line} | awk '{print $2}')
  114.       ip=$(echo ${line} | awk '{print $1}')
  115.       host_fun
  116.       echo "${HOST}" >> ${host_cfg}
  117. }

  118. # Create ${service_cfg}
  119. CSC()
  120. {
  121.       name_service=$(echo ${line} | awk '{print $2}')
  122.       for stac in host_alive_fun check_tcp_fun
  123.       do
  124.             ${stac}
  125.             echo "${SERVICE}" >> ${service_cfg}
  126.       done
  127.       for SEV in ${monitor[*]}
  128.       do
  129.             service_fun ${SEV}
  130.             echo "${SERVICE}" >> ${service_cfg}
  131.       done
  132. }

  133. WRL CHC
  134. WRL CSC

  135. # Append the hostgroups to ${group_cfg}

  136. name=$(cat ${file} | awk '{print $2}' | xargs | sed 's# #,#g')

  137. GROUP="
  138. define hostgroup {
  139.        hostgroup_name          ${group_name}_group
  140.        alias                   ${group_name}
  141.        members                 ${name}
  142.        }"

  143. echo "${GROUP}" >> ${group_cfg}

  144. # Add the code below to ${nagios_cfg}

  145. config=(host_cfg service_cfg)
  146. for cfg in ${config[*]}
  147. do
  148.      [[ x$(grep "cfg_file=${!cfg}" ${nagios_cfg}) != x ]] || echo "cfg_file=${!cfg}" >> ${nagios_cfg}
  149. done

  150. # Check the configuration
  151. # bash /root/check_nagios.sh
  152. /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

  153. # Restart the service
  154. service nagios restart
复制代码

作者: crulat    时间: 2011-09-17 11:07
本帖最后由 crulat 于 2011-09-17 11:12 编辑

并行执行命令的脚本:

  1. #!/bin/bash
  2. #
  3. # pssh

  4. CMD=$1
  5. IP_FILE=$2
  6. DIR=/usr/local/etc/

  7. if [[ $# != 2 ]]; then
  8.     echo "Usage: pssh \"commands\" ip_file"
  9.     exit 1
  10. fi

  11. if [ ! -e ${DIR}${IP_FILE} ]; then
  12.     echo "file ${DIR}${IP_FILE} doesn't exist"
  13.     exit 1
  14. fi

  15. for IP in $(egrep -v "^#|^$" ${DIR}${IP_FILE} | sort -n | uniq)
  16. do
  17.      echo "---> ${IP}"
  18.      ssh ${IP} ${CMD} || echo ${IP} >> failed_ip_list &
  19. done 2> /dev/null
  20. wait &> /dev/null
复制代码
并行传输数据的脚本:

  1. #!/bin/bash
  2. #
  3. # ptar

  4. FILE=$1
  5. TDIR=$2
  6. IP_FILE=$3
  7. DIR=/usr/local/etc/

  8. if [[ $# != 3 ]]; then
  9.     echo "Usage: ptar \"file\" target_dir ip_file"
  10.     exit 1
  11. fi

  12. if [ ! -e ${FILE} ]; then
  13.     echo "file ${FILE} doesn't exist"
  14.     exit 1
  15. fi

  16. if [ ! -e ${DIR}${IP_FILE} ]; then
  17.     echo "file ${DIR}${IP_FILE} doesn't exist"
  18.     exit 1
  19. fi

  20. for IP in $(egrep -v "^#|^$" ${DIR}${IP_FILE} | sort -n | uniq)
  21. do
  22.      echo "---> ${IP}"
  23.      tar -jcpvf - ${FILE} | ssh  ${IP} "cd ${TDIR}; tar -jxpvf -" || echo ${IP} >> failed_ip_list &
  24. done 2> /dev/null
  25. wait &> /dev/null
复制代码

作者: dongnanyk    时间: 2011-09-17 11:08
本帖最后由 dongnanyk 于 2011-09-17 11:33 编辑

小弟不才只能写简单脚本
功能:找到没用过的ip,其实就是简单ping 命令,遇到禁止icmp包就没办法了,但是ping 的 -f -W 参数还是比较有用的,前者flood ,后者timeout!

  1. #!/bin/bash
  2. #Not used to find the ip
  3. #20110909

  4. #variables
  5. ip_duan=10.0.100
  6. ip_head=1
  7. ip_end=254
  8. user=`id -u`


  9. #
  10. if [ $user -ne 0 ];then
  11.     echo "must root !!"
  12.     exit 1
  13. fi


  14. for ((i=$ip_head;i<=$ip_end;i++));do
  15.     ping -f -c 3 -W 1 "$ip_duan.$i" >/dev/null
  16.     if [ $? -eq 1 ];then
  17.         echo "$ip_duan.$i"
  18.     fi
  19. done
复制代码

作者: hackers365    时间: 2011-09-17 11:08
我们的开发环境是在一台服务器上。程序员映射目录到自己的机器上。每个人在服务器上配置一个虚拟主机。通过设置hosts来访问。每来一位新同事就得添加samba目录。添加nginx虚拟主机。svn co代码。改config.php配置等一系列操作。每位员工调动时。需要把他在服务器上的目录以及配置删掉。。下面是一个脚本来做这些事情。。包括一个模块文件
/data/software/sh/template.conf
  1. ############{{user}}############
  2.     server {
  3.         listen       80;
  4.         server_name  {user}.lava.cn;

  5.         #charset koi8-r;

  6.         access_log  logs/{user}.lava.cn.access.log;
  7.         error_log   /data/weblog/{user}.lava.cn.error.log;
  8.         location / {
  9.             root   /home/{user}/gamebox/htdocs;
  10.             index  index.php index.html index.htm;
  11.         }


  12.         # pass the PHP scripts to FastCGI server listening on 192.168.1.123:9000
  13.         #
  14.         location ~ \.php$ {
  15.             root           /home/{user}/gamebox/htdocs;
  16.             fastcgi_pass   127.0.0.1:9000;
  17.             fastcgi_index  index.php;
  18.             fastcgi_param  FILE_SCRIPTNAME  $document_root$fastcgi_script_name;
  19.             fastcgi_param  PHP_VALUE "include_path=/home/{user}/gamebox/include:/usr/share/pear";
  20.             include        fastcgi_params;
  21.         }
  22.     include vhosts/rewrite.conf;
  23.     }
  24. ############{{user}}############
  25. ##########**{{user}}**##########
  26. [{user}]
  27. comment = {user}.lava.cn
  28. path = /home/{user}
  29. public = no
  30. browseable=no
  31. writable = yes
  32. printable = no
  33. valid users = {user}
  34. write list = {user}
  35. read only = no
  36. create mask = 775
  37. delete readonly = yes
  38. ##########**{{user}}**##########
复制代码
  1. #!/bin/bash
  2. #filename:adduser.sh
  3. #add user script
  4. #1. add nginx conf
  5. #2. add samba conf
  6. #3. add system user
  7. #4. add samba user
  8. #5. reload nginx conf
  9. #6. reload samba conf
  10. #7. mkdir smarty tmp directory

  11. TEMPLATE='/data/software/sh/template.conf'
  12. SAMBACONF='/etc/samba/smb.conf'
  13. SMBPASSWD='/usr/bin/smbpasswd'
  14. SMBSBIN='/etc/rc.d/samba'
  15. NGINXCONF='/etc/nginx/conf/nginx.conf'
  16. NGINXCONFDIR='/etc/nginx/conf/vhosts'
  17. NGINXSBIN='/usr/sbin/nginx'
  18. function addnginxconf
  19. {
  20.     USERNGINXCONF=${NGINXCONFDIR}/${1}.lava.cn.conf
  21.     read  num1 num2 <<< `grep -n "##{$1}##" $NGINXCONF | cut -d: -f1`
  22.     if [ -z $num1 ];then
  23.         read num1 num2 <<< `grep -n '##{{user}}##' $TEMPLATE | cut -d: -f1`
  24.         touch $USERNGINXCONF
  25.         sed -n -e "s/{user}/${1}/g" -e "$num1,${num2}p" $TEMPLATE > $USERNGINXCONF
  26.         read last <<< `grep -n '}' $NGINXCONF | grep -v '#' | tail -n 1 | cut -d: -f1`
  27.         str="############{$1}###########\ninclude $USERNGINXCONF\;\n############{$1}############"
  28.         cp $NGINXCONF ${NGINXCONF}_add_${1}.bak
  29.         sed -i "${last}i\ ${str}" $NGINXCONF
  30.         echo "nginxconfig:add file $USERNGINXCONF and modify $NGINXCONF file"
  31.     else
  32.         echo "nginx main conf is exist $1 record , nothing to do"
  33.     fi
  34. }
  35. function delnginxconf
  36. {
  37.     USERNGINXCONF=${NGINXCONFDIR}/${1}.lava.cn.conf
  38.     read  num1 num2 <<< `grep -n "##{$1}##" $NGINXCONF | cut -d: -f1`
  39.     if [ ! -z $num1 ];then
  40.         cp $NGINXCONF ${NGINXCONF}_del_${1}.bak
  41.         sed -i "${num1},${num2}d" $NGINXCONF
  42.         rm -rf $USERNGINXCONF
  43.         echo "delelte file $USERNGINXCONF and modify nginx main file sucess"
  44.     else
  45.         echo "nginx main conf is not exist $1 record , nothing to do"
  46.     fi
  47. }
  48. function addsambaconf
  49. {
  50.     read num1 num2 <<< `grep -n "\*\*{$1}\*\*" $SAMBACONF | cut -d: -f1`
  51.     if [ -z $num1 ];then
  52.         read num1 num2 <<< `grep -n '\*\*{{user}}\*\*' $TEMPLATE|cut -d: -f1`
  53.         sed -n -e "s/{user}/$1/g" -e "$num1,${num2}p" $TEMPLATE >> $SAMBACONF
  54.         cp $SAMBACONF ${SAMBACONF}_add_${1}.bak
  55.         echo "backup samba config file in ${SAMBACONF}_add_${1}.bak modify $SAMBACONF file add user $1 sucess"
  56.     else
  57.         echo "$1 user's record is exist in $SAMBACONF , nothing to do"
  58.     fi
  59. }
  60. function delsambaconf
  61. {
  62.     read num1 num2 <<< `grep -n "\*\*{$1}\*\*" $SAMBACONF | cut -d: -f1`
  63.     if [ ! -z $num1 ];then
  64.         cp $SAMBACONF ${SAMBACONF}_del_${1}.bak
  65.         sed -i "${num1},${num2}d" $SAMBACONF
  66.         echo "modify samba config file sucess and drop user $1"
  67.     else
  68.         echo "samba conf is not exist $1 record , nothing to do"
  69.     fi
  70. }
  71. function addsystemuser
  72. {
  73.    groupadd $1
  74.    useradd -g $1 -m -s /bin/bash -d /home/${1}/ $1
  75.    chmod +x /home/${1}
  76.    echo -e "${1}\n${1}" | passwd $1
  77.    echo "add system user $1 sucess"
  78. }
  79. function delsystemuser
  80. {
  81.     userdel -r -f $1 > /dev/null 2>&1
  82.     echo "delete system user $1 sucess"
  83. }
  84. function addsambauser
  85. {
  86.     echo -e "$1\n$1" | $SMBPASSWD -s -a $1
  87.     echo "add samba user $1 sucess"
  88. }
  89. function delsambauser
  90. {
  91.     $SMBPASSWD -x $1 > /dev/null 2>&1
  92.     echo "delete samba user $1 sucess"
  93. }
  94. function co
  95. {
  96.     svn co --username ${1} --password ${1}123 svn://192.168.1.200/yanfa3/lava.cn/dev /home/${1}/gamebox
  97. }
  98. function modifyconfig
  99. {
  100.     cp /home/${1}/gamebox/include/Config.local.php /home/${1}/gamebox/include/Config.php
  101.     sed -i "3s/b/${1}/g" /home/${1}/gamebox/include/Config.php
  102. }
  103. function useage
  104. {
  105.     echo -e "useage:$0 -a/-d username"
  106. }
  107. function addu
  108. {
  109.     addnginxconf $1
  110.     addsambaconf $1
  111.     addsystemuser $1
  112.     addsambauser $1
  113.     mkdir -p /tmp/smarty/${1}/compile
  114.     chmod -R 777 /tmp/smarty/${1}/
  115.     $NGINXSBIN -t
  116.     if [ $? -eq 0 ];then
  117.          $NGINXSBIN -s reload
  118.     else
  119.          echo "nginx test parm fail , will not nginx -s reload"
  120.     fi
  121.     $SMBSBIN restart
  122.     co $1
  123.     modifyconfig $1
  124.     touch /home/${1}/gamebox/htodcs/index.html
  125.     chmod 777 /home/${1}/gamebox/htdocs/index.html
  126.     chown -R ${1}.${1} /home/${1}/
  127. }
  128. function delu {
  129.     delnginxconf $1
  130.     delsambaconf $1
  131.     delsambauser $1
  132.     delsystemuser $1
  133.     rm -rf /tmp/smarty/${1}/
  134.     $NGINXSBIN -s reload
  135.     $SMBSBIN restart
  136. }
  137. #addnginxconf shijingbo
  138. #addsambaconf $1
  139. #delnginxconf shijingbo
  140. #delsambaconf $1
  141. #addsystemuser $1
  142. #delsystemuser $1
  143. #getopts ":a:d:" opt

  144. if [ $# -ne 2 ];then
  145.     useage;exit 1;
  146. fi
  147. #addu $2

  148. while getopts ":a:d:" opt
  149. do
  150.     case $opt in
  151.         a) addu $OPTARG;;
  152.         d) delu $OPTARG;;
  153.         ?) useage;exit 1;;
  154.     esac
  155. done
  156. #$SMBSBIN restart
复制代码

作者: hackers365    时间: 2011-09-17 11:27
标题: 我是标题
本帖最后由 hackers365 于 2011-09-17 11:37 编辑

新接手一台服务器。想快速了解服务器信息。肿么办?。。发个脚本。愣说我有非法内容。。所以放在附件里了。。

collect.rar

849 Bytes, 下载次数: 154


作者: hackers365    时间: 2011-09-17 11:41
监控进程。如果down掉。。把它启动。并邮件报警。报警超过三次。则不再发送邮件报警。进程恢复以后发送恢复邮件通知。。需要安装msmtp才可以发邮件。
  1. #!/bin/bash
  2. #monitor services,if service down mail to administrator
  3. #and restart the service
  4. #services list,you can add the monitor service to it

  5. #define monitor services
  6. servicelist=(httpd nginx phpfpm)
  7. LOG_PATH=/var/log/monitor.log
  8. #define service start parameters
  9. httpd="service httpds start"
  10. httpd_log="/var/log/messages"
  11. httpd_pid="/etc/httpd/run/httpd.pid"
  12. nginx="/usr/local/nginx/sbin/nginx"
  13. nginx_log="/usr/local/nginx/logs/error.log"
  14. nginx_pid="/usr/local/nginx/logs/nginx.pid"
  15. phpfpm="/usr/local/php5.3.25/sbin/php-fpm"
  16. phpfpm_log="/usr/local/php5.3.25/var/log/php-fpm.log"
  17. phpfpm_pid="/usr/local/php5.3.25/var/run/php-fpm.pid"

  18. function ser_restart()
  19. {
  20.         if [ $# -ne 1 ];then
  21.                 :
  22.         else
  23.                 count=1
  24.                 while [ $count -lt 4 ];do
  25.                         `$1>/dev/null 2>&1`
  26.                         if [ $? -eq 0 ];then
  27.                                 return $count;
  28.                         fi
  29.                         let "count=$count+1"
  30.                 done

  31.         fi
  32.         if [ $count -eq 4 ];then
  33.                 count=0
  34.         fi
  35.         #return restart count
  36.         return $count;
  37. }
  38. function recovery_alert()
  39. {
  40.         ipaddr=`ifconfig eth0|grep 'inet addr'|awk -F: '{print $2}'|awk '{print $1}'`
  41.         subj="`date` $1 now is ok!"
  42.         log_error "$subj"
  43.         echo "$subj"|/usr/bin/mutt -s "$subj" 13876005014@139.com
  44. }
  45. function alert_admin()
  46. {
  47.         ipaddr=`ifconfig eth0|grep 'inet addr'|awk -F: '{print $2}'|awk '{print $1}'`
  48.         eval log_path=\${${1}_log}
  49.         if [ $2 -eq 0 ];then
  50.                 subj="$ipaddr: $1 is down and restart 3 counts but fail"
  51.         else
  52.                 subj="$ipaddr: $1 is down and restart $2 counts, now the service is ok!"
  53.         fi
  54.         tail -n10 $log_path>/tmp/temp
  55.         log="`date` $1 is down"
  56.         log_error "$log"
  57.         /usr/bin/mutt -s "$subj" 13876005014@139.com</tmp/temp
  58.         rm -rf /tmp/temp
  59. }
  60. function check_status()
  61. {
  62.         eval pid=\${${1}_pid}
  63.         #whether file is exist
  64.         if [ -e $pid ];then
  65.                 ps aux|grep -v 'grep'|grep "`cat $pid`" > /dev/null 2>&1
  66.                 if [ $? -eq 0 ];then
  67.                         :
  68.                 else
  69.                         return 1
  70.                 fi
  71.         else
  72.                 return 1
  73.         fi
  74. }
  75. function log_error()
  76. {
  77.         echo "$1" >> $LOG_PATH
  78. }
  79. #now,we check the service start string is OK
  80. while :
  81. do
  82.         for a in ${servicelist[@]}
  83.         do
  84.                 eval tep=\${${a}_count:=0}
  85.                 check_status $a
  86.                 if [ $? -eq 0 ];then
  87.                         #decide whether state is recovery,if recovery then send recovery alert mail
  88.                         if [ $tep -eq 3 ];then
  89.                                 recovery_alert $a
  90.                         fi
  91.                         eval ${a}_count=0
  92.                 else
  93.                         #if alert count > 3 ,then ignore alert
  94.                         eval tep=\${${a}_count:=0}

  95.                         if [  $tep -lt 3 ];then
  96.                                 #restart service
  97.                                 eval ha="\${${a}}"
  98.                                 ser_restart "$ha"
  99.                                 #alert administrator
  100.                                 alert_admin "$a" "$?"
  101.                                 let ${a}_count=${a}_count+1
  102.                         else
  103.                                 :
  104.                         fi
  105.                 fi
  106.         done
  107. sleep 10
  108. done
复制代码

作者: yuhongchun    时间: 2011-09-17 13:36
提示: 作者被禁止或删除 内容自动屏蔽
作者: coralzd    时间: 2011-09-17 14:38
本帖最后由 coralzd 于 2011-09-17 15:10 编辑

linux 负载报警脚本,系统负载超过一定数值,就重启php-cgi,并发送报警短信。
  1. #!/bin/sh
  2. #description:system load average
  3. #author:coralzd powered by www.freebsdsystem.org
  4. host=$(hostname)
  5. channel=$(hostname | sed 's/[0-9]//g')
  6. runday=$(date "+%Y-%m-%d")
  7. IPhost=$(/sbin/ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}')
  8. i=10
  9.   while [ 1 ];do
  10. rundaytime=$(date "+%Y-%m-%d %H:%M:%S")
  11. L=$(cat /proc/loadavg|cut -c1-4)
  12. RESULT=$(echo "$L > $i"|bc)
  13. if [ "${RESULT}" == "$i" ]; then
  14. echo "$runday" >> /var/tmp/${host}.txt
  15. wget http://10.10.10.10/phpsms/smsu.php?phone=15012345678\&msg=warning%20${IPhost}%20Load%20avarage%20is%20high -O /dev/null >/dev/null 2>&1
  16. /usr/local/php52/sbin/php-fpm restart
  17. echo "${runday}" >> /var/log/${host}.txt
  18. echo "The system load average is 10+ ,php-fpm already restart" >> /var/log/${host}.txt
  19. fi
  20. sleep 600
  21. done
复制代码

作者: coralzd    时间: 2011-09-17 14:40
本帖最后由 coralzd 于 2011-09-17 15:10 编辑

文件防篡改脚本,已有文件被修改,立即发送报警短信。
  1. #!/bin/bash
  2. #description: check files shell
  3. #author:coralzd powered by www.freebsdsystem.org
  4. checkdir=/data/www/bbs.xxx.com

  5. ipadd=`ifconfig |grep "inet" |cut -c 0-36|sed -e 's/[a-zA-Z: ]//g' |grep -v "127.0.0.1"`

  6. while [ 1 ]
  7. do
  8.   DATE=`date +%Y-%m-%d.%H:%M:%S`
  9.   find ${checkdir} \( -path ${checkdir}/forumdata/threadcaches -o -path  ${checkdir}/forumdata_1/threadcaches -o -path  ${checkdir}/forumdata_1/templates  -o -path ${checkdir}/f
  10. orumdata_1/cache -o -path ${checkdir}/forumdata/dzwxuser -o -path ${checkdir}/attachments -o -path ${checkdir}/forumdata/cache -o -path ${checkdir}/forumdata/templates -o -path
  11. ${checkdir}/forumdata/dzwxuser -o -path ${checkdir}/dzwxuserid/cache -o -path ${checkdir}/forumdata_1 \) -prune -o -name "*php" -mmin -1 -print >/tmp/tmpdd
  12.   SZ=`ls -la /tmp/tmpdd|awk '{print $5}'`
  13.   if [ "${SZ}" -gt "2" ]; then
  14.         SN=`cat /tmp/tmpdd`
  15.     echo ${DATE} ${SN} >>/var/tmp/checkfile.log
  16.     wget http://10.10.10.10/phpsms/smsu.php?phone=15012345678\&msg=%E7%95%99%E6%84%8F%EF%BC%9A${ipadd}_%E5%8F%AF%E8%83%BD%E5%87%BA%E7%8E%B0%E6%96%87%E4%BB%B6%E7%AF%A
  17. 1%E6%94%B9 -O /dev/null >/dev/null 2>&1
  18.   fi
  19.   sleep 60
  20. done
复制代码

作者: coralzd    时间: 2011-09-17 14:59
nginx_php 自动安装脚本第二版。
  1. #!/bin/bash
  2. # author:coralzd powered by www.freebsdsystem.org
  3. # written by coralzd 2010.11.05
  4. # version 0.1.4 build 20110831
  5. # description: nginx php mysql install shell

  6. nginx_dir="/usr/local/nginx"
  7. php52_dir="/usr/local/php52"
  8. mysql_dir="/usr/local/mysql"

  9. function init()
  10. {

  11. yum -y install wget gcc gcc-c++ autoconf bison flex re2c  libmhash libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel gd gd-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers

  12. read -p "Now,will download nginxphp software...Y|y:"  nginxphp

  13. case "$nginxphp" in

  14.      Y|y)

  15. echo -n "starting download nginx_php ..."
  16. cat > list << "EOF" &&
  17. nginx-1.0.1.tar.gz
  18. php-5.2.17.tar.gz
  19. php-5.2.17-fpm-0.5.14.diff.gz
  20. libiconv-1.13.1.tar.gz
  21. libmcrypt-2.5.8.tar.gz
  22. mcrypt-2.6.8.tar.gz
  23. memcache-2.2.5.tgz
  24. mhash-0.9.9.9.tar.gz
  25. mysql-5.1.58.tar.gz
  26. suhosin-patch-5.2.17-0.9.7.patch
  27. pcre-8.10.tar.gz
  28. autoconf-2.13.tar.gz
  29. eaccelerator-0.9.5.3.tar.bz2
  30. PDO_MYSQL-1.0.2.tgz
  31. libunwind-0.99.tar.gz
  32. ImageMagick.tar.gz
  33. imagick-2.3.0.tgz
  34. google-perftools-1.6.tar.gz
  35. fcgi.conf
  36. php.ini
  37. my.cnf
  38. nginx.conf
  39. php-fpm.conf
  40. EOF
  41. mkdir packages
  42.         for i in `cat list`
  43. do
  44. if [ -s packages/$i ]; then
  45.   echo "$i [found]"
  46. else
  47.   echo "Error: $i not found!!!download now......"
  48.   wget http://www.freebsdsystem.org/linux/nginx-php/$i -P packages/
  49. fi
  50. wget http://www.freebsdsystem.org/linux/nginx-php/nginxd
  51. wget http://www.freebsdsystem.org/linux/nginx-php/php-fpm
  52. mv nginxd /etc/init.d/
  53. mv php-fpm /etc/init.d/
  54. chmod 755 /etc/init.d/*
  55. chkconfig --add nginxd
  56. chkconfig --add php-fpm
  57. echo "create the eaccelerator directory to /data0/cache"
  58. mkdir /data0/cache
  59. echo "create the mysql data directory to /data0/mysql/data"
  60. mkdir -p /data0/mysql/data
  61. echo "PATH=/usr/local/mysql/bin/:$PATH" >> /etc/profile
  62. source  /etc/profile
  63. done
  64. ;;

  65. *)

  66.   echo -n "exit install script"
  67.    exit 0
  68. ;;

  69. esac  

  70. groupadd www &&  useradd www -s /sbin/nologin -g www
  71. groupadd mysql && useradd mysql -s /sbin/nologin -g mysql
  72. echo "www and mysql user && group create!"
  73. cd packages/
  74. tar zxf
  75. /bin/rm -rf list

  76. echo -e "All of installed sucussful!"


  77. }
  78. function is_version()

  79. {

  80.    
  81. if [ `uname -m` == "x86_64" ];then
  82. tar zxf libunwind-0.99.tar.gz
  83. tar zxvf libunwind-0.99.tar.gz
  84. cd libunwind-0.99/
  85. CFLAGS=-fPIC ./configure
  86. make CFLAGS=-fPIC
  87. make CFLAGS=-fPIC install
  88. cd ../
  89. else

  90.         echo "your system is 32bit ,not install libunwind lib!"
  91. fi


  92. }

  93. function ins_nginx()

  94. {

  95. cd packages/
  96. is_version
  97. tar zxf google-perftools-1.6.tar.gz
  98. cd google-perftools*
  99. ./configure
  100. make
  101. make install
  102. cd ..

  103. tar zxf pcre-8.10.tar.gz
  104. cd pcre-*
  105. ./configure
  106. make
  107. make install
  108. cd ..
  109. tar zxf nginx-1.0.1.tar.gz
  110. cd nginx-1.0.1
  111. ./configure --prefix=${nginx_dir} --user=www --group=www --with-http_stub_status_module   

  112. make && make install
  113. cd ..
  114. rm -rf /usr/local/nginx/conf/nginx.conf
  115. echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
  116. cp nginx.conf /usr/local/nginx/conf/
  117. cp fcgi.conf /usr/local/nginx/conf/
  118. echo "nginx installed sucussfully!"
  119. }

  120. function ins_mysqlserver()
  121. {

  122. cd packages/
  123. tar zxf mysql-5.1.58.tar.gz
  124. cd mysql-5.1.58
  125. CHOST="x86_64-pc-linux-gnu"
  126. CFLAGS="-march=nocona -O2 -pipe"
  127. CXXFLAGS="${CFLAGS}"
  128. ./configure --prefix=/usr/local/mysql --enable-assembler --with-server-suffix=-DZWWW --enable-thread-safe-client --enable-local-infile --enable-thread-safe-client --with-big-tables --with-charset=utf8 --with-client-ldflags=-all-static --with-collation=utf8_general_ci --with-extra-charsets=all --with-mysqld-ldflags=-all-static --with-mysqld-ldflags=-ltcmalloc  --with-mysqld-user=mysql --with-plugins=partition,myisammrg --with-pthread --with-unix-socket-path=/tmp/mysql.sock --without-ndb-debug
  129. make && make install
  130. cp support-*/mysql.server /etc/init.d/mysqld
  131. cp my.cnf /etc/
  132. chmod 744 /etc/init.d/mysqld
  133. cd /usr/local/mysql

  134. chown -R mysql:mysql .
  135. rm -rf sql-bench mysql-test
  136. mkdir -p /data0/mysql/relaylog/
  137. mkdir -p /data0/mysql/binlog/
  138. chown -R mysql.mysql /data0/mysql

  139. /usr/local/mysql/bin/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/data0/mysql/data
  140. echo "mysql server  5.1.58 installed successfully!"
  141. }

  142. function ins_mysqlclient()
  143. {

  144. cd packages/
  145. tar zxf mysql-5.1.58.tar.gz
  146. cd mysql-5.1.58
  147. CHOST="x86_64-pc-linux-gnu"
  148. CFLAGS="-march=nocona -O2 -pipe"
  149. CXXFLAGS="${CFLAGS}"
  150. ./configure "--prefix=${mysql_dir}"   "--with-mysqld-user=mysql"   "--without-debug" "--with-charset=utf8"  "--with-extra-charsets=all"  "--with-pthread" "--with-big-tables" "--enable-thread-safe-client" "--enable-assembler" "--with-readline" "--with-ssl" "--enable-local-infile"  "--without-server"

  151. make && make install
  152. cd /usr/local/mysql
  153. chown -R mysql:mysql .
  154. rm -rf sql-bench mysql-test
  155. echo "mysql client  5.1.58 installed successfully!"
  156. }
  157. function ins_php52()       
  158. {
  159. cd packages/
  160. tar zxf libiconv-1.13.1.tar.gz
  161. cd libiconv-1.13.1/
  162. ./configure --prefix=/usr/local
  163. make
  164. make install
  165. cd ../

  166. tar zxf autoconf-2.13.tar.gz
  167. cd autoconf-2.13
  168. ./configuire --prefix=/usr
  169. make && make install
  170. cd ..

  171. tar zxf libmcrypt-2.5.8.tar.gz
  172. cd libmcrypt-2.5.8/
  173. ./configure
  174. make
  175. make install
  176. /sbin/ldconfig
  177. cd libltdl/
  178. ./configure --enable-ltdl-install
  179. make
  180. make install
  181. cd ../../

  182. tar zxf mhash-0.9.9.9.tar.gz
  183. cd mhash-0.9.9.9/
  184. ./configure
  185. make
  186. make install
  187. cd ../

  188. ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
  189. ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
  190. ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
  191. ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
  192. ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
  193. ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
  194. ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
  195. ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
  196. ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1
  197. ln -s /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config

  198. tar zxf mcrypt-2.6.8.tar.gz
  199. cd mcrypt-2.6.8/
  200. /sbin/ldconfig
  201. ./configure
  202. make
  203. make install
  204. cd ../


  205. tar zxf php-5.2.17.tar.gz
  206. gzip -cd php-5.2.17-fpm-0.5.14.diff.gz | patch -d php-5.2.17 -p1
  207. cd php-5.2.17/
  208. patch -p1 -i ../suhosin-patch-5.2.17-0.9.7.patch
  209. ./buildconf --force  
  210. ./configure --prefix=${php52_dir} --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-config-file-path=${php52_dir}/etc  --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-fpm --enable-force-cgi-redirect --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap --enable-suhosin --enable-ftp
  211. make ZEND_EXTRA_LIBS='-liconv'
  212. make install
  213. cd ..
  214. cp php.ini /usr/local/php52/etc/
  215. cp php-fpm.conf /usr/local/php52/etc/

  216. echo "/usr/local/mysql/lib/mysql" >> /etc/ld.so.conf.d/mysql_lib.conf
  217. /sbin/ldconfig
  218. echo "php52 installed successfully!"
  219. }

  220. function ins_php52ext()

  221. {
  222. cd packages/

  223. tar zxf memcache-2.2.5.tgz
  224. cd memcache-2.2.5/
  225. ${php52_dir}/bin/phpize
  226. ./configure --with-php-config=${php52_dir}/bin/php-config
  227. make
  228. make install
  229. cd ../

  230. tar jxf eaccelerator-0.9.5.3.tar.bz2
  231. cd eaccelerator-0.9.5.3
  232. ${php52_dir}/bin/phpize
  233. ./configure --enable-eaccelerator=shared --with-eaccelerator-shared-memory --with-php-config=${php52_dir}/bin/php-config
  234. make
  235. make install
  236. cd ../

  237. #tar zxf PDO_MYSQL-1.0.2.tgz
  238. #cd PDO_MYSQL-1.0.2/
  239. #${php52_dir}/bin/phpize
  240. #./configure --with-php-config=${php52_dir}/bin/php-config --with-pdo-mysql=${mysql_dir}
  241. #make
  242. #make install
  243. #cd ../

  244. tar zxf ImageMagick.tar.gz
  245. cd ImageMagick-6.5.1-2/
  246. ./configure
  247. make
  248. make install
  249. cd ../

  250. tar zxf imagick-2.3.0.tgz
  251. cd imagick-2.3.0/
  252. ${php52_dir}/bin/phpize
  253. ./configure --with-php-config=${php52_dir}/bin/php-config
  254. make
  255. make install
  256. cd ..


  257. echo "php52 extension installed successfully!"


  258. }

  259. case $1 in


  260. init)

  261.         init
  262.          ;;
  263. ins_mysqlserver)
  264.          
  265.           ins_mysqlserver

  266.           ;;
  267. ins_mysqlclient)
  268.           ins_mysqlclient
  269.           ;;
  270. ins_nginx)
  271.            ins_nginx
  272.            ;;
  273. ins_php52)
  274.        ins_php52  
  275.            ;;
  276. ins_php52ext)
  277.        ins_php52ext
  278.        ;;
  279. *)

  280.      echo "Usage:`basename $0` {init|ins_mysqlserver|ins_mysqlclient|ins_php52|ins_php52ext}"
  281.          ;;
  282. esac
复制代码

作者: coralzd    时间: 2011-09-17 15:30
对于短信报警,我们这里采用的是短信猫,并没有采用飞信,因为它不太稳定!
作者: yuhongchun    时间: 2011-09-17 16:11
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-17 17:19
回复 60# Shell_HAT

呵呵。。这个-r确实是多余的,有时要递归复制,习惯性的加了一个-r
作者: king_819    时间: 2011-09-17 17:28
回复  king_819


很多机器里面的grep不能直接查找多个关键字,加上 -E 会比较好。
Shell_HAT 发表于 2011-09-16 20:21



使用扩展模式匹配
作者: 2gua    时间: 2011-09-18 08:28
占位先。
作者: shplpy    时间: 2011-09-18 08:43
再来分享一个收集IP地址段的脚本
king_819 发表于 2011-09-14 17:31



    很想知道这个脚本的源头出自哪位高人之手~
作者: shplpy    时间: 2011-09-18 08:48
并行执行命令的脚本:并行传输数据的脚本:
crulat 发表于 2011-09-17 11:07



    进程批量放入后台,没有数量控制,如果服务器很多,会有执行失败的进程。
作者: shplpy    时间: 2011-09-18 09:17
nginx_php 自动安装脚本第二版。
coralzd 发表于 2011-09-17 14:59


    支持下!
作者: yuhongchun    时间: 2011-09-18 11:41
提示: 作者被禁止或删除 内容自动屏蔽
作者: yifangyou    时间: 2011-09-18 12:16
回复 70# yuhongchun

还真是啊,又学到了,没相对grep还有这样用的{:3_203:}
作者: crulat    时间: 2011-09-18 14:01
进程批量放入后台,没有数量控制,如果服务器很多,会有执行失败的进程。
shplpy 发表于 2011-09-18 08:48


可根据实际情况做合理的调整!
作者: coralzd    时间: 2011-09-18 15:17
回复 88# shplpy


    好好学习,天天向上!
作者: yuhongchun    时间: 2011-09-18 16:22
提示: 作者被禁止或删除 内容自动屏蔽
作者: king_819    时间: 2011-09-18 21:51
回复 86# shplpy


有什么问题吗?
作者: shplpy    时间: 2011-09-19 08:18
回复 94# king_819


    没有问题,只是想膜拜一下
作者: wenzizone    时间: 2011-09-19 17:38
再来发个之前写的perl清除squid缓存的脚本
  1. #! /bin/env perl

  2. use File::Find;
  3. use Net::HTTP;

  4. our @src_file_dir = ("/usr/local/squid/cache");
  5. our $grp_file = $ARGV[0];

  6. find(\&amp;wanted, @src_file_dir);

  7. sub wanted {
  8.     !-d &amp;&amp; search($File::Find::name);
  9. }

  10. sub search {
  11.     my $filename = shift;

  12.     open FH,"strings $filename |";

  13.     while(&lt;FH&gt;) {
  14.         chomp;
  15.         \&amp;purge_cache($_) if (/$grp_file/i and /^http/);
  16.     }
  17. }

  18. sub purge_cache {
  19.     my $url = shift;
  20.     my $conn = Net::HTTP-&gt;new(Host =&gt; "127.0.0.1") or die $@;
  21.     $conn-&gt;write_request(PURGE =&gt; $url);
  22.     my($code, $mess, %h) = $conn-&gt;read_response_headers;
  23.     print $url,":",$code,"\n";
  24. }
复制代码
设置:
@src_file_dir= 设置squid缓存目录的路径
用法:
1、清除所有Flash缓存(扩展名.swf):
./clear_cache.pl swf
2、清除URL中包含wenzizone.cn的所有缓存:
./clear_cache.pl wenzizone.cn
作者: yuhongchun    时间: 2011-09-19 18:36
提示: 作者被禁止或删除 内容自动屏蔽
作者: surpass_li    时间: 2011-09-19 21:01
初学者怎么入门SHELL脚本?
1.要了解shell的执行过程及执行环境。
2.如何执行shell脚本文件
3.学习shell逻辑判断式与表达式以及控制语句等
4.多加练习,多读网上高手的shell
作者: david2878    时间: 2011-09-19 23:26
支持,路过。
作者: rock0018    时间: 2011-09-20 14:15
回复 1# yuhongchun
潜水很长时间 ,来一段python script ,遍历指定目录下文件 ,在删除文件创建日期大于28天的文件(python version 3.1 or later)

  1. #!/usr/bin/env python            
  2. import os,datetime,time,sys

  3. def nukedir(dir):
  4.     if dir[-1] == os.sep: dir = dir[:-1]
  5.     now=datetime.date.today()
  6.     files = os.listdir(dir)
  7.     for file in files:
  8.         
  9.         if file == '.' or file == '..': continue
  10.         path = dir + os.sep + file
  11.         if os.path.isdir(path):
  12.             nukedir(path)
  13.         else:
  14.             year=time.localtime(os.stat(path).st_ctime).tm_year
  15.             mon=time.localtime(os.stat(path).st_ctime).tm_mon
  16.             day=time.localtime(os.stat(path).st_ctime).tm_mday
  17.             createdate=datetime.date(year,mon,day)
  18.             days= (now -createdate).days
  19.             if days > 28 :
  20.                     os.unlink(path)
  21.                

  22. nukedir("G:\SH_DEV_DB_Backup");
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2