Using pexpect to automate IP validations - python

My end goal is to log into a switch, get the CDP neighbor details written to a file. parse out the IP addresses and run pings on the IP address and output that to a file. I've searched the forums and found nothing really pertaining to switches. Mainly servers, and I've adapted from there. But Now I am stuck.
I get as far as getting logged into a switch and my login prompts seem to be written to a file but nothing else.
Please excuse errors in the code. Also, the second try block is a work in progress. I am new to python and learning as I go. I am open to any and all critiques and suggestions. I want to know what I have done incorrectly, fix it, and build from there.
Thanks in advance!
import pexpect
import getpass
import sys
import re
import os
import time
try:
switch = raw_input("Host: ")
un = raw_input("Username: ")
pw = getpass.getpass("Password: ")
options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
prompt = "#"
connection_string = ("ssh %s#%s %s" % (un,switch,options))
child = pexpect.spawn(connection_string, timeout=5)
file_output = open('switch_output.txt','wb+')
child.logfile = file_output
rva12 = "";
child.expect(re.escape("password:"))
time.sleep(1)
child.sendline(pw)
time.sleep(1)
child.expect(prompt)
time.sleep(1)
child.sendline("no page")
time.sleep(1)
child.expect(prompt)
child.sendline("show cdp nei det")
time.sleep(1)
child.expect(prompt)
child.before
file_output.close()
except Exception as e:
print("Failed on login")
print(sys.exc_info()[0].__name__,
os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
sys.exc_info()[2].tb_lineno)
print(e)
try:
f = open('switch_output.txt', 'r')
pattern_one = re.compile('.*A\d\n|\:\s\d{2,}\.\d{2,}\.\d{1,}.\d{1,}?')
for line in f:
matches = []
if pattern_one.search(line):
matches.append(line.split(':', 1)[-1].strip())
mp = re.compile('\d{2,}\.\d{2,}\.\d{1,}.\d{1,}')
with open('MDF1.txt', 'wb+') as file:
for match in matches:
if mp.search(match):
file.write(match+'\n')
file.close()
for line in open('MDF1.txt','r'):
child.expect(prompt)
child.sendline('ping '+ line)
time.sleep(10)
except Exception as e:
print(sys.exc_info()[0].__name__,
os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
sys.exc_info()[2].tb_lineno)
print(e)

Related

Python 3 Print output from try statement on the same line and I am trying to learn threading

import os
import time
import threading
import urllib.request
def message(msg):
print(time.strftime('[%H:%M:%S]'), msg)
def check(proxy):
proxy_support = urllib.request.ProxyHandler({'https':proxy})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
message("Trying => "+proxy)
try:
urllib.request.urlopen("https://www.google.com", timeout=5)
print("Working")
with open("CheckedProxies.txt", "a") as appe:
appe.write(proxy.replace("\n","") + "\n")
except:
print("Not Working")
pass
try:
proxies = open("/home/zion/Desktop/proxies.txt", "r").readlines()
except:
message("File Empty Exiting!")
exit()
if proxies == "":
print("File Empty, Enter Proxies")
newtxt = open("CheckedProxies.txt","w")
message("~ Loading "+ str(len(proxies)) +" Proxies!")
time.sleep(1)
for proxy in proxies:
check(proxy)
os.exit(CTRL-C)
message("Done Checking Proxies!")
I am trying to get the Not working to print on the same line as Trying proxy....my current output is:
[23:20:51] ~ Loading 1598 Proxies!
[23:20:52] Trying => 1.0.135.34:8080
Not Working
[23:20:53] Trying => 1.10.236.214:8080
Not Working
[23:20:53] Trying => 103.122.255.18:8080
I am trying to get it to print like this
[23:20:53] Trying => 127.0.0.1:8080 Not Working!
I have tried to "print("Not Working", end='')"
but it prints out like this``
Not Working[23:07:30] Trying => 1.10.236.214:8080
I am not sure how to get the Not working to print after the trying and proxy....
I am also trying to learn how to use the threading module but am having trouble....
I want my program to open multiple threads testing my proxys... thank you in advance for any help.
In regards to threading, the best way to do it here is to use a Multiprocessing Pool.
from multiprocessing import Pool
And then instead of:
for proxy in proxies:
check(proxy)
Use:
p=Pool(5)
p.map(check,proxies)
For making them all on one line, I would add the outputs to a string, then at the end of the function print it out.
Regarding the printing, it seems that you want to print without an automatic newline and you have worked out to use end
print("Hello ", end = '')
print("World! ")
you say
I have tried to "print("Not Working", end='')" but it prints out like
this``
but it seems to me that the problematic print() is in
def message(msg):

Retry urllib request on exception

I have a very small and simple python script on my raspberry, it works well for as long as there is an active Wi-Fi connection. The raspberry is connected to a mobile hotspot and it's possible it will lose it's connection as it could get out of range. As soon as this happens it throws an exception and ends the request "while" loop.
I was hoping to get more information to how i can make this script pause or "ignore" the exception so it goes back into the loop as soon as the connection is restored.
import urllib
import serial
from time import sleep
link = "http://myurl/"
while True:
f = urllib.urlopen(link)
myfile = f.read()
print myfile
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write(myfile)
sleep(3)
You can try something called, (obviously) a try statement!
Within your while loop, you can use a try: except block to make sure that even if your code does't execute (your pi loses connection or something else weird happens) you won't end the program!
This type of code would look like this:
import urllib
import serial
from time import sleep
link = "http://myurl/"
while True:
try:
f = urllib.urlopen(link)
myfile = f.read()
print myfile
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write(myfile)
sleep(3)
except:
sleep(3) #If the code executed in the try part fails, then your program will simply sleep off 3 seconds before trying again!

Python requests exceptions timeout

I wrote a python script like this:
#!/usr/bin/python
import sys
import requests
if len(sys.argv) != 2:
print "Usage: python %s <IP-LIST>" % (sys.argv[0])
sys.exit();
InputFile = sys.argv[1]
try:
File = open(InputFile)
for ip in File:
IP = ip.rstrip()
out = requests.get("http://" + IP, timeout=5)
out.status_code
except (KeyboardInterrupt, SystemExit):
print "\nKeyboardInterruption with Ctrl+c signal"
except IOError as e:
print "The file \"%s\" does not exist!" % (sys.argv[1])
When url has nothing to respond the following output appears for me:
The file "list.txt" does not exist!
Why?
requests uses exceptions that subclass IOError, which you are catching and assuming to be file not found. If you were using Python 3 you could catch the more specific FileNotFoundError. Here you should put an except requests.RequestException block above your except IOError block (or break it out into specific requests errors if you want.

Python GI Notify How can I call the Gtk.main()?

I'm trying to create a Python notification application. To make it short here is what I wanted to do :
1. Checking my gmail account
2. Display a notification with the number of unread mails
3. Display a button that permits me to open chromium (using a system call)
For now everything looks just fine. The checking mail part was kind of easy. I serialised my unread mail count so that the notification doesn't show up every single minute. It only displays if I have a new mail.
Where I'm blocking is that I don't know how to create the main gtk loop so that I can handle the button signal.
Here is my code :
#!/usr/bin/python
from gi.repository import Notify, Gtk, GLib
from urllib.request import FancyURLopener
from datetime import datetime, date, time, timedelta
import os.path, sys, getopt
from subprocess import call
serialisedvalue=0;
serialiseddate=0;
def callback():
call(["chromium", "gmail.com"])
def serialise(unread):
try:
f = open("mailcount", "w")
try:
f.write(unread+"\n") # Write a string to a file
f.write(datetime.now().strftime('%b %d %Y %I:%M%p'))
finally:
f.close()
except IOError:
pass
def deserialise():
global serialisedvalue
global serialiseddate
try:
f = open("mailcount", "r")
try:
serialisedvalue = f.readline().rstrip()
serialiseddate = datetime.strptime(f.readline(), '%b %d %Y %I:%M%p')
finally:
f.close()
except IOError:
pass
def notif(unread):
Notify.init ("New Mail")
if unread != "1":
Hello=Notify.Notification.new ("New mail","You have "+unread+" unread mails","/usr/share/icons/Faenza/actions/96/mail-forward.png")
else :
Hello=Notify.Notification.new ("New mail","You have "+unread+" unread mails","/usr/share/icons/Faenza/actions/96/mail-forward.png")
Hello.add_action('action', 'Read', callback, None, None)
Hello.show ()
def main(argv):
notify=0
forced=0
try:
opts, args = getopt.getopt(argv,"nf",['notify','force-notify'])
except getopt.GetoptError:
print("unreadgmail.py [-n --notify] [-f --force-notify")
sys.exit(2)
for opt,args in opts:
if opt in ("-n", "--notify"):
notify=1
elif opt in ("-f","--force-notify"):
forced=1
url = 'https://%s:%s#mail.google.com/mail/feed/atom' % ("myaccount", "mypassword")
opener = FancyURLopener()
page = opener.open(url)
contents = page.read().decode('utf-8')
ifrom = contents.index('<fullcount>') + 11
ito = contents.index('</fullcount>')
unread = contents[ifrom:ito]
print("Unread messages : "+unread)
if notify==1 and forced==0:
if os.path.exists("mailcount"):
deserialise()
else:
serialise(unread)
deserialise()
if unread != "0":
if unread != serialisedvalue:
notif(unread)
serialise(unread)
elif ((datetime.now() - serialiseddate) > timedelta(hours=1)):
notif(unread)
if forced==1:
notif(unread)
GLib.MainLoop().run()
if __name__ == "__main__":
main(sys.argv[1:])
I remember that my notifications used to work fine with pygtk and pynotify. Though I want to update my code and since I lost the last code, I don't have a clue on that. Calling Gtk.main() in my main just block the program until I kill it.
I'm using Gnome3.6, Archlinux and python3.3.
So does anyone know how to "wait" for the signal handler to be clicked before the program ends ? In fact it runs fine, but the script just end when the notification is displayed and it doesn't wait for the signal.
Thanks a lot :)
EDIT : A bit more details of my problem :
As you can see, the program already ended and is not waiting for a signal. That's what I'm trying to solve right now.
If you're not using GTK+--which as far as I can tell you aren't--you could probably call GLib.MainLoop().run() at the end of your main function to keep your program running.

connect telnet with python

I tried to connect bbs with python's library "telnetlib", try to make a robot to answer
the message. While I answered the message,the robot return more than 1 message.These are my
code.
# -*- coding: cp950 -*-
import telnetlib,random
#f= open("ans.txt","r")
ans = [b"oao", b"xd"]
'''while True:
line = f.readline()
if line = "":
break
ans.append(line)
'''
tn = telnetlib.Telnet("ptt.cc")
tn.read_very_eager()
tn.write(b"*****\r\n") # this is where i enter my username
tn.read_very_eager()
tn.write(b"*****\r\n") # this is wher i enter my password
tn.read_very_eager()
tn.write(b"\r\n")
while True:
if tn.read_very_eager() != "" :
tn.write(b"")
tn.read_very_eager()
tn.write(b"su\r\n")
tn.read_very_eager()
tn.write(b"\r\n")
tn.read_very_eager()
tn.write(b"\r\n\r\n←")
tn.read_very_eager()
tn.read_very_eager()
for i in range(0,1000000):
x = 1
First, I have absolutely no experience with telnet.
Looking at the Python documentation on telnetlib I can see some differences between your code and the example at the bottom of the docs page. The major difference is they wait for a prompt to log-in or provide a password. Even if your read_very_eager should do the same thing, it's more clear to read_until. It could solve your problem, or give you a hint about it.
Try adapting the example to fit your needs.
import sys
import telnetlib
HOST = 'ptt.cc'
user = 'username'
password = 'pass123'
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
# Do anything you need to here.
# If your server will accept these, try them first to isolate the problem
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
As mentioned by MatthieuW, you could sleep with the time library.
from time import sleep
print 'Start'
sleep(1)
print 'One second later'

Categories

Resources