Exemplo n.º 1
0
def check_paramiko():
    r_handle = os.popen('python -c "import paramiko;"')
    result = r_handle.read()
    r_handle.close()
    if result.find('No module named') == -1:
        info(u'paramiko包检查结果:正常。')
    else:
        err(u'paramiko包检查结果:异常,请手动安装,否则会导致无法自动清理存储空间。')
Exemplo n.º 2
0
def check_vpr_config(db_cursor, local_ip, db_ip):
    cp = ConfigParser.ConfigParser()
    cp.read('/home/park/config/config.cfg')

    vpr_in_cfg = cp.get('vpr', 'in_ip').strip()
    vpr_in_cfg2 = cp.get('vpr', 'in_ip2').strip()
    vpr_out_cfg = cp.get('vpr', 'out_ip').strip()
    vpr_out_cfg2 = cp.get('vpr', 'out_ip2').strip()
    vpr_type = cp.get('vpr', 'vpr_type').strip()
    db_server = cp.get('mysql', 'host').strip()

    db_cursor.execute(
        'select depot_site.vpr_ip, depot_site.vpr_1_ip from depot_site,depot_terminal where depot_site.terminal_id = '
        'depot_terminal.id and depot_terminal.ip = "%s" and depot_site.is_in_site = 1; '
        % local_ip)

    value = db_cursor.fetchall()
    if value:
        vpr_in_db = value[0][0].strip()
        vpr_in_db2 = value[0][1].strip()
    else:
        vpr_in_db = ''
        vpr_in_db2 = ''

    db_cursor.execute(
        'select depot_site.vpr_ip, depot_site.vpr_1_ip from depot_site,depot_terminal where '
        'depot_site.terminal_id = depot_terminal.id and depot_terminal.ip = "%s" and depot_site.is_in_site = 0; '
        % local_ip)
    value = db_cursor.fetchall()

    if value:
        vpr_out_db = value[0][0].strip()
        vpr_out_db2 = value[0][1].strip()
    else:
        vpr_out_db = ''
        vpr_out_db2 = ''

    flag = 0
    if vpr_in_cfg != vpr_in_db:
        err(u'进口主相机ip配置不一致,页面配置值:%s,config文件值:%s,请同步页面配置值到config.cfg文件。' %
            (vpr_in_db, vpr_in_cfg))
        flag = 1
    if vpr_in_cfg2 != vpr_in_db2:
        err(u'进口辅相机ip配置不一致,页面配置值:%s,config文件值:%s,请同步页面配置值到config.cfg文件。' %
            (vpr_in_db2, vpr_in_cfg2))
        flag = 1
    if vpr_out_cfg != vpr_out_db:
        err(u'出口主相机ip配置不一致,页面配置值:%s,config文件值:%s,请同步页面配置值到config.cfg文件。' %
            (vpr_out_db, vpr_out_cfg))
        flag = 1
    if vpr_out_cfg2 != vpr_out_db2:
        err(u'出口辅相机ip配置不一致,页面配置值:%s,config文件值:%s,请同步页面配置值到config.cfg文件。' %
            (vpr_out_db2, vpr_out_cfg2))
        flag = 1

    if not flag:
        info(u'V3 相机配置一致性检查结果:正常。')
Exemplo n.º 3
0
def check_network_connection():
    r_handle_in = os.popen("ping -c 1 sc.parkingwang.com")
    result = r_handle_in.read()
    r_handle_in.close()
    lost_per = ''
    index = result.rfind('% packet loss,')
    if index != -1:
        index_begin = result[:index].rfind(' ')
        if index_begin != -1:
            lost_per = result[index_begin + 1:index]
    if lost_per and int(lost_per) > 0:
        err(u'外网检测异常,请检查网络连接和DNS。')
    else:
        info(u'外网检测正常。')
Exemplo n.º 4
0
def main():
    start()
    try:
        charge_no = sys.argv[1]
        log_date = sys.argv[2]
        log_date = datetime.datetime.strptime(log_date, '%Y-%m-%d').date()

        lines = read_log_lines(LogFile.IData, log_date)
        if not lines:
            raise Exception('Read nothing from log')
        sync_info = sync_info_extract(lines, charge_no)
        info(sync_info.__repr__())
    except Exception, e:
        err('%s\n%s' % (str(e), traceback()))
Exemplo n.º 5
0
def check_disk_space():
    r_handle = os.popen('df -hl')
    result = r_handle.read()
    r_handle.close()
    # debug(result)

    patt = re.compile('.*?/dev/root.*?(\d+)%.*?', re.I)
    temp = patt.findall(result)
    if temp:
        value = int(temp[0])
        if value > 90:
            err(u'磁盘占用:%i%%, 存储满,请手动清理。' % value)
        else:
            info(u'磁盘占用:%i%%, 正常。' % value)
    else:
        err(u'磁盘空间检查失败,无法获取到磁盘占用')
Exemplo n.º 6
0
def check_link_file():
    r_handle = os.popen(
        '''python -c "import os,sys,irain_lib; print sys.modules['irain_lib'].__version__"'''
    )
    result = r_handle.read().strip()
    r_handle.close()
    info('版本检查: %s' % result)
    err_list = []
    file_list = [
        '/usr/local/lib/python2.7/dist-packages/irain_park-%s-py2.7.egg/irain_web/app/static/xls'
        % result
    ]
    for item in file_list:
        if not (not os.path.isfile(item) and os.path.exists(item)):
            err_list.append(item)
    if not err_list:
        info(u'V3 链接文件检查结果:正常。')
    else:
        err(u'V3 链接文件检查结果:异常,缺少以下文件:%s。' % err_list)
Exemplo n.º 7
0
def check_boa_and_serial(db_cursor, local_ip):
    db_cursor.execute("select id from depot_terminal where ip = '%s'" %
                      local_ip)
    terminal_id = db_cursor.fetchall()[0][0]
    db_cursor.execute(
        'select conf_value from depot_terminal_detail where terminal_id = %d and conf_type = "img_server_port";'
        % terminal_id)
    boa_port_conf = ''
    value = db_cursor.fetchall()
    if value:
        boa_port_conf = value[0][0]

    with open('/etc/boa/boa.conf', 'rb') as r_handle:
        text = r_handle.read()

    patt = re.compile('.*?Port\s+(\d+).*?', re.I)
    temp = patt.findall(text)
    value = ''
    if temp:
        value = temp[0]

    if boa_port_conf == value:
        info(u'boa 配置检查结果, 正常。')
    else:
        err(u'boa 配置检查结果:错误,系统配置值:%s, boa.conf配置值:%s' % (boa_port_conf, value))

    serial_trans_flag = '0'
    db_cursor.execute(
        'select conf_value from depot_terminal_detail where terminal_id = %d and conf_type = '
        '"serial_trans_camera_flag"; ' % terminal_id)
    boa_port_conf = ''
    value = db_cursor.fetchall()
    if value:
        serial_trans_flag = value[0][0]

    if serial_trans_flag == '1':
        info(u'车场透传标志校验结果:正常。')
    else:
        err(u'车场透传标志校验结果:未开启,请确认此终端是否为非透传模式。')
Exemplo n.º 8
0
def main():
    start()
    try:
        vpr = sys.argv[1]
        log_datetime = sys.argv[2]
        log_datetime = datetime.datetime.strptime(log_datetime,
                                                  '%Y-%m-%d %H:%M:%S')

        lines = read_log_lines(LogFile.ParkOut, log_datetime.date())
        if not lines:
            raise Exception('Read nothing from log')
        park_info = extract_park_info(lines, vpr, log_datetime)

        if u'出场方式' not in park_info:
            if u'出口报费' in park_info and park_info[u'出口报费'] == 0:
                park_info[u'出场方式'] = u'自动抬杆出场'
            else:
                park_info[u'出场方式'] = u'未知'

        info(park_info.__repr__())
    except Exception, e:
        err('%s\n%s' % (str(e), traceback()))
Exemplo n.º 9
0
def check_processes():
    r_handle = os.popen("ps -ef|grep python")
    result = r_handle.read()
    r_handle.close()
    err_proc_list = []
    # key_list = ['mails', 'code', 'codes', 'exchange']
    key_list = [
        'irain_park', 'irain_web', 'irain_websocket', 'irain_sync',
        'irain_celery'
    ]
    for item in key_list:
        if result.find(item) == -1:
            err_proc_list.append(item)

    r_handle = os.popen("ps -ef|grep vpr_ser")
    result = r_handle.read()
    r_handle.close()

    if result.find('vpr_server') == -1:
        err_proc_list.append('vpr_server')
    if not err_proc_list:
        info(u'关键进程检查结果:正常。')
    else:
        err(u'关键进程检查结果:异常,缺少以下关键进程:%s。' % err_proc_list)
Exemplo n.º 10
0
def main():
    if not os.path.exists('/home/llrp/llrpc.ini'):
        info('fail')
        return

    with open('/home/llrp/llrpc.ini') as f:
        for line in f.readlines():
            if 'client_id' in line:
                info(line)
            if 'name' in line:
                info(line)
                return
Exemplo n.º 11
0
from helper import get_local_ip, start, end, info

if __name__ == '__main__':
    start()
    info(get_local_ip())
    end()
 def install_drivers_it(self, g=False):
     helper.do("ubuntu-drivers autoinstall", True)
     helper.info("Riavvio richiesto!")
 def install_drivers(self, g=False):
     helper.do("ubuntu-drivers autoinstall", True)
     helper.info("Reboot required!")
if __name__ == "__main__":

    progress(0)
    start()

    try:
        db_ip, db_port = get_mysql_addr()
        arm_ip = os.popen(
            "ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1"
        ).read()
    except Exception as e:
        err("init param exception %s\n%s" % (e, traceback.format_exc()))

    try:
        info("mysqldump start")

        tool_run_time = time.strftime('%Y%m%d_%H%M%S', time.localtime())
        ssh = active_connect(str(arm_ip), 22, "root", "iraindev10241GB")
        ssh.exec_command(
            "mysqldump -h%s -uroot -piraindb10241GB irain_park new_auth_charge > /home/park/new_auth_charge_%s.sql"
            % (db_ip, tool_run_time))

        info("mysqldump new_auth_charge end")

    except Exception as e:
        err("dump new_auth_charge failed:%s" % e)

    try:
        info("operate mysql start")
Exemplo n.º 15
0
from helper import get_all_terminals_addr, start, end, info

if __name__ == '__main__':
    start()
    for addr in get_all_terminals_addr():
        info(addr)
    end()
Exemplo n.º 16
0
        db_ip, db_port = get_mysql_addr()
        end_time = sys.argv[1]
    except Exception as e:
        err("init param exception %s\n%s" % (e, traceback.format_exc()))

    try:
        if not os.path.exists("./db_dump"):
            os.mkdir("./db_dump")
        tool_run_time = time.strftime('%Y%m%d_%H%M%S', time.localtime())
        f_path = os.path.join("./db_dump",
                              "irain_parkin_inside_'%s'.sql" % tool_run_time)
        os.system(
            "mysqldump - h'%s' - uroot - piraindb10241GB irain_park park_in park_inside "
            "> %s" % (db_ip, f_path))

        info("dump park_inside success: %s: %s" % (get_local_ip(), f_path))

    except Exception as e:
        err("dump mysql park_inside failed")

    try:
        conn = MySQLdb.connect(host=db_ip,
                               port=db_port,
                               user='******',
                               passwd='iraindb10241GB',
                               db='irain_park',
                               charset='utf8')
        cursor = conn.cursor()
        cursor.execute("delete from park_inside where park_in_id in "
                       "(select id from park_in where in_time <= '%s')" %
                       end_time)
Exemplo n.º 17
0
from helper import get_mysql_addr, start, info, err, end, progress, traceback, get_local_ip
import os

bak_dir = 'db_backup/'
if __name__ == '__main__':
    try:
        start()

        db_user = '******'
        db_pwd = 'iraindb10241GB'

        progress(5, '开始获取数据库地址')
        db_ip, db_port = get_mysql_addr()
        progress(10, '获取成功')

        info('数据库 %s : %d' % (db_ip, db_port))

        if not os.path.exists(bak_dir):
            progress(25, '未找到 %s 目录,自动创建该目录' % bak_dir)
            os.makedirs(bak_dir)

        progress(40, '开始进行备份,过程中将使得数据库不可用,进出车将无法正常工作')

        f_path = os.path.join(
            bak_dir, '%s.sql' % str(datetime.datetime.now()).replace(' ', '_'))
        os.system('mysqldump -u%s -p%s -h%s irain_park > %s' %
                  (db_user, db_pwd, db_ip, f_path))

        progress(95, '备份成功')

        progress(98, '备份文件地址:%s:%s' % (get_local_ip(), f_path))
Exemplo n.º 18
0
                out = "%s" % (chan.recv(1024 * 100)).decode("ascii")
                info += "number of httpd process: %d"  %(int(out))
                break

        chan.close()
        client.close()
    except Exception, e:
        print "*** Caught exception : %s %s" % (e.__class__, e)

        traceback.print_exc()
        try:
            client.close()
        except:
            pass

if __name__ == "__main__":
    while True:
        info = ""
        config = ConfigParser()
        config.read(pwd + "/config.ini")
        checktoday_config = dict(config.items('checktoday'))

        for section in config.sections():
            if section != "checktoday":
                distance = dict(config.items(section))
                if distance["protocal"] == "ssh":
                    check_server_with_ssh(distance["ip"], distance["user"], distance["port"], distance["name"])

        helper.info(info)
        time.sleep(float(checktoday_config["internal"]))
Exemplo n.º 19
0
        cursor.execute("SELECT ip FROM depot_terminal;")
        ip_list = cursor.fetchall()
    except Exception as e:
        err("check terminal ip failuer %s\n%s" % (e, traceback.format_exc()))

    try:
        threads = []

        def work(addr):
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(addr[0], port=22, username='******', password='******', timeout=60)
            _, stdout, _ = ssh.exec_command("cd /home/park;sh restart.sh")
            stdout.read()

        for ip in ip_list:
            t = threading.Thread(target=work, args=(ip,))
            t.start()
            threads.append(t)

        for t in threads:
            t.join()

        progress(100)
        info("success")

    except Exception as e:
        err("restart failuer: %s\n%s" % (e, traceback.format_exc()))

    end()
Exemplo n.º 20
0
        f = xlwt.Workbook()  # 创建工作簿
        sheet1 = f.add_sheet(u'场内记录', cell_overwrite_ok=True)  # 创建sheet
        row0 = [u'进场时间', u'车牌号']
        for i in range(0, len(row0)):
            sheet1.write(0, i, row0[i], set_style('Times New Roman', 220,
                                                  True))
        for j in range(0, len(result)):
            sheet1.write(j + 1, 0, str(result[j][0]))
            sheet1.write(j + 1, 1, result[j][1])
        tool_run_time = time.strftime('%Y%m%d_%H%M%S', time.localtime())

        if not os.path.exists("./excel"):
            os.mkdir("./excel")

        f_path = os.path.join("./excel",
                              "inside_records_%s.xlsx" % tool_run_time)
        f.save(f_path)

        progress(80)
        info("FilePath:%s" % os.path.abspath(f_path))

        progress(100)
        info("success")

    except Exception as e:
        err("check terminal ip failuer %s\n%s" % (e, traceback.format_exc()))
        end()
        sys.exit(1)

    end()
Exemplo n.º 21
0
def main():
    run_sql('create index trace_pay_uk on pay_count_history(trace_pay_uk)')
    info('ok')
Exemplo n.º 22
0
def sms():
    response = twiml.Response()
    from_number = request.values.get('From', None)
    body = request.form['Body']
    reg = re.compile('[r|R]eg name:[\s|\S]+ dob:[\s|\S]+ zipcode:[\s|\S]+')
    send = re.compile('[s|S]end \+\d\d\d\d\d\d\d\d\d\d\d')
    email = re.compile('[e|E]mail [\s|\S]+@[\s|\S]+.[\s|\S]+')
    if reg.match(body) is not None:
        if from_number in db:
            response.sms("User already exists!")
        else:
            input = re.split(' name:| dob:| zipcode:', body)
            name = input[1]
            dobarray = input[2].split('/')
            month = dobarray[0]
            day = dobarray[1]
            year = dobarray[2]
            dob = datetime.datetime(int(year), int(month), int(day))
            zipcode = input[3]
            db[from_number] = {
                "name":name,
                "dob":dob,
                "zipcode":zipcode,
                "bcg":0,
                "hepb1":0,
                "hepb2":0,
                "hepb3":0,
                "polio1":0,
                "polio2":0,
                "polio3":0,
                "polio4":0,
                "polio5":0,
                "polio6":0,
                "polio7":0,
                "polio8":0,
                "dtp1":0,
                "dtp2":0,
                "dtp3":0,
                "dtp4":0,
                "dtp5":0,
                "tdap":0,
                "hib1":0,
                "hib2":0,
                "hib3":0,
                "hib4":0,
                "pcv1":0,
                "pcv2":0,
                "pcv3":0,
                "pcv4":0,
                "rv1":0,
                "rv2":0,
                "rv3":0,
                "measles":0,
                "mmr1":0,
                "mmr2":0,
                "var1":0,
                "var2":0,
                "hepa1":0,
                "hepa2":0,
                "typhoid":0,
                "hpv1":0,
                "hpv2":0,
                "hpv3":0,
            }
            response.sms(helper.confirmationMsg(name, dob, zipcode))
    elif from_number not in db:
        response.sms("Please register first!")
    elif body in vaccineCode:
        if db[from_number][vaccineCode[body]] != 0:
            response.sms("Already received vaccine!")
        else:
            db[from_number][vaccineCode[body]] = datetime.datetime.now()
            response.sms(helper.responseFromVaccine(vaccineCode[body])) 
    
    elif body == "record" or body =="Record":
        response.sms(helper.info(db[from_number], vaccineTimes))
    elif send.match(body) is not None:
        inputs = body.split('+')
        args = ['curl', '-u', 'zD93Tl5vChhg63gpeRLF8JiSvVBCaKEk:AZmEit4I6WQQ19y5QCHWyOVjU5VV2JrpdPtqaIXc4R8In0xQ', '-vX', 'POST', 'https://api.tigertext.me/v1/message', '--data-urlencode', 'recipient=+' + str(inputs[1]), '--data', 'body=' + helper.sendInfo(db[from_number], vaccineTimes, db[from_number]["name"]), '--data', 'ttl=7200']
        subprocess.call(args)
        response.sms("Success: record sent")
    elif email.match(body) is not None:
        addr = body.split()[1]
        args = ['curl', '--user', '68cd5472024e0b9bd997d7d3ba2ed22f:e7e35bfa50119ca4bf77bc6dd534f43e', 'https://api.mailjet.com/v3/send', '-F', '[email protected]', '-F', 'to=' + addr, '-F', 'subject=Immunization Record for ' + db[from_number]["name"], '-F', 'text=' + helper.sendInfo(db[from_number], vaccineTimes, db[from_number]["name"])]
        subprocess.call(args)
        response.sms("Success: record sent")
    else:
        response.sms("Error: Ill-formed Submission")
     
    return str(response)
Exemplo n.º 23
0
from helper import get_mysql_addr, start, end, info

if __name__ == '__main__':
    start()
    addr = get_mysql_addr()
    info('%s %d' % (addr[0], addr[1]))
    end()
# coding:utf-8
from helper import start, end, get_mysql_addr, info
import os

if __name__ == '__main__':
    start()
    db_ip, _ = get_mysql_addr()
    _, out = os.popen2(
        """mysql -uroot -piraindb10241GB -h%s -sN irain_park -e 'update project_conf set value = "http://img.parkingwang.com/picupload/" where id=3'"""
        % db_ip)
    info(out.read())

    _, out = os.popen2(
        """mysql -uroot -piraindb10241GB -h%s -sN irain_park -e 'select value from project_conf where id=3'"""
        % db_ip)
    info(out.read())

    end()