Archive for the ‘Linux&Unix’ Category

Linux常遇问题

星期六, 07月 19th, 2008

Linux常遇问题 
1.split分割合并文件

split -b1440k a_whopping_big_file chunk
cat chunk* > a_whopping_big_file
#####################################

2.wget下载整个网站

wget -t0 -c -nH -np -b -m -P /localdir http://freesoft.online.sh.cn/mirrors/ftp.redhat.com -o wget.log
#####################################
3.cp时显示进度

cp -r -v dir1 dir2
cp -a -d -v dir1 dir2
#####################################

4.ls重定向到多个文件

ls | tee 1.txt 2.txt 3.txt …..
#####################################

5.mail#Linux中命令行下发送带附件的邮件
方法1.    uuencode   | mail -s ”title” mail@address
 本地需要作为附件的文件名。
 邮件中的附件文件名,可以和不同,其实内容一样。
方法2.    cat  | mutt -s ”title” -a  mail@address
邮件正文内容。
本地需要作为附件的文件名。
####################################################

6.移动光标

echo -e ’33[20;10f’ 把光标移动到20行10列
###################################################

7.杀掉一类进程

ps -efww|grep LOCAL=NO|grep -v grep|cut -c 9-15|xargs kill -9
###################################################

8.查看部分文件

如果你只想看文件的前5行,可以使用head命令,
如:head-5/etc/passwd
如果你想查看文件的后10行,可以使用tail命令,
如:tail-10/etc/passwd
你知道怎么查看文件中间一段吗?你可以使用sed命令
如:sed-n’5,10p’/etc/passwd这样你就可以只查看文件的第5行到第10行。
###################################################

9.xmms字体设置

xmms -adobe-helvetica-medium-r-normal–12-*-*-*-*-*-iso8859-1,-misc-simsun-medium-r-normal–12-*-*-*-*-*-gbk-0,*-r-*
###################################################

10.mount应用
mount -t ntfs /dev/hda1 /mnt/c -o codepage=936,iocharset=gb2312
mount -t iso9660 -o iocharset=cp936,ro /dev/cdrom /mnt/cdrom
#######################################################

11. nslookup 域名 查看域名所指IP

12.setterm控制台下的屏幕截图

setterm -dump 1 用setterm程序来获得控制台下的屏幕截图,1 tty1
######################################################

13.mencoder图片做成电影
mencoder *.jpg -mf on:fps=15 -o output.avi -ovc xvid 图片做成电影
######################################################

14.ldconfig加入指定的联接库

echo ”/usr/local/lib” >> /etc/ld.so.conf
/sbin/ldconfig
######################################################

15.reset解决控制台乱码

终端乱码解决 reset    setterm -reset   cat /bin/bash
######################################################

16.合并多个pdf文件
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf f1.pdf f2.pdf f3.pdf  合并多个pdf文件
######################################################

gconftool-2 -s /desktop/gnome/url-handlers/http/command –type string ’opera ”%s”‘

17.find应用
find . -ctime +1 -ctime -7 -print 找到当前目录下1~7天以前的文件,
find ./ -type f -name ”*.mp3″ > playlist.lst
######################################################

18.wc应用

ls |wc -l 统计当前目录下的非隐藏目录和非隐藏文件的个数
ls -a |wc -l 统计当前目录下的所有文件和目录的个数实际数目
find ./ |wc -l 统计当前目录下的所有文件包括隐藏文件和文件夹
######################################################

19.制作grub图

convert -geometry 640×480 -colors 14 XXX.png XXX.xpm && gzip XXX.xpm    #grub
###################################################

20.应用tee
tee    tee:从标准输入中读取,向标准输出和其他文件中写入。
tee    (2)部分参数说明
tee    tee [-ai] [–append] [–ignore-interrupts] [–help]
tee    [–version] [文件名列表]
tee    -a, –append:将标准输入追加到输出文件的后面而不是缺省的覆盖它。
tee    -i, –ignore-interrupt:忽略中断信号。
tee    –help:在标准输出上输出帮助信息并退出。
tee    –version:在标准输出上输出版本信息并退出。

21. hdparm应用

hdparm -Tt /dev/hda    本帖最后由 bugkill 于 2005-11-6 12:00 编辑 ]

22.aa=`grep _GQAdd $1` 把命令结果传给一个变量

23. echo应用

echo ”abcdefg” | perl -lne ’{$a = reverse($_); print $a;}’ 把一个字符串翻转
echo bottle|rev 把一个字符串翻转

24. dd命令

dd    命令常常用来制作Linux启动盘。先找一个可引导内核,令它的根设备指向正确的根分区,然后使用dd命令将其写入软盘:
dd    $ rdev vmlinuz /dev/hda
dd    $dd if=vmlinuz of=/dev/fd0
dd    上面代码说明,使用rdev命令将可引导内核vmlinuz中的根设备指向/dev/hda,请把“hda”换成自己的根分区,接下来用dd命令将该内核写入软盘。

25.

sudo  shan ALL=/usr/local/pureftpd/sbin/pure-ftpwho,/usr/local/bin/mymount cdrom,/usr/local/bin/mymount -u cdrom      ALL  /etc/sudoer

26.iso

cp /dev/cdrom xxxx.iso  将光盘做成iso文件

27.memory应用

memory   grep MemTotal /proc/meminfo  看内存大小

mlterm   /etc/mlterm/termcap文件中xterm那一行(因为我的$TERM是xterm):
mlterm   [root@/etc/mlterm]# cat termcap
mlterm   mlterm:\
mlterm   kD=\E[3~:kb=^?
mlterm   xterm|rxvt:\
mlterm   kD=\E[3~:kb=^H:ut
mlterm   *:\
mlterm   kD=\e[3~

rm \.[^\.]* -r

xmms -*-*-*-*-*-iso8859-1,-misc-simsun-medium-r-normal–12-*-*-*-*-*-gbk-0,*-r-

28.rpm -q 软件名 显示软件包的版本信息  rpm –prefix=路径 -ivh 包名

29.rpm -qlp *.rpm 看看包里面有什么文件 which softwarename 查找应用程序路径

30. tar命令

tar -xjvf *.tar.bz2   tar xvfz *.tar.gz 解压
tar xvfzC *.tar.gz  path/ 解压到指定的目录(目录存在)
tar czvf *.tar.gz dirname  tar cvf *.tar dirname 压缩

31.rar 命令

rar a *.rar file-dir  压缩/加入压缩包 rar d  *.rar file 从包中删除文件
rar x *.rar 解压到当前目录保持目录结构,e不保持目录结构

32.du命令

du -s 显示当前目录所用空间
du -sh 只显示目录大小

33.mount -t iso9660 xxxxx.iso /any/path/if/u/like -o loop

34.grep string file 列出string所在行的内容?

35.alias newname=’command’命令的别名

36.mount -t vfat /dev/sda1 /mnt/usb -o codepage=936,iocharset=gb2312

37.fstab  /dev/hda1 /mnt/c vfat defaults,codepage=936,iocharset=gb2312 0 0

39.怎样编译mplayer
./configure –prefix=/usr/local/mplayer –enable-gui –libdir=/usr/local/mplayer/lib –language=zh –with-reallibdir=/usr/local/mplayer/lib/rp9codecs –with-win32libdir=/usr/local/mplayer/lib/win32codecs –enable-freetype

40.fcitx输入法

fcitx  export XMODIFIERS=@im=fcitx
fcitx  export XIM=fcitx
fcitx  export XIM_PROGRAM=fcitx
fcitx  export GTK_IM_MODULE=xim

opera  cn u-JhyKr-e8c7j-pQt7k-BrwaN-kMTmh

41.unzip

unzip  unzip ”*” 一次解压多个zip文件

42.

ifconfig  dhclient  动态IP
ifconfig  ifconfig eth0 down
ifconfig  ifconfig eth0 要抢的IP
ifconfig  ifconfig eth0 up
ifconfig  arping 网关

43.
perl  perl -p -i -e ”s/\\\/\\\\\\\/g” aa 把aa中\换为\\
perl  perl -p -i -e ”s/abcde/edbca/g” * 比如把目录中所有文件中都出现的“abcde”替
换成“edbca”
rpm  kernel2.65rpm不能运行
rpm  运行rpm之前先export LD_ASSUME_KERNEL=2.2.5

44.

chmod  改变文件或目录之读、写、执行之允许权
chmod  ====================================
chmod  执行格式:chmod [-R] mode name ( name 可为文件名或目录名;mode可为 3 个 8 位元之数字,或利用ls -l 命令,列出文件或目录之读、写、执行允许权之文字缩写。)
chmod  mode : rwx rwx rwx r:read w:write x:execute(user group other 缩写为: u g o)
chmod  Example :
chmod  % chmod 755 dir1 将目录dir1,设定成任何使用者,皆有读取及执行之权利,但只有拥有者可做修改。
chmod  % chmod 700 file1 将文件file1,设定只有拥有者可以读、写和执行。
chmod  % chmod o+x file2 将文件file2,增加拥有者可以执行之权利。
chmod  % chmod g+x file3 将文件file3,增加群组使用者可执行之权利。
chmod  % chmod o-r file4 将文件file4,除去其它使用者可读取之权利。

45.

chown  改变文件或目录之拥有权
chown  ======================
chown  执行格式:chown [-R] username name ( name 可为文件名或目录名。)
chown  Example :
chown  % chown user file1 将文件 file1 之拥有权,改为使用者 user 所有。
chown  % chown -R user dir1 将目录 dir1,及其下所有文件和子目录之拥有权,改为使用者 user 所有。

46.
groups  检查自己所属之群组名称
groups  ======================
groups  执行格式:groups
groups  Example :
groups  % groups

47.

chgrp  改变文件或目录之群组拥有权
chgrp  ==========================
chgrp  执行格式:chgrp [-R] groupname name ( name 可为文件名或目录名 )
chgrp  Example :
chgrp  % chgrp vlsi file1 将文件 file1 之群组拥有权,改为 vlsi 群组。
chgrp  % chgrp -R image dir1 将目录dir1,及其下所有文件和子目录,改为 image 群组。

48.

touch  改变文件或目录之最后修改时间(变为当前时间)
touch  =========================================
touch  执行格式:touch name ( name 可为文件或目录名称。)
touch  Example :
touch  % touch file1
touch  % touch dir1

49.

ln  文件之连结
ln  ==========
ln  同一文件,可拥有一个以上之名称,可将文件做数个连结。
ln  执行格式:ln oldname newname ( Hard link )
ln  Example :
ln  % ln file1 file2   将名称 file2,连结至文件 file1。
ln  执行格式:ln -s oldname newname ( Symblick link )
ln  Example :
ln  % ln -s file3 file4 将名称 file4,连结至文件file3。

50.

grep  文件之字串找寻
grep  ==============
grep  执行格式:grep string file
grep  Example :
grep  % grep abc file1 寻找文件file1中,列出字串 abc 所在之整行文字内容。

51.

find  找寻文件或命令之路径
find  ====================
find  执行格式:whereis command ( 显示命令之路径。)
find  执行格式:which command ( 显示命令之路径,及使用者所定义之别 )
find  执行格式:whatis command ( 显示命令功能之摘要。)
find  执行格式:find search-path -name filename -print ( 搜寻指定路径下,某文件之路径 )
find  Example :
find  % find / -name file1 -print ( 自根目录下,寻找文件名为 file1 之路径)

53.
比较文件或目录之内容
====================
执行格式:diff [-r] name1 name2 ( name1 name2 可同时为文件名,或目录名称 )
Example :
% diff file1 file2 比较文件 file1 与 file2 内,各行之不同处。
% diff -r dir1 dir2 比较目录 dir1 与 dir2 内,各文件之不同处。

54.
IP  如何实现为一个网卡绑定多个IP地址?
IP  ====================================
IP   Linux的网络设备配置文件存放在/etc/sysconfig/network-scripts里面,对于以太网的第一个网络设备,配置文件名一 般为 ifcfg-eth0 如果需IP  要为第一个网络设备绑定多一个IP地址,只需要在/etc/sysconfig/network- scripts目录里面创建一个名为ifcfg-eth0:0的文件,内容样例为:
IP  DEVICE=”eth0:0″
IP  IPADDR=”211.100.10.119″
IP  NETMASK=”255.255.255.0″
IP  ONBOOT=”yes”
IP  其中的DEVICE为设备的名称,IPADDR为此设备的IP地址,NETMASK为子网掩码,ONBOOT表示在系统启动时自动启动。
IP  如果需要再绑定多一个IP地址,只需要把文件名和文件内的DEVICE中的eth0:x加一即可。LINUX最多可以支持255个IP别名。

55.
login  如何设置login后欢迎信息
login  ====================================
login  修改/etc/motd,往里面写入文本,就能使用户通过telnet正确登录后执行shell之前得到相应的提示信息。
login  motd就是“messages of the day”,也就是当日信息的意思。管理员可以往里面写一些需要注意的事项或者通知等来提醒正式用户。

[ 本帖最后由 bugkill 于 2005-11-6 12:11 编辑 ]
login  如何设置login前欢迎界面
login  ====================================
login  修改/etc/issue或者issue.net,往里面写入文本,就能使得用户在login前得到相应的提示,这将有助于用户分辨自己正在连接哪里的主机。
login  issue的内容是出现在本机登录的用户界面上,而issue.net则是在用户通过网络telnet的时候出现。

bash  如何在bash下快速执行某个特定历史命令
bash  ====================================
bash  在bash下面按ctrl+r可以查找历史命令中匹配的命令并执行

如何查看进程继承关系
====================================
直接在命令行中输入
pstree
即可,程序会以树状结构方式列出系统中正在运行的各进程之间的继承关系。

ps  如何找出内存占用最大的进程
ps  ====================================
ps  除了可以使用top命令查看内存使用情况之外,还可以使用更快的命令行命令,相关的命令如下:
ps  ps aux | sort +4n
ps  或者
ps  ps aux | sort +5n

如何在Linux下面编辑二进制文件
====================================
http://freshmeat.net/redir/hexedit/4088/url_tgz/hexedit-1.2.3.src.tgz下载hexedit安装到系统上,就能用hexedit filename来编辑二进制文件。

如何设置用户密码过期时间
====================================
设置某个用户的密码过期时间可以用usermod -e来设置,如果要统一设置用户的密码过期时间,那么就要修改/etc/login.defs里面的PASS_MAX_DAYS,比如修改所有用户的密码过期时间是30天:
PASS_MAX_DAYS 30
如果这个值是99999,那么表示密码永不过期。

MAC  如何修改网卡MAC地址
MAC  ====================================
MAC  首先必须关闭网卡设备,否则会报告系统忙,无法更改。
MAC  命令是: /sbin/ifconfig eth0 down
MAC  修改 MAC 地址,这一步较 Windows 中的修改要简单。
MAC  命令是:/sbin/ifconfig eth0 hw ether 00:AA:BB:CC:DD:EE
MAC  重新启用网卡 /sbin/ifconfig eth0 up
MAC  网卡的 MAC 地址更改就完成了

bash  如何用Bash纠正错误命令
bash  ====================================
bash  当你输入一个命令不知道是否正确的时候,可以使用ctrl+t来纠正到正确的命令。
bash  比如输入mkdri,然后按ctrl+t,bash会帮你纠正到最接近的命令mkdir。

login  如何使非root用户都不能远程登录
login  ====================================
login  建立/etc/nologin文件,这样所有的非root用户都不能远程登录。

mesg  如何不显示其他用户的消息
mesg  ====================================
mesg  用户可以使用mesg n来禁止别人给他发送信息,其实就是禁止别人往自己的终端上面的写权限。当别人试图再使用write给他发送信息时,发送者将会看见提示:
mesg  write: user has messages disabled on pts/n

如何知道某个命令使用了什么库文件
====================================
例如要知道ls使用了什么库文件,可以使用:
$ ldd /bin/ls

swap  如何临时增加交换空间
swap  ====================================
swap  产生一个64M的空文件
swap  #dd if=/dev/zero of=/swapfile bs=1024 count=65536

swap  初始化该文件为交换文件:
swap  mkswap /swapfile 65536
swap  sync

swap  激活这个交换文件:
swap  swapon /swapfile

nohup  如何使一个用户进程在用户退出系统后仍然运行
nohup  ====================================
nohup  使用nohup command &,比如:
nohup  nohup wget -c ftp://test.com/test.iso
nohup  这样即使用户退出系统,wget进程仍然继续运行直到test.iso下载完成为止

login  如何限制用户的最小密码长度
login  ====================================
login  修改/etc/login.defs里面的PASS_MIN_LEN的值。比如限制用户最小密码长度是8:
login  PASS_MIN_LEN 8
login  这样用户设置密码的时候如果输入的密码长度小于8将不能设置

login  如何限制只有0组(gid=0)的用户可以su成root
login  ====================================
login  修改/etc/login.defs里面的SU_WHEEL_ONLY的值为:
login  SU_WHEEL_ONLY yes
login  那么就只有gid为0的用户可以su成root。

ctrlaltdel  如何禁用Ctrl+Alt+Del键重启系统
ctrlaltdel  ====================================
ctrlaltdel  有时候为了防止误操作导致系统重新启动(如机房里面新来了个习惯用Window$系统的管理员:-D),或者出于安全的原因,需要禁用Ctrl+Alt+Del组合键。
ctrlaltdel  只需要注释掉/etc/inittab文件内的
ctrlaltdel  ca::ctrlaltdel:/sbin/shutdown -t3 -r now
ctrlaltdel  这一行即可。如何注释?在这一行的行首放一个“#”号即可。

format  怎么样格式化磁盘
format  ====================================
format  Linux下有一条mkfs命令,相当于format,可以对磁盘进行文件系统制作操作(或者说格式化)。命令的语法为:
format  mkfs -t 文件系统类型 /dev/设备名
format  如要把/dev/sda1格式为reiserfs格式,使用以下命令:
format  mkfs -t reiserfs /dev/sda1
format  当然,也可以使用mkfs.fstype命令来格式化磁盘,其中的fstype为文件系统名,如reiserfs文件系统的格式化命令为mkfs.reiserfs。上面那条命令的相应版本为:
format  mkfs.reiserfs /dev/sda1

如何取消root命令历史记录以增加安全性
====================================
为了设置系统不记录每个人执行过的命令,就在/etc/profile里设置:
HISTFILESIZE=0
HISTSIZE=0
或者:
ln -s /dev/null ~/.bash_history
这样就可以了。

ftp  如何使用netrc文件进行自动ftp
ftp  ====================================
ftp  在自己的home目录下建立一个权限600,名为.netrc的文件,内容是:
ftp  machine 192.168.0.1 login test password test
ftp  这样以后你每次ftp 192.168.0.1的时候,系统都会帮你以用户名test,密码test登录。
ftp  利用这个特征可以实现自动ftp。
ftp  例如你想要每天5:00到192.168.0.1机器上面获得/test目录下的文件test.txt,可以这么做:
ftp  建立一个文件ftp_cmd,内容为:
ftp  cd test
ftp  get test.txt
ftp  bye
ftp  然后使用crontab -e设置定时任务:
ftp  0 5 * * * ftp 192.168.0.1

mount  floppy -fstype=vfat :/dev/fd0
mount  e2floppy -fstype=ext2 :/dev/fd0
mount  注:
mount  a.确保/dev/cdrom作为符号链接指向你的光驱所在的分区,作为我的情况:
mount  [jephe@sh3 /dev]$ ls cdrom -l
mount  lrwxrwxrwx 1 root root 3 Aug 26 08:44 cdrom -> hdd
mount  b.当软盘为windows 95格化化的vfat分区类型时,设定了安装目录/misc/floppy
mount  c.当软盘为Linux格式化过的ext2分区类型时,设定了安装目录/misc/e2floppy

mount  至此,若还未启动autofs,则运行/etc/rc.d/init.d/autofs start, 若对上述两个文件中做过任何更改,运行/etc/rc.d/init.d/autofs restart即可。

mount   放入一片光盘进入光驱后,不需任何动作,直接进入目录/misc/cdrom,autofs 将自动先为你mount光驱同样,若放入一张vfat格式的 软盘,你可以cd /misc/floppy,若是ext2格式的软盘,则cd /misc/e2floppy。
mount  在超过一分钟未使用它们,且当前目录不是自动mount目录/misc/cdrom,/misc/floppy,/misc/e2floppy,系统将自动umount它们。

rename  批量重命名
rename  =================================
rename  for i in /root/mud/*.C; do mv $i ${i%.C}.c; done

cron 计划任务
====================================
简介
crontab-操作每个用户的守护程序和该执行的时间表。

部分参数说明
crontab file [-u user]-用指定的文件替代目前的crontab。
crontab-[-u user]-用标准输入替代目前的crontab.
crontab-1[user]-列出用户目前的crontab.
crontab-e[user]-编辑用户目前的crontab.
crontab-d[user]-删除用户目前的crontab.
crontab-c dir- 指定crontab的目录。
crontab文件的格式:M H D m d cmd.
M: 分钟(0-59)。
H:小时(0-23)。
D:天(1-31)。
m: 月(1-12)。
d: 一星期内的天(0~6,0为星期天)。
cmd要运行的程序,程序被送入sh执行,这个shell只有USER,HOME,SHELL这三个环境变量。

下面是一个例子文件:
#MIN HOUR DAY MONTH DAYOFWEEK COMMAND
#每天早上6点10分
10 6 * * * date
#每两个小时
0 */2 * * * date
#晚上11点到早上8点之间每两个小时,早上8点
0 23-7/2,8 * * * date
#每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点
0 11 4 * mon-wed date
#1月份日早上4点
0 4 1 jan * date
范例
$crontab -l 列出用户目前的crontab.
#MIN HOUR DAY MONTH DAYOFWEEK COMMAND
10 6 * * * date
0 */2 * * * date
0 23-7/2,8 * * * date

如何在Linux里面恢复mbr?
====================================
可以使用下面的命令来恢复:
dd if=/boot/boot.NNNN of=/dev/hda bs=446 count=1
其中bs(buffer size)是指重写的字节数。为什么不是512呢?主引导扇区是一个扇区(512字节)呀?答案是因为我们用上面的命令是为了 修复可能被病毒修改了的主引导记录MBR,或者想把LILO卸载掉,而不是恢复整个主引导扇区。所以我们只把主引导扇区的备份文件boot.NNNN的前 446个字节重写入主引导扇区。boot.NNNN是我们在安装Linux之前整个主引导分区的备份。如果我们把512个字节全部写入主引导扇区就可能会 把安装了Linux后改变了的硬盘DPT表也破坏掉。那就坏事了。 :-)

如何列出一个目录占用的空间
====================================
du或du -s或du -k
du -S | sort -n 可以迅速发现那个目录是最大的。

用df可以看到已安装的文件系统的空间大小及剩余空间大小。

quota -v查看用户的磁盘空间信息,如果你用quota限制了用户空间大小的话。

在使用less 或 more时,如何直接启动编辑器
====================================
在less或者more中打入v键,会立即启动vi编辑器,可以对文件进行编辑

如何察看你当前使用的Linux内核的版本
====================================
可以使用uname -r来查看当前内核版本。如果使用uname -a可以查看包括内核版本,机器硬件信息、网络节点名、操作系统名字等信息

如何显示文件的类型
====================================
用命令 file 可以使你知道某个文件究竟是ELF格式的可执行文件, 还是shell script文件或是其他的什么格式 例如:
#file startx

如何将man page转成HTML格式
====================================
使用 man2html 这个指令,就可以将 man page 转成 HTML 格式了。用法是:
man2html filename > htmlfile.html
例子:
man2html /usr/man/man1/man2html.1 > ~/man2html.html

查看文件内容的特殊方法
====================================
相信最基本的cat和less你已经很熟悉了,如果有特殊的要求呢:
如果你只想看文件的前5行,可以使用head命令,如:
head -5 /etc/passwd

如果你想查看文件的后10行,可以使用tail命令,如:
tail -10 /etc/passwd
tail -f /var/log/messages
参数-f使tail不停地去读最新的内容,这样有实时监视的效果,当你在ppp拨号的过程中用它岂不是很方便!

查看文件中间一段,你可以使用sed命令,如:
sed -n ’5,10p’ /etc/passwd
这样你就可以只查看文件的第5行到第10行。

linux下文件分割与合并
====================================
$dd if=source of=target.1 bs=1M count=10
$dd if=source of=target.2 bs=1M skip=10
source被分为target.1和target.2两个文件,其中target.1为source的前10M部分;target.2为source的减去10M后的部分。
$cat target.1 target.2 > othersource
source与othersource是同一个文件。

color  RedHat下如何显示彩色目录列表
color  ====================================
color  打开/etc/bashrc, 加入如下一行:
color  alias ls=”ls –color”
color  下次启动bash时就可以像在Slackware里那样显示彩色的目录列表了, 其中颜色的color含义如下:
color  蓝色–>目录
color  绿色–>可执行文件
color  红色–>压缩文件
color  浅蓝色–>链接文件
color  灰色–>其他文件

什么是Linux 运行级?
====================================
什么是运行级呢?简单的说,运行级就是操作系统当前正在运行的功能级别。这个级别从1到6,具有不同的功能。这些级别在/etc/inittab文件里指定。这个文件是init程序寻找的主要文件,最先运行的服务是那些放在/etc/rc.d 目录下的文件。
不同的运行级定义如下:(可以参考Red Hat Linux 里面的/etc/inittab)
# 缺省的运行级,RHS 用到的级别如下:
# 0 - 停机(千万不要把initdefault 设置为0 )
# 1 - 单用户模式
# 2 - 多用户,但是没有 NFS
# 3 - 完全多用户模式
# 4 - 没有用到
# 5 - X11
# 6 - 重新启动 (千万不要把initdefault 设置为6 )

对各个运行级的详细解释:
0 为停机,机器关闭。
1 为单用户模式,就像Win9x 下的安全模式类似。
2 为多用户模式,但是没有NFS 支持。
3 为完整的多用户模式,是标准的运行级。
4 一般不用,在一些特殊情况下可以用它来做一些事情。例如在笔记本电脑的电池用尽时,可以切换到这个模式来做一些设置。
5 就是X11,进到Xwindow系统了。
6 为重启,运行init 6机器就会重启。
不同的运行级有不同的用处,也应该根据自己的不同情形来设置。例如,如果丢失了root 口令,那么可以让机器启动进入单用户状态来设置。在启动后的 lilo 提示符下输入:
init=/bin/sh rw
就可以使机器进入运行级1 ,并把root文件系统挂为读写。他会跳过所有系统认证,让你使用passwd 程序来改变root口令,然后启动到一个新的运行级。

系统平均负载(Load average)释疑
====================================
在Linux系统中,uptime、w、top等命令都会有系统平均负载load average的输出,那么什么是系统平均负载呢?
系统平均负载被定义为在特定时间间隔内运行队列中的平均进程树。如果一个进程满足以下条件则其就会位于运行队列中:
- 它没有在等待I/O操作的结果
- 它没有主动进入等待状态(也就是没有调用’wait’)
- 没有被停止(例如:等待终止)
例如:
[root@www2 init.d]# uptime
7:51pm up 2 days, 5:43, 2 users, load average: 8.13, 5.90, 4.94
命令输出的最后内容表示在过去的1、5、15分钟内运行队列中的平均进程数量。
一般来说只要每个CPU的当前活动进程数不大于3那么系统的性能就是良好的,如果每个CPU的任务数大于5,那么就表示这台机器的性能有严重问题。对于 上面的例子来说,假设系统有两个CPU,那么其每个CPU的当前任务数为:8.13/2=4.065。这表示该系统的性能是可以接受的。

ps 如何以树状结构显示系统当前的任务
ps ====================================
ps   运行ps时指定-forest选项,当前运行的进程将会以树状格式显示出来。比如:所有由xserver运行的程序,将会以xserver做为它们的“根”显示出ps 来。
ps 命令格式:
ps   ps afx
ps   其中’a’表示列出所有运行的进程;’x’列出所有的后台进程;’f’是’-forest’的缩写。输出的格式如下:
ps   329 ? SW 0:00 [wdm]
ps   342 ? R 9:57 \_ /usr/X11R6/bin/X :0 vt7 -fbbpp 16 -auth /usr/etc/
ps   343 ? SW 0:00 \_ [wdm]
ps   364 ? S 0:45 \_ /usr/bin/enlightenment
ps   399 ? S 0:00 \_ /usr/bin/ssh-agent sh /home/tuneup/.xse
ps   404 ? S 2:28 \_ gkrellm -wm
ps   787 ? S 0:05 \_ aterm -fg white -tr
ps   788 ttyp0 SW 0:00 \_ [bash]
ps   792 ttyp0 S 0:00 \_ vim todo

ps  注:另外一种得到格式化输出结果的方法是:pstree -pu

列目录时如何显示中文文件名
====================================
我们可以使用–show-control-chars命令选项来显示。
例如:
$ls –show-control-chars
以通过修改fstab来实现,在fstab中加入类似内容:
fstab  /dev/hda1 /mnt/c vfat defaults,codepage=936,iocharset=cp936 0 0

查询你的CPU等级
====================================
cat /proc/cpuinfo

如何使用户没有telnet和ftp权限
====================================
若只希望用户没telnet权限,则需要修改/etc/passwd中对应该用户的shell为/bin/true。
若只希望用户没有telnet和ftp权限,则需要修改/etc/passwd中对应该用户的shell为/bin/false。

如何连续执行一个命令
====================================
使用watch命令,可以反复执行命令,如果和ls配合,可以达到观察某文件大小变化的效果。例如:
$watch ls -l file.name

如何防止某个关键文件被修改
====================================
在linux下,有些配置文件是不允许任何人包括root修改的,为了防止被误删除或修改,可以设定该文件的”不可修改位(immutable)”。
例如:
chattr +i /etc/fstab
如果需要修改文件则:
chattr -i /etc/fstab
以后再修改文件。

linux环境下如何undelete
====================================
先在自己的主目录下创建一个名为.trash的子目录,然后在bashrc加入以下指令:
alias rm ’mv -f !* ~/.trash’
alias undel ’mv ~/.trash/!* ./!*’
alias cleantrash ’/bin/rm -rf ~/.trash; mkdir ~/.trash;sync’
alias lrm ’ls ~/.trash’
若文档是直接用rm命令删除的,理论上 ext2 内 rm 掉的档案还是可以用 debugfs , ext2ed 救回来的.当然… 被 overwrite 掉就没救了。

find  如何找出磁盘中某个大小范围内的文件
find  ====================================
find  比如要查找磁盘中大于3M的文件:
find  find . -size +3000k -exec ls -ld {} ;

如何快速重新执行已经执行过的命令
====================================
使用!可以实现该功能,例如你前面执行了很多命令,现在突然想执行上一次执行的./configure命令,则只需要输入“!./con”即可而无需使用上下键来滚动查找。
而!!则能代替前面一个命令。比如刚执行过一次ifconfig,输入“!!”则等于再执行一次ifconfig。
而且这两个用法可以和其他命令组合,比如你刚执行过ifconfig,然后执行man !!,就等于执行man ifconfig。

当终端出现混乱时,如何让它恢复正常
====================================
当使用stty命令而出现一些混乱或者更糟的是,使用一个程序而使终端设置完全混乱了时怎么办?要回到“现实”,试试下面的命令:
stty sane
如果击键变得混乱时,试着用来把命令括起来,输入的顺序是先按下CTRL再键入j键。
ctty sane
这个命令不会回到先前的设置,但却可以去除一些稀奇古怪的设置。而真正会出现什么设置要依赖于所使用的系统,但它至少会让你能输入字符,并见到结果。从这里开始,你可以把一些组合键设置为你所喜欢的方式。

tar  如何将.gz文件分割为数个1.44mb
tar  ====================================
tar  把一个文件分割到软盘:
tar  tar cfvm /dev/fd0 file.tar.gz
tar  把软盘上的文件合并到硬盘:
tar  tar xvfm /dev/fd0

如何一次处理一整个目录
====================================
Linux/UNIX 的很多常用命令如 rm , cp 等都有一个参数—- -r , 是递归的意思, 命令里加了参数 -r 就可以对目标目录及其下所有子目录进行操作,如:
rm -rf /test (f 是 force 意为强行)
该命令完全删除根目录下的子目录 test ,作用类似于 dos 下的 deltree ,当然使用这个命令时要特别小心。再如:
cp -r /test /test1
有类似 dos 下 xcopy /s 的作用。

redhat下如何允许root通过telnet登录?
====================================
方法1:/etc/securetty ( 加入 pts/0 、pts/1、…)
# echo ”pts/0″ >> /etc/securetty
方法2:为了在redhat linux系统中激活远程登陆,从文件/etc/pam.d/login中移去下面这一行:
auth required /lib/security/pam_security.so
将/etc/securetty这个文件改名就行啦,该文件是定义root只能在tty1~tty6的终端上登录的,详细的信息可以”man login”。

reboot  Linux正常重新启动的方法有很多种,下面介绍几种常用的重新启动方法:
reboot  ====================================
reboot  Ctrl+Alt+Del
reboot  #init 6
reboot  #shutdown -r now
reboot  #reboot

为什么我的linux不允许普通用户登录?
====================================
以root的身份登录系统,检查是不是有/etc/nologin这个文件,删除这个文件,然后再以普通用户的身份登录。相信问题已经解决。
出现这种问题一般是因为系统在关闭的过程中意外中断了操作,如断线或者是插头被拔了之类的意外。而系统在关闭的过程中会自动的产生这个文件,以便通知用户系统正在关闭这就造成普通用户无法登录了。
另外一种原因是系统管理员在对系统进行维护,为了维护的过程中不受其他用户的影响,需要生成这个文件来禁止其他用户登录。但很不幸系统管理维护完以后忘记删除这个文件了。

chown  如何改变当前路径下所有目录和文件的所有权
chown  ====================================
chown  改变所有子目录及文件的所有权
chown  #chown -R owner[.group] *
chown  也可以用find命令来实现:
chown  #find . -exec chown owner[.group] {} ;

改变所有子目录及文件的属性
在你要改变属性的目录下,输入命令:
#chmod -R 777 *
就可以改变下面所有子目录及文件的属性,不过使用这个命令的时候要特别小心,要是在根目录下打入这个命令,你所有文件的属性都将改变,这就会引起很大的安全性问题。

如何快速查找文件
====================================
查找文件可以用find,但最好是用locate,速度快,参数少。
$locate filename
它是在一个数据库里面查找,所以,要记得经常用updatedb命令更新数据库。一般地,在crontab中的cron.daily脚本会执行/usr/sbin/logrotate /etc/logrotate.conf命令,让机子在每天深夜更新数据库。

如何将Linux或FreeBSD复制到另一颗硬盘 ?
====================================
Linux上的系统复制很简单,使用cp -ax将partition资料复制过去,重开机後设定lilo就可以了。
FreeBSD也可以用cp来复制文档,但是对于复制整个文档系统并不是好方法。
这里介绍使用dump和restore来做:

创建新的文档系统
假如你的新硬盘为ad1, 而将来的根分区将是ad1s1a, 你可以先创建文档系统:
newfs /dev/ad1s1a
mount /dev/ad1s1a /mnt
cd /mnt

复制:
dump -f- / | restore -f- -r
这是把老的根文档系统复制输出到管道,restore从管道里读数据,写入当前目录所在的文档系统。

按部就班复制其他文档系统
复制完後,也许 要修改新硬盘下的/etc/fstab,安装上新的分区,摘下老硬盘就可以了。
再补充一点,如果你要复制的是另外一台机器,可以用rsh,这样就可以通过网络把一个分区数据传送到另外一台机器,不需要NFS,不需SAMBA等就可以解决问题,而cp就很难作到了。
newfs /dev/ad1s1a
mount /dev/ad1s1a /mnt
cd /mnt
rsh -l yourname thathost ’dump -f- /’ | restore -f- -r

linux怎么给一个普通用户reboot权限?
====================================
分四种情况讨论:
1.让任何人(包括根本不拥有系统帐号的人)都可以通过控制台reboot
在/etc/inittab文件中保留ca::ctrlaltdel:/sbin/shutdown -t3 -r now
这一行。这样全国人民都可以reboot你的机器,只要你把控制台交出来。

2.让所有系统用户都可以reboot
执 行# > /etc/security/console.apps/reboot即可。这就在console.apps目录下生成了一个空文件,文 件名就是授权的application。以上路径是针对Mandrake系统而言的,其他系统我不清楚。不过,真正高雅的Mandraker或许根本就不 会去靠“>”来生成这个文件??????他们会使用msec来进行控制的。

3.让指定的用户才可以reboot
假设我们要让用户zhizunbao拥有reboot的权限,我们靠uid/gid来完成控制:
# groupadd reboot
# cd /usr/local
# mkdir reboot
# chown root:reboot reboot/
# chmod 750 reboot/
# cd reboot
# cp /sbin/reboot .
# chmod 4755 reboot
# usermod -G reboot zhizunbao

现在,zhizunbao就可以运行/usr/local/reboot/reboot来重启动机器。

4.在一台不设普通用户的机器上启用口令验证reboot
这实际上是靠添加一个关机帐号来实现的,该帐号的shell就是加了s位的/sbin/halt,并且口令只有少数维护人员知道。我们这里采用的就是第4套方案。

怎样知道自己的机器上有哪些服务在运行
====================================
若一台机器运行有很多不需要的服务,那么被攻击者入侵的可能性就会大大加大,因此作为管理员就应该经常查看系统运行有哪些服务。
首先查看系统运行的进程
若需要查看系统当前运行的所有进程,就需要用如下命令:
# ps auxw
其中参数a表示显示系统中所有用户的的进程;u表示输出进程用户所属信息;x表示也显示没有控制台的进程;若显示行太长而被截断则可以使用f参数;
查看系统监听的服务
# netstat -ln
l表示显示当前系统监听的端口信息;n表示端口按照端口号来显示,而不转换为service文件中定义的端口名;若希望了解各个端口都是由哪些进程监听则可以使用p参数。
若发现不需要的服务,可以使用linuxconf或ntsysv命令来关闭这些服务在系统启动时自启动,然后重新启动系统则这些服务将在运行。
有些服务是由inetd超级服务器来监控的,则需要标记/etc/inetd.conf来关闭这些服务。

查询端口对应的服务
====================================
# lsof -i :端口号
查询此端口对应的服务。

vi 中设置自动缩进
====================================
:set autoindent
:set ai
取消
:set noautoindent
:set noai

如何使linux系统对ping不反应
====================================
在linux里,如果要想使ping 没反应也就是用来忽略icmp包。可以用:
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all
若想恢复就用:
echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all

如何实现多网卡bondin
====================================
使用多块网卡虚拟成为一块网卡,具有相同的IP地址。这项技术其实在sun和cisco中已经存在,分别称为Trunking和etherchannel技术,在Linux中,这种技术称为bonding。
因为bonding在内核2.4.x中已经包含了,只需要在编译的时候把网络设备选项中的Bonding driver support选中就可以了。
然后,重新编译核心,重新起动计算机,执行如下命令:
ismod bonding
ifconfig eth0 down
ifconfig eth1 down
ifconfig bond0 ipaddress
ifenslave bond0 eth0
ifenslave bond0 eth1
现在两块网卡已经象一块一样工作了.这样可以提高集群节点间的数据传输.
你最好把这几句写成一个脚本,再由/etc/rc.d/rc.local调用,以便一开机就生效.
bonding对于服务器来是个比较好的选择,在没有千兆网卡时,用两三块100兆网卡作bonding,可大大提高服务器到交换机之间的带宽.但是需要在交换机上设置连接bonding网卡的两个口子映射为同一个虚拟接口。

Removing ^M from file
======================================================
if you have transferred a file from MS Windows to UNIX, you might find that the file looks like this:
bleh bleh ^M
leh leh ^M
tey tey tey^M
This is because Windows uses carridge return and newline to indicate a new line.
Here are a number of ways to get rid of the ^M characters:
1- cat filename1 | tr -d ”^V^M” > newfile
2- sed -e ”s/^V^M//” filename > outputfilename
where ^V is actually control-V and ^M is actually control-M (you must type these yourself, don’t just copy and paste this command from this web page)
3-vi solution : open file with vi
1. hit the ESC key
2. :%s/^V^M//
3 - some distributions contain a command called dos2unix which removes these carridge return characters
4- use the texteditor vim (www.vim.org) and edit the file. If all the lines (not only some) contain consistently the carridge return characters then vim will show [textmode] and when you change the mode with the command
:set notextmode
it will remove them.

Create /dev/null
====================================
I have moved a file to /dev/null and now my system doesn’t work
If you move a file with the mv command to ”/dev/null” then it will be overwritten with an ordinary file.
How to fix it:
Boot your system. If it doesn’t boot take a one disk distribution like Toms rtbt and mount your /dev/hdXX partition.
Now type in a shell ”mknod /dev/null c 1 3″ to create a nod file. /dev/null is the path where the nod file will be saved. The c stands for a character device and the two numbers are the major and the minor numbers for the null device.
After that you must change with ”chmod 666 /dev/null” the read, write and execute permissions.
With ”ls -alF /dev/” you will see all nod files with it’s own three parameters like
“crw-rw-rw- 1 root root 1, 3 Oct 4 11:34 null ”.
You will see a ”c” in the near of the rwx flags an a ” 1, 3″ left of the date.

Howto log in to your server passwordless via ssh ( rsa version )
====================================
Create your private and public keys via ssh-keygen program
$ ssh-keygen
Computing keys
Testing the keys..
Key generation complete..
Enter the file in which to save the key (/usr/home/murat/.ssh/identity)
Press enter for the default value…
Your identification has been saved in /usr/home/murat/.ssh/identity
Your public ket is:
blah….blah…blah….
Your public key has been saved in /usr/home/murat/.ssh/identity.pub
Now that we have created our `public` key, take your
public key which is ~/.ssh/identity.pub to your server,
in the ~/.ssh/ directory, create a file named authorized_keys
and append the content of identity.pub file to your authorized_keys file
now, in your machine, type
$ ssh -l username your_remote_machine.domain.com
Boom, no password, no headache, you’re in the other side…;)

Blocking anyone to su to root
====================================
The su (Substitute User) command allows you to become other existing
users on the system. For example you can temporarily
become ”root” and execute commands as the super-user ”root”. If
you don’t want anyone to su to root or restrict ”su” command to
certain users then add the following two lines to the top of
your ”su” configuration file in the ”/etc/pam.d/” directory.
1- Edit the su file (vi /etc/pam.d/su) and add the following two
lines to the top of the file:
auth sufficient /lib/security/pam_rootok.so debug
auth required /lib/security/pam_wheel.so group=wheel
After adding the two lines above, the ”/etc/pam.d/su” file should
look like this:
#%PAM-1.0
auth sufficient /lib/security/pam_rootok.so debug
auth required /lib/security/pam_wheel.so group=wheel
auth required /lib/security/pam_pwdb.so shadow nullok
account required /lib/security/pam_pwdb.so
password required /lib/security/pam_cracklib.so
password required /lib/security/pam_pwdb.so shadow use_authtok nullok
session required /lib/security/pam_pwdb.so
session optional /lib/security/pam_xauth.so
Which means only those who are a member of the ”wheel” group can su to root;
and to add a user to wheel group use:
root# usermod -G10 username
Ok, now everybody can not be root using su. When an user that is not in wheel group runs su command ,he/she can not be root even if he/she writes correct root password.

Disable reboot,halt ,shutdown for users
====================================
On Redhat
[root@apache /]# rm -f /etc/security/console.apps/halt
[root@apache /]# rm -f /etc/security/console.apps/poweroff
[root@apache /]# rm -f /etc/security/console.apps/reboot
[root@apache /]# rm -f /etc/security/console.apps/shutdown
[root@apache /]# rm -f /etc/security/console.apps/xserver (if removed, root will be the only user able to start x).

mkdir -p rep1/rep2/rep3 一次建多个目录

rm -rf /tmp/.??* /tmp/* 删除所有文件,包括隐藏文件
You can put this into /etc/rc.d/init.d/syslog into the ”stop)” section. This will clean up /tmp at every shutdown and keep your disk tidy.
Do not run the above command while running X11 or before you run startx. X11 needs the /tmp/.font-unix which is created by xfont server and X11 it self creates the directory /tmp/.X11-unix which is needed to talk to the X11 windows.

1、BIOS的安全设置

这是最基本的了,也是最简单的了。一定要给你的BIOS设置密码,以防止通过在BIOS中改变启动顺序,而可以从软盘启动。这样可以阻止别有用心的试图用特殊的启动盘启动你的系统,还可以阻止别人进入BIOS改动其中的设置,使机器的硬件设置不能被别人随意改动。

2、LILO的安全设置

LILO是LInux

LOader的缩写,它是LINUX的启动模块。可以通过修改“/etc/lilo.conf”文件中的内容来进行配置。在 /etc/lilo.conf文件中加如下面两个参数:restricted,password。这三个参数可以使你的系统在启动lilo时就要求密码验 证。

第一步:编辑lilo.conf文件(vi /etc/lilo.comf),假如或改变这三个参数:
boot=/dev/hda
map=/boot/map
install=/boot/boot.b
prompt
timeout=00 #把这行该为00,这样系统启动时将不在等待,而直接启动LINUX
message=/boot/message
linear
default=linux
restricted #加入这行
password= #加入这行并设置自己的密码

image=/boot/vmlinuz-2.4.2-2
label=linux
root=/dev/hda6
read-only

第二步:因为”/etc/lilo.conf”文件中包含明文密码,所以要把它设置为root权限读取。
# chmod 0600 /etc/lilo.conf

第三步:更新系统,以便对“/etc/lilo.conf”文件做的修改起作用。
# /sbin/lilo -v

第四步:使用“chattr”命令使”/etc/lilo.conf”文件变为不可改变。
# chattr +i /etc/lilo.conf

这样可以在一定程度上防止对“/etc/lilo.conf”任何改变(意外或其他原因)

3、让口令更加安全

口令可以说是系统的第一道防线,目前网上的大部分对系统的攻击都是从截获口令或者猜测口令开始的,所以我们应该选择更加安全的口令。
首先要杜绝不设口令的帐号存在。这可以通过查看/etc/passwd文件发现。例如,存在的用户名为test的帐号,没有设置口令,则在/etc/passwd文件中就有如下一行:
test::100:9::/home/test:/bin/bash

其第二项为空,说明test这个帐号没有设置口令,这是非常危险的!应将该类帐号删除或者设置口令。
其 次,在旧版本的linux中,在/etc/passwd文件中是包含有加密的密码的,这就给系统的安全性带来了很大的隐患,最简单的方法就是可以用暴力破 解的方法来获得口令。可以使用命令/usr/sbin/pwconv或者/usr/sbin/grpconv来建立/etc/shadow或者 /etc/gshadow文件,这样在/etc/passwd文件中不再包含加密的密码,而是放在/etc/shadow文件中,该文件只有超级用户 root可读!

第三点是修改一些系统帐号的Shell变量,例如uucp,ftp和news等,还有一些仅仅需要FTP功能的 帐号,一定不要给他们设置/bin/bash或者/bin/sh等Shell变量。可以在/etc/passwd中将它们的Shell变量置空,例如设为 /bin/false或者/dev/null等,也可以使用usermod -s /dev/null username命令来更改username的 Shell为/dev/null。这样使用这些帐号将无法Telnet远程登录到系统中来!

第四点是修改缺省的密码长度:在你安装linux时默认的密码长度是5个字节。但这并不够,要把它设为8。修改最短密码长度需要编辑login.defs文件(vi/etc/login.defs),把下面这行
PASS_MIN_LEN 5
改为
PASS_MIN_LEN 8
login.defs文件是login程序的配置文件。

4、自动注销帐号的登录

在unix系统中root账户是具有最高特权的。如果系统管理员在离开系统之前忘记注销root账户,那将会带来很大的安全隐患,应该让系统会自动注 销。通过修改账户中“TMOUT”参数,可以实现此功能。TMOUT按秒计算。编辑你的profile文件(vi /etc/profile),在 “HISTFILESIZE=”后面加入下面这行:
TMOUT=300

300,表示300秒,也就是表示5分钟。这样,如果系统中登陆的用户在5分钟内都没有动作,那么系统会自动注销这个账户。你可以在个别用户的“.bashrc”文件中添加该值,以便系统对该用户实行特殊的自动注销时间。

改变这项设置后,必须先注销用户,再用该用户登陆才能激活这个功能。

5、取消普通用户的控制台访问权限

你应该取消普通用户的控制台访问权限,比如shutdown、reboot、halt等命令。
# rm -f /etc/security/console.apps/
是你要注销的程序名。

6、取消并反安装所有不用的服务

取消并反安装所有不用的服务,这样你的担心就会少很多。察看“/etc/inetd.conf”文件,通过注释取消所有你不需要的服务(在该服务项目之前加一个“#”)。然后用“sighup”命令升级“inetd.conf”文件。

第一步:

更改“/etc/inetd.conf”权限为600,只允许root来读写该文件。
# chmod 600 /etc/inetd.conf

第二步:

确定“/etc/inetd.conf”文件所有者为root。

第三步:

编辑 /etc/inetd.conf文件(vi /etc/inetd.conf),取消下列服务(你不需要的):ftp, telnet,  shell, login, exec, talk, ntalk, imap, pop-2, pop-3, finger, auth等等。把不需 要的服务关闭可以使系统的危险性降低很多。

第四步:

给inetd进程发送一个HUP信号:
# killall -HUP inetd

第五步:

用chattr命令把/ec/inetd.conf文件设为不可修改,这样就没人可以修改它:
# chattr +i /etc/inetd.conf

这样可以防止对inetd.conf的任何修改(以外或其他原因)。唯一可以取消这个属性的人只有root。如果要修改inetd.conf文件,首先要是取消不可修改性质:
# chattr -i /etc/inetd.conf

别忘了该后再把它的性质改为不可修改的。

7、TCP_WRAPPERS

使用TCP_WRAPPERS可以使你的系统安全面对外部入侵。最好的策略就是阻止所有的主机(”/etc/hosts.deny”文件中加入 “ALL: ALL@ALL, PARANOID” ),然后再在”/etc/hosts.allow” 文件中加入所有允许访问的主机列表。

第一步:

编辑hosts.deny文件(vi /etc/hosts.deny),加入下面这行
# Deny access to everyone.
ALL: ALL@ALL, PARANOID

这表明除非该地址包在允许访问的主机列表中,否则阻塞所有的服务和地址。

第二步:

编辑hosts.allow文件(vi /etc/hosts.allow),加入允许访问的主机列表,比如:
ftp: 202.54.15.99 foo.com
202.54.15.99和 foo.com是允许访问ftp服务的ip地址和主机名称。

第三步:

tcpdchk程序是tepd wrapper设置检查程序。它用来检查你的tcp wrapper设置,并报告发现的潜在的和真实的问题。设置完后,运行下面这个命令:
# tcpdchk

8、修改“/etc/host.conf”文件

“/etc/host.conf”说明了如何解析地址。编辑“/etc/host.conf”文件(vi /etc/host.conf),加入下面这行:
# Lookup names via DNS first then fall back to /etc/hosts.
order bind,hosts
# We have machines with multiple IP addresses.
multi on
# Check for IP address spoofing.
nospoof on

第一项设置首先通过DNS解析IP地址,然后通过hosts文件解析。第二项设置检测是否“/etc/hosts”文件中的主机是否拥有多个IP地址(比如有多个以太口网卡)。第三项设置说明要注意对本机未经许可的电子欺骗。

9、使“/etc/services”文件免疫

使“/etc/services”文件免疫,防止未经许可的删除或添加服务:
# chattr +i /etc/services

10、不允许从不同的控制台进行root登陆

“/etc/securetty”文件允许你定义root用户可以从那个TTY设备登陆。你可以编辑”/etc/securetty”文件,再不需要登陆的TTY设备前添加“#”标志,来禁止从该TTY设备进行root登陆。

在/etc/inittab文件中有如下一段话:
# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
#3:2345:respawn:/sbin/mingetty tty3
#4:2345:respawn:/sbin/mingetty tty4
#5:2345:respawn:/sbin/mingetty tty5
#6:2345:respawn:/sbin/mingetty tty6

系统默认的可以使用6个控制台,即Alt+F1,Alt+F2…,这里在3,4,5,6前面加上“#”,注释该句话,这样现在只有两个控制台可供使用,最好保留两个。然后重新启动init进程,改动即可生效!

11、使用PAM(可插拔认证模块)禁止任何人通过su命令改变为root用户su(Substitute

User替代用户)命令允许你成为系统中其他已存在的用户。如果你不希望任何人通过su命令改变为root用户或对某些用户限制使用su命令,你可以在su配置文件(在”/etc/pam.d/”目录下)的开头添加下面两行:
编辑su文件(vi /etc/pam.d/su),在开头添加下面两行:
auth sufficient /lib/security/pam_rootok.so
auth required /lib/security/Pam_wheel.so group=wheel

这表明只有”wheel”组的成员可以使用su命令成为root用户。你可以把用户添加到“wheel”组,以使它可以使用su命令成为root用户。添加方法可以用这个命令:chmod -G10 username 。

12、Shell logging Bash

shell在“~/.bash_history”(“~/”表示用户目录)文件中保存了500条使用过的命令,这样可以使你输入使用过的长命令变得容易。每个在系统中拥有账号的用户在他的目录下都有一个“.bash_history”文件。bash
shell应该保存少量的命令,并且在每次用户注销时都把这些历史命令删除。

第一步:

“/etc/profile”文件中的“HISTFILESIZE”和“HISTSIZE”行确定所有用户的“.bash_history”文件中可以 保存的旧命令条数。强烈建议把把“/etc/profile”文件中的“HISTFILESIZE”和“HISTSIZE”行的值设为一个较小的数,比如 30。编辑profile文件(vi/etc/profile),把下面这行改为:
HISTFILESIZE=30
HISTSIZE=30

这表示每个用户的“.bash_history”文件只可以保存30条旧命令。

第二步:

网管还应该在”/etc/skel/.bash_logout” 文件中添加下面这行”rm -f $HOME/.bash_history” 。这样,当用户每次注销时,“.bash_history”文件都会被删除。

编辑.bash_logout文件(vi /etc/skel/.bash_logout) ,添加下面这行:
rm -f $HOME/.bash_history

13、禁止Control-Alt-Delete键盘关闭命令

在”/etc/inittab” 文件中注释掉下面这行(使用#):
ca::ctrlaltdel:/sbin/shutdown -t3 -r now
改为:
#ca::ctrlaltdel:/sbin/shutdown -t3 -r now

为了使这项改动起作用,输入下面这个命令:
# /sbin/init q

14、给”/etc/rc.d/init.d” 下script文件设置权限

给执行或关闭启动时执行的程序的script文件设置权限。
# chmod -R 700 /etc/rc.d/init.d/*

这表示只有root才允许读、写、执行该目录下的script文件。

15、隐藏系统信息

在缺省情况下,当你登陆到linux系统,它会告诉你该linux发行版的名称、版本、内核版本、服务器的名称。对于黑客来说这些信息足够它入侵你的系统了。你应该只给它显示一个“login:”提示符。

首先编辑”/etc/rc.d/rc.local” 文件,在下面显示的这些行前加一个“#”,把输出信息的命令注释掉。
# This will overwrite /etc/issue at every boot. So, make any changes you
# want to make to /etc/issue here or you will lose them when you reboot.
#echo ”” > /etc/issue
#echo ”$R” >> /etc/issue
#echo ”Kernel $(uname -r) on $a $(uname -m)” >> /etc/issue
#
#cp -f /etc/issue /etc/issue.net
#echo >> /etc/issue

其次删除”/etc”目录下的“isue.net”和”issue”文件:
# rm -f /etc/issue
# rm -f /etc/issue.net

16、禁止不使用的SUID/SGID程序

如果一个程序被设置成了SUID

root,那么普通用户就可以以root身份来运行这个程序。网管应尽可能的少使用SUID/SGID 程序,禁止所有不必要的SUID/SGID程序。

查找root-owned程序中使用’s’位的程序:
# find / -type f ( -perm -04000 -o -perm -02000 ) -exec ls -lg {} \;

用下面命令禁止选中的带有’s’位的程序:
# chmod a-s [program]

MRTG + lm_sensors + CPU溫度 on linux

星期一, 06月 23rd, 2008

用 lm_sensors套件取得 cpu溫度

[1] apt-get install lm_sensors

[2] 執行 sensors-detect指令
     此用來偵測設定值,全Enter即可,
     之後它自已會將該要的module放於/etc/sysconfig/lm_sensors裡

[3] 載入/etc/sysconfig/lm_sensors裡的模組
      指令如下
         modprobe module1
         modprobe module2

     如果是 RPM安裝
        service lm_sensors start

     執行 sensors指令可看到溫度資訊 (more…)

在Linux系统下多线路ADSL的配置

星期五, 06月 6th, 2008

双ADSL及多ADSL增加线路的配置过程。

Linux配置多线路ADSL的方法

powered by KindGeorge http://kindgeorge.at.3322.org\经过一段时间的观察,证明运行良好,现把设置过程及方法总结一下,欢迎指正.

此文档可以说明双adsl及多adsl增加线路的配置过程.

实验环境:

操作系统: RedHat7.3

两条adsl,长期观察线路稳定,动态ip,带宽2M,

三块网卡: eth0 tulip,接内网

eth1 3c59x,接第一条adsl

eth2 8139too,接第二条adsl

ethn xxxx,(如果还有的话….)

目的:用两条adsl共同上网,分担负载,实现一般的简单负载平衡,带动内网上网.

1.添加网卡

插入网卡,启动机器,如果需要双线路上网,就要三块网卡了,配置网卡也可以参考其他资料.

配置为找到相应的型号模块,例如:eth2是8139的网卡

[root@kindgeorge root]# vi /etc/modules.conf
alias parport_lowlevel parport_pc
alias eth0 tulip
alias eth1 3c59x
alias eth2 8139too

把新的线路插在eth2上

2.配置adsl

方法一:

(1)运行adsl-setup程序,会一步一步的提示你完成配置过程.

创建ppp0和ppp1的拨号配置文件,并保存配置,一般保存在/etc/sysconfig/network-scripts/ifcfg-ppp1

(2)确定/etc/sysconfig/network-scripts/ifcfg-ppp0文件,其中的PIDFILE参数设为:

PIDFILE=/var/run/ppp-adsl.pid

修改/etc/sysconfig/network-scripts/ifcfg-ppp1文件,将其中的PIDFILE参数设为:

PIDFILE=/var/run/ppp-adsl1.pid

如果你有更多的线路,可以继续增加0,1,2,3….等

这是为了使不同的拨好用不同的pid,如果不修改此参数将无法启动第二条线路接口。

(3)配置文件一般是:

USERCTL=no
     BOOTPROTO=dialup
     NAME=DSLppp1
     DEVICE=ppp1
     TYPE=xDSL
     ONBOOT=yes
     PIDFILE=/var/run/pppoe-adsl1.pid
     FIREWALL=NONE
     PING=.
     PPPOE_TIMEOUT=20
     LCP_FAILURE=3
     LCP_INTERVAL=20
     CLAMPMSS=1412
     CONNECT_POLL=6
     CONNECT_TIMEOUT=60
     DEFROUTE=yes
     SYNCHRONOUS=no
     ETH=eth2 (对应新线路的网卡)
     PROVIDER=DSLppp1
     USER=isp提供的新用户名字2
     PEERDNS=no

方法二:

(1)直接拷贝

cp /etc/sysconfig/network-scripts/ifcfg-ppp0 /etc/sysconfig/network-scripts/ifcfg-ppp1

(2)修改其中的ppp0为ppp1,

修改PIDFILE=/var/run/pppoe-adsl.pid 为PIDFILE=/var/run/pppoe-adsl1.pid

修改采用的新接线路的网卡,例如:改ETH=eth1 为ETH=eth2

(3)增加新线路的帐号和密码. 帐号密码一般是保存在/etc/ppp/chap-secrets 和pap-secrets

我们只需要在最后增加新的用户名2和密码2即可.

/etc/ppp/chap-secrets文件一般是这样的:

# Secrets for authentication using CHAP

# client server secret IP addresses

“用户名1″ * “密码1″

“用户名2″ * “密码2″

“用户名n” * “密码n”

3.启动ppp接口

因为adsl-start 命令缺省只能启动第一的ppp接口。所以要启动两个接口,必须指定配置文件。

可以用:方法一:

ifup ppp0

ifup ppp1

(ifup pppn…)

或方法二:

adsl-start /etc/sysconfig/network-scripts/ifcfg-ppp0

adsl-start /etc/sysconfig/network-scripts/ifcfg-ppp1

(adsl-start /etc/sysconfig/network-scripts/ifcfg-pppn)

4.查看新设置是否启动:

方法一:执行: ifconfig

出现ppp0 和ppp1 ,并且均得到ip了.说明成功了,结果象这样:

ppp0   Link encap:Point-to-Point Protocol 
          inet addr:218.114.37.137  P-t-P:61.142.110.30  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1492  Metric:1
          RX packets:165721 errors:0 dropped:0 overruns:0 frame:0
          TX packets:123673 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3
          RX bytes:157324193 (150.0 Mb)  TX bytes:14068892 (13.4 Mb)

   ppp1   Link encap:Point-to-Point Protocol 
          inet addr:218.114.35.62  P-t-P:61.142.110.30  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1492  Metric:1
          RX packets:560055 errors:0 dropped:0 overruns:0 frame:0
          TX packets:439711 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3
          RX bytes:530025378 (505.4 Mb)  TX bytes:80895162 (77.1 Mb)

方法二: 执行ip高级命令: ip link ls

也可以检验ppp0和ppp1,结果象这样:

1: lo: mtu 16436 qdisc noqueue
            link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
         2: eth0: mtu 1500 qdisc pfifo_fast qlen 100
            link/ether 00:50:bf:07:4e:32 brd ff:ff:ff:ff:ff:ff
         3: eth1: mtu 1500 qdisc pfifo_fast qlen 100
            link/ether 00:01:02:9a:31:b9 brd ff:ff:ff:ff:ff:ff
         4: eth2: mtu 1500 qdisc pfifo_fast qlen 100
            link/ether 00:e0:4c:79:44:71 brd ff:ff:ff:ff:ff:ff
       268: ppp1: mtu 1492 qdisc pfifo_fast qlen 3
            link/ppp
       273: ppp0: mtu 1492 qdisc cbq qlen 3
            link/ppp

方法三: 用命令测试反应

ping -I ppp0 202.96.134.133 (测试ppp0的线路状况)

ping -I ppp1 202.96.134.133 (测试ppp1的线路状况)

ping -I ppp2 ……n (如果还有多条的话)

5.如果单单是要实现链路负载平衡,让ppp0和ppp1分担负载,那么我们象以下设置一下配置:

(1)启动路由,允许转发echo 1 > /proc/sys/net/ipv4/ip_forward

(2)进行伪装:

iptables -A POSTROUTING -t nat -s 192.168.1.0/24 -o ppp0 -j MASQUERADE

iptables -A POSTROUTING -t nat -s 192.168.1.0/24 -o ppp1 -j MASQUERADE

iptables -A POSTROUTING -t nat -s 192.168.1.0/24 -o pppn -j MASQUERADE (如果还有多条的话)

(3)修改网关

ip route replace default scope global nexthop dev ppp0 weight 1 nexthop dev ppp1 weight 1

说明: 用replace的原因是当原来没有网关时会增加这个网关,当已经存在网关时,会修改原来的网关.

用add 也可以,但是当已经存在默认网关时就要先delete再add.

两个weight 1的意思是这两条链路的权值是相等的,两条链路承担的网络流量是相等的。

有一点是需要说明的,因为路由表是基于缓存的,所以在实际中两条链路并不能100%的平分流量

nexthop NEXTHOP 设置多路径路由的下一跳地址。NEXTHOP比较复杂,它的语法和以下高层参数类似:

via ADDRESS–表示下一跳路由器;

dev NAME–表示输出设备;

weight NUMBER–在多路由路径中,这个元素的权重。表示相对带宽或者服务质量。

如果你有多条线路,那么继续在其中增加 nexthop dev ppp2(ppp3……)即可

(4) 刷新路由

ip route flush cache

6.即时检查数据的方向

用tcpdump 分别监察两条线路,用下面命令:

tcpdump -i ppp0
  tcpdump -i ppp1
  tcpdump -i ppp2……n (有多条的话)

7.为了每次启动时自动启动,把命令写在启动脚本里面,在 /etc/rc.local 后面增加:

ifup ppp0
  ifup ppp1
  echo 1 > /proc/sys/net/ipv4/ip_forward
  iptables -A POSTROUTING -t nat -s 192.168.1.0/24 -o ppp0 -j MASQUERADE
  iptables -A POSTROUTING -t nat -s 192.168.1.0/24 -o ppp1 -j MASQUERADE
  ip route replace default scope global nexthop dev ppp0 weight 1 nexthop dev ppp1 weight 1
  ip route flush cache

结果:运行数月,效果稳定良好。

上网会明显加快,为何呢,因为两条线路分摊了负载.例如,内网80人同时上网, 如果网络是一条2M的adsl,那么整条线路都拥挤,挤得死死的,每人分得的带宽可能只有30k.大家都会明显感觉上网很慢。

如果增加多一条线路,那么两条2M共同分摊拥挤程度,这样,可能每人分得的带宽就会变成60K,是原来的加倍,以这种形式来加快上网速度,增加了并发连接的个数。

Amfphp简介

星期三, 05月 14th, 2008

Amfphp 是PHP的RPC工具,它可以使PHP与下述技术无缝通信:

  • Flash 和 Flex Remoting
  • JavaScript JSON 和 Ajax JSON
  • XML 和XML-RPC

一、什么是RPC?

远端程序调用(RPC, Remote Procedure Call) 是一种客户端与服务器端交换数据方式。我们可以调用本地对象带对各种参数方法 ,设置回调并接受调用结果。我们不用关心发送和接收数据的实现细节。实现细节通常是抽象的, 就像我们在调用本地方法一样.

二、工作原理

客户端(Flash)与服务器端(php), 使用相同的方式描述方法调用和复杂数据。客户端序列化请求并将它发送到网关Amfphp。Amfphp再执行:

  • 反序列化请求
  • 找到相应的远程服务类
  • 实例化类
  • 执行安全检查
  • (使用指定参数)调用服务器端方法
  • 序列化返回的数据

Amfphp 可以正确地序列化、反序列化复杂类型数据。除了对象和数组,它还支持resources 数据连接资源,这就意味着我们可以通过调用远程方法简单返回mysql_query,amfphp 会处理这一切。 如果平台支持 (目前来说,Flash Remoting 和Flex Remoting), phpamf还可以处理循环引用和自定义数据。 它也支持简单的远程调试。还有amfphp 附带一个服务浏览器,它可以在创建客户端代码前测试远程服务。amfphp 1.0.1还添加了模板,可以自动生成客户端代码。Amfphp 1.9 beta更是新增了对AMF3的支持。详见http://www.riafan.com/article.asp?id=31

三、教学资源

1. 英文

2. 中文

centos 5.1 xen实例

星期三, 05月 14th, 2008

建立一个文件,使其成为guest所使用的磁盘:
mkdir /xen
dd if=/dev/zero of=/xen/hdcentos.img bs=1M count=6000

这样就在/xen中建立了一个6G左右的文件。

newfs下这个文件:

mke2fs -F -j /xen/hdcentos.img

将对应的文件挂到系统中来:

mount -o loop /xen/hdcentos.img /mnt/vm

为vm建立对应的设置

# mkdir /mnt/vm/dev
# /sbin/MAKEDEV -d /mnt/vm/dev -x console
# /sbin/MAKEDEV -d /mnt/vm/dev -x null
# /sbin/MAKEDEV -d /mnt/vm/dev -x zero

为vm准备对应的fstab文件

/dev/sda1 / ext3 defaults 1 1
none /dev/pts devpts gid=5,mode=620 0 0
none /dev/shm tmpfs defaults 0 0
none /proc proc defaults 0 0
none /sys sysfs defaults 0 0

加臷proc

# mkdir /mnt/vm/proc
# mount -t proc none /mnt/vm/proc

安装操作系统:

yum –installroot=/mnt/vm -y groupinstall Base

配置网卡(/etc/sysconfig/network-scripts/ifcfg-eth0):

DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
TYPE=Ethernet
USERCTL=yes
PEERDNS=yes
IPV6INIT=no

配置网络在启动时开始工作(/etc/sysconfig/network):

NETWORKING=yes

做一个在dom0上引导domU的initrd:

mkinitrd -v -f –fstab /mnt/vm/etc/fstab –with xenblk –with xennet –preload xenblk –preload xennet initrd-2.6.18-53.el5xen.vbird.img `uname -r`

最后,写上xen的配置文件(/etc/xen/hdcentos):
name = “hdcentos”
maxmem = 2048
memory = 2048
vcpus = 1
kernel = “/boot/vmlinuz-2.6.18-53.el5xen”
ramdisk = “/boot/initrd-2.6.18-53.el5xen.vbird.img”
on_poweroff = “destroy”
on_reboot = “restart”
on_crash = “restart”
vfb = [ "type=vnc,vncunused=1,keymap=en-us" ]
disk = [ "tap:aio:/xen/hdcentos.img,sda1,w" ]
vif = [ "bridge=xenbr0" ]
root = “/dev/sda1 ro ”

下面你就可以启动你自己的虚拟domU了。

如何保护自己编写的shell程序

星期一, 04月 28th, 2008

要保护自己编写的shell脚本程序,方法有很多,最简单的方法有两种:1、加密 2、设定过期时间,下面以shc工具为例说明:
一、安装shc工具
shc是一个加密shell脚本的工具.它的作用是把shell脚本转换为一个可执行的二进制文件.
 
shc的下载地址:             
http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.6.tgz

安装:
tar zxvf shc-3.8.tgz
cd shc-3.8
make test
make
make test
make strings
make install  这一步需要root权限
 
二、加密方法:
shc -r -f scrīpt-name  注意:要有-r选项, -f 后跟要加密的脚本名.
运行后会生成两个文件,scrīpt-name.x 和 scrīpt-name.x.c
scrīpt-name.x是加密后的可执行的二进制文件.
./scrīpt-name    即可运行.
scrīpt-name.x.c是生成scrīpt-name.x的原文件(c语言)

三、设定期限:
首先使用shc转化为二进制,并加上过期时间,如
./shc -e 12/06/2006 -m “please contact yazjiyao@yahoo.com.cn” -r -f flushvpn.sh
 
 我一般在程序中加入自动更新系统时间 的命令,防止用户更改系统时间。

$(( )) 與 $( ) 還有${ } 差在哪?

星期六, 04月 26th, 2008

我們上一章介紹了 ( ) 與 { } 的不同,這次讓我們擴展一下,看看更多的變化:$( ) 與 ${ } 又是啥玩意兒呢?

在 bash shell 中,$( ) 與 ` ` (反引號) 都是用來做命令替換用(command substitution)的。
所謂的命令替換與我們第五章學過的變量替換差不多,都是用來重組命令行:
* 完成引號裡的命令行,然後將其結果替換出來,再重組命令行。
例如:
[code]$ echo the last sunday is $(date -d “last sunday” +%Y-%m-%d)[/code]
如此便可方便得到上一星期天的日期了… ^_^

在操作上,用 $( ) 或 ` ` 都無所謂,只是我”個人”比較喜歡用 $( ) ,理由是:

1,  ` ` 很容易與 ‘ ‘ ( 單引號)搞混亂,尤其對初學者來說。
有時在一些奇怪的字形顯示中,兩種符號是一模一樣的(直豎兩點)。
當然了,有經驗的朋友還是一眼就能分辯兩者。只是,若能更好的避免混亂,又何樂不為呢? ^_^

2, 在多層次的復合替換中,` ` 須要額外的跳脫( \` )處理,而 $( ) 則比較直觀。例如:
這是錯的:
[code]command1 `command2 `command3` `[/code]
原本的意圖是要在 command2 `command3` 先將 command3 提換出來給 command 2 處理,
然後再將結果傳給 command1 `command2 …` 來處理。
然而,真正的結果在命令行中卻是分成了 `command2 ` 與 “ 兩段。
正確的輸入應該如下:
[code]command1 `command2 \`command3\` `[/code]

要不然,換成 $( ) 就沒問題了:
[code]command1 $(command2 $(command3))[/code]
只要你喜歡,做多少層的替換都沒問題啦~~~  ^_^

不過,$( ) 並不是沒有斃端的…
首先,` ` 基本上可用在全部的 unix shell 中使用,若寫成 shell script ,其移植性比較高。
而 $( ) 並不見的每一種 shell 都能使用,我只能跟你說,若你用 bash2 的話,肯定沒問題…  ^_^

接下來,再讓我們看 ${ } 吧… 它其實就是用來作變量替換用的啦。
一般情況下,$var 與 ${var} 並沒有啥不一樣。
但是用 ${ } 會比較精確的界定變量名稱的範圍,比方說:
[code]$ A=B
$ echo $AB

[/code]
原本是打算先將 $A 的結果替換出來,然後再補一個 B 字母於其後,
但在命令行上,真正的結果卻是只會提換變量名稱為 AB 的值出來…
若使用 ${ } 就沒問題了:
[code]$ echo ${A}B
BB[/code]

不過,假如你只看到 ${ } 只能用來界定變量名稱的話,那你就實在太小看 bash 了﹗
有興趣的話,你可先參考一下 cu 本版的精華文章:
http://www.chinaunix.net/forum/viewtopic.php?t=201843

為了完整起見,我這裡再用一些例子加以說明 ${ } 的一些特異功能:
假設我們定義了一個變量為:
file=/dir1/dir2/dir3/my.file.txt
我們可以用 ${ } 分別替換獲得不同的值:
${file#*/}:拿掉第一條 / 及其左邊的字串:dir1/dir2/dir3/my.file.txt
${file##*/}:拿掉最後一條 / 及其左邊的字串:my.file.txt
${file#*.}:拿掉第一個 .  及其左邊的字串:file.txt
${file##*.}:拿掉最後一個 .  及其左邊的字串:txt
${file%/*}:拿掉最後條 / 及其右邊的字串:/dir1/dir2/dir3
${file%%/*}:拿掉第一條 / 及其右邊的字串:(空值)
${file%.*}:拿掉最後一個 .  及其右邊的字串:/dir1/dir2/dir3/my.file
${file%%.*}:拿掉第一個 .  及其右邊的字串:/dir1/dir2/dir3/my
記憶的方法為:
[list]# 是去掉左邊(在鑑盤上 # 在 $ 之左邊)
% 是去掉右邊(在鑑盤上 % 在 $ 之右邊)
單一符號是最小匹配﹔兩個符號是最大匹配。[/list]
${file:0:5}:提取最左邊的 5 個字節:/dir1
${file:5:5}:提取第 5 個字節右邊的連續 5 個字節:/dir2

我們也可以對變量值裡的字串作替換:
${file/dir/path}:將第一個 dir 提換為 path:/path1/dir2/dir3/my.file.txt
${file//dir/path}:將全部 dir 提換為 path:/path1/path2/path3/my.file.txt

利用 ${ } 還可針對不同的變數狀態賦值(沒設定、空值、非空值):
${file-my.file.txt} :假如 $file 沒有設定,則使用 my.file.txt 作傳回值。(空值及非空值時不作處理)
${file:-my.file.txt} :假如 $file 沒有設定或為空值,則使用 my.file.txt 作傳回值。 (非空值時不作處理)
${file+my.file.txt} :假如 $file 設為空值或非空值,均使用 my.file.txt 作傳回值。(沒設定時不作處理)
${file:+my.file.txt} :若 $file 為非空值,則使用 my.file.txt 作傳回值。 (沒設定及空值時不作處理)
${file=my.file.txt} :若 $file 沒設定,則使用 my.file.txt 作傳回值,同時將 $file 賦值為 my.file.txt 。 (空值及非空值時不作處理)
${file:=my.file.txt} :若 $file 沒設定或為空值,則使用 my.file.txt 作傳回值,同時將 $file 賦值為 my.file.txt 。 (非空值時不作處理)
${file?my.file.txt} :若 $file 沒設定,則將 my.file.txt 輸出至 STDERR。 (空值及非空值時不作處理)
${file:?my.file.txt} :若 $file 沒設定或為空值,則將 my.file.txt 輸出至 STDERR。 (非空值時不作處理)

tips:
以上的理解在於, 你一定要分清楚 unset 與 null 及 non-null 這三種賦值狀態.
一般而言, : 與 null 有關, 若不帶 : 的話, null 不受影響, 若帶 : 則連 null 也受影響.

還有哦,${#var} 可計算出變量值的長度:
${#file} 可得到 27 ,因為 /dir1/dir2/dir3/my.file.txt 剛好是 27 個字節…

接下來,再為大家介稍一下 bash 的組數(array)處理方法。
一般而言,A=”a b c def” 這樣的變量只是將 $A 替換為一個單一的字串,
但是改為 A=(a b c def) ,則是將 $A 定義為組數…
bash 的組數替換方法可參考如下方法:
${A[@]} 或 ${A[*]} 可得到 a b c def (全部組數)
${A[0]} 可得到 a (第一個組數),${A[1]} 則為第二個組數…
${#A[@]} 或 ${#A[*]} 可得到 4 (全部組數數量)
${#A[0]} 可得到 1 (即第一個組數(a)的長度),${#A[3]} 可得到 3 (第四個組數(def)的長度)
A[3]=xyz 則是將第四個組數重新定義為 xyz …

諸如此類的….
能夠善用 bash 的 $( ) 與 ${ } 可大大提高及簡化 shell 在變量上的處理能力哦~~~  ^_^

好了,最後為大家介紹 $(( )) 的用途吧:它是用來作整數運算的。
在 bash 中,$(( )) 的整數運算符號大致有這些:
+ - * / :分別為 “加、減、乘、除”。
% :餘數運算
& | ^ !:分別為 “AND、OR、XOR、NOT” 運算。

例:
[code]$ a=5; b=7; c=2
$ echo $(( a+b*c ))
19
$ echo $(( (a+b)/c ))
6
$ echo $(( (a*b)%c))
1[/code]

在 $(( )) 中的變量名稱,可於其前面加 $ 符號來替換,也可以不用,如:
$(( $a + $b * $c)) 也可得到 19 的結果

此外,$(( )) 還可作不同進位(如二進位、八進位、十六進位)作運算呢,只是,輸出結果皆為十進位而已:
echo $((16#2a)) 結果為 42 (16進位轉十進位)
以一個實用的例子來看看吧:
假如當前的  umask 是 022 ,那麼新建文件的權限即為:
[code]$ umask 022
$ echo “obase=8;$(( 8#666 & (8#777 ^ 8#$(umask)) ))” | bc
644[/code]

事實上,單純用 (( )) 也可重定義變量值,或作 testing:
a=5; ((a++)) 可將 $a 重定義為 6
a=5; ((a–)) 則為 a=4
a=5; b=7; ((a < b)) 會得到  0 (true) 的返回值。
常見的用於 (( )) 的測試符號有如下這些:
[list]<:小於
>:大於
<=:小於或等於
>=:大於或等於
==:等於
!=:不等於[/list]
不過,使用 (( )) 作整數測試時,請不要跟 [ ] 的整數測試搞混亂了。(更多的測試我將於第十章為大家介紹)

怎樣?好玩吧..  ^_^  okay,這次暫時說這麼多…
上面的介紹,並沒有詳列每一種可用的狀態,更多的,就請讀者參考手冊文件囉…

如何实现在RHEL下将多个网卡bonding为一个单一通道?

星期三, 04月 9th, 2008

Linux Channel Bonding可以支持把多个网络适配器集合在一起, 当作一个网络适配器来使用。在 Linux 下,网卡的高可用性是通过 MII 或者 ETHTOOL 的状态监测来实现的,所以,需要检查系统中的网络适配器是否支持 MII 或者ETHTOOL 的连状态监测。可以用命令 “ethtool eth0″ 来检查,如果显示的 “Link detected:” 信息与实现的连接状态一致,就没有问题。如果系统中的网络适配器不支持 MII 或者 ETHTOOL 状态监测,当连接失效时,系统就不能检测到,同时,在 bonding 驱动加载时,会记录一条不支持 MII 和 ETHTOOL 的警告信息。

环境: Red Hat Enterprise Linux 4 Update1  

 

解决方法:

RHEL支持在内核级实现将多个物理网卡帮定为一个逻辑bonding设备,通过把多个物理网卡帮定为一个逻辑设备,可以实现增加带宽吞吐量,提供冗余。

为了创建一个bonding设备,在/etc/sysconfig/network-scripts/下创建文件ifcfg-bond<N>,N是一个数字,例如0。

该文件内容对不同类型网卡的帮定都是一样的,例如以太设备。唯一的区别是DEVICE=应该是bond<N>,下面是一个示例文件:

DEVICE=bond0
BOOTPROTO=none
ONBOOT=yes
NETWORK=10.0.1.0
NETMASK=255.255.255.0
IPADDR=10.0.1.27
USERCTL=no

一旦创建了bonding接口,bonding设备包含的网卡设备必须进行配置,在配置文件中添加到MASTER=和SLAVE=,所有网卡的配置文件都是类似的,例如一个bonding设备帮定了两个网卡,eth0和eth1的配置文件可能如下:

DEVICE=eth<N>
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
USERCTL=no

在本例中,把<N>替换为网卡编号。

为了激活bonding设备,必须加载内核模块,在RHEL4和RHEL3下加载模块的过程稍有不同。

RHEL4

为了确保在bonding设备在启动时模块被加载,在/etc/modprobe.conf中添加如下内容:

install bond<N> /sbin/modprobe bonding -o bond<N> miimon=100 mode=0

替换<N>为设备编号,例如0。

miimon 是指多久时间检查网络一次,单位是ms(毫秒),其意义是假设其中有一条网络断线,会在0.1秒内自动备援

 mode 共有七种模式(0~6)
 mode=0:负载均衡模式,有自动备援,但需要”Switch”支持和设定。
 mode=1:自动备援模式,其中一条线若断线,其他线路将会自动备援。
 mode=6:负载均衡模式,有自动备援,不需要”Switch”支持和设定。

如果还要使用互备模式,需要加上参数primary=ethx

对于每个虚拟bonding设备,在/etc/modprobe.conf中都要有对应行。需要注意的是在RHEL4U2之前的版本,不支持多个bonding设备。如果需要配置多个bonding设备,则需要升级内核到 RHEL4U2。

一旦/etc/modprobe.conf被配置,bonding虚拟设备配置文件以及网卡配置文件配置完毕,ifup命令将用来启动bonding虚拟设备,或者通过重新起动网络。

linux下解决大量的TIME_WAIT

星期三, 04月 9th, 2008

 vi /etc/sysctl.conf
新增如下内容:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies=1
使内核参数生效:
[root@web02 ~]# sysctl -p
readme:
net.ipv4.tcp_syncookies=1 打开TIME-WAIT套接字重用功能,对于存在大量连接的Web服务器非常有效。
net.ipv4.tcp_tw_recyle=1
net.ipv4.tcp_tw_reuse=1 减少处于FIN-WAIT-2连接状态的时间,使系统可以处理更多的连接。
net.ipv4.tcp_fin_timeout=30 减少TCP KeepAlive连接侦测的时间,使系统可以处理更多的连接。
net.ipv4.tcp_keepalive_time=1800 增加TCP SYN队列长度,使系统可以处理更多的并发连接。
net.ipv4.tcp_max_syn_backlog=8192

找到一篇sed强文:sed1line

星期六, 03月 22nd, 2008

HANDY ONE-LINERS FOR SED (Unix stream editor)               Mar. 23, 2001
compiled by Eric Pement <pemente@northpark.edu>               version 5.1
Latest version of this file is usually at:
   http://www.student.northpark.edu/pemente/sed/sed1line.txt
   http://www.cornerstonemag.com/sed/sed1line.txt
This file is also available in Portuguese at:
   http://www.lrv.ufsc.br/wmaker/sed_ptBR.html

FILE SPACING:

 # double space a file
 sed G

 # double space a file which already has blank lines in it. Output file
 # should contain no more than one blank line between lines of text.
 sed ’/^$/d;G’

 # triple space a file
 sed ’G;G’

 # undo double-spacing (assumes even-numbered lines are always blank)
 sed ’n;d’

NUMBERING:

 # number each line of a file (simple left alignment). Using a tab (see
 # note on ’\t’ at end of file) instead of space will preserve margins.
 sed = filename | sed ’N;s/\n/\t/’

 # number each line of a file (number on left, right-aligned)
 sed = filename | sed ’N; s/^/     /; s/ *\(.\{6,\}\)\n/\1  /’

 # number each line of file, but only print numbers if line is not blank
 sed ’/./=’ filename | sed ’/./N; s/\n/ /’

 # count lines (emulates ”wc -l”)
 sed -n ’$=’

TEXT CONVERSION AND SUBSTITUTION:

 # IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
 sed ’s/.$//’               # assumes that all lines end with CR/LF
 sed ’s/^M$//’              # in bash/tcsh, press Ctrl-V then Ctrl-M
 sed ’s/\x0D$//’            # gsed 3.02.80, but top script is easier

 # IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format
 sed ”s/$/`echo -e \\\r`/”            # command line under ksh
 sed ’s/$’”/`echo \\\r`/”             # command line under bash
 sed ”s/$/`echo \\\r`/”               # command line under zsh
 sed ’s/$/\r/’                        # gsed 3.02.80

 # IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
 sed ”s/$//”                          # method 1
 sed -n p                             # method 2

 # IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
 # Cannot be done with DOS versions of sed. Use ”tr” instead.
 tr -d \r <infile >outfile            # GNU tr version 1.22 or higher

 # delete leading whitespace (spaces, tabs) from front of each line
 # aligns all text flush left
 sed ’s/^[ \t]*//’                    # see note on ’\t’ at end of file

 # delete trailing whitespace (spaces, tabs) from end of each line
 sed ’s/[ \t]*$//’                    # see note on ’\t’ at end of file

 # delete BOTH leading and trailing whitespace from each line
 sed ’s/^[ \t]*//;s/[ \t]*$//’

 # insert 5 blank spaces at beginning of each line (make page offset)
 sed ’s/^/     /’

 # align all text flush right on a 79-column width
 sed -e :a -e ’s/^.\{1,78\}$/ &/;ta’  # set at 78 plus 1 space

 # center all text in the middle of 79-column width. In method 1,
 # spaces at the beginning of the line are significant, and trailing
 # spaces are appended at the end of the line. In method 2, spaces at
 # the beginning of the line are discarded in centering the line, and
 # no trailing spaces appear at the end of lines.
 sed  -e :a -e ’s/^.\{1,77\}$/ & /;ta’                     # method 1
 sed  -e :a -e ’s/^.\{1,77\}$/ &/;ta’ -e ’s/\( *\)\1/\1/’  # method 2

 # substitute (find and replace) ”foo” with ”bar” on each line
 sed ’s/foo/bar/’             # replaces only 1st instance in a line
 sed ’s/foo/bar/4′            # replaces only 4th instance in a line
 sed ’s/foo/bar/g’            # replaces ALL instances in a line
 sed ’s/\(.*\)foo\(.*foo\)/\1bar\2/’ # replace the next-to-last case
 sed ’s/\(.*\)foo/\1bar/’            # replace only the last case

 # substitute ”foo” with ”bar” ONLY for lines which contain ”baz”
 sed ’/baz/s/foo/bar/g’

 # substitute ”foo” with ”bar” EXCEPT for lines which contain ”baz”
 sed ’/baz/!s/foo/bar/g’

 # change ”scarlet” or ”ruby” or ”puce” to ”red”
 sed ’s/scarlet/red/g;s/ruby/red/g;s/puce/red/g’   # most seds
 gsed ’s/scarlet\|ruby\|puce/red/g’                # GNU sed only

 # reverse order of lines (emulates ”tac”)
 # bug/feature in HHsed v1.5 causes blank lines to be deleted
 sed ’1!G;h;$!d’               # method 1
 sed -n ’1!G;h;$p’             # method 2

 # reverse each character on the line (emulates ”rev”)
 sed ’/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//’

 # join pairs of lines side-by-side (like ”paste”)
 sed ’$!N;s/\n/ /’

 # if a line ends with a backslash, append the next line to it
 sed -e :a -e ’/\\$/N; s/\\\n//; ta’

 # if a line begins with an equal sign, append it to the previous line
 # and replace the ”=” with a single space
 sed -e :a -e ’$!N;s/\n=/ /;ta’ -e ’P;D’

 # add commas to numeric strings, changing ”1234567″ to ”1,234,567″
 gsed ’:a;s/\B[0-9]\{3\}\>/,&/;ta’                     # GNU sed
 sed -e :a -e ’s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta’  # other seds

 # add commas to numbers with decimal points and minus signs (GNU sed)
 gsed ’:a;s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta’

 # add a blank line every 5 lines (after lines 5, 10, 15, 20, etc.)
 gsed ’0~5G’                  # GNU sed only
 sed ’n;n;n;n;G;’             # other seds

SELECTIVE PRINTING OF CERTAIN LINES:

 # print first 10 lines of file (emulates behavior of ”head”)
 sed 10q

 # print first line of file (emulates ”head -1″)
 sed q

 # print the last 10 lines of a file (emulates ”tail”)
 sed -e :a -e ’$q;N;11,$D;ba’

 # print the last 2 lines of a file (emulates ”tail -2″)
 sed ’$!N;$!D’

 # print the last line of a file (emulates ”tail -1″)
 sed ’$!d’                    # method 1
 sed -n ’$p’                  # method 2

 # print only lines which match regular expression (emulates ”grep”)
 sed -n ’/regexp/p’           # method 1
 sed ’/regexp/!d’             # method 2

 # print only lines which do NOT match regexp (emulates ”grep -v”)
 sed -n ’/regexp/!p’          # method 1, corresponds to above
 sed ’/regexp/d’              # method 2, simpler syntax

 # print the line immediately before a regexp, but not the line
 # containing the regexp
 sed -n ’/regexp/{g;1!p;};h’

 # print the line immediately after a regexp, but not the line
 # containing the regexp
 sed -n ’/regexp/{n;p;}’

 # print 1 line of context before and after regexp, with line number
 # indicating where the regexp occurred (similar to ”grep -A1 -B1″)
 sed -n -e ’/regexp/{=;x;1!p;g;$!N;p;D;}’ -e h

 # grep for AAA and BBB and CCC (in any order)
 sed ’/AAA/!d; /BBB/!d; /CCC/!d’

 # grep for AAA and BBB and CCC (in that order)
 sed ’/AAA.*BBB.*CCC/!d’

 # grep for AAA or BBB or CCC (emulates ”egrep”)
 sed -e ’/AAA/b’ -e ’/BBB/b’ -e ’/CCC/b’ -e d    # most seds
 gsed ’/AAA\|BBB\|CCC/!d’                        # GNU sed only

 # print paragraph if it contains AAA (blank lines separate paragraphs)
 # HHsed v1.5 must insert a ’G;’ after ’x;’ in the next 3 scripts below
 sed -e ’/./{H;$!d;}’ -e ’x;/AAA/!d;’

 # print paragraph if it contains AAA and BBB and CCC (in any order)
 sed -e ’/./{H;$!d;}’ -e ’x;/AAA/!d;/BBB/!d;/CCC/!d’

 # print paragraph if it contains AAA or BBB or CCC
 sed -e ’/./{H;$!d;}’ -e ’x;/AAA/b’ -e ’/BBB/b’ -e ’/CCC/b’ -e d
 gsed ’/./{H;$!d;};x;/AAA\|BBB\|CCC/b;d’         # GNU sed only

 # print only lines of 65 characters or longer
 sed -n ’/^.\{65\}/p’

 # print only lines of less than 65 characters
 sed -n ’/^.\{65\}/!p’        # method 1, corresponds to above
 sed ’/^.\{65\}/d’            # method 2, simpler syntax

 # print section of file from regular expression to end of file
 sed -n ’/regexp/,$p’

 # print section of file based on line numbers (lines 8-12, inclusive)
 sed -n ’8,12p’               # method 1
 sed ’8,12!d’                 # method 2

 # print line number 52
 sed -n ’52p’                 # method 1
 sed ’52!d’                   # method 2
 sed ’52q;d’                  # method 3, efficient on large files

 # beginning at line 3, print every 7th line
 gsed -n ’3~7p’               # GNU sed only
 sed -n ’3,${p;n;n;n;n;n;n;}’ # other seds

 # print section of file between two regular expressions (inclusive)
 sed -n ’/Iowa/,/Montana/p’             # case sensitive

SELECTIVE DELETION OF CERTAIN LINES:

 # print all of file EXCEPT section between 2 regular expressions
 sed ’/Iowa/,/Montana/d’

 # delete duplicate, consecutive lines from a file (emulates ”uniq”).
 # First line in a set of duplicate lines is kept, rest are deleted.
 sed ’$!N; /^\(.*\)\n\1$/!P; D’

 # delete duplicate, nonconsecutive lines from a file. Beware not to
 # overflow the buffer size of the hold space, or else use GNU sed.
 sed -n ’G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P’

 # delete the first 10 lines of a file
 sed ’1,10d’

 # delete the last line of a file
 sed ’$d’

 # delete the last 2 lines of a file
 sed ’N;$!P;$!D;$d’

 # delete the last 10 lines of a file
 sed -e :a -e ’$d;N;2,10ba’ -e ’P;D’   # method 1
 sed -n -e :a -e ’1,10!{P;N;D;};N;ba’  # method 2

 # delete every 8th line
 gsed ’0~8d’                           # GNU sed only
 sed ’n;n;n;n;n;n;n;d;’                # other seds

 # delete ALL blank lines from a file (same as ”grep ’.' ”)
 sed ’/^$/d’                           # method 1
 sed ’/./!d’                           # method 2

 # delete all CONSECUTIVE blank lines from file except the first; also
 # deletes all blank lines from top and end of file (emulates ”cat -s”)
 sed ’/./,/^$/!d’          # method 1, allows 0 blanks at top, 1 at EOF
 sed ’/^$/N;/\n$/D’        # method 2, allows 1 blank at top, 0 at EOF

 # delete all CONSECUTIVE blank lines from file except the first 2:
 sed ’/^$/N;/\n$/N;//D’

 # delete all leading blank lines at top of file
 sed ’/./,$!d’

 # delete all trailing blank lines at end of file
 sed -e :a -e ’/^\n*$/{$d;N;ba’ -e ’}'  # works on all seds
 sed -e :a -e ’/^\n*$/N;/\n$/ba’        # ditto, except for gsed 3.02*

 # delete the last line of each paragraph
 sed -n ’/^$/{p;h;};/./{x;/./p;}’

SPECIAL APPLICATIONS:

 # remove nroff overstrikes (char, backspace) from man pages. The ’echo’
 # command may need an -e switch if you use Unix System V or bash shell.
 sed ”s/.`echo \\\b`//g”    # double quotes required for Unix environment
 sed ’s/.^H//g’             # in bash/tcsh, press Ctrl-V and then Ctrl-H
 sed ’s/.\x08//g’           # hex expression for sed v1.5

 # get Usenet/e-mail message header
 sed ’/^$/q’                # deletes everything after first blank line

 # get Usenet/e-mail message body
 sed ’1,/^$/d’              # deletes everything up to first blank line

 # get Subject header, but remove initial ”Subject: ” portion
 sed ’/^Subject: */!d; s///;q’

 # get return address header
 sed ’/^Reply-To:/q; /^From:/h; /./d;g;q’

 # parse out the address proper. Pulls out the e-mail address by itself
 # from the 1-line return address header (see preceding script)
 sed ’s/ *(.*)//; s/>.*//; s/.*[:<] *//’

 # add a leading angle bracket and space to each line (quote a message)
 sed ’s/^/> /’

 # delete leading angle bracket & space from each line (unquote a message)
 sed ’s/^> //’

 # remove most HTML tags (accommodates multiple-line tags)
 sed -e :a -e ’s/<[^>]*>//g;/</N;//ba’

 # extract multi-part uuencoded binaries, removing extraneous header
 # info, so that only the uuencoded portion remains. Files passed to
 # sed must be passed in the proper order. Version 1 can be entered
 # from the command line; version 2 can be made into an executable
 # Unix shell script. (Modified from a script by Rahul Dhesi.)
 sed ’/^end/,/^begin/d’ file1 file2 … fileX | uudecode   # vers. 1
 sed ’/^end/,/^begin/d’ ”$@” | uudecode                    # vers. 2

 # zip up each .TXT file individually, deleting the source file and
 # setting the name of each .ZIP file to the basename of the .TXT file
 # (under DOS: the ”dir /b” switch returns bare filenames in all caps).
 echo @echo off >zipup.bat
 dir /b *.txt | sed ”s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/” >>zipup.bat

TYPICAL USE: Sed takes one or more editing commands and applies all of
them, in sequence, to each line of input. After all the commands have
been applied to the first input line, that line is output and a second
input line is taken for processing, and the cycle repeats. The
preceding examples assume that input comes from the standard input
device (i.e, the console, normally this will be piped input). One or
more filenames can be appended to the command line if the input does
not come from stdin. Output is sent to stdout (the screen). Thus:

 cat filename | sed ’10q’        # uses piped input
 sed ’10q’ filename              # same effect, avoids a useless ”cat”
 sed ’10q’ filename > newfile    # redirects output to disk

For additional syntax instructions, including the way to apply editing
commands from a disk file instead of the command line, consult ”sed &
awk, 2nd Edition,” by Dale Dougherty and Arnold Robbins (O’Reilly,
1997; http://www.ora.com), ”UNIX Text Processing,” by Dale Dougherty
and Tim O’Reilly (Hayden Books, 1987) or the tutorials by Mike Arst
distributed in U-SEDIT2.ZIP (many sites). To fully exploit the power
of sed, one must understand ”regular expressions.” For this, see
“Mastering Regular Expressions” by Jeffrey Friedl (O’Reilly, 1997).
The manual (”man”) pages on Unix systems may be helpful (try ”man
sed”, ”man regexp”, or the subsection on regular expressions in ”man
ed”), but man pages are notoriously difficult. They are not written to
teach sed use or regexps to first-time users, but as a reference text
for those already acquainted with these tools.

QUOTING SYNTAX: The preceding examples use single quotes (’…’)
instead of double quotes (”…”) to enclose editing commands, since
sed is typically used on a Unix platform. Single quotes prevent the
Unix shell from intrepreting the dollar sign ($) and backquotes
(`…`), which are expanded by the shell if they are enclosed in
double quotes. Users of the ”csh” shell and derivatives will also need
to quote the exclamation mark (!) with the backslash (i.e., \!) to
properly run the examples listed above, even within single quotes.
Versions of sed written for DOS invariably require double quotes
(”…”) instead of single quotes to enclose editing commands.

USE OF ’\t’ IN SED SCRIPTS: For clarity in documentation, we have used
the expression ’\t’ to indicate a tab character (0×09) in the scripts.
However, most versions of sed do not recognize the ’\t’ abbreviation,
so when typing these scripts from the command line, you should press
the TAB key instead. ’\t’ is supported as a regular expression
metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80.

VERSIONS OF SED: Versions of sed do differ, and some slight syntax
variation is to be expected. In particular, most do not support the
use of labels (:name) or branch instructions (b,t) within editing
commands, except at the end of those commands. We have used the syntax
which will be portable to most users of sed, even though the popular
GNU versions of sed allow a more succinct syntax. When the reader sees
a fairly long command such as this:

   sed -e ’/AAA/b’ -e ’/BBB/b’ -e ’/CCC/b’ -e d

it is heartening to know that GNU sed will let you reduce it to:

   sed ’/AAA/b;/BBB/b;/CCC/b;d’      # or even
   sed ’/AAA\|BBB\|CCC/b;d’

In addition, remember that while many versions of sed accept a command
like ”/one/ s/RE1/RE2/”, some do NOT allow ”/one/! s/RE1/RE2/”, which
contains space before the ’s’. Omit the space when typing the command.

OPTIMIZING FOR SPEED: If execution speed needs to be increased (due to
large input files or slow processors or hard disks), substitution will
be executed more quickly if the ”find” expression is specified before
giving the ”s/…/…/” instruction. Thus:

   sed ’s/foo/bar/g’ filename         # standard replace command
   sed ’/foo/ s/foo/bar/g’ filename   # executes more quickly
   sed ’/foo/ s//bar/g’ filename      # shorthand sed syntax

On line selection or deletion in which you only need to output lines
from the first part of the file, a ”quit” command (q) in the script
will drastically reduce processing time for large files. Thus:

   sed -n ’45,50p’ filename           # print line nos. 45-50 of a file
   sed -n ’51q;45,50p’ filename       # same, but executes much faster

If you have any additional scripts to contribute or if you find errors
in this document, please send e-mail to the compiler. Indicate the
version of sed you used, the operating system it was compiled for, and
the nature of the problem. Various scripts in this file were written
or contributed by:

 Al Aab <af137@freenet.toronto.on.ca>   # ”seders” list moderator
 Edgar Allen <era@sky.net>              # various
 Yiorgos Adamopoulos <adamo@softlab.ece.ntua.gr>
 Dale Dougherty <dale@songline.com>     # author of ”sed & awk”
 Carlos Duarte <cdua@algos.inesc.pt>    # author of ”do it with sed”
 Eric Pement <pemente@northpark.edu>    # author of this document
 Ken Pizzini <ken@halcyon.com>          # author of GNU sed v3.02
 S.G. Ravenhall <stew.ravenhall@totalise.co.uk> # great de-html script
 Greg Ubben <gsu@romulus.ncsc.mil>      # many contributions & much help