#教程# 阿里云国际 – 流量包脚本监控 超流量自动关机
很多同学在使用#阿里云##国际#的时候被无聊的人#刷流量#,导致很快#流量包#被用完,这里给出个 PHP 的#监控#,用定时 cron 实现超流量就自动关机。
把下面的文件保存为 datamonitoring.php
{
$canonicalizedQueryString .= ‘&’ . percentEncode($key)
. ‘=’ . percentEncode($value);
}
// 生成用于计算签名的字符串 stringToSign
$stringToSign = ‘GET&%2F&’ . percentencode(substr($canonicalizedQueryString, 1));
// 计算签名,注意 accessKeySecret 后面要加上字符’&’
$signature = base64_encode(hash_hmac(‘sha1’, $stringToSign, $accessKeySecret . ‘&’, true));
return $signature;
}
function get_action($data,$Version,$host){
date_default_timezone_set(“GMT”);
$dateTimeFormat = ‘Y-m-d\TH:i:s\Z’;
global $AccessKey_ID;
global $Access_Key_Secret;
$publicdata = array(
// 公共参数
‘Format’ => ‘JSON’,
‘Version’ => $Version,
‘AccessKeyId’ => $AccessKey_ID,
‘SignatureVersion’ => ‘1.0’,
‘SignatureMethod’ => ‘HMAC-SHA1’,
‘SignatureNonce’=> uniqid(),
‘Timestamp’ => date($dateTimeFormat),
‘TimeStamp’ => date($dateTimeFormat)
);
$data = array_merge($publicdata,$data);
$data[‘Signature’] = computeSignature($data, $Access_Key_Secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host . http_build_query($data));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
date_default_timezone_set(‘PRC’);
//echo $res;
return $res;
}
//流量 JSON
function get_(){
$data = array(
‘Action’ => ‘QueryResourcePackageInstances’,
‘RegionId’ => ‘ap-southeast-1′
);
$res = (string)get_action($data,’2017-12-14′,’https://business.ap-southeast-1.aliyuncs.com/?’);
//echo $res;
$jsonarray = json_decode($res,true);
if($jsonarray[‘Message’]==’Successful!’){
echo $jsonarray[‘Data’][‘Instances’][‘Instance’][0][‘RemainingAmount’];
if($jsonarray[‘Data’][‘Instances’][‘Instance’][0][‘RemainingAmount’]<=20){//这里判断流量小于 20G StopInstance(); } } } function StopInstance(){ global $InstanceId; $data = array( ‘Action’ => ‘StopInstance’,
‘InstanceId’ => $InstanceId,
‘ForceStop’ =>”true”,
‘StoppedMode’ => “keepcharging”,
‘ConfirmStop’ => “false”
);
$res = (string)get_action($data,’2014-05-26′,’https://ecs.aliyuncs.com/?’);
echo $res;
}
get_();
?>
自行更改 用户 AccessKey 地区 机器 ID
如果只有 1 台 ecs 且是新加坡的 只需修改上面 3 个变量值 就能使用
AccessKey 获取方式 登录阿里云-进入控制台-右上角头像-AccessKey
机器 ID 就是 ecs 的 id
然后在/var/spool/cron/root 里添加
*/1 * * * * /root/datamonitoring.php >> /home/wwwlogs/datamonitoring.log
每分钟检测一次,日志保存在/home/wwwlogs/datamonitoring.log