def ping_module(hostip,port,username): ''' 通过ansible api 通过ping命令检测远程主机是否在线 :param hostip: :param port: :param username: :return: ''' host_data = [ { "hostname": "主机:%s"%hostip, # key值 "ip": hostip, "port": port, "username": username, }, ] inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) tasks = [{"action": {"module": "ping"}, "name": "ping"}] #获取执行结果: ret = runner.run(tasks) # 打印执行结果: print(ret.results_raw) if ret.results_raw["ok"]: return True else: return False
def initlog(hostlist, playbook): host_data = [{ "hostname": h.hostip, "ip": h.hostip, "port": h.ssh_port } for h in hostlist] print(host_data) inventory = Inventory(host_data) runner = PlayBookRunner(inventory).run(playbook) return runner
def change_command(request): """ var zNodes =[ { id:1, pId:0, name:"随意勾选 1", open:true}, { id:11, pId:1, name:"随意勾选 1-1"}, { id:12, pId:1, name:"随意勾选 1-2", open:true}, ]; pid 是父id open:true 是否展开 host_data = [ { "hostname": "10.211.55.19", "ip": "10.211.55.19", "port": 22, "username": "******", }, ] inventory = Inventory(host_data) #动态生成组 runner = CommandRunner(inventory) res = runner.execute('pwd') # print(res.results_command) print(res.results_raw,type(res.results_raw)) :param request: :param pk: :return: """ host_nodes = [{"id": 1, "pId": 0, "name": "主机列表", "open": "true"}] for h in Host.objects.all(): host_nodes.append({"id": 11, "pId": 1, "name": h.ip}) if request.method == 'POST': nodes = request.POST.getlist("nodes[]") hosts_list = Host.objects.filter(ip__in=nodes) host_data = [{ "hostname": h.ip, "ip": h.ip, "port": h.ssh } for h in hosts_list] inventory = Inventory(host_data) # 动态生成组 runner = CommandRunner(inventory) res = runner.execute(request.POST.get("command")) print(res.results_raw) Command.objects.create(command=request.POST.get("command"), user=request.account, hosts_list=nodes, result=res.results_raw) return JsonResponse({"status": 0, "msg": res.results_raw}) return TemplateResponse(request, 'create/command_create.html', { 'nodes': host_nodes, "page_title": "执行命令" })
def ansible_helper(host_list, task): ''' 远程执行任务 :param host_list: 主机对象 :param task: 具体任务 :return: ''' host_data = [{"hostname": h.name, "ip": h.hostip, "port": h.ssh_port, } for h in host_list] # 主机列表 inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) ret = runner.run(task) # ret.results_raw 返回结果(字典),如果有["ok"]这个key说明执行成功返回True,否则返回false return True if ret.results_raw["ok"] else False
def host_ping(hostip,ssh_port): host_data=[{ "hostname":hostip, "ip":hostip, "port":ssh_port }] inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) tasks=[{ "action":{"module":'ping'} }] ret = runner.run(tasks) if not ret.results_raw['ok']: return False return True
def TestPlayBookRunner(): """ 执行playbook :return: """ host_data = [ { "hostname": "10.211.55.19", "ip": "10.211.55.19", "port": 22, "username": "******", }, ] inventory = Inventory(host_data) runner = PlayBookRunner(inventory).run("/Users/derekwang/test") print(runner)
def change_cron(request, pk=0): cron = Cron.objects.filter(pk=pk).first() time = None if not pk else cron.time form_obj = CronForm(instance=cron) title = "编辑" if pk else "添加" if request.method == 'POST': time = request.POST.getlist("time") form_obj = CronForm(request.POST, instance=cron) if form_obj.is_valid(): host_data = [] form_obj.instance.create_user = request.account form_obj.instance.time = time for h in form_obj.cleaned_data["host_list"]: host_data.append({ "hostname": h.ip, "ip": h.ip, "port": h.ssh }) # 主机列表 print(host_data) inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) tasks = [{ "action": { "module": "cron", "args": f"minute={time[0]} hour={time[1]} day={time[2]} month={time[3]} weekday={time[4]}\ name={form_obj.cleaned_data['name']} job={form_obj.cleaned_data['job']} user={form_obj.cleaned_data['user']}" } }] ret = runner.run(tasks) if not ret.results_raw["ok"]: return JsonResponse({'status': 1, 'msg': '添加失败'}) form_obj.save() return JsonResponse({'status': 0, 'msg': f'{title}成功'}) else: return JsonResponse({ 'status': 1, 'msg': f'{title}失败,失败的原因是{form_obj.errors}' }) return TemplateResponse(request, 'create/cron_create.html', { 'form_obj': form_obj, "pk": pk, "page_title": f"{title}计划任务", "time": time })
def nginx(item, host, type=1): """ 摘nginx 重启nginx 挂载nginx :type 1摘nginx 0 挂载nginx :return: """ nginxhosts = item.team.nginxhost.all() tasks = [] if type == 1: replace_nginx = { "action": { "module": "replace", "args": 'path={} regexp="^({}.*)" replace="#\\1"'.format( item.team.nginxconf, host) }, "name": "down nginx" } else: replace_nginx = { "action": { "module": "replace", "args": 'path={} regexp="^#({}.*)" replace="\\1"'.format( item.team.nginxconf, host) }, "name": "down nginx" } restart_nginx = { "action": { "module": "service", "args": 'name=nginx state=reload' }, "name": "reload nginx" } tasks.append(replace_nginx) tasks.append(restart_nginx) host_data = [{ "hostname": ng.hostip, 'ip': ng.hostip, 'user': '******' } for ng in nginxhosts] inventory = Inventory(host_data) runner = AdHocRunner(inventory) runner.run(tasks)
def TestAdHocRunner(): """ 以yml的形式 执行多个命令 :return: """ host_data = [ { "hostname": "10.211.55.13", "ip": "10.211.55.13", "username": "******", }, ] inventory = Inventory(host_data) runner = AdHocRunner(inventory) # dest = "/opt/mysql/world.sh" tasks = [ { "action": { "module": "shell", "args": "whoami" }, "name": "run_whoami" }, { "action": { "module": "replace", "args": 'path=/tmp/a.txt regexp="^(192.168.1.1.*)" replace="#\\1"' }, "name": "down nginx" } # {"action": {"module": "shell", "args": "free -m | awk 'NR\=\=2{printf \"%.2f\", $3*100/$2 }'"}, "name": "get_mem_usage"}, # {"action": {"module": "shell", "args": "df -h | awk '$NF\=\=\"/\"{printf \"%s\", $5}'"}, "name": "get_disk_usage"}, # {"action": {"module": "copy", "args": "src=/home/python/Desktop/3358.cnf dest=/opt/mysql/my3358.cnf mode=0777"}, "name": "send_file"}, # {"action": {"module": "copy", "args": "src=/home/python/Desktop/deploy.sh dest=/opt/mysql/deploy.sh mode=0777"}, "name": "send_file"}, # {"action": {"module": "command", "args": "sh /opt/mysql/hello.sh"}, "name": "execute_file"}, # {"action": {"module": "shell", "args": "sudo sh /opt/mysql/deploy.sh"}, "name": "execute_file"}, # {"action": {"module": "lineinfile", "args": "dest=/opt/mysql/hello.sh line=hello1 regexp=echo state=present"}, "name": "modify_file"}, # {"action": {"module": "lineinfile", "args": "dest=/opt/mysql/world.sh line="" regexp=echo state=present"}, "name": "modify_file"}, # {"action": {"module": "lineinfile", "args": "dest=%s line=sun regexp=echo state=present" % dest}, "name": "modify_file"}, # {"action": {"module": "shell", "args": "lineinfile dest=/opt/mysql/hello.sh regexp=hello insertafter=#echo line=hello world"}, "name": "modify_file"}, # {"action": {"module": "shell", "args": "grep 'cpu ' /proc/stat | awk '{usage\=($2+$4)*100/($2+$4+$5)} END {print usage}'"}, "name": "get_cpu_usage"}, ] ret = runner.run(tasks) print(ret.results_summary) print(ret.results_raw)
def command(hostlist, com): ''' 根据主机和命令,执行 本方法使用ansible api中的CommandRunner方法 :param hostlist: 主机 :param com: 命令 :return: ''' host_data = [{ "hostname": h.hostip, "ip": h.hostip, "port": h.ssh_port } for h in hostlist] inventory = Inventory(host_data) # 重新组成虚拟组 runner = CommandRunner(inventory) res = runner.execute(com) #执行命令 return res.results_raw #返回结果
def cron_module(host_list,time=None,job=None,name=None,user=None,type=None): host_data=[{"hostname":h.name,"ip":h.hostip,"port":h.ssh_port}for h in host_list] inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) if type ==1: tasks=[{"action":{"module":"cron","args":"name={} state=absent".format(name)}}] else: tasks = [{"action": {"module": "cron", "args": "minute={} hour={} day={} month={} weekday={} name={} job={} user={}".format( time[0], time[1], time[2], time[3], time[4], name, job, user)}, "name": "cron"}] ret = runner.run(tasks) if ret.results_raw["ok"]: return True else: return False
def service(src_path, backup_path, path, host_list, type=1): """ 后端服务器操作 :param filepath 文件地址 :param path 项目目录 :param host: 对应的主机 :param type: 1更新 2回滚 :return: """ tasks = [] if type == 1: backup = { "action": { "module": "shell", "args": "cp -rf {} {}".format(path, backup_path) }, #硬连接不能实现 "name": "backup file" } task = { "action": { "module": "copy", "args": "dest={},src={}".format(path, src_path) }, "name": "copy file" } # 复制本地文件到远程 tasks.append(backup) else: task = { "action": { "module": "shell", "args": "cp -rf {} {}".format(backup_path, path) }, "name": "goback" } # 回滚 tasks.append(task) print([host.team.name for host in host_list]) host_data = [{ "hostname": host.host.hostip, 'ip': host.host.hostip, 'user': '******' } for host in host_list] print(host_data, tasks) inventory = Inventory(host_data) runner = AdHocRunner(inventory) runner.run(tasks)
def playbook(host_list, playbook_path): ''' 具体执行项目功能 返回结果 根据ansible api TestPlayBookRunner方法 接收host_list 和 playbook_path 参数 :param host_list: ProjectLog表 host_list 字段(多对多关联host表)。在直接获取主机表中相关字段,完成host_data(动态生成主机配置信息) :param playbook_path: 执行脚本路径 :return: 返回执行结果 ''' host_data = [{ "hostname": h.name, "ip": h.hostip, "port": h.ssh_port, "username": h.user, } for h in host_list] inventory = Inventory(host_data) #动态生成主机配置信息 runner = PlayBookRunner(inventory).run(playbook_path) #获取执行结果 return runner #返回结果
def TestCommandRunner(): """ 执行单个命令,返回结果 :return: """ host_data = [ { "hostname": "10.211.55.19", #key值 "ip": "10.211.55.19", "port": 22, "username": "******", }, ] inventory = Inventory(host_data) #重新组成虚拟组 runner = CommandRunner(inventory) res = runner.execute('pwd') # print(res.results_command) print(res.results_raw,type(res.results_raw))
def TestCommandRunner(): """ 执行单个命令,返回结果 :return: """ host_data = [ { "hostname": "192.168.220.133", "ip": "192.168.220.133", "port": 22, "username": "******", }, ] inventory = Inventory(host_data) # 动态生成主机列表,也就是组 runner = CommandRunner(inventory) res = runner.execute('pwd') # print(res.results_command) print(res.results_raw, type(res.results_raw))
def Remote_directory(host_list, backup_path, path): ''' 在远程主机上创建备份目录 和项目目录 :param backup_path: 备份目录 :param path: 项目目录 :return: ''' host_data = [{ "hostname": h.name, "ip": h.hostip, } for h in host_list] inventory = Inventory(host_data) # 重新组成虚拟组 runner = CommandRunner(inventory) #创建备份目录 creates 检测目录是否存在,存在则不执行后面的mkdir res = runner.execute('creates={} mkdir {} -p'.format( backup_path, backup_path)) #创建项目目录 ret = runner.execute('creates={} mkdir {} -p'.format(path, path)) return True if res.results_raw["ok"] and ret.results_raw["ok"] else False
def TestPlayBookRunner(): """ 执行playbook :return: """ host_data = [ { "hostname": "10.211.55.13", # "ip": "10.211.55.13", "port": 22, "username": "******", # "list_hosts":"all" # "private_key": "/home/python/.ssh/id_rsa_1", }, ] inventory = Inventory(host_data) opstions = {"playbook_path": "/Users/derekwang/test/a.yml"} runner = PlayBookRunner(inventory, options=opstions, playbook_path="/Users/derekwang/test/a.yml").run() print(runner)
def command_create(request): com_obj = CommandCreateForm() if request.method == "POST": com_obj = CommandCreateForm(request.POST) if com_obj.is_valid(): hosts=com_obj.cleaned_data['host'] host_data = [{"hostname": i,"ip": i,"port": 22,"username": "******"} for i in hosts.hostip] inventory = Inventory(host_data) runner = CommandRunner(inventory) res = runner.execute('pwd', 'all') print(res.results_command) print(res.results_raw) print(res.results_command['10.211.55.13']['stdout']) com_obj.save() return JsonResponse({'status': 0, 'msg': "操作成功!"}) else: return JsonResponse({'status': 1, 'msg': "操作失败!,{}".format(com_obj.errors)}) return render(request, 'command_create.html', {'form': com_obj})
def create_initlog(request): form = InitLogForm() if request.method == "POST": form = InitLogForm(request.POST) if form.is_valid(): form.instance.user = request.account host_data = [{ "hostname": h.ip, "ip": h.ip, 'port': h.ssh } for h in form.cleaned_data["hosts_list"]] inventory = Inventory(host_data) runner = PlayBookRunner(inventory).run( form.cleaned_data["init"].playbook) form.save() return JsonResponse({"status": 0, "msg": "添加成功"}) else: return JsonResponse({ "status": 1, "msg": "添加失败,失败的原因是{}".format(form.errors) }) return render(request, "create/initlog_create.html", {"form": form})
def TestCommandRunner(): """ 执行单个命令,返回结果 :return: """ host_data = [ { "hostname": "10.211.55.13", "ip": "10.211.55.13", "port": 22, "username": "******", # "private_key": "/home/python/.ssh/id_rsa_1", }, ] inventory = Inventory(host_data) runner = CommandRunner(inventory) res = runner.execute('pwd', 'all') print(res.results_command) print(res.results_raw) print(res.results_command['10.211.55.13']['stdout'])
def del_cron(request, pk): cron = Cron.objects.filter(pk=pk).first() host_data = [] for h in cron.host_list.all(): host_data.append({"hostname": h.ip, "ip": h.ip, "port": h.ssh}) # 主机列表 print(host_data) inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) tasks = [{ "action": { "module": 'cron', "args": "name={} user={} state=absent".format(cron.name, cron.user) } }] ret = runner.run(tasks) if not ret.results_raw["ok"]: return JsonResponse({'status': 1, 'msg': '删除失败'}) cron.delete() if cron: return JsonResponse({'status': 0, 'msg': '删除成功'}) else: return JsonResponse({'status': 1, 'msg': '删除失败'})
def change_host(request, pk=None): host = Host.objects.filter(pk=pk).first() form_obj = HostForm(instance=host) title = "编辑" if pk else "添加" if request.method == 'POST': form_obj = HostForm(request.POST, instance=host) if form_obj.is_valid(): # 校验form后 使用ansible检验机器是否在线 host_data = [ { "hostname": form_obj.cleaned_data["ip"], # 获取主机ip "ip": form_obj.cleaned_data["ip"], "port": form_obj.cleaned_data["ssh"], }, ] # 主机列表 inventory = Inventory(host_data) # 动态生成主机配置信息 runner = AdHocRunner(inventory) tasks = [{"action": {"module": "ping"}}] ret = runner.run(tasks) print(ret.results_summary) print(ret.results_raw) """ { 'contacted': ['192.168.220.134'], 'dark': {} } { 'ok': { '192.168.220.134': { 'ping': { 'invocation': { 'module_args': { 'data': 'pong' } }, 'ping': 'pong', '_ansible_parsed': True, '_ansible_no_log': False, 'changed': False } } }, 'failed': {}, 'unreachable': {}, 'skipped': {} } """ if not ret.results_raw["ok"]: return JsonResponse({ 'status': 1, 'msg': f'添加失败,失败的原因是主机不可达,请检查网络或ssh_key' }) form_obj.save() return JsonResponse({'status': 0, 'msg': f'{title}成功'}) else: return JsonResponse({ 'status': 1, 'msg': f'{title}失败,失败的原因是{form_obj.errors}' }) return render(request, 'create/host_create.html', { 'form_obj': form_obj, "pk": pk })