Traceroute Implementation on Python - python

So I've been trying to understand how this code works using Scapy on Python as I am trying to create a similar traceroute for my project. However, this does not work. I tried printing the reply type and it shows '11' in between hops. Does anyone have any suggestions on how to fix this or does this whole thing just not work?
hostname = "172.217.17.46" #Change that to user input later
print("Destination: " + hostname)
for i in range(1,28):
pkt = IP(dst=hostname, ttl=i)/ UDP(dport=33434)
#packet is sent
reply = sr1(pkt, verbose=0)
#print(reply.type)
#No reply
if reply is None:
print("hi")
break
elif reply.type == 3:
#reached
print("Done", reply.src)
break
#continue
else:
#print(reply.type)
print ("%d hops away: " %i, reply.src)
#continue
break

Related

python looping in list

need some help on looping the all the list and print the list name
currently i have few raspberry pi type and windows PC, i want to ping all the pi and windows and get respond
below are some of what i have tried
question is how to loop, piserver, pi2b,pi2,pi3,pi4 and windows
import platform
plat = platform.system()
piservers = {"10.10.10.115", "10.10.10.125", "10.10.10.135", "10.10.10.145", "10.10.10.165", "10.10.10.175", "10.10.10.185"}
pi2b= {"10.10.10.111", "10.10.10.112", "10.10.10.113", "10.10.10.114"}
pi2 = {"10.10.10.121", "10.10.10.122", "10.10.10.123", "10.10.10.124"}
pi3 = {"10.10.10.131", "10.10.10.132", "10.10.10.133", "10.10.10.134"}
pi4 = {"10.10.10.141", "10.10.10.142", "10.10.10.143", "10.10.10.144"}
Windows = {"10.10.10.151", "10.10.10.152", "10.10.10.153", "10.10.10.154"}
for vm in piservers :
# Check for Windows and Linux Platforms
if plat == "Windows":
response = os.system("ping -n 1 " + vm)
pass
elif plat == "Linux":
response = os.system("ping -c 1 -W 3 " + vm)
pass
#and then check the response...
if response == 0:
print ("***********************************")
print(vm, 'is UP!')
print ("***********************************")
print ("\n")
elif response == 2 or 256 or 512:
print ("***********************************")
print(vm, 'is DOWN and No response from Server!')
print ("***********************************")
print ("\n")
else:
print ("***********************************")
print(vm, 'is DOWN!')
print ("***********************************")
print ("\n")
If you want to loop through all the sets at once, you can do:
for vm in piservers|pi2b|pi2|pi3|pi4|Windows:
Update
To get the server list name, write a function like this:
def get_server(ip):
servers = ['piservers', 'pi2b', 'pi2', 'pi3', 'pi4', 'Windows']
for server in servers:
if ip in eval(server):
return server
return ''
Use this function where ever you need to show the list name.
for example:
get_server('10.10.10.151')
'Windows'
get_server('10.10.10.133')
'pi3'
In your case, the code will look like this,
get_server(vm)
In your elif statement, it should be:
elif response == 2 or response == 256 or response == 512:

Pexpect Brute Force, Python 2.7

I've written a program that connects to a server on port 80, the goal being to brute force the login to gain access to the files inside.
I'm using john.txt as my password list, I know this list contains the password I need. When I run the program, it starts to attempt different passwords, but it's only testing every 3rd password in the list.
Here's my code:
import pexpect
password_list = 'john.txt'
passwords = open(password_list)
child = pexpect.spawn('nc 83.212.97.72 80')
for x in passwords.readlines():
ans = child.expect(['Login:', 'Password:', 'Login Incorrect', 'Too many failed attempts', 'Welcome max'])
if ans == 0:
child.sendline('max')
elif ans == 1:
child.sendline(x)
print 'Attemping {}'.format(x)
elif ans == 2:
child = pexpect.spawn('nc 83.212.97.72 80')
elif ans == 3:
child = pexpect.spawn('nc 83.212.97.72 80')
elif ans == 4:
print 'Login completed, welcome max'
As far as I can tell, there's no Syntax errors in my code, does anyone know why the program is only testing every 3rd password in john.txt?

Ping until success check in Python, then break assign variable

I have the following piece of Python 2.7 code:
def getGateway():
""" Use the configuration to determine valid gateway
If more GWs are present, one will be chosen by random.choice
"""
localServer = ThisLocalServer(log=LOG)
gw=localServer.getRandomAgentGateway()
print "See if its a string %s - %s" % (gw,type(gw))
candidate = "gw"
response = os.system("ping -c 1 " + candidate)
if response == 0:
print candidate, 'is up!'
return gw
else:
print candidate, 'is down we need a new gatewuy'
The use case is as follows:
My software determines an IP using getRandomAgentGateway. Unfortunately it is not as inteligent as i want it to be and sometimes the result is an unreachable IP. I want to build in a ping check that will :
A) Get one IP ( there are only two in the list ) using the already built in getRandomAgentGateway
B) Ping the IP
C) Make sure this IP is reachable , if yes - deliver a reachable IP, break out of the loop and execute "return gw" , if not - stay in the loop and call "getRandomAgentGateway()" again until it finds a reachable IP
I cannot modify getRandomAgentGateway, so i would like to build the ping check here. Any assistance will be highly appreciated.
It seems that you have an error in your logic.
candidate = "gw"
seems to be doing the wrong thing. What you need is probably
if isinstance(gw,str):
# do whatever
Actually, why getRandomAgentGateway will return other answer than an str?
Finally, for this to work you probably should try more than one time, writing something like:
def teste():
max_number_of_tries = 2
current_try = 0
while current_try < max_number_of_tries:
gw=getRandomAgentGateway()
if isinstance(gw,str):
response = os.system("ping " + gw)
if response == 0:
print( gw, 'is up!')
return gw
else:
print( gw, 'is down we need a new gatewuy, trying again')
current_try += 1
print ( "Too much tries" )

Parallel While loops

I am writing a Python program, and I want to run two while loops at the same time. I am pretty new to Python, so this could be a elementary mistake/misconception. The project is having a Raspberry Pi monitor a sump pump to make sure that it is working, and if not, send an email to the specified recipients. One loop is going to interact with the user, and respond to commands send to it in real time through SSH.
while running is True:
user_input = raw_input("What would you like to do? \n").lower()
if user_input == "tell me a story":
story()
elif user_input == "what is your name":
print "Lancelot"
elif user_input == "what is your quest":
print "To seek the Holy Grail"
elif user_input == "what is your favorite color":
print "Blue"
elif user_input == "status":
if floatSwitch == True:
print "The switch is up"
else:
print "The switch is down"
elif user_input == "history":
print log.readline(-2)
print log.readline(-1) + "\n"
elif user_input == "exit" or "stop":
break
else:
print "I do not recognize that command. Please try agian."
print "Have a nice day!"
The other loop will be monitoring all of the hardware and to send the email if something goes wrong.
if floatSwitch is True:
#Write the time and what happened to the file
log.write(str(now) + "Float switch turned on")
timeLastOn = now
#Wait until switch is turned off
while floatSwitch:
startTime = time.time()
if floatSwitch is False:
log.write(str(now) + "Float switch turned off")
timeLastOff = now
break
#if elapsedTime > 3 min (in the form of 180 seconds)
elif elapsedTime() > 180:
log.write(str(now) + " Sump Pump has been deemed broaken")
sendEmail("The sump pump is now broken.")
break
Both of these functions are critical, and I want them to run in parallel, so how do I get them to run like that? Thanks for everyone's help!
Stuff running in parallel? Try using threading - see for example this module in the standard library, or the multiprocessing module.
You will need to create a thread for each of the while loops.
This post has some good examples of how to use threads.
On some other notes, I can't help noticing you use if variable is True: instead of if variable: and if variable is False: instead of if not variable:, the alternatives given being more normal and Pythonic.
When you do elif user_input == "exit" or "stop": this will always be true because it is actually testing if (use_input == "exit") or ("stop"). "stop" is a non-empty string, so it will always evaluate to True in this context. What you actually want is elif user_input == "exit" or user_input == "stop": or even elif user_input in ("exit", "stop"):.
Finally when you do log.write(str(now) + "Float switch turned off") it would probably better to do string formatting. You could do log.write("{}Float switch turned off".format(now)), or use % (I don't know how to do that since I only used Python 2.x for a few weeks before moving to 3.x, where % has been deprecated).

Skype4py !command with arguments

I currently have a skypebot which replies to commands and pings websites when I use the following code:
if Status == 'SENT' or (Status == 'RECEIVED'):
if Message.Body.lower() == '!ping google':
ping = os.system("ping google.com")
if ping == 0:
Message.Chat.SendMessage("Online!")
else:
Message.Chat.SendMessage('Offline!')
This works and if the website is online it will display Online! in chat. However, it requires me to define the website before hand. I have searched for a good few hours now to try to find how I would make it so I can do !ping [website] and allow for the user at any time to use whatever website they want. Any ideas?
I would do something like this:
body = Message.Body
if body.startswith('!'):
parts = body.split() # ['!ping', 'google.com']
command = parts[0][1:] # 'ping'
result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
Message.Chat.SendMessage(result) # Prints out the resulting string
Now, you can define simple functions:
def ping(url):
if os.system("ping " + url) == 0:
return 'Online!'
else:
return 'Offline!'
And add them to a commands dictionary:
commands = {
'ping': ping
}
os.system() is insecure if you're expecting arbitrary user input, so I'd use subprocess.Popen instead (or just try connecting to the website with just Python).
I have a SkypeBot I made as well.
I use http://www.downforeveryoneorjustme.com/
I do it this way:
Functions.py
def isUP(url):
try:
source = urllib2.urlopen('http://www.downforeveryoneorjustme.com/' + url).read()
if source.find('It\'s just you.') != -1:
return 'Website Responsive'
elif source.find('It\'s not just you!') != -1:
return 'Tango Down.'
elif source.find('Huh?') != -1:
return 'Invalid Website. Try again'
else:
return 'UNKNOWN'
except:
return 'UNKNOWN ERROR'
And for commands.py
elif msg.startswith('!isup '):
debug.action('!isup command executed.')
send(self.nick + 'Checking website. Please wait...')
url = msg.replace('!isup ', '', 1)
url = functions.getCleanURL(url)
send(self.nick + functions.isUP(url))
Of course with "import functions" in the commands.py file.
I'm sure you can alter this a bit to work to check a website's status for your bot as well.
Good luck :)

Categories

Resources