#!/usr/bin/env python
#-*- coding: utf8 -*-
# Author: HandP
# Date: 20171025
import os
import sys
import socket
IPNumToString = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
IPStringToNum = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
StartIP = 0
EndIP = 0

def helpmessage():
    message = """
    ======================================================
    =                                                    =
    =                    scanhosts V1.0                   =
    =  Usage:                                            =
    =    python scanhosts.py 1.2.3.4                      =
    =    python scanhosts.py 1.2.3.4-255                  =
    =    python scanhosts.py 1.2.3.4 - 1.2.4.5            =
    =    python scanhosts.py f   targetfile
    ======================================================
            """
    print message

def settargets():
    try:
        commandargs = sys.argv[1:]
        if not commandargs:
            return False
        commandargs = ''.join(commandargs)
        commandargs = commandargs.split('-')
        global StartIP
        global EndIP
        commandlen = len(commandargs)
        if commandlen == 1:
            StartIP = EndIP = int(IPStringToNum(commandargs[0]))
        elif commandlen == 2:
            StartIP = commandargs[0]
            EndIP = commandargs[1]
            if len(StartIP.split('.')) !=4 :
                return False
            endiplen =  len(EndIP.split('.'))
            if endiplen == 1:
                prefixip = StartIP.split('.')[0:3]
                prefixip.append(EndIP)
                EndIP = '.'.join(prefixip)
            elif endiplen == 4:
                pass
            else:
                return False

            StartIP = int(IPStringToNum(StartIP))
            EndIP   = int(IPStringToNum(EndIP))

    except Exception,e :
        print e
        return False
    return True


def checkhoston(ip):
    try:
		if "TTL"  in os.popen("ping -n 1 %s"%IPNumToString(ip)).read():
			return True
    except Exception as e:
        print e

def processcheckhost():
    global StartIP
    global EndIP
    alivecount = 0
    StartIP = int(StartIP)
    EndIP = int(EndIP)
    totalip = EndIP - StartIP + 1
    if totalip <= 0:
        helpmessage()
        exit(0)
    print 'Startint scan ',IPNumToString(StartIP),' -> ',IPNumToString(EndIP), ',please wait...'
    fd = open('scanhost.txt',"w")

    ip = StartIP

    while True:
        if ip > EndIP:
            break
        if checkhoston(ip):
            fd.write(IPNumToString(ip)+'\n')
            alivecount = alivecount + 1

        ip = ip + 1
        sys.stdout.write('#')
        if (ip-StartIP) % 20 == 0:
            sys.stdout.write('\r\n')
    fd.close()
    return alivecount

def showresult(shownnum):
    if not os.path.isfile('scanhost.txt'):
        print '[-]'+'scanhost.txt'+'does not exists!'
        exit(0)
    if not os.access('scanhost.txt',os.R_OK):
        print '[-]'+'scanhost.txt'+'access denied'
        exit(0)
    fd = open('scanhost.txt',"r")
    for line in fd.readlines(shownnum):
        print line.strip('\n')
    fd.close()


def scanactivehost():
    pass

def main():
    global StartIP
    global EndIP
    alivehost = 0
    count = 0
    if not sys.argv[1:]:
        helpmessage()
        exit(0)
    if  str(sys.argv[1]).lower() == "f":
        filename = sys.argv[2]
        if not os.path.isfile(filename):
            print '[-]'+filename+'does not exists!'
            exit(0)
        if not os.access(filename,os.R_OK):
            print '[-]'+filename+'access denied'
            exit(0)
        else:
            f = open(filename,'r')
            saveresult = open('scanhost.txt',"w")
            print "[+] scanprogress start now , please wait!"
            for line in f.readlines():
                line = line.strip('\n')
                if checkhoston(int(IPStringToNum(line))):
                    saveresult.write(line+'\n')
                    alivehost = alivehost + 1
                count += 1
                sys.stdout.write('#')
                if count % 20 == 0:
                    sys.stdout.write('\r\n')
            saveresult.close()
            f.close()
            print "\r\n [%d] host is on,please see the scanhost.txt, top 300 will be shown below" % alivehost
            showresult(300)
            if alivehost > 300:
                print "More ips please see scanhost.txt"
            exit(0)
    else:
        if not settargets():
            helpmessage()
            exit(0)
        alivecount = processcheckhost()
        print "\r\n [%d] host is on,please see the scanhost.txt, top 300 will be shown below" % alivecount
        showresult(300)
        if alivecount > 300:
            print "More ips please see scanhost.txt"


if __name__ == "__main__":
    main()


