Completed
Push — master ( 29ba9e...e0e0e8 )
by Sepand
01:09
created

set_mask()   A

Complexity

Conditions 4

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 6
rs 9.2
c 0
b 0
f 0
1
import socket #  Added For Finding Host IP
2
import subprocess as sub # Added For Run Command By CMD
3
import string
4
import datetime
5
import sys # For Exit
6
import multiprocessing as mu # for multtiprocessing
7
import time
8
9
mask = "192.168.1."
10
11
def line(number,char="-"):
12
    response=""
13
    i=0
14
    while(i<number):
15
        response+=char
16
        i+=1
17
    return response
18
def ping(i): # ping function
19
    output=str(list(sub.Popen("ping "+i,stdout=sub.PIPE,stderr=sub.PIPE,shell=True).communicate())[0])
20
    return output
21
def ip_filter(i_list): # This Function Get A List Of IPs and Split IP
22
    '''((list)->list'''
23
    dic = list(string.digits + ".")
24
    temp_list=[]
25
    for i in range(len(i_list)):
26
        for j in range(len(i_list[i])):
27
            if i_list[i][j] not in dic:
28
                temp_list.append(i_list[i][:j])
29
                break
30
    return temp_list
31
def search_ip(output): # This Function Get A String As Input ( ARP Command Output) and Find For Local IPs
32
    '''(str)->list'''
33
    index=0
34
    ip_list=[]
35
    while(True):
36
        index=output.find("192",index)
37
        ip_list.append(output[index:index+16])
38
        if (index==-1):
39
            break
40
        else:
41
            index=index+16
42
    return ip_list
43
def string_conv(i):
44
    return mask+str(i)
45
def ARP(my_ip,file):
46
    try:
47
        sub.Popen("ping " + my_ip, stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
48
        response = sub.Popen("arp -a", stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
49
        output = str(list(response.communicate())[0])
50
        ip_list = search_ip(output)
51
        ip_list = ip_filter(ip_list)
52
        for i in ip_list:
53
            print("IP : ", i, "Is  available")
54
            file.write("IP : "+ i+ "Is  available\n")
55
    except Exception as e:
56
        if file.closed==False:
57
            file.close()
58
        print(e)
59
60
def Manual(range_min,range_max,file):
61
    try:
62
        ip_list = list(map(string_conv, list(range(range_min, range_max + 1))))
63
        p = mu.Pool(mu.cpu_count() + 100)  # for multiprocessing
64
        result = p.map(ping, ip_list)  # result of pings
65
        for output in result:
66
            if output.find("timed out") == -1 and output.find("unreachable") == -1:
67
                # ssh_response=sub.call("ssh "+ip_list[result.index(output)],stdout=sub.PIPE,stderr=sub.PIPE,timeout=30,shell=True)
68
                print("IP : ", ip_list[result.index(output)], "Is available")
69
                file.write("IP : "+ ip_list[result.index(output)]+ " Is available\n")
70
            else:
71
                print("IP : ", ip_list[result.index(output)], "Is not available")
72
                file.write("IP : "+ ip_list[result.index(output)]+ " Is not available\n")
73
    except Exception as e:
74
        if file.closed==False:
75
            file.close()
76
        print(e)
77
78
def find(mode="manual",my_ip="0.0.0.0",range_min=0,range_max=254): # This Function Ping And SSH IPs to find SSH Server
79
    log_file=open("log_file.txt","a")
80
    log_file.write(str(datetime.datetime.now())+"\n")
81
    log_file.write(line(30,"%")+"\n")
82
    if mode=="manual":
83
        Manual(range_max=range_max,range_min=range_min,file=log_file)
84
    elif mode=="ARP":
85
        ARP(my_ip,log_file)
86
    log_file.write(line(30, "*") + "\n")
87
    log_file.close()
88
def set_mask():
89
    get_mask = input("Please Enter Mask :")
90
    if get_mask.find("192.") != -1 and get_mask.find("168.") != -1:
91
        if get_mask[-1] != ".":
92
            get_mask = get_mask + "."
93
    return get_mask
94
def set_range():
95
    try:
96
        range_max_input = int(input("Please Enter Range Max : "))
97
        range_min_input = int(input("Please Enter Range Min : "))
98
    except ValueError:  # If User Ignore Input Step
99
        range_max_input = 0
100
        range_min_input = 0
101
    print("Please Wait : Scan IPs . . . ")
102
    if range_max_input > range_min_input and range_max_input < 256:
103
        find(range_max=range_max_input, range_min=range_min_input)
104
    else:
105
        find()
106
def main():
107
    mu.freeze_support()
108
    global mask
109
    print("Running On Netmask: " + mask)
110
    my_ip = socket.gethostbyname(socket.gethostname())
111
    if my_ip == "127.0.0.1":
112
        print("Problem In Netwrok Connection ( Please Check )")
113
        input()
114
        sys.exit()
115
    inp = int(input("Please Choose ARP[1] or Linear Search[2]"))
116
    time_1 = time.perf_counter()
117
    if inp == 1:
118
        print("Please Wait : Scan IPs . . . ")
119
        find(mode="ARP", my_ip=my_ip)
120
        time_2 = time.perf_counter()
121
    else:
122
        mask = set_mask()
123
        set_range()
124
        time_2 = time.perf_counter()
125
    print("Scan Time :", str((time_2 - time_1) / 60), " min")
126
    input("Press Any Key To Exit")
127
128
                
129
        
130
        
131
        
132