程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Day10: Python nmap module learning and socket module writing simple script

編輯:Python

DAY10:Python-nmap And socket Module write simple script

1、Nmap Four functions :

 The host found
Port scanning
Service version detection
Operating system detection

2、 Basic scanning strategy

2.1、 No additional parameters

Sub situation : If it's a power user , Parameterless scanning is equivalent to sS Parameter scanning (SYN, Half connected, otherwise , Parameterless scanning is equivalent to sT Parameter scanning (TCP, Full connection )

nmap xxx.xxx.x.x

2.2、 redundancy

According to the basic law ,v Parameters usually indicate redundancy . We use two v The parameter indicates that the printout of the original of the detection process .

nmap -vv xxx.xxx.x.x

2.3、 Specify port number

here p The parameter indicates the port , There is no space between the port numbers followed by the standard writing . But it doesn't matter if you write a space .4

nmap -p22 xxx.xxx.x.x
nmap -p 1-200 xxx.xxx.x.1 #-p Parameters # Specify port range scanning

2.4、 Operating system detection

There are two parameter options for operating system detection , One is the parameter O, The second is parameters A, The latter is a redundant version of the former . More use A Parameters , To get more information .

nmap -O xxx.xxx.x.x
nmap -A xxx.xxx.x.x

2.5、 Only host discovery

There are dozens of ways to discover hosts , But the most commonly used is sn Parameters , It said “ Use ping Scan to detect surviving hosts , Without port scanning ”.

[email protected]:~# nmap -sn xxx.xxx.x.x
Nmap scan report for xxx.xxx.x.x
Host is up (0.00034s latency).
MAC Address: xx:xx:xx:xx

2.6、 Skip host discovery

Sometimes the host of the other party opens the firewall ( It's natural ), You may have filtered out the messages you sent ICMP Protocol packet , So if you want to use sn Parameter for host discovery is useless , The results are also unreliable . So you have to use Pn Parameters , It assumes all goals IP All alive , And scan ports one by one , You know, this will cost some time .

nmap -Pn xxx.xxx.x.x

2.7、 Scanning and version number detection

This option determines open services by detecting open ports , And try to detect its version . although A Options can also be done , But check the open service version ,sV It must be the most appropriate .

nmap -sV xxx.xxx.x.x

2.8、UDP scanning

Our previous scans were all aimed at TCP Of , Some services are built on UDP Agreement on the . such as NTP(123 port )、SNMP(161 port ) Etc , Must use UDP Scan the protocol .

nmap -sU xxx.xxx.x.x

3、python-nmap

​ Two common classes

3.1、PortScanner() class

Implemented a nmap Encapsulation of the port scanning function of the tool

Class PortScanner(object):
def get_nmap_last_output # Return text output ( It can be used for debugging )
def nmap_version(self) # Check nmap Version information for 
def listenscan(self,host='127.0.0.1') # No scanning , But parse a target host and return a list 
import nmap
nm=nmap.PortScanner()
nm.scan('www.baidu.com','22,80,443,8080','-sV')
def all_hosts(self) # Returns the target as a list ip
nm.all_hosts()
def command_line(self) # Return the input command line 
def scaninfo() # return nmap Scan the information , The format is dictionary type 
nmscaninfo()
def scanstats() # Returns the scan state as a structure 
def has_host(self,host) # If the host responds, it will return true
nm['14.215.177.38'].all_tcp() # Return scan TCP Protocol port information 
nm['14.215.177.38'].hostname() # Return to domain name 
nm['14.215.177.38'].state() # Return to the target host status 
nm['14.215.177.38'].all_protocols() # Return to scan protocol 

3.2、PortScannerHostDict() class

Realize the storage and access of the scanning results of the host

Class PortScannerHostDict(object):
hostname(self)
hostname()
tcp()
all_protocols()
hostname(self) # Return the hostname of the scanned object 
nm['192.168.1.22'].hostname()
u'SN2013-08-022'
state(self) # Return the status of the scanned object , Include 4 States (up、down、unknown、skipped)
nm['192.168.1.22'].state()
u'up'
all_protocols(self) # Return to the scanned Protocol 
nm['192.168.1.22'].all_prococols()
[u'tcp']
all_tcp(self) # return TCP Port scanned by protocol 
nm['192.168.1.22'].all_tcp()
[22,80]
tcp(self,port) # Return scan TCP Scanning protocol port( port ) Information about 
nm['192.168.1.22'].tcp(22)
{
'state': u'open','reason':u'syn-ack','name':u'ssh'}

4、socket modular

4.1、socket()

Socket , Applications usually use sockets , To send a request to the network or answer a network request , To enable communication between hosts or processes on a computer

grammar :

socket.socket([family[, type[, proto]]])
family # Socket family can make AF_UNIX perhaps AF_INET.
type # Socket types can be classified into connection oriented or connectionless SOCK_STREAM or SOCK_DGRAM.
protocol # Generally speaking, we don't think that 0.

4.2、Socket object ( The built-in ) Method

''' Client socket '''
s.connect() # Active initialization TCP Server connection ,. commonly address The format of is tuple (hostname,port), If there is a connection error , return socket.error error 
''' Server socket '''
s.listen() # Start TCP monitor .backlog Specify before rejecting the connection , The maximum number of connections that the operating system can suspend . The value is at least 1, Most applications are set to 5 Can 
s.accept() # Passive acceptance TCP Client connection ,( Blocking type ) Waiting for the connection 
s.bind() # Binding address (host,port) To socket , stay AF_INET Next , In tuples (host,port) Represents the address in the form of 
''' Socket functions for public use '''
s.close() # Close socket 
s.recv() # receive TCP data , The data is returned as a string ,bufsize Specifies the maximum amount of data to receive 
s.send() # send out TCP data , take string The data in is sent to the connected socket 
s.close() # Close socket 
s.getsockname() # Returns the socket's own address . It's usually a tuple (ip,port)
s.gettimeout() # Returns the value of the current timeout period , Company ( second ), If the timeout period is not set , Then return to None

4.3、Internet modular

''' Network protocol Function, use port python modular '''
HTTP Web access 80 httplib, urllib, xmlrpclib
NNTP Read and post articles 119 nntplib
FTP File transfer 20 ftplib, urllib
SMTP Send E-mail 25 smtplib
POP3 Receiving mail 110 poplib
IMAP4 Get mail 143 imaplib
Telnet Command line 23 telnetlib
Gopher Information search 70 gopherlib, urllib

Example :

1、 Determine whether the host is alive

import nmap
nm = nmap.PortScanner()
nm.scan(hosts = '172.17.2.0/24', arguments='-n -sP -PE')
up_hosts = nm.all_hosts() # Get the list of surviving hosts 
print(up_hosts)

2、 Single IP scanning

import nmap # Import nmap.py modular 
nm = nmap.PortScanner() # obtain PortScanner object 
nm.scan('127.0.0.1', '22-443') # Scan host 127.0.0.1 Port number 22-443
nm.command_line() # Get the command line for scanning :nmap -oX - -p 22-443 127.0.0.1
nm.scaninfo() # Get the information of this scan {'tcp': {'services': '22-443', 'method': 'connect'}}
nm.all_hosts() # Get all scanned hosts 
nm['127.0.0.1'].hostname() # obtain 127.0.0.1 The host name 
nm['127.0.0.1'].hostnames() # obtain list Format host name dict 127.0.0.1 # Such as [{'name':'hostname1', 'type':'PTR'}, {'name':'hostname2', 'type':'user'}]
nm['127.0.0.1'].state() # Access to the host 127.0.0.1 The state of (up|down|unknown|skipped)
nm['127.0.0.1']['tcp'].keys() # Get all tcp port 
nm['127.0.0.1'].all_tcp() # Get all tcp port ( sorted )
nm['127.0.0.1'].all_udp() # Get all tcp port 
nm['127.0.0.1'].all_ip() # Get all tcp port 
nm['127.0.0.1'].all_sctp() # Get all tcp port 
nm['127.0.0.1'].has_tcp(22) # Whether it contains the host 127.0.0.1 Of 22 Port information 
nm['127.0.0.1']['tcp'][22] # Access to the host 127.0.0.1 22 port (tcp) All the information about 
nm['127.0.0.1'].tcp(22) # Access to the host 127.0.0.1 22 All information about the port 

3、 Host survival scanning and help manual

import nmap
import optparse
def NmapScan(targetIP):
nm=nmap.PortScanner() # Instantiation PortScanner object 
try:
result=nm.scan(hosts=targetIP,arguments='-sn -PE ') #hostse Target IP Address ,arguments by nmap Scan parameters -sn: Use ping scan -PE: Use icmp Of echo Request package 
state=result['scan'][targetIP]['status']['state'] # Slice the scanning results Extract host scanning information 
print("[{}] is [{}]".format(targetIP,state))
except Exception as e:
pass
if __name__=="__main__":
parser=optparse.OptionParser('usage:python %prog -i ip \n\n'
'Example:python %porg -i 172.16.0.172[172.16.0.1-200]\n')
parser.add_option('-i','--ip',dest='targetIP',default='172.16.0.1',type='string',help='target ip address')
options,args=parser.parse_args() # Add target ip Parameters -i
if '-' in options.targetIP:
for i in range(int(options.targetIP.split('-')[0].split('.')[3]),int(options.targetIP.split('-')[1])+1):
NmapScan(options.targetIP.split('-')[0] + '.' + options.targetIP.split('.')[1] + '.' + options.targetIP.split('.')[2]) + '.' + str(i)
else:
NmapScan(options.targetIP)
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", 80))
if result == 0:
flag = True
else:
flag = False

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved