-
Notifications
You must be signed in to change notification settings - Fork 32
/
utils.py
69 lines (57 loc) · 2.73 KB
/
utils.py
1
2
3
4
5
6
7
8
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Copyright (C) 2015, Wazuh Inc.
# Created by Wazuh, Inc. <[email protected]>.
# This program is a free software; you can redistribute it and/or modify it under the terms of GPLv2
import paramiko
import re
import yaml
import logging
import time
from .logger.logger import logger
paramiko_logger = logging.getLogger("paramiko")
paramiko_logger.setLevel(logging.CRITICAL)
class Utils:
@staticmethod
def extract_ansible_host(file_path) -> str:
with open(file_path, 'r') as yaml_file:
inventory_data = yaml.safe_load(yaml_file)
return inventory_data.get('ansible_host')
@staticmethod
def check_inventory_connection(inventory_path, attempts=10, sleep=30) -> bool:
if 'manager' in inventory_path:
match = re.search(r'/manager-linux-([^-]+)-([^-]+)-', inventory_path)
elif 'agent' in inventory_path:
match = re.search(r'/agent-linux-([^-]+)-([^-]+)-', inventory_path)
if match:
os_name = match.group(1)+ '-' + match.group(2)
logger.info(f'Checking connection to {os_name}')
try:
with open(inventory_path, 'r') as file:
inventory_data = yaml.safe_load(file)
except FileNotFoundError:
raise FileNotFoundError(logger.error(f'File not found in {os_name}'))
except yaml.YAMLError:
raise ValueError(logger.error(f'Invalid inventory information in {os_name}'))
host = inventory_data.get('ansible_host')
port = inventory_data.get('ansible_port')
private_key_path = inventory_data.get('ansible_ssh_private_key_file')
username = inventory_data.get('ansible_user')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
for attempt in range(1, attempts + 1):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
try:
ssh.connect(hostname=host, port=port, username=username, pkey=private_key)
logger.info(f'Connection established successfully in {os_name}')
ssh.close()
return True
except paramiko.AuthenticationException:
logger.error(f'Authentication error. Check SSH credentials in {os_name}')
return False
except Exception as e:
logger.warning(f'Error on attempt {attempt} of {attempts}: {e}')
time.sleep(sleep)
logger.error(f'Connection attempts failed after {attempts} tries. Connection timeout in {os_name}')
return False