Play from zero single row Python security Programming (II)

Source: Internet
Author: User
Tags ack python script

Transferred from: http://www.secpulse.com/archives/35893.html

All say Python Dafa is good, as a qualified security practitioners, not a few scripting languages are embarrassed to say that they are engaged in the security industry.

And Python is the easiest scripting language to get started, and in order not to cause the programmer World War, we don't say that Python is the best language in the world and none of it.

This is the second chapter in the "Zero single row of play to Python safe programming". First article see Safety Pulse < play from zero single row Python security Programming (I) >


This tutorial continues to demonstrate some basic Python scripting concepts. We convert our code into a script, function, class, and System module.

The script structure of Python:

The following is a script that you can use to start Python.

We started by "#!/usr/bin/env Python" to tell the operating system (OS) which compiler (interpreter) to use.
Then we declare a main function "Def main ()" and the last 2 lines of code to let main () run first. Other features that you can define in the script make the code easier to understand and modify:

#!/usr/bin/pythonimport <module1>,<module2> def myFunction (): def main ():        myFunction () if __name__== " __MAIN__ ":        Main ()

Function Functions

One common way to take advantage of a function is to have a piece of code that performs some action and returns output. Here are some basic code demos for this concept:

# Declare Function/setup logicdef MyFunction:  ...  Return output #Call The function from Main:def main ():  output = MyFunction (input)

Class (classes):

The Python class (classes) may seem confusing at first because it is a different way to design your code.
If you grasp the concept of a definition, you can logically group (logical grouping) the data and definitions (definition) of the class.
Such a class will have certain attributes (attribute) and methods associated with it. This is called object-oriented programming (object-oriented programming) When you define an object class that can later create the properties that the class will inherit and the methods associated with it.
If this concept is confusing to you, I suggest that you do not care too much about class (classes). You don't actually need to take advantage of the class (classes), but it can make your code less redundant.
Below we will use the "class" keyword to define a new class of "domain".
There are various ways to choose between class codes (various methods within the class code is available) when you need a domain type object (object of type domain).

>>> import os>>> class Domain: ... def __init__ (self, Domain, port, Protocol): # Stores the variabled  Passed inside-variables ... self.port=port ... self.protocol=protocol# defines a         method to build a URL ... def url (self): ... if self.protocol = = ' https ': ...         URL = ' https://' +self.domain+ ': ' +self.port+ '/' ... if self.protocol = = ' http ': ...  URL = '//' +self.domain+ ': ' +self.port+ '/' ... return url# sets up a method to lookup resolve domain to IP using Host command via Os.system ... def lookup: Os.system ("host" +self.domain) ...>>>>>> do Main=domain (' google.com ', ' 443 ', ' https ') >>>>>> dir (Domain) [' URL ', ' __doc__ ', ' __init__ ', ' __ module__ ', ' IP ', ' lookup ', ' Port ', ' protocol ']>>> domain. URL () ' https://8.8.8.8:443/' >>> domain.ip ' 8.8.8.8 ' >>> domain.port ' 443 ' >>> Domain.protocol ' https ' >>> Domain.lookUp () google.com have address 74.125.228.233google.com has address 74.125.228.227google.com have address 74.125.228.232 

As you can see after instantiating an instance of the domain name class, you can run the methods in the class.
Again, this concept can be confusing at first, especially if you have just mastered Python and programming.
You can try to implement a new class in a Python script that you've already written, and I find that this may be an effective way to start mastering the concept.

To process the command line parameter "SYS":

The last module in this introduction touches the SYS module. This allows you to read the CLI given parameter (argument) and pull it into the variable (variable) in the script.
The syntax is very simple, sys.agrv[0] is the name of the script, and given each parameter (argument) in the command line, each parameter is assigned a number.
The following is a simple example:

Import Sysscript = Sys.argv[0]ip = Sys.argv[1]port = Sys.argv[2]print "[+] The script name is:" +scriptprint "[+] the IP i S: "+ip+" and the port is: "+port

When this quick script is called on the command line, a few parameters are added to produce the following output:

~$ python sys.py 8.8.8.8 53[+] The script name is:sys.py[+] The IP is:8.8.8.8 and the port is:53

Continue to explore more Python modules and built-in features as they will allow you to solve the problem much easier as you begin to write more complex code.

-----------------------------------------------------------------------------------------

The next tutorial will introduce the concept of establishing a network connection with Python by building a basic port scanner.

In this tutorial, we will show you how to make a network connection to Python by establishing a basic port scan (scanner) program.

What we will do is to set up a network socket connection over and over using the ip/port combination. In order to do this, we will introduce a new concept, loop (for loop):

>>>>>> for port in range (1000,1024): ...   print "[+] the port is:" +str (port) ... [+] The port is:1000[+] the port is:1001[+] the port is:1002[+] the port is:1003[+] the port is:1004[+] the port is:1005 [+] The port is:1006[+] the port is:1007[+] the port is:1008[+] the port is:1009[+] the port is:1010[+] the port is:1011 [+] The port is:1012[+] the port is:1013[+] the port is:1014[+] the port is:1015[+] the port is:1016[+] the port is:1017 [+] The port is:1018[+] the port is:1019[+] the port is:1020[+] the port is:1021[+] the port is:1022[+] the port is:1023

Note that the code fragment above the for loop has indentation. People usually indent 2 spaces or tabs, but it doesn't matter as long as you're consistent throughout the script.

To make a simple port scanner, we replace the print statement (print statement) with a snippet (code snippet) to establish a socket connection (socket connection).

The following code shows how to use the built-in socket module (built-in socket modules) for socket connection (socket connection):

>>>>>> Import socket>>>>>> s = Socket.socket () >>> s.connect (' 127.0.0.1 ', ') >>> s.send (' Primal Security \ n ') 17>>> banner = S.RECV (1024x768) >>> print Banneropenssh

Above we import the socket module and call the Connect () function to connect to the given IP address and port number.

This establishes a TCP connection (Syn/syn-ack/ack), and we actually use the Send () function to send the data to the specified service and use recv () to print the response (response).

Now, if the port does not open the socket will throw an exception (exception):

>>>>>> S.connect ((' 127.0.0.1 ', $)) Traceback (most recent call last):  File "", Line 1, in?  File "", Line 1, in Connectsocket.error: (111, ' Connection refused ')

This can be solved in a number of ways. Now, we will use a very simple method, using the "try/exclude (except)" Loop (loop), and pass the exception (exception).

>>>>>> Try:   ... S.connect ((' 127.0.0.1 ') ... except:pass...>>>

Please note that there is no "error! "It's a good way to make your code look like they're working O (∩_∩) o~. Now let's use these concepts and make a fast loop (for loop) port (scanner) Scanner:

>>>>>> for port in range (20,25): ...   Try:    ... print "[+] attempting to connect to 127.0.0.1:" +str (port)     ... S.connect ((' 127.0.0.1 ', port)     ... S.send (' Primal Security \ n ') ...     Banner = S.RECV (1024x768)     ... If banner:       ... print "[+] Port" +str (port) + "open:" +banner     ... S.close ()   ... Except:pass ... 17[+] Attempting to connect to 127.0.0.1:20[+] attempting to connect to 127.0.0.1:21[+] attempting to connect to 127.0.0.1 : 22[+] Port open:openssh[+] Attempting to connect to 127.0.0.1:23[+] Attempting-connect to 127.0.0.1:24[+] Attempti ng to connect to 127.0.0.1:25

The basic usage of the "try/exclude (except)" Loop (loop) above shows the exception (exception) thrown by the socket (socket) when the pass port (port) is closed. We also showed how to use a basic conditional statement "if" to just try to print an open port if the port responds to our probe (probe). Another way to create a port scanner is to define a list to include the ports you want to scan with arrays (array), and then loop through this array (array):

>>>>>> ports = [445, 443, 3389]>>> for port in ports: ...   Print Port ... 22445804433389>>>

If we want to process multiple hosts (hosts) at once, we will take advantage of a nested loop (nested for loop). This will involve an outer (outter layer) loop (for loop) that loops through the host loop and then within the loop (inner for loop) through that port (port). Here is a basic example of how to use a nested for loop to create a slightly more complex scanner:

 >>>>>> hosts = [' 127.0.0.1 ', ' 192.168.1.5 ', ' 10.0.0.1 ']>>>>>> ports = [22, 445 , 443, 3389]>>>>>> for host in hosts: ... for port in ports: ... print "[+] Conne Cting to "+host+": "+str (port) ... s.connect ((host, port) ... s.send (' Primal Security \ n ') ... banner = S.RECV (1024x768) ... if banner: ... print "[+] Port" +str (Port) + "open:" +banner ... s.close Pt:pass ... [+] Connecting to 127.0.0.1:22[+] Port [open:openssh[+] connecting to 127.0.0.1:445[+] connecting to 127.0.0.1:80[+] Connec  Ting to 127.0.0.1:443[+] connecting to 127.0.0.1:3389[+] connecting to 192.168.1.5:22[+ [connecting to 192.168.1.5:445[+] Connecting to 192.168.1.5:80[+] connecting to 192.168.1.5:443[+] connecting to 192.168.1.5:3389[+] Connecting to 10.0.0.1 : 22[+] Connecting to 10.0.0.1:445[+ "connecting to 10.0.0.1:80[+]" Connecting to 10.0.0.1:443[+ "Connecting to 10.0.0.1:338 9 

As you can see through the output, it loops the array of hosts (hosts array) and tries each port in the port array (ports array) and then moves to the next host. For the final port scanner, you may want to modify the print report to print only those ports that are open.

At the end of the day, you will find that Nmap is still a better choice for port scanning, but in future blog posts we will build on these concepts to complete some more practical use cases. Take some time to explore the various features available in the socket module, "DIR (socket)".

"Original: 0x0-python-tutorials-getting-started-pt2 && 0x1–port Scanner translation: safety pulse DIM7 Reprint please specify from the safety pulse sharing technology enjoy quality"

Play from zero single row Python security Programming (II)

Related Article

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.