-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiprelay.py
100 lines (69 loc) · 1.83 KB
/
iprelay.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
#!/usr/bin/python
import subprocess
import piplates.RELAYplate as RELAY
import time
import json
import os.path
import ipaddress
import sys
RELAY.relayON(0,1)
delay = 10
relay_add = 0
relay_num = 1
file = ("target.json")
#open json file and convert to dictionary
def file_read():
with open(file, "r", encoding = "utf-8") as r:
data = json.loads(r.read())
return data
#write to json file
def file_write(write):
with open(file, "w", encoding = "utf-8") as w:
json.dump(write,w)
#create a JSON file for IP storage
def json_create():
dic = {"data":{"IP":"$"}}
file_write(dic)
print("JSON has been created")
main()
# write user defined IP to the JSON file
def write():
ip_input = input("Enter IP Address: ")
ipaddress.ip_address(ip_input)
data = file_read()
data['data']['IP'] = ip_input
file_write(data)
print("Stand by for ping response...")
main()
#trigger the relay to power cycle the device
def relay(delay,add,num):
data = file_read()
ipaddr = data["data"]["IP"]
try:
output = subprocess.check_output(['ping', '-c 4', '{}'.format(ipaddr)])
print(output)
return True
except:
print(f"NO RESPONSE: Triggering Relay for {delay} seconds")
RELAY.relayOFF(add,num)
time.sleep(delay)
RELAY.relayON(add,num)
finally:
print("Sequence Finished")
sys.exit()
def sequence():
data = file_read()
check = data["data"]["IP"]
if check == "$":
write()
if check != "$":
relay(delay,relay_add,relay_num)
# elif:
# print("ERROR")
def main():
if os.path.isfile("target.json") == False:
json_create()
elif os.path.isfile("target.json") == True:
sequence()
if __name__ == "__main__":
main()