def retag_image_release(repo_name, tag): harbor_domain = get_dir("harbor_domain") username = get_dir("harbor_username") password = get_dir("harbor_password") tags_url = "%s/api/repositories/%s/tags" % (harbor_domain, repo_name) headers = { "Accept": "application/json", "Content-Type": "application/json" } if tag.split('.')[-1] == "Release": body = json.dumps({ "tag": tag, "src_image": "%s:%s" % (repo_name, tag), "override": False }) else: body = json.dumps({ "tag": tag.replace('Test', 'Release'), "src_image": "%s:%s" % (repo_name, tag), "override": False }) response = requests.post(tags_url, data=body, auth=(username, password), headers=headers) if response.status_code == 200: result = True else: result = False return result
def dingding_token(): corpid = get_dir("dingding_corpid") corpsecret = get_dir("dingding_corpsecret") url = 'https://oapi.dingtalk.com/gettoken?corpid=%s&corpsecret=%s' page = urllib.urlopen(url % (corpid, corpsecret)) str = page.read() dict = json.loads(str) token = dict["access_token"] return token
def fetch_repos_id(proj_name): harbor_domain = get_dir("harbor_domain") username = get_dir("harbor_username") password = get_dir("harbor_password") proj_url = "%s/api/projects" % harbor_domain proj_info = requests.get(proj_url, auth=(username, password)).json() for info in proj_info: if info["name"] == proj_name: return info["project_id"]
def collect(request): asset_info = json.loads(request.body) if request.method == 'POST': vendor = asset_info['vendor'] # group = asset_info['group'] disk = asset_info['disk'] cpu_model = asset_info['cpu_model'] cpu_num = asset_info['cpu_num'] memory = asset_info['memory'] sn = asset_info['sn'] osver = asset_info['osver'] hostname = asset_info['hostname'] ip = asset_info['ip'] if not ip or not hostname: return HttpResponse( "Error your agent ip or hostname is empty! Please resolve your hostname." ) # asset_type = "" # status = "" try: host = Host.objects.get(hostname=hostname) except Exception as msg: print(msg) host = Host() level = get_dir("log_level") ssh_pwd = get_dir("ssh_pwd") log_path = get_dir("log_path") log("cmdb.log", level, log_path) logging.info("==========sshkey deploy start==========") data = deploy_key(ip, ssh_pwd) logging.info(data) logging.info("==========sshkey deploy end==========") # if req.POST.get('identity'): # identity = req.POST.get('identity') # try: # host = Host.objects.get(identity=identity) # except: # host = Host() host.hostname = hostname # host.group = group host.cpu_num = int(cpu_num) host.cpu_model = cpu_model host.memory = int(memory) host.sn = sn host.disk = disk host.os = osver host.vendor = vendor host.ip = ip # host.asset_type = asset_type # host.status = status host.save() return HttpResponse("Post asset data to server successfully!") else: return HttpResponse("No any post data!")
def connect_db(cls): mongodb_ip = get_dir("mongodb_ip") mongodb_port = get_dir("mongodb_port") mongodb_user = get_dir("mongodb_user") mongodb_pwd = get_dir("mongodb_pwd") if mongodb_user: uri = 'mongodb://'+mongodb_user+':'+mongodb_pwd+'@'+mongodb_ip+':'+mongodb_port+'/'+cls.db client = MongoClient(uri) else: client = MongoClient(mongodb_ip, int(mongodb_port)) return client
class GetRedis(object): host = get_dir("redis_host") port = get_dir("redis_port") db = get_dir("redis_db") password = get_dir("redis_password") @classmethod def connect(cls): conn = redis.StrictRedis(host=cls.host, port=cls.port, password=cls.password, db=cls.db) return conn
def connect_db(cls): mongodb_ip = get_dir("mongodb_ip") mongodb_port = get_dir("mongodb_port") mongodb_user = get_dir("mongodb_user") mongodb_pwd = get_dir("mongodb_pwd") if mongodb_user: uri = 'mongodb://'+mongodb_user+':'+mongodb_pwd+'@'+mongodb_ip+':'+mongodb_port+'/'+cls.collection client = MongoClient(uri) else: client = MongoClient(mongodb_ip, int(mongodb_port)) return client
def check_image_tag(repo_name, tag): harbor_domain = get_dir("harbor_domain") username = get_dir("harbor_username") password = get_dir("harbor_password") tags_url = "%s/api/repositories/%s/tags/%s" % (harbor_domain, repo_name, tag) response = requests.get(tags_url, auth=(username, password)) if response.status_code == 200: result = True else: result = False return result
def collect(request): asset_info = json.loads(request.body) if request.method == 'POST': vendor = asset_info['vendor'] # group = asset_info['group'] disk = asset_info['disk'] cpu_model = asset_info['cpu_model'] cpu_num = asset_info['cpu_num'] memory = asset_info['memory'] sn = asset_info['sn'] osver = asset_info['osver'] hostname = asset_info['hostname'] ip = asset_info['ip'] if not ip or not hostname: return HttpResponse("Error your agent ip or hostname is empty! Please resolve your hostname.") # asset_type = "" # status = "" try: host = Host.objects.get(hostname=hostname) except Exception as msg: print(msg) host = Host() level = get_dir("log_level") ssh_pwd = get_dir("ssh_pwd") log_path = get_dir("log_path") log("cmdb.log", level, log_path) logging.info("==========sshkey deploy start==========") data = deploy_key(ip, ssh_pwd) logging.info(data) logging.info("==========sshkey deploy end==========") # if req.POST.get('identity'): # identity = req.POST.get('identity') # try: # host = Host.objects.get(identity=identity) # except: # host = Host() host.hostname = hostname # host.group = group host.cpu_num = int(cpu_num) host.cpu_model = cpu_model host.memory = int(memory) host.sn = sn host.disk = disk host.os = osver host.vendor = vendor host.ip = ip # host.asset_type = asset_type # host.status = status host.save() return HttpResponse("Post asset data to server successfully!") else: return HttpResponse("No any post data!")
def received_sys_info(request): if request.method == 'POST': mongodb_ip = get_dir("mongodb_ip") mongodb_port = get_dir("mongodb_port") received_json_data = json.loads(request.body) hostname = received_json_data["hostname"] received_json_data['timestamp'] = int(time.time()) client = MongoClient(mongodb_ip, int(mongodb_port)) db = client.sys_info collection = db[hostname] collection.insert_one(received_json_data) return HttpResponse("Post the system Monitor Data successfully!") else: return HttpResponse("Your push have errors, Please Check your data!")
def get_conn(): host = get_dir("cmdb_host") port = int(get_dir("cmdb_port")) username = get_dir("cmdb_user") password = get_dir("cmdb_password") database = get_dir("cmdb_database") conn = MySQLdb.connect(host=host, port=port, user=username, passwd=password, db=database, charset='utf8') return conn
def launch_task(cookie, project_id, template_id, project_name, version): semaphore_domain = get_dir("semaphore_domain") api_url = "%s/api" % semaphore_domain task_url = "%s/project/%s/tasks" % (api_url, project_id) name_ = "%s_version" % project_name.replace("-", "_") env_conf = get_environment_conf(cookie, project_id, template_id) env_conf[name_] = version env = json.dumps(env_conf) logger.info("project: %s, version: %s, env: %s", project_name, version, env) task_content = { "template_id": template_id, "debug": False, "dry_run": False, "playbook": "", "environment": env } cookie_handler = urllib2.HTTPCookieProcessor(cookie) url_opener = urllib2.build_opener(cookie_handler) urllib2.install_opener(url_opener) body = json.dumps(task_content) headers = { "Accept": "application/json", "Content-Type": "application/json" } request = urllib2.Request(task_url, data=body, headers=headers) response = urllib2.urlopen(request) ret = json.loads(response.read()) return ret["id"]
def asset(request): temp_name = "cmdb/cmdb-header.html" webssh_domain = get_dir("webssh_domain") asset_find = [] idc_info = Idc.objects.all() host_list = Host.objects.all() group_info = HostGroup.objects.all() asset_types = ASSET_TYPE asset_status = ASSET_STATUS idc_name = request.GET.get('idc', '') # print ("idc_name,",idc_name) group_name = request.GET.get('group', '') asset_type = request.GET.get('asset_type', '') status = request.GET.get('status', '') keyword = request.GET.get('keyword', '') export = request.GET.get("export", '') group_id = request.GET.get("group_id", '') cabinet_id = request.GET.get("cabinet_id", '') idc_id = request.GET.get("idc_id", '') asset_id_all = request.GET.getlist("id", '') if group_id: group = get_object(HostGroup, id=group_id) if group: asset_find = Host.objects.filter(group=group) if cabinet_id: cabinet = get_object(Cabinet, id=cabinet_id) if cabinet: asset_find = Host.objects.filter(cabinet=cabinet) elif idc_id: idc = get_object(Idc, id=idc_id) if idc: asset_find = Host.objects.filter(idc=idc) else: asset_find = Host.objects.all() if idc_name: asset_find = asset_find.filter(idc__name__contains=idc_name) if group_name: get_group = HostGroup.objects.get(name=group_name) asset_find = get_group.serverList.all() if asset_type: asset_find = asset_find.filter(asset_type__contains=asset_type) if status: asset_find = asset_find.filter(status__contains=status) if keyword: asset_find = asset_find.filter( Q(hostname__contains=keyword) | Q(ip__contains=keyword) | Q(other_ip__contains=keyword) | Q(os__contains=keyword) | Q(vendor__contains=keyword) | Q(cpu_model__contains=keyword) | Q(cpu_num__contains=keyword) | Q(memory__contains=keyword) | Q(disk__contains=keyword) | Q(sn__contains=keyword) | Q(position__contains=keyword) | Q(memo__contains=keyword)) if export: response = create_asset_excel(export, asset_id_all) return response assets_list, p, assets, page_range, current_page, show_first, show_end, end_page = pages( asset_find, request) return render(request, 'cmdb/index.html', locals())
def dbscript_download(request, dbscript_id): status = 0 try: if request.user.is_superuser or request.user.is_staff: dbscript = DBScript.objects.get(id=dbscript_id) else: dbscript = DBScript.objects.get( Q(id=dbscript_id) & Q(order_user=request.user.username)) except: return HttpResponseRedirect(reverse('permission_deny')) script_path = os.path.join(get_dir("script_path"), dbscript.db_name.name, dbscript.env) archive_path = os.path.join(script_path, "archive") archive_file = str(dbscript.id) + "_" + dbscript.script_name if dbscript.status == 1: file = os.path.join(archive_path, archive_file) elif dbscript.status == 0: file = os.path.join(script_path, dbscript.script_name) if os.path.exists(file): destination = open(file, 'rb') response = FileResponse(destination) response["Content-Type"] = "application/octet-stream" response[ "Content-Disposition"] = 'attachment;filename="%s"' % dbscript.script_name.encode( 'utf8') status = 1 return response else: status = 2 return HttpResponseRedirect(reverse('dbscript_list'))
def dbscript_finish(request, dbscript_id): if dbscript_id: DBScript.objects.filter(id=dbscript_id).update( status=1, update_time=datetime.datetime.now(), completion_time=datetime.datetime.now()) dbscript = DBScript.objects.get(id=dbscript_id) script_path = os.path.join(get_dir("script_path"), dbscript.db_name.name, dbscript.env) archive_path = os.path.join(script_path, "archive") archive_file = str(dbscript.id) + "_" + dbscript.script_name if not os.path.exists(archive_path): os.makedirs(archive_path) srcfile = os.path.join(script_path, dbscript.script_name) dstfile = os.path.join(archive_path, archive_file) if os.path.exists(srcfile): shutil.move(srcfile, dstfile) db_name = DBScript.objects.filter( id=dbscript_id).values("db_name__name").first() msg_user = AppOwner.objects.filter( username__username=dbscript.order_user).values("dingding").first() if msg_user is not None and db_name is not None and dbscript.script_name is not None: if msg_user["dingding"] is not None: dingding_msg.delay(msg_user["dingding"], \ u"您的工单(编号:%s)已处理,环境:%s,数据库名:%s,脚本:%s" \ % (dbscript_id, dbscript.env, db_name["db_name__name"], dbscript.script_name)) return HttpResponseRedirect(reverse('dbscript_list'))
class GetSysData(object): collection = get_dir("mongodb_collection") def __init__(self, hostname, monitor_item, timing, no=0): self.hostname = hostname self.monitor_item = monitor_item self.timing = timing self.no = no @classmethod def connect_db(cls): mongodb_ip = get_dir("mongodb_ip") mongodb_port = get_dir("mongodb_port") mongodb_user = get_dir("mongodb_user") mongodb_pwd = get_dir("mongodb_pwd") if mongodb_user: uri = 'mongodb://'+mongodb_user+':'+mongodb_pwd+'@'+mongodb_ip+':'+mongodb_port+'/'+cls.collection client = MongoClient(uri) else: client = MongoClient(mongodb_ip, int(mongodb_port)) return client def get_data(self): client = self.connect_db() db = client[self.collection] collection = db[self.hostname] now_time = int(time.time()) find_time = now_time-self.timing cursor = collection.find({'timestamp': {'$gte': find_time}}, {self.monitor_item: 1, "timestamp": 1}).limit(self.no) return cursor
def dbscript_del(request): dbscript_id = request.GET.get('id', '') if dbscript_id: try: if request.user.is_superuser or request.user.is_staff: dbscript = DBScript.objects.get(id=dbscript_id) DBScript.objects.filter(id=dbscript_id).delete() else: dbscript = DBScript.objects.get( Q(id=dbscript_id) & Q(order_user=request.user.username)) DBScript.objects.filter( Q(id=dbscript_id) & Q(order_user=request.user.username)).delete() except: return HttpResponseRedirect(reverse('permission_deny')) script_path = os.path.join(get_dir("script_path"), dbscript.db_name.name, dbscript.env) file = os.path.join(script_path, dbscript.script_name) if os.path.exists(file): os.remove(file) dbscript_id_all = str(request.POST.get('dbscript_id_all', '')) if dbscript_id_all: for dbscript_id in dbscript_id_all.split(','): try: if request.user.is_superuser or request.user.is_staff: dbscript = DBScript.objects.get(id=dbscript_id) else: dbscript = DBScript.objects.get( Q(id=dbscript_id) & Q(order_user=request.user.username)) except: return HttpResponseRedirect(reverse('permission_deny')) script_path = os.path.join(get_dir("script_path"), dbscript.db_name.name, dbscript.env) if dbscript.status == 0: DBScript.objects.filter(id=dbscript_id).delete() file = os.path.join(script_path, dbscript.script_name) if os.path.exists(file): os.remove(file) return HttpResponseRedirect(reverse('dbscript_list'))
def dbscript_add(request): status = 0 if request.method == 'POST': dbscript_file = request.FILES.get("dbscript_file", None) env_list = request.POST.getlist('checkbox_env') if env_list: for env in env_list: form = DBScriptForm(request.POST) if form.is_valid() and dbscript_file: db_name = form.cleaned_data["db_name"].name script_path = os.path.join(get_dir("script_path"), db_name, env) if not os.path.exists(script_path): os.makedirs(script_path) file = os.path.join(script_path, dbscript_file.name) if not os.path.exists(file): destination = open(file, 'wb+') for chunk in dbscript_file.chunks(): destination.write(chunk) destination.close() db_form = form.save(commit=False) db_form.script_name = dbscript_file.name db_form.order_user = request.user.username db_form.env = env db_form.save() dbscript_id = db_form.id msg_user = Database.objects.filter( name=db_name).values("ops__dingding").first() if db_name is not None and msg_user is not None: if msg_user["ops__dingding"] is not None: dingding_msg.delay(msg_user["ops__dingding"], \ u"您有数据库更新(编号:%s)需要处理,环境:%s,数据库名:%s,脚本:%s" \ % (dbscript_id, env, db_name, dbscript_file.name)) status = 1 else: status = 3 break else: status = 2 break if status == 1: return HttpResponseRedirect(reverse('dbscript_list')) else: form = DBScriptForm(request.POST) status = 4 else: form = DBScriptForm() results = { 'form': form, 'status': status, 'request': request, } return render(request, 'orders/dbscript_base.html', results)
def asset(request): temp_name = "cmdb/cmdb-header.html" webssh_domain = get_dir("webssh_domain") asset_find = [] idc_info = Idc.objects.all() host_list = Host.objects.all() group_info = HostGroup.objects.all() asset_types = ASSET_TYPE asset_status = ASSET_STATUS idc_name = request.GET.get('idc', '') group_name = request.GET.get('group', '') asset_type = request.GET.get('asset_type', '') status = request.GET.get('status', '') keyword = request.GET.get('keyword', '') export = request.GET.get("export", '') group_id = request.GET.get("group_id", '') idc_id = request.GET.get("idc_id", '') asset_id_all = request.GET.getlist("id", '') if group_id: group = get_object(HostGroup, id=group_id) if group: asset_find = Host.objects.filter(group=group) elif idc_id: idc = get_object(Idc, id=idc_id) if idc: asset_find = Host.objects.filter(idc=idc) else: asset_find = Host.objects.all() if idc_name: asset_find = asset_find.filter(idc__name__contains=idc_name) if group_name: asset_find = asset_find.filter(group__name__contains=group_name) if asset_type: asset_find = asset_find.filter(asset_type__contains=asset_type) if status: asset_find = asset_find.filter(status__contains=status) if keyword: asset_find = asset_find.filter( Q(hostname__contains=keyword) | Q(ip__contains=keyword) | Q(other_ip__contains=keyword) | Q(os__contains=keyword) | Q(vendor__contains=keyword) | Q(cpu_model__contains=keyword) | Q(cpu_num__contains=keyword) | Q(memory__contains=keyword) | Q(disk__contains=keyword) | Q(sn__contains=keyword) | Q(position__contains=keyword) | Q(memo__contains=keyword)) if export: response = create_asset_excel(export, asset_id_all) return response assets_list, p, assets, page_range, current_page, show_first, show_end = pages(asset_find, request) return render(request, 'cmdb/index.html', locals())
def dbscript_add_mini(request): status = 0 dbscript_id = 0 if request.method == 'POST': form = DBScriptForm(request.POST) dbscript_file = request.FILES.get("dbscript_file", None) env = "Pro" if form.is_valid() and dbscript_file: db_name = form.cleaned_data["db_name"].name script_path = os.path.join(get_dir("script_path"), db_name, env) if not os.path.exists(script_path): os.makedirs(script_path) file = os.path.join(script_path, dbscript_file.name) if not os.path.exists(file): destination = open(file, 'wb+') for chunk in dbscript_file.chunks(): destination.write(chunk) destination.close() db_form = form.save(commit=False) db_form.script_name = dbscript_file.name db_form.order_user = request.user.username db_form.env = env db_form.save() dbscript_id = db_form.id msg_user = Database.objects.filter( name=db_name).values("ops__dingding").first() if db_name is not None and msg_user is not None: if msg_user["ops__dingding"] is not None: dingding_msg.delay(msg_user["ops__dingding"], \ u"您有数据库更新(编号:%s)需要处理,环境:%s,数据库名:%s,脚本:%s" \ % (dbscript_id, env, db_name, dbscript_file.name)) status = 1 dbscript_id = DBScript.objects.get( Q(db_name__name=db_name) & Q(script_name=dbscript_file.name) & Q(status=0)).id else: status = 3 else: status = 2 else: form = DBScriptForm() results = { 'form': form, 'request': request, 'status': status, 'dbscript_id': dbscript_id, } return render(request, 'orders/dbscript_add_mini.html', results)
def database_add(request): if request.method == 'POST': form = DatabaseForm(request.POST) if form.is_valid(): db_name = form.cleaned_data["name"] pro_script_path = os.path.join(get_dir("script_path"), db_name, "Pro") pre_script_path = os.path.join(get_dir("script_path"), db_name, "Pre") if not os.path.exists(pro_script_path): os.makedirs(pro_script_path) if not os.path.exists(pre_script_path): os.makedirs(pre_script_path) form.save() return HttpResponseRedirect(reverse('database_list')) else: form = DatabaseForm() results = { 'form': form, 'request': request, } return render(request, 'appconf/database_base.html', results)
def fetch_latest_tag(proj_name): latest_tag_dict = {} harbor_domain = get_dir("harbor_domain") username = get_dir("harbor_username") password = get_dir("harbor_password") repos_url = "%s/api/repositories" % harbor_domain repos_id = fetch_repos_id(proj_name) all_repos = requests.get(repos_url, auth=(username, password), params={ "project_id": repos_id }).json() for repo in all_repos: tag_url = "%s/%s/tags" % (repos_url, repo["name"]) all_tags = requests.get(tag_url, auth=(username, password)).json() tags_sort = sorted(all_tags, key=lambda a: a["created"]) for tag in tags_sort[::-1]: if '.Test' in tag["name"] or '.Release' in tag["name"]: tags_sort.remove(tag) latest_tag = tags_sort[-1] latest_tag_dict[repo["name"]] = latest_tag["name"] return latest_tag_dict
def semaphore_cookie(): semaphore_domain = get_dir("semaphore_domain") api_url = "%s/api" % semaphore_domain login_url = "%s/auth/login" % api_url login_content = { "auth": get_dir("semaphore_username"), "password": get_dir("semaphore_password") } cookie_jar = cookielib.CookieJar() cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar) url_opener = urllib2.build_opener(cookie_handler) urllib2.install_opener(url_opener) jdata = json.dumps(login_content) headers = { "Content-Type": "application/json", "Accept": "application/json" } request = urllib2.Request(login_url, data=jdata, headers=headers) response = urllib2.urlopen(request) return cookie_jar
def __init__(self): self.port = get_dir("ldap_port") self.server = get_dir("ldap_server") self.manager = get_dir("ldap_manager") self.passwd = get_dir("ldap_password") self.base = get_dir("base_dn") self.type = get_dir("ldap_filter") if self.port: self.server = self.server + ":" + self.port
def _wrapped_view(request, *args, **kwargs): set_token = get_dir('token') error_info = 'Post forbidden, your token is error!' if request.method == 'POST': post_token = json.loads(request.body) if set_token == post_token['token']: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) if request.GET: post_token = request.GET['token'] if set_token == post_token: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403)
def get_task_status(cookie, project_id, task_id): semaphore_domain = get_dir("semaphore_domain") api_url = "%s/api" % semaphore_domain task_url = "%s/project/%s/tasks" % (api_url, project_id) output_url = "%s/%s" % (task_url, task_id) cookie_handler = urllib2.HTTPCookieProcessor(cookie) url_opener = urllib2.build_opener(cookie_handler) urllib2.install_opener(url_opener) headers = {"Accept": "application/json"} request = urllib2.Request(output_url, headers=headers) response = urllib2.urlopen(request) ret = json.loads(response.read()) return ret["status"]
def _wrapped_view(request, *args, **kwargs): set_token = get_dir('token') error_info = "Post forbidden, your token error!!" if request.method == 'POST': post_token = json.loads(request.body) if set_token == post_token["token"]: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) if request.GET: post_token = request.GET['token'] if set_token == post_token: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) return HttpResponse(error_info, status=403)
def _wrapped_view(request, *args, **kwargs): iToken = get_dir('token') error_info = "Post forbidden, your token error!!" if request.method == 'POST': # pToken = request.POST.get('token') pToken = json.loads(request.body) if iToken == pToken["token"]: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) if request.GET: pToken = request.GET['token'] if iToken == pToken: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) return HttpResponse(error_info, status=403)
def _wrapped_view(request, *args, **kwargs): iToken = get_dir('token') if request.POST: pToken = request.POST.get('token') if iToken == pToken: return view_func(request, *args, **kwargs) else: message = "forbidden your token error!!" print message return HttpResponse(status=403) if request.GET: pToken = request.GET['token'] if iToken == pToken: return view_func(request, *args, **kwargs) else: message = "forbidden your token error!!" print message return HttpResponse(status=403) return HttpResponse(status=403)
def _wrapped_view(request, *args, **kwargs): # 从配置文件中获取 自定义token值 set_token = get_dir('token') error_info = "Post forbidden, your token error!!" if request.method == 'POST': post_token = json.loads(request.body) print post_token if set_token == post_token["token"]: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) if request.GET: post_token = request.GET['token'] print post_token if set_token == post_token: return view_func(request, *args, **kwargs) else: return HttpResponse(error_info, status=403) return HttpResponse(error_info, status=403)
#! /usr/bin/env python # -*- coding: utf-8 -*- from cmdb.models import Host, HostGroup from django.shortcuts import render from subprocess import Popen, PIPE import sh from config.views import get_dir from django.contrib.auth.decorators import login_required from accounts.permission import permission_verify from lib.log import log from lib.setup import get_scripts import logging scripts_dir = get_dir("s_path") level = get_dir("log_level") log_path = get_dir("log_path") log("setup.log", level, log_path) @login_required() @permission_verify() def index(request): temp_name = "setup/setup-header.html" all_host = Host.objects.all() all_group = HostGroup.objects.all() all_scripts = get_scripts(scripts_dir) return render(request, 'setup/shell.html', locals()) @login_required() @permission_verify() def exec_scripts(request):
#! /usr/bin/env python # -*- coding: utf-8 -*- from assets.models import Asset, HostGroup, NIC from django.shortcuts import render, HttpResponse from subprocess import Popen, PIPE import os import shutil from config.views import get_dir from django.contrib.auth.decorators import login_required from lib.log import log from lib.setup import get_files import logging from accounts.permission import permission_verify uploadfile_dir = get_dir("f_path") level = get_dir("log_level") log_path = get_dir("log_path") log("setup.log", level, log_path) @login_required() @permission_verify() def index(request): return render(request, 'setup/fileupload.html', locals()) @login_required() @permission_verify() def fileupload_result(request): if request.method == "POST": # 请求方法为POST时,进行处理 myFiles = request.FILES.getlist("myfile",
# -*- coding: utf-8 -*- from subprocess import Popen, PIPE from cmdb.models import Host, HostGroup from django.shortcuts import render from django.http import HttpResponse import os from config.views import get_dir from django.contrib.auth.decorators import login_required from accounts.permission import permission_verify import logging from lib.log import log from lib.setup import get_playbook, get_roles # var info ansible_dir = get_dir("a_path") roles_dir = get_dir("r_path") playbook_dir = get_dir("p_path") level = get_dir("log_level") log_path = get_dir("log_path") log("setup.log", level, log_path) def write_role_vars(roles, vargs): r_vars = vargs.split('\r\n') for r in roles: if vargs: if os.path.exists(roles_dir + r + "/vars"): pass
# -*- coding: utf-8 -*- from subprocess import Popen, PIPE from cmdb.models import Host, HostGroup from django.shortcuts import render from django.http import HttpResponse import os from config.views import get_dir from django.contrib.auth.decorators import login_required from accounts.permission import permission_verify import logging from lib.log import log from lib.setup import get_playbook, get_roles # var info ansible_dir = get_dir("a_path") roles_dir = get_dir("r_path") playbook_dir = get_dir("p_path") level = get_dir("log_level") log_path = get_dir("log_path") log("setup.log", level, log_path) def write_role_vars(roles, vargs): r_vars = vargs.split('\r\n') for r in roles: if vargs: if os.path.exists(roles_dir+r+"/vars"): pass
#! /usr/bin/env python # -*- coding: utf-8 -*- from assets.models import Asset, HostGroup, NIC from django.shortcuts import render from subprocess import Popen, PIPE import sh from config.views import get_dir from django.contrib.auth.decorators import login_required from lib.log import log from lib.setup import get_scripts import logging from accounts.permission import permission_verify from setup.models import TaskRecord import datetime scripts_dir = get_dir("s_path") level = get_dir("log_level") log_path = get_dir("log_path") log("setup.log", level, log_path) @login_required() @permission_verify() def index(request): all_host = Asset.objects.all() all_group = HostGroup.objects.all() all_scripts = get_scripts(scripts_dir) return render(request, 'setup/shell.html', locals()) @login_required()
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from celery import shared_task from subprocess import Popen, PIPE from cmdb.models import Host import sh from config.views import get_dir scripts_dir = get_dir("s_path") @shared_task def command(host, name): h = Host.objects.get(hostname=host) cmd = sh.ssh("root@"+h.ip, " "+name) data = str(cmd) return data @shared_task def script(host, name): h = Host.objects.get(hostname=host) sh.scp(scripts_dir+name, "root@"+h.ip+":/tmp/"+name) cmd = "ssh root@"+h.ip+" "+'"sh /tmp/{}"'.format(name) p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) data = p.communicate() return data