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

471次阅读
没有评论

共计 1585 个字符,预计需要花费 4 分钟才能阅读完成。

用过 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()

 

正文完
 
admin
版权声明:本站原创文章,由 admin 2020-01-13发表,共计1585字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码