Reputation: 45
I'm new in Python. Can't make my first script to work well. What I want:
This XLS contains about 6k hosts. I've got some ideas about making multi-threading but know nothing about this yet. Will try soon.
Problem is, I can't get good "print(host)" output in console. Script work well, but instead of correct name of IP I see everytime first IP.
IP list:
10.1.115.105 10.1.115.108 10.1.115.143 etc.
I see in chat
[root@localhost python]# python3.3 telnet_bck.py
10.1.115.105
10.1.115.105
10.1.115.105
But the files are saving correctly
-rw-r--r-- 1 root root 16536 Apr 8 07:38 10.1.115.105
-rw-r--r-- 1 root root 16536 Apr 8 07:38 10.1.115.108
-rw-r--r-- 1 root root 16536 Apr 8 06:53 10.1.115.243
I guess problem is somewhere near "host = ip_addr_list[0]" but can't understand where. Please help, guys. Any help would be greatly appreciated.
import xlrd #Excel module
import re #Parser module
import os
import glob
import sys
import telnetlib #telnet module
rb = xlrd.open_workbook('/samba/allaccess/test.xlsx')
sheet = rb.sheet_by_name('IPs')
num_rows = sheet.nrows
num_cols = sheet.ncols
ip_addr_list = [sheet.row_values(rawnum)[0] for rawnum in range(sheet.nrows)]
num_ips = 0
while num_ips < num_rows:
host = ip_addr_list[0]
port = "23"
user = "test"
password = "test"
print(host)
tn = telnetlib.Telnet(host,port)
tn.read_until(b"ser name:")
tn.write(user.encode('ascii')+b"\n")
tn.read_until(b"assword:")
tn.write(password.encode('ascii')+b"\n")
tn.write(b"sh ru"+b"\n")
tn.write(b"exit"+b"\n")
str_all = tn.read_all()
re.sub("^\s+|\n|\r|\s+$", '', str_all.decode())
file = open('{0}'.format(ip_addr_list[num_ips]),"wb")
file.write(str_all)
num_ips += 1
Upvotes: 0
Views: 176
Reputation: 157
As you correctly assume, problem is exactly in host = ip_addr_list[0]
. ip_addr_list
is list (array) of elements and [0]
is index of element in list. So no matter how many times your loop runs, host
will be always first element of your ip_addr_list
.
In addition, there is more "pythonic" way of iterating over list. It would be:
for host in ip_addr_list:
port = "23"
user = "test"
password = "test"
print(host)
tn = telnetlib.Telnet(host,port)
tn.read_until(b"ser name:")
tn.write(user.encode('ascii')+b"\n")
tn.read_until(b"assword:")
tn.write(password.encode('ascii')+b"\n")
tn.write(b"sh ru"+b"\n")
tn.write(b"exit"+b"\n")
str_all = tn.read_all()
re.sub("^\s+|\n|\r|\s+$", '', str_all.decode())
file = open('{0}'.format(host),"wb")
file.write(str_all)
num_ips += 1
This way in every iteration of loop, your host
will contain next element from ip_addr_list
.
Also you may consider moving port, user
and password
definition out of the loop. They are always the same so theres no need to asigne then every time sa value.
Upvotes: 1