Example #1
0
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
Example #2
0
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
Example #3
0
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
Example #4
0
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)
Example #5
0
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)
Example #6
0
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
    })
Example #7
0
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
Example #8
0
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)
Example #9
0
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': '删除失败'})
Example #10
0
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
    })