能否通过工具或CLI向多台Telnet可达的Cisco交换机批量发送命令并保存配置?
Hey there! Let's tackle your two questions head-on—both using automation tools and CLI-based methods are totally feasible for your 20 Cisco switches (192.168.1.10-30) that support Telnet. I'll walk you through practical examples for each approach, including how to send a command and save the config across all devices.
Tools like Ansible or custom Python scripts are perfect here—they cut down on manual repetition and make it easy to tweak commands later. Let's start with Ansible, since it's built for network automation out of the box.
Ansible Playbook Example
First, set up your inventory file (inventory.ini) to list all your switches (you can use a range shortcut for brevity):
[cisco_switches] cisco_switches ansible_host=192.168.1.[10:30]
Then create a playbook (configure_switches.yml) to send commands and save config changes:
- name: Configure Cisco switches via Telnet hosts: cisco_switches gather_facts: no connection: network_cli vars: ansible_network_os: ios ansible_user: "your_telnet_username" ansible_password: "your_telnet_password" ansible_become: yes ansible_become_method: enable ansible_become_password: "your_enable_password" tasks: - name: Push configuration commands ios_config: commands: - interface vlan 1 - ip address 192.168.1.1 255.255.255.0 # Replace with your actual command - no shutdown save_when: changed # Only saves if config was modified - name: Force config save (optional) ios_command: commands: write memory
Run the playbook with this CLI command:
ansible-playbook -i inventory.ini configure_switches.yml
Custom Python Script (Using telnetlib)
If you prefer writing your own script, Python's built-in telnetlib works great for Telnet connections. Here's a simplified example:
import telnetlib import time # Define your credentials and commands username = "your_username" password = "your_password" enable_pass = "your_enable_password" config_commands = ["interface vlan 1", "ip address 192.168.1.1 255.255.255.0", "no shutdown"] save_command = "write memory" # Loop through the IP range for ip_suffix in range(10, 31): switch_ip = f"192.168.1.{ip_suffix}" print(f"Connecting to {switch_ip}...") try: # Establish Telnet connection tn = telnetlib.Telnet(switch_ip) # Authenticate tn.read_until(b"Username: ") tn.write(username.encode('ascii') + b"\n") tn.read_until(b"Password: ") tn.write(password.encode('ascii') + b"\n") # Enter enable mode tn.read_until(b">") tn.write(b"enable\n") tn.read_until(b"Password: ") tn.write(enable_pass.encode('ascii') + b"\n") # Enter config mode and send commands tn.read_until(b"#") tn.write(b"configure terminal\n") for cmd in config_commands: tn.read_until(b"(config)#") tn.write(cmd.encode('ascii') + b"\n") # Exit config mode and save tn.read_until(b"(config)#") tn.write(b"exit\n") tn.read_until(b"#") tn.write(save_command.encode('ascii') + b"\n") time.sleep(2) # Wait for save to complete tn.close() print(f"Successfully configured {switch_ip}") except Exception as e: print(f"Failed to connect to {switch_ip}: {str(e)}")
If you can't use automation tools, you can use CLI scripts with expect (Linux/macOS) or PowerShell (Windows) to automate Telnet sessions.
Linux/macOS: Expect Script
Create a file batch_telnet.exp with this content:
#!/usr/bin/expect -f set username "your_username" set password "your_password" set enable_pass "your_enable_password" set config_commands [list "interface vlan 1" "ip address 192.168.1.1 255.255.255.0" "no shutdown"] set save_cmd "write memory" # Loop through IPs 10-30 for {set ip 10} {$ip <= 30} {incr ip} { set switch_ip "192.168.1.$ip" puts "Connecting to $switch_ip..." spawn telnet $switch_ip expect "Username: " send "$username\r" expect "Password: " send "$password\r" expect ">" send "enable\r" expect "Password: " send "$enable_pass\r" expect "#" send "configure terminal\r" # Send each config command foreach cmd $config_commands { expect "(config)#" send "$cmd\r" } expect "(config)#" send "exit\r" expect "#" send "$save_cmd\r" sleep 2 send "exit\r" expect eof }
Make it executable and run it:
chmod +x batch_telnet.exp ./batch_telnet.exp
Windows: PowerShell Script
Use PowerShell's built-in TelnetClient to automate sessions:
$username = "your_username" $password = "your_password" $enablePass = "your_enable_password" $configCommands = @("interface vlan 1", "ip address 192.168.1.1 255.255.255.0", "no shutdown") $saveCommand = "write memory" # Loop through IP range 10-30 10..30 | ForEach-Object { $switchIp = "192.168.1.$_" Write-Host "Connecting to $switchIp..." try { $telnet = New-Object System.Net.Sockets.TelnetClient($switchIp, 23) $telnet.Connect() $stream = $telnet.GetStream() $writer = New-Object System.IO.StreamWriter($stream) $reader = New-Object System.IO.StreamReader($stream) # Helper function to send command and wait for prompt function Send-Command { param($Cmd, $Prompt) $writer.WriteLine($Cmd) $writer.Flush() Start-Sleep -Seconds 1 while (!$reader.EndOfStream) { $output = $reader.ReadLine() if ($output -like "*$Prompt*") { break } } } # Run through authentication and commands Send-Command -Cmd $username -Prompt "Password:" Send-Command -Cmd $password -Prompt ">" Send-Command -Cmd "enable" -Prompt "Password:" Send-Command -Cmd $enablePass -Prompt "#" Send-Command -Cmd "configure terminal" -Prompt "(config)#" foreach ($cmd in $configCommands) { Send-Command -Cmd $cmd -Prompt "(config)#" } Send-Command -Cmd "exit" -Prompt "#" Send-Command -Cmd $saveCommand -Prompt "#" Send-Command -Cmd "exit" -Prompt "" $telnet.Dispose() Write-Host "Completed configuration for $switchIp" } catch { Write-Host "Failed to configure $switchIp : $_" } }
Quick Notes
- Security Alert: Telnet sends credentials in plaintext. If your switches support it, switch to SSH for better security—most of these examples can be adapted for SSH with minimal changes.
- Test First: Always run commands on a single test switch before deploying to all 20 devices!
内容的提问来源于stack exchange,提问作者ckoautomate




