Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

collect sheduled show tech #15

Closed
ksator opened this issue Apr 21, 2022 · 2 comments
Closed

collect sheduled show tech #15

ksator opened this issue Apr 21, 2022 · 2 comments
Assignees

Comments

@ksator
Copy link
Collaborator

ksator commented Apr 21, 2022

#!/usr/bin/env python3

## This script collects all the tech-support files stored on Arista switches flash and copies them locally

import ssl
import paramiko
from jsonrpclib import Server
from scp import SCPClient
from time import strftime, gmtime
from argparse import ArgumentParser
from getpass import getpass
import os
from sys import exit
from socket import setdefaulttimeout

port = 22
ssl._create_default_https_context = ssl._create_unverified_context
date = strftime("%d %b %Y %H:%M:%S", gmtime())

def device_directories (device, root_dir):
    cwd = os.getcwd()
    show_tech_directory = cwd + '/' + root_dir
    device_directory = show_tech_directory + '/' + device
    for directory in [show_tech_directory, device_directory]:
        if not os.path.exists(directory):
            os.makedirs(directory)
    result = show_tech_directory, device_directory
    return result

def createSSHClient (device, port, username, password):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(device, port, username, password)
    return client

def main():
    parser = ArgumentParser(
        description='Collect all the tech-support files'
        )
    parser.add_argument(
        '-i',
        help='Text file containing a list of switches',
        dest='file',
        required=True
        )
    parser.add_argument(
        '-u',
        help='Devices username',
        dest='username',
        required=True
        )
    parser.add_argument(
        '-o',
        help='Output directory',
        dest='output_directory',
        required=True
        )
    args = parser.parse_args()
    args.password = getpass(prompt='Device password: ')

    try:
        with open(args.file, 'r') as file:
            devices = file.readlines()
    except:
        print('Error opening ' + args.file)
        exit(1)

    for i,device in enumerate(devices):
        devices[i] = device.strip()

    # Deletes unreachable devices from devices list

    unreachable = []
    
    print('Connecting to devices .... please be patient ... ')
    
    for device in devices:
        try:
            setdefaulttimeout(5)
            url = 'https://%s:%s@%s/command-api' %(args.username, args.password, device)
            switch = Server(url)
            response = switch.runCmds(1, ['enable'])
        except:
            unreachable.append(device)
    
    for item in unreachable:
        devices.remove(item)
        print("Can not connect to device " + item)

    # Collects all the tech-support files stored on Arista switches flash and copies them locally

    for device in devices:
        url = "https://" + args.username + ":" + args.password + "@" + device + "/command-api"
        try:
            ## Create one zip file named all_files.zip on the device with the all the show tech-support files in it
            cmds=['enable','bash timeout 30 zip /mnt/flash/schedule/all_files.zip /mnt/flash/schedule/tech-support/*']
            switch = Server(url)
            switch.runCmds(1,cmds, 'text')
            ## Connect to the device using SSH
            ssh = createSSHClient(device, port, args.username, args.password)
            ## Create directories 
            output_dir = device_directories (device, args.output_directory)
            ## Get the zipped file all_files.zip using SCP and save it locally
            my_path = output_dir[1] + '/' + date + '.zip'
            ssh = createSSHClient(device, port, args.username, args.password)
            scp = SCPClient(ssh.get_transport())
            scp.get("/mnt/flash/schedule/all_files.zip",local_path = my_path)
            scp.close()
            ## Delete the created zip file on the device
            cmds=['enable','bash timeout 30 rm /mnt/flash/schedule/all_files.zip']
            switch.runCmds(1,cmds, 'text')
        except:
            print('You are unlucky today! ' + device + ' does not like this script')

if __name__ == '__main__':
    main()
    ```
@ksator ksator self-assigned this Apr 21, 2022
@ksator
Copy link
Collaborator Author

ksator commented Apr 21, 2022

$ python3 showtech.py -i devices.txt -u ansible -o showtech
Device password: 
Connecting to devices .... please be patient ... 
Can not connect to device 2.2.2.2
Can not connect to device 2.2.2.3
$ ls showtech/10.73.1.105/
'21 Apr 2022 21:49:00.zip'

@ksator
Copy link
Collaborator Author

ksator commented Apr 22, 2022

done

@ksator ksator closed this as completed Apr 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant