>  기사  >  php教程  >  SAE域名绑定设置服务器宕机时自动修改A记录并飞信通知

SAE域名绑定设置服务器宕机时自动修改A记录并飞信通知

WBOY
WBOY원래의
2016-05-25 16:40:312252검색

SAE域名绑定之后,一般是用CNAME方式将域名绑定到应用中。但是有时候我们需要用到A记录(比如说根域名,虽然在DNSPOD上可以设置CNAME记录,但很可能会影响到MX记录),而SAE的IP地址经常改变,ping应用二级域名得到的IP没多久就失效了(前些天网站因此几天打不开都没发现,我用的是教育网,自己能打开,但是电信线路变了)。还好DNSPOD有个功能叫D监控,可以帮你监控网站能否正常打开。如果发现宕机,DNSPOD会用邮件、短信、微信等方式提醒你。这里用到的是它的另一个通知方式,那就是URL回调"通过DNSPod 提供的D监控 URL 回调功能,您可以让宕机或恢复信息提交到您指定的 URL 上,从而更加灵活地处理各种通知信息。"

我们可以通过宕机之后的URL回调取得相关参数,并通过DNSPOD API实现自动修改记录的功能,再通过飞信发送宕机通知。

代码在后面,先说设置方法:

1.点此下载代码,修改其中的参数为你自己的。

2.将代码上传到网站。

3.在DNSPOD开启D监控,在通知设置中回调URL一栏填入monitorCallback.php的地址,如http://blog.gimhoy.com/monitorCallback.php?rHost=hipic.sinaapp.com.其中rHost是SAE的二级域名。并设置回调密钥。

4.Enjoy~ dnspod-monitor-callback

monitorCallback.php,代码如下:

<?php
/*
 * Copyright 2007-2014 Gimhoy Studio.
 *
 * @author Gimhoy
 * @email contact@gimhoy.com
 * @version 1.0.0
*/
$rHost = $_GET[&#39;rHost&#39;]; // SAE二级域名
if (emptyempty($rHost)) $rHost = &#39;sinaapp.com&#39;;
$logName = &#39;monitorLog.txt&#39;; //log 文件名
$logStorDomain = &#39;log&#39;; // Storage Domain
$FetionNum = &#39;&#39;; //飞信登陆号码
$FetionPwd = &#39;&#39;; //飞信登陆密码
$MobileNum = &#39;&#39;; //接收通知短信的号码
$callback_key = &#39;MYKEY&#39;; // 添加监控时设置的密钥
$monitor_id = $_POST[&#39;monitor_id&#39;]; // 监控编号
$domain_id = $_POST[&#39;domain_id&#39;]; // 域名编号
$domain = $_POST[&#39;domain&#39;]; // 域名名称
$record_id = $_POST[&#39;record_id&#39;]; // 记录编号
$sub_domain = $_POST[&#39;sub_domain&#39;]; // 主机名称
$record_line = $_POST[&#39;record_line&#39;]; // 记录线路
$ip = $_POST[&#39;ip&#39;]; // 记录IP
$status = $_POST[&#39;status&#39;]; // 当前状态
$status_code = $_POST[&#39;status_code&#39;]; // 状态代码
$reason = $_POST[&#39;reason&#39;]; // 宕机原因
$created_at = $_POST[&#39;created_at&#39;]; // 发生时间
$checksum = $_POST[&#39;checksum&#39;]; // 校检代码
if (md5($monitor_id . $domain_id . $record_id . $callback_key . $created_at) != $checksum) {
    // 非法请求
    echo &#39;BAD REQUEST&#39;;
} else {
    // 开始处理
    if ($status == &#39;Warn&#39; || $status == &#39;Ok&#39;) {
        // 宕机恢复
        $msg = date("Y-m-d H:i:s") . &#39; &#39; . $sub_domain . &#39;.&#39; . $domain . "(" . $record_line . " " . $ip . ")宕机恢复";
    } elseif ($status == &#39;Down&#39;) {
        // 宕机
        $msg = date("Y-m-d H:i:s") . &#39; &#39; . $sub_domain . &#39;.&#39; . $domain . "(" . $record_line . " " . $ip . ")在" . $created_at . "宕机。宕机原因:" . $reason . "可用IP:";
        $ips = @gethostbyname($rHost);
        include_once &#39;dnspod.class.php&#39;;
        $newIP = $ips;
        $data = array(
            &#39;domain_id&#39; => $domain_id,
            &#39;record_id&#39; => $record_id,
            &#39;sub_domain&#39; => $sub_domain,
            &#39;record_type&#39; => &#39;A&#39;,
            &#39;record_line&#39; => $record_line,
            &#39;ttl&#39; => &#39;600&#39;,
            &#39;value&#39; => $newIP
        );
        $dnspod = new dnspod();
        $response = $dnspod->api_call(&#39;Record.Modify&#39;, $data);
        if (isset($response[&#39;status&#39;][&#39;code&#39;]) && $response[&#39;status&#39;][&#39;code&#39;] == 1) {
            $msg = $msg . $newIP . &#39;(已切换)&#39;;
        } else {
            $msg = $msg . $newIP . &#39;(切换失败,错误代码&#39; . $response[&#39;status&#39;][&#39;code&#39;] . &#39;)&#39;;
        }
    }
    //飞信通知
    require_once &#39;Fetion.class.php&#39;;
    $fetion = new PHPFetion($FetionNum, $FetionPwd);
    $result = $fetion->send($MobileNum, $msg);
    if (strpos($result, &#39;短信发送成功!&#39;) || strpos($result, &#39;发送消息成功!&#39;)) {
        $r = "成功。";
    } else {
        $r = "失败。";
    }
    $s = new SaeStorage();
    $content = $s->read($logStorDomain, $logName);
    $content = $content . $msg . &#39;。飞信通知&#39; . $r . &#39; 
&#39;; //开源代码phprm.com
    $s->write($logStorDomain, $logName, $content);
    // 处理完成
    echo &#39;DONE&#39;;
}
dnspod . class . php
/*
 * DNSPod API PHP Web 示例
 * http://www.phprm.com/
 *
 * Copyright 2011, Kexian Li
 * Released under the MIT, BSD, and GPL Licenses.
 *
*/
class dnspod {
    public function api_call($api, $data) {
        if ($api == &#39;&#39; || !is_array($data)) {
            exit(&#39;内部错误:参数错误&#39;);
        }
        $api = &#39;https://dnsapi.cn/&#39; . $api;
        $data = array_merge($data, array(
            &#39;login_email&#39; => &#39;DNSPOD登陆账号&#39;,
            &#39;login_password&#39; => &#39;DNSPOD登陆密码&#39;,
            &#39;format&#39; => &#39;json&#39;,
            &#39;lang&#39; => &#39;cn&#39;,
            &#39;error_on_empty&#39; => &#39;yes&#39;
        ));
        $result = $this->post_data($api, $data);
        if (!$result) {
            exit(&#39;内部错误:调用失败&#39;);
        }
        $results = @json_decode($result, 1);
        if (!is_array($results)) {
            exit(&#39;内部错误:返回错误&#39;);
        }
        if ($results[&#39;status&#39;][&#39;code&#39;] != 1) {
            exit($results[&#39;status&#39;][&#39;message&#39;]);
        }
        return $results;
    }
    private function post_data($url, $data) {
        if ($url == &#39;&#39; || !is_array($data)) {
            return false;
        }
        $ch = @curl_init();
        if (!$ch) {
            exit(&#39;内部错误:服务器不支持CURL&#39;);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERAGENT, &#39;Gimhoy Monitor/1.0 (contact@gimhoy.com)&#39;);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
?>

Fetion.class.php,代码如下:

<?php
header(&#39;Content-Type: text/html; charset=utf-8&#39;);
/** 
 * PHP飞信发送类
 * @author quanhengzhuang
 * @version 1.5.0
 */
class PHPFetion {
    /** 
     * 发送者手机号
     * @var string
     */
    protected $_mobile;
    /** 
     * 飞信密码
     * @param string
     */
    protected $_password;
    /** 
     * Cookie字符串
     * @param string
     */
    protected $_cookie = &#39;&#39;;
    /** 
     * Uid缓存
     * @var array
     */
    protected $_uids = array();
    /** 
     * csrfToken
     * @param string
     */
    protected $_csrfToten = null;
    /** 
     * 构造函数
     * @param string $mobile 手机号(登录者)
     * @param string $password 飞信密码
     */
    public function __construct($mobile, $password) {
        if ($mobile === &#39;&#39; || $password === &#39;&#39;) {
            return;
        }
        $this->_mobile = $mobile;
        $this->_password = $password;
        $this->_login();
    }
    /** 
     * 析构函数
     */
    public function __destruct() {
        $this->_logout();
    }
    /** 
     * 登录
     * @return string
     */
    protected function _login() {
        $uri = &#39;/huc/user/space/login.do?m=submit&fr=space&#39;;
        $data = &#39;mobilenum=&#39; . $this->_mobile . &#39;&password=&#39; . urlencode($this->_password);
        $result = $this->_postWithCookie($uri, $data);
        //解析Cookie
        preg_match_all(&#39;/.*?rnSet-Cookie: (.*?);.*?/si&#39;, $result, $matches);
        if (isset($matches[1])) {
            $this->_cookie = implode(&#39;; &#39;, $matches[1]);
        }
        $result = $this->_postWithCookie(&#39;/im/login/cklogin.action&#39;, &#39;&#39;);
        return $result;
    }
    /** 
     * 获取csrfToken,给好友发飞信时需要这个字段
     * @param string $uid 飞信ID
     * @return string
     */
    protected function _getCsrfToken($uid) {
        if ($this->_csrfToten === null) {
            $uri = &#39;/im/chat/toinputMsg.action?touserid=&#39; . $uid;
            $result = $this->_postWithCookie($uri, &#39;&#39;);
            preg_match(&#39;/name="csrfToken".*?value="(.*?)"/&#39;, $result, $matches);
            $this->_csrfToten = isset($matches[1]) ? $matches[1] : &#39;&#39;;
        }
        return $this->_csrfToten;
    }
    /** 
     * 向指定的手机号发送飞信
     * @param string $mobile 手机号(接收者)
     * @param string $message 短信内容
     * @return string
     */
    public function send($mobile, $message) {
        if ($message === &#39;&#39;) {
            return &#39;&#39;;
        }
        // 判断是给自己发还是给好友发
        if ($mobile === $this->_mobile) {
            return $this->_toMyself($message);
        } else if (strlen($mobile) === 11) {
            $uid = $this->_getUid($mobile);
        } else {
            $uid = $mobile;
        }
        return $uid === &#39;&#39; ? $this->_addFriend($mobile) : $this->_toUid($uid, $message);
    }
    protected function _getname() {
        $uri = &#39;/im/index/index.action&#39;;
        $result = $this->_postWithCookie($uri, &#39;#&#39;);
        // 匹配
        preg_match(&#39;/(.*?)</a>/si&#39;, $result, $matches);
        return $matches[2];
    }
    /*
     * 通过手机号增加好友
     * @param string $number 手机号(要加的好友手机)
     * @param string $nickname 你的名字,出现在对方的验证短信里
     * @param string $buddylist 分组,默认为空
     * @param string $localName 好友屏显名
     * @return string
    */
    protected function _addFriend($number) {
        $uri = &#39;/im/user/insertfriendsubmit.action&#39;;
        $data = &#39;nickname=&#39; . urlencode($this->_getname()) . &#39;&buddylist=1&localName=&number=&#39; . $number . &#39;&type=0&#39;;
        $result = $this->_postWithCookie($uri, $data);
        return $result;
    }
    /** 
     * 获取飞信ID
     * @param string $mobile 手机号
     * @return string
     */
    protected function _getUid($mobile) {
        if (emptyempty($this->_uids[$mobile])) {
            $uri = &#39;/im/index/searchOtherInfoList.action&#39;;
            $data = &#39;searchText=&#39; . $mobile;
            $result = $this->_postWithCookie($uri, $data);
            //匹配
            preg_match(&#39;/toinputMsg.action?touserid=(d+)/si&#39;, $result, $matches);
            $this->_uids[$mobile] = isset($matches[1]) ? $matches[1] : &#39;&#39;;
        }
        return $this->_uids[$mobile];
    }
    /** 
     * 向好友发送飞信
     * @param string $uid 飞信ID
     * @param string $message 短信内容
     * @return string
     */
    protected function _toUid($uid, $message) {
        $uri = &#39;/im/chat/sendMsg.action?touserid=&#39; . $uid;
        $csrfToken = $this->_getCsrfToken($uid);
        $data = &#39;msg=&#39; . urlencode($message) . &#39;&csrfToken=&#39; . $csrfToken;
        $result = $this->_postWithCookie($uri, $data);
        return $result;
    }
    /** 
     * 给自己发飞信
     * @param string $message
     * @return string
     */
    protected function _toMyself($message) {
        $uri = &#39;/im/user/sendMsgToMyselfs.action&#39;;
        $result = $this->_postWithCookie($uri, &#39;msg=&#39; . urlencode($message));
        return $result;
    }
    /** 
     * 退出飞信
     * @return string
     */
    protected function _logout() {
        $uri = &#39;/im/index/logoutsubmit.action&#39;;
        $result = $this->_postWithCookie($uri, &#39;&#39;);
        return $result;
    }
    protected function getgroup() {
        $uri = &#39;/im/index/index.action&#39;;
        $data = &#39;type=group&#39;;
        $result = $this->_postWithCookie($uri, $data);
        // 匹配
        preg_match_all(&#39;/contactlistView.action?idContactList=(d+)/si&#39;, $result, $matches);
        foreach ($matches[1] as $k => $v) {
            if ($k == 0) {
                $min = $v;
                $max = $v;
            } else if ($v != 9998 && $v != 9999) {
                $min = min($min, $v);
                $max = max($max, $v);
            }
        }
        return $max;
    }
    public function getyou1() {
        $list = $this->getgroup();
        for ($i = 0; $i <= $list; $i++) {
            $uri = &#39;/im/index/contactlistView.action&#39;;
            $data = &#39;idContactList=&#39; . $i . &#39;&type=group&#39;;
            $result = $this->_postWithCookie($uri, $data);
            preg_match(&#39;/(.*?)|(.*?)((.*?)/(.*?))/si&#39;, $result, $listn);
            if (!$listn[2]) {
                continue;
            }
            $shuchu.= str_replace(" ", "", $listn[2]) . "(" . $listn[4] . ")n";
            preg_match(&#39;/共(d+)页/si&#39;, $result, $zpage);
            preg_match(&#39;/共(d+)</a>页/si&#39;, $result, $dpage);
            isset($zpage[1]) ? $page = $zpage[1] : $page = $dpage[4];
            for ($j = 1; $j <= $page; $j++) {
                $uri = &#39;/im/index/contactlistView.action&#39;;
                $data = &#39;idContactList=&#39; . $i . &#39;&page=&#39; . $j;
                $result = $this->_postWithCookie($uri, $data);
                preg_match_all(&#39;/(.*?)</a>/si&#39;, $result, $matches);
                if (!$matches[1][0]) {
                    break;
                }
                for ($x = 0; $x <= 9; $x++) {
                    if (!$matches[1][$x]) {
                        continue;
                    }
                    $shuchu.= $matches[1][$x] . " " . str_replace(" ", "", $matches[3][$x]) . "n";
                }
            }
        }
        return $shuchu;
    }
    public function getyou() {
        $list = $this->getgroup();
        for ($i = 0; $i <= $list; $i++) {
            $uri = &#39;/im/index/contactlistView.action&#39;;
            $data = &#39;idContactList=&#39; . $i . &#39;&type=group&#39;;
            $result = $this->_postWithCookie($uri, $data);
            preg_match(&#39;/(.*?)|(.*?)((.*?)/(.*?))/si&#39;, $result, $listn);
            if (!$listn[2]) {
                continue;
            }
            $shuchu.= str_replace(" ", "", $listn[2]) . "(" . $listn[4] . ")n";
            preg_match(&#39;/共(d+)页/si&#39;, $result, $zpage);
            preg_match(&#39;/共(d+)</a>页/si&#39;, $result, $dpage);
            isset($zpage[1]) ? $page = $zpage[1] : $page = $dpage[4];
            for ($j = 1; $j <= $page; $j++) {
                $uri = &#39;/im/index/contactlistView.action&#39;;
                $data = &#39;idContactList=&#39; . $i . &#39;&page=&#39; . $j;
                $result = $this->_postWithCookie($uri, $data);
                preg_match_all(&#39;/(.*?)</a>/si&#39;, $result, $matches);
                if (!$matches[1][0]) {
                    break;
                }
                for ($x = 0; $x <= 9; $x++) {
                    if (!$matches[1][$x]) {
                        continue;
                    }
                    $shuchu.= $matches[1][$x] . " " . str_replace(" ", "", $matches[3][$x]) . "n";
                }
            }
        }
        return $shuchu;
    }
    /** 
     * 携带Cookie向f.10086.cn发送POST请求
     * @param string $uri
     * @param string $data
     */
    protected function _postWithCookie($uri, $data) {
        $fp = fsockopen(&#39;f.10086.cn&#39;, 80);
        fputs($fp, "POST $uri HTTP/1.1rn");
        fputs($fp, "Host: f.10086.cnrn");
        fputs($fp, "Cookie: {$this->_cookie}rn");
        fputs($fp, "Content-Type: application/x-www-form-urlencodedrn");
        fputs($fp, "User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1rn");
        fputs($fp, "Content-Length: " . strlen($data) . "rn");
        fputs($fp, "Connection: closernrn");
        fputs($fp, $data);
        $result = &#39;&#39;;
        while (!feof($fp)) {
            $result.= fgets($fp);
        }
        fclose($fp);
        return $result;
    }
}
?>


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.