Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, 19 August 2017

Port scanner in Python ~ programming info

Overview

This post will show how you can make a small and easy-to-use port scanner program
written in Python.

There are many ways of doing this with Python, and I'm going to do it using the
built-in module Socket.

Sockets

The socket module in Python provides access to the BSD socket interface. 

It includes the socket class, for handling the actual data channel, and functions 
for network-related tasks such as converting a server’s name to an address and
formatting data to be sent across the network. Source

Sockets are widely used on the Internet, as they are behind any kind of
network communications done by your computer. 

The INET sockets, account for at least 99% of the sockets in use. 

The web browser’s that you use opens a socket and connects to the web server.

Any network communication goes through a socket.

For more reading about the socket module, please see the official documentation. 

Socket functions

Before we get started with our sample program, let's see some of the socket
functions we are going to use.

sock = socket.socket (socket_family, socket_type)
Syntax for creating a socket

sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
Creates a stream socket

AF_INET
Socket Family (here Address Family version 4 or IPv4)

SOCK_STREAM
Socket type TCP connections

SOCK_DGRAM
Socket type UDP connections

gethostbyname("host")
Translate a host name to IPv4 address format

socket.gethostbyname_ex("host")
Translate a host name to IPv4 address format, extended interface

socket.getfqdn("8.8.8.8")
Get the fqdn (fully qualified domain name)

socket.gethostname()
Returns the hostname of the machine..

socket.error
Exception handling

Making a program using Python Sockets

How to make a simple port scanner program in Python

This small port scanner program will try to connect on every port you define for
a particular host. 

The first thing we must do is import the socket library and other libraries that
we need. 

Open up an text editor, copy & paste the code below. Save the file as:
"portscanner.py" and exit the editor
#!/usr/bin/env python
import socket
import subprocess
import sys
from datetime import datetime

# Clear the screen
subprocess.call('clear', shell=True)

# Ask for input
remoteServer    = raw_input("Enter a remote host to scan: ")
remoteServerIP  = socket.gethostbyname(remoteServer)

# Print a nice banner with information on which host we are about to scan
print "-" * 60
print "Please wait, scanning remote host", remoteServerIP
print "-" * 60

# Check what time the scan started
t1 = datetime.now()

# Using the range function to specify ports (here it will scans all ports between 1 and 1024)

# We also put in some error handling for catching errors

try:
    for port in range(1,1025):  
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((remoteServerIP, port))
        if result == 0:
            print "Port {}:   Open".format(port)
        sock.close()

except KeyboardInterrupt:
    print "You pressed Ctrl+C"
    sys.exit()

except socket.gaierror:
    print 'Hostname could not be resolved. Exiting'
    sys.exit()

except socket.error:
    print "Couldn't connect to server"
    sys.exit()

# Checking the time again
t2 = datetime.now()

# Calculates the difference of time, to see how long it took to run the script
total =  t2 - t1

# Printing the information to screen
print 'Scanning Completed in: ', total

Sample output
Let's run the program and see how an output can look like
$ python portscanner.py

Enter a remote host to scan: www.your_host_example.com
------------------------------------------------------------
Please wait, scanning remote host xxxx.xxxx.xxxx.xxxx
------------------------------------------------------------

Port 21:   Open
Port 22:    Open
Port 23:    Open
Port 80:    Open
Port 110:   Open
Port 111:   Open
Port 143:   Open
Port 443:   Open
Port 465:   Open
Port 587:   Open
Port 993:   Open
Port 995:   Open

Scanning Completed in:  0:06:34.705170
Read More »

CommandLineFu with Python ~ programming info

Overview

One of the best methods to practice Python coding is to study some code and try
them out yourself.

By doing a lot of code exercises, you will get a much better understanding of what
it really does. 

In other words, learning by doing. 

To help you improve your Python coding skill, I've created a program below which
is using the API from CommandLineFu.com

CommandLineFu API

A common first step when you want to use a Web-based services is to see if they
have an API. 

Luckily for me, Commandlinefu.com provides one and can be found here

"
The content of commandlinefu.com is available in a variety of different formats
for you to do what you like with. 

Any page which contains a list of commands (such as the listings by tag, function
or user) can be returned in a format of your choice through a simple change to the
request URL."
The example URL that they provide is:
http://www.commandlinefu.com/commands/'command-set'/'format'/

where:

command-set
is the URL component which specifies which set of commands to return.

Possible values are:
browse/sort-by-votes
tagged/163/grep
matching/ssh/c3No

format
is one of the following: plaintext, json and rss.

I prefer using the json format and that is also what I'm using in the program
below.

Creating the "Command Line Search Tool"

I think we have all the API information we need, so let's get to it.

The program is well documented and should be straightforward. 

Open up a text editor, copy & paste the code below. 

Save the file as: "commandlinefu.py" and exit the editor.
#!/usr/bin/env python27
import urllib2
import base64
import json
import os
import sys
import re

os.system("clear")
print "-" * 80
print "Command Line Search Tool"
print "-" * 80

def Banner(text):
    print "=" * 70
    print text
    print "=" * 70
    sys.stdout.flush()

def sortByVotes():
    Banner('Sort By Votes')
    url = "http://www.commandlinefu.com/commands/browse/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    #print json.dumps(response,indent=2)
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesToday():
    Banner('Printing All commands the last day (Sort By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-day/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesWeek():
    Banner('Printing All commands the last week (Sort By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-week/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesMonth():
    Banner('Printing: All commands from the last months (Sorted By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-month/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByMatch():
    #import base64
    Banner("Sort By Match")
    match = raw_input("Please enter a search command: ")
    bestmatch = re.compile(r' ')
    search = bestmatch.sub('+', match)
    b64_encoded = base64.b64encode(search)
    url = "http://www.commandlinefu.com/commands/matching/" + search + "/" + b64_encoded + "/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
  print c['command']

print """
1. Sort By Votes (All time)
2. Sort By Votes (Today)
3. Sort by Votes (Week)
4. Sort by Votes (Month)
5. Search for a command
 
Press enter to quit
"""

while True:
  answer = raw_input("What would you like to do? ")

 if answer == "":
    sys.exit()
  
  elif answer == "1":
   sortByVotes()
 
  elif answer == "2":
   print sortByVotesToday()
  
  elif answer == "3":
   print sortByVotesWeek()
 
  elif answer == "4":
   print sortByVotesMonth()
  
  elif answer == "5":
   print sortByMatch()
 
  else:
   print "Not a valid choice"
When you run the program, you will be presented with a menu in which you can make
your choices.

--------------------------------------------------------------------------------
Command Line Search Tool
--------------------------------------------------------------------------------

1. Sort By Votes (All time)
2. Sort By Votes (Today)
3. Sort by Votes (Week)
4. Sort by Votes (Month)
5. Search for a command

Press enter to quit
Read More »

Magic 8-ball in Python ~ programming info

# Import the modules
import sys
import random

ans = True

while ans:
    question = raw_input("Ask the magic 8 ball a question: (press enter to quit) ")
    
    answers = random.randint(1,8)
    
    if question == "":
        sys.exit()
    
    elif answers == 1:
        print "It is certain"
    
    elif answers == 2:
        print "Outlook good"
    
    elif answers == 3:
        print "You may rely on it"
    
    elif answers == 4:
        print "Ask again later"
    
    elif answers == 5:
        print "Concentrate and ask again"
    
    elif answers == 6:
        print "Reply hazy, try again"
    
    elif answers == 7:
        print "My reply is no"
    
    elif answers == 8:
        print "My sources say no"
Read More »