-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcron_job.py
190 lines (153 loc) · 5.06 KB
/
cron_job.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
#!/usr/bin/python
import socket
import time
import uuid
import csv
import io
import os
import subprocess
from subprocess import Popen, PIPE
from header import printHeader
import re
# ip = "codeserverbwn.duckdns.org"
port = 4059
retry = 1
delay = 0.05
timeout = 1
data = list()
tailingFilename = str(uuid.uuid4())
folder_name = 'cron_output'
dir_path = os.path.dirname(os.path.realpath(__file__))
# Create the folder, skip if exists
if not os.path.exists(dir_path+"/"+folder_name):
os.makedirs(dir_path+"/"+folder_name)
def isOpen(ip, port):
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
s.connect((ip, int(port), 0, 0))
s.shutdown(socket.SHUT_RDWR)
return True
except:
return False
finally:
s.close()
pingcount = 3
telnetretry = 2
def pingStatistics(ip):
print " > GETTING STATISTICS FOR [ ", ip, " ]"
try:
command = "ping6 -W 1 -c "+pingcount+" "+ip
process = Popen(command, stdout=PIPE, stderr=None, shell=True)
output = process.communicate()[0]
regex = r"rtt min\/avg\/max\/mdev = ([.0-9]+)\/([.0-9]+)\/([.0-9]+)\/(.*)$"
regex_per_loss = r"(\d+%)"
stats = list()
# min, avg, max, mdev
for block in re.findall(regex, output, re.S):
stats.append(block[0])
stats.append(block[1])
stats.append(block[2])
stats.append(block[3].strip('\n'))
loss = re.search(regex_per_loss, output).group(1)
stats.append(loss)
print " > STATISTICS FOR [ ", ip, " ] ==> ", stats
if loss == '100%':
return ['HOST_DOWN', 'HOST_DOWN', 'HOST_DOWN', 'HOST_DOWN', loss]
else:
return stats
except:
print(' > STATISTCS_FAILURE')
def pingSuccess(ip):
hostname = ip
# -i for duration, -c for packet count
response = os.system("ping6 -W 1 -c " + str(pingcount)+" " + hostname)
if response == 0:
return 0
else:
return -1
def checkHost(ip, port):
lst = list()
ipup = False
ping = True
if pingSuccess(ip) == 0:
for i in range(retry):
print('=> ping success')
for x in range(1, telnetretry+1):
telnetStatus = isOpen(ip, port)
if x != 1:
print "[ ! WARN ! Retrying telnet (", x, ")... ]"
if telnetStatus == True:
ipup = True
break
else:
time.sleep(delay)
""" if isOpen(ip, port):
ipup = True
break
else:
time.sleep(delay) """
else:
ping = ipup = False
if ping == True:
lst.append("PING SUCCESS")
else:
lst.append("PING FAIL")
if ipup == True:
lst.append("PORT OPEN")
else:
lst.append("PORT CLOSED")
if ping == True:
# Collect ping statistics only when the host is up
lst.append(pingStatistics(ip))
else:
lst.append(['--', '--', '-', '--', '100%'])
""" lst.append(ping)
lst.append(ipup) """
return lst
def readFromCSV(filename):
print("FILE PATH", dir_path)
with io.open(dir_path+"/"+filename+'.csv', newline='') as f:
reader = csv.reader(f)
data.append(list(reader))
f.close()
def preprocess(s):
return bytes(s)
# BELOW TWO FUNCTIONS CONVERT THE OUTPUT TXT TO CSV
def getFileData():
with io.open(os.path.join(dir_path, folder_name, "Results_"+tailingFilename+".txt"), 'r', newline='') as flhndl:
return flhndl.readlines()
def extractToCSV(listData):
header = ['HOST IP', 'PING STATUS', 'TELNET STATUS',
'MIN', 'MAX', 'AVG', 'LATENCY', 'LOSS %']
with io.open(os.path.join(dir_path, folder_name, "Output_ResultsCSV_"+tailingFilename+".csv"), 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(header)
for lines in listData:
temp = str(lines[0:len(lines) - 1])
first = temp.split('\t')
print("{}".format(first))
wr.writerow(first)
filename = "ipaddr_jobs"
print(filename)
readFromCSV(filename)
with io.open(os.path.join(dir_path, folder_name, "Results_"+tailingFilename+".txt"), 'w', newline='') as file:
for ips in data:
for index, ips_get in enumerate(ips):
print "[ ```````````````````````````````````````````` ]"
print("[ RUN {} ]".format(index+1))
get_lst = list()
get_lst = checkHost(ips_get[0], port)
file.write(
unicode(ips_get[0]+"\t" +
str(get_lst[0])+"\t" +
str(get_lst[1])+"\t" +
str(get_lst[2][0])+"\t" +
str(get_lst[2][1])+"\t" +
str(get_lst[2][2])+"\t" +
str(get_lst[2][3])+"\t" +
str(get_lst[2][4].strip())+"\n"))
print "[ ```````````````````````````````````````````` ]\n\n"
printHeader()
data = getFileData()
extractToCSV(data)