Python Regex Syntax - python

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.

Related

Return string from Python to Shell script

I have Python code like:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
Write your error messages to standard error, to avoid them being captured as well.
Use raw_input, not input, in Python 2.
)
Then your shell
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason not to, always quote parameter expansions.
Just use print instead of return - you bash snippet expects result on STDOUT.

Upper method doesn't make sense

Code:
def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if len(sys.argv) == 1:
print "please input a port"
else:
port = solve_the_input(sys.argv[1])
Input
python test.py 42328
Actual Output:
input port is a558
input port is a558
Expected Output:
input port is a558
input port is A558
I don't know why the upper() method is not working as expected.
The upper method returns new string in uppercase. So use
split_port = split_result[1].upper()
Couple of points
split_port.upper() return is not assigned back to split_port
No need to split on '0x'. You can use replace function instead. Will be less complicated.
Code with replace function:
import sys
def solve_the_input(port):
port = hex(int(port))
result = port.replace("0x",'')
print 'input port is ',result
result = result.upper()
print 'input port is ',result
return result
if __name__ == "__main__":
if len(sys.argv) == 1:
print "please input a port"
else :
port = solve_the_input(sys.argv[1])
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py 1235
input port is 4d3
input port is 4D3
C:\Users\dinesh_pundkar\Desktop>
Upper method returning new string but you need to store that string.
split_port = split_result[1].upper()

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" )

How to pass when variable = null in python 3

so far I have this:
import datetime
f = open("log.txt", "a", encoding='UTF-8')
print ("Log file created")
print ("Enter /close to leave.")
spc = " "
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if msg == None:
pass
if msg == " ":
pass
else:
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
However, this line is not functioning as I want it, it still returns a blank line on the log file:
if msg == None:
pass
I want it to not return anything and simply continue the while loop, How would I fix this?
You should be using
if msg is None:
pass
Edit
You're missing what the pass function is all about. I would re-write your look like so. This way we're only processing this if the msg is not one of the bad input. Once we're done we break out of the loop.
...
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if not msg in [None, " "]
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
break
Evaluation of the rest of the loop will still continue after pass, and as None does not equal " ", this means the block beginning with msg2 = now1+spc+msg+"\n" will be executed. You need to either unite the if ... if ... else into a single if block by changing if msg == " ": to elif msg == " ": or else change if msg == None: pass to if msg == None: continue.
try:
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
except:
pass #example for a function: return None or raise
Your condition doesn't make any sense. The input function will never return None, only strings.
If you want to skip empty strings, a better test would be if not msg (empty strings are "falsy"). Or, if you want to reject any all-whitespace strings, try if not msg.strip() (which removes leading and trailing whitespace before checking if the rest of the string is empty or not).
Further, it's rarely a good idea to write an if statement that just contains pass. Instead, invert the test so that the condition is true for cases where you want to run some code (in this case, when msg is not empty or all whitespace) and simply omit the cases where you'd do nothing:
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if msg.strip(): # msg is not empty or all whitespace
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
One final issue (unrelated to the main question). Python's exit function is primarily intended for use in the interactive interpreter. It is added to the builtins by the site module, and so it won't exist if Python was run with the -S flag. If you want to close the interpreter, you should instead call sys.exit, raise a SystemExit exception, or just run off the end of the main module (a break statement would probably do that for the loop you've shown here, or perhaps a return if you're in a function somewhere).

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