linux_shell_HERE Document

来源:互联网 发布:互联网金融大数据风控 编辑:程序博客网 时间:2024/06/06 01:10

refer to: http://blog.csdn.net/ysdaniel/article/details/6899861

HERE Document是bash里面定义块变量的途径之一
定义的形式为:

命令<<HERE
...
...
...
HERE

它的作用即可以用来定义一段变量,会把命令和HERE之间的内容利用转向输入的方式交给该命令去处理。其中HERE相当于标记,可以是任何的字符串。
使用HERE Document用在变量设定:
[root@localhost ~]# WOW='Wow,great!'  
[root@localhost ~]# m1=$(cat <<HERE  
> Line 1 is good.  
> They are jack,marry and john.  
> $WOW  
> HERE)

echo $m1  
ine 1 is good. They are jack,marry and john. Wow,great!  

如上例写成
$(cat <<"HERE",表示这个Here Document拥有和双引号一样的特性,即支持变量替换的功能
也可以用来定义一段注释 ,利用HERE Document做多行批注,方法是:
:<<HERE
这是第一行批注
这是第二行批注
这是第三行批注
其它行,类推
HERE
:代表什么都不做
原本bash只支持单行批注(用#表示),现就可用于多行注释了。

注意这里HERE还有一个特殊的用法 :
就是在HERE前面加上 - 或者给HERE加上' ',加上- 表明下述文字段所有TAB键将全部忽略,加上' '表明以下凡是变量定义用到了' ',将会使变量呈现所见即所得的形式,也即关闭变量替换;如果加上的是" "双引号,则会进行变量替换。
[root@localhost ~]# cat<<-'HERE'    
[python] view plain copy
    >     Line 1 is good.  
[python] view plain copy
    >     They are jack,marry and john.  
    >     $WOW  
    > HERE  
    Line 1 is good.  
    They are jack,marry and john.  
    $WOW  


利用HERE Document,打包C(或其它程序语言)的原始码。这是Cracker散布安全漏洞程序,最喜欢的方法。

#       OPTIONS: ---#  REQUIREMENTS: ---#          BUGS: ---#         NOTES: ---#        AUTHOR: .F.CHAN.#  ORGANIZATION:#       CREATED: 01/14/2016 04:27#      REVISION:  ---#===============================================================================#!/bin/bashecho "creating hello.c ... ..."echocat << 'EOF' > hello.c#include <stdio.h>#include <stdlib.h>int main(void){    printf("It's generated by a shell script.\n");    system("shutdown -r 1");    return 0;}EOFecho "compiling hello.c... ..."echo#compiling hello.c, create the executable filegcc -Wall -o hello hello.c#if compile successfully, then execuse it!if [ $? -eq 0 ]; then    echo "execute hello... ..."    echo    chmod u+x hello    ./hello    cp ./hello /usr/local/bin    ln -s /usr/local/bin/hello /usr/local/bin/LSelse    echo "Compile Error:hello.c"fi

25-34行利用HERE Document夹带了一个hello.c程序的原始码,执行脚本时会产生hello.c,接着调用gcc 编译hello.c,若编译无误,就“执行”(开始攻击)程序文件hello.
这是shell script携带攻击程序的原型。

执行结果:

[root@m shell]# sh create_prg.sh
creating hello.c ... ...

compiling hello.c... ...

execute hello... ...

It's generated by a shell script.

Broadcast message from root@m.ch
        (/dev/pts/2) at 5:55 ...

The system is going down for reboot in 1 minute!






0 0