php执行外部命令

这几天在做一个域名解析的东东,要在php中调用系统命令,就整理一下。

一、使用exec()函数执行系统外部命令:
原型:function exec(string $command,array[optional] $output,int[optional] $return_value)
例:exec("nslookup $s1 $s2",$result,$output);//执行nslookup命令

  exec执行系统外部命令时不会输出结果,而是返回结果的最后一行,如果想得到结果可以使用第二个参数,将结果输出到指定的数组,数组一个记录代表输出的一行,第三个参数是取得命令执行的状态码,执行成功返回0.

二、使用system函数执行系统外部命令:

 

原型:function system(string $command,int[optional] $return_value)
例:system("nslookup $s1 $s2");

三、使用函数passthru执行外部命令:

 

原型:function passthru(string $command,int[optional] $return_value)

 

与system的区别是,passthru直接将结果输出到浏览器,但是不返回任何值,且可以输出二进制。
 
四、反撇号(`)执行外部命令:
    使用该命令时要确保shell_exec函数可用。

vim中文乱码

    用vim打开中文的时候可能会出现乱码,解决方法:修改vimrc。

    vi /usr/share/vim/vimrc,在vimrc最后添加:

        set fileencodings=utf-8,gb2312,gbk,gb18030i

        set termencoding=utf-8

        set encoding=utf-8

    另, 转一篇vim编码的文章:http://edyfox.codecarver.org/html/vim_fileencodings_detection.html

 

常用的shell命令

1、如何计算当前目录下的文件数和目录数

       ls -l * |grep "^-"|wc -l          #文件数

       ls -l * |grep "^d"|wc -l        #目录数

2、如何只列子目录

        ls -F | grep /$

3、如何取出文件中特定行内容

      head -5 /etc/passwd     #前5行

      tail -5 /etc/passwd        #后5行

       sed -n '5,10p' /etc/passwd         #只查看文件中第5行到第10行内容

4、查找含特定字符串的文件

        $find . -type f -exec grep “the string” {} ; -print        #查找当前目录下含有“the string”字符串的文件

5、取出文件中特定的内容

       可以通过cut来实现:

         ifconfig | grep "inet "| cut -f 2 -d ":"|cut -f 1 -d " "

        -d用来定义分隔符,-f表示需要取得哪个字段

        也可使用cut取得文件中每行特定的几个字符。

        cut -c3-5 /etc/passwd      #输出/etc/passwd中每行第3到5个的字符。

6、获取本机IP:

        内网:ifconfig -a | grep 'inet' | cut -f 2 -d ':' | cut -f 1 -d ' ' | grep -v '^127'

        外网:curl "http://checkip.dyndns.org/" 2>/dev/null|awk '{print $6}'|cut -d '<' -f1

                    curl -s "http://checkip.dyndns.org/"|cut -f 6 -d" "|cut -f 1 -d"<"

                    w3m -dump http://submit.apnic.net/templates/yourip.html | grep -P -o '(\d+\.){3}\d+'

                    curl -s "http://checkip.dyndns.org/"| sed 's/.*Address: \([0-9\.]*\).*/\1/g'

                    curl -s "http://checkip.dyndns.org/"|cut -d "<" -f7|cut -c 26-

                    curl ifconfig.me

                    curl icanhazip.com

7、获取mac地址:

        MAC=`LANG=C ifconfig $NIC | awk '/HWaddr/{ print $5 }' `

(继续添加^_^)