The refinement and misuse of Python:eval

Source: Internet
Author: User

The eval () function is powerful, as the official demo interprets the string str as a valid expression to evaluate and return the result of the calculation.

So, combining math as a calculator is very useful.

Other methods of use can convert list,tuple,dict and string to each other. See the following example:

A = "[[up], [3,4], [5,6], [7,8], [9,0]]" B = eval (a) bout[3]: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]type (b) out[4]: lista = "{1: ' A ', 2: ' B '}" B = eval (a) bout[7]: {1: ' A ', 2: ' B '}type (b) out[8]: dicta = "([up], [3,4], [5,6], [7,8], (9,0))" B = Ev Al (a) bout[11]: ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
Not very powerful!

but!

Powerful functions are at the cost. Security is one of its biggest drawbacks.

Think about the use of the environment: users need to enter an expression. and evaluated.

Assume that the user entered maliciously. Like what:

__import__ (' OS '). System (' dir ')
After eval (), you will find that the current folder file is now in front of the user.

Then continue typing:

Open (' File name '). Read ()

The code is given to people.

Gets the completion, a delete command. The file disappears.

Let's cry!

How to avoid security problems?

1, self-written check function;

2. Use Ast.literal_eval: View document by yourself

3, many other good text: Restricted "safe" eval (Python recipe)

This article by @the_third_wave (blog address: http://blog.csdn.net/zhanh1218) original.

There are not covered, will be updated periodically, there are errors please correct me.

If you see this blog post as incomplete, that's why I first announced half of the crawler to prevent it. Please see the original author blog.


Let's say this blog post is helpful to you for a good network environment. not recommended reprint, recommended collection. Suppose you must reprint. Please bring the suffix and the address of this document.


The refinement and misuse of Python:eval

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.