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" )
Related
I created a program that I'm distributing. The program checks for username availability, and after each check a variable named checkedCount gets updated. Each check costs about 4mb or ram, which makes the total memory usage high. For example, I ran the program for about two hours which resulted in 7gb's of ram being in use. I've tried to use clear = lambda: os.system('cls') after each request to clear the terminal, but that didn't work.
Code:
def screen(self):
clear()
print(r"""
/~\
C oo
_( ^)
/ ~\
""")
print(f"""{Fore.LIGHTBLACK_EX}[>]{Fore.RESET} Checks: {self.checkedCount}
{Fore.LIGHTBLACK_EX}[>]{Fore.RESET} Claims: {self.claimedCount}
{Fore.LIGHTBLACK_EX}[>]{Fore.RESET} Errors: {self.errorCount}
""")
def checker(self):
self.proxer = self.proxies()
while True:
self.screen()
[self.usernames.put(line.strip()) for line in open(f"external/{wordlistInput}")]
name = self.usernames.get(); self.usernames.put(name)
url = f"https://public-ubiservices.ubi.com/v3/profiles?nameOnPlatform={name}&platformType=uplay"
if len(name) > 2:
try:
r = requests.get(url, headers=self.headers, proxies=self.proxer)
ctypes.windll.kernel32.SetConsoleTitleW(f"{datetime.now().strftime('%H:%M')} | Developed by gxzs#2979")
if self.checkedCount % 75 == 0:
self.checkedCount += 1
self.proxer = self.proxies()
self.login()
if r.status_code == 200:
self.checkedCount += 1
if len(r.json()['profiles']) != 0:
pass
else:
self.create(name)
else:
with open('external/errors.txt', "a") as errorFile:
errorFile.write(f"{datetime.now().strftime('%H:%M')} | Error message: {r.text}\n")
self.errorCount += 1
self.proxer = self.proxies()
self.login()
except Exception:
pass
Edit: It doesn't seem to be a issue with the variable checkedCount. I removed it from the code and it still happens
I do not know what kind of data struture is self.username and if the .put() method overwrites already existing entries, but if it doesn't then
the line:
[self.usernames.put(line.strip()) for line in open(f"external/{wordlistInput}")]
Will put the content of f"external/{wordlistInput}" at every iteration in your while True: inside self.usernames without ever clearing it's content.
Also you are not exiting the while, I don't know if its intentional.
This is a shot in the dark since there isn't more information available.
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
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:
I have the following function:
def handleRequest(self, command, ident, ip, duration=0):
if not re.match("^[0-9]+$", ident) or not re.match("^[0-9.]+$", ip) or \
(duration and not re.match("^[0-9]+$", duration)):
print ("Unknown command")
return
if command == "DOTHIS":
reactor.callInThread(self.func, ident, "./DOTHIS.sh", ip, 0, command)
elif command == "DOTHAT":
reactor.callInThread(self.func, ident, "./DOTHAT.sh", ip, 0, command)
elif command == "DOTHAT":
reactor.callInThread(self.func, ident, "./DOTHING.sh", ip, duration, command)
elif command == "DOMORETHINGS":
reactor.callInThread(self.func, ident, "./DOMORETHINGS.sh", ip, duration, command)
else:
print ("Unknown command")
return
I use this function to execute certain scripts on my server.
My problem is the correct syntaxis of the to be executed commands (DOTHIS, DOTHAT etc.)
It must have something to do with regex.
The commands can have several parameters (e.g. DOTHIS 127.0.0.1).
No matter how I query the command, the result is always "Unknown Command".
Could anyone give me an example of a command with the right syntaxis (including a couple of parameters).
Thanks!
in handleRequest what are you sample inputs ?
i.e for command, ident?
assuming ip='127.0.0.1', duration ='10'
FYI, This condition always make the output False if the string contains just number.
(duration and not re.match("^[0-9]+$", duration))
This assumes all arguments are strings, but this should work:
import re
def handleRequest(self, command, ident, ip, duration=0):
returnEarly = 0
if not re.match("^\d+$", ident):
print ("Invalid ident")
returnEarly = 1
if not re.match("^[\d.]+$", ip):
print ("Invalid ip")
returnEarly = 1
if (duration and not re.match("^\d+$", duration)):
print ("Invalid Duration")
returnEarly = 1
if returnEarly:
return
if command == "DOTHIS":
print ("DOTHIS")
elif command == "DOTHAT":
print ("DOTHAT")
elif command == "DOTHING":
print ("DOTHING")
elif command == "DOMORETHINGS":
print ("DOMORETHING")
else:
print ("Unknown command")
handleRequest("", "DOTHIS", "11", "127.0.0.1", "10") # works
handleRequest("", "BADCOMMAND", "11", "127.0.0.1", "10") # fails on command
handleRequest("", "DOTHIS", "11C", "127.0.0B.1", "A10") # fails on arguments
I used the "\d" regex shortcut in python for numbers, I also made each check explicit so if it does fail you know why. If you are passing in arguments that are not strings you can use str(argX) to convert it to a string before checking. I used python 2.7 to test this.
EDIT:
I should also point out, that I lazily did not make this method part of a class, and just passed in the empty string for self.
re.match("^[0-9.]+$", number)
matches all strings that contain only numbers.
So you should be able to do:
def handleRequest(self, command = '0', ident = '0', ip = '0', duration='0'):
use help('re') to find out about what the characters mean.
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 :)