Python How to generate file name - python

I was wondering if the community can help me out I'm a newbie to programming. I trying to ssh to a list of devices contain on "list.txt" once it logs into the router I send the same command to each one and write the output to a file. However, on the code below it overrides the output of each device. I need to create a unique file for each output with the name of the IP address that is contains on the "list.txt" file. If anybody can help me out I would really appreciated.
import paramiko
import time
import os
def disable_paging(remote_conn):
'''Disable paging on a Cisco router'''
remote_conn.send("terminal length 0\n")
time.sleep(1)
# Clear the buffer on the screen
output = remote_conn.recv(1000)
return output
#Create variables
f = open('list.txt')
filepath = ('test/tas.txt')
username = 'test'
password = 'test'
#Create a for loop
for i in f:
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
remote_conn_pre.connect(i, username=username, password=password)
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(1000)
disable_paging(remote_conn)
# Now let's try to send the router a command
remote_conn.send("\n")
remote_conn.send("show int des\n")
# Wait for the command to complete
time.sleep(2)
output = remote_conn.recv(88880000)
# print output
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
with open(filepath, "w") as f:
f.write(output)
f.close()

You could just have your 'filepath' variable defined in the for loop, and use the 'i' string to create it :
for i in f:
filename = 'tas_%s.txt' % str(i)
filepath = os.path.join('test', filename)
# anything else remains unchanged
Hope it works (difficult without knowing the content of 'list.txt').

Related

how to construct loop and write netmiko commands to files using python

As per the below script, it adds both commands to output.txt.
Instead how to add "show system" command to output1.txt and "show run" command to output2.txt.
Python Script:
Import program dependencies
from netmiko import ConnectHandler
import getpass
Read from a list of hostnames to connect to
hosts = open('hosts.txt','r')
hosts = hosts.read()
hosts = hosts.strip().splitlines()
Get UserName and password from input
userName = input('Username: ')
passWord = getpass.getpass()
Loop to process hosts in hosts.txt file
for host in hosts:
# Define device type and connection attributes
Brocade_ICX = {
'device_type': 'brocade_fastiron',
'ip': host,
'username': userName,
'password': passWord),
}
# Netmiko SSH Connection Handler
net_connect = ConnectHandler(**Brocade_ICX)
#open file to write command output
file = open('output.txt', 'w')
# Execute commands
output = net_connect.send_command('show system')
output = net_connect.send_command('show run')
# Print output to console screen
print('-------------- Output from ' + host + '------------------')
print(output)
print()
print()
# Write output to file above
file.write(output)
file.close()
you are doing the looping wrong..
think about the last iteration of j variable in the loop
it points to c then inner loop goes through each file and and writes c to them
to fix it you need only one loop
for i in range(len(command)):
file = open(command[i] +'_output.txt', 'w')
file.write(output[i])
file.close()
Follow just four simple steps to get the solution.
Opening a text file.
file = open('text file','w')
Adding a test line in the file.
file.write('We will be seeing aninterated printing of numbers between 0 to 10\n')
Writing a for loop over the file.
for i in range(0,11):
file.write(str(i))
file.write('\n')
Closing the text file.
file.close()

Is it possible to search for something specific in the output of an outside executable file using python?

I am writing a code that is using an outside executable file and i am trying to see if there is a way I can search through the output for information that only corresponds with a specific date I provide. The executable file is tsk_gettimes and I am needing to scan through all of the information of the provided file given by a user where the user can just input a date they would like to search for and the code only prints out that information rather than all the information of that file.
import os, sys, re
#user file input
filename = input()
if(filename = NULL)
print(os.system('"C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe"'))
#user date input
keydate = input()
#executable file
os.chdir('C:\\Program Files\\sleuthkit-4.11.1-win32\\bin')
os.system('"C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe %s"', filename).read()
#search for key date
for in
re.search()
#date specifier
this is the code i have so far if this helps.
Use subprocess.popen() to run a command and read its output.
import subprocess
with subprocess.Popen(['C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe', filename], stdout=PIPE) as proc:
output = proc.stdout.read()
if re.search(regexp, output):
...
You could try something like this... I am not super convinced it will work though without knowing what your executable does.
import subprocess
import os
filename, keydate = input().split(' ')
print(filename)
assert os.path.exists(filename) # can't find filename
assert os.path.exists("C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe") # can't find executable
prog = subprocess.run([
"C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe",
filename
], stdout=subrocess.PIPE)
output = prog.stdout.decode().split('\n')
for i in output:
if keydate in i:
print(i)
If you get an encoding error just put latin-1 as an argument to decode.
output = prog.stdout.decode('latin-1').split('\n')
Or try this if you prefer to continue to use os.system:
import os, sys, re
# user file input
# user date input
keydate = input()
filename = input()
temp = "temp"
with open(temp,'wt') as tempfile:
pass
temp = f'"{os.path.abspath(temp)}"'
filename = f'{filename}'
#executable file
os.system(f'"C:\\Program Files\\sleuthkit-4.11.1-win32\\bin\\tsk_gettimes.exe" {filename} >> {temp_location}')
with open(temp_location,'rt') as temp:
data = temp.read()
os.remove(temp_location)
#search for key date
for i in data.split('\n'):
if keydate in i:
print(i)

Save variable in pc python

I want to save a variable (user input fo mail) in pc. Because I don't want it to ask to login again and again. So please help me with how to store email variable in pc and also how to access it. Thank you.
I'm not sure what you want exactly.
If you just wanna save a text(I mean, string) in variable, then write it to a file like this.
f = open("some_file_to_save.txt", 'w')
f.write(your_variable)
f.close()
Or if you want data to be loaded as python variable again, then you can utilize pickle
May be you need config to your program?
So for this use the configparser
import configparser
You need 2 functions, first to Save:
def save_config(email):
config = configparser.ConfigParser()
config['DEFAULT'] = {
'Email': email
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
And second to read saved data:
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config['DEFAULT']['Email']
Then add it to your code or use this example:
try:
email = read_config()
except:
print("Config doest contain email, type it:")
email = input()
print(f"My email is {email}")
save_config(email)

find and print - regular expression

This program is to login to my switch and copies output to a file; and the second part is for finding a keyword and print the entire line.
When I run the code the first part works fine but second part of the code does not print the line containing the key word i am looking for..
However, when i run the second part of the code separately i am able to print the line containing the key_word.
What is wrong here? Pease help me out?
import paramiko
import sys
import re
host = "15.112.34.36"
port = 22
username = "admin"
password = "ssmssm99"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
commands = ["switchshow"]
for command in commands:
print(command)
sys.stdout = open('zones_list.txt', 'w')
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
lines = "".join(lines)
print(lines)
ssh.close()
#SECOND PART
#open the zone_list file and search for a keyword
#search for wwn and print the entire line --> doesnt print why?
wwn = "10:00:00:90:fa:73:df:c9"
with open('zones_list.txt', 'r') as f:
lines = f.readlines()
for line in lines:
if re.search(r'10:00:00:90:fa:73:df:c9', line):
print (line)
break
You're redicting stdout to a file in line 17:
sys.stdout = open('zones_list.txt', 'w')
All print statements afterwards don't write to the console, but to the file.
Secondly you open the same file twice, once for writing and once for reading, but in the second case f.readlines() returns an empty list.
Example to show why it's problematic to open the file twice.
import sys
# 1. Opening the file without closing it => will be closed at the end of the program
# 2. stdout now writes into the file
sys.stdout = open('text3', 'w')
# Will be writen into the file when the program finishes
print ('line1')
print ('line2')
# We open the file a second time
with open('text3', 'r') as f:
# lines will always be an empty list, no matter if there was something in the file before
lines = f.readlines()
# Writing to stderr so we see the output in the console (stdout still points at the file)
sys.stderr.write('length: {}'.format(len(lines)))
for line in lines:
# We should never be here
sys.stderr.write (line)
# write some more stuff the the file
for i in range(1, 6):
print ('i + {}'.format(i))
print('line3')
The first part of the script redirected stdout to the file. So print(line) in the second part is also writing to the file instead of displaying the matching line. Also, you never closed the file in the first part, so buffered output won't be written to the file.
Don't use sys.stdout in the first part, use an ordinary variable.
Another problem is that you're overwriting the file for each command in commands. You should open the file once before the loop, not each time through the loop.
wwn isn't a regular expression, there's no need to use re.search(). Just use if wwn in line:. And you don't need to use f.readlines(), just loop through the file itself.
import paramiko
import sys
host = "15.112.34.36"
port = 22
username = "admin"
password = "ssmssm99"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
commands = ["switchshow"]
with open('zones_list.txt', 'w') as f:
for command in commands:
print(command)
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
lines = "".join(lines)
print(lines, file=f)
ssh.close()
#SECOND PART
#open the zone_list file and search for a keyword
#search for wwn and print the entire line --> doesnt print why?
wwn = "10:00:00:90:fa:73:df:c9"
with open('zones_list.txt', 'r') as f:
for line in f:
if wwn in line:
print (line)
break
got the code straight. And couple of questions to bug you and Maddi.
This code asks the user to enter the "wwn" to search for in the host and print the line which contains the "wwn" number.
Question1: I would run this code multiple times whenever I would like to search for "wwn"...
And here I would like to have a clear "zones_list.txt" file each time I start. So I opened the file in 'w' mode -- SO this clears each time right? Any other suggestion?
Question2: IS there any other way to store the output and search it for a string and print the output? I guess storing the data in a file and searching through it is the best?
Question3: I would like to add a GUI where user is asked to enter the "wwn" and print the output. Any suggestion?
Thanks again :)
import paramiko
import sys
import re
#host details to fetch data - nodefind
host = "15.112.34.36"
port = 22
username = "admin"
password = "ssmssm99"
#shell into the client host
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
#asking user to enter the wwn to search in the host
wwn = input('Enter the wwn to be searched >')
#for example command is: nodefind 20:34:00:02:ac:07:e9:d5
commands = ["nodefind " + wwn, "switchshow"]
f =open('zones_list.txt', 'w')
for command in commands:
print(command)
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
lines = "".join(lines)
print(lines, file=open('zones_list.txt', 'a'))
ssh.close()
#print a particular line in console to the user
f =open('zones_list.txt', 'r')
for line in f:
if wwn in line:
print(line)
break

how to open up a child process to tail the files present in a config file using python on a mac machine?

I am trying to tail the files in a config file using python on mac
I am able to get the values from the config file but not able to open up child processes for the same
a sample config file has
[section1]
host_prefix = true
timestamp_prefix = true
[section2]
host = localhost
port = 1463
pids = /var/run/harvester
[files]
apache.access = /var/log/apache2/access.log
apache.errors = /var/log/apache2/errors.log
mail = /var/log/mail.log
mysql.log = /var/log/mysql.log
I am opening up the config file and trying to get the filepaths and I need to tail them in new child processes in separate terminals
#! /bin/env python
import StringIO
import os
import re
from multiprocessing import Process
COMMENT_CHAR = '#'
OPTION_CHAR = '='
def parse_config(filename):
options = {}
f = open(filename)
for line in f:
if COMMENT_CHAR in line:
line, comment = line.split(COMMENT_CHAR, 1)
if OPTION_CHAR in line:
option, value = line.split(OPTION_CHAR, 1)
option = option.strip()
value = value.strip()
options[option] = value
f.close()
return options
try:
f = open("/etc/harvest.conf", 'r')
print 'found'
options = parse_config('/etc/harvest.conf')
print options.values()
os.system('tail -f options.values')
except:
try:
f = open("/usr/local/etc/harvest.conf", 'r')
print 'found'
options = parse_config('/usr/local/etc/harvest.conf')
print options.values()
os.system('tail -f options.values')
except IOError:
print 'cannot find file'
the above code gives me all the values from the config file that includes 'localhost','1463'
but I want only the paths from the file and need to tail them in separate child processes
Try ConfigParser. It can work with INI files.
use os.path.exists to check if a file exists
use ConfigParser to parse an ini-type config file

Categories

Resources