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
Related
I have the following code that reads a CSV with a list of hostnames, and runs 2 commands.
I need to change this so that the CSV file it receives has 2 columns, one with the hostname, and another with the corresponding command to be inserted in that router.
Hostname
Comand
CPE_1111
sh ip int br
CPE_2222
sh run
etc
(...)
(...)
nodenum=1
f=open('routers.csv', 'r') #File with Hostnames
c=f.read()
file_as_list = c.splitlines()
with open('Output.txt','w') as f: #File with output
logf = open("error.csv", "a") #Logfile
loga = csv.writer(logf)
loga.writerow(["Hostname"])
for i in file_as_list :
print ("Node", nodenum, "...Checking IP Address...", i)
try:
Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios" , username=raw_input("Enter your Username:"), password=getpass.getpass(), verbose=False)
except:
try:
print("Cannot connect via SSH. Trying Telnet")
Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios_telnet" , username=raw_input("Enter your Username:"), password=getpass.getpass(), verbose=False)
except:
print("SSH and Telnet Failed")
print("")
now = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
loga.writerow([i])
nodenum = nodenum+1
continue
hostname = (Connection.send_command("show run | include hostname"))
cellular = (Connection.send_command("sh ip int brief"))
Connection.disconnect
(...)
Your answer lies with how the csv is read. You can use csv.DictReader() to read each row and convert it to a dictionary.
import csv
with open(file="routers.csv", mode="rt") as f:
next(f)
lst = csv.DictReader(f=f, fieldnames=["ip", "cmd"])
ips_cmds = list(lst)
for ip_cmd in ips_cmds:
print("Hostname:", ip_cmd["ip"])
print("Command:", ip_cmd["cmd"], end="\n\n")
# Hostname: CPE_1111
# Command: show ip interface brief
# Hostname: CPE_2222
# Command: show running-config
Then in the for loop where you connect to each router, you can select the value you need from the keys specified in fieldnames.
conn = ConnectHandler(
device_type="cisco_ios",
ip=ip_cmd["ip"],
username=input("Username: "),
password=getpass(prompt="Password: "),
secret=getpass(prompt="Enable Secret: "),
fast_cli=False,
)
hostname = conn.send_command(command_string=ip_cmd["cmd"])
Don't forget to add the parentheses for disconnect() function to be executed.
conn.disconnect()
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 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()}
I would like to retrieve multiple log files from an Ubuntu server (using Python 2.7 on win 7 machine) without having to write verbose, repetitive code. I'm sure I can use a loop to accomplish this, but I can't come up with any valid solutions (neophyte programmer). I need the direction of someone more seasoned than I. In advanced, I appreciate the help. Below is the code I'm using in my script to log into a server and retrieve one file. Below is a sample path of files I would like to retrieve at the same time:
/var/log/apache/a.log
/var/log/apache/e.log
/var/opt/smart/log/me.log
/var/opt/smart/log/se.log
I have several more paths, but I imagine you get the idea. Below is the code used to log into the server:
def do_siteserver(self, line):
import paramiko
paramiko.util.log_to_file('c:\Python27\paramiko-wininst.log')
host = '10.5.48.65'
port = 22
transport = paramiko.Transport((host,port))
while True:
try:
print '\n'
passW = raw_input("Enter the SiteServer weekly password: ")
password = passW
username = 'gilbert'
print '\n'
print 'Establishing SFTP connection to: ', host + ':' + str(port), '...'
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
print 'Authorization Successful!!!'
filepath = '/var/log/apache2/error.log'
localpath = 'C:\\remote\\NewFile.log'
sftp.get(filepath, localpath)
sftp.close()
transport.close()
break
except:
print '\n'
print "Authorization Failed!!!"
break
Instead of
filepath = '/var/log/apache2/error.log'
localpath = 'C:\\remote\\NewFile.log'
sftp.get(filepath, localpath)
I propose this :
log_names = {
"/var/log/apache2/error.log" : 'C:\\remote\\NewFile.log',
"/var/log/apache/a.log" : 'C:\\remote\\NewFile_a.log',
} # add here all the log files you want to retrieve
for log_file, local_name in log_names.iteritems():
sftp.get(log_file, local_name)
That ?? :
def do_siteserver(self, line):
import paramiko
host = '10.5.48.65'
port = 22
username = 'gilbert'
password = raw_input("\nEnter the SiteServer weekly password: ")
localpath = 'C:\\remote\\NewFile.log'
paramiko.util.log_to_file('c:\Python27\paramiko-wininst.log')
with open(localpath,'w') as lf:
for filepath in ('/var/log/apache/a.log',
'/var/log/apache/e.log',
'/var/opt/smart/log/me.log'
'/var/opt/smart/log/se.log'):
try:
print '\nEstablishing SFTP connection to: {}: {}...'.format(host,port)
transport = paramiko.Transport((host,port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
print 'Authorization Successful!!!'
lf.write("Content of server's file : "+filepath+'\n\n')
sftp.get(filepath, localpath)
# or sftp.get(filepath, lf) ?
sftp.close()
transport.close()
lf.write("\n\n\n")
except:
print "\nAuthorization Failed!!!"
break
I understood that you want to record the got contents in only one file of path 'C:\remote\NewFile.log'
I don't know if mixing instruction sftp.get(filepath, localpath) and instruction lf.write() is authorized.
.
EDIT
Now I have understood the aim I can propose a more correct code:
def do_siteserver(self, line):
import paramiko
host = '10.5.48.65'
port = 22
username = 'gilbert'
password = raw_input("\nEnter the SiteServer weekly password: ")
localpath = 'C:\\remote\\NewFile'
paramiko.util.log_to_file('c:\Python27\paramiko-wininst.log')
for filepath in ('/var/log/apache/a.log',
'/var/log/apache/e.log',
'/var/opt/smart/log/me.log'
'/var/opt/smart/log/se.log'):
try:
print '\nEstablishing SFTP connection to: {}: {}...'.format(host,port)
transport = paramiko.Transport((host,port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
print 'Authorization Successful!!!'
sftp.get(filepath, localpath + filepath.replace('/','_'))
sftp.close()
transport.close()
except:
print "\nAuthorization Failed!!!"
break
BY the way, there is no need of break in the try portion