Safety of eval function

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Safety of eval function

 
0
  #1
Mar 27th, 2006
I keep hearing that the eval() function is unsafe. It is a nice function, because you can use it like
print eval("2.5*49.7/(23+3.14)")
and it will solve the math.

Is there any way to protect against some nasty minded person to enter a "os.system(command)" where the command will erase a file or all files?
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,113
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 944
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Safety of eval function

 
0
  #2
Mar 28th, 2006
Several languages offer the eval() function and its safety is hotly debated. You hear eval() is only one letter away from evil()!

My feelings, if eval() is directly connected to a user input, avoid it!!! This is particularly true for Python's input() function that uses raw_input() and then sends the string to eval() to extract the number. In this case you can't even intercept the input, so if a nasty person enters (don't even try this!!!) "__import__('os').system('del *.*')" you just wiped out all the files on your drive!

If you use raw_input(), then you could check the input string for 'os' or 'system' before sending it to the eval() function. A safe use of eval() would be in a GUI calculator, where the input is limited by the buttons you have supplied.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Safety of eval function

 
0
  #3
Mar 29th, 2006
I will avoid using the input() function then. How would you write a custom numeric_input function using raw_input()?
drink her pretty
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC