Python Forum
Print output in single file using pramika loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Print output in single file using pramika loop (/thread-28194.html)



Print output in single file using pramika loop - deepakkhw - Jul-09-2020

Hi,
I am using the below script for my automation but currently, it is making different putout file each device but I want to make a only single file for all devices. Can you help me:
import paramiko
import time
import datetime
import re
import sys
import getpass
import time
from datetime import date
from datetime import datetime
import os
import socket


def get_filename_datetime():
    # Use current date & time to get a text file name.
        return str(datetime.now().strftime('%Y_%m_%d %H_%M_%S'))

# Get full path for writing.
fname = get_filename_datetime()

user = input("Enter your M-account: ")
password = getpass.getpass("Enter your M-account Password: ")

ssh = paramiko.SSHClient()

ips = [i.strip() for i in open("switchlist.txt")] # creates a list from input file

for HOST in ips:
    try:
        #date_time = datetime.datetime.now().strftime("%Y-%m-%d")
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, port=22, username=user, password=password, look_for_keys=False, timeout=8, banner_timeout=5)
        connection = ssh.invoke_shell()
        connection.send("show run | se vty\n")
        time.sleep(10)
        file_output = connection.recv(99999999).decode(encoding='utf-8')
        hostname = (re.search('(.+)#', file_output)).group().strip('#')
        print(file_output)
        outFile = open(hostname + "_" + HOST + ".txt", "w")
        outFile.writelines(file_output)
        outFile.close()
        ssh.close()
       print("*" * 20 + " " + "%s is done" % hostname + " " + "*" * 20)

    except paramiko.AuthenticationException:
        print("X" * 20 + " " + HOST + ' === Bad credentials ' + "X" * 20)
    except paramiko.SSHException:
        print("X" * 20 + " " + HOST + ' === Issues with ssh service ' + "X" * 20)
    except socket.error:
        print("X" * 20 + " " + HOST + ' === Device unreachable ' + "X" * 20)



RE: Print output in single file using pramika loop - j.crater - Jul-11-2020

Hello,
the code loops through ips list, and for each ip (in the try block) outFile = open(hostname + "_" + HOST + ".txt", "w") this line creates a new file at each for loop iteration.
There are several possible solutions to this. What I would do is (assuming "switchlist.txt" isn't a humongous list) first loop through ips. Store the data you need in a data structure (list of strings, for example) with each iteration. And after the for loop is finished, write the collected data to the file.