├── README.md └── devops ├── api ├── __init__.py ├── __init__.pyc ├── auth.py ├── auth.pyc ├── cabinet.py ├── cabinet.pyc ├── cobbler.py ├── cobbler.pyc ├── cobbler_api.py ├── cobbler_api.pyc ├── idc.py ├── idc.pyc ├── jigui.py ├── jigui.pyc ├── login.py ├── login.pyc ├── power.py ├── power.pyc ├── report.py ├── report.pyc ├── role.py ├── role.pyc ├── select.py ├── select.pyc ├── selectd.py ├── selectd.pyc ├── server.py ├── server.pyc ├── switch.py ├── switch.pyc ├── user.py ├── user.pyc ├── zabbix.py ├── zabbix.pyc ├── zabbix_Graph_api.py ├── zabbix_Graph_api.pyc ├── zabbix_api.py ├── zabbix_api.pyc ├── zbhost.py └── zbhost.pyc ├── conf ├── .service.conf.swp ├── config_api.ini ├── config_web.ini ├── devops.sql ├── logger.conf └── service.conf ├── db.py ├── db.pyc ├── install ├── a.txt ├── cobbler.sh ├── create.sql ├── db.sql ├── demo.cfg ├── devops.sql └── install.txt ├── runapi.py ├── runweb.py ├── switch.py ├── sysinfo.py ├── tasks.py ├── tasks.pyc ├── test.py ├── util.py ├── util.pyc └── web ├── __init__.py ├── __init__.pyc ├── demo.py ├── demo.pyc ├── login.py ├── login.pyc ├── public.py ├── public.pyc ├── static ├── .DS_Store ├── images │ └── serverico │ │ ├── 0.gif │ │ ├── 1.gif │ │ ├── 2u_normal.gif │ │ ├── jg.gif │ │ ├── qiang.gif │ │ └── ta_normal.gif ├── img │ ├── .DS_Store │ ├── devops.jpg │ └── favicon.ico ├── vendor │ ├── .DS_Store │ ├── alert │ │ ├── .sweet-alert.css.swp │ │ ├── sweet-alert.css │ │ └── sweet-alert.min.js │ ├── bootstrap-multiselect.css │ ├── bootstrap-multiselect.js │ ├── bootstrap-treeview.js │ ├── bootstrap │ │ ├── css │ │ │ ├── bootstrap-datetimepicker.css │ │ │ ├── bootstrap-theme.css │ │ │ ├── bootstrap-theme.css.map │ │ │ ├── bootstrap-theme.min.css │ │ │ ├── bootstrap.css │ │ │ ├── bootstrap.css.map │ │ │ └── bootstrap.min.css │ │ ├── fonts │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ └── glyphicons-halflings-regular.woff2 │ │ └── js │ │ │ ├── bootstrap-datetimepicker.js │ │ │ ├── bootstrap-datetimepicker.zh-CN.js │ │ │ ├── bootstrap.js │ │ │ ├── bootstrap.min.js │ │ │ └── npm.js │ ├── datatable │ │ ├── datatable.css │ │ └── datatable.js │ ├── font-awesome │ │ ├── css │ │ │ ├── font-awesome.css │ │ │ └── font-awesome.min.css │ │ └── fonts │ │ │ ├── FontAwesome.otf │ │ │ ├── fontawesome-webfont.eot │ │ │ ├── fontawesome-webfont.svg │ │ │ ├── fontawesome-webfont.ttf │ │ │ └── fontawesome-webfont.woff │ ├── jquery │ │ └── jquery.min.js │ ├── metismenu │ │ ├── metis-menu.min.css │ │ └── metis-menu.min.js │ ├── sb-admin-2.css │ ├── server_down.js │ ├── server_top.js │ ├── token-field │ │ ├── bootstrap-tokenfield.js │ │ ├── bootstrap-tokenfield.min.js │ │ └── css │ │ │ ├── bootstrap-tokenfield.css │ │ │ ├── bootstrap-tokenfield.min.css │ │ │ ├── tokenfield-typeahead.css │ │ │ └── tokenfield-typeahead.min.css │ ├── validate │ │ ├── bootstrap.js │ │ └── validate.js │ ├── validform.css │ └── validform.js └── zabbix │ ├── 564_20160907172408.jpg │ ├── 565_20160907172408.jpg │ ├── 567_20160907172408.jpg │ ├── 568_20160907172408.jpg │ └── 569_20160907172408.jpg └── templates ├── 404.html ├── 500.html ├── access.html ├── apply.html ├── cabinet.html ├── cobbler.html ├── dashboard.html ├── deploy.html ├── distro.html ├── down.html ├── favicon.ico.html ├── idc.html ├── index.html ├── install.html ├── jigui.html ├── layout.html ├── layout.html.bal ├── login.html ├── maintain.html ├── maintenance.html ├── power.html ├── project.html ├── report.html ├── role.html ├── server.html ├── switch.html ├── system.html ├── template.html ├── testing.html └── userlist.html /README.md: -------------------------------------------------------------------------------- 1 | # roncoo-cmdb 2 | 龙果学院推出开源运维平台,目前版本实现:权限控制,CMDB,cobbler装机平台,zabbix管理平台,机柜展示,图像展示,故障申报
3 | 后期会持续推出发布平台,批量管理平台、希望跟大家交流学习、表结构也有更新,大家重新下载然后创建表结构 4 | 功能说明:非常感谢51reboot几位老师的指导,www.51reboot.com 5 | 6 | 相关视频地址:http://www.roncoo.com/course/view/a2d58fe08172447696412fb7af1de620 7 | 8 | 一、装机平台:基于cobbler来做二次开发. 9 | 10 | 11 | 平台指定安装操作系统版本镜像,安装的分区规划。当然定制ks文件这一块可以随机修改。 12 | 13 | 通过厂商MAC地址,指定IP,MAC,网关等,通过管理平台指定IP和系统版本之后,机房相关人员插上网线开机即可安装。 14 | 15 | 记录操作数据。 16 | 17 | 18 | 二、用户权限管理: 19 | 20 | 21 | 可以对用户进行管理,对用户增删改查修改密码等。 22 | 23 | 用户权限管理,比如监控组有zabbix操作权限,故障申报所有人都有权限,故障下架处理由管理员执行 24 | 25 | 26 | 三、CMDB管理: 27 | 28 | 29 | 机房,机柜的相关管理增删改查,这一块只有admin用户可以查看和修改。 30 | 31 | 脚本采集系统硬件数据,通过API方式提交和人工录入的半自动方式。 32 | 33 | 数据收集参数和删除。 34 | 35 | 36 | 四、zabbix管理:
37 | 38 | 39 | 通过CMDB平台联动到zabbix数据库。 40 | 41 | 实现对zabbix主机的批量模板绑定、删除;基本上已经完成zabbix管理工作。 42 | 43 | 主机出现问题,或者维护数据时候添加维护周期。 44 | 45 | 调用zabbix图形在运维平台展示 46 | 47 | 五、系统保障处理:
48 | 工程师把处理的故障上报平台,管理员,项目经理知悉;并且异步发送邮件到管理员有些,管理员给出操作指示,下架等操作 49 | 50 | 51 | 六、机柜机房拓扑展示:
52 | 根据录入的主机机房,机柜信息,进行拓扑展示。告警结合zabbix API动态展示机器状态 53 | 54 | -------------------------------------------------------------------------------- /devops/api/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_jsonrpc import JSONRPC 3 | import sys 4 | 5 | reload(sys) 6 | sys.setdefaultencoding('utf-8') 7 | 8 | app = Flask(__name__) 9 | jsonrpc = JSONRPC(app, '/api') 10 | 11 | import login 12 | import power 13 | import role 14 | import user 15 | import selectd 16 | import idc 17 | import cabinet 18 | import server 19 | import zabbix 20 | import zbhost 21 | import zabbix_api 22 | import cobbler 23 | import zabbix_Graph_api 24 | import switch 25 | import jigui 26 | import report 27 | -------------------------------------------------------------------------------- /devops/api/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/__init__.pyc -------------------------------------------------------------------------------- /devops/api/auth.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from flask import request 3 | from . import app 4 | import json,traceback 5 | import util 6 | 7 | 8 | def auth_login(func): 9 | def wrapper(*arg, **kwargs): 10 | try: 11 | authorization = request.headers.get('authorization', 'None') 12 | res = util.validate(authorization, app.config['passport_key']) 13 | res = json.loads(res) 14 | #res = {u'username': u'admin', u'code': 0, u'uid': u'1', u'r_id': u'1'} 15 | if int(res['code']) == 1: 16 | util.write_log('api').warning("Request forbiden:%s" % res['errmsg']) 17 | return json.dumps({'code': 1, 'errmsg': '%s' % res['errmsg']}) 18 | except: 19 | util.write_log('api').warning("Validate error: %s" % traceback.format_exc()) 20 | return json.dumps({'code': 1, 'errmsg': '验证异常'}) 21 | return func(res, *arg, **kwargs) 22 | wrapper.__name__ = '%s_wrapper' % func.__name__ 23 | return wrapper 24 | 25 | -------------------------------------------------------------------------------- /devops/api/auth.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/auth.pyc -------------------------------------------------------------------------------- /devops/api/cabinet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | 9 | 10 | #这里是关于用户角色的增删改查及组对应的权限id2name 11 | 12 | @jsonrpc.method('cabinet.create') 13 | @auth_login 14 | def idc_create(auth_info, **kwargs): 15 | if auth_info['code'] == 1: 16 | return json.dumps(auth_info) 17 | username = auth_info['username'] 18 | try: 19 | data = request.get_json()['params'] 20 | check_name = str(data['name']) 21 | ## if not util.check_name(check_name): 22 | # return json.dumps({'code': 1, 'errmsg': 'name must be string or int'}) 23 | app.config['cursor'].execute_insert_sql('cabinet', data) 24 | util.write_log('api').info(username, "create cabinet %s scucess" % data['name']) 25 | return json.dumps({'code':0,'result':'create cabinet %s scucess' % data['name']}) 26 | except: 27 | util.write_log('api').error(username,"create cabinet error: %s" % traceback.format_exc()) 28 | return json.dumps({'code':1,'errmsg':'create cabinet fail'}) 29 | 30 | @jsonrpc.method('cabinet.getlist') 31 | @auth_login 32 | def cabinet_select(auth_info,**kwargs): 33 | data_result = [] 34 | if auth_info['code'] == 1: 35 | return json.dumps(auth_info) 36 | username = auth_info['username'] 37 | if '1' not in auth_info['r_id']: 38 | return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) 39 | try: 40 | fields = ['id','name','idc_id','power'] 41 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 42 | res = app.config['cursor'].get_results('cabinet', fields) 43 | for i in res: 44 | where = {'id':int(i['idc_id'])} 45 | result = app.config['cursor'].get_results('idc',['id','idc_name'],where) 46 | i["idc_name"] = result[0]['idc_name'] 47 | data_result.append(i) 48 | util.write_log('api').info(username, 'select cabinet list success') 49 | return json.dumps({'code':0,'result':data_result}) 50 | except: 51 | util.write_log('api').error("select role list error: %s" % traceback.format_exc()) 52 | return json.dumps({'code':1,'errmsg':'get rolelist failed'}) 53 | 54 | @jsonrpc.method('cabinet.get') 55 | @auth_login 56 | def idc_get(auth_info, **kwargs): 57 | if auth_info['code'] == 1: 58 | return json.dumps(auth_info) 59 | username = auth_info['username'] 60 | try: 61 | output = ['id','name','idc_id','power'] 62 | data = request.get_json()['params'] 63 | fields = data.get('output', output) 64 | where = data.get('where',None) 65 | if not where: 66 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 67 | result = app.config['cursor'].get_one_result('cabinet', fields, where) 68 | if not result : 69 | return json.dumps({'code':1, 'errmsg':'result is null'}) 70 | else: 71 | util.write_log('api').info(username, "select cabinet by id success") 72 | return json.dumps({'code':0,'result':result}) 73 | except: 74 | util.write_log('api').error('select idc by id error: %s' % traceback.format_exc()) 75 | return json.dumps({'code':1,'errmsg':'get idc failed'}) 76 | 77 | @jsonrpc.method('cabinet.update') 78 | @auth_login 79 | def idc_update(auth_info, **kwargs): 80 | if auth_info['code'] == 1: 81 | return json.dumps(auth_info) 82 | username = auth_info['username'] 83 | if '1' not in auth_info['r_id']: 84 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 85 | try: 86 | data = request.get_json()['params'] 87 | # print data 88 | where = data.get('where',None) 89 | data = data.get('data',None) 90 | if not where: 91 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 92 | result = app.config['cursor'].execute_update_sql('cabinet', data, where) 93 | if not result: 94 | return json.dumps({'code':1, 'errmsg':'result is null'}) 95 | util.write_log('api').info(username, 'update cabinet success!' ) 96 | return json.dumps({'code':0,'result':'update cabinet scucess'}) 97 | except: 98 | util.write_log('api' ).error("update error: %s" % traceback.format_exc()) 99 | return json.dumps( {'code':1,'errmsg':"update cabinet failed"}) 100 | 101 | @jsonrpc.method('cabinet.delete') 102 | @auth_login 103 | def idc_delete(auth_info,**kwargs): 104 | if auth_info['code'] == 1: 105 | return json.dumps(auth_info) 106 | username = auth_info['username'] 107 | if '1' not in auth_info['r_id']: 108 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 109 | try: 110 | data = request.get_json()['params'] 111 | where = data.get('where',None) 112 | if not where: 113 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 114 | result = app.config['cursor'].execute_delete_sql('cabinet', where) 115 | if not result : 116 | return json.dumps({'code':1, 'errmsg':'result is null'}) 117 | util.write_log('api').info(username, 'delete cabinet successed') 118 | return json.dumps({'code':0,'result':'delete cabinet scucess'}) 119 | except: 120 | util.write_log('api'). error('delete idc error: %s' % traceback.format_exc()) 121 | return json.dumps({'co de':1,'errmsg':'delete cabinet failed'}) 122 | 123 | -------------------------------------------------------------------------------- /devops/api/cabinet.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/cabinet.pyc -------------------------------------------------------------------------------- /devops/api/cobbler.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/cobbler.pyc -------------------------------------------------------------------------------- /devops/api/cobbler_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | 5 | import xmlrpclib 6 | import os 7 | 8 | class CobblerAPI(object): 9 | def __init__(self,url,user,password): 10 | self.remote = xmlrpclib.Server(url) 11 | self.token = self.remote.login(user,password) 12 | self.ret = { 13 | "result": True, 14 | "comment": [], 15 | } 16 | 17 | def add_system(self,hostname,ip_add,mac_add,profile,gateway,subnet): 18 | ''' 19 | Add Cobbler System Infomation 20 | ''' 21 | 22 | system_id = self.remote.new_system(self.token) 23 | self.remote.modify_system(system_id,"name",hostname,self.token) 24 | self.remote.modify_system(system_id,"hostname",hostname,self.token) 25 | self.remote.modify_system(system_id,'modify_interface', { 26 | "macaddress-eth0" : mac_add, 27 | "ipaddress-eth0" : ip_add, 28 | "gateway-eth0" : gateway, 29 | "subnet-eth0" : subnet, 30 | "static-eth0" : 1, 31 | "name-servers-eth0" : "114.114.114.114,8.8.8.8", 32 | }, self.token) 33 | self.remote.modify_system(system_id,"profile",profile,self.token) 34 | self.remote.save_system(system_id, self.token) 35 | try: 36 | self.remote.sync(self.token) 37 | os.system("cobbler system edit --name=%s --gateway=%s"%(hostname,gateway)) 38 | except Exception as e: 39 | self.ret['result'] = False 40 | self.ret['comment'].append(str(e)) 41 | return self.ret 42 | 43 | def get_profile(self): 44 | """ 45 | get cobbler profile return 46 | """ 47 | try: 48 | os = self.remote.get_profiles(self.token) 49 | for i in os: 50 | self.ret['comment'].append(i['name']) 51 | return self.ret 52 | except Exception as e: 53 | self.ret['result'] = False 54 | self.ret['comment'].append(str(e)) 55 | return self.ret 56 | 57 | def get_distro(self): 58 | """ 59 | get cobbler distro return 60 | """ 61 | try: 62 | os = self.remote.get_distros(self.token) 63 | for i in os: 64 | self.ret['comment'].append(i['name']) 65 | return self.ret 66 | except Exception as e: 67 | self.ret['result'] = False 68 | self.ret['comment'].append(str(e)) 69 | return self.ret 70 | 71 | def create_profile(self,name,distro,ks): 72 | """ 73 | create cobbler profile 74 | """ 75 | profile_id = self.remote.new_profile(self.token) 76 | self.remote.modify_profile(profile_id,"name",name,self.token) 77 | self.remote.modify_profile(profile_id,"distro",distro,self.token) 78 | self.remote.modify_profile(profile_id,"kickstart",ks,self.token) 79 | self.remote.save_profile(profile_id, self.token) 80 | try: 81 | self.remote.sync(self.token) 82 | except Exception as e: 83 | self.ret['result'] = False 84 | self.ret['comment'].append(str(e)) 85 | return self.ret 86 | 87 | def remove_profile(self,name): 88 | """ 89 | remove cobbler profile 90 | """ 91 | try: 92 | self.remote.remove_profile(name,self.token) 93 | except Exception as e: 94 | self.ret['result'] = False 95 | self.ret['comment'].append(str(e)) 96 | return self.ret 97 | 98 | def remove_system(self,name): 99 | """ 100 | remove cobbler profile 101 | """ 102 | try: 103 | self.remote.remove_system(name,self.token) 104 | except Exception as e: 105 | self.ret['result'] = False 106 | self.ret['comment'].append(str(e)) 107 | return self.ret 108 | 109 | 110 | 111 | def system(url,user,password,hostname,ip_add,mac_add,profile,gateway,subnet): 112 | cobbler = CobblerAPI(url,user,password) 113 | ret = cobbler.add_system(hostname,ip_add,mac_add,profile,gateway,subnet) 114 | return ret 115 | 116 | def get_profile(url,user,password): 117 | cobbler = CobblerAPI(url,user,password) 118 | ret = cobbler.get_profile() 119 | return ret 120 | 121 | def get_distro(url,user,password): 122 | cobbler = CobblerAPI(url,user,password) 123 | ret = cobbler.get_distro() 124 | return ret 125 | 126 | def profile_create(url,user,password,name,distro,ks): 127 | cobbler = CobblerAPI(url,user,password) 128 | ret = cobbler.create_profile(name,distro,ks) 129 | return ret 130 | 131 | def profile_remove(url,user,password,name): 132 | cobbler = CobblerAPI(url,user,password) 133 | ret = cobbler.remove_profile(name) 134 | return ret 135 | 136 | def system_remove(url,user,password,name): 137 | cobbler = CobblerAPI(url,user,password) 138 | ret = cobbler.remove_system(name) 139 | return ret 140 | if __name__ == '__main__': 141 | # main() 142 | system = CobblerAPI("http://192.168.63.182/cobbler_api","xiaoluo","123456") 143 | print system.add_system("test",'192.168.63.102','00:50:54:2D:32:DE','centos-6.5-x86_64','192.168.10.254','255.255.255.0') 144 | -------------------------------------------------------------------------------- /devops/api/cobbler_api.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/cobbler_api.pyc -------------------------------------------------------------------------------- /devops/api/idc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | 9 | 10 | #这里是关于用户角色的增删改查及组对应的权限id2name 11 | 12 | @jsonrpc.method('idc.create') 13 | @auth_login 14 | def idc_create(auth_info, **kwargs): 15 | if auth_info['code'] == 1: 16 | return json.dumps(auth_info) 17 | username = auth_info['username'] 18 | try: 19 | data = request.get_json()['params'] 20 | # print data 21 | if not util.check_name(data['name']): 22 | return json.dumps({'code': 1, 'errmsg': 'name must be string or int'}) 23 | app.config['cursor'].execute_insert_sql('idc', data) 24 | util.write_log('api').info(username, "create idc %s scucess" % data['name']) 25 | return json.dumps({'code':0,'result':'create idc %s scucess' % data['name']}) 26 | except: 27 | util.write_log('api').error(username,"create idc error: %s" % traceback.format_exc()) 28 | return json.dumps({'code':1,'errmsg':'create idc fail'}) 29 | 30 | @jsonrpc.method('idc.getlist') 31 | @auth_login 32 | def idc_select(auth_info,**kwargs): 33 | if auth_info['code'] == 1: 34 | return json.dumps(auth_info) 35 | username = auth_info['username'] 36 | if '1' not in auth_info['r_id']: 37 | return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) 38 | try: 39 | fields = ['id','name','idc_name','address','phone','email','user_interface','user_phone','rel_cabinet_num','pact_cabinet_num'] 40 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 41 | res = app.config['cursor'].get_results('idc', fields) 42 | util.write_log('api').info(username, 'select idc list success') 43 | return json.dumps({'code':0,'result':res}) 44 | except: 45 | util.write_log('api').error("select role list error: %s" % traceback.format_exc()) 46 | return json.dumps({'code':1,'errmsg':'get rolelist failed'}) 47 | 48 | @jsonrpc.method('idc.get') 49 | @auth_login 50 | def idc_get(auth_info, **kwargs): 51 | if auth_info['code'] == 1: 52 | return json.dumps(auth_info) 53 | username = auth_info['username'] 54 | try: 55 | output = ['id','name','idc_name','address','phone','email','user_interface','user_phone','rel_cabinet_num','pact_cabinet_num'] 56 | data = request.get_json()['params'] 57 | fields = data.get('output', output) 58 | where = data.get('where',None) 59 | # print where 60 | if not where: 61 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 62 | result = app.config['cursor'].get_one_result('idc', fields, where) 63 | # print result 64 | if not result : 65 | return json.dumps({'code':1, 'errmsg':'result is null'}) 66 | else: 67 | util.write_log('api').info(username, "select role by id success") 68 | return json.dumps({'code':0,'result':result}) 69 | except: 70 | util.write_log('api').error('select idc by id error: %s' % traceback.format_exc()) 71 | return json.dumps({'code':1,'errmsg':'get idc failed'}) 72 | 73 | @jsonrpc.method('idc.update') 74 | @auth_login 75 | def idc_update(auth_info, **kwargs): 76 | if auth_info['code'] == 1: 77 | return json.dumps(auth_info) 78 | username = auth_info['username'] 79 | if '1' not in auth_info['r_id']: 80 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 81 | try: 82 | data = request.get_json()['params'] 83 | where = data.get('where',None) 84 | data = data.get('data',None) 85 | # print where 86 | if not where: 87 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 88 | result = app.config['cursor'].execute_update_sql('idc', data, where) 89 | if not result: 90 | return json.dumps({'code':1, 'errmsg':'result is null'}) 91 | util.write_log('api').info(username, 'update idc success!' ) 92 | return json.dumps({'code':0,'result':'update idc scucess'}) 93 | except: 94 | util.write_log('api' ).error("update error: %s" % traceback.format_exc()) 95 | return json.dumps( {'code':1,'errmsg':"update idc failed"}) 96 | 97 | @jsonrpc.method('idc.delete') 98 | @auth_login 99 | def idc_delete(auth_info,**kwargs): 100 | if auth_info['code'] == 1: 101 | return json.dumps(auth_info) 102 | username = auth_info['username'] 103 | if '1' not in auth_info['r_id']: 104 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 105 | try: 106 | data = request.get_json()['params'] 107 | where = data.get('where',None) 108 | if not where: 109 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 110 | result = app.config['cursor'].execute_delete_sql('idc', where) 111 | if not result : 112 | return json.dumps({'code':1, 'errmsg':'result is null'}) 113 | util.write_log('api').info(username, 'delete idc successed') 114 | return json.dumps({'code':0,'result':'delete idc scucess'}) 115 | except: 116 | util.write_log('api'). error('delete idc error: %s' % traceback.format_exc()) 117 | return json.dumps({'co de':1,'errmsg':'delete idc failed'}) 118 | 119 | -------------------------------------------------------------------------------- /devops/api/idc.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/idc.pyc -------------------------------------------------------------------------------- /devops/api/jigui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | 9 | @jsonrpc.method('jigui.getlist') 10 | @auth_login 11 | def jigui_select(auth_info,**kwargs): 12 | if auth_info['code'] == 1: 13 | return json.dumps(auth_info) 14 | username = auth_info['username'] 15 | try: 16 | data_result = [] 17 | ret_json = {} 18 | fields = ['id','vm_status','os','server_purpose','idc_id','cabinet_id','cabinet_pos','host_status','ip','host_models'] 19 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 20 | data = app.config['cursor'].get_results('server', fields) 21 | for i in data: 22 | if i["idc_id"]: 23 | idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc_id"])}) 24 | cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet_id"])}) 25 | i['idc_name'] = str(idc['name']) 26 | i['cabinet_name'] = str(cabinet['name']) 27 | data_result.append(i) 28 | # print data_result 29 | util.write_log('api').info(username, 'select jigui list success') 30 | return json.dumps({'code':0,'result':data_result}) 31 | except: 32 | util.write_log('api').error("select role list error: %s" % traceback.format_exc()) 33 | return json.dumps({'code':1,'errmsg':'get rolelist failed'}) 34 | -------------------------------------------------------------------------------- /devops/api/jigui.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/jigui.pyc -------------------------------------------------------------------------------- /devops/api/login.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import Flask, request 4 | from . import app 5 | import util 6 | import json,time,traceback,hashlib 7 | 8 | #用户登录验证,并生成token 9 | @app.route('/api/login', methods=['GET']) 10 | def login(): 11 | try: 12 | username = request.args.get('username', None) 13 | passwd = request.args.get('passwd', None) 14 | passwd = hashlib.md5(passwd).hexdigest() 15 | if not (username and passwd): 16 | return json.dumps({'code': 1, 'errmsg': "需要输入用户名和密码"}) 17 | result = app.config['cursor'].get_one_result('user', ['id', 'username', 'password', 'r_id', 'is_lock'], {'username': username}) 18 | if not result: 19 | return json.dumps({'code': 1, 'errmsg': "用户不存在"}) 20 | if result['is_lock'] == 1: 21 | return json.dumps({'code': 1, 'errmsg': "用户已被锁定"}) 22 | 23 | if passwd == result['password']: 24 | data = {'last_login': time.strftime('%Y-%m-%d %H:%M:%S')} 25 | app.config['cursor'].execute_update_sql('user', data, {'username': username}) 26 | token = util.get_validate(result['username'], result['id'], result['r_id'], app.config['passport_key']) 27 | return json.dumps({'code': 0, 'authorization': token}) 28 | else: 29 | return json.dumps({'code': 1, 'errmsg': "输入密码有误"}) 30 | except: 31 | util.write_log('api').error("login error: %s" % traceback.format_exc()) 32 | return json.dumps({'code': 1, 'errmsg': "登录失败"}) 33 | 34 | 35 | -------------------------------------------------------------------------------- /devops/api/login.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/login.pyc -------------------------------------------------------------------------------- /devops/api/power.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | 9 | # 权限的增删改查 10 | 11 | @jsonrpc.method('power.create') 12 | @auth_login 13 | def create(auth_info,**kwargs): 14 | if auth_info['code'] == 1: 15 | return json.dumps(auth_info) 16 | username = auth_info['username'] 17 | if '1' not in auth_info['r_id']: 18 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 19 | try: 20 | data = request.get_json()['params'] 21 | if not util.check_name(data['name']): 22 | return json.dumps({'code': 1, 'errmsg': 'name must be string or num'}) 23 | # print data 24 | app.config['cursor'].execute_insert_sql('power', data) 25 | util.write_log('api').info(username, "create power %s success" % data['name']) 26 | return json.dumps({'code':0,'result':'create %s success' % data['name']}) 27 | except: 28 | util.write_log('api').error('create power error:%s' % traceback.format_exc()) 29 | return json.dumps({'code':1,'errmsg': 'create power failed'}) 30 | 31 | @jsonrpc.method('power.delete') 32 | @auth_login 33 | def delete(auth_info,**kwargs): 34 | if auth_info['code']==1: 35 | return json.dumps(auth_info) 36 | username = auth_info['username'] 37 | if '1' not in auth_info['r_id']: 38 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 39 | try: 40 | data = request.get_json()['params'] 41 | where = data.get('where',None) 42 | if not where: 43 | return json.dumps({'code':1,'errmsg':'must need a condition'}) 44 | result = app.config['cursor'].get_one_result('power', ['name'], where) 45 | if not result: 46 | return json.dumps({'code':1,'errmsg':'data not exist'}) 47 | app.config['cursor'].execute_delete_sql('power', where) 48 | util.write_log('api').info(username, "delete power success") 49 | return json.dumps({'code':0,'result':'delete power success'}) 50 | except: 51 | util.write_log('api').error("delete power error:%s" % traceback.format_exc()) 52 | return json.dumps({'code':1,'errmsg': 'delete power failed'}) 53 | 54 | @jsonrpc.method('power.getlist') 55 | @auth_login 56 | def getlist(auth_info,**kwargs): 57 | if auth_info['code']==1: 58 | return json.dumps(auth_info) 59 | username = auth_info['username'] 60 | if '1' not in auth_info['r_id']: 61 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 62 | try: 63 | output = ['id','name','name_cn','url','comment'] 64 | data = request.get_json()['params'] 65 | fields = data.get('output', output) 66 | result = app.config['cursor'].get_results('power', fields) 67 | util.write_log('api').info(username, 'select permission list success') 68 | return json.dumps({'code':0,'result':result,'count':len(result)}) 69 | except: 70 | util.write_log('api').error("get list permission error: %s" % traceback.format_exc()) 71 | return json.dumps({'code':1,'errmsg':'get power_list failed'}) 72 | 73 | @jsonrpc.method('power.get') 74 | @auth_login 75 | def getbyid(auth_info,**kwargs): 76 | if auth_info['code'] == 1: 77 | return json.dumps(auth_info) 78 | username = auth_info['username'] 79 | if '1' not in auth_info['r_id']: 80 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 81 | try: 82 | output = ['id','name','name_cn','url','comment'] 83 | data = request.get_json()['params'] 84 | fields = data.get('output', output) 85 | where = data.get('where',None) 86 | if not where: 87 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 88 | result = app.config['cursor'].get_one_result('power', fields, where) 89 | if not result: 90 | return json.dumps({'code':1, 'errmsg':'data not exist'}) 91 | util.write_log('api').info(username,'select permission by id successed!') 92 | return json.dumps({'code':0, 'result':result}) 93 | except: 94 | util.write_log('api').error("select power by id error: %s" % traceback.format_exc()) 95 | return json.dumps({'code':1,'errmsg':'get power failed'}) 96 | 97 | 98 | @jsonrpc.method('power.update') 99 | @auth_login 100 | def update(auth_info, **kwargs): 101 | if auth_info['code'] == 1: 102 | return json.dumps(auth_info) 103 | username = auth_info['username'] 104 | if '1' not in auth_info['r_id']: 105 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 106 | try: 107 | data = request.get_json ()['params'] 108 | where = data.get('where',None) 109 | data = data.get('data',None) 110 | if not where: 111 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 112 | result=app.config['cursor'].execute_update_sql('power', data, where) 113 | if not result: 114 | return json.dumps({'code':1, 'errmsg':'data not exist'}) 115 | util.write_log('api').info(username,"update power successed" ) 116 | return json.dumps({'code':0,'result':'update power success'}) 117 | except: 118 | util.write_log('api').error("update error: %s" % traceback. format_exc()) 119 | return json.dumps({'code':1,'errmsg':'update power failed'}) 120 | -------------------------------------------------------------------------------- /devops/api/power.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/power.pyc -------------------------------------------------------------------------------- /devops/api/report.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/report.pyc -------------------------------------------------------------------------------- /devops/api/role.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | 9 | 10 | #这里是关于用户角色的增删改查及组对应的权限id2name 11 | 12 | @jsonrpc.method('role.create') 13 | @auth_login 14 | def role_create(auth_info, **kwargs): 15 | if auth_info['code'] == 1: 16 | return json.dumps(auth_info) 17 | username = auth_info['username'] 18 | if '1' not in auth_info['r_id']: 19 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 20 | try: 21 | data = request.get_json()['params'] 22 | if not data.has_key('p_id'): 23 | return json.dumps({'code':1,'errmsg':'must hava p_id'}) 24 | if not app.config['cursor'].if_id_exist('power',data['p_id'].split(',')): 25 | return json.dumps({'code':1,'errmsg':'p_id not exist'}) 26 | if not util.check_name(data['name']): 27 | return json.dumps({'code': 1, 'errmsg': 'name must be string or int'}) 28 | app.config['cursor'].execute_insert_sql('role', data) 29 | util.write_log('api').info(username, "create role %s scucess" % data['name']) 30 | return json.dumps({'code':0,'result':'create role %s scucess' % data['name']}) 31 | except: 32 | util.write_log('api').error(username,"create role error: %s" % traceback.format_exc()) 33 | return json.dumps({'code':1,'errmsg':'create role fail'}) 34 | 35 | @jsonrpc.method('role.getlist') 36 | @auth_login 37 | def role_select(auth_info,**kwargs): 38 | if auth_info['code'] == 1: 39 | return json.dumps(auth_info) 40 | username = auth_info['username'] 41 | if '1' not in auth_info['r_id']: 42 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 43 | try: 44 | output = ['id','name','name_cn','p_id','info'] 45 | data = request.get_json()['params'] 46 | fields = data.get('output', output) 47 | 48 | #查询权限表,生产id2name的字典 49 | result = app.config['cursor'].get_results('power', ['id', 'name']) 50 | power_name = dict([(str(x['id']), x['name']) for x in result]) 51 | 52 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 53 | result = [] 54 | res = app.config['cursor'].get_results('role', fields) 55 | for x in res: 56 | p_name = [power_name[p_id] for p_id in x['p_id'].split(',') if p_id in power_name] 57 | x['p_id'] = ','.join(p_name) #将原有x['p_id']中的id转为name 58 | result.append(x) 59 | 60 | util.write_log('api').info(username, 'select role list success') 61 | return json.dumps({'code':0,'result':result,'count':len(result)}) 62 | except: 63 | util.write_log('api').error("select role list error: %s" % traceback.format_exc()) 64 | return json.dumps({'code':1,'errmsg':'get rolelist failed'}) 65 | 66 | @jsonrpc.method('role.get') 67 | @auth_login 68 | def role_get(auth_info, **kwargs): 69 | if auth_info['code'] == 1: 70 | return json.dumps(auth_info) 71 | username = auth_info['username'] 72 | try: 73 | output = ['id','name','name_cn','p_id','info'] 74 | data = request.get_json()['params'] 75 | fields = data.get('output', output) 76 | where = data.get('where',None) 77 | if not where: 78 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 79 | result = app.config['cursor'].get_one_result('role', fields, where) 80 | if not result : 81 | return json.dumps({'code':1, 'errmsg':'result is null'}) 82 | else: 83 | util.write_log('api').info(username, "select role by id success") 84 | return json.dumps({'code':0,'result':result}) 85 | except: 86 | util.write_log('api').error('select role by id error: %s' % traceback.format_exc()) 87 | return json.dumps({'code':1,'errmsg':'get role failed'}) 88 | 89 | @jsonrpc.method('role.update') 90 | @auth_login 91 | def role_update(auth_info, **kwargs): 92 | if auth_info['code'] == 1: 93 | return json.dumps(auth_info) 94 | username = auth_info['username'] 95 | if '1' not in auth_info['r_id']: 96 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 97 | try: 98 | data = request.get_json()['params'] 99 | where = data.get('where',None) 100 | data = data.get('data',None) 101 | if not where: 102 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 103 | result = app.config['cursor'].execute_update_sql('role', data, where) 104 | if not result: 105 | return json.dumps({'code':1, 'errmsg':'result is null'}) 106 | util.write_log('api').info(username, 'update role success!' ) 107 | return json.dumps({'code':0,'result':'update role scucess'}) 108 | except: 109 | util.write_log('api' ).error("update error: %s" % traceback.format_exc()) 110 | return json.dumps( {'code':1,'errmsg':"update role failed"}) 111 | 112 | @jsonrpc.method('role.delete') 113 | @auth_login 114 | def role_delete(auth_info,**kwargs): 115 | if auth_info['code'] == 1: 116 | return json.dumps(auth_info) 117 | username = auth_info['username'] 118 | if '1' not in auth_info['r_id']: 119 | return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) 120 | try: 121 | data = request.get_json()['params'] 122 | where = data.get('where',None) 123 | if not where: 124 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 125 | result = app.config['cursor'].execute_delete_sql('role', where) 126 | if not result : 127 | return json.dumps({'code':1, 'errmsg':'result is null'}) 128 | util.write_log('api').info(username, 'delete role successed') 129 | return json.dumps({'code':0,'result':'delete role scucess'}) 130 | except: 131 | util.write_log('api'). error('delete role error: %s' % traceback.format_exc()) 132 | return json.dumps({'co de':1,'errmsg':'delete role failed'}) 133 | 134 | -------------------------------------------------------------------------------- /devops/api/role.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/role.pyc -------------------------------------------------------------------------------- /devops/api/select.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import Flask, request 4 | from . import app,jsonrpc 5 | import util 6 | from auth import auth_login 7 | import json,time,traceback 8 | 9 | @jsonrpc.method('selected.get') 10 | @auth_login 11 | def selected(auth_info,**kwargs): 12 | if auth_info['code'] == 1: 13 | return json.dumps(auth_info) 14 | username = auth_info['username'] 15 | try: 16 | data=request.get_json()['params'] 17 | where = data.get('where',None) 18 | m_table = data.get('m_table',None) 19 | field = data.get('field',None) 20 | s_table = data.get('s_table',None) 21 | res = app.config['cursor'].get_one_result(m_table,[field],where) 22 | res=res[field].split(',') #eg: ['1','2'] 23 | result = app.config['cursor'].get_results(s_table,['id','name']) 24 | for x in result: #eg: [{'id':1,'name':'sa'},{'id':2,'name':'php'}] 25 | for r_id in res: 26 | if r_id in str(x['id']): 27 | x['selected'] = 'selected="selected"' 28 | util.write_log('api').info(username,'selected %s successfully' % (s_table)) 29 | return json.dumps({'code':0,'result':result}) 30 | except: 31 | util.write_log('api').error('selected error: %s' % traceback.format_exc()) 32 | return json.dumps({'code':'1','errmsg':'selected.get error'}) 33 | 34 | 35 | -------------------------------------------------------------------------------- /devops/api/select.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/select.pyc -------------------------------------------------------------------------------- /devops/api/selectd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import Flask, request 4 | from . import app,jsonrpc 5 | import util 6 | from auth import auth_login 7 | import json,time,traceback 8 | 9 | @jsonrpc.method('selected.get') 10 | @auth_login 11 | def selected(auth_info,**kwargs): 12 | if auth_info['code'] == 1: 13 | return json.dumps(auth_info) 14 | username = auth_info['username'] 15 | try: 16 | data=request.get_json()['params'] 17 | where = data.get('where',None) 18 | m_table = data.get('m_table',None) 19 | field = data.get('field',None) 20 | s_table = data.get('s_table',None) 21 | res = app.config['cursor'].get_one_result(m_table,[field],where) 22 | res=res[field].split(',') #eg: ['1','2'] 23 | result = app.config['cursor'].get_results(s_table,['id','name']) 24 | for x in result: #eg: [{'id':1,'name':'sa'},{'id':2,'name':'php'}] 25 | for r_id in res: 26 | if r_id in str(x['id']): 27 | x['selected'] = 'selected="selected"' 28 | util.write_log('api').info(username,'selected %s successfully' % (s_table)) 29 | return json.dumps({'code':0,'result':result}) 30 | except: 31 | util.write_log('api').error('selected error: %s' % traceback.format_exc()) 32 | return json.dumps({'code':'1','errmsg':'selected.get error'}) 33 | 34 | 35 | -------------------------------------------------------------------------------- /devops/api/selectd.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/selectd.pyc -------------------------------------------------------------------------------- /devops/api/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | from datetime import date, datetime 9 | 10 | #这里是关于用户角色的增删改查及组对应的权限id2name 11 | 12 | @jsonrpc.method('server.create') 13 | def server_create(**kwargs): 14 | # if auth_info['code'] == 1: 15 | # return json.dumps(auth_info) 16 | # username = auth_info['username'] 17 | try: 18 | data = request.get_json()['params'] 19 | # if not util.check_name(data['name']): 20 | # return json.dumps({'code': 1, 'errmsg': 'name must be string or int'}) 21 | print data 22 | res = app.config['cursor'].execute_insert_sql('server', data) 23 | print res 24 | # util.write_log('api').info(username, "create server %s scucess" % data['name']) 25 | return json.dumps({'code':0,'result':'create server scucess'}) 26 | except: 27 | util.write_log('api').error(username,"create server error: %s" % traceback.format_exc()) 28 | return json.dumps({'code':1,'errmsg':'create server fail'}) 29 | 30 | 31 | 32 | @jsonrpc.method('server.radd') 33 | def server_radd(**kwargs): 34 | try: 35 | data = request.get_json()['params'] 36 | #查询是否含有mac_address 37 | where = {"mac_address":str(data['mac_address'])} 38 | fields = ['mac_address'] 39 | result = app.config['cursor'].get_one_result('server', fields, where) 40 | if result: 41 | res = app.config['cursor'].execute_update_sql('server', data, where) 42 | return json.dumps({'code':0,'result':'update server scucess'}) 43 | else: 44 | res = app.config['cursor'].execute_insert_sql('server', data) 45 | return json.dumps({'code':0,'result':'create server scucess'}) 46 | except: 47 | return json.dumps({'code':1,'errmsg':'create server fail'}) 48 | 49 | 50 | @jsonrpc.method('server.getlist') 51 | @auth_login 52 | def server_select(auth_info,**kwargs): 53 | data_result = [] 54 | if auth_info['code'] == 1: 55 | return json.dumps(auth_info) 56 | username = auth_info['username'] 57 | if '1' not in auth_info['r_id']: 58 | return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) 59 | try: 60 | fields = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','server_purpose','server_run','expire','server_up_time','idc_id','cabinet_id','supplier','supplier_phone'] 61 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 62 | res = app.config['cursor'].get_results('server', fields) 63 | print res 64 | for i in res: 65 | i['check_update_time'] = str(i['check_update_time']) 66 | i['manufacture_date'] = str(i['manufacture_date']) 67 | i['expire'] = str(i['expire']) 68 | i['server_up_time'] = str(i['server_up_time']) 69 | if i["idc_id"]: 70 | idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc_id"])}) 71 | cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet_id"])}) 72 | i['idc_name'] = str(idc['name']) 73 | i['cabinet_name'] = str(cabinet['name']) 74 | i['expire'] = i['expire'].split()[0] 75 | i['server_up_time'] = i['server_up_time'].split()[0] 76 | data_result.append(i) 77 | else: 78 | data_result.append(i) 79 | util.write_log('api').info(username, 'select server list success') 80 | return json.dumps({'code':0,'result':data_result}) 81 | except: 82 | util.write_log('api').error("select server list error: %s" % traceback.format_exc()) 83 | return json.dumps({'code':1,'errmsg':'get serverlist failed'}) 84 | 85 | @jsonrpc.method('server.get') 86 | @auth_login 87 | def server_get(auth_info, **kwargs): 88 | res = [] 89 | if auth_info['code'] == 1: 90 | return json.dumps(auth_info) 91 | username = auth_info['username'] 92 | try: 93 | output = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','supplier','supplier_phone','idc_id','cabinet_id','cabinet_pos','expire','server_up_time','server_purpose','server_run','host'] 94 | data = request.get_json()['params'] 95 | fields = data.get('output', output) 96 | where = data.get('where',None) 97 | if not where: 98 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 99 | result = app.config['cursor'].get_one_result('server', fields, where) 100 | result['check_update_time'] = str(result['check_update_time']) 101 | result['manufacture_date'] = str(result['manufacture_date']) 102 | result['expire'] = str(result['expire']) 103 | result['server_up_time'] = str(result['server_up_time']) 104 | # print result 105 | if not result : 106 | return json.dumps({'code':1, 'errmsg':'result is null'}) 107 | else: 108 | util.write_log('api').info(username, "select server by id success") 109 | return json.dumps({'code':0,'result':result}) 110 | except: 111 | util.write_log('api').error('select server by id error: %s' % traceback.format_exc()) 112 | return json.dumps({'code':1,'errmsg':'get server failed'}) 113 | 114 | @jsonrpc.method('server.update') 115 | @auth_login 116 | def idc_update(auth_info, **kwargs): 117 | if auth_info['code'] == 1: 118 | return json.dumps(auth_info) 119 | username = auth_info['username'] 120 | if '1' not in auth_info['r_id']: 121 | return json.dumps({'code': 1,'errmsg':'you not admin,no server' }) 122 | try: 123 | data = request.get_json()['params'] 124 | # print data 125 | where = data.get('where',None) 126 | data = data.get('data',None) 127 | if not where: 128 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 129 | result = app.config['cursor'].execute_update_sql('server', data, where) 130 | if not result: 131 | return json.dumps({'code':1, 'errmsg':'result is null'}) 132 | util.write_log('api').info(username, 'update server success!' ) 133 | return json.dumps({'code':0,'result':'update server scucess'}) 134 | except: 135 | util.write_log('api' ).error("update error: %s" % traceback.format_exc()) 136 | return json.dumps( {'code':1,'errmsg':"update server failed"}) 137 | 138 | @jsonrpc.method('server.delete') 139 | @auth_login 140 | def idc_delete(auth_info,**kwargs): 141 | if auth_info['code'] == 1: 142 | return json.dumps(auth_info) 143 | username = auth_info['username'] 144 | if '1' not in auth_info['r_id']: 145 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 146 | try: 147 | data = request.get_json()['params'] 148 | output = ['id','hostid'] 149 | fields = data.get('output', output) 150 | where = data.get('where',None) 151 | if not where: 152 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 153 | result = app.config['cursor'].get_one_result('zbhost', fields, where) 154 | print result 155 | if not result : 156 | return json.dumps({'code':1, 'errmsg':'result is null'}) 157 | util.write_log('api').info(username, 'delete server successed') 158 | return json.dumps({'code':0,'result':'delete server scucess'}) 159 | except: 160 | util.write_log('api'). error('delete idc error: %s' % traceback.format_exc()) 161 | return json.dumps({'co de':1,'errmsg':'delete server failed'}) 162 | 163 | -------------------------------------------------------------------------------- /devops/api/server.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/server.pyc -------------------------------------------------------------------------------- /devops/api/switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | 9 | 10 | #这里是关于用户角色的增删改查及组对应的权限id2name 11 | 12 | @jsonrpc.method('switch.create') 13 | @auth_login 14 | def switch_create(auth_info, **kwargs): 15 | if auth_info['code'] == 1: 16 | return json.dumps(auth_info) 17 | username = auth_info['username'] 18 | try: 19 | data = request.get_json()['params'] 20 | # print data 21 | data['cabinet']= int(data['cabinet']) 22 | data['idc'] = int(data['idc']) 23 | data['port'] = int(data['port']) 24 | app.config['cursor'].execute_insert_sql('switch', data) 25 | util.write_log('api').info(username, "create switch %s scucess" % data['ip']) 26 | return json.dumps({'code':0,'result':'create switch %s scucess' % data['ip']}) 27 | except: 28 | util.write_log('api').error(username,"create switch error: %s" % traceback.format_exc()) 29 | return json.dumps({'code':1,'errmsg':'create switch fail'}) 30 | 31 | @jsonrpc.method('switch.getlist') 32 | @auth_login 33 | def switch_select(auth_info,**kwargs): 34 | data_result = [] 35 | if auth_info['code'] == 1: 36 | return json.dumps(auth_info) 37 | username = auth_info['username'] 38 | if '1' not in auth_info['r_id']: 39 | return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) 40 | try: 41 | fields = ['id','ip','device','port','port','cabinet','idc'] 42 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 43 | res = app.config['cursor'].get_results('switch', fields) 44 | for i in res: 45 | if i['idc']: 46 | idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc"])}) 47 | cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet"])}) 48 | i['idc_name'] = str(idc['name']) 49 | i['cabinet_name'] = str(cabinet['name']) 50 | data_result.append(i) 51 | else: 52 | data_result.append(i) 53 | util.write_log('api').info(username, 'select switch list success') 54 | return json.dumps({'code':0,'result':data_result}) 55 | except: 56 | util.write_log('api').error("select switch list error: %s" % traceback.format_exc()) 57 | return json.dumps({'code':1,'errmsg':'get switch failed'}) 58 | 59 | @jsonrpc.method('switch.get') 60 | @auth_login 61 | def switch_get(auth_info, **kwargs): 62 | if auth_info['code'] == 1: 63 | return json.dumps(auth_info) 64 | username = auth_info['username'] 65 | try: 66 | output = ['id','ip','device','port','cabinet','idc'] 67 | data = request.get_json()['params'] 68 | fields = data.get('output', output) 69 | where = data.get('where',None) 70 | # print where 71 | if not where: 72 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 73 | result = app.config['cursor'].get_one_result('switch', fields, where) 74 | # print result 75 | if not result : 76 | return json.dumps({'code':1, 'errmsg':'result is null'}) 77 | else: 78 | util.write_log('api').info(username, "select role by id success") 79 | return json.dumps({'code':0,'result':result}) 80 | except: 81 | util.write_log('api').error('select switch by id error: %s' % traceback.format_exc()) 82 | return json.dumps({'code':1,'errmsg':'get switch failed'}) 83 | 84 | @jsonrpc.method('switch.update') 85 | @auth_login 86 | def switch_update(auth_info, **kwargs): 87 | if auth_info['code'] == 1: 88 | return json.dumps(auth_info) 89 | username = auth_info['username'] 90 | if '1' not in auth_info['r_id']: 91 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 92 | try: 93 | data = request.get_json()['params'] 94 | where = data.get('where',None) 95 | data = data.get('data',None) 96 | # print where 97 | if not where: 98 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 99 | result = app.config['cursor'].execute_update_sql('switch', data, where) 100 | if not result: 101 | return json.dumps({'code':1, 'errmsg':'result is null'}) 102 | util.write_log('api').info(username, 'update switch success!' ) 103 | return json.dumps({'code':0,'result':'update switch scucess'}) 104 | except: 105 | util.write_log('api' ).error("update error: %s" % traceback.format_exc()) 106 | return json.dumps( {'code':1,'errmsg':"update switch failed"}) 107 | 108 | @jsonrpc.method('switch.delete') 109 | @auth_login 110 | def switch_delete(auth_info,**kwargs): 111 | if auth_info['code'] == 1: 112 | return json.dumps(auth_info) 113 | username = auth_info['username'] 114 | if '1' not in auth_info['r_id']: 115 | return json.dumps({'code': 1,'errmsg':'you not admin,no switch' }) 116 | try: 117 | data = request.get_json()['params'] 118 | where = data.get('where',None) 119 | if not where: 120 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 121 | result = app.config['cursor'].execute_delete_sql('switch', where) 122 | if not result : 123 | return json.dumps({'code':1, 'errmsg':'result is null'}) 124 | util.write_log('api').info(username, 'delete switch successed') 125 | return json.dumps({'code':0,'result':'delete switch scucess'}) 126 | except: 127 | util.write_log('api'). error('delete switch error: %s' % traceback.format_exc()) 128 | return json.dumps({'co de':1,'errmsg':'delete switch failed'}) 129 | 130 | @jsonrpc.method('switch.add') 131 | def server_radd(**kwargs): 132 | try: 133 | data = request.get_json()['params'] 134 | # print data 135 | #查询是否含有mac_address 136 | where = {"ip":str(data['ip'])} 137 | fields = ['ip'] 138 | result = app.config['cursor'].get_one_result('switch', fields, where) 139 | idc_id_ret = app.config['cursor'].get_one_result('idc',['id'],{"id":int(data['idc'])}) 140 | cabinet_id_ret = app.config['cursor'].get_one_result('cabinet',['id'],{"id":int(data['cabinet'])}) 141 | if result and idc_id_ret and cabinet_id_ret: 142 | res = app.config['cursor'].execute_update_sql('switch', data, where) 143 | return json.dumps({'code':0,'result':'update switch scucess'}) 144 | if idc_id_ret and cabinet_id_ret: 145 | res = app.config['cursor'].execute_insert_sql('switch', data) 146 | return json.dumps({'code':0,'result':'create switch scucess'}) 147 | else: 148 | return json.dumps({'code':1,'errmsg':'create switch fail, please check idcid or cabinet id'}) 149 | except: 150 | return json.dumps({'code':1,'errmsg':'create switch fail'}) 151 | -------------------------------------------------------------------------------- /devops/api/switch.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/switch.pyc -------------------------------------------------------------------------------- /devops/api/user.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/user.pyc -------------------------------------------------------------------------------- /devops/api/zabbix.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/zabbix.pyc -------------------------------------------------------------------------------- /devops/api/zabbix_Graph_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from . import app , jsonrpc 4 | import util 5 | import json, traceback 6 | import MySQLdb 7 | import datetime 8 | import cookielib, urllib2,urllib 9 | import smtplib 10 | 11 | class ZabbixGraph(): 12 | def __init__(self,url="http://192.168.63.216/zabbix/index.php",name="Admin",password="zabbix"): 13 | self.url=url 14 | self.name=name 15 | self.passwd=password 16 | #初始化的时候生成cookies 17 | cookiejar = cookielib.CookieJar() 18 | urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) 19 | values = {"name":self.name,'password':self.passwd,'autologin':1,"enter":'Sign in'} 20 | data = urllib.urlencode(values) 21 | request = urllib2.Request(url, data) 22 | try: 23 | urlOpener.open(request,timeout=10) 24 | self.urlOpener=urlOpener 25 | except urllib2.HTTPError, e: 26 | print e 27 | def GetGraph(self,url="http://192.168.63.216/zabbix/chart2.php",values={'width': 800, 'height': 200, 'graphid': '564', 'stime': '20160907090409', 'period': 3600},image_dir="/tmp"): 28 | data=urllib.urlencode(values) 29 | request = urllib2.Request(url,data) 30 | url = self.urlOpener.open(request) 31 | image = url.read() 32 | imagename="%s/%s_%s.jpg" % (image_dir, values["graphid"], values["stime"]) 33 | f=open(imagename,'wb') 34 | f.write(image) 35 | return '1' 36 | 37 | if __name__ == "__main__": 38 | graph = ZabbixGraph() 39 | values = {'width': 800, 'height': 200, 'graphid': '564', 'stime': '20160907090409', 'period': 3600} 40 | graph.GetGraph("http://192.168.63.216/zabbix/chart2.php",values,"/tmp") 41 | -------------------------------------------------------------------------------- /devops/api/zabbix_Graph_api.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/zabbix_Graph_api.pyc -------------------------------------------------------------------------------- /devops/api/zabbix_api.py: -------------------------------------------------------------------------------- 1 | #coding:utf8 2 | from . import app , jsonrpc 3 | import util 4 | from zabbix_client import ZabbixServerProxy 5 | import json, traceback 6 | 7 | class Zabbix(): 8 | def __init__(self,data): 9 | self.zb = ZabbixServerProxy(data['zabbix_url']) 10 | self.zb.user.login(user=data['zabbix_user'], password=data['zabbix_password']) 11 | 12 | def get_hosts(self): 13 | return self.zb.host.get(output=['hostid','host']) 14 | 15 | def get_host_tem(self): 16 | data = { 17 | "output": ["hostid","name"], 18 | "selectParentTemplates": ["templateid","name"] 19 | } 20 | ret = self.zb.host.get(**data) 21 | return ret 22 | 23 | def get_interface(self, hostids): 24 | data = self.zb.hostinterface.get(hostids=hostids, output=['hostid','ip']) 25 | ret = {} 26 | for d in data: 27 | ret[d['hostid']] = d['ip'] 28 | return ret 29 | def get_hostgroup(self): 30 | return self.zb.hostgroup.get(output=['groupid','name']) 31 | 32 | def create_host(self, params): 33 | return self.zb.host.create(**params) 34 | 35 | def get_template(self): 36 | ret = self.zb.template.get(output=["templateid","name"]) 37 | return ret 38 | 39 | def link_template(self, hostid, templateids): 40 | data = { 41 | "hostid":hostid, 42 | "templates":templateids 43 | } 44 | ret=self.zb.host.update(data) 45 | return ret 46 | 47 | 48 | def unlink_template(self, hostid, templateid): 49 | return self.zb.host.update(hostid=hostid, templates_clear = [{"templateid":templateid}]) 50 | 51 | def create_maintenance(self, params): 52 | return self.zb.maintenance.create(**params) 53 | 54 | def get_maintenance(self): 55 | data = { 56 | "output": "extend", 57 | "selectHosts": ["name"] 58 | } 59 | ret = self.zb.maintenance.get(**data) 60 | return ret 61 | 62 | def del_maintenance(self, maintenanceids): 63 | return self.zb.maintenance.delete(maintenanceids) 64 | 65 | def get_trigger(self, params): 66 | return self.zb.trigger.get(**params) 67 | 68 | def get_alerts(self, params): 69 | return self.zb.alert.get(**params) 70 | 71 | def host_status(self, hostid, status): 72 | return self.zb.host.update(hostid=hostid, status = status) 73 | 74 | def hostid_get_template(self,hostids): 75 | data = { 76 | "output": ["hostid"], 77 | "selectParentTemplates": ["templateid"], 78 | "hostids": hostids 79 | } 80 | 81 | return self.zb.host.get(**data) 82 | 83 | def get_graphid(self,hostid): 84 | data = { 85 | "selectGraphs": ["graphid","name"], 86 | "filter": {"hostid": hostid} 87 | } 88 | 89 | ret = self.zb.host.get(**data) 90 | return ret[0]['graphs'] 91 | 92 | 93 | #zabbix_server = Zabbix("http://192.168.63.233/zabbix","Admin","zabbix") 94 | 95 | 96 | def init(): 97 | app.config['cursor'].execute_clean_sql('zbhost') 98 | init_zabbix() 99 | init_cmdb() 100 | 101 | 102 | def init_cmdb(): 103 | try: 104 | #取host (在server表里) 105 | fields = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','server_purpose','server_run','expire','server_up_time'] 106 | #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name 107 | hosts = app.config['cursor'].get_results('server', fields) 108 | for h in hosts: 109 | data = {'cmdb_hostid':h['id']} 110 | where = {'ip':h['ip']} 111 | result = app.config['cursor'].execute_update_sql('zbhost', data, where) 112 | #更新到cache表, ip 113 | except: 114 | return "" 115 | 116 | 117 | def init_zabbix(): 118 | try: 119 | #第一步 取出所有host,要ip,host,id 120 | zb_hosts = app.config['zabbix'].get_hosts() 121 | zb_hosts_interface = app.config['zabbix'].get_interface([z['hostid'] for z in zb_hosts]) 122 | data = [] 123 | ret = [] 124 | for h in zb_hosts: 125 | h['ip'] = zb_hosts_interface[h['hostid']] 126 | data.append(h) 127 | ###数据插入数据库 128 | for i in data: 129 | result = app.config['cursor'].execute_insert_sql('zbhost', i) 130 | 131 | except: 132 | return "" 133 | 134 | def create_zabbix_host(hostid,groupid): 135 | ret = [] 136 | for host in hostid: 137 | data = { 138 | "host": host, 139 | "interfaces": [ 140 | { 141 | "type": 1, 142 | "main": 1, 143 | "useip": 1, 144 | "ip": host, 145 | "dns": "", 146 | "port": "10050" 147 | } 148 | ], 149 | "groups": [ 150 | { 151 | "groupid": groupid 152 | } 153 | ] 154 | } 155 | ret.append(app.config['zabbix'].create_host(data)) 156 | return ret 157 | 158 | def create_maintenance(name,start,stop,hostids,time): 159 | data = { 160 | "name": name, 161 | "active_since": start, 162 | "active_till": stop, 163 | "hostids": hostids, 164 | "timeperiods": [ 165 | { 166 | "timeperiod_type": 0, 167 | "period": time 168 | } 169 | ] 170 | } 171 | ret = app.config['zabbix'].create_maintenance(data) 172 | return ret 173 | -------------------------------------------------------------------------------- /devops/api/zabbix_api.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/zabbix_api.pyc -------------------------------------------------------------------------------- /devops/api/zbhost.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | from flask import request 4 | from . import app , jsonrpc 5 | from auth import auth_login 6 | import json, traceback 7 | import util 8 | from zabbix_api import * 9 | #这里是关于用户角色的增删改查及组对应的权限id2name 10 | 11 | @jsonrpc.method('zbhost.create') 12 | @auth_login 13 | def idc_create(auth_info, **kwargs): 14 | if auth_info['code'] == 1: 15 | return json.dumps(auth_info) 16 | username = auth_info['username'] 17 | try: 18 | data = request.get_json()['params'] 19 | print data 20 | if not util.check_name(data['name']): 21 | return json.dumps({'code': 1, 'errmsg': 'name must be string or int'}) 22 | app.config['cursor'].execute_insert_sql('zbhost', data) 23 | util.write_log('api').info(username, "create idc %s scucess" % data['name']) 24 | return json.dumps({'code':0,'result':'create idc %s scucess' % data['name']}) 25 | except: 26 | util.write_log('api').error(username,"create idc error: %s" % traceback.format_exc()) 27 | return json.dumps({'code':1,'errmsg':'create idc fail'}) 28 | 29 | @jsonrpc.method('zbhost.getlist') 30 | @auth_login 31 | def zbhost_select(auth_info,**kwargs): 32 | datadict = {} 33 | ret = [] 34 | if auth_info['code'] == 1: 35 | return json.dumps(auth_info) 36 | username = auth_info['username'] 37 | if '1' not in auth_info['r_id']: 38 | return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) 39 | try: 40 | init() 41 | fields = ['id','cmdb_hostid','hostid','host','ip'] 42 | zabbix_hosts = app.config['cursor'].get_results('zbhost', fields) 43 | hostid = [str(zb["cmdb_hostid"]) for zb in zabbix_hosts] 44 | server_hosts = app.config['cursor'].get_results('server',["id"]) 45 | for i in server_hosts: 46 | if str(i["id"]) not in hostid: 47 | datadict["id"] = i["id"] 48 | #all_host = app.config['cursor'].get_results('server',["ip"],datadict) 49 | get_ip = app.config['cursor'].get_where_results('server',["id","ip"],datadict) 50 | ret.append(get_ip[0]) 51 | util.write_log('api').info(username, 'select zabbix list success') 52 | return json.dumps({'code':0, 'result':ret}) 53 | 54 | except: 55 | util.write_log('api').error("select zabbixgroup list error: %s" % traceback.format_exc()) 56 | return json.dumps({'code':1,'errmsg':'getzabbixgroup failed'}) 57 | 58 | 59 | @jsonrpc.method('zbhost_allhost.getlist') 60 | @auth_login 61 | def zbhost_allhost_select(auth_info,**kwargs): 62 | datalist = [] 63 | if auth_info['code'] == 1: 64 | return json.dumps(auth_info) 65 | username = auth_info['username'] 66 | if '1' not in auth_info['r_id']: 67 | return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) 68 | try: 69 | data = app.config['zabbix'].get_hosts() 70 | #print data 71 | return json.dumps({'code':0, 'result':data}) 72 | except: 73 | util.write_log('api').error("select zabbixgroup list error: %s" % traceback.format_exc()) 74 | return json.dumps({'code':1,'errmsg':'get zabbixgroup failed'}) 75 | 76 | @jsonrpc.method('zbhost.update') 77 | @auth_login 78 | def idc_update(auth_info, **kwargs): 79 | if auth_info['code'] == 1: 80 | return json.dumps(auth_info) 81 | username = auth_info['username'] 82 | if '1' not in auth_info['r_id']: 83 | return json.dumps({'code': 1,'errmsg':'you not admin,no idc' }) 84 | try: 85 | data = request.get_json()['params'] 86 | print data 87 | where = data.get('where',None) 88 | data = data.get('data',None) 89 | if not where: 90 | return json.dumps({'code':1, 'errmsg':'must need a condition'}) 91 | result = app.config['cursor'].execute_update_sql('idc', data, where) 92 | if not result: 93 | return json.dumps({'code':1, 'errmsg':'result is null'}) 94 | util.write_log('api').info(username, 'update idc success!' ) 95 | return json.dumps({'code':0,'result':'update idc scucess'}) 96 | except: 97 | util.write_log('api' ).error("update error: %s" % traceback.format_exc()) 98 | return json.dumps( {'code':1,'errmsg':"update idc failed"}) 99 | -------------------------------------------------------------------------------- /devops/api/zbhost.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/api/zbhost.pyc -------------------------------------------------------------------------------- /devops/conf/.service.conf.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/conf/.service.conf.swp -------------------------------------------------------------------------------- /devops/conf/config_api.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | socket = 0.0.0.0:3000 3 | processes = 4 4 | threads = 2 5 | pythonpath = /data/wwwroot/reboot/devops 6 | module = runapi 7 | callable = app 8 | buffer-size = 32768 9 | -------------------------------------------------------------------------------- /devops/conf/config_web.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | socket = 0.0.0.0:3001 3 | processes = 4 4 | threads = 2 5 | pythonpath = /datawwroot/reboot/devops 6 | module = runweb 7 | callable = app 8 | buffer-size = 32768 9 | -------------------------------------------------------------------------------- /devops/conf/devops.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `user` ( 2 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 3 | `username` varchar(40) NOT NULL COMMENT '用户名', 4 | `password` varchar(64) NOT NULL COMMENT '密码', 5 | `name` varchar(80) NOT NULL COMMENT '姓名', 6 | `email` varchar(64) NOT NULL COMMENT '公司邮箱', 7 | `mobile` varchar(16) COMMENT '手机号', 8 | `r_id` varchar(32) NOT NULL COMMENT '角色id,允许多个r_id,存为字符串类型', 9 | `is_lock` tinyint(1) unsigned NOT NULL COMMENT '是否锁定 0-未锁定 1-锁定', 10 | `join_date` datetime DEFAULT NULL COMMENT '注册时间', 11 | `last_login` datetime DEFAULT NULL COMMENT '最后登录时间', 12 | PRIMARY KEY (`id`), 13 | UNIQUE KEY `username` (`username`) 14 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 15 | 16 | 17 | CREATE TABLE `role` ( 18 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 19 | `name` varchar(20) NOT NULL COMMENT '角色名', 20 | `name_cn` varchar(40) NOT NULL COMMENT '角色中文名', 21 | `p_id` varchar(20) NOT NULL COMMENT '权限id,允许多个p_id,存为字符串类型', 22 | `info` varchar(50) DEFAULT NULL COMMENT '角色描述信息', 23 | PRIMARY KEY (`id`), 24 | UNIQUE KEY `name` (`name`) 25 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 26 | 27 | 28 | CREATE TABLE `power` ( 29 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 30 | `name` varchar(32) NOT NULL COMMENT '权限英文名', 31 | `name_cn` varchar(40) NOT NULL COMMENT '权限中文名', 32 | `url` varchar(128) NOT NULL COMMENT '权限对应的url', 33 | `comment` varchar(128) NOT NULL COMMENT '备注', 34 | PRIMARY KEY (`id`), 35 | UNIQUE KEY `name` (`name`) 36 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 37 | 38 | 39 | CREATE TABLE `project` ( 40 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 41 | `name` varchar(128) NOT NULL COMMENT '项目名', 42 | `path` varchar(80) NOT NULL COMMENT '项目代码仓库路径', 43 | `principal` int(10) unsigned NOT NULL COMMENT '负责人', 44 | `p_user` int(10) unsigned DEFAULT NULL COMMENT '有权限的用户', 45 | `p_group` int(10) unsigned DEFAULT NULL COMMENT '有权限的组', 46 | `create_date` date NOT NULL COMMENT '创建时间', 47 | `is_lock` tinyint(1) unsigned DEFAULT '0' COMMENT '是否锁定 0-未锁定 1-锁定', 48 | `comment` varchar(256) DEFAULT NULL COMMENT '备注', 49 | PRIMARY KEY (`id`), 50 | UNIQUE KEY `name` (`name`) 51 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 52 | 53 | 54 | CREATE TABLE `project_test` ( 55 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 56 | `project_id` int(10) NOT NULL COMMENT '对应project项目ID', 57 | `host` varchar(64) NOT NULL COMMENT '测试主机', 58 | `commit` varchar(64) NOT NULL COMMENT '推送版本号', 59 | `pusher` varchar(128) NOT NULL COMMENT '推送人', 60 | `push_date` datetime NOT NULL COMMENT '推送时间', 61 | `comment` varchar(256) COMMENT '备注', 62 | PRIMARY KEY (`id`) 63 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 64 | 65 | 66 | CREATE TABLE `project_apply` ( 67 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 68 | `project_id` int(10) NOT NULL COMMENT '对应project项目ID', 69 | `info` varchar(64) NOT NULL COMMENT '发布简介', 70 | `applicant` varchar(64) NOT NULL COMMENT '申请人', 71 | `version` varchar(64) DEFAULT NULL COMMENT '发布版本', 72 | `commit` varchar(64) NOT NULL COMMENT '代码最新版本', 73 | `apply_date` datetime NOT NULL COMMENT '申请时间', 74 | `status` int(10) DEFAULT 0 COMMENT '发布状态', 75 | `detail` text COMMENT '发布详情', 76 | PRIMARY KEY (`id`), 77 | UNIQUE KEY `project_id` (`project_id`) 78 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 79 | 80 | CREATE TABLE `project_deploy` ( 81 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 82 | `project_id` int(10) NOT NULL COMMENT '对应project的项目ID', 83 | `info` varchar(64) NOT NULL COMMENT '发布简介', 84 | `version` varchar(64) DEFAULT NULL COMMENT '发布版本', 85 | `commit` varchar(64) NOT NULL COMMENT '代码最新版本', 86 | `applicant` varchar(64) NOT NULL COMMENT '操作人', 87 | `apply_date` datetime NOT NULL COMMENT '操作时间', 88 | `status` int(10) DEFAULT 0 COMMENT '发布状态', 89 | `detail` text COMMENT '发布详情', 90 | PRIMARY KEY (`id`) 91 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 92 | 93 | CREATE TABLE `cobbler` ( 94 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 95 | `ip` varchar(50) NOT NULL COMMENT '给主机分配IP', 96 | `MAC` varchar(50) NOT NULL COMMENT '通过MAC地址定制安装', 97 | `hostname` varchar(50) DEFAULT NULL COMMENT '主机名', 98 | `os` varchar(50) NOT NULL COMMENT '系统', 99 | `status` varchar(50) DEFAULT 0 COMMENT '装机状态', 100 | PRIMARY KEY (`id`) 101 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 102 | 103 | CREATE TABLE `install` ( 104 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 105 | `ip` varchar(50) NOT NULL COMMENT '给主机分配IP', 106 | 'install_time' datetime NOT NULL COMMENT '安装时间', 107 | `os` varchar(50) NOT NULL COMMENT '操作系统', 108 | PRIMARY KEY (`id`) 109 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 110 | 111 | CREATE TABLE `profile` ( 112 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 113 | `name` varchar(50) NOT NULL COMMENT 'profile name', 114 | `os` varchar(50) NOT NULL COMMENT '操作系统', 115 | `ks` varchar(100) NOT NULL COMMENT 'ks文件', 116 | PRIMARY KEY (`id`) 117 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 118 | 119 | CREATE TABLE `cabinet` ( 120 | `id` int(11) NOT NULL AUTO_INCREMENT, 121 | `name` varchar(30) NOT NULL, 122 | `idc_id` int(11) NOT NULL, 123 | `power` varchar(20) DEFAULT NULL, 124 | PRIMARY KEY (`id`) 125 | ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; 126 | 127 | CREATE TABLE `idc` ( 128 | `id` int(11) NOT NULL AUTO_INCREMENT, 129 | `name` varchar(20) NOT NULL, 130 | `idc_name` varchar(30) NOT NULL, 131 | `address` varchar(255) NOT NULL, 132 | `phone` varchar(15) NOT NULL, 133 | `email` varchar(30) NOT NULL, 134 | `user_interface` varchar(50) NOT NULL, 135 | `user_phone` varchar(20) NOT NULL, 136 | `rel_cabinet_num` int(11) DEFAULT NULL, 137 | `pact_cabinet_num` int(11) NOT NULL, 138 | PRIMARY KEY (`id`) 139 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; 140 | 141 | CREATE TABLE `maintenance` ( 142 | `id` int(11) NOT NULL AUTO_INCREMENT, 143 | `maintenance_name` varchar(50) DEFAULT NULL, 144 | `hostname` varchar(50) DEFAULT NULL, 145 | `maintenance_time` int(11) DEFAULT NULL, 146 | `update_time` datetime DEFAULT NULL, 147 | PRIMARY KEY (`id`) 148 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 149 | 150 | CREATE TABLE `product` ( 151 | `id` int(11) NOT NULL AUTO_INCREMENT, 152 | `service_name` varchar(20) DEFAULT NULL, 153 | `pid` int(11) DEFAULT NULL, 154 | `module_letter` varchar(10) DEFAULT NULL, 155 | PRIMARY KEY (`id`) 156 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 157 | 158 | CREATE TABLE `server` ( 159 | `id` int(11) NOT NULL AUTO_INCREMENT, 160 | `hostname` varchar(20) DEFAULT NULL, 161 | `ip` varchar(20) DEFAULT NULL, 162 | `vm_status` int(11) DEFAULT NULL, 163 | `st` varchar(20) DEFAULT NULL, 164 | `uuid` varchar(100) DEFAULT NULL, 165 | `manufacturers` varchar(100) DEFAULT NULL, 166 | `server_type` varchar(100) DEFAULT NULL, 167 | `server_cpu` varchar(200) DEFAULT NULL, 168 | `os` varchar(30) DEFAULT NULL, 169 | `server_disk` varchar(20) DEFAULT NULL, 170 | `server_mem` int(11) DEFAULT NULL, 171 | `mac_address` varchar(30) DEFAULT NULL, 172 | `manufacture_date` date DEFAULT NULL, 173 | `check_update_time` datetime DEFAULT NULL, 174 | `supplier` varchar(30) DEFAULT NULL, 175 | `idc_id` int(11) DEFAULT NULL, 176 | `cabinet_id` int(11) DEFAULT NULL, 177 | `cabinet_pos` varchar(10) DEFAULT NULL, 178 | `expire` datetime DEFAULT NULL, 179 | `supplier_phone` varchar(20) DEFAULT NULL, 180 | `server_up_time` datetime DEFAULT NULL, 181 | `server_purpose` varchar(30) DEFAULT NULL, 182 | `host` int(11) DEFAULT NULL, 183 | `server_run` varchar(30) DEFAULT NULL, 184 | PRIMARY KEY (`id`) 185 | ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; 186 | 187 | CREATE TABLE `zbhost` ( 188 | `id` int(11) NOT NULL AUTO_INCREMENT, 189 | `cmdb_hostid` int(11) DEFAULT NULL, 190 | `hostid` int(11) DEFAULT NULL, 191 | `host` varchar(40) DEFAULT NULL, 192 | `ip` varchar(30) DEFAULT NULL, 193 | PRIMARY KEY (`id`) 194 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 195 | 196 | CREATE TABLE `Switch` ( 197 | `id` int(11) NOT NULL AUTO_INCREMENT, 198 | `ip` varchar(50) DEFAULT NULL, 199 | `device` varchar(40) DEFAULT NULL, 200 | `port` int(8) DEFAULT NULL, 201 | `cabinet` int(4) DEFAULT NULL, 202 | `idc` int(4) DEFAULT NULL, 203 | PRIMARY KEY (`id`) 204 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 205 | -------------------------------------------------------------------------------- /devops/conf/logger.conf: -------------------------------------------------------------------------------- 1 | [loggers] 2 | keys=root,api,web 3 | 4 | # [logger_xxxx] logger_模块名称, 其中logger_root是必须的,否则报错 5 | # level 级别,级别有DEBUG、INFO、WARNING、ERROR、CRITICAL 6 | # handlers 处理类,可以有多个,用逗号分开 7 | # qualname logger名称,应用程序通过 logging.getLogger获取。对于不能获取的名称,则记录到root模块。 8 | # propagate 是否继承父类的log信息,0:否 1:是 9 | 10 | [logger_root] 11 | level=DEBUG 12 | handlers=root 13 | 14 | [logger_api] 15 | handlers=api 16 | qualname=api 17 | propagate=0 18 | 19 | [logger_web] 20 | handlers=web 21 | qualname=web 22 | propagate=0 23 | 24 | # [handler_xxxx] 25 | # class handler类名 26 | # level 日志级别 27 | # formatter,上面定义的formatter 28 | # args handler初始化函数参数 29 | 30 | [handlers] 31 | keys=root,api,web 32 | 33 | [handler_root] 34 | class=StreamHandler 35 | level=INFO 36 | formatter=fmt01 37 | args=(sys.stderr,) 38 | 39 | 40 | [handler_api] 41 | class=handlers.RotatingFileHandler 42 | level=DEBUG 43 | formatter=fmt01 44 | args=('/var/log/api/api.log', 'a', 10*1024*1024, 5) 45 | 46 | [handler_web] 47 | class=handlers.RotatingFileHandler 48 | level=DEBUG 49 | formatter=fmt01 50 | args=('/var/log/web/web.log', 'a', 10*1024*1024, 5) 51 | 52 | # 日志格式 53 | [formatters] 54 | keys=fmt01 55 | 56 | [formatter_fmt01] 57 | format=%(asctime)s %(filename)s-%(funcName)s:[%(lineno)d] %(name)s %(levelname)s %(message)s 58 | datefmt=%d-%b-%Y %H:%M:%S 59 | 60 | -------------------------------------------------------------------------------- /devops/conf/service.conf: -------------------------------------------------------------------------------- 1 | [common] 2 | mysql_host=127.0.0.1 3 | mysql_port=3306 4 | mysql_user=root 5 | mysql_passwd=123456 6 | mysql_db=devops 7 | mysql_charset=utf8 8 | passport_key=123456 9 | smtp_host=**** 10 | smtp_user=***** 11 | smtp_pass=***** 12 | 13 | [api] 14 | port=2000 15 | bind=0.0.0.0 16 | 17 | [web] 18 | port=2001 19 | api_host=127.0.0.1:2000 20 | 21 | [zabbix] 22 | zabbix_url = http://192.168.63.247/zabbix 23 | zabbix_user = Admin 24 | zabbix_password = zabbix 25 | zabbix_login_url = http://192.168.63.247/zabbix/index.php 26 | zabbix_graph_url = http://192.168.63.247/zabbix/chart2.php 27 | 28 | [cobbler] 29 | cobbler_url=http://192.168.63.182/cobbler_api 30 | cobbler_user=xiaoluo 31 | cobbler_password=123456 32 | 33 | [celery] 34 | redis_host = redis://127.0.0.1:6379/0 35 | mail_host = smtp.163.com 36 | mail_user = xxx@163.com ###自己的163账号 37 | mail_pass = xxxx ###自己的163密码 38 | mail_postfix = 163.com 39 | 40 | -------------------------------------------------------------------------------- /devops/db.py: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | import util,traceback 3 | import MySQLdb as mysql 4 | 5 | class Cursor(): 6 | def __init__(self, config): 7 | self.config = dict([(k[6:], config[k]) for k in config if k.startswith('mysql_')]) 8 | if 'port' in self.config: 9 | self.config['port'] = int(self.config['port']) 10 | if self.config: 11 | self._connect_db() 12 | 13 | def _connect_db(self): 14 | self.db = mysql.connect(**self.config) 15 | self.db.autocommit(True) 16 | self.cur = self.db.cursor() 17 | 18 | def _close_db(self): 19 | self.cur.close() 20 | self.db.close() 21 | 22 | def _execute(self, sql): 23 | try: 24 | return self.cur.execute(sql) 25 | except: 26 | self._close_db() 27 | self._connect_db() 28 | return self.cur.execute(sql) 29 | 30 | def _fetchone(self): 31 | return self.cur.fetchone() 32 | 33 | def _fetchall(self): 34 | return self.cur.fetchall() 35 | 36 | def _insert_sql(self, table_name, data): 37 | fields, values = [], [] 38 | for k, v in data.items(): 39 | fields.append(k) 40 | values.append("'%s'" % v) 41 | sql = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ','.join(fields), ','.join(values)) 42 | util.write_log('api').info("Insert sql: %s" % sql) 43 | return sql 44 | 45 | def execute_insert_sql(self, table_name, data): 46 | try: 47 | sql = self._insert_sql(table_name, data) 48 | if not sql: 49 | return None 50 | return self._execute(sql) 51 | except: 52 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 53 | 54 | def execute_clean_sql(self, table_name): 55 | try: 56 | sql = "truncate %s"%(table_name) 57 | return self._execute(sql) 58 | except: 59 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 60 | 61 | def _select_sql(self, table_name, fields, where=None, order=None, asc_order=True, limit=None): 62 | if isinstance(where, dict) and where: 63 | conditions = [] 64 | for k, v in where.items(): 65 | if isinstance(v, list): 66 | conditions.append("%s IN (%s)" % (k, ','.join(v))) 67 | elif isinstance(v, str) or isinstance(v, unicode): 68 | conditions.append("%s='%s'" % (k, v)) 69 | elif isinstance(v, int): 70 | conditions.append("%s=%s" % (k, v)) 71 | 72 | sql = "SELECT %s FROM %s WHERE %s" % (','.join(fields), table_name, ' AND '.join(conditions)) 73 | elif not where: 74 | sql = "SELECT %s FROM %s" % (','.join(fields), table_name) 75 | else: 76 | sql = "" 77 | if order and (isinstance(order, str) or isinstance(order, unicode)): 78 | sql = "%s ORDER BY %s %s" % (sql, order, 'ASC' if asc_order else 'DESC') 79 | if limit and isinstance(limit, tuple) and len(limit) == 2: 80 | sql = "%s LIMIT %s,%s" % (sql, limit[0], limit[1]) 81 | util.write_log('api').info("Select sql: %s" % sql) 82 | return sql 83 | 84 | def get_one_result(self, table_name, fields, where=None, order=None, asc_order=True, limit=None): 85 | try: 86 | sql = self._select_sql(table_name, fields, where, order, asc_order, limit) 87 | if not sql: 88 | return None 89 | self._execute(sql) 90 | result_set = self._fetchone() 91 | return dict([(k, '' if result_set[i] is None else result_set[i]) for i,k in enumerate(fields)]) 92 | except: 93 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 94 | return {} 95 | 96 | def get_results(self, table_name, fields, where=None, order=None, asc_order=True, limit=None): 97 | try: 98 | sql = self._select_sql(table_name, fields, where, order, asc_order, limit) 99 | self._execute(sql) 100 | result_sets = self._fetchall() 101 | return [dict([(k, '' if row[i] is None else row[i]) for i,k in enumerate(fields)]) for row in result_sets] 102 | except: 103 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 104 | return [] 105 | 106 | def get_where_results(self, table_name,fields,where): 107 | try: 108 | for k,v in where.items(): 109 | sql = "SELECT %s FROM %s WHERE %s=%s" % (','.join(fields),table_name,k,v) 110 | self._execute(sql) 111 | result_sets = self._fetchall() 112 | return [dict([(k, '' if row[i] is None else row[i]) for i,k in enumerate(fields)]) for row in result_sets] 113 | except: 114 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 115 | return [] 116 | 117 | 118 | 119 | 120 | def _update_sql(self, table_name, data, where, fields=None): 121 | if not (where and isinstance(where, dict)): 122 | return "" 123 | where_cond = ["%s='%s'" % (k, v) for k,v in where.items()] 124 | if fields: 125 | conditions = ["%s='%s'" % (k, data[k]) for k in fields] 126 | else: 127 | conditions = ["%s='%s'" % (k, data[k]) for k in data] 128 | sql = "UPDATE %s SET %s WHERE %s" % (table_name, ','.join(conditions), ' AND '.join(where_cond)) 129 | util.write_log('api').info("Update sql: %s" % sql) 130 | return sql 131 | 132 | def execute_update_sql(self, table_name, data, where, fields=None): 133 | try: 134 | sql = self._update_sql(table_name, data, where, fields) 135 | if sql: 136 | return self._execute(sql) 137 | except: 138 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 139 | 140 | 141 | def _delete_sql(self, table_name, where): 142 | if not (where and isinstance(where, dict)): 143 | return "" 144 | where_cond = ["%s='%s'" % (k, v) for k,v in where.items()] 145 | sql = "DELETE FROM %s WHERE %s" % (table_name, ' AND '.join(where_cond)) 146 | util.write_log('api').info("Delete sql: %s" % sql) 147 | return sql 148 | 149 | def execute_delete_sql(self, table_name, where): 150 | try: 151 | sql = self._delete_sql(table_name, where) 152 | if sql: 153 | return self._execute(sql) 154 | except: 155 | util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) 156 | 157 | def if_id_exist(self, table_name,field_id): 158 | if isinstance(field_id, list): 159 | id_num=len(field_id) 160 | result = self.get_results(table_name, ['id'], {'id': field_id}) 161 | if id_num !=len(result): 162 | result=False 163 | else: 164 | result = self.get_one_result(table_name, ['id'], {'id': field_id}) 165 | if result: 166 | return True 167 | else: 168 | util.write_log('api').error("%s '%s' is not exist" % (table_name,field_id)) 169 | return False 170 | 171 | 172 | def getinfo(self, table_name, fields): 173 | ''' 174 | 175 | 查询单个数据表内容,fields首字段为key 176 | fields为两个字段,返回{v1: v2, ...},格式为 ['field1','field2'], 例如['id','name'],['name','r_id'] 177 | 返回结果一,两列都是字符串如:用户id2name {'1':'tom','2','jerry'}; 组信息id2name {'1':'sa','2':'ask'} 178 | 返回结果二,第二列是个列表如:用户权限信息:{u'songpeng': [u'1', u'2'], u'admin': [u'1', u'2', u'4', u'3']} 179 | 180 | ''' 181 | result = app.config['cursor'].get_results(table_name,fields) 182 | if fields[1] in ['r_id','p_id','user_all_perm']: #第二列的结果为列表的字段拼接为字符串 183 | result = dict((str(x[fields[0]]), x[fields[1]].split(',')) for x in result) 184 | else: 185 | result = dict((str(x[fields[0]]), x[fields[1]]) for x in result) 186 | return result 187 | 188 | @property 189 | def users(self): 190 | return self.getinfo('user', ['id', 'username']) 191 | 192 | @property 193 | def groups(self): 194 | return self.getinfo('user_group', ['id', 'name']) 195 | 196 | @property 197 | def user_groups(self): 198 | return self.getinfo('user', ['id', 'r_id']) 199 | 200 | @property 201 | def projects(self): 202 | return self.getinfo('project', ['id', 'name']) 203 | 204 | @property 205 | def project_perms(self): 206 | return self.getinfo('project', ['id','user_all_perm']) 207 | 208 | -------------------------------------------------------------------------------- /devops/db.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/db.pyc -------------------------------------------------------------------------------- /devops/install/a.txt: -------------------------------------------------------------------------------- 1 | Flask 2 | Flask-Bootstrap 3 | Flask-Moment 4 | Flask-Script 5 | Flask-Migrate 6 | Flask-SQLAlchemy 7 | Flask-WTF 8 | MySQL-python 9 | requests 10 | Flask-JSONRPC 11 | psutil 12 | zabbix_client 13 | -------------------------------------------------------------------------------- /devops/install/cobbler.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | #coding=utf8 3 | ################################################################## 4 | #将如下IP修改成你cobbler服务器的IP地址 5 | ip=192.168.63.182 6 | #将如下net修改成你Cobbler所在网段的NET 7 | net=192.168.63.0 8 | #修改成dhcp计划分配的IP段 9 | begin=192.168.63.250 10 | end=192.168.63.253 11 | echo "$ip www.xiaoluo.com" >> /etc/hosts 12 | yum install cobbler cobbler-web pykickstart dhcp debmirror syslinux cman fence-agents vim -y 13 | /etc/init.d/iptables stop 14 | /etc/init.d/httpd start 15 | /etc/init.d/cobblerd start 16 | service cobblerd restart 17 | sed -i -e 's/= yes/= no/g' /etc/xinetd.d/rsync 18 | sed -i -e 's/= yes/= no/g' /etc/xinetd.d/tftp 19 | sed -i 's@next_server: 127.0.0.1@next_server: '$ip'@g' /etc/cobbler/settings 20 | sed -i 's@server: 127.0.0.1@server: '$ip'@g' /etc/cobbler/settings 21 | cp /usr/share/syslinux/pxelinux.0 /var/lib/cobbler/loaders/ 22 | cp /usr/share/syslinux/meminfo.c32 /var/lib/cobbler/loaders/ 23 | sed -i 's$@arches="i386"$#@arches="i386"$g' /etc/debmirror.conf 24 | sed -i 's$@dists="sid"$#@dists="sid"$g' /etc/debmirror.conf 25 | sed -i 's@default_password_crypted@#default_password_crypted@g' /etc/cobbler/settings 26 | echo "default_password_crypted: "$1$ac756ac7$erF27Ljjp3rDItLVqHLOg/"" >> /etc/cobbler/settings 27 | cobbler get-loaders 28 | service cobblerd restart 29 | cobbler sync 30 | ####用cobbler check 查看到底有哪些步骤没有操作完成。 31 | cobbler check 32 | #dhcp 33 | cat > /etc/dhcp/dhcpd.conf < /etc/supervisord.confg 181 | 182 | vim /etc/supervisord.conf 183 | 184 | 在配置后面添加以下参数 185 | 186 | [program:celery] 187 | command=/devops/env/bin/celery worker -A tasks --loglevel=info ###注意看自己的沙盒环境 188 | directory=/devops/roncoo-cmdb/devops ##这个目录就是tasks的父目录 189 | stdout_logfile=/var/log/celery.log ##日志存放目录 190 | autostart=true 191 | autorestart=true 192 | redirect_stderr=true 193 | stopsignal=QUIT 194 | 195 | 10.3:启动后台进程管理: 196 | 197 | /devops/env/bin/supervisord 198 | 199 | 10.4:查看是否启动成功 200 | [root@drfdai www]# ps -ef |grep supervisor 201 | root 28656 1 0 04:52 ? 00:00:00 /usr/bin/python /usr/bin/supervisord 202 | root 28692 1542 0 04:53 pts/0 00:00:00 grep supervisor 203 | 204 | 10.5:有进程启动之后就可以启动celery: 205 | 启动celery: 206 | supervisorctl start celery 207 | 208 | 查看是否已经启动: 209 | (env)[root@www api]# ps -ef | grep work 210 | root 9634 2296 0 15:19 ? 00:00:05 /devops/env/bin/python /devops/env/bin/celery worker -A tasks --loglevel=info 211 | 212 | 11、安装完成之后启动: 213 | 214 | python runweb 215 | 216 | python runapi 217 | 218 | 12、主机采集通过sysinfo.py来操作,采集主机之后,手工录入硬件资源 219 | -------------------------------------------------------------------------------- /devops/runapi.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | from api import app, zabbix_api, zabbix_Graph_api 4 | import os,sys,logging,logging.config 5 | import db,util 6 | from celery import Celery,platforms 7 | 8 | #session使用需要设置secret_key 9 | app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' 10 | 11 | #导入自定义的各种配置参数,最终参数以字典形式返回 12 | work_dir = os.path.dirname(os.path.realpath(__file__)) 13 | service_conf = os.path.join(work_dir, 'conf/service.conf') 14 | img = os.path.join(work_dir,'web/static/zabbix') 15 | img_url = {"zabbix_img_url":img} 16 | 17 | 18 | config = util.get_config(service_conf, 'api') 19 | cobbler_config = util.get_config(service_conf, 'cobbler') 20 | zabbix_config = util.get_config(service_conf, 'zabbix') 21 | 22 | 23 | 24 | #将参数追加到app.config字典中,就可以随意调用了 25 | app.config.update(config) 26 | app.config.update(cobbler_config) 27 | app.config.update(img_url) 28 | app.config.update(zabbix_config) 29 | #print app.config 30 | 31 | 32 | #实例化数据库类,并将实例化的对象导入配置 33 | app.config['cursor'] = db.Cursor(config) 34 | app.config['zabbix'] = zabbix_api.Zabbix(zabbix_config) 35 | 36 | ########celery实例化加载########### 37 | 38 | 39 | 40 | 41 | if __name__ == '__main__': 42 | app.run(host=config.get('bind', '0.0.0.0'),port=int(config.get('port')), debug=True) 43 | -------------------------------------------------------------------------------- /devops/runweb.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | from web import app 4 | import os,sys,logging,logging.config 5 | import db,util 6 | 7 | work_dir = os.path.dirname(os.path.realpath(__file__)) 8 | app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' 9 | 10 | service_conf = os.path.join(work_dir, 'conf/service.conf') 11 | config = util.get_config(service_conf, 'web') 12 | #print config 13 | 14 | #将参数追加到app.config字典中,就可以随意调用了 15 | app.config.update(config) 16 | 17 | 18 | 19 | if __name__ == '__main__': 20 | app.run(host=config.get('bind', '0.0.0.0'),port=int(config.get('port')), debug=True) 21 | -------------------------------------------------------------------------------- /devops/switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # coding:utf-8 3 | 4 | 5 | import json 6 | import psutil 7 | import socket 8 | import time 9 | import re 10 | import requests 11 | 12 | def run(): 13 | data = {'device': 'huawei-5710', 'ip': '192.168.10.10','cabinet': 1,'idc':1,'port':38} 14 | res = {} 15 | res['params']=data 16 | res['jsonrpc'] = "2.0" 17 | res["id"] = 1 18 | res["method"]= "switch.add" 19 | # print res 20 | # for k,v in data.iteritems(): 21 | # print k, v 22 | send(res) 23 | 24 | def send(data): 25 | url = "http://192.168.63.182:2000/api" 26 | r = requests.post(url, headers=headers,json=data) 27 | print r.status_code 28 | print r.content 29 | 30 | 31 | if __name__ == "__main__": 32 | run() 33 | -------------------------------------------------------------------------------- /devops/sysinfo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # coding:utf-8 3 | 4 | 5 | import json 6 | import subprocess 7 | import psutil 8 | import socket 9 | import time 10 | import re 11 | import platform 12 | import requests 13 | 14 | 15 | device_white = ['eth0','eth1', 'eth2', 'eth3', 'em1'] 16 | 17 | headers = {"Content-Type": "application/json"} 18 | 19 | 20 | def get_hostname(): 21 | return socket.gethostname() 22 | 23 | def get_device_info(): 24 | ret = [] 25 | for device, info in psutil.net_if_addrs().iteritems(): 26 | if device in device_white: 27 | device_info = {'device': device} 28 | for snic in info: 29 | if snic.family == 2: 30 | device_info['ip'] = snic.address 31 | elif snic.family == 17: 32 | device_info['mac'] = snic.address 33 | ret.append(device_info) 34 | return ret 35 | 36 | def get_cpuinfo(): 37 | ret = {"cpu": '', 'num': 0} 38 | with open('/proc/cpuinfo') as f: 39 | for line in f: 40 | line_list = line.strip().split(':') 41 | key = line_list[0].rstrip() 42 | if key == "model name": 43 | ret['cpu'] = line_list[1].lstrip() 44 | if key == "processor": 45 | ret['num'] += 1 46 | return ret 47 | 48 | def get_disk(): 49 | cmd = """/sbin/fdisk -l|grep Disk|egrep -v 'identifier|mapper|Disklabel'""" 50 | disk_data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 51 | partition_size = [] 52 | for dev in disk_data.stdout.readlines(): 53 | try: 54 | size = int(dev.strip().split(', ')[1].split()[0]) / 1024 / 1024 / 1024 55 | partition_size.append(str(size)) 56 | except: 57 | pass 58 | return " + ".join(partition_size) 59 | 60 | def get_Manufacturer(): 61 | cmd = """/usr/sbin/dmidecode | grep -A6 'System Information'""" 62 | ret = {} 63 | manufacturer_data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 64 | for line in manufacturer_data.stdout.readlines(): 65 | if "Manufacturer" in line: 66 | ret['manufacturers'] = line.split(': ')[1].strip() 67 | elif "Product Name" in line: 68 | ret['server_type'] = line.split(': ')[1].strip() 69 | elif "Serial Number" in line: 70 | ret['st'] = line.split(': ')[1].strip().replace(' ','') 71 | elif "UUID" in line: 72 | ret['uuid'] = line.split(': ')[1].strip() 73 | return ret 74 | #return manufacturer_data.stdout.readline().split(': ')[1].strip() 75 | 76 | # 出厂日期 77 | def get_rel_date(): 78 | cmd = """/usr/sbin/dmidecode | grep -i release""" 79 | data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 80 | date = data.stdout.readline().split(': ')[1].strip() 81 | return re.sub(r'(\d+)/(\d+)/(\d+)',r'\3-\1-\2',date) 82 | 83 | def get_os_version(): 84 | return " ".join(platform.linux_distribution()) 85 | 86 | def get_innerIp(ipinfo): 87 | inner_device = ["eth0", "bond0"] 88 | ret = {} 89 | for info in ipinfo: 90 | if info.has_key('ip') and info.get('device', None) in inner_device: 91 | ret['ip'] = info['ip'] 92 | ret['mac_address'] = info['mac'] 93 | return ret 94 | return {} 95 | 96 | def get_Memtotal(): 97 | with open('/proc/meminfo') as mem_open: 98 | a = int(mem_open.readline().split()[1]) 99 | return a / 1024 100 | 101 | 102 | def run(): 103 | data = {} 104 | res = {} 105 | data['hostname'] = get_hostname() 106 | data.update(get_innerIp(get_device_info())) 107 | cpuinfo = get_cpuinfo() 108 | data['server_cpu'] = "{cpu} {num}".format(**cpuinfo) 109 | data['server_disk'] = get_disk() 110 | data.update( get_Manufacturer()) 111 | data['manufacture_date'] = get_rel_date() 112 | data['os'] = get_os_version() 113 | data['server_mem'] = get_Memtotal() 114 | if "VMware" in data['manufacturers']: 115 | data['vm_status'] = 0 116 | else: 117 | data['vm_status'] = 1 118 | res['params']=data 119 | res['jsonrpc'] = "2.0" 120 | res["id"] = 1 121 | res["method"]= "server.radd" 122 | # print res 123 | # for k,v in data.iteritems(): 124 | # print k, v 125 | send(res) 126 | 127 | def send(data): 128 | url = "http://192.168.63.182:2000/api" 129 | r = requests.post(url, headers=headers,json=data) 130 | print r.status_code 131 | print r.content 132 | 133 | 134 | if __name__ == "__main__": 135 | run() 136 | -------------------------------------------------------------------------------- /devops/tasks.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf-8 3 | 4 | import smtplib 5 | from email.mime.text import MIMEText 6 | import sys,os 7 | from celery import Celery,platforms 8 | import util 9 | 10 | work_dir = os.path.dirname(os.path.realpath(__file__)) 11 | service_conf = os.path.join(work_dir, 'conf/service.conf') 12 | 13 | config = util.get_config(service_conf, 'celery') 14 | 15 | celery = Celery('tasks', broker=config['redis_host']) 16 | platforms.C_FORCE_ROOT = True 17 | 18 | mail_host = config['mail_host'] 19 | mail_user = config['mail_user'] 20 | mail_pass = config['mail_pass'] 21 | mail_postfix = config['mail_postfix'] 22 | 23 | 24 | @celery.task 25 | def sendMail(mailto,subject,body,format='plain'): 26 | if isinstance(body,unicode): 27 | body = str(body) 28 | me= mail_user+"<"+mail_user+"@"+mail_postfix+">" 29 | msg = MIMEText(body,format,'utf-8') 30 | if not isinstance(subject,unicode): 31 | subject = unicode(subject) 32 | msg['Subject'] = subject 33 | msg['From'] = me 34 | msg['To'] = mailto 35 | msg["Accept-Language"]="zh-CN" 36 | msg["Accept-Charset"]="ISO-8859-1,utf-8" 37 | try: 38 | s = smtplib.SMTP() 39 | s.connect(mail_host) 40 | s.login(mail_user,mail_pass) 41 | s.sendmail(me, mailto, msg.as_string()) 42 | s.close() 43 | return True 44 | except Exception, e: 45 | print str(e) 46 | return False 47 | 48 | 49 | if __name__ == "__main__": 50 | sendMail(sys.argv[1], sys.argv[2], sys.argv[3]) 51 | -------------------------------------------------------------------------------- /devops/tasks.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/tasks.pyc -------------------------------------------------------------------------------- /devops/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # coding:utf-8 3 | 4 | 5 | import json 6 | import subprocess 7 | import psutil 8 | import socket 9 | import time 10 | import re 11 | import platform 12 | import requests 13 | 14 | 15 | device_white = ['eth0','eth1', 'eth2', 'eth3', 'em1'] 16 | 17 | headers = {"Content-Type": "application/json"} 18 | 19 | 20 | def get_hostname(): 21 | return socket.gethostname() 22 | 23 | def get_device_info(): 24 | ret = [] 25 | for device, info in psutil.net_if_addrs().iteritems(): 26 | if device in device_white: 27 | device_info = {'device': device} 28 | for snic in info: 29 | if snic.family == 2: 30 | device_info['ip'] = snic.address 31 | elif snic.family == 17: 32 | device_info['mac'] = snic.address 33 | ret.append(device_info) 34 | return ret 35 | 36 | def get_cpuinfo(): 37 | ret = {"cpu": '', 'num': 0} 38 | with open('/proc/cpuinfo') as f: 39 | for line in f: 40 | line_list = line.strip().split(':') 41 | key = line_list[0].rstrip() 42 | if key == "model name": 43 | ret['cpu'] = line_list[1].lstrip() 44 | if key == "processor": 45 | ret['num'] += 1 46 | return ret 47 | 48 | def get_disk(): 49 | cmd = """/sbin/fdisk -l|grep Disk|egrep -v 'identifier|mapper|Disklabel'""" 50 | disk_data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 51 | partition_size = [] 52 | for dev in disk_data.stdout.readlines(): 53 | try: 54 | size = int(dev.strip().split(', ')[1].split()[0]) / 1024 / 1024 / 1024 55 | partition_size.append(str(size)) 56 | except: 57 | pass 58 | return " + ".join(partition_size) 59 | 60 | def get_Manufacturer(): 61 | cmd = """/usr/sbin/dmidecode | grep -A6 'System Information'""" 62 | ret = {} 63 | manufacturer_data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 64 | for line in manufacturer_data.stdout.readlines(): 65 | if "Manufacturer" in line: 66 | ret['manufacturers'] = line.split(': ')[1].strip() 67 | elif "Product Name" in line: 68 | ret['server_type'] = line.split(': ')[1].strip() 69 | elif "Serial Number" in line: 70 | ret['st'] = line.split(': ')[1].strip().replace(' ','') 71 | elif "UUID" in line: 72 | ret['uuid'] = line.split(': ')[1].strip() 73 | return ret 74 | #return manufacturer_data.stdout.readline().split(': ')[1].strip() 75 | 76 | # 出厂日期 77 | def get_rel_date(): 78 | cmd = """/usr/sbin/dmidecode | grep -i release""" 79 | data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 80 | date = data.stdout.readline().split(': ')[1].strip() 81 | return re.sub(r'(\d+)/(\d+)/(\d+)',r'\3-\1-\2',date) 82 | 83 | def get_os_version(): 84 | return " ".join(platform.linux_distribution()) 85 | 86 | def get_innerIp(ipinfo): 87 | inner_device = ["eth0", "bond0"] 88 | ret = {} 89 | for info in ipinfo: 90 | if info.has_key('ip') and info.get('device', None) in inner_device: 91 | ret['ip'] = info['ip'] 92 | ret['mac_address'] = info['mac'] 93 | return ret 94 | return {} 95 | 96 | def get_Memtotal(): 97 | with open('/proc/meminfo') as mem_open: 98 | a = int(mem_open.readline().split()[1]) 99 | return a / 1024 100 | 101 | 102 | def run(): 103 | data = {} 104 | res = {} 105 | data['hostname'] = get_hostname() 106 | data.update(get_innerIp(get_device_info())) 107 | cpuinfo = get_cpuinfo() 108 | data['server_cpu'] = "{cpu} {num}".format(**cpuinfo) 109 | data['server_disk'] = get_disk() 110 | data.update( get_Manufacturer()) 111 | data['manufacture_date'] = get_rel_date() 112 | data['os'] = get_os_version() 113 | data['server_mem'] = get_Memtotal() 114 | if "VMware" in data['manufacturers']: 115 | data['vm_status'] = 0 116 | else: 117 | data['vm_status'] = 1 118 | res['params']=data 119 | res['jsonrpc'] = "2.0" 120 | res["id"] = 1 121 | res["method"]= "zabbix_Graph.add" 122 | # print res 123 | # for k,v in data.iteritems(): 124 | # print k, v 125 | send(res) 126 | 127 | def send(data): 128 | url = "http://192.168.63.216:2000/api" 129 | r = requests.post(url, headers=headers,json=data) 130 | print r.status_code 131 | print r.content 132 | 133 | 134 | if __name__ == "__main__": 135 | run() 136 | -------------------------------------------------------------------------------- /devops/util.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | 4 | import os, os.path 5 | import time,json 6 | import base64,glob 7 | import hashlib 8 | import traceback 9 | import ConfigParser 10 | import logging,logging.config 11 | 12 | def get_config(service_conf, section=''): 13 | config = ConfigParser.ConfigParser() 14 | config.read(service_conf) 15 | 16 | conf_items = dict(config.items('common')) if config.has_section('common') else {} 17 | if section and config.has_section(section): 18 | conf_items.update(config.items(section)) 19 | return conf_items 20 | 21 | def write_log(loggername): 22 | work_dir = os.path.dirname(os.path.realpath(__file__)) 23 | log_conf= os.path.join(work_dir, 'conf/logger.conf') 24 | logging.config.fileConfig(log_conf) 25 | logger = logging.getLogger(loggername) 26 | return logger 27 | 28 | 29 | def get_validate(username, uid, role, fix_pwd): 30 | t = int(time.time()) 31 | validate_key = hashlib.md5('%s%s%s' % (username, t, fix_pwd)).hexdigest() 32 | return base64.b64encode('%s|%s|%s|%s|%s' % (username, t, uid, role, validate_key)).strip() 33 | 34 | def validate(key, fix_pwd): 35 | t = int(time.time()) 36 | key = base64.b64decode(key) 37 | x = key.split('|') 38 | if len(x) != 5: 39 | write_log('api').warning("token参数数量不足") 40 | return json.dumps({'code':1,'errmsg':'token参数不足'}) 41 | 42 | if t > int(x[1]) + 2*60*60: 43 | write_log('api').warning("登录已经过期") 44 | return json.dumps({'code':1,'errmsg':'登录已过期'}) 45 | validate_key = hashlib.md5('%s%s%s' % (x[0], x[1], fix_pwd)).hexdigest() 46 | if validate_key == x[4]: 47 | write_log('api').info("api认证通过") 48 | return json.dumps({'code':0,'username':x[0],'uid':x[2],'r_id':x[3]}) 49 | else: 50 | write_log('api').warning("密码不正确") 51 | return json.dumps({'code':1,'errmsg':'密码不正确'}) 52 | def check_name(name): 53 | if isinstance(name, str) or isinstance(name, unicode): 54 | return name.isalnum() and len(name) >= 2 55 | else: 56 | return False 57 | 58 | def copy_file(name): 59 | inputFile = open("/var/lib/cobbler/kickstarts/demo.cfg","r") 60 | outputFile = open("/var/lib/cobbler/kickstarts/%s" %name,"a") 61 | alllines = inputFile.readlines() 62 | for eachline in alllines: 63 | outputFile.write(eachline) 64 | inputFile.close() 65 | outputFile.close() 66 | 67 | def write_file(name,para): 68 | with open('/var/lib/cobbler/kickstarts/%s'%name,'a+') as f: 69 | for k,v in para.items(): 70 | if k == "swap": 71 | line = "part %s --size=%s\n"%(k,v) 72 | else: 73 | line = "part %s --fstype ext4 --size=%s\n"%(k,v) 74 | f.write(line) 75 | addline = "%pre\n$SNIPPET('log_ks_pre')\n$SNIPPET('kickstart_start')\n$SNIPPET('pre_install_network_config')\n$SNIPPET('pre_anamon')\n%post\n%end\n" 76 | f.write(addline) 77 | def replace_url(name,url): 78 | with open('/var/lib/cobbler/kickstarts/%s'%name,'r') as r: 79 | lines=r.readlines() 80 | with open('/var/lib/cobbler/kickstarts/%s'%name,'w') as w: 81 | for l in lines: 82 | w.write(l.replace('urllist',url)) 83 | 84 | def graph_file(name): 85 | try: 86 | file = glob.glob(name+'/*') 87 | for i in file: 88 | os.remove(i) 89 | except: 90 | return 1 91 | 92 | def graph_img(name): 93 | try: 94 | ret = [] 95 | file = glob.glob(name+'/*') 96 | for i in file: 97 | ret.append(i.split("web")[1]) 98 | return ret 99 | except: 100 | return ret 101 | -------------------------------------------------------------------------------- /devops/util.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/util.pyc -------------------------------------------------------------------------------- /devops/web/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import sys 3 | reload(sys) 4 | sys.setdefaultencoding('utf-8') 5 | app = Flask(__name__) 6 | 7 | import demo,public,login 8 | 9 | -------------------------------------------------------------------------------- /devops/web/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/__init__.pyc -------------------------------------------------------------------------------- /devops/web/demo.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from __future__ import unicode_literals 3 | from flask import Flask, render_template,session,redirect,request,url_for 4 | from . import app 5 | import requests,json 6 | import util 7 | 8 | headers = {'content-type': 'application/json'} 9 | #deshboard页面 10 | @app.route('/') 11 | def index(): 12 | if session.get('author','nologin') == 'nologin': 13 | return redirect('/login') 14 | headers['authorization'] = session['author'] 15 | url = "http://%s/api" % app.config['api_host'] 16 | data = {'jsonrpc': '2.0', 'id': 1, 'method': 'user.getinfo'} 17 | req = requests.post(url, headers=headers, json=data) 18 | result = json.loads(json.loads(req.content).get('result', '{}')) 19 | # print result 20 | if result['code'] == 0: 21 | user = result['user'] 22 | session['user'] = result['user'] #用户信息存入session 23 | session['role'] = user['r_id'] #角色名eg:['sa','php'] 24 | session['perm'] = user['p_id'].keys() #权限名eg:['git','mysql'] 25 | session['username'] = user['name'] if user['name'] else user['username'] 26 | user['role'] = ','.join(user['r_id']) 27 | user['perm'] = ','.join(['%s' % (x['url'], x['name_cn']) for x in user['p_id'].values()]) 28 | return render_template('index.html',info=session,user=user) 29 | else: 30 | return redirect('/login') 31 | 32 | #适用于比较简单多功能,直接/htmlname 就能访问到,eg:deshboard 33 | @app.route('/') 34 | def single(htmlname): 35 | if session.get('author','nologin') == 'nologin': 36 | return redirect('/login') 37 | headers['authorization'] = session['author'] 38 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 39 | if int(validate_result['code']) == 0: 40 | return render_template(htmlname+'.html',info=session,user=session['user']) 41 | else: 42 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 43 | 44 | #用户权限系统模块,输入的htmlname名会展示对应的html页面 45 | @app.route('/user/') 46 | def user(htmlname): 47 | if session.get('author','nologin') == 'nologin': 48 | return redirect('/login') 49 | headers['authorization'] = session['author'] 50 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 51 | if int(validate_result['code']) == 0: 52 | return render_template(htmlname+'.html',info=session,user=session['user']) 53 | else: 54 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 55 | 56 | #项目管理模块 57 | @app.route('/project/') 58 | def project(htmlname): 59 | if session.get('author','nologin') == 'nologin': 60 | return redirect('/login') 61 | headers['authorization'] = session['author'] 62 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 63 | if int(validate_result['code']) == 0: 64 | return render_template(htmlname+'.html',info=session,user=session['user']) 65 | else: 66 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 67 | 68 | #cmdb模块 69 | @app.route('/cmdb/') 70 | def cmdb(htmlname): 71 | if session.get('author','nologin') == 'nologin': 72 | return redirect('/login') 73 | headers['authorization'] = session['author'] 74 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 75 | if int(validate_result['code']) == 0: 76 | return render_template(htmlname+'.html',info=session,user=session['user']) 77 | else: 78 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 79 | 80 | #zabbix 监控 81 | @app.route('/zabbix/') 82 | def zabbix(htmlname): 83 | if session.get('author','nologin') == 'nologin': 84 | return redirect('/login') 85 | headers['authorization'] = session['author'] 86 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 87 | if int(validate_result['code']) == 0: 88 | return render_template(htmlname+'.html',info=session,user=session['user']) 89 | else: 90 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 91 | 92 | #cobbler 平台 93 | @app.route('/cobbler/') 94 | def cobbler(htmlname): 95 | if session.get('author','nologin') == 'nologin': 96 | return redirect('/login') 97 | headers['authorization'] = session['author'] 98 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 99 | if int(validate_result['code']) == 0: 100 | return render_template(htmlname+'.html',info=session,user=session['user']) 101 | else: 102 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 103 | 104 | 105 | #故障平台 106 | @app.route('/device/') 107 | def device(htmlname): 108 | if session.get('author','nologin') == 'nologin': 109 | return redirect('/login') 110 | headers['authorization'] = session['author'] 111 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 112 | if int(validate_result['code']) == 0: 113 | return render_template(htmlname+'.html',info=session,user=session['user']) 114 | else: 115 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 116 | 117 | 118 | #第三方API接口页面 119 | @app.route('/api/') 120 | def api(htmlname): 121 | if session.get('author','nologin') == 'nologin': 122 | return redirect('/login') 123 | headers['authorization'] = session['author'] 124 | validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) 125 | if int(validate_result['code']) == 0: 126 | return render_template(htmlname+'.html',info=session,user=session['user']) 127 | else: 128 | return render_template(htmlname+'.html',errmsg=validate_result['errmsg']) 129 | 130 | #管理员修改用户密码 131 | @app.route("/user/changepasswd",methods=['GET','POST']) 132 | def changepasswd(): 133 | if session.get('username') == None : 134 | return redirect('/login') 135 | headers['authorization'] = session['author'] 136 | if request.method == 'POST': 137 | user_id = int(request.form.get('passwdid')) 138 | password = request.form.get('changepasswd') 139 | data = {'user_id':user_id,'password':password} 140 | url = "http://%s/api/password" % app.config['api_host'] 141 | r = requests.post(url, headers=headers,json=data) 142 | return r.text 143 | 144 | 145 | #用户修改个人密码 146 | @app.route("/user/chpwdoneself",methods=['GET','POST']) 147 | def chpwdoneself(): 148 | if session.get('username') == None: 149 | return redirect('/login') 150 | headers['authorization'] = session['author'] 151 | if request.method == 'POST': 152 | oldpasswd = request.form.get('oldpasswd') 153 | newpasswd = request.form.get('newpasswd') 154 | data = {'oldpassword':oldpasswd,'password':newpasswd} 155 | url = "http://%s/api/password" % app.config['api_host'] 156 | r = requests.post(url, headers=headers,json=data) 157 | return r.text 158 | 159 | 160 | @app.errorhandler(404) #系统自带的装饰器,遇到404回自动返回制定的404页面 161 | def not_found(e): 162 | return render_template('404.html') 163 | 164 | @app.errorhandler(500) 165 | def internal_server_error(e): 166 | return render_template('500.html') 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /devops/web/demo.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/demo.pyc -------------------------------------------------------------------------------- /devops/web/login.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from flask import Flask,request,session,render_template,redirect 3 | from . import app 4 | import requests,json 5 | import util 6 | 7 | headers = {'content-type': 'application/json'} 8 | 9 | @app.route("/login",methods=['GET','POST']) 10 | def login(): 11 | if request.method == 'POST': 12 | username = request.form.get('username') 13 | password = request.form.get('passwd') 14 | url = "http://%s/api/login?username=%s&passwd=%s" % (app.config['api_host'],username,password) 15 | r = requests.get(url, headers=headers) #请求API验证用户,并获取token 16 | result = json.loads(r.content) 17 | if result['code'] == 0: 18 | token = result["authorization"] 19 | res = util.validate(token,app.config['passport_key']) #解密token 20 | res = json.loads(res) #return : dict(username:*,uid:*,role:*) 21 | session['author'] = token 22 | session['username'] = username 23 | return json.dumps({'code':0}) 24 | else: 25 | return json.dumps({'code':1,'errmsg':result['errmsg']}) 26 | return render_template('login.html') 27 | 28 | @app.route("/logout",methods=['GET','POST']) 29 | def logout(): 30 | if session.get('author','nologin') == 'nologin': 31 | return redirect('/login') 32 | session.pop('author',None) 33 | return redirect('/login') 34 | -------------------------------------------------------------------------------- /devops/web/login.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/login.pyc -------------------------------------------------------------------------------- /devops/web/public.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from __future__ import unicode_literals 3 | from flask import Flask, render_template,session,redirect,request 4 | from . import app 5 | import requests,json 6 | import util,urllib 7 | 8 | headers = {"Content-Type": "application/json"} 9 | data = { 10 | "jsonrpc": "2.0", 11 | "id":1, 12 | } 13 | 14 | def get_url(): 15 | return "http://%s/api" % app.config['api_host'] 16 | 17 | def Handleformdata(formdata): 18 | res = {} 19 | for x in formdata.split('&'): #formdata="id=1&id=2&id=3&name=lzp&passwd=1111" > ['id=1','id=2','name=lzp'......] 20 | k, v = x.split('=', 1) # x: id=1,name=wd, > k=id,v=1 21 | if k in res and isinstance(res[k], list): 22 | res[k].append(v) # 3: res['id']=[1,2,3] 23 | elif k in res: 24 | res[k] = [res[k], v] #2: res['id']=[1,2] 25 | else: 26 | res[k] = v #1: res['id']=1 27 | #res={'id': ['1', '2','3'], 'name': 'wd', 'passwd': '1111'} 28 | 29 | for k in res: 30 | if isinstance(res[k] , list): 31 | res[k] = ','.join(res[k]) 32 | return res 33 | #res={'id': ['1,2,3'], 'name': 'wd', 'passwd': '1111'} 34 | 35 | 36 | @app.route('/listapi') 37 | def listapi(): 38 | headers['authorization'] = session['author'] 39 | method = request.args.get('method') 40 | data['method'] = method+".getlist" 41 | data['params'] = {} 42 | util.write_log('web').info(data) 43 | r = requests.post(get_url(),headers=headers,json=data) 44 | # print r.text 45 | util.write_log('web').info(r.text) 46 | return r.text 47 | 48 | @app.route('/addapi', methods=['GET','POST']) 49 | def addapi(): 50 | headers['authorization'] = session['author'] 51 | method = request.form.get('method') 52 | formdata = request.form.get('formdata') #str 53 | print repr(formdata) #flask默认解码为unicode格式如: u'id=13&name=aa&remark=%E4%BD%A0%E5%A5%BD' 中文部分python无法解析 54 | try: 55 | formdata = urllib.unquote(formdata).encode('iso-8859-1') 56 | #print repr(formdata) #解码后中文为utf8格式: u'id=13&name=aa&remark==\xe4\xbd\xa0\xe5\xa5\xbd' 57 | except: 58 | pass 59 | formdata = Handleformdata(formdata) 60 | data['method'] = method+".create" 61 | data['params']=formdata 62 | util.write_log('web').info(data) 63 | r = requests.post(get_url(),headers=headers,json=data) 64 | return r.text 65 | 66 | @app.route('/getapi') 67 | def getapi(): 68 | headers['authorization'] = session['author'] 69 | method = request.args.get('method') 70 | data['method'] = method+".get" 71 | uid = request.args.get('id') 72 | data['params'] = { 73 | "m_table":request.args.get('m_table',None), 74 | 'field':request.args.get('field',None), 75 | 's_table':request.args.get('s_table',None), 76 | 'where':{'id':int(request.args.get('id'))} 77 | } 78 | util.write_log('web').info(data) 79 | r = requests.post(get_url(),headers=headers,json=data) 80 | return r.text 81 | 82 | 83 | @app.route('/updateapi',methods=['GET','POST']) 84 | def updateapi(): 85 | headers['authorization'] = session['author'] 86 | method = request.form.get('method') 87 | formdata = request.form.get('formdata') #str 88 | # print formdata 89 | try: 90 | formdata = urllib.unquote(formdata).encode('iso-8859-1') 91 | except: 92 | pass 93 | formdata = Handleformdata(formdata) 94 | data['method'] = method+".update" 95 | data['params'] = { 96 | "data":formdata, 97 | "where":{ 98 | "id":int(formdata['id']) 99 | } 100 | } 101 | util.write_log('web').info(data) 102 | r = requests.post(get_url(), headers=headers, json=data) 103 | return r.content 104 | 105 | @app.route('/deleteapi') 106 | def deleteapi(): 107 | headers['authorization'] = session['author'] 108 | method = request.args.get('method') 109 | data['method'] = method+".delete" 110 | data['params'] = { 111 | "where":{ 112 | "id":int(request.args.get('id')) 113 | } 114 | } 115 | util.write_log('web').info(data) 116 | r = requests.post(get_url(),headers=headers,json=data) 117 | return r.text 118 | 119 | @app.route('/updateserverapi',methods=['GET','POST']) 120 | def updateserverapi(): 121 | headers['authorization'] = session['author'] 122 | method = request.form.get('method') 123 | formdata = request.form.get('formdata') #str 124 | # print formdata 125 | try: 126 | formdata = urllib.unquote(formdata).encode('iso-8859-1') 127 | except: 128 | pass 129 | formdata = Handleformdata(formdata) 130 | data['method'] = method+".update" 131 | data['params'] = { 132 | "data":formdata, 133 | "where":{ 134 | "ip":formdata['ip'] 135 | } 136 | } 137 | util.write_log('web').info(data) 138 | r = requests.post(get_url(), headers=headers, json=data) 139 | return r.content 140 | 141 | @app.route('/zabbixapi',methods=['GET','POST']) 142 | def add_zabbix_api(): 143 | headers['authorization'] = session['author'] 144 | params = dict(request.form) 145 | data['method']= 'zabbix.'+str(params['method'][0]) 146 | data['params'] = { 147 | "hostids": params["hostids"], 148 | "groupid": params["groupid"][0] 149 | } 150 | util.write_log('web').info(data) 151 | r = requests.post(get_url(), headers=headers, json=data) 152 | return r.content 153 | 154 | 155 | @app.route('/zabbix_template',methods=['GET','POST']) 156 | def zabbix_template(): 157 | headers['authorization'] = session['author'] 158 | params = dict(request.form) 159 | data['method']= 'zabbix_template.'+str(params['method'][0]) 160 | data['params'] = { 161 | "hostids": params["hostid"], 162 | "templateid": params["templateid"][0] 163 | } 164 | util.write_log('web').info(data) 165 | r = requests.post(get_url(), headers=headers, json=data) 166 | return r.content 167 | -------------------------------------------------------------------------------- /devops/web/public.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/public.pyc -------------------------------------------------------------------------------- /devops/web/static/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/.DS_Store -------------------------------------------------------------------------------- /devops/web/static/images/serverico/0.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/images/serverico/0.gif -------------------------------------------------------------------------------- /devops/web/static/images/serverico/1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/images/serverico/1.gif -------------------------------------------------------------------------------- /devops/web/static/images/serverico/2u_normal.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/images/serverico/2u_normal.gif -------------------------------------------------------------------------------- /devops/web/static/images/serverico/jg.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/images/serverico/jg.gif -------------------------------------------------------------------------------- /devops/web/static/images/serverico/qiang.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/images/serverico/qiang.gif -------------------------------------------------------------------------------- /devops/web/static/images/serverico/ta_normal.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/images/serverico/ta_normal.gif -------------------------------------------------------------------------------- /devops/web/static/img/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/img/.DS_Store -------------------------------------------------------------------------------- /devops/web/static/img/devops.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/img/devops.jpg -------------------------------------------------------------------------------- /devops/web/static/img/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/img/favicon.ico -------------------------------------------------------------------------------- /devops/web/static/vendor/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/.DS_Store -------------------------------------------------------------------------------- /devops/web/static/vendor/alert/.sweet-alert.css.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/alert/.sweet-alert.css.swp -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap-multiselect.css: -------------------------------------------------------------------------------- 1 | .multiselect-container{position:absolute;list-style-type:none;margin:0;padding:0}.multiselect-container .input-group{margin:5px}.multiselect-container>li{padding:0}.multiselect-container>li>a.multiselect-all label{font-weight:bold}.multiselect-container>li>label.multiselect-group{margin:0;padding:3px 20px 3px 20px;height:100%;font-weight:bold}.multiselect-container>li>a>label{margin:0;height:100%;cursor:pointer;font-weight:normal}.multiselect-container>li>a>label.radio,.multiselect-container>li>a>label.checkbox{margin:0}.multiselect-container>li>a>label>input[type="checkbox"]{margin-bottom:5px}.btn-group>.btn-group:nth-child(2)>.multiselect.btn{border-top-left-radius:4px;border-bottom-left-radius:4px} -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/bootstrap/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap/js/bootstrap-datetimepicker.zh-CN.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Simplified Chinese translation for bootstrap-datetimepicker 3 | * Yuan Cheung 4 | */ 5 | ;(function($){ 6 | $.fn.datetimepicker.dates['zh-CN'] = { 7 | days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"], 8 | daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"], 9 | daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"], 10 | months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], 11 | monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], 12 | today: "今天", 13 | suffix: [], 14 | meridiem: ["上午", "下午"] 15 | }; 16 | }(jQuery)); 17 | -------------------------------------------------------------------------------- /devops/web/static/vendor/bootstrap/js/npm.js: -------------------------------------------------------------------------------- 1 | // This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment. 2 | require('../../js/transition.js') 3 | require('../../js/alert.js') 4 | require('../../js/button.js') 5 | require('../../js/carousel.js') 6 | require('../../js/collapse.js') 7 | require('../../js/dropdown.js') 8 | require('../../js/modal.js') 9 | require('../../js/tooltip.js') 10 | require('../../js/popover.js') 11 | require('../../js/scrollspy.js') 12 | require('../../js/tab.js') 13 | require('../../js/affix.js') -------------------------------------------------------------------------------- /devops/web/static/vendor/font-awesome/fonts/FontAwesome.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/font-awesome/fonts/FontAwesome.otf -------------------------------------------------------------------------------- /devops/web/static/vendor/font-awesome/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/font-awesome/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /devops/web/static/vendor/font-awesome/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/font-awesome/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /devops/web/static/vendor/font-awesome/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncoo/roncoo-cmdb/31b7fbcf48a7a777989b82dca45763aa1689a154/devops/web/static/vendor/font-awesome/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /devops/web/static/vendor/metismenu/metis-menu.min.css: -------------------------------------------------------------------------------- 1 | /* 2 | * metismenu - v1.1.3 3 | * Easy menu jQuery plugin for Twitter Bootstrap 3 4 | * https://github.com/onokumus/metisMenu 5 | * 6 | * Made by Osman Nuri Okumus 7 | * Under MIT License 8 | */ 9 | 10 | .arrow{float:right;line-height:1.42857}.glyphicon.arrow:before{content:"\e079"}.active>a>.glyphicon.arrow:before{content:"\e114"}.fa.arrow:before{content:"\f104"}.active>a>.fa.arrow:before{content:"\f107"}.plus-times{float:right}.fa.plus-times:before{content:"\f067"}.active>a>.fa.plus-times{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}.plus-minus{float:right}.fa.plus-minus:before{content:"\f067"}.active>a>.fa.plus-minus:before{content:"\f068"} -------------------------------------------------------------------------------- /devops/web/static/vendor/metismenu/metis-menu.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | * metismenu - v1.1.3 3 | * Easy menu jQuery plugin for Twitter Bootstrap 3 4 | * https://github.com/onokumus/metisMenu 5 | * 6 | * Made by Osman Nuri Okumus 7 | * Under MIT License 8 | */ 9 | !function(a,b,c){function d(b,c){this.element=a(b),this.settings=a.extend({},f,c),this._defaults=f,this._name=e,this.init()}var e="metisMenu",f={toggle:!0,doubleTapToGo:!1};d.prototype={init:function(){var b=this.element,d=this.settings.toggle,f=this;this.isIE()<=9?(b.find("li.active").has("ul").children("ul").collapse("show"),b.find("li").not(".active").has("ul").children("ul").collapse("hide")):(b.find("li.active").has("ul").children("ul").addClass("collapse in"),b.find("li").not(".active").has("ul").children("ul").addClass("collapse")),f.settings.doubleTapToGo&&b.find("li.active").has("ul").children("a").addClass("doubleTapToGo"),b.find("li").has("ul").children("a").on("click."+e,function(b){return b.preventDefault(),f.settings.doubleTapToGo&&f.doubleTapToGo(a(this))&&"#"!==a(this).attr("href")&&""!==a(this).attr("href")?(b.stopPropagation(),void(c.location=a(this).attr("href"))):(a(this).parent("li").toggleClass("active").children("ul").collapse("toggle"),void(d&&a(this).parent("li").siblings().removeClass("active").children("ul.in").collapse("hide")))})},isIE:function(){for(var a,b=3,d=c.createElement("div"),e=d.getElementsByTagName("i");d.innerHTML="",e[0];)return b>4?b:a},doubleTapToGo:function(a){var b=this.element;return a.hasClass("doubleTapToGo")?(a.removeClass("doubleTapToGo"),!0):a.parent().children("ul").length?(b.find(".doubleTapToGo").removeClass("doubleTapToGo"),a.addClass("doubleTapToGo"),!1):void 0},remove:function(){this.element.off("."+e),this.element.removeData(e)}},a.fn[e]=function(b){return this.each(function(){var c=a(this);c.data(e)&&c.data(e).remove(),c.data(e,new d(this,b))}),this}}(jQuery,window,document); -------------------------------------------------------------------------------- /devops/web/static/vendor/server_down.js: -------------------------------------------------------------------------------- 1 | 2 | document.writeln(""); 3 | document.writeln(" "); 4 | document.writeln(""); 5 | document.writeln("

 <\/p>"); 6 | document.writeln(""); 7 | document.writeln("

 <\/p>"); 8 | document.writeln(""); 9 | document.writeln("

 <\/p><\/td>"); 10 | document.writeln(""); 11 | document.writeln(" <\/tr>"); 12 | document.writeln(""); 13 | document.writeln(" "); 14 | document.writeln(""); 15 | document.writeln("

澶�<\/p>"); 16 | document.writeln(""); 17 | document.writeln("

闂�<\/p>"); 18 | document.writeln(""); 19 | document.writeln("

鍏�<\/p>"); 20 | document.writeln(""); 21 | document.writeln("

鍙�<\/p><\/td>"); 22 | document.writeln(""); 23 | document.writeln(" <\/tr>"); 24 | document.writeln(""); 25 | document.writeln("<\/table>"); 26 | document.writeln(""); 27 | document.writeln("<\/body>"); 28 | document.writeln(""); 29 | document.writeln("<\/html>"); 30 | -------------------------------------------------------------------------------- /devops/web/static/vendor/server_top.js: -------------------------------------------------------------------------------- 1 | document.writeln(" 90 | 91 | 92 | 93 | 94 | 95 |

96 | 97 | 203 | 204 | {% endblock %} 205 | -------------------------------------------------------------------------------- /devops/web/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 24 | 25 | Devops平台 - 管理员登陆 26 | 27 | 28 | 29 |
30 | 41 |
42 | 43 | 44 | 45 | 46 | 47 | 48 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /devops/web/templates/project.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block breadcrumb %} 4 |
  • 发布系统
  • 5 |
  • 项目管理
  • 6 | {% endblock %} 7 | 8 | {% block body %} 9 |
    10 |
    11 |
    项目管理
    12 | 13 |
    14 | 15 |
    16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
    项目名负责人项目开发者创建时间状态备注操作
    32 | 33 | 34 | 35 | 36 |
    37 | 38 |
    39 | {% endblock %} 40 | 41 | {% block js %} 42 | 43 | {% endblock %} 44 | -------------------------------------------------------------------------------- /devops/web/templates/template.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block breadcrumb %} 4 |
  • dashboard
  • 5 | {% endblock %} 6 | 16 | 17 | 18 | {% block body %} 19 |
    20 |
    21 |
    22 |
    23 | 40 |
    41 |
    42 |
    43 |
    44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | {% endblock %} 53 | {% block js%} 54 | 55 | function getlist(){ 56 | zabbix_group = $("#zabbix_group"); 57 | sync_host_list = $("#host_list"); 58 | var url = "/listapi?method=zabbix_gettem" 59 | $.getJSON('/listapi?method=zbhost_allhost', function(data){ 60 | sync_host_list.empty(); 61 | server_list = JSON.parse(data['result']); 62 | if(server_list['code'] == 0){ 63 | $.each(server_list['result'], function(n, obj){ 64 | html = '
    '; 65 | html += ''; 69 | html += '
    '; 70 | sync_host_list.append(html); 71 | }); 72 | } 73 | else { 74 | 75 | swal(data['errmsg']); 76 | } 77 | 78 | }); 79 | $.getJSON(url,function(data){ 80 | data = JSON.parse(data['result']); 81 | console.log(data); 82 | if(data['code'] == 0){ 83 | $.each(data['result'], function(n, obj){ 84 | 85 | zabbix_group.append(""); 86 | }) 87 | }else 88 | { 89 | swal(data['errmsg']) 90 | } 91 | }) 92 | $("#create").click(function(){ 93 | hostids = new Array(); 94 | $("input[name='zabbix_hosts']:checked").each(function (i, n) { 95 | hostids[i] = n.value 96 | }); 97 | zabbix_groupid = $("#zabbix_group").val(); 98 | $.post('/zabbixapi',{method:"link_tem",hostids:hostids.toString(), groupid:zabbix_groupid}, 99 | function(data){ 100 | data=JSON.parse(data); //将json串转换为对象,然后取值 101 | data = JSON.parse(data['result']) //object 102 | console.log(data) 103 | if(data['code'] == 0){ 104 | swal({ 105 | title:"success", 106 | text:"添加成功", 107 | type:"success", 108 | confirmButtonText:'添加zabbi主机成功' 109 | },function(){ 110 | location.reload() 111 | }) 112 | }else{ 113 | swal(data['errmsg']) 114 | } 115 | 116 | }) 117 | }) /*end of create*/ 118 | 119 | $("#clean").click(function(){ 120 | hostids = new Array(); 121 | $("input[name='zabbix_hosts']:checked").each(function (i, n) { 122 | hostids[i] = n.value 123 | }); 124 | zabbix_groupid = $("#zabbix_group").val(); 125 | $.post('/zabbixapi',{method:"unlink_tem",hostids:hostids.toString(), groupid:zabbix_groupid}, 126 | function(data){ 127 | data=JSON.parse(data); //将json串转换为对象,然后取值 128 | data = JSON.parse(data['result']) //object 129 | console.log(data) 130 | if(data['code'] == 0){ 131 | swal({ 132 | title:"success", 133 | text:"删除成功", 134 | type:"success", 135 | confirmButtonText:'成功解绑模板' 136 | },function(){ 137 | location.reload() 138 | }) 139 | }else{ 140 | swal(data['errmsg']) 141 | } 142 | 143 | }) 144 | }) /*end of clean*/ 145 | 146 | } /*end of all*/ 147 | 148 | getlist() 149 | 150 | function inster_zabbix_data(data){ 151 | $.each( data, function(num, obj){ 152 | html = ""; 153 | html += get_host_html(obj); 154 | html += get_template_html(obj); 155 | $("#zb_content").append(html) 156 | }); 157 | } 158 | 159 | function get_host_html(data){ 160 | html = '
    '; 161 | return html 162 | } 163 | function get_template_html(data){ 164 | hostname = data.hostname; 165 | hostid = data.hostid; 166 | html = '
    '; 167 | html += '
      '; 168 | $.each( data.parentTemplates, function(num, obj){ 169 | html += '
    • '+obj.name; 170 | data = "template='"+obj.name+"' hostid='"+hostid+"' templateid='"+obj.templateid+"' hostname='"+hostname+"'"; 171 | html += '
    • '; 172 | }); 173 | html += '
    '; 174 | html += '
    '; 175 | return html 176 | } 177 | 178 | function get_templeate(){ 179 | $.getJSON("/listapi?method=zabbix_tem",function(data){ 180 | data = JSON.parse(data['result']); 181 | console.log(data); 182 | if(data['code'] == 0){ 183 | inster_zabbix_data(data['result']) 184 | 185 | }else 186 | { 187 | swal(data['errmsg']) 188 | } 189 | }) 190 | } 191 | 192 | get_templeate() 193 | 194 | $("#zb_content").on("click", ".unlink", function(){ 195 | click_obj = $(this); 196 | cli_hostid = click_obj.attr('hostid'); 197 | cli_templateid = click_obj.attr('templateid'); 198 | cli_template = click_obj.attr('template'); 199 | console.log(cli_hostid) 200 | swal({ 201 | title: "确定删除吗?", 202 | text: "将从 "+ cli_hostid +" 上取消关联 "+ cli_template +" 模板", 203 | type: "warning", 204 | showCancelButton: true, 205 | confirmButtonColor: "#DD6B55", 206 | cancelButtonText: "取消", 207 | confirmButtonText: "删除", 208 | closeOnConfirm: false }, 209 | function(){ 210 | $.post("/zabbix_template", {method:"unlink_tem",hostid: cli_hostid, templateid: cli_templateid} , function(data){ 211 | data=JSON.parse(data); //将json串转换为对象,然后取值 212 | data = JSON.parse(data['result']) //object 213 | console.log(data); 214 | if (data['code'] == 0){ 215 | swal("操作成功", "模板解绑成功", "success"); 216 | click_obj.parents('li').remove() 217 | }else{ 218 | swal("操作失败", data, "error"); 219 | } 220 | 221 | }); 222 | 223 | }); 224 | }) 225 | 226 | 227 | 228 | 229 | {% endblock %} 230 | -------------------------------------------------------------------------------- /devops/web/templates/testing.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block breadcrumb %} 4 |
  • 发布系统
  • 5 |
  • 测试发布
  • 6 | {% endblock %} 7 | 8 | {% block body %} 9 |
    10 |
    11 |
    测试发布
    12 |
    13 | 14 |
    15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
    项目名测试主机最新发布人最新发布时间最新commit操作
    30 | 31 |
    32 | 33 |
    34 | {% endblock %} 35 | 36 | {% block js %} 37 | 38 | {% endblock %} 39 | --------------------------------------------------------------------------------