0Pricing
Linux Networking & TCP/IP for Developers · 课时

使用 Python 实现网络自动化

使用 `paramiko` 和 `netmiko` 等 Python 库,通过 SSH 与网络设备交互并自动配置

使用 Python 实现网络自动化 是 CoddyKit 上的免费 Linux Networking & TCP/IP for Developers 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Linux Networking & TCP/IP for Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Linux Networking & TCP/IP for Developers 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Python for Network Automation

Welcome to network automation with Python! Python is a powerful and versatile language, making it a favorite for automating network tasks.

It simplifies complex operations, helps manage devices, and integrates with various network APIs. Let's see how!

Introducing Paramiko

Our first tool is Paramiko. It's a Python library that implements the SSHv2 protocol. Think of it as a low-level toolkit for secure shell (SSH) connections.

  • SSH Client/Server: Can act as both client and server.
  • Secure: Uses strong encryption for communication.
  • Versatile: Great for general-purpose SSH tasks, like running commands or transferring files.

Paramiko: Basic SSH Connection

Here's how you can use Paramiko to connect to a remote server and execute a command. Remember to replace the placeholder credentials!

import paramiko

def connect_and_run(hostname, username, password, command):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        client.connect(hostname=hostname, username=username, password=password, timeout=5)
        stdin, stdout, stderr = client.exec_command(command)
        print(f"Output:\n{stdout.read().decode().strip()}")
        print(f"Errors:\n{stderr.read().decode().strip()}")
    except paramiko.AuthenticationException:
        print("Authentication failed, please check your credentials.")
    except paramiko.SSHException as e:
        print(f"SSH connection error: {e}")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        client.close()

if __name__ == "__main__":
    # Replace with your actual server details and command
    HOST = "your_server_ip"
    USER = "your_username"
    PASS = "your_password"
    CMD = "echo Hello from Paramiko!"
    
    print("Attempting to connect with Paramiko...")
    connect_and_run(HOST, USER, PASS, CMD)
    print("Note: This code won't connect without a live server and valid credentials.")

Handling Command Output

When you run client.exec_command(command), it returns three file-like objects: stdin, stdout, and stderr.

  • stdout: The standard output of the command.
  • stderr: Any error messages produced by the command.
  • stdin: Used to send input to the command (less common for simple exec).

Always decode the output (e.g., .decode()) as it comes as bytes.

Paramiko for File Transfers (SFTP)

Beyond running commands, Paramiko also supports SFTP (SSH File Transfer Protocol). This allows you to securely copy files to and from remote systems.

You can use it to upload configuration files, download logs, or manage software packages on your network devices.

Introducing Netmiko

While Paramiko is powerful, interacting with specific network devices often requires extra logic for prompts, pagination, and different command modes. That's where Netmiko shines!

  • Built on Paramiko: Uses Paramiko under the hood.
  • Device-Specific: Supports many vendors (Cisco, Juniper, Arista, etc.).
  • Simplified API: Handles common network device interactions automatically.

Netmiko: Connect to Network Devices

Netmiko uses a dictionary to define device details, making connections straightforward. It simplifies many network automation tasks.

from netmiko import ConnectHandler

def connect_with_netmiko(device_info):
    try:
        print(f"Attempting to connect to {device_info['host']} with Netmiko...")
        net_connect = ConnectHandler(**device_info)
        print(f"Successfully connected to {net_connect.base_prompt}")
        net_connect.disconnect()
        print("Disconnected from device.")
    except Exception as e:
        print(f"Netmiko connection error: {e}")

if __name__ == "__main__":
    # Replace with your actual device details
    device = {
        "device_type": "cisco_ios", # e.g., cisco_ios, juniper_junos, etc.
        "host": "your_device_ip",
        "username": "your_username",
        "password": "your_password",
        "secret": "your_enable_secret" # Optional, for enable mode
    }
    
    connect_with_netmiko(device)
    print("Note: This code won't connect without a live device and valid credentials.")

Netmiko: Sending Configuration

Netmiko excels at sending configuration commands. Use send_config_set() for a list of commands and send_command() for operational commands.

from netmiko import ConnectHandler

def send_config_to_device(device_info, config_commands):
    try:
        print(f"Connecting to {device_info['host']} to send config...")
        net_connect = ConnectHandler(**device_info)
        
        print("Sending configuration commands...")
        output = net_connect.send_config_set(config_commands)
        print(f"Configuration Output:\n{output}")
        
        net_connect.disconnect()
        print("Disconnected.")
    except Exception as e:
        print(f"Netmiko config error: {e}")

if __name__ == "__main__":
    # Replace with your actual device details
    device = {
        "device_type": "cisco_ios",
        "host": "your_device_ip",
        "username": "your_username",
        "password": "your_password",
        "secret": "your_enable_secret"
    }
    
    # Example configuration commands
    config_lines = [
        "hostname CoddyRouter",
        "no ip domain lookup",
        "line vty 0 4",
        "login local"
    ]
    
    send_config_to_device(device, config_lines)
    print("Note: This code won't apply config without a live device and valid credentials.")

Best Practices & Security

When automating, always prioritize security and robustness:

  • Credential Management: Never hardcode passwords. Use environment variables, secure vaults, or input prompts.
  • Error Handling: Use try-except blocks to catch connection issues or command failures gracefully.
  • Logging: Log all actions and outputs for auditing and troubleshooting.
  • Idempotency: Design scripts to be idempotent (running them multiple times has the same effect as running once).

Paramiko vs. Netmiko

You've seen both Paramiko and Netmiko. Now, let's test your understanding of when to use which tool for your network automation tasks.

Recap: Python for Net Automation

Great job! In this lesson, you learned about:

  • Paramiko: A low-level Python library for general SSH client/server tasks and SFTP.
  • Netmiko: A higher-level library built on Paramiko, specifically designed for automating interactions with various network devices.

These tools empower you to write powerful Python scripts to manage, configure, and monitor your network infrastructure programmatically!

常见问题解答

「使用 Python 实现网络自动化」课时是免费的吗?

是的 — 「使用 Python 实现网络自动化」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Linux Networking & TCP/IP for Developers 课程的其余内容,请升级到 CoddyKit PRO。 Linux Networking & TCP/IP for Developers 课程共包含 4 节课。

「使用 Python 实现网络自动化」这节课中我会学到什么?

使用 `paramiko` 和 `netmiko` 等 Python 库,通过 SSH 与网络设备交互并自动配置 你通过在浏览器中直接运行的动手代码来练习 Linux Networking & TCP/IP for Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Linux Networking & TCP/IP for Developers 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Linux Networking & TCP/IP for Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 Python 实现网络自动化」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Linux Networking & TCP/IP for Developers 课中编写并运行代码吗?

能。每节 Linux Networking & TCP/IP for Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Bash 编写网络脚本
  2. 使用 Python 实现网络自动化
  3. 网络设备的 REST API
  4. 使用 Ansible 进行网络配置
← 返回 Linux Networking & TCP/IP for Developers