יום שבת, 26 באפריל 2014

Check if tcp port is open using scapy

The simple way to scan the open port
sudo nmap -sS -O 192.168.0.1

The following python script  checks if a port is open using scapy .

import logging
import sys
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
dst_ip = "192.168.0.1"
src_port = 400
dst_port=80
 
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=3)
if(tcp_connect_scan_resp is None):
    print ("The port is Closed")
    sys.exit()
     
print ("The flags:" + str (tcp_connect_scan_resp.getlayer(TCP).flags))    
    
if(tcp_connect_scan_resp.haslayer(TCP)):
    if(tcp_connect_scan_resp.getlayer(TCP).flags == 0x12):
        #send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="AR"),timeout=3)
        print ("The port is Open")
        sys.exit ();
            
#(tcp_connect_scan_resp.getlayer(TCP).flags == 0x14):
print ("The port is Closed ")

notes:
Currently scapy supports only Python 2.7 .
Needed sudo privilege in order to execute script with scapy .

The results:
zvika@ubuntu:~/myStaff/myCode$ sudo python PortsScan.py
Begin emission:
..Finished to send 1 packets.
*
Received 3 packets, got 1 answers, remaining 0 packets
The flags:18
The port is Open


The code is based on :
http://resources.infosecinstitute.com/port-scanning-using-scapy/

Other good references : 
http://theitgeekchronicles.files.wordpress.com/2012/05/scapyguide1.pdf
http://thesprawl.org/research/scapy/
http://thepacketgeek.com/scapy-p-06-sending-and-receiving-with-scapy/

אין תגובות:

הוסף רשומת תגובה