如何使用Python在FRR中添加BFD Peer?脚本执行终端交互问题求助
I've run into similar FRR CLI automation headaches before—interactive terminals are a pain to handle in scripts, but there are two reliable workarounds that let you automate this without relying on manual terminal input.
Method 1: Use Multiple -c Arguments with vtysh
FRR's vtysh supports passing multiple commands via repeated -c flags. Each flag maps to one command you'd enter manually, and vtysh executes them in sequence while preserving the CLI context (like automatically staying in config-bfd mode after running bfd).
Here's a Python script using subprocess to implement this:
import subprocess # Define the exact sequence of commands you'd run in vtysh frr_commands = [ "configure", "bfd", "peer 10.6.5.8", "do show bfd peers" ] # Build the full vtysh command with repeated -c arguments vtysh_command = ["vtysh"] for cmd in frr_commands: vtysh_command.extend(["-c", cmd]) # Execute the command and capture output result = subprocess.run(vtysh_command, capture_output=True, text=True) # Print results to verify success print("Command Output:\n", result.stdout) if result.stderr: print("Errors:\n", result.stderr)
Method 2: Load Commands from a Temporary File
For longer or more complex config sequences, it's cleaner to write commands to a temporary file and load it with vtysh -f:
import subprocess import tempfile import os # Define your FRR configuration as a multi-line string config_script = """configure bfd peer 10.6.5.8 do show bfd peers """ # Create a temporary file to hold the config commands with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file: temp_file.write(config_script) temp_path = temp_file.name try: # Run vtysh with the temporary config file result = subprocess.run(["vtysh", "-f", temp_path], capture_output=True, text=True) print("Command Output:\n", result.stdout) if result.stderr: print("Errors:\n", result.stderr) finally: # Clean up the temporary file after execution os.unlink(temp_path)
Why Your Previous Attempts Failed
- Running
run_command("vtysh")launches an interactive terminal, which pauses your script until the terminal is closed—this can't handle automated command input. - Using a single
-cwith semicolon-separated commands (likevtysh -c "configure; bfd; peer 10.6.5.8") usually fails because FRR's CLI doesn't handle context switches correctly with semicolons. The multi--cor file-based approach mimics manual input properly, keeping the CLI context intact as you move between sub-modes.
Note on Permissions
If your user doesn't have direct access to vtysh, add sudo to the command list (e.g., ["sudo", "vtysh"] instead of just ["vtysh"]). You may need to set up passwordless sudo for the script's user to avoid interactive password prompts.
内容的提问来源于stack exchange,提问作者Riya Singh




