AWS Lightsail 流量超出自动关机脚本(Python)

小助手读文章 00:00 / 00:00

温馨提示:
本文所述内容具有依赖性,可能因软硬条件不同而与预期有所差异,故请以实际为准,仅供参考。

用过 AWS 的几乎都会有莫名其妙被扣费的经历,倒不是说 AWS 收费不透明,而是项目非常多,很容易就会被忽视。比如说,如果你在 20 号开启了 Lightsail 免费试用一个月,正常来说我们会认为是试用期到下个月 20 号,但实际上,不管是 EC2 还是 Lightsail 都是 1 号出账并重置流量,也就是说试用期只到本月底,一不小心就会被收取 20 天的费用,当然了,大部分人是用 40 刀、100 刀、150 刀服务抵扣券去开的服务......

以下内容保存为脚本文件,加入开机启动即可(需要 root 权限),只在亚马逊的 Debian 8.7 系统测试过。

#!/usr/bin/python
#coding=utf-8
import sys,re,time,os
maxdata = 1073741824 #流量上限,包括流入和流出,单位Byte
memfilename = '/root/newnetcardtransdata.txt'
netcard = '/proc/net/dev'
def checkfile(filename):
    if os.path.isfile(filename):
        pass
    else:
        f = open(filename, 'w')
        f.write('0')
        f.close()
def get_net_data():
    nc = netcard or '/proc/net/dev'
    fd = open(nc, "r")
    netcardstatus = False
    for line in fd.readlines():
        if line.find("eth0") > 0:
            netcardstatus = True
            field = line.split()
            recv = field[0].split(":")[1]
            recv = recv or field[1]
            send = field[9] #如果流量计算错误,请根据/proc/net/dev的内容修改此变量
    if not netcardstatus:
        fd.close()
        print 'Please setup your netcard'
        sys.exit()
    fd.close()
    return (float(recv), float(send))
    
def net_loop():
    (recv, send) = get_net_data()
    checkfile(memfilename)
    lasttransdaraopen = open(memfilename,'r')
    lasttransdata = lasttransdaraopen.readline()
    lasttransdaraopen.close()
    totaltrans = int(lasttransdata) or 0
    while True:
        time.sleep(3)
        nowtime = time.strftime('%d %H:%M',time.localtime(time.time()))
        sec = time.localtime().tm_sec
        if nowtime == '01 00:00': #流量更新时间,默认为每月1日00:00
            if sec < 10:
                totaltrans = 0
        (new_recv, new_send) = get_net_data()
        recvdata = new_recv - recv
        recv = new_recv
        senddata = new_send - send
        send = new_send
        totaltrans += int(recvdata)
        totaltrans += int(senddata)
        memw = open(memfilename,'w')
        memw.write(str(totaltrans))
        memw.close()
        if totaltrans >= maxdata:
            os.system('rm -f /root/newnetcardtransdata.txt && init 0') #可以修改为其他命令
if __name__ == "__main__":
    net_loop()

另外提一句, AWS 是双向计流量~


参考文章:
1、《AWS Lightsail 流量超出自动关机脚本


ArmxMod for Typecho
个性化、自适应、功能强大的响应式主题

推广

 继续浏览关于 awsamazonlightsail流量自动关机脚本 的文章

 本文最后更新于 2018/12/03 10:56:13,可能因经年累月而与现状有所差异

 引用转载请注明: VirCloud's Blog > 经验 > AWS Lightsail 流量超出自动关机脚本(Python)