×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Ansible scripting
2

Ansible scripting

Ansible scripting

(OP)
Anyone have any experience with Ansible and setting up scripts to patch gateways? Or change passwords on gateways and servers from the cli?

Kevin

RE: Ansible scripting

(OP)
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.

RE: Ansible scripting

(OP)
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) 

RE: Ansible scripting

Hi mcpheekp,

Unfortunately python code without indentation is not readable. To post your code with proper formatting, please place it between the tags
[code] 
... 
[/code] 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login


Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close