SecureCRT python scripting - python

I'm writing a script that will find out what router model and what IOS version a Cisco router is using. I'm writing it in Python using the SecureCRT api. The script sends a show version command that displays information about the router, including the information I need. I then use the SecureCRT api to pull all of that text from the application screen and then I iterate through the text to and use if statements to match router models to see which one it is. Everytime i run the script it runs and doesnt error out but the "new.txt" file is blank.
# $language = "python"
# $interface = "1.0"
crt.Screen.Synchronous = True
ModelIOSScreen = ""
def Main():
ModelIOS()
def ModelIOS():
crt.Screen.Send("show version" + chr(13))
crt.Screen.WaitForString(">")
Screen = crt.Screen.Get(-1, 1, 50, 70)
ModelIOSScreen = str(Screen.split(" ", -1))
RouterModel = ""
for word in ModelIOSScreen:
if word == "2811":
RouterModel = "2811"
elif word == "2801":
RouterModel = "2801"
elif word == "CISCO2911/K9":
RouterModel = "2911"
file = open("new.txt", "w")
file.write(ModelIOSScreen)

I'm on my phone and could probably write a better answer, but I'm about to go to bed. You never close the file you open. Using the following works better.
with open(file, "w") as fp:
fp.write(variable)

Related

Editing a config file with python

I am building a program that edits a .toml config file, take this for example:
This is one of the sections from the entire .toml config file:
[APU]
apu = "any" # Audio system. Use: [any, nop, sdl,xaudio2]
Normally the users changes the options manually for example if they want to change the apu they just replace the any inside quotation marks ("") with xaudio2 for example.
I want to create a code which presents the setting (apu = " "), and the options that the user has (any,xaudio,nop...)
and let the user choose between the options.
This was the code I originally wrote:
f = open("config.toml", "r")
fread = f.read()
### APU Options ###
nop = fread.replace('apu = "any"', 'apu = "nop"')
sdl = fread.replace('apu = "any"', 'apu = "sdl"')
xaudio2 = fread.replace('apu = "any"', 'apu = "xaudio2"')
### Write the New File ####
with open("config.toml", "w") as f:
f.write(xaudio2)
this code lacks something, when a user changes the apu to xaudio2 with this exact code, after the user re opens the program(this python code) for changing the apu again , the python code can not detect the original code since it was:
apu = "any"
and now after the user has changed it to xaudio2 It will be this:
apu = "xaudio2"
the python code looks only for the apu = "any" to change and replace any with other options.
What do you think is the solution? (when one of the settings in the config changes)

Easier way to simplify?

Trying to write a script to simplify my cisco configs. User inputs names and passwords and the script will add them all together in a line by line document i can copy and paste from.
This is the method i've chosen (very new with python) and was wondering if there was a simpler way with functions or anything else?
hostname = input("Enter Hostname?" '\n')
en_secret = input("Enter Enable Password" '\n')
en_secret_script = "enable secret {}".format (en_secret)
hostname_script = "hostname {}".format(hostname)
script = '\n'.join([hostname_script, en_secret_script])
print(script)
You can get the same result with less line like this:
hostname = input("Enter Hostname?" '\n')
en_secret = input("Enter Enable Password" '\n')
print(f"hostname {hostname} \nenable secret {en_secret}")

Python executable file closes without showing outputs

I created a code that use Google Books API on Jupiter in python language. I would like to create an .exe file in order to use it on other PCs. I did it with pyinstaller name_of_the_script.py, but when I execute it after I entered the second input, the command window disappears without showing outputs, also if I put an input line at the end in order to keep alive the script until I press a key.
Here the code:
import requests
quote = input('Inserisci la citazione: ')
lingua = input('\nInserisci lingua (sigla, ad esempio ''it'' per ''Italiano''): ')
key = 'xxxxxxxxx'
parms = {'q':quote, 'key':key, 'maxResults':5,'langRestrict':lingua}
r = requests.get(url='https://www.googleapis.com/books/v1/volumes', params = parms)
rj = r.json()
for i in range(0,3):
print('\n' + rj['items'][i]['volumeInfo']['title'] + '\n')
for authors in rj['items'][i]['volumeInfo']['authors']:
print(authors)
print('\n' + '\n')
input('press enter to quit')
What is wrong?
I solved!
It was an error in the conversion of the .ipynb file into .py file.
To convert it I used a code found here in SO and now it works.
Here the post that helped me:
Is it possible to generate an executable (.exe) in a jupyter-notebook?

How do I run python '__main__' program file from bash prompt in Windows10?

I am trying to run a python3 program file and am getting some unexpected behaviors.
I'll start off first with my PATH and env setup configuration. When I run:
which Python
I get:
/c/Program Files/Python36/python
From there, I cd into the directory where my python program is located to prepare to run the program.
Roughly speaking this is how my python program is set up:
import modulesNeeded
print('1st debug statement to show program execution')
# variables declared as needed
def aFunctionNeeded():
print('2nd debug statement to show fxn exe, never prints')
... function logic...
if __name__ == '__main__':
aFunctionNeeded() # Never gets called
Here is a link to the repository with the code I am working with in case you would like more details as to the implementation. Keep in mind that API keys are not published, but API keys are in local file correctly:
https://github.com/lopezdp/API.Mashups
My question revolves around why my 1st debug statements inside the files are printing to the terminal, but not the 2nd debug statements inside the functions?
This is happening in both of the findRestaurant.py file and the geocode.py file.
I know I have written my if __name__ == '__main__': program entry point correctly as this is the same exact way I have done it for other programs, but in this case I may be missing something that I am not noticing.
If this is my output when I run my program in my bash terminal:
$ python findRestaurant.py
inside geo
inside find
then, why does it appear that my aFunctionNeeded() method shown in my pseudo code is not being called from the main?
Why do both programs seem to fail immediately after the first debug statements are printed to the terminal?
findRestaurant.py File that can also be found in link above
from geocode import getGeocodeLocation
import json
import httplib2
import sys
import codecs
print('inside find')
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
foursquare_client_id = "..."
foursquare_client_secret = "..."
def findARestaurant(mealType,location):
print('inside findFxn')
#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
latitude, longitude = getGeocodeLocation(location)
#2. Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
if result['response']['venues']:
#3. Grab the first restaurant
restaurant = result['response']['venues'][0]
venue_id = restaurant['id']
restaurant_name = restaurant['name']
restaurant_address = restaurant['location']['formattedAddress']
address = ""
for i in restaurant_address:
address += i + " "
restaurant_address = address
#4. Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
result = json.loads(h.request(url, 'GET')[1])
#5. Grab the first image
if result['response']['photos']['items']:
firstpic = result['response']['photos']['items'][0]
prefix = firstpic['prefix']
suffix = firstpic['suffix']
imageURL = prefix + "300x300" + suffix
else:
#6. if no image available, insert default image url
imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
#7. return a dictionary containing the restaurant name, address, and image url
restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
print ("Restaurant Name: %s" % restaurantInfo['name'])
print ("Restaurant Address: %s" % restaurantInfo['address'])
print ("Image: %s \n" % restaurantInfo['image'])
return restaurantInfo
else:
print ("No Restaurants Found for %s" % location)
return "No Restaurants Found"
if __name__ == '__main__':
findARestaurant("Pizza", "Tokyo, Japan")
geocode.py File that can also be found in link above
import httplib2
import json
print('inside geo')
def getGeocodeLocation(inputString):
print('inside of geoFxn')
# Use Google Maps to convert a location into Latitute/Longitute coordinates
# FORMAT: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY
google_api_key = "..."
locationString = inputString.replace(" ", "+")
url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s' % (locationString, google_api_key))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
latitude = result['results'][0]['geometry']['location']['lat']
longitude = result['results'][0]['geometry']['location']['lng']
return (latitude,longitude)
The reason you're not seeing the output of the later parts of your code is that you've rebound the standard output and error streams with these lines:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
I'm not exactly sure why those lines are breaking things for you, perhaps your console does not expect utf8 encoded output... But because they don't work as intended, you're not seeing anything from the rest of your code, including error messages, since you rebound the stderr stream along with the stdout stream.

gammu receive sms message python fails

I have found a script on this website http://wammu.eu/docs/manual/smsd/run.html
#!/usr/bin/python
import os
import sys
numparts = int(os.environ['DECODED_PARTS'])
# Are there any decoded parts?
if numparts == 0:
print('No decoded parts!')
sys.exit(1)
# Get all text parts
text = ''
for i in range(1, numparts + 1):
varname = 'DECODED_%d_TEXT' % i
if varname in os.environ:
text = text + os.environ[varname]
# Do something with the text
f = open('/home/pi/output.txt','w')
f.write('Number %s have sent text: %s' % (os.environ['SMS_1_NUMBER'], text))
And i know that my gammu-smsd is working fine, because i can turn of my ledlamp on raspberry by sending sms to the raspberry, but my question is why is this script failing? nonthing is happening. and when I try to run the script by it self it also fails.
What I would like to do is just receive the sms and then read the content and save the content and phonenumber which sent the sms to a file.
I hope you understand my issue.
Thank you in advance, all the best.
In the gammu-smsd config file, you can use the file backend which does this for you automatically.
See this example from the gammu documentation
http://wammu.eu/docs/manual/smsd/config.html#files-service
[smsd]
Service = files
PIN = 1234
LogFile = syslog
InboxPath = /var/spool/sms/inbox/
OutboPpath = /var/spool/sms/outbox/
SentSMSPath = /var/spool/sms/sent/
ErrorSMSPath = /var/spool/sms/error/
Also see options for the file backend to tailor to your needs.
http://wammu.eu/docs/manual/smsd/config.html#files-backend-options
Hope this helps :)

Categories

Resources