I am writing a simple script in python , to telnet multiple cisco switches and add vlans. I am testing my script in UNET LABS or latest EVE-NG.
When I telnet to multiple switches using FOR loop and call
tn = telnetlib.Telnet(HOST)
from with in loop , it only telnets to last value in variable HOST i.e. 10.1.1.7
Here is my code,
#!/usr/bin/env python
import getpass
import sys
import telnetlib
user = raw_input("Enter your telnet username: ")
password = getpass.getpass()
for h in range (2,8):
print "Telnet to host" + str(h)
HOST = "10.1.1." + str(h)
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("conf t\n")
for n in range (10,20):
tn.write("vlan " + str(n) + "\n")
Following code is working for me. Put all of your IPs in a sheet (IP_test.txt).
import getpass
import sys
import telnetlib
user = "YOURUSER"
password = "YOURPASSWORD"
with open('IP_test.txt') as file:
for HOST in file:
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("Command1\n")
tn.write("Command2\n")
print(tn.read_all())
This python script below works for me for the same purpose
#!/usr/bin/env python3
import getpass
import telnetlib
user = input("Enter your Telnet Username: ")
password = getpass.getpass()
DeviceList=open('/home/tt/Hostname.txt')
for HOST in DeviceList:
print('Configuring on Device : ',HOST)
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"enable\n")
EnPass=input('Enter your Enable password : ')
tn.write(EnPass.encode('ascii')+b'\n')
c=open('/home/tt/Commands.txt')
for i in c:
tn.write(i.encode('ascii')+b'\n')
c.close()
print(tn.read_all().decode('ascii'))
tn.close()
DeviceList.close()}
Related
with python script I want to make some configuration on mikrotik routers, looks like script is right and no gives errors but ends without printing command outputs
import telnetlib
import time
dev_ip = "172.16.62.160"
user = "admin"
PASSWORD = ""
comm1 = "ip address print"
tn = telnetlib.Telnet(dev_ip, timeout=1)
tn.read_until(b"Login: ")
tn.write(user.encode("ascii") + b'\n')
tn.read_until(b"Password: ")
tn.write(PASSWORD.encode("ascii") + b'\n')
tn.read_until(b">")
time.sleep(1)
tn.write(comm1.encode("ascii") + b"\r\n")
Showcmdoutput = tn.read_very_eager().decode('ascii')
print(Showcmdoutput)
tn.close()
print("DONE")
running on Ubuntu Desktop
problem solved after putting:
time.sleep(1)
before Showcmdoutput = tn.read_very_eager().decode('ascii')
tn.write(comm1.encode("ascii") + b"\r\n")
time.sleep(1)
Showcmdoutput = tn.read_very_eager().decode('ascii')
I have written a program that can change the system's IP address/password automatically at a specific time. In addition, it has two separate python files.
The first one is a program that runs the main program under the service, retrieves the desired information from the user and stores it in a `.txt' file.
# Import/Lib
import os
import sys
import pysc
import time
# Services
if __name__ == '__main__':
service_name = 'test4'
script_path = os.path.join(
os.path.dirname(__file__)+"\\"+"Run.exe"
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
print("CreateService SUCCESS")
pysc.start(service_name)
print("StartService SUCCESS")
# Input data
time_today = input("Enter a Time (MM:SS): ")
date_today = input("Enter a Date (YYYY-MM-DD): ")
adapter_name = input("Enter your interface name: ")
interface_name = "\"" + adapter_name + "\""
static_ip = input("Enter your static ip: ")
subnet = input("Enter your subnet mask: ")
gateway = input("Enter your gateway: ")
time.sleep(0.5)
print("")
pass_complexity = "Windows password complexity rules:""\n" \
"-Password must not contain the user's account name or more than two consecutive "\
"characters from the user's full name.""\n"\
"-Password must be six or more characters long.""\n"\
"-Password must contain characters from three of the following four categories:""\n"\
" .Uppercase characters A-Z (Latin alphabet)""\n"\
" .Lowercase characters a-z (Latin alphabet)""\n"\
" .Digits 0-9""\n"\
" .Special characters (!, $, #, %, etc.)""\n"
print(pass_complexity)
password = input("New password: ")
conform_pass = input("Confirm password: ")
stop = True
while stop == True:
if password == conform_pass:
print("Input info completed")
print("Interface adapter", interface_name + ":")
print("IPv4 Address. . . . . . . . . . . : ", static_ip)
print("Subnet Mask . . . . . . . . . . . : ", subnet)
print("Default Gateway . . . . . . . . . : ", gateway, "\n")
print("Your password:", password, "\n")
stop = False
else:
print("Sorry, passwords do not match.", "\n")
password = input("New password: ")
conform_pass = input("Confirm password: ")
# Write file
file_name = os.path.dirname(__file__)+"\\"+"Network Monitoring Utility.txt"
my_file = open(file_name, 'w')
my_file.write(time_today+" ")
my_file.write(date_today+" ")
my_file.write(interface_name+" ")
my_file.write(static_ip+" ")
my_file.write(subnet+" ")
my_file.write(gateway+" ")
my_file.write(password+" ")
my_file.close()
wait = input("Please enter for exit.")
The second program compares the system clock with the read time by reading the desired .txt file information. If the system date and time are the same as the date and time entered, it will change the system's IP address/password.
# Import Lib
import subprocess
import getpass
from datetime import date
import datetime
import time
time.sleep(90)
# Read data
my_file = open('Network Monitoring Utility.txt', 'r')
data = my_file.read()
data = data.split()
my_file.close()
time = data[0]
set_date = data[1]
interface_name = data[2]
static_ip = data[3]
subnet = data[4]
gateway = data[5]
password = data[6]
# Check data and time and change ip, subnet mask, gateway and password
stop = True
while stop == True:
now_time = str(datetime.datetime.now().time())
now_date = str(date.today())
if now_date == set_date and now_time > time:
stop = False
subprocess.check_call("netsh interface ipv4 set address name="
+ interface_name + " " + "static" + " " + static_ip + " " + subnet + " "
+ gateway, shell=True)
username = getpass.getuser()
subprocess.check_call("net users " + username + " " + password, shell=True)
When I run this program in Pycharm it runs without any problems. But when I convert both programs with pyinstaller to '.exe', the program will not run under service. this will cause an error.
filenotfounderror: [winerror 2] the system cannot find the file specified.
This message is also because the program requires a Python executable file to run severely on the service.
How to run this service without having to install Python on a system?
I have this program that access devices and change its hostname based from csv file but after entering the user/password script doesn't write any or seem like its tn.write is not running.
While logs from device shows that the python script can access the device. Also no error when running this script.
import csv
import telnetlib
import getpass
import sys
import time
##from prettytable import PrettyTable
def main():
#open csv file, then put to variable csvfile.
with open(input("Input the CSV filename: ")) as csvfile:
riphostCSV = csv.reader(csvfile, delimiter=',')
#Put the data as list from excel.
ipaddress = []
nhostname = []
## Menu = PrettyTable()
## Menu.field_names=['IPadd','Nhostname']
#Action - Put the data from excel to variable[list]
for col in riphostCSV:
ipadr = col[0]
nhost = col[1]
ipaddress.append(ipadr)
nhostname.append(nhost)
#List of devices from CSV file
print("LIST OF DEVICES")
for i in ipaddress:
print(i, nhostname[ipaddress.index(i)])
dev = ipaddress
print ("Host: ",dev)
user = input("Enter your username: ")
password=getpass.getpass("Enter Your Password Here: ")
## password = getpass.getpass()
print ("Now accessing the devices " + i)
dev = i.strip()
tn = telnetlib.Telnet(dev)
print("host:",dev)
tn.read_until(b"Username:")
tn.write(user.encode("ascii") + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode("ascii") + b"\n")
tn.read_until(b"#")
tn.write(b"conf t \n")
time.sleep(1)
tn.write(b"hostname test33 \n")
tn.write(b"exit \n")
tn.write(b"wr mem \n")
## tn.close()
## break
main()
OUTPUT
nput the CSV filename: iphost.csv
LIST OF DEVICES
192.168.137.50 lab-sw01
Host: ['192.168.137.50']
Enter your username: cisco
Warning (from warnings module):
File "C:\Users\GlobalNOC\AppData\Local\Programs\Python\Python37-32\lib\getpass.py", line 100
return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
Enter Your Password Here: cisco
Now accessing the devices 192.168.137.50
host: 192.168.137.50
Thanks
if i put the ips in the list by hand, the script is working, if i try to read them from a txt file i get the error:gaierror: [Errno 11001] getaddrinfo failed
Here is my code:
import telnetlib
from __future__ import with_statement
file = open('ips.txt', 'r')
HOST = file.readlines()
print HOST
user = "root"
password = "root"
for i in range(len(HOST)):
tn = telnetlib.Telnet(HOST[i])
tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("show slot info\n")
tn.write("exit\n")
string = str(tn.read_all())
print string
for line in string.splitlines():
if line.startswith('Temperature:'):
Temperature = line[34:36]
print Temperature
Likely, you need to strip the newlines off the host; readlines() returns the full line, including any newline characters, so you're looking up a host like example.com\n.
tn = telnetlib.Telnet(HOST[i].strip())
I'm using Python's telnetlib to telnet to some machine and executing few commands and I want to get the output of these commands.
So, what the current scenario is -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
tn.write("command2")
tn.write("command3")
tn.write("command4")
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
#here I get the whole output
Now, I can get all the consolidated output in sess_op.
But, what I want is to get the output of command1 immediately after its execution and before the execution of command2 as if I'm working in the shell of the other machine, as shown here -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
#here I want to get the output for command1
tn.write("command2")
#here I want to get the output for command2
tn.write("command3")
tn.write("command4")
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
I ran into something similar while working with telnetlib.
Then I realized a missing carriage return and a new line at the end of each command and did a read_eager for all commands. Something like this:
tn = telnetlib.Telnet(HOST, PORT)
tn.read_until("login: ")
tn.write(user + "\r\n")
tn.read_until("password: ")
tn.write(password + "\r\n")
tn.write("command1\r\n")
ret1 = tn.read_eager()
print ret1 #or use however you want
tn.write("command2\r\n")
print tn.read_eager()
... and so on
instead of only writing the command like:
tn.write("command1")
print tn.read_eager()
If it worked with just a "\n" for you, adding only a "\n" might be enough instead of "\r\n" but in my case, I had to use "\r\n" and I haven't tried with just a new line yet.
You must refer to the documentation of telnetlib module here.
Try this -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
print tn.read_eager()
tn.write("command2")
print tn.read_eager()
tn.write("command3")
print tn.read_eager()
tn.write("command4")
print tn.read_eager()
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
I was also going through the same issue where the read_very_eager() function was not displaying any data. From some post got the idea that the command will require some time to execute. so used the time.sleep() function.
Code Snippet:
tn.write(b"sh ip rou\r\n")
time.sleep(10)
data9 = tn.read_very_eager()
print(data9)