-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_rommon.py
More file actions
330 lines (228 loc) · 8.43 KB
/
Copy pathfix_rommon.py
File metadata and controls
330 lines (228 loc) · 8.43 KB
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
Handles a Cisco IR809 router stuck in ROMMON-2 mode.
Automatically finds the correct USB port, detects the router state,
and boots the router from flash if it is in ROMMON-2 mode.
The script then saves the boot variable permanently in the startup configuration
so the router can boot normally in the future.
"""
import serial
import time
import glob
import subprocess
import re
def close_screen_sessions():
"""
Closes all active screen sessions to free the serial ports.
Runs `screen -list` to check for active sessions.
If any sessions are found, they are closed using `screen -X quit`.
"""
result = subprocess.run(["screen", "-list"], capture_output=True, text=True)
if "No Sockets found" not in result.stdout:
subprocess.run(["screen", "-X", "quit"])
time.sleep(1)
print("Screen sessions closed")
else:
print("No screen sessions found")
def find_port():
"""
Searches for and returns an active USB serial port.
The function loops until an active port is found by sending a newline
and checking if the router responds. If no active port is found, it
retries every 5 seconds.
Returns:
str: The path to the active port, for example '/dev/ttyUSB0'.
"""
print("Searching for USB port...")
while True:
ports = glob.glob("/dev/ttyUSB*")
for port in ports:
try:
test = serial.Serial(port=port, baudrate=9600, timeout=2)
test.write(b"\r\n")
time.sleep(3)
output = test.read(test.in_waiting).decode("utf-8", errors="ignore")
test.close()
time.sleep(1)
if output:
print(f"Found active port: {port}")
return port
except:
continue
print("No active port found, retrying in 5 seconds...")
time.sleep(5)
def find_ios_file_rommon():
"""
Searches for the IOS file in flash while the router is in ROMMON mode.
Sends the `dir flash:` command and reads the response until the ROMMON
prompt appears again. The function loops until a matching IOS file is found.
Returns:
str: The IOS image filename, for example `ir800-universalk9-mz.xxx`.
"""
print("Searching for IOS file...")
while True:
ser.write(b"dir flash:\r\n")
output = ""
deadline = time.time() + 20
while time.time() < deadline:
if ser.in_waiting:
output += ser.read(ser.in_waiting).decode("utf-8", errors="ignore")
if "rommon" in output.lower() and output.count("rommon") >= 2:
break
time.sleep(0.3)
match = re.search(r"ir800-universalk9-mz\S+", output)
if match:
ios_file = match.group(0).strip().rstrip(".")
print(f"Found IOS file: {ios_file}")
return ios_file
print("Could not find IOS file, retrying in 5 seconds...")
time.sleep(5)
def find_ios_file_ios():
"""
Searches for the IOS file in flash while the router is running IOS.
Sends the `show flash:` command and reads the response until an IOS
or enable prompt appears.
Returns:
str or None: The IOS image filename if found,
otherwise None.
"""
print("Searching for IOS file...")
ser.write(b"show flash:\r\n")
output = ""
deadline = time.time() + 20
while time.time() < deadline:
if ser.in_waiting:
output += ser.read(ser.in_waiting).decode("utf-8", errors="ignore")
if "#" in output or "IR800>" in output:
break
time.sleep(0.3)
match = re.search(r"ir800-universalk9-mz\S+", output)
if match:
ios_file = match.group(0).strip().rstrip(".")
print(f"Found IOS file: {ios_file}")
return ios_file
print("Could not find IOS file!")
return None
def save_boot_variable(ios_file):
"""
Saves the boot variable permanently in the router startup configuration.
Enters enable and configuration mode, removes existing boot directives,
sets a new boot variable, and saves it using `write memory`.
Arguments:
ios_file (str): The IOS image filename to use during boot.
Returns:
bool: True if the save was successful, otherwise False.
"""
print("Saving boot variable permanently...")
time.sleep(3)
ser.write(b"enable\r\n")
time.sleep(3)
ser.write(b"conf t\r\n")
time.sleep(3)
ser.write(b"no boot system\r\n")
time.sleep(3)
ser.write(f"boot system flash:{ios_file}\r\n".encode())
time.sleep(3)
ser.write(b"end\r\n")
time.sleep(3)
ser.write(b"write memory\r\n")
output = ""
deadline = time.time() + 30
while time.time() < deadline:
if ser.in_waiting:
output += ser.read(ser.in_waiting).decode("utf-8", errors="ignore")
if "[OK]" in output or "Building" in output:
time.sleep(3)
break
time.sleep(0.3)
if "[OK]" in output or "Building" in output:
print("Boot variable saved permanently!")
print("The router will now boot normally without ROMMON-2!")
return True
else:
print("Could not save boot variable!")
return False
def fix_rommon():
"""
Waits for the router and handles ROMMON-2 mode automatically.
Monitors serial output and reacts to different states: ROMMON-2,
'Press RETURN' prompt, initial configuration dialog, and normal IOS prompt.
If the router gets stuck in ROMMON-2, it is booted manually from flash.
When IOS is up, the boot variable is saved permanently.
Returns:
bool: True if the router successfully booted into IOS,
otherwise False on timeout.
"""
print("Waiting for the router...")
output = ""
rommon_handled = False
ios_booted = False
ios_file = None
last_enter = time.time()
deadline = time.time() + 400
while time.time() < deadline:
if not ser.in_waiting and time.time() - last_enter > 5:
ser.write(b"\r\n")
last_enter = time.time()
if ser.in_waiting:
chunk = ser.read(ser.in_waiting).decode("utf-8", errors="ignore")
output += chunk
# Handle ROMMON-2
if "rommon" in output.lower() and not rommon_handled:
print("Router in ROMMON-2, booting up...")
time.sleep(3)
ios_file = find_ios_file_rommon()
ser.write(f"set BOOT=flash:{ios_file}\r\n".encode())
time.sleep(2)
ser.write(b"set BOOT_IOS_SEQUENCE=20\r\n")
time.sleep(2)
ser.write(f"boot flash:{ios_file}\r\n".encode())
time.sleep(2)
rommon_handled = True
output = ""
# Handle Press RETURN
if "press ret" in output.lower() or "press return" in output.lower():
time.sleep(2)
ser.write(b"\r\n")
time.sleep(2)
output = ""
# Handle initial configuration dialog
if "yes/no" in output.lower() and "configuration dialog" in output.lower():
print("Answering no to configuration dialog...")
time.sleep(2)
ser.write(b"no\r\n")
time.sleep(5)
output = ""
# Router booted into IOS
if "IR800>" in output and not ios_booted and ios_file:
print("Router booted into IOS!")
ios_booted = True
time.sleep(8)
save_boot_variable(ios_file)
return True
time.sleep(0.2)
print("Timeout!")
return False
# Main program - closes screen sessions and finds active port
close_screen_sessions()
time.sleep(2)
port = find_port()
ser = serial.Serial(port=port, baudrate=9600, timeout=5)
ser.write(b"\r\n")
time.sleep(3)
output = ser.read(ser.in_waiting).decode("utf-8", errors="ignore")
# Check the router state and act accordingly
if "rommon" in output.lower():
print("Router is in ROMMON-2, fixing...")
fix_rommon()
elif "IR800>" in output or "IR800#" in output:
print("Router is already running IOS...")
ios_file = find_ios_file_ios()
if ios_file:
save_boot_variable(ios_file)
else:
print("Could not find IOS file!")
else:
print("Waiting for the router...")
fix_rommon()
print("Done!")
ser.close()