Bash

We want to write a banner grabber. We can send a newline character (which will close our connection) \n with echo "" as it sends a newline character by default. (To omit this, you can use echo -n). We should get the response in our terminal

#!/bin/bash
# usage ./bannergrab.sh <ip> <port>

ip=$1
port=$2

echo "" | nc -v -n -r -w1 $ip $port

Here is the output:

[root@kadi bash]# ./bannergrab.sh 127.0.0.1 80
(UNKNOWN) [127.0.0.1] 80 (http) open
HTTP/1.1 400 Bad Request
Date: Fri, 19 Jun 2020 01:01:09 GMT
Server: Apache/2.4.43 (Debian)
Content-Length: 301
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.43 (Debian) Server at kadi.home Port 80</address>
</body></html>

Python

We can use a similar method in python, but we will use sockets to connect. This connects and receives 1024 bytes. We put it inside a try block so that in case it fails, the script does not break.

#!/usr/bin/python
# usage ./bannergrab.py <ip> <port>

import socket
import sys
import os

def bannergrab(ip, port):
    try:
        s = socket.socket()
        s.connect((ip, port))
        banner = s.recv(1024)
        print ip + ' : ' + banner
    except:
        print "error"
        return

arguments = str(sys.argv)
ip = str(sys.argv[1])
port = int(sys.argv[2])

bannergrab(ip, port)

Here is the output:

[root@kadi python]# ./bannergrab.py 127.0.0.1 22
127.0.0.1 : SSH-2.0-OpenSSH_8.2p1 Debian-4