sqlite处理数据
- # coding: UTF-8
- import platform
- from _utils.patrol2 import run_cmd, data_format, report_format
- import os, sys, re, json, copy
- import stat
- import socket
- import stat
- import sqlite3
- #
- # conn=sqlite3.connect(':memory:')
- if os.path.exists('was_patrol.db'):
- os.remove('was_patrol.db')
- conn = sqlite3.connect('was_patrol.db')
- c = conn.cursor()
- c.execute('''CREATE TABLE WAS
- (ID INT PRIMARY KEY NOT NULL,
- CELL CHAR(50),
- HOME CHAR(50),
- CLUSTER CHAR(50),
- NODE CHAR(50),
- SERVER CHAR(50),
- STATE CHAR(50),
- PORTS CHAR(500),
- HOST CHAR(50));''')
- print "Table created successfully"
- conn.commit()
- version = version.split('.')[0]
- content = """import sys, java
- def get_names(type,parent_obj=None):
- if not parent_obj:
- obj_list = AdminConfig.list(type)
- else:
- obj_list = AdminConfig.list(type, parent_obj)
- if len(obj_list) == 0:
- return [],None
- obj_lists = obj_list.split(lineSeparator)
- names=[]
- for obj in obj_lists:
- name = AdminConfig.showAttribute(obj, "name")
- names.append(name)
- return names,obj_lists
- lineSeparator = java.lang.System.getProperty('line.separator')
- cell_names,cells=get_names("Cell")
- reports = []
- print cell_names,cells
- for cell in cells:
- cell_name=AdminConfig.showAttribute(cell, "name")
- cluster_names,clusters=get_names("ServerCluster",parent_obj=cell)
- node_names, nodes = get_names("Node", parent_obj=cell)
- for node in nodes:
- nname = AdminConfig.showAttribute(node, "name")
- server_names, servers = get_names("Server", parent_obj=node)
- hostname= AdminConfig.showAttribute(node, "hostName")
- print 'node:',node
- print 'servers:',servers
- for server in servers:
- type=AdminConfig.showAttribute(server, "serverType")
- if type=='NODE_AGENT':
- continue
- sname = AdminConfig.showAttribute(server, "name")
- cname = AdminConfig.showAttribute(server, "clusterName")
- runserv = AdminConfig.getObjectName(server)
- if len(runserv) > 0:
- state = AdminControl.getAttribute(runserv, "state")
- else:
- state='down'
- other_port=id=''
- if int('{version}')>=6:
- ports=AdminTask.listServerPorts(sname, '[-nodeName '+nname+']')
- else:
- ports=[]
- endpoints=AdminConfig.list('EndPoint', server).split(lineSeparator)
- print endpoints
- #endpoints=AdminConfig.list('EndPoint', AdminConfig.getid( '/Cell:'+cell_name+'/Node:'+nname+'/Server:'+sname+'/')).split(lineSeparator)
- for endpoint in endpoints[1:]:
- end_result=AdminConfig.show(endpoint).split(lineSeparator)
- print end_result
- if end_result:
- ports.append(end_result[1].split()[1].split(']')[0])
- ports=','.join(ports)
- print ports
- id=AdminConfig.getid( '/Cell:'+cell_name+'/VirtualHost:default_host/')
- if not id:
- id=AdminConfig.getid( '/Cell:'+cell_name+'/VirtualHost:admin_host/')
- if id:
- other_port=AdminConfig.list('HostAlias',id ).split(lineSeparator)[0]
- other_port=AdminConfig.showAttribute(other_port,'port')
- if not cname:
- # no cluster and has server
- reports.append({{'cell': cell_name, 'cluster': 'N/A', 'server': sname, 'node': nname,'obj':server,'state':state,'ports':ports,'host':hostname,'other_port':other_port}})
- else:
- # has cluster and node
- reports.append({{'cell': cell_name, 'cluster': cname, 'server': sname, 'node': nname,
- 'obj': server,'state':state,'ports':ports,'host':hostname,'other_port':other_port}})
- print 'clusters',clusters
- reports1=[]
- if clusters:
- for cluster in clusters:
- cluster_name = AdminConfig.showAttribute(cluster, "name")
- memberList = AdminConfig.showAttribute(cluster, "members")
- if memberList!='[]' and memberList!=[] :
- #has cluster and node
- #pass
- members = memberList[1:len(memberList)-1].split(" ")
- for member in members:
- mname = AdminConfig.showAttribute(member, "memberName")
- nname = AdminConfig.showAttribute(member, "nodeName")
- reports1.append({{'cell':cell_name,'cluster':cluster_name,'server':mname,'node':nname,'obj':server}})
- else:
- # has cluster and no node
- reports1.append({{'cell':cell_name,'cluster':cluster_name,'server':'N/A','node':'N/A','obj':None}})
- print "==data=="
- print reports
- print "==data=="
- print "==datas=="
- print reports1
- print "==datas=="
- """.format(version=version)
- if 'Windows' in platform.system():
- tmp_script = 'C:\\patrol.py'
- else:
- tmp_script = '/tmp/patrol.py'
- with open(tmp_script, 'w') as f:
- f.write(content)
- os.chmod(tmp_script, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
- hostname = platform.node()
- was_homes = was_home
- datas = {'cell': [], 'cluster': [], 'node': [], 'server': []}
- all_reports = []
- cell_reports = []
- cluster_reports = []
- server_reports = []
- resource = []
- count = 0
- for was_home in was_homes.split(','):
- run_script = os.path.join('{}'.format(was_home), 'bin/wsadmin.sh')
- if mw_password:
- password = '-password {}'.format(mw_password)
- else:
- password = ''
- if 'Windows' in platform.system():
- run_script = os.path.join('{}'.format(was_home), 'bin', 'wsadmin.bat')
- cmd = '"{}" -username {} {} -lang jython -f {}'.format(run_script, mw_user, password,
- tmp_script)
- else:
- cmd = 'su {} -c "{} -username {} {} -lang jython -f {}"'.format(os_was_user,
- run_script, mw_user,
- password,
- tmp_script)
- print cmd
- code, out = run_cmd(cmd)
- print out
- if 'Ensure that user and password are correct' in out:
- print '请确认输入的用户名和密码是否正确'
- sys.exit(1)
- if code:
- print out
- sys.exit(1)
- try:
- res = re.findall(r'==data==([\s\S]*)==data==', out)
- if not res:
- print '无输出'
- sys.exit(1)
- res = eval(res[0].strip())
- res1 = re.findall(r'==datas==([\s\S]*)==datas==', out)
- if not res1:
- print '无输出'
- sys.exit(1)
- res1 = eval(res1[0].strip())
- print '集群信息', res1
- except Exception as e:
- print e
- sys.exit(1)
- resource.append({'res': res, 'washome': was_home})
- cell_name = None
- for i in res:
- cell_name = i['cell']
- if i['cell'] not in datas['cell']:
- datas['cell'].append(i['cell'])
- if i['cluster'] not in datas['cluster']:
- datas['cluster'].append(i['cluster'])
- if i['node'] not in datas['node']:
- datas['node'].append(i['node'])
- if i['server'] not in datas['server']:
- datas['server'].append(i['server'])
- c = conn.cursor()
- port = ''
- ports = i.get('ports', '')
- if int(version) >= 6:
- for j in ports.split('\n'):
- if j.startswith('[[WC_adminhost ') and i['server'] == 'dmgr':
- port = j.rstrip('] ]]] ]').split(' ')[-1]
- if not port:
- for j in ports.split('\n'):
- if j.startswith('[[WC_defaulthost '):
- port = j.rstrip('] ]]] ]').split(' ')[-1]
- if not port:
- for j in ports.split('\n'):
- if j.startswith('[[WEBSERVER_ADDRESS '):
- port = j.rstrip('] ]]] ]').split(' ')[-1]
- else:
- print '端点:', ports
- import requests
- for j in ports.split(','):
- print j
- try:
- res = requests.get('http://localhost:{}/snoop'.format(j))
- if res.status_code == 200:
- port = j
- break
- if not port:
- res = requests.get('https://localhost:{}/snoop'.format(j), is_verify=False)
- if res.status_code == 200:
- port = j
- break
- except:
- pass
- if not port:
- port = ports.split(',')[0]
- print 'port',port
- state= i.get('state','')
- if int(version) <= 5:
- cmd = "netstat -Aan|grep -w '*.{}'".format(port)
- code, res = run_cmd(cmd)
- if res and 'LISTEN' in res.split()[-1]:
- state = 'STARTED'
- c.execute("INSERT INTO WAS (ID,CELL,HOME,CLUSTER,NODE,SERVER,STATE,PORTS,HOST) \
- VALUES ({}, '{}', '{}', '{}', '{}','{}','{}','{}','{}' )".format(count,
- i['cell'],
- was_home,
- i['cluster'],
- i['node'],
- i['server'],state,
- port,
- i.get('host',
- '')))
- count += 1
- conn.commit()
- print datas
- cursor = conn.execute("SELECT distinct CELL from WAS")
- cells = []
- for row in cursor:
- cell = row[0]
- if cell not in cells:
- cells.append(cell)
- cell_reports.append(data_format('单元名称', cell, alert=0, group_name="单元情况"))
- cell_num = len(cells)
- if cell_num == 1:
- all_reports.append(report_format("{}".format(hostname), cell_reports))
- else:
- all_reports.append(report_format("{}".format(hostname), childs=cell_reports))
- cell_clusters = []
- cell_cluster_report = {}
- cursor = conn.execute("SELECT id, cell, home,cluster,node, server,state,ports,host from WAS")
- for row in cursor:
- cell = row[1]
- node = row[4]
- server = row[5]
- home = row[2]
- cluster = row[3]
- if cell_num == 1:
- cell_cluster = '{}'.format(hostname)
- else:
- cell_cluster = '{}/{}'.format(hostname, cell)
- if cell_cluster not in cell_clusters:
- cell_cluster_report.update({cell_cluster: []})
- cell_clusters.append(cell_cluster)
- if cluster not in cell_cluster_report[cell_cluster]:
- cell_cluster_report[cell_cluster].append(cluster)
- reports = []
- for k, v in cell_cluster_report.items():
- for i in v:
- reports.append(data_format('集群名称', i, alert=0, group_name="集群名称"))
- all_reports.append(report_format(k, childs=reports))
- reports = json.dumps(all_reports)
- print reports
sqlite处理数据的更多相关文章
- Android 一键直接查看Sqlite数据库数据
转自:http://www.cnblogs.com/trinea/archive/2012/11/16/2773656.html 本文主要介绍Android开发中如何一键直接查看sqlite数据库中的 ...
- 解决sqlite删除数据后,文件大小不变问题(VACUUM)
删除表格的全部数据: DELETE FROM [Name] 当在sqlite中删除了大量数据后,数据库文件的大小还是那样,没有变.原因是:从Sqlite删除数据后,未使用的磁盘空间被添加到一个内在的” ...
- Python读取和处理文件后缀为".sqlite"的数据文件
最近在弄一个项目分析的时候,看到有一个后缀为”.sqlite”的数据文件,由于以前没怎么接触过,就想着怎么用python来打开并进行数据分析与处理,于是稍微研究了一下. SQLite是一款非常流行的关 ...
- 解决sqlite删除数据或者表后,文件大小不变的问题
原因分析: sqlite采用的是变长纪录存储,当你从Sqlite删除数据后,未使用的磁盘空间被添加到一个内在的"空闲列表"中用于存储你下次插入的数据,用于提高效率,磁盘空间并没有丢 ...
- 解决sqlite删除数据后,文件大小不变问题 转载
原文地址:http://blog.csdn.net/yangchun1213/article/details/7656146 说了这么多,没进主题,我的主题是给Sqlite在删除数据后擦屁股. 大 ...
- Android开发之利用SQLite进行数据存储
Android开发之利用SQLite进行数据存储 Android开发之利用SQLite进行数据存储 SQLite数据库简单介绍 Android中怎样使用SQLite 1 创建SQLiteOpenHel ...
- sqlite删除数据
sqlite删除数据 某日, 在使用sqlite的时候发现查询速度极慢, 查看了一下文件大小, sqlite数据库文件已经达到了 22G! 对于一个文件数据库来说, 已经相当致命了,先不说后面如果解决 ...
- C#(.net)实现用apache activemq传递SQLite的数据
版权声明:本文为搜集借鉴各类文章的原创文章,转载请注明出处:http://www.cnblogs.com/2186009311CFF/p/6382623.html. C#(.net)实现用apache ...
- mono for android中使用dapper或petapoco对sqlite进行数据操作
在mono for android中使用dapper或petapoco,很简单,新建android 类库项目,直接把原来的文件复制过来,对Connection连接报错部分进行注释和修改就可以运行了.( ...
- 从SQLite获取数据完成一个产品信息展示
在ios实际开发当中,我们常常用到Core Data做为数据储存首选.但在处理一些大量复杂的数据值且数据之间相互关联的时候,这就不得不使用关系型数据库来实现.例如一个导航程序,自身应该包含大量的地图自 ...
随机推荐
- SpringBoot实战一:发送邮件
目录 邮件协议 引入邮件包 创建邮件类和测试类,写yml文件 文本邮件,HTML邮件,附件邮件,图片邮件 模板邮件 异常处理 来进行一个SpringBoot项目的实战,发送一下邮件,这里我们先了解一下 ...
- 16、JDBC-DBUtils封装
使用DBUtils写个通用CURD小工具 依赖配置 pom.xml <?xml version="1.0" encoding="UTF-8"?> & ...
- 清理sql2012数据库日志
--1.先把数据库设置为简单模式(右击数据库名->点'属性'->点'选项'->恢复模式改成'简单'->点'确定'按钮,--2.再执行下面的语句(或者右击数据库点'任务'-> ...
- Web前端框架与移动应用开发第八章
Web前端框架与移动应用开发:制作58招聘专题页 1.html代码: <!DOCTYPE html><html><head> <meta charset=&q ...
- 自学python 2.
1.T or F 1>1 or 3<4 or 4>5 and 2>1 and 9>8 or 7<6 t not 2>1 and 3<4 or 4> ...
- Vector集合
Vector集合也是List接口的一个实现类,但是它是同步的,这就意味着是单线程的,速度比较慢,被ArrayList集合所取代了(PS:为什么我现在也还不知道,先记录了)
- python中\r的意义及用法
\r的意义 \r 表示将光标的位置回退到本行的开头位置 \b表示将光标的位置回退一位 在python里print会默认进行换行,可以通过修改参数让其不换行 (1) python2中可以在print语句 ...
- Sliverlight常见错误集锦
1. 使用GridSplitter时候(参考),出现如下错误 C# 中的错误Error 2 The type 'sp:GridSplitter' was not found. Verify…… 对程序 ...
- js 操作对象 记录
js 对象记录一下: let obj_1 = { name : 'james', age : '22', sex: '1' } for ( i in obj_1 ) { console.log(i) ...
- .Net结合JQuery实现向aspx后台函数进行请求。
$.ajax({ url: "Default.aspx/aaaa", async: false, type: "POST", c ...