Python - Readfile and SSH - python

I currently have this code to read a .CSV file, and SSH into a router with the hostname/IP listed on the .CSV
The problem is that the file reads the line as "192.168.2.1/r/n"
Example: ('Node', 4, '...Checking IP Address...', 'CPE-SIBFOPASO-103179-01\r\n')
Can you please help?
Code Sample:
nodenum=1
f=open('Routers.csv', 'r') #Ficheiro com Hostnames
c=f.readlines()
with open('Output.csv','wb') as f: #Ficheiro novo com o output
write = csv.writer(f)
write.writerow(['Hostname', "Cellular"])
for i in c :
print ("Node", nodenum, "...Checking IP Address...", i)
try:
Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios" , username="y", password="x", verbose=Fal
se)

Ended up achieving the result I wanted by changing the code to this:
f=open('Routers.csv', 'r')
c=f.read()
file_as_list = c.splitlines()

Related

show interfaces description cisco to txt <-> csv python

I'm trying to convert from a txt file to another csv file but why can't do how can I need.
I got this txt:
Interface Status Protocol Description
Gi1 up up MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2 up up Network Interface
Gi2.101 up up mpls-subinterface-CKTx904949
Gi3 admin down down Network Interface
Lo0 up up
Lo56 up up THIS IS A TEST LOOPBACK
Vi0 up up
and this is my script:
output = open("command.txt", "r")
for line in output.readlines():
lista = re.sub(r'\s{2,}', ";", line)
archivo_csv = open("output-1.txt", "a")
archivo_csv.write(lista + ";" + "\n")
archivo_csv.close()
output.close()
output = open("output.txt", "r+") #This second "loop" is becose between "Protocol"
lineas = output.readlines() #and "Description" be only one space, the regular
linea_1 = lineas[0] #expression that i did don't work for this case
lista = re.sub(r'\s+', ";", linea_1)
output.seek(0)
output.write(lista)
output.close()
vaciar_archivo = open("output.csv", "w")
vaciar_archivo.close()
output = open("output.txt", "r")
for line in output.readlines():
lista = line
archivo_csv = open("output.csv", "a")
archivo_csv.write(lista)
archivo_csv.close()
output.close()
the output is this:
Interface;Status;Protocol;Description;
;
Gi1;up;up;MANAGEMENT INTERFACE - DON'T TOUCH ME
;
Gi2;up;up;Network Interface
;
Gi2.101;up;up;mpls-subinterface-CKTx904949
;
Gi3;admin down;down;Network Interface
;
Lo0;up;up;;
Lo56;up;up;THIS IS A TEST LOOPBACK
;
Vi0;up;up;;
i can't do this well, i think that i have a problem with the form of the regular expression.
I need this so that the CSV file does not generate blank lines:
Interface;Status;Protocol;Description
Gi1;up;up;MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2;up;up;Network Interface
Gi2.101;up;up;mpls-subinterface-CKTx904949
Gi3;admin down;down;Network Interface
Lo0;up;up
Lo56;up;up;THIS IS A TEST LOOPBACK
Vi0;up;up
Could you help me improve my code?
You can try pandas.read_fwf:
import pandas as pd
df = pd.read_fwf("your_input_file.txt")
df["Description"] = (
df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip()
)
df = df.iloc[:, :4]
print(df)
df.to_csv("data.csv", index=False, sep=";")
Prints:
Interface Status Protocol Description
0 Gi1 up up MANAGEMENT INTERFACE - DON'T TOUCH ME
1 Gi2 up up Network Interface
2 Gi2.101 up up mpls-subinterface-CKTx904949
3 Gi3 admin down down Network Interface
4 Lo0 up up
5 Lo56 up up THIS IS A TEST LOOPBACK
6 Vi0 up up
and saves data.csv:
Interface;Status;Protocol;Description
Gi1;up;up;MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2;up;up;Network Interface
Gi2.101;up;up;mpls-subinterface-CKTx904949
Gi3;admin down;down;Network Interface
Lo0;up;up;
Lo56;up;up;THIS IS A TEST LOOPBACK
Vi0;up;up;

how to write system info to a spreadsheet in python

I am trying to write system info to a spreadsheet. but when I try to use my variables they come out black
import csv
import os
import linecache
os.system('getmac -v > mac.txt')
os.system("wmic bios get serialnumber > serial.txt")
os.system("wmic computersystem get model > model.txt")
os.system("hostname > hostname.txt")
os.system("ipconfig > ip.txt")
open('ip1.txt','w').writelines([line for line in open('ip.txt')if 'IPv4' in line])
open('mac1.txt','w').writelines([line for line in open('mac.txt')if 'Wi-Fi' in line])
open('mac2.txt','w').writelines([line for line in open('mac.txt')if 'Ethernet' in line])
serial = linecache.getline('serial.txt', 3)
model = linecache.getline('model.txt', 3)
mac = open("mac.txt","r")
IP = open("ip1.txt","r")
mac1 = open("mac1.txt","r")
mac2 = open("mac2.txt","r")
hostname = open("hostname.txt","r")
Rmac = mac.read()
Rip = IP.read()
Rmac1 = mac1.read()
Rmac2 = mac2.read()
Rhostname = hostname.read()
myData = [[model]]
myFile = open('example2.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(myData)
this just will not write the information to the spreadsheet? what am I doing wrong? I am very new to programming btw
You don't need intermediary files, why not call your commands and write their info to your CSV immediately without all that back and forward dancing?
import csv
import subprocess
# get the model
model = subprocess.check_output(["WMIC", "computersystem", "get", "model"],
universal_newlines=True).strip().rsplit("\n", 1)[1]
# get the serial
serial = subprocess.check_output(["WMIC", "bios", "get", "serialnumber"],
universal_newlines=True).strip().rsplit("\n", 1)[1]
# get the host name
hostname = subprocess.check_output(["hostname"], universal_newlines=True).strip()
# get WMI output for all addresses
ips = subprocess.check_output(["WMIC", "NICCONFIG", "where", "IPEnabled=true",
"get", "IPAddress"],
universal_newlines=True).strip().split("\n\n")[1:]
# post-process to get the addresses only
ips = [ip.split(",")[0].strip('"{} ') for ip in ips]
# etc.
with open("example2.csv", "wb") as f: # open your CSV for writing
writer = csv.writer(f) # create a writer
# you didn't write a header but let's add it in
writer.writerow(["model", "serial", "hostname", "ips"]) # etc., you get the picture...
writer.writerow([model, serial, hostname, ",".join(ips)]) # add other columns, too
And you'll get a nice example2.csv containing:
model,serial,hostname,ips
Your Model,Your Serial,Your-Hostname,List.Of.IP.Addresses
Do the same for the other fields and you're done.

python create daily folder

I would like to read from the serial of RPi and store the data in a daily folder as a 'csv.' file. I can create a file, write/read to/from csv file and had the serial comm working with putty for now (tried in a different project). In the future, the comm is going to be between pi and a various sensor. Considering everything else is working I am not sure how to create a seperate file automatically for each day. This is what I've done so far;
import serial
import time
import csv
def readLine(port)
rv = ""
while True:
ch = port.read()
rv += ch
if ch == '\r' or ch =='':
return rv
port = serial.Serial("/dev/ttyAMA0", baudrate = 115200, timeout = 10)
while True:
rcv=readLineCR(port)
str1 = time.strftime("%d%m%y")
file = open('directory....')
with open('test.csv', 'w') as fp:
a = csv.writer(fp, delimiter=',')
# data to be tested
data = [[str1,'1234'],[str1,'4321']]
a.writerows(data)
print('csv is created on: ' + str1)
reader = csv.reader(file)
for line in reader:
print(line)
Any help would be appreciated
Use datetime.datetime.now().strftime("%Y-%d-%m") to create folder name, os.path.exists(...) to check if folder exists and os.mkdir(...) to create new folder.
Thank you #furas. this is what I did and seems like its working.
import os
todayDate = time.strftime("%d-%m-%y")
directory = '/home/pi/...' + todayDate
if not os.path.exists(directory)
os.makedirs(directory)

searching for a string in a file using python faliure

I am using this code to search for emails in a particular file and write them into a another file. I have used 'in' operator to make sure that the email are not duplicated.
But this code does not get executed after the for line in f: line.
Can any one point out the mistake i have made here?
tempPath = input("Please Enter the Path of the File\n")
temp_file = open(tempPath, "r")
fileContent = temp_file.read()
temp_file.close()
pattern_normal = re.compile("[-a-zA-Z0-9._]+#[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
pattern_normal_list = pattern_normal.findall(str(fileContent))
with open('emails_file.txt', 'a+') as f:
for item in pattern_normal_list:
for line in f:
if line in item:
print("duplicate")
else:
print("%s" %item)
f.write("%s" %item)
f.write('\n')
New solution:
tempPath = input("Please Enter the Path of the File\n")
temp_file = open(tempPath, "r")
fileContent = temp_file.read()
temp_file.close()
pattern_normal = re.compile("[-a-zA-Z0-9._]+#[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
addresses = list(set(pattern_normal.findall(str(fileContent))))
with open('new_emails.txt', 'a+') as f:
f.write('\n'.join(addresses))
I think your logic was wrong, this works:
addresses = ['test#wham.com', 'heffa#wham.com']
with open('emails_file.txt', 'a+') as f:
fdata = f.read()
for mail in addresses:
if not mail in fdata:
f.write(mail + '\n')
Without reading to much into your code,
it looks like youre looping line by line, checking if the address you've also looping through exists in the line, if it doesn't you append your e-mail to it? But in 99% of a 100 lines the address will not be in the line, hence you'll get an unwanted addition.
Output of my code snippet:
[Torxed#faparch ~]$ cat emails_file.txt
test#wham.com
Torxed#whoever.com
[Torxed#faparch ~]$ python test.py
[Torxed#faparch ~]$ cat emails_file.txt
test#wham.com
Torxed#whoever.com
heffa#wham.com
[Torxed#faparch ~]$
for line in f:
Shouldn't you first call f.readlines()?
lines = f.readlines()
for line in lines:
Check this.

Test if string exists in file with Python

I'd like to add only servers currently doesn't exist at file
My current code :
f = open(filename,'a')
for server in cmo.getServers() :
print >>f, server.getListenAddress()
Thanks in advance
try this:
data = set( [i.strip() for i in open( filename, 'r' ).readlines()] )
for server in cmo.getServers() :
data.add( server.getListenAddress() )
open( filename, 'w' ).write('\n'.join(data))
Build a list of servers already present in the file:
present = [l.strip() for l in open(filename)]
(assuming the file format is just one server per line, no other symbols).
Then check if an address is in the list:
for server in cmo.getServers():
address = server.getListenAddress()
if address not in present:
print >>f, address
This assumes that the addresses you get from getServers() will not repeat.
If that's also possible, then build a set of them first:
new = set(server.getListenAddress() for server in cmo.getServers())
for address in new:
if address not in present:
print >>f, address

Categories