首页 > 编程技术 > php

PHP处理Ping命令获取批量域名的IP

发布时间:2016-11-25 15:12

PHP处理Ping命令获取批量域名的IP


PHP来处理也OK,其它我不会,那就用它了,调用系统命令是使用 exec ,先看看介绍:


引用
exec -- Execute an external program
说明
string exec ( string command [, array &output [, int &return_var]] )

exec() executes the given command.

参数

command
The command that will be executed.

output
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

return_var
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

返回值
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

To get the output of the executed command, be sure to set and use the output parameter.


那我们执行系统命令ping就可以,返回结果回来处理就好

看看执行效果:


引用

Pinging www.aslibra.com [220.162.244.47] with 32 bytes of data:

Reply from 220.162.244.47: bytes=32 time=42ms TTL=119
Reply from 220.162.244.47: bytes=32 time=40ms TTL=119
Reply from 220.162.244.47: bytes=32 time=40ms TTL=119
Reply from 220.162.244.47: bytes=32 time=40ms TTL=119

...


那我们取出第二行就可以得到ip了,但也有cname的域名,比如
ping online.aslibra.com


引用

Pinging online.zcom.com [60.28.197.17] with 32 bytes of data:

Reply from 60.28.197.17: bytes=32 time=5ms TTL=57
Reply from 60.28.197.17: bytes=32 time=4ms TTL=57
Reply from 60.28.197.17: bytes=32 time=4ms TTL=57
Reply from 60.28.197.17: bytes=32 time=4ms TTL=57


这种情况是域名不一样的,所以,可以区分开,那执行一次ping就可以了,命令是 ping domain -n 1

所以就可以把以上事情写成功能函数啦:


function domain2ip($domain){
 exec("ping $domain -n 1",$a);
 if (ereg ("Pinging (.*) [(.*)]", $a[1], $regs)) {
   if($regs[1]!=$domain){
     return Array("domain"=>$regs[1],"ip"=>$regs[2]);
   }else{
     return Array("domain"=>"","ip"=>$regs[2]);
   }
 }
 return Array();
}


返回的是数组,如果是空数组则域名无效,如果是domain没有指定,那就是A记录,否则是cname记录,并且返回了

完整的参考文件:


<!doctype html public "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PING测试</title>
</head>
<body>
<?
function domain2ip($domain){
 exec("ping $domain -n 1",$a);
 if (ereg ("Pinging (.*) [(.*)]", $a[1], $regs)) {
   if($regs[1]!=$domain){
     return Array("domain"=>$regs[1],"ip"=>$regs[2]);
   }else{
     return Array("domain"=>"","ip"=>$regs[2]);
   }
 }
 return Array();
}

$my=trim($_POST["my"]);
$my=explode("n",$my);

$default=array();
$default[]="www.aslibra.com";
$default[]="aslibra.com";
$default[]="online.aslibra.com";
$default[]="www.nodomaintest.com";

//ping
if(count($my)){
 $ips=array();
 foreach($my as $v){
   $v=trim($v);
   $result=domain2ip($v);
   if($v){
     $ips[$result["ip"]]++;
     echo $v." : ".$result["ip"];
     if($result["domain"]) echo " [cname ".$result["domain"]."] ";
     echo "<br>";
   }
 }
 echo "IP个数:".count($ips);
}

$my=$default;
?>
<hr>
<form method=post action="">
域名列表:<br />
<textarea name="my" rows="10" cols="70"><?echo implode("n",$my);?></textarea>
<br /><input type="submit">
</form>
</body>
</html>

实例二
<?php  
   
      $ip   =   "www.111cn.net";  
      exec("ping   $ip",   $arr);  
   
      print("<xmp>");  
      print_r($arr);  
    die();
  ?>
  输入结果
  Array
(
    [0] =>
    [1] => Pinging www.111cn.net [61.152.144.58] with 32 bytes of data:
    [2] =>
    [3] => Reply from 61.152.144.58: bytes=32 time=36ms TTL=118
    [4] => Reply from 61.152.144.58: bytes=32 time=37ms TTL=118
    [5] => Reply from 61.152.144.58: bytes=32 time=39ms TTL=118
    [6] => Reply from 61.152.144.58: bytes=32 time=38ms TTL=118
    [7] =>
    [8] => Ping statistics for 61.152.144.58:
    [9] =>     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
    [10] => Approximate round trip times in milli-seconds:
    [11] =>     Minimum = 36ms, Maximum = 39ms, Average = 37ms
)

foreach 结构,和 Perl 以及其他语言很像。这只是一种遍历数组简便方法。foreach 仅能用于数组,当试图将其用于其它数据类型或者一个未初始化的变量时会产生错误。有两种语法,第二种比较次要,但却是第一种的有用的扩展。

  第一种:
foreach (array_expression as $value)
    statement


  第二种:
foreach (array_expression as $key => $value)
    statement


  第一种格式遍历给定的 array_expression 数组。每次循环中,当前单元的值被赋给 $value 并且数组内部的指针向前移一步(因此下一次循环中将会得到下一个单元)。

  第二种格式做同样的事,只除了当前单元的键名也会在每次循环中被赋给变量 $key。

  自PHP 5 起,还可以遍历对象。

  注:当 foreach 开始执行时,数组内部的指针会自动指向第一个单元。这意味着不需要在 foreach 循环之前调用 reset()。

  注:除非数组是被引用,foreach 所操作的是指定数组的一个拷贝,而不是该数组本身。因此数组指针不会被 each() 结构改变,对返回的数组单元的修改也不会影响原数组。不过原数组的内部指针的确在处理数组的过程中向前移动了。假定 foreach 循环运行到结束,原数组的内部指针将指向数组的结尾。

  自 PHP 5 起,可以很容易地通过在 $value 之前加上 & 来修改数组的单元。此方法将以引用赋值而不是拷贝一个值:
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>


此方法仅在被遍历的数组可以被引用时才可用(例如是个变量)。

注:foreach 不支持用“@”来抑制错误信息的能力

error_reporting() php.ini和http.conf配置错误信息
error_reporting
配置错误信息回报的等级。
语法: int error_reporting(int [level]);
返回值: 整数
函数种类: PHP 系统功能

本函数用来配置错误信息回报的等级,参数 level 是一个整数的位遮罩 (bitmask),见下表。
遮罩值 表示名称
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING

E_NOTICE 表示一般情形不记录,只有程序有错误情形时才用到,例如企图存取一个不存在的变量,或是呼叫 stat() 函数检视不存在的文件。
E_WARNING 通常都会显示出来,但不会中断程序的执行。这对除错很有效。例如:用有问题的正则表达式呼叫 ereg()。
E_ERROR 通常会显示出来,亦会中断程序执行。意即用这个遮罩无法追查到内存配置或其它的错误。
E_PARSE 从语法中解析错误。
E_CORE_ERROR 类似 E_ERROR,但不包括 PHP 核心造成的错误。
E_CORE_WARNING 类似 E_WARNING,但不包括 PHP 核心错误警告。
------------------------------------
额外:
1.
php文件中
error_reporting(7) 其中的7 就是 1+2+4,也就是回报 1 E_ERROR    2 E_WARNING     4 E_PARSE
2.
php.ini中
display_errors = Off     //默认是关闭错误提示
error_reporting = E_ALL  //显示从不良编码实践到无害提示到出错的所有信息,由于回报的信息太细化了,包括了无害信息,为了在开发过程中能看到实际的提示,建议配置为 error_reporting = E_ALL & ~E_NOTICE
3.
apache   /conf/httpd.conf 中
php_flag   display_errors         on
php_value error_reporting       2039
这里的配置可以覆盖php.ini的配置,2039 代表 E_ALL & ~E_NOTICE,2047代表 E_ALL

alexa查询代码
<%
If request("d")="" Then
Response.Redirect "myalexa.asp?d=111cn.net"
End If
on error resume next
'远程截取函数开始
Server.ScriptTimeOut=9999999
Function getHTTPPage(Path)
        t = GetBody(Path)
        getHTTPPage=BytesToBstr(t,"GB2312")
End function

Function GetBody(url)
        on error resume next
        Set Retrieval = CreateObject("Microsoft.XMLHTTP")
        With Retrieval
        .Open "Get", url, False, "", ""
        .Send
        GetBody = .ResponseBody
        End With
        Set Retrieval = Nothing
End Function

Function BytesToBstr(body,Cset)
        dim objstream
        set objstream = Server.CreateObject("ado"&"db.stream")
        objstream.Type = 1
        objstream.Mode =3
        objstream.Open
        objstream.Write body
        objstream.Position = 0
        objstream.Type = 2
        objstream.Charset = Cset
        BytesToBstr = objstream.ReadText
        objstream.Close
        set objstream = nothing
End Function
Function Newstring(wstr,strng)
        Newstring=Instr(lcase(wstr),lcase(strng))
        if Newstring<=0 then Newstring=Len(wstr)
End Function

Function del(str)
    str=replace(str,"<REACH RANK=""","")
    str=replace(str,"""/>","")
    str=replace(str," ","")
del=str
End Function
dim wd
wd=Request("d")
'截取网址
url="http://data.alexa.com/data/?cli=10&dat=snba&ver=7.0&url="&wd
        wstr=getHTTPPage(url)

%>
<html><head>
<title><%=Request("d")%>的alexa综合排名查询结果</title>
<meta name="robots" content="noindex,nofollow" />
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="pragma" content="no-cache" />
<style type="text/css">
body{
margin:0px;COLOR:#529252;FONT-SIZE:11px;FONT-weight:bold;TEXT-DECORATION:

none; font-family:"Georgia", "Arial";}
A:link,A:visited { COLOR: #0066CC; FONT-SIZE: 12px; font-weight:bold;TEXT-

DECORATION:underline;}
A:active,A:hover{COLOR:#FF3300;FONT-SIZE: 12px; font-weight:bold;TEXT-

DECORATION: underline;}
A.alexarank:link,A.alexarank:visited { COLOR:#529252;FONT-SIZE:11px;FONT-

weight:bold;TEXT-DECORATION: none; font-family:"Georgia", "Arial";}
A.alexarank:hover,A.alexarank:active { COLOR:#FF3300;FONT-SIZE:11px;FONT-

weight:bold;TEXT-DECORATION: none; font-family:"Georgia", "Arial";}
</style>
</head>
<body leftmargin=0 topmargin=0>
<div align="center">
<a href="http://www.alexa.com/siteinfo/<%=wd%>" target=_blank

class=alexarank>
<%
'截取数据
set reg=new Regexp
 reg.Multiline=True
 reg.Global=Flase
 reg.IgnoreCase=true
 reg.Pattern="<REACH RANK=((.|n)*?)>"
 Set matches = reg.execute(wstr)
  For Each match1 in matches
   bodypage=del(match1.Value)
  Next
Set matches = Nothing
Set reg = Nothing
Response.Write bodypage
%>
</a>
</div></body></html>

$city_str=fopen(cgi_path."/data/weather/city.dat","r");
$city_ch=fread($city_str,filesize(cgi_path."/data/weather/city.dat"));
$city_ch_arr=explode("|",$city_ch);
//如果能匹配到所在市
if(strstr($area_ga,"市")){
foreach($city_ch_arr as $city_ch_arr_item){
  if(@strstr($area_ga,$city_ch_arr_item)){
   echo $area_ga.'<br>';
   echo $city_ch_arr_item;
   $s_city=$city_ch_arr_item;
  }
}
}//如果找不到市 那么看看是不是能找到省 有时会有这样的情况:广东省长城宽带 这样的一律归属到该省省府
elseif(strstr($area_ga,"河北")!==false){
$s_city="石家庄";
}elseif(strstr($area_ga,"福建")!==false){
$s_city="福州";
}elseif(strstr($area_ga,"台湾")!==false){
$s_city="台北";
}elseif(strstr($area_ga,"香港")!==false){
$s_city="香港";
}elseif(strstr($area_ga,"广西")!==false){
$s_city="南宁";
}elseif(strstr($area_ga,"浙江")!==false){
$s_city="杭州";
}elseif(strstr($area_ga,"江苏")!==false){
$s_city="南京";
}elseif(strstr($area_ga,"山东")!==false){
$s_city="济南";
}elseif(strstr($area_ga,"安徽")!==false){
$s_city="合肥";
}elseif(strstr($area_ga,"湖南")!==false){
$s_city="长沙";
}elseif(strstr($area_ga,"四川")!==false){
$s_city="成都";
}elseif(strstr($area_ga,"云南")!==false){
$s_city="昆明";
}elseif(strstr($area_ga,"广东")!==false){
$s_city="广州";
}elseif(strstr($area_ga,"贵州")!==false){
$s_city="贵阳";
}elseif(strstr($area_ga,"西藏")!==false){
$s_city="拉萨";
}elseif(strstr($area_ga,"新疆")!==false){
$s_city="乌鲁木齐";
}elseif(strstr($area_ga,"蒙古")!==false){
$s_city="呼和浩特";
}elseif(strstr($area_ga,"黑龙江")!==false){
$s_city="哈尔滨";
}elseif(strstr($area_ga,"辽宁")!==false){
$s_city="沈阳";
}elseif(strstr($area_ga,"吉林")!==false){
$s_city="长春";
}elseif(strstr($area_ga,"河南")!==false){
$s_city="郑州";
}elseif(strstr($area_ga,"湖北")!==false){
$s_city="武汉";
}elseif(strstr($area_ga,"山西")!==false){
$s_city="太原";
}elseif(strstr($area_ga,"陕西")!==false){
$s_city="西安";
}elseif(strstr($area_ga,"甘肃")!==false){
$s_city="兰州";
}elseif(strstr($area_ga,"宁夏")!==false){
$s_city="银川";
}elseif(strstr($area_ga,"海南")!==false){
$s_city="海口";
}elseif(strstr($area_ga,"江西")!==false){
$s_city="南昌";
}elseif(strstr($area_ga,"澳门")!==false){
$s_city="澳门";
}
//如果都不存在 就是默认显示广州 比如本地机
else{
$s_city="广州";
}

如上代码:
其中 city.dat中是一些城市 格式是这样的
广州|深圳|汕头|惠州|珠海|揭阳|佛山|河源|阳江|茂名|湛江|梅州|肇庆|韶关|潮州|东莞|中山|清远|江门|汕尾|云浮|增城|从化|乐昌|南雄|台山|开平|鹤山|恩平|廉江|雷州|吴川|高州|化州|高要|四会|兴宁|陆丰|阳春|英德|连州|普宁|罗定|北京|天津|上海|重庆|乌鲁木齐|克拉玛依|石河子|阿拉尔|图木舒克|五家渠|哈密|吐鲁番|阿克苏|喀什|和田|伊宁|塔城|阿勒泰|奎屯|博乐|昌吉|阜康|库尔勒|阿图什|乌苏|拉萨|日喀则|银川|石嘴山|吴忠|固原|中卫|呼和浩特|包头|乌海|赤峰|通辽|鄂尔多斯|呼伦贝尔|巴彦淖尔|乌兰察布|霍林郭勒|满洲里|牙克石|扎兰屯|根河|额尔古纳|丰镇|锡林浩特|二连浩特|乌兰浩特|


参考

echo strstr('aaaaaaaaaaaboaaaaaaaaaaaaboxcccccccccbcccccccccccccc','box')."n"; 

05 // 完整匹配中间的box 不因前而的b而停止 

06 echo strstr('aaaaaaAbaaa aaaa aaaaaaaaaboxccccccccccccboxccccccccccc','box')."n"; 

07 // 有两个关键字时, 遇到第一个停止. 

08 echo strstr('Subscrtibe our to free newsletter about New Freew to','to')."n"; 

09   
吧。

标签:[!--infotagslink--]

您可能感兴趣的文章: