Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Ansible scripting 2

Status
Not open for further replies.

mcpheekp

IS-IT--Management
Nov 27, 2013
6
US
Anyone have any experience with Ansible and setting up scripts to patch gateways? Or change passwords on gateways and servers from the cli?

Kevin
 
I have figured out the Gateway patching and Password change Ansible YML.
You need to create inventory files to load into Tower for these to work.

There are two YML's, one for patching, and one for passwords. and one Python file for SSH commands to run in the gateways. You must use Python3 and Parimeko version to match.

Only allowed one attachment per post, so look for the follow on posts.
 
 https://files.engineering.com/getfile.aspx?folder=97af5065-a16e-4c9b-9999-b9ecac12af4b&file=ssh_cmd.py
ssh_cmd python script.
Code:
import platform
import sys
import logging
import os
import paramiko
import argparse
import json
import time

#########Logging configuration##########
here = os.path.abspath(os.path.dirname(__file__))
if platform.platform().startswith('Windows'):
    logging_file = os.path.join(here, os.path.splitext(
        os.path.basename(__file__))[0]+'.log')
else:
    logging_file = os.path.join(here, os.path.splitext(
        os.path.basename(__file__))[0]+'.log')

log_formatter = logging.Formatter(
    '%(asctime)s : %(levelname)s : %(threadName)-9s : %(message)s')
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.DEBUG)

fileHandler = logging.FileHandler(logging_file)
fileHandler.setFormatter(log_formatter)
fileHandler.setLevel(logging.DEBUG)
LOG.addHandler(fileHandler)

consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(log_formatter)
consoleHandler.setLevel(logging.DEBUG)
LOG.addHandler(consoleHandler)
#########Logging configuration ends##########
__version__ = "1.0"


def jsondata_parser(json_file):
    with open(json_file) as fd:
        if json_file.endswith(".json"):
            try:
                json_data = json.load(fd)
                return json_data
            except:
                LOG.exception("Parsing config file: {}".format(json_file))
                return None
    return None


class SSH:
    """
    simplifies ssh to ssh server
    """

    def __init__(self, ip, username, pwd, port=22):
        self.ip = ip
        self.user = username
        self.pwd = pwd
        self.port = port
        self.ssh_client = None
        self.terminal = None

    def connect(self):
        LOG.debug("Trying to connect {} as {}".format(self.ip, self.user))
        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(self.ip, self.port, self.user, self.pwd)
            LOG.debug("Connected to {}".format(self.ip))
            self.ssh_client = ssh_client

            remote = self.ssh_client.invoke_shell()
            self.terminal = remote
        except paramiko.ssh_exception.AuthenticationException:
            LOG.exception(
                "Authentication failed when connecting to {}".format(self.ip))
            exit(1)
        except Exception as e:
            LOG.exception(
                "Could not SSH to {}, reason: {}".format(self.ip, str(e)))

    def execute_command(self, cmd):
        if self.ssh_client:
            LOG.debug("executing cmd: {}".format(cmd))
            try:
                while not self.terminal.send_ready():
                    time.sleep(1)
                self.terminal.send(cmd)

                while not self.terminal.recv_ready():
                    time.sleep(1)

                output = self.terminal.recv(9999)
                LOG.debug("command output: \n{}".format(output))
            except paramiko.ssh_exception.SSHException:
                LOG.exception("Failed to run command")

            return output

    def close_ssh(self):
        LOG.debug("Closing SSH connection")
        if self.ssh_client:
            self.ssh_client.close()


def perform_ssh(ssh_list):
    for target in ssh_list["SSH Servers"]:
        if target["ignore"] == "True":
            continue
        client = SSH(target["host"], target["user"], target["password"])
        client.connect()
        for command in target['commands']:
            client.execute_command(command)
        client.close_ssh()


def main(arg):
    if not os.path.exists(arg.conf):
        logging.error("{} doesn't exist".format(arg.conf))
        return

    config_data = jsondata_parser(arg.conf)

    if not config_data:
        logging.error(
            "No configuration found in json: (). Exiting.".format(arg.conf))
        return

    perform_ssh(config_data)


if __name__ == "__main__":
    """
        Execution starts here.
    """

    parser = argparse.ArgumentParser(description='Run commands over SSH')
    parser.add_argument('-c', '--conf', help='config', type=str, required=True)
    args = parser.parse_args()

    main(args)
 
Hi mcpheekp,

Unfortunately python code without indentation is not readable. To post your code with proper formatting, please place it between the tags
[pre]
Code:
[/pre]
[pre]...[/pre]
[pre]
[/pre]
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top