forked from kay/RouterOS
XcodeGen-basiertes SwiftUI-Projekt für den RouterOS-Interview-Assistenten. Erster Wizard-Schritt: Verbindung zu Mikrotik-Geräten per REST-API (RouterOS >=7.1) mit SSH-CLI-Fallback für ältere Firmware, Zertifikats- TOFU-Bestätigung, Zugangsdaten im Keychain. Unit-Tests für CLI-Parser und Fallback-Logik. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HReLXMbmPvtQ23p1iWiJNW
60 lines
2.7 KiB
Swift
60 lines
2.7 KiB
Swift
import Foundation
|
|
|
|
/// Best-effort parser for RouterOS CLI output over SSH.
|
|
/// Not verified against a live device yet — check against real router output during the M2 dry-run pass.
|
|
enum RouterOSCliParser {
|
|
/// Parses `/system resource print` output (colon-separated "key: value" lines).
|
|
static func parseDeviceInfo(_ raw: String) -> RouterDeviceInfo {
|
|
var fields: [String: String] = [:]
|
|
for line in raw.split(separator: "\n") {
|
|
guard let colonIndex = line.firstIndex(of: ":") else { continue }
|
|
let key = String(line[line.startIndex..<colonIndex]).trimmingCharacters(in: .whitespaces)
|
|
let value = String(line[line.index(after: colonIndex)...]).trimmingCharacters(in: .whitespaces)
|
|
fields[key] = value
|
|
}
|
|
return RouterDeviceInfo(
|
|
boardName: fields["board-name"] ?? "unbekannt",
|
|
routerOSVersion: fields["version"] ?? "unbekannt",
|
|
architecture: fields["architecture-name"] ?? "unbekannt",
|
|
uptime: fields["uptime"] ?? "-"
|
|
)
|
|
}
|
|
|
|
/// Parses `/interface print terse` output (one line per interface, `key=value` pairs).
|
|
static func parseInterfaces(_ raw: String) -> [NetworkInterface] {
|
|
raw.split(separator: "\n").compactMap { line in
|
|
let fields = keyValues(from: String(line))
|
|
guard let name = fields["name"] else { return nil }
|
|
return NetworkInterface(
|
|
name: name,
|
|
type: fields["type"] ?? "unbekannt",
|
|
running: isTrue(fields["running"]),
|
|
disabled: isTrue(fields["disabled"]),
|
|
macAddress: fields["mac-address"]
|
|
)
|
|
}
|
|
}
|
|
|
|
/// RouterOS CLI output mixes "true"/"false" and "yes"/"no" for booleans depending on field/version.
|
|
private static func isTrue(_ value: String?) -> Bool {
|
|
value == "true" || value == "yes"
|
|
}
|
|
|
|
private static func keyValues(from text: String) -> [String: String] {
|
|
var result: [String: String] = [:]
|
|
let pattern = #"([a-zA-Z0-9-]+)=("[^"]*"|\S+)"#
|
|
guard let regex = try? NSRegularExpression(pattern: pattern) else { return result }
|
|
let nsText = text as NSString
|
|
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
|
|
for match in matches {
|
|
let key = nsText.substring(with: match.range(at: 1))
|
|
var value = nsText.substring(with: match.range(at: 2))
|
|
if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 {
|
|
value = String(value.dropFirst().dropLast())
|
|
}
|
|
result[key] = value
|
|
}
|
|
return result
|
|
}
|
|
}
|