hi guys please how can I save the output logs to text file for this script to solve this problem
import sys
import telnetlib
import getpass
#####################
###### Define Host
host=["192.168.1.164","192.168.1.169"]
devno=len(host)
user='ali'
Password='cisco'
for i in range(devno):
print('*'*50 + ' Connected to device : '+str(host[i]) +'*'*50)
tn=telnetlib.Telnet(host[i])
tn.read_until(b'Username: ')
tn.write(user.encode('ascii')+ b'\n')
tn.read_until(b'Password')
tn.write(Password.encode('ascii')+b'\n')
#tn.write(b'enable' + b'\n')
#tn.write(b"\n")
#tn.write(b"terminal length 0\n")
#tn.write(b"show run\n")
#tn.write(b' show ip route\n')
tn.write(b' exit\n')
print(tn.read_all().decode('ascii'))
you could add this at the end of your for loop
with open("text1.txt", "w") as f:
f.write(str(tn.read_all().decode("ascii")))
the above should save the output of your commands to the file
if you want to get the logs as well then you need to add the following just before you exit
tn.write(b' show log\n')
Related
I want down load "*_ice.nc" files in ftp. so..
library
import wget
import math
import re
from urllib import request
adress and file list
url = "ftp://ftp.hycom.org/datasets/GLBy0.08/expt_93.0/data/hindcasts/2021/" #url
html = request.urlopen(url) #open url
html_contents = str(html.read().decode("cp949"))
url_list = re.findall(r"(ftp)(.+)(_ice.nc)", html_contents)
loop for download
for url in url_list: #loop
url_full="".join(url) #tuple to string
file_name=url_full.split("/")[-1]
print('\nDownloading ' + file_name)
wget.download(url_full) #down with wget
but error messege occured like this
(ValueError: unknown url type: 'ftp%20%20%20%20%20%20ftp%20%20%20%20%20%20382663848%20Jan%2002%20%202021%20hycom_GLBy0.08_930_2021010112_t000_ice.nc')
could i get some help?
After decoding
ftp%20%20%20%20%20%20ftp%20%20%20%20%20%20382663848%20Jan%2002%20%202021%20hycom_GLBy0.08_930_2021010112_t000_ice.nc
is
ftp ftp 382663848 Jan 02 2021 hycom_GLBy0.08_930_2021010112_t000_ice.nc
which clearly is not legal ftp address. You need alter your code so it will be
ftp://ftp.hycom.org/datasets/GLBy0.08/expt_93.0/data/hindcasts/2021/hycom_GLBy0.08_930_2021010112_t000_ice.nc
I suggest temporarily replacing wget.download(url_full) using print(url_full), then apply changes to get desired output and then reverting to wget.download(url_full).
I am trying an assignment to open a syslog for a server program (called ticky) that creates logs and errors and then assign the errors to a dictionary and export to a csv file to sort and host to a webpage,
I am unsure of how to access syslog files, as the course only went into sys.argv and I don't know if this can be used or if I need to figure out how to use syslog module. Once the log is opened, the regex will pull the error message and add it to the dictionary, either creating a new entry or adding value to an existing key.
Am I on the right track?
#!/usr/bin/env python3
import re
import sys
errors = {}
# log line format
# Jun 1 11:06:48 ubuntu.local ticky: ERROR: Connection to DB failed (username)
logfile = sys.argv[1]
# NOTE: Check to find correct log file
with open(logfile) as f:
for line in f:
if "ERROR:" not in line:
continue
regex_error = r"ERROR: (\d+) "
"""searches for error messages"""
error = re.search(regex_error, line)
if error is None:
continue
name = error[1]
errors[name] = errors.get(name, 0) + 1
I need to further optimize my code in Python.
I was earlier executing commands on the Device Under Test step by step which was a lot as I also required sleep timers. However I was able to minimize it through a list and calling elements of the list in a for loop:
I need your inputs to further optimize this code:
ConfigListBFD = ['conf t' , 'int Fa1/0' , 'ip address 10.10.10.1 255.255.255.0', 'no shut']
for i in ConfigListBFD:
tn.write(i.encode('ascii') + b"\n")
print (i, "command entered successfully")
time.sleep(2)
Please note: I am telnetting the DUT as ssh is not supported.
i am using this optimized common code for telnet. we can create a common file where you can add this method
import telnetlib
import time
def telnet(host):
user = <username>
password = <password>
try :
tn = telnetlib.Telnet(host)
except :
print("Unable to connect")
sys.exit()
tn.read_until(b"Username:") # read until username prompt
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password:") #read until password prompt
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"#")
return tn #return telnetlib handle
than import this method to another file, where we write our script
I have this code Which is trying to retrieve file from Git Hub Repositories.
import os
import tarfile
from six.moves import urllib
import urllib.request
DOWNLOAD_ROOT = "https://github.com/ageron/handson-ml/tree/master/"
HOUSING_PATH = os.path.join("datasets", "housing").replace("\\","/")
print(HOUSING_PATH)
HOUSING_URL = DOWNLOAD_ROOT + HOUSING_PATH
print(HOUSING_URL)
print(os.getcwd())
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
if not os.path.isdir(housing_path):
os.makedirs(housing_path)
tgz_path = os.path.join(housing_path, "housing.tgz").replace("\\","/")
print(tgz_path)
urllib.request.urlretrieve(housing_url, tgz_path)
housing_tgz = tarfile.open(tgz_path)
housing_tgz.extractall(path=housing_path)
housing_tgz.close()
fetch_housing_data()
After Executing the code I got this Error ReadError: file could not be opened successfully. I did checked the actual file size and the file which is download after executing this code and I came to know that file is downloaded partially.
So is their any way to download the whole file ? Thanks in Advance
Finally I got the problem. It was with the link that I was using to retrieve the file. I didn't knew that RAW link should be used along with the file name (Not using file name will give you 404 Error) in Git Hub Repositories.
So I little bit of modification is needs to be done in actual code posted in my question.
That is :
Change the link from
DOWNLOAD_ROOT = "https://github.com/ageron/handson-ml/tree/master/"
To this :
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
And this
HOUSING_URL = DOWNLOAD_ROOT + HOUSING_PATH
to
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz" \\**( Actual File name is needed)**
Thank you !
I need to get a connection to a device via TELNET and write in to telnet session.
I Use - Python 3.3.2 and PyDev For Eclipse 2.7.5
I use IP2COM cause it allows me to open another telnet to the same device and see how the commands are executed.
The main purpose of this is to Read\Write in to Telnet session using Python.
Here is the code that i use:
import getpass
import sys
import telnetlib
HOST = "172.17.174.50"
port = "1003"
#user = input("Enter your remote account: ")
#password = getpass.getpass()
tn = telnetlib.Telnet(HOST, port)
#tn.read_until("user:")
#tn.write(user.encode('ascii') + b"\r")
#tn.write(user.encode("test" + "\r")
#if password:
# tn.read_until(b"Password: ")
# tn.write(password.encode('ascii') + b"\n")
tn.write("sh run" + "\r")
tn.write("exit" + "\r")
print(tn.read_all()
Here is the error that i'm getting :
File "C:\Users\user\workspace\main\src\telnet.py", line 23
^
SyntaxError: unexpected EOF while parsing
The strange thing is that i have only 22 lines.. line number 23 is empty...
Can someone help me with that?
Thanks.
A parenthesis is missing in the last line.
print(tn.read_all())
print(tn.read_all().decode('ascii'))
Try this.