Create Server Banner Grabber Using Python Socket

Namaste Friends,


                                           

                                                    Today, I am Going To Show You How To Create Python Script For Banner Grabbing. Or Simple Banner Grabbing Script And How To Use Banner Grabbing Script.


lately, I have not posted any tutorial because of some python projects. for this late, I am really very sorry.

so, let's start today's tutorial


after listening about banner grabbing

the first question comes in our mind is

Q 1. What Is Banner Grabbing?


Ans.

Banner grabbing is a technique used to gain information about a computer system on a network and the services running on its open ports. 

Administrators can use this to take inventory of the systems and services on their network.

now, our second question is


Q 2. How Banner Grabbing Scripts Works?



Ans. Let me explain you in simple sentences, 

Our Banner Grabbing Scripts try to established their connection with servers using a different port. 

and after connection establishment.

 normally, 

every server send a banner.to their client and

 these banners contain information about their services, version, type, etc.. etc

so, collecting all these banner is called banner grabbing.

for e.g:-
we establish a connection to a target web server using Netcat, then send an HTTP request. The response will typically contain information about the service running on the host:
[root@prober] nc www.targethost.com 80
HEAD / HTTP/1.1

HTTP/1.1 200 OK
Date: Mon, 11 May 2009 22:10:40 EST
Server: Apache/2.0.46 (Unix)  (Red Hat/Linux)
Last-Modified: Thu, 16 Apr 2009 11:20:14 PST
ETag: "1986-69b-123a4bc6"
Accept-Ranges: bytes
Content-Length: 1110
Connection: close
Content-Type: text/html

                                             (Example Source: Wikipedia)

So, Let's Start practical Coding.

here, I am going to explain all steps one by one.

first, import modules


#!/usr/bin/python
import socket

second, 

here, I creating a function for capturing banners.



Python Banner Grabbing code: 


def BannerGrabber(ip, port):
    try:
        # Set default timeout
        socket.setdefaulttimeout(2)

        # Create Socket Object
        s = socket.socket()

        # Established Connection With Server
        s.connect((ip, port))

        # Recv Banner
        banner = s.recv(1024)

        # return Banner
        return banner
    # Handle Timeout and connection refuse error
    except:
        return


so, now, I think you all get it how python can grab banners.

so,

now, this is the right time of showing SSB codes of banner grabbing written in python.


Here, I am Sharing My Codes But If You Want More Better Example Then, You Can Modify these codes yourself or Download This Script From My GitHub repository (link given at the end of these codes ).


1. bannergrab.py



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
__author__='''

######################################################
                By S.S.B Group                          
######################################################

    Suraj Singh
    Admin
    S.S.B Group
    surajsinghbisht054@gmail.com
    http://bitforestinfo.blogspot.com/

    Note: We Feel Proud To Be Indian
######################################################
'''

# =================Other Configuration================ 
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.2"
# ====================================================

# Importing Modules
import socket
import time
import threading
import optparse
import sys
import errno

# Port Scanner Engine
class BannerScanner:
    def __init__(self, target, port, thread, timeout):
        self.target=target
        self.port=port
        self.thread=thread
        self.timeout=timeout
        self.store_open_ports=[]
        self.port.reverse()

        # Start Thread
    def get_result(self):
        return self.startthreading()

        # Check Port 
    def checkopenport(self):
        s=socket.socket()
        s.settimeout(float(self.timeout))
        #socket.setdefaulttimeout(float(self.timeout))
        port=self.port.pop()
        storeobj=str(s.connect_ex((self.target, int(port))))
        if storeobj=="0":
            # If Open Port Found
            self.store_open_ports.append(port)
        s.close()
        return 
        

        # Start Threadings
    def startthreading(self):
        listthread=[]
        for i in range(len(self.port)):
            storethread=threading.Thread(target=self.checkopenport)
            storethread.start()
            # Threead Controller
            if int(threading.activeCount())==int(self.thread):
                printingline="\r< IP : {} | Number of Threads : {} | Open Port Checking : {} | Open Ports Founded {} >".format(self.target,str(threading.activeCount()),str(i),str(len(self.store_open_ports)))
                sys.stdout.write(printingline)
                sys.stdout.flush()
                time.sleep(float(self.timeout))
            listthread.append(storethread)

        # Wait For All Thread
        for i in listthread:
            i.join()
        return (self.target, self.store_open_ports)

# Banner Grabbing Class
class BannerGrabber:
    def __init__(self, host, thread, output):
        self.host = host
        self.thread = thread
        self.output = output
        self.banners = []
        self.iter_address()

        # iter All Address
    def iter_address(self):
        starttime = time.time()
        # iter Host Iterms
        for address, port in self.host.iteritems():
            self.start_threading(address, port)
        closetime = time.time()
        print "\n\n",'*'*50,'\n'
        for i in self.banners:
            print "[+] IP : {} | Port : {} | Banner : {}".format(i[0][0],i[0][1],i[1])
        print "\n",'*'*50,'\n'
        print "[+] Scan Started On ", time.ctime(starttime)
        print "[+] Scan Finished On", time.ctime(closetime)            
        print '[+] Total Time Taken ',
        print closetime-starttime, ' Seconds '
        print "\n",'*'*50,'\n'
        print "\n\n Thanks For Using My Program by SSB"
        # if Output File Name Is Provided
        if self.output:
            f = open(self.output, 'a')
            for address, port in self.host.iteritems():
                f.write("{} | {} | {}".format(i[0][0],i[0][1],[i[1]]))
            f.close() 
        return

        # Start threadings
    def start_threading(self, address, port):
        listthread=[]
        for i in port:
            storethread=threading.Thread(target=self.banner_ip, args=(address, i,))
            storethread.start()
            if int(threading.activeCount())==int(self.thread):
                printingline="\r< IP : {} | Number of Threads : {} | Port : {}>".format(address, threading.activeCount(),i)
                sys.stdout.write(printingline)
                sys.stdout.flush()
                time.sleep(float(2))
            listthread.append(storethread)
        # Wait For All Threads
        for i in listthread:
            i.join()
        return

        # Banner Grabbing Functions
    def banner_ip(self,address, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #s.settimeout(10)
        try:
            s.connect((address, port))
            if port==80:
                print "\n[+] HTTP PROTOCOL Founded. IP : {}| PORT : {}".format(address, port)
                #Send some data to remote server
                message = "GET / HTTP/1.1\r\n\r\n"
                s.sendall(message)
                #Now receive data
                self.banners.append([(address, port),s.recv(4096)])
            else:
                self.banners.append([(address, port),s.recv(4096)])
        except socket.error as e:
            if e.errno == errno.ECONNREFUSED:
                pass
            else:
                self.banners.append([(address, port), e])
        s.close()
        return 



# Port Numbers Extractor
def port_extraction(port):
    storeport=[]
    # Verifiying Port Value
    if port:
        # Verifying Port is in Range
        if "-" in port and "," not in port:
            x1,x2=port.split('-')
            storeport=range(int(x1),int(x2))
        # Verifying Port is in Commas
        elif "," in port and "-" not in port:
            storeport=port.split(',')
        elif "," in port and "-" in port:
            x2=[]
            for i in port.split(','):
                if '-' in i:
                    y1,y2=i.split('-')
                    x2=x2+range(int(y1),int(y2))
                else:
                    x2.append(i)
            storeport=x2
        else:
            storeport.append(port)
    else:
        print "[*] Please Provide Ports For Scanning."
        sys.exit(0)
    return storeport



# Port Numbers Extractor
def port_extraction(port):
    storeport=[]
    # Verifiying Port Value
    if port:
        # Verifying Port is in Range
        if "-" in port and "," not in port:
            x1,x2=port.split('-')
            storeport=range(int(x1),int(x2))
        # Verifying Port is in Commas
        elif "," in port and "-" not in port:
            storeport=port.split(',')
        elif "," in port and "-" in port:
            x2=[]
            for i in port.split(','):
                if '-' in i:
                    y1,y2=i.split('-')
                    x2=x2+range(int(y1),int(y2))
                else:
                    x2.append(i)
            storeport=x2
        else:
            storeport.append(port)
    else:
        print "[*] Please Provide Ports For Scanning."
        sys.exit(0)
    return storeport

# Checking About User Input Data is IP Or Host
def valid_ip(ip):
    " Verifying IP Address "
    try:
        socket.inet_aton(ip)
    except socket.error:
        ip=socket.gethostbyname(ip)
    return ip

# Main Function
def main():
    print __author__
    parser=optparse.OptionParser(usage=usage,version=Version)
    parser.add_option('-t','--target',type='string',dest='target',help="Specify Target For Scan", default=None)
    parser.add_option('-i','--input',type='string',dest='input',help="Specify Input Txt File Of Data", default=None)
    parser.add_option("-p","--port",type='string', dest="port", help="Specify Target Ports Seperated by commas or Provide Range of Ports. eg. 80-1200", default=None)
    parser.add_option('-n',"--thread",type='string', dest="thread", help="Specify Number of Thread For Scanning ", default='500')
    parser.add_option('-o',"--output",type='string', dest="output", help="Specify Path For Saving Output in Txt.", default=None)
    parser.add_option('-c',"--check",type='string', dest="check", help="Specify False Or 0 If Provided Open Ports Are Already TESTED. Or if open ports are not verified then, don't use this argument.", default=None)
    parser.add_option('-T','--timeout',type='string', dest="timeout", help="Specify Port Time Out Seconds ",default='2')

    (options, args)= parser.parse_args()

    # Conditions
    if not options.input:
        if (not options.target):
            print "[*] Please Specify Target. e.g: -t 192.168.10.1 or -t www.site.org \n[*]\t\t or Provide Input File. e.g: -i file.txt"
            sys.exit(0)

        if not options.port and not options.port:
            print "[*] Please Specify Ports Seperated by commas or Provide Range of Ports. eg. 80-120,121,122,123-1200 \n[*]\t\t or Provide Input File. e.g: -i file.txt"
            sys.exit(0)

        if not options.input:
            host = {}
            host[valid_ip(options.target)]=port_extraction(options.port)
    
    else:
        host={}
        lines =open(options.input, 'r').readlines()
        for i in lines:
            host[i.split("\t")[0]]=[]
        for i in lines:
            h = i.split("\t")[0]
            p = i.split("\t")[-1]
            host[h].append(int(p))

    thread=options.thread
    output=options.output
    timeout=options.timeout

    for h,p in host.iteritems():
        print "[*] IP Address Detected : {} | Num. Of Port Detected : {}".format(h,len(p))


    if not options.check:
        for target, port in host.iteritems():
             s = BannerScanner(target, port, thread, timeout)
             r = s.get_result()
             host[r[0]]=r[1]
             print "[*] Open Ports Verified.\n[+] IP : {} | Ports : {}".format(r[0], r[1]) 
    BannerGrabber(host, thread, output)
   

# Trigger 
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print "[Exiting Program] \n [+]Thanks For Using! Have a nice day! Bitforestinfo[=]"
        sys.exit(0)
    except Exception as e:
        print e


Features

  • Easy To Use
  • Easy To Maintain


Now, 

Let's run these codes.

to run, this script:


Example 1. 



python bannergrab.py -t www.sitehere.com -p 80-500,555,666


Example 2.




python bannergrab.py -t www.site.in -p 0-22,24,80 


Example 3. 




python bannergrab.py -t www.site.in -p 22,80,60,65,453 -o results.txt


Example 4.




python bannergrab.py -t www.site.in -p 0-22000 -o results.txt --thread 800


Let's Check its Output.



        $ python bannergrab.py -t www.site.com -p 50-500

my output... (i removed some keywords..)


######################################################
                By S.S.B Group                          
######################################################

    Suraj Singh
    Admin
    S.S.B Group
    surajsinghbisht054@gmail.com
    http://bitforestinfo.blogspot.com/

    Note: We Feel Proud To Be Indian
######################################################

[*] IP Address Detected : 192.**.***.*** | Num. Of Port Detected : 450
[*] Open Ports Verified.
[+] IP : 192.**.***.*** | Ports : [80, 443]

[+] HTTP PROTOCOL Founded. IP : 192.**.***.***| PORT : 80


************************************************** 

[+] IP : 192.**.***.*** | Port : 80 | Banner : HTTP/1.1 OK
Content-length: 0
Location: https:///
Connection: close


[+] IP : 192.**.***.*** | Port : 443 | Banner : 

************************************************** 

[+] Scan Started On  Tue Mar 14 00:23:48 2017
[+] Scan Finished On Tue Mar 14 00:25:49 2017
[+] Total Time Taken  121.873281002  Seconds 

************************************************** 



 Thanks For Using My Program by SSB

Warning I am Creating This Tutorial Only For Practise and Educational Purpose. I will not Take any type of responsibility about any illegal activities.

For Downloading, Raw Script Click Here



For More Update, Visit Our Regularly. 
And Subscribe Our Blog, 

Follow Us and share it.
For Any Type of Suggestion Or Help
Contact me:
S.S.B
surajsinghbisht054@gmail.com






Share this

Related Posts

Previous
Next Post »