Skip to content

Commit a007e06

Browse files
committed
Add pythonping for cron jobs
1 parent 9958483 commit a007e06

File tree

1 file changed

+190
-0
lines changed

1 file changed

+190
-0
lines changed

cron_job.py

+190
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
#!/usr/bin/python
2+
3+
import socket
4+
import time
5+
import uuid
6+
import csv
7+
import io
8+
import os
9+
import subprocess
10+
from subprocess import Popen, PIPE
11+
from header import printHeader
12+
import re
13+
14+
# ip = "codeserverbwn.duckdns.org"
15+
port = 4059
16+
retry = 1
17+
delay = 0.05
18+
timeout = 1
19+
20+
data = list()
21+
tailingFilename = str(uuid.uuid4())
22+
23+
folder_name = 'cron_output'
24+
dir_path = os.path.dirname(os.path.realpath(__file__))
25+
26+
# Create the folder, skip if exists
27+
if not os.path.exists(dir_path+"/"+folder_name):
28+
os.makedirs(dir_path+"/"+folder_name)
29+
30+
31+
def isOpen(ip, port):
32+
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
33+
s.settimeout(timeout)
34+
try:
35+
s.connect((ip, int(port), 0, 0))
36+
s.shutdown(socket.SHUT_RDWR)
37+
return True
38+
except:
39+
return False
40+
finally:
41+
s.close()
42+
43+
44+
pingcount = 3
45+
telnetretry = 2
46+
47+
48+
def pingStatistics(ip):
49+
print " > GETTING STATISTICS FOR [ ", ip, " ]"
50+
51+
try:
52+
command = "ping6 -W 1 -c "+pingcount+" "+ip
53+
process = Popen(command, stdout=PIPE, stderr=None, shell=True)
54+
output = process.communicate()[0]
55+
56+
regex = r"rtt min\/avg\/max\/mdev = ([.0-9]+)\/([.0-9]+)\/([.0-9]+)\/(.*)$"
57+
regex_per_loss = r"(\d+%)"
58+
stats = list()
59+
# min, avg, max, mdev
60+
for block in re.findall(regex, output, re.S):
61+
stats.append(block[0])
62+
stats.append(block[1])
63+
stats.append(block[2])
64+
stats.append(block[3].strip('\n'))
65+
loss = re.search(regex_per_loss, output).group(1)
66+
stats.append(loss)
67+
print " > STATISTICS FOR [ ", ip, " ] ==> ", stats
68+
if loss == '100%':
69+
return ['HOST_DOWN', 'HOST_DOWN', 'HOST_DOWN', 'HOST_DOWN', loss]
70+
else:
71+
return stats
72+
73+
except:
74+
print(' > STATISTCS_FAILURE')
75+
76+
77+
def pingSuccess(ip):
78+
hostname = ip
79+
# -i for duration, -c for packet count
80+
response = os.system("ping6 -W 1 -c " + str(pingcount)+" " + hostname)
81+
if response == 0:
82+
return 0
83+
else:
84+
return -1
85+
86+
87+
def checkHost(ip, port):
88+
lst = list()
89+
ipup = False
90+
ping = True
91+
92+
if pingSuccess(ip) == 0:
93+
for i in range(retry):
94+
print('=> ping success')
95+
96+
for x in range(1, telnetretry+1):
97+
telnetStatus = isOpen(ip, port)
98+
if x != 1:
99+
print "[ ! WARN ! Retrying telnet (", x, ")... ]"
100+
if telnetStatus == True:
101+
ipup = True
102+
break
103+
else:
104+
time.sleep(delay)
105+
""" if isOpen(ip, port):
106+
ipup = True
107+
break
108+
else:
109+
time.sleep(delay) """
110+
else:
111+
ping = ipup = False
112+
113+
if ping == True:
114+
lst.append("PING SUCCESS")
115+
else:
116+
lst.append("PING FAIL")
117+
if ipup == True:
118+
lst.append("PORT OPEN")
119+
else:
120+
lst.append("PORT CLOSED")
121+
122+
if ping == True:
123+
# Collect ping statistics only when the host is up
124+
lst.append(pingStatistics(ip))
125+
else:
126+
lst.append(['--', '--', '-', '--', '100%'])
127+
""" lst.append(ping)
128+
lst.append(ipup) """
129+
return lst
130+
131+
132+
def readFromCSV(filename):
133+
print("FILE PATH", dir_path)
134+
with io.open(dir_path+"/"+filename+'.csv', newline='') as f:
135+
reader = csv.reader(f)
136+
data.append(list(reader))
137+
f.close()
138+
139+
140+
def preprocess(s):
141+
return bytes(s)
142+
143+
# BELOW TWO FUNCTIONS CONVERT THE OUTPUT TXT TO CSV
144+
145+
146+
def getFileData():
147+
with io.open(os.path.join(dir_path, folder_name, "Results_"+tailingFilename+".txt"), 'r', newline='') as flhndl:
148+
return flhndl.readlines()
149+
150+
151+
def extractToCSV(listData):
152+
header = ['HOST IP', 'PING STATUS', 'TELNET STATUS',
153+
'MIN', 'MAX', 'AVG', 'LATENCY', 'LOSS %']
154+
with io.open(os.path.join(dir_path, folder_name, "Output_ResultsCSV_"+tailingFilename+".csv"), 'wb') as myfile:
155+
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
156+
wr.writerow(header)
157+
for lines in listData:
158+
temp = str(lines[0:len(lines) - 1])
159+
first = temp.split('\t')
160+
print("{}".format(first))
161+
162+
wr.writerow(first)
163+
164+
165+
filename = "ipaddr_jobs"
166+
print(filename)
167+
readFromCSV(filename)
168+
with io.open(os.path.join(dir_path, folder_name, "Results_"+tailingFilename+".txt"), 'w', newline='') as file:
169+
for ips in data:
170+
for index, ips_get in enumerate(ips):
171+
print "[ ```````````````````````````````````````````` ]"
172+
print("[ RUN {} ]".format(index+1))
173+
get_lst = list()
174+
get_lst = checkHost(ips_get[0], port)
175+
file.write(
176+
unicode(ips_get[0]+"\t" +
177+
str(get_lst[0])+"\t" +
178+
str(get_lst[1])+"\t" +
179+
str(get_lst[2][0])+"\t" +
180+
str(get_lst[2][1])+"\t" +
181+
str(get_lst[2][2])+"\t" +
182+
str(get_lst[2][3])+"\t" +
183+
str(get_lst[2][4].strip())+"\n"))
184+
185+
print "[ ```````````````````````````````````````````` ]\n\n"
186+
187+
188+
printHeader()
189+
data = getFileData()
190+
extractToCSV(data)

0 commit comments

Comments
 (0)