Posts Tagged: SHELL


28
六 11

bash中getopts的用法

getopts 用于解析命令行参数。
用法: getopts 选项字符串 名称 [参数]
举个例子:
一个a.sh内容如下
#!/bin/bash
usage() {
cat << -EOF-
Usage:
$0 -I interface -i ipaddr

-EOF-
exit 1
}
while getopts “I:i:” opt ; do
case $opt in
I) interface=$OPTARG ;;
i) IP=$OPTARG ;;
?) usage ;;
done

if [[ -z "$interface" || -z "$ip" ]] ; then
usage
else
ifconfig $interface $ip
fi

其中:
1. 选顶字符串中,后面跟”:”(冒号)表示后面要跟一个参数,这个参数应用空格与选项隔开;这个参数保存在OPTARG变量中。
2. 选项字符串以”:”开始,将打开“沉默错误报错方式”,不能识别的选择等,将不打印错误信息。
3. getopts 将使用三个变量:name, OPTIND, OPTARG,OPTERR.
OPTERR :如果OPTERR=0, shell将禁用“错误提示输出”,即使选项字符串的开头不是冒号。
OPTARG : 当getopts解析到“选项”时,将指定的参数保存到这个变量中。
OPTIND : 存储$* 位置参数中的位置,随着getopts的处理而被getopts修改。

  


6
十一 10

在脚本中使用ssh时的几个注意事项

1. 超时设置
-o ConnectTimeout=3

2. 重定项标准输入到/dev/null
-n
当使用这样的形式时 (使用 key 认证):

    while read line ; do
        ip=$(awk '{print $1}' < << $line )
        ssh -n -o ConnectTimeout=3 $i uptime
    done < file

假如此时不使用 -n ,则只有第一行会被处理。

3. 批处理模式,在脚本中使用再合适不过(使用 key 认证)
-o BatchMode=yes
当 key 认证不成功时,有可能会弹出“密码认识”,从而影响脚本运行下去,此时可以打开 BatchMode模式。

4. 遇到未知主机:

-o StrictHostKeyChecking=no

当遇到未知的主机公钥时,自动接受key。

5. 糟遇远程主机连接后无响应:

当设置了 BatchMode 时 ServerAliveInterval 默认被设置成 300 秒(服务端无数据传回的持续时间)。
ServerAliveCountMax相当于是重试的次数,比如下面的例子,15秒 x 3 = 45 秒,即当 45 秒后,真正超时断开。
TCPKeepAlive打开时,便于发现网络的断开。当网络故障(比如路由器坏掉)或者远端开机、死机时,连接会主动断开,否则的话,将会等待相当一段时间后才会断开。

-o ServerAliveInterval=15
-o ServerAliveCountMax=3
-o TCPKeepAlive=yes

需要注意的是,这里的超时、无响应,仅是 ssh或者sshd无影响,假如是在远程上执行程序,程序无响应,则不能处理此时的超时,解决方法见上一篇《在Shell中实现异步》。

 


6
十一 10

在Shell中实现异步

在shell脚本中,如何实现异步的超时设置功能?

关键部分的代码如下:

            scp ../local_hw_oob_init.sh $i: &>/dev/null
            ssh $i /root/local_hw_oob_init.sh &>/dev/null &
            SSHPID=$!
            { sleep 60 ; kill -9 $SSHPID ; } &
            KILLPID=$!
            wait $SSHPID
            if [ $? = 0 ] ; then
                kill -9 $KILLPID
                echo -n "SSH_OK,"
            else
                echo -n "SSH_KILLED,"
            fi

首先,将主任务 TASK1 放到后台,记录 TASK1_PID;然后立即在后台再运行第二个任务 { sleep 60 ; kill -9 $TASK1_PID ; } 到后台,然后启动一个 waith $TASK1_PID 的指令。

假如在 60 秒内,TASK1 还没有返回,就会被第二个后台的任务 kill 掉,此时,waith 收到 TASK1 的退出状态,并返回。
假如在 60 秒内,TASK1 返回,则wait之后,紧跟着 kill 掉第二个任务。


10
二 10

系统调用exec和fork

Exec 与 fork 是 UNIX 中的两个系统调用,UNIX 程序利用它们来创建新的进程。

由一个进程产生 (spawn) 另一个进程 ,可能是进程产生后用新进程取代它,即exec;或者如何需要保留这个进程,那就复制一个进程,即 fork 。

举个例子:Getty 进程监测一个串行端口 (tty),提供了一个 “login:” 提示符,当用户输入登录名回车之后,getty的任务就完成了;它执行 (exec) 了 login 命令,当 login 检测密码输入正确之后,它执行 (exec) 登录 shell 。一旦用户启动另一个程序,shell 程序就会派生 (fork) 自己,并且这个复本将执行 (exec) 用户所要运行的任何程序。


2
二 10

查找后门程序

每个进程都会有一个PID,而每一个PID都会在/proc目录下有一个相应的目录,这是Linux(当前内核2.6)系统的实现。

一般后门程序,在ps等进程查看工具里找不到,因为这些常用工具甚至系统库在系统被入侵之后基本上已经被动过手脚(网上流传着大量的rootkit。假如是内核级的木马,那么该方法就无效了)。

因为修改系统内核相对复杂(假如内核被修改过,或者是内核级的木马,就更难发现了),所以在/proc下,基本上还都可以找到木马的痕迹。

思路:
在/proc中存在的进程ID,在 ps 中查看不到(被隐藏),必有问题。

str_pids=`ps -A | awk ‘{print $1}’`
for i in /proc/[0-9]* ; do
        if  echo $str_pids | grep -q `basename $i` ; then
                :
            else
                echo “Rootkit’s PID: `basename $i`”
        fi
done
unset str_pids i

讨论:

检查系统(Linux)是不是被黑,其复杂程度主要取决于入侵者“扫尾工作”是否做得充足。对于一次做足功课的入侵来说,要想剔除干净,将是一件分精密、痛苦的事情,通常这种情况,需要用专业的第三方的工具(有开源的,比如tripwire,比如aide)来做这件事情。

而专业的工具,部署、使用相对比较麻烦,也并非所有的管理员都能熟练使用。

实际上Linux系统本身已经提供了一套“校验”机制,在检查系统上的程序没有被修改。比如rpm包管理系统提供的 -V 功能:

rpm -Va

即可校验系统上所有的包,输出与安装时被修改过的文件及相关信息。但是rpm系统也可能被破坏了,比如被修改过。


17
九 08

几个性能工具备忘

top:

* A: PID        = Process Id
* E: USER       = User Name
* H: PR         = Priority
* I: NI         = Nice value
* O: VIRT       = Virtual Image (kb)
* Q: RES        = Resident size (kb)
* T: SHR        = Shared Mem size (kb)
* W: S          = Process Status
* K: %CPU       = CPU usage
* N: %MEM       = Memory usage (RES)
* M: TIME+      = CPU Time, hundredths
b: PPID       = Parent Process Pid
c: RUSER      = Real user name
d: UID        = User Id
f: GROUP      = Group Name
g: TTY        = Controlling Tty
j: P          = Last used cpu (SMP)
p: SWAP       = Swapped size (kb)
l: TIME       = CPU Time
r: CODE       = Code size (kb)
s: DATA       = Data+Stack size (kb)
u: nFLT       = Page Fault count
v: nDRT       = Dirty Pages count
y: WCHAN      = Sleeping in Function
z: Flags      = Task Flags <sched.h>
* X: COMMAND    = Command name/line

Flags field:
0×00000001  PF_ALIGNWARN
0×00000002  PF_STARTING
0×00000004  PF_EXITING
0×00000040  PF_FORKNOEXEC
0×00000100  PF_SUPERPRIV
0×00000200  PF_DUMPCORE
0×00000400  PF_SIGNALED
0×00000800  PF_MEMALLOC
0×00002000  PF_FREE_PAGES (2.5)
0×00008000  debug flag (2.5)
0×00024000  special threads (2.5)
0x001D0000  special states (2.5)
0×00100000  PF_USEDFPU (thru 2.4)

进程的优先级和nice级别
进程优先级是一个决定进程被CPU执行优先顺序的参数,内核会根据需要调整这个值。Nice值是一个对优先权的限制。进程优先级的值不能低于nice值。(nice值越低优先级越高)
进程优先级是无法去手动改变的,只有通过改变nice值去间接的调整进程优先级。如果一个进程运行的太慢了,你可以通过指定一个较低的nice值去为它分配更多的CPU资源。当然,这意味着其他的一些进程将被分配更少的CPU资源,运行更慢一些。Linux支持nice值的范围是19(低优先级)到-20(高优先级),默认的值是0。如果需要改变一个进程的nice值为负数(高优先级),必须使用su命令登陆到root用户。下面是一些调整nice值的命令示例,
以nice值-5开始程序xyz
#nice –n -5 xyz

改变已经运行的程序的nice值
#renice level pid

将pid为2500的进程的nice值改为10
#renice 10 2500

vmstat:

·process(procs)
r:等待运行时间的进程数量
b:处在不可中断睡眠状态的进程
w:被交换出去但是仍然可以运行的进程,这个值是计算出来的
·memoryswpd:虚拟内存的数量
free:空闲内存的数量
buff:用做缓冲区的内存数量
·swap
si:从硬盘交换来的数量
so:交换到硬盘去的数量
·IO
bi:向一个块设备输出的块数量
bo:从一个块设备接受的块数量
·system
in:每秒发生的中断数量, 包括时钟
cs:每秒发生的context switches的数量
·cpu(整个cpu运行时间的百分比)
us:非内核代码运行的时间(用户时间,包括nice时间)
sy:内核代码运行的时间(系统时间)
id:空闲时间,在Linux 2.5.41之前的内核版本中,这个值包括I/O等待时间;
wa:等待I/O操作的时间,在Linux 2.5.41之前的内核版本中这个值为0

iostat:

%user:user level(应用)的CPU占用率情况
%nice:加入nice优先级的user level的CPU占用率情况
%sys:system level(内核)的CPU占用情况
%idle:空闲的CPU资源情况

Device:块设备名
Tps:设备每秒进行传输的数量(每秒的I/O请求)。多个单独的I/O请求可以被组成一个传输操作,因为一个传输操作可以是不同的容量。
Blk_read/s, Blk_wrtn/s:该设备每秒读写的块的数量。块可能为不同的容量。
Blk_read, Blk_wrtn:自系统启动以来读写的块设备的总量。

块可能为不同的容量。块的大小一般为1024、2048、4048byte。可通过tune2fs或dumpe2fs获得:
# tune2fs -l /dev/hda1|grep ‘Block size’
Block size:               4096
# dumpe2fs -h /dev/hda1|grep ‘Block size’
dumpe2fs 1.35 (28-Feb-2004)
Block size:               4096


11
七 08

shell中的判断

[ -f $file ]
像这们的句子,应该写成
[ -f "${file}" ] 这样可以
第1:避免变量file里包含特殊符号的情况。(当然这样也不是万能的)
第2:万一还有一个变量f,那么$file就会出现异常。

2010-02-01
apachectl 脚本中判断变量不为空:
$ULIMIT_MAX_FILES=”ulimit -S -n `ulimit -H -n`”
if [ "x$ULIMIT_MAX_FILES" != "x" ] ; then
    $ULIMIT_MAX_FILES
fi


10
七 08

BASH中字符串的处理

$x=abcd

[得到长度]

方法1:
$expr length $x
4

方法2:
$echo ${#x}
4

方法3:
$expr “$x” : “.*”    #expr的手册信息
4           #STRING : REGEXP anchored pattern match of REGEXP in STRIN

[查找子串]

$expr index $x “b”
2
$expr index $x “a”
1

[得到子字符串]

方法1:
#expr startpos length
$expr substr “$x” 1 3
abc
$expr substr “$x” 1 5
abcd
$expr substr “$x” 2 5
bcd

方法2:
#${x:pos:lenght}
$echo ${x:1}
bcd
$echo ${x:2}
cd
$echo ${x:0}
abcd
$echo ${x:0:1}
a

[匹配正则表达式]

[打印匹配长度]
$expr match $x “.”
1
$expr match $x “abc”
3
$expr match $x “bc”
0

[字符串的掐头去尾]

$x=aabbaarealwwvvww
$echo “${x%w*w}”
aabbaarealwwvv
$echo “${x%%w*w}”
aabbaareal
$echo “${x##a*a}”
lwwvvww
$echo “${x#a*a}”
bbaarealwwvvww

其中 , # 表示掐头, 因为键盘上 # 在 $ 的左面。
其中 , % 表示%, 因为键盘上 % 在 $ 的右面。
单个的表示最小匹配,双个表示最大匹配。
也就是说,当匹配的有多种方案的时候,选择匹配的最大长度还是最小长度。

[字符串的替换]

$x=abcdabcd
$echo ${x/a/b} # 只替换一个
bbcdabcd
$echo ${x//a/b} # 替换所有
bbcdbbcd


10
七 08

SHELL程序的不同执行方式

在当前shell环境运行:继承并影响当前环境。
. a.sh
source a.sh
实际上,”.”号与source的效果是一样的。
在当前shell运行时,需要注意,shell程序会影响、改变当前shell的环境。假如a.sh中有exit指令,那么用户将退出shell登录。

启动新的shell执行:只继承export输入的变量,并切不影响父进程的环境。exit指令只是退出新启动的shell。
bash a.sh
bash <a.sh
chmod+x a.sh
./a.sh

在( ) 中运行:executed in a subshell environment

也是在新的进程中运行。但是继承关系有点复杂,实验如下:

####START####
$su -
#chmod +x a.sh
#cat a.sh
echo $a
exit
#a=FreeBSD
#(./a.sh)

#(source a.sh)
FreeBSD
#(. a.sh)
FreeBSD
####END####

a.sh中的exit均没有影响到当前shell,但是却继承了当前shell的变量,但是改变a的操作却不能影响当前shell下a的值。

另外:
exec ./a.sh
关于exec:
exec: exec [-cl] [-a name] file [redirection ...]
Exec FILE, replacing this shell with the specified program.
If FILE is not specified, the redirections take effect in this
shell. If the first argument is `-l’, then place a dash in the
zeroth arg passed to FILE, as login does. If the `-c’option
is supplied, FILE is executed with a null environment. The `-a’
option means to make set argv[0] of the executed process to NAME.
If the file cannot be executed and the shell is not interactive,
then the shell exits, unless the shell option `execfail’is set.

man bash

Compound Commands
A compound command is one of the following:

(list) list  is  executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below).  Variable assignments and builtin commands that affect the shell’s environment do not remain in effect after the command completes.  The return status is the exit status  of list.

{ list; }
list  is simply executed in the current shell environment.  list must be terminated with a newline or semicolon.  This is known as a group command.  The return status is the exit status of list.  Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized.  Since they do not cause a word break, they must be sep-arated from list by whitespace.
Command Substitution
Command substitution allows the output of a command to replace the command name.  There are two forms:

$(command)
or
‘command‘

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing  newlines  deleted.  Embedded newlines are not deleted, but they may be removed during word splitting.  The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, ‘, or \.  The first backquote not preceded by a backslash terminates the command substitution.  When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

Command substitutions may be nested.  To nest when using the backquoted form, escape the inner backquotes with backslashes.

If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

COMMAND EXECUTION ENVIRONMENT
The shell has an execution environment, which consists of the following:

·      open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin

·      the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation

·      the file creation mode mask as set by umask or inherited from the shell’s parent

·      current traps set by trap

·      shell parameters that are set by variable assignment or with set or inherited from the shell’s parent in the environment

·      shell functions defined during execution or inherited from the shell’s parent in the environment

·      options enabled at invocation (either by default or with command-line arguments) or by set

·      options enabled by shopt

·      shell aliases defined with alias

·      various process IDs, including those of background jobs, the value of $$, and the value of $PPID

When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate  execution  environment  that consists of the following.  Unless otherwise noted, the values are inherited from the shell.

·      the shell’s open files, plus any modifications and additions specified by redirections to the command

·      the current working directory

·      the file creation mode mask

·      shell variables and functions marked for export, along with variables exported for the command, passed in the environment

·      traps caught by the shell are reset to the values inherited from the shell’s parent, and traps ignored by the shell are ignored

A command invoked in this separate environment cannot affect the shell’s execution environment.

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent  at invocation.   Builtin  commands  that are invoked as part of a pipeline are also executed in a subshell environment.  Changes made to the subshell environment cannot affect the shell’s execution environment.

If a command is followed by a & and job control is not active, the default standard input for the command is the  empty  file  /dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections.


10
七 08

BASH多进程并行处理的方法实现

#!/bin/bash

SEND_THREAD_NUM=13
tmp_fifofile=”/tmp/$$.fifo” # 脚本运行的当前进程ID号作为文件名
mkfifo “$tmp_fifofile” # 新建一个随机fifo管道文件
exec 6<>”$tmp_fifofile” # 定义文件描述符6指向这个fifo管道文件
rm $tmp_fifofile
for ((i=0;i<$SEND_THREAD_NUM;i++));do
echo # for循环 往 fifo管道文件中写入13个空行
done >&6

for i in `seq 100`;do # 100 次 for 循环 开始
read -u6 # 从文件描述符6中读取行(实际指向fifo管道)

{
echo $i # 打印 i
sleep 3 # 暂停3秒
echo >&6 # 再次往fifo管道文件中写入一个空行。
} &

# {} 这部分语句被放入后台作为一个子进程执行,所以不必每次等待3秒后执行
#下一个,这部分的echo $i几乎是同时完成的,当fifo中13个空行读完后 for循环
# 继续等待 read 中读取fifo数据,当后台的13个子进程等待3秒后,按次序
# 排队往fifo输入空行,这样fifo中又有了数据,for语句继续执行

pid=$! #打印最后一个进入后台的子进程id
echo $pid

done
wait
exec 6>&- #删除文件描述符6

exit 0


26
六 08

在BASH中进行数学运算

以前只知道expr,今天发现了BASH内置的let:
let: let arg [arg ...]
Each ARG is an arithmetic expression to be evaluated.  Evaluation
is done in fixed-width integers with no check for overflow, though
division by 0 is trapped and flagged as an error.  The following
list of operators is grouped into levels of equal-precedence operators.
The levels are listed in order of decreasing precedence.

id++, id–      variable post-increment, post-decrement
++id, –id      variable pre-increment, pre-decrement
-, +            unary minus, plus
!, ~            logical and bitwise negation
**              exponentiation
*, /, %         multiplication, division, remainder
+, -            addition, subtraction
<<, >>          left and right bitwise shifts
<=, >=, <, >    comparison
==, !=          equality, inequality
&               bitwise AND
^               bitwise XOR
|               bitwise OR
&&              logical AND
||              logical OR
expr ? expr : expr
conditional operator
=, *=, /=, %=,
+=, -=, <<=, >>=,
&=, ^=, |=      assignment

Shell variables are allowed as operands.  The name of the variable
is replaced by its value (coerced to a fixed-width integer) within
an expression.  The variable need not have its integer attribute
turned on to be used in an expression.

Operators are evaluated in order of precedence.  Sub-expressions in
parentheses are evaluated first and may override the precedence
rules above.

If the last ARG evaluates to 0, let returns 1; 0 is returned
otherwise.

注:是“脚本”,不是“角本”。

2008-07-02

今天又有新的发现:

(( … )): (( expression ))
The EXPRESSION is evaluated according to the rules for arithmetic
evaluation.  Equivalent to “let EXPRESSION”.

$a=1
$(( a++ ))
$echo $a
2

2011-07-23
一个有意思的用法:
$ echo $((2#11111111))
255
二进制11111111的值(十进制)是多少?


12
五 08

BASH中使用数组

Bash中还可以使用数组变量,其赋值有两种:

(1) name = (value1 … valuen) 此时下标从0开始
(2) name[index] = value

数组下标的范围没有任何限制,同时也不必使用连续的分量.

———————————————————-

$ A=(a b c def)
=========================================

$ echo ${A[@]} //取全部元素
a b c def
========================================
$ echo ${A[0]} //取第一个元素
a
========================================
//取得数组元素的个数
$ echo ${#A[@]}
4
$ echo ${#A
}
4
$ echo ${#A[3]} //取得元素3的长度
$
========================================

$ A[3]=yaoshuyin //将第三个元素重新赋值
$ echo ${A[@]}
a b c yaoshuyin

=======================================
//清除变量
$ unset A
$ echo ${A[@]}
$

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

//清空变量,即将值变为空
$ A=
$ echo ${A[@]}
$
=======================================

A=B
B=C
unset $A 事实上所取消的变量是 B 而不是 A
=================示例 while循环=============

#建立数组
arrSource=(“arrJobs.php” “arrSubHangye.php” “arrFirst.php” )

arrDest=(“buildhr” \
“buildtrain/htdocs” \
“bankhr” \
“healthr” \
“elehr” \
)

#取数组无元素个数
lenArrSource=${#arrSource
}
lenArrDest=${#arrDest
}
#循环列出数组元素
i=0
while [ $i -lt $lenArrSource ]
do
echo ${arrSource[$i]}
let i++
done
i=0
while [ $i -lt $lenArrDest ]
do

echo ${arrDest[$i]}
let i++
done
=======================示例: for循环=========

#源文件
arrSource=(“/home/800hr/htdocs/login_jump.php”)

#目标网站
arrDest=(ithr elehr buildhr bankhr healthr ctvhr chenhr mechr clothr cneduhr 56hr tourhr foodhr greenhr cnlawhr waimaohr)

for outer in ${arrSource
} #${arrSource
} 是数组中的所有元素
do
for inner in ${arrDest
}
do
echo “ln -s $outer /home/${inner}/campus/”
done
done


15
三 08

trap for shell

一. trap捕捉到信号之后,可以有三种反应方式:

(1)执行一段程序来处理这一信号

(2)接受信号的默认操作

(3)忽视这一信号

二. trap对上面三种方式提供了三种基本形式:

第一种形式的trap命令在shell接收到signal list清单中数值相同的信号时,将执行双

引号中的命令串。

trap ‘commands’signal-list

trap “commands” signal-list

为了恢复信号的默认操作,使用第二种形式的trap命令:

trap signal-list

第三种形式的trap命令允许忽视信号

trap ” ” signal-list

注意:

(1) 对信号11(段违例)不能捕捉,因为shell本身需要捕捉该信号去进行内存的转储。

(2) 在trap中可以定义对信号0的处理(实际上没有这个信号), shell程序在其终止(如

执行exit语句)时发出该信号。

(3) 在捕捉到signal-list中指定的信号并执行完相应的命令之后, 如果这些命令没有

将shell程序终止的话,shell程序将继续执行收到信号时所执行的命令后面的命令,这样将

很容易导致shell程序无法终止。

另外,在trap语句中,单引号和双引号是不同的,当shell程序第一次碰到trap语句时,

将把commands中的命令扫描一遍。此时若commands是用单引号括起来的话,那么shell不会

对commands中的变量和命令进行替换, 否则commands中的变量和命令将用当时具体的值来

替换。

在有些情况下,我们不希望自己的shell脚本在运行时刻被中断,比如说我们写得shell脚
本设为某一用户的默认shell,使这一用户进入系统后只能作某一项工作,如数据库备份, 我
们可不希望用户使用ctrl+C之类便进入到shell状态,做我们不希望做的事情。这便用到了信号
处理。

kill -l可以列出系统的信号名称,如下:
-bash-3.00# kill -l
1) SIGHUP    2) SIGINT    3) SIGQUIT   4) SIGILL
5) SIGTRAP   6) SIGABRT   7) SIGBUS    8) SIGFPE
9) SIGKILL   10) SIGUSR1   11) SIGSEGV   12) SIGUSR2
13) SIGPIPE   14) SIGALRM   15) SIGTERM   17) SIGCHLD
18) SIGCONT   19) SIGSTOP   20) SIGTSTP   21) SIGTTIN
22) SIGTTOU   23) SIGURG   24) SIGXCPU   25) SIGXFSZ
26) SIGVTALRM  27) SIGPROF   28) SIGWINCH  29) SIGIO
30) SIGPWR   31) SIGSYS   34) SIGRTMIN  35) SIGRTMIN+1
36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5
40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9
44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13
52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9
56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5
60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1
64) SIGRTMAX

-bash-3.00#
通常我们需要忽略的信号有四个,即:HUP, INT, QUIT, TSTP,也就是信号1, 2, 3, 24
使用这样的语句可以使这些中断信号被忽略:
trap “” 1 2 3 24 或 trap “” HUP INT QUIT TSTP
用 trap :1 2 3 24 或 trap HUP INT QUIT TSTP使其回复默认值。
用stty -a可以列出中断信号与键盘的对应,分别执行上面的命令后,运行
tail -f /etc/passwd, 然后尝试用键盘中断,试试两种情况(默认和忽略)下有何不同。
更方便的是我们可以用在shell中用trap定义我们自己的信号处理程序,就象在c中用
signal一样。

P.S.

2010-11-2

通常使用 kill 0 来杀掉所有子进程及自己。

 


14
三 08

while 循环中使用read

#!/bin/bash
while read line ; do
ehco  $line
done < file


6
十二 07

Shell产生随机数

BASH Shell中有一个用于生成随机数的变量:RANDOM

这个变量的值是不断变化的,每次echo $RANDOM都会得到不同的值,在shell角本中可以做为随机数使用。

从别人的脚本里得到的一个获得随机数的方法:
rand() {
dd if=/dev/urandom bs=1 count=4 2>/dev/null | od -t u4 | awk ‘NR=1{print $2}’
}


6
十二 07

加密shell脚本

shc是一个加密shell脚本的工具.它的作用是把shell脚本转换为一个可执行的二进制文件.

用shell脚本对系统进行自动化维护,简单,便捷而且可移植性好.

但shell脚本是可读写的,很有可能会泄露敏感信息,如用户名,密码,路径,IP等.

同样,在shell脚本运行时会也泄露敏感信息.

shc是一个加密shell脚本的工具.它的作用是把shell脚本转换为一个可执行的二进制文件.

这就很好的解决了上述问题.

shc的下载地址:

http://www.anyside.com/linux/shc-3.8.tgz

http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.tgz

安装:

tar zxvf shc-3.8.tgz
cd shc-3.8
make test
make
make test
make strings
make install 这一步需要root权限

使用方法:

shc -r -f script-name 注意:要有-r选项, -f 后跟要加密的脚本名.

运行后会生成两个文件,script-name.x 和 script-name.x.c

script-name.x是加密后的可执行的二进制文件.

./script-name 即可运行.

script-name.x.c是生成script-name.x的原文件(c语言)

设定期限:

首先使用shc转化为二进制,并加上过期时间,如

./shc -e 12/06/2006 -m “please contact jdaoyou@sohu.com” -r -f flushvpn.sh

我一般在程序中加入自动更新系统时间的命令,防止用户更改系统时间。

注:在使用的过程中遇到不少问题,运行并不是直分理想。