routeros-config-export/app.spy
2023-07-21 18:12:10 +02:00

70 lines
2.3 KiB
Text

import os
import subprocess
from git import Repo
import paramiko
# Function to export RouterOS configuration
def export_routeros_config(device_config):
device = device_config["host"]
username = device_config["username"]
ssh_key_path = device_config["ssh_key_path"]
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(device, username=username, key_filename=ssh_key_path)
# Modify the export command based on the RouterOS command for configuration export
stdin, stdout, stderr = ssh.exec_command("/export")
with open(f"{device}_config_export.txt", "w") as f:
f.write(stdout.read().decode())
ssh.close()
# Function to check if the Git repository exists and pull or clone accordingly
def check_and_pull_git_repo():
git_repo_path = os.environ.get("GIT_REPO_PATH")
if os.path.exists(git_repo_path):
repo = Repo(git_repo_path)
if not repo.bare:
origin = repo.remote(name="origin")
origin.pull()
else:
print("Error: The directory exists but is not a Git repository.")
exit(1)
else:
git_repo_url = os.environ.get("GIT_REPO_URL")
Repo.clone_from(git_repo_url, git_repo_path)
# Function to commit and push the configuration to the Git repository
def commit_and_push_to_git():
git_repo_path = os.environ.get("GIT_REPO_PATH")
repo = Repo(git_repo_path)
index = repo.index
# Add the RouterOS config files to the index
config_files = [f"{device['host']}_config_export.txt" for device in DEVICE_CONFIGS]
index.add(config_files)
# Commit and push the changes
index.commit("Update configuration")
origin = repo.remote(name="origin")
origin.push()
if __name__ == "__main__":
# RouterOS devices SSH connection settings
DEVICE_CONFIGS = os.environ.get("DEVICE_CONFIGS").split()
DEVICE_CONFIGS = [
{"host": device.split(',')[0], "username": device.split(',')[1], "ssh_key_path": device.split(',')[2]}
for device in DEVICE_CONFIGS
]
# Export RouterOS configurations
for device_config in DEVICE_CONFIGS:
export_routeros_config(device_config)
# Check and pull the Git repository
check_and_pull_git_repo()
# Commit and push the configurations to the Git repository
commit_and_push_to_git()