杰瑞科技汇

Python SSHLibrary如何实现远程自动化?

Of course! The robotframework-sshlibrary is a powerful and popular Robot Framework library for automating remote server interactions over SSH. It's an essential tool for system administrators, DevOps engineers, and anyone who needs to automate tasks on remote machines.

Python SSHLibrary如何实现远程自动化?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything from installation to advanced usage.


What is SSHLibrary?

robotframework-sshlibrary is a Robot Framework library that provides keywords for connecting to remote servers using SSH (Secure Shell) and executing commands. It's built on top of the popular paramiko Python library.

Key Features:

  • Establish SSH Connections: Connect to servers with password, public key, or keyboard-interactive authentication.
  • Execute Commands: Run single commands or entire shell scripts on the remote machine.
  • File Transfer: Upload and download files and directories (SFTP).
  • Handle Interactive Sessions: Manage shells that require interactive input (e.g., sudo prompts).
  • Robust Output Handling: Easily access command return codes, standard output, and standard error.
  • Built-in Keywords: Comes with a rich set of keywords for common tasks like checking if a file exists, reading a file's content, etc.

Installation

First, you need to install the library using pip. It's also highly recommended to install the robotframework package itself if you haven't already.

Python SSHLibrary如何实现远程自动化?-图2
(图片来源网络,侵删)
# Install the SSHLibrary
pip install robotframework-sshlibrary
# (Optional but recommended) Install Robot Framework
pip install robotframework

Basic Usage and Keywords

Let's start with a simple Robot Framework test case (test.robot) that connects to a server, runs a command, and checks the output.

test.robot

*** Settings ***
Library    SSHLibrary
*** Variables ***
${HOST}        192.168.1.100
${USERNAME}    myuser
${PASSWORD}    mypassword
*** Test Cases ***
Connect and Check Disk Usage
    [Documentation]    Connects to a server and checks the disk usage of the root partition.
    # 1. Open a connection to the remote host
    Open Connection    ${HOST}
    Login    ${USERNAME}    ${PASSWORD}
    # 2. Execute a command and get its output
    ${output}=    Execute Command    df -h / | awk 'NR==2 {print $5}'
    # 3. Log the result to the console
    Log    Disk usage is: ${output}
    # 4. Assert a condition (e.g., disk usage is less than 90%)
    Should Match Regexp    ${output}    \d+%    msg=Disk usage percentage not found
    ${usage_percentage}=    Evaluate    int('${output}'.replace('%', ''))
    Should Be True    ${usage_percentage} < 90    msg=Disk usage is too high!
    # 5. Close the connection
    Close Connection

Explanation of Keywords Used:

  • Library SSHLibrary: Imports the library into your test suite.
  • Open Connection ${HOST}: Opens an SSH connection to the specified host. You can also specify port, timeout, and alias here.
  • Login ${USERNAME} ${PASSWORD}: Authenticates the user with the given credentials.
  • Execute Command <command>: Executes a command on the remote server and returns its standard output as a string. It waits for the command to finish.
  • Log <message>: Writes a message to the log file and console.
  • Should Match Regexp: A built Robot Framework keyword for assertion. It checks if the output matches a regular expression.
  • Should Be True: Another assertion keyword.
  • Close Connection: Closes the active SSH connection.

Advanced Features

1. Handling sudo Prompts

When a command requires sudo and asks for a password, you can handle it using the Run Command keyword and providing the password.

*** Test Cases ***
Run Sudo Command
    Open Connection    ${HOST}
    Login    ${USERNAME}    ${PASSWORD}
    # The 'sudo' command will prompt for a password.
    # We provide it using the 'sudo_password' argument.
    ${output}=    Run Command    sudo ls /root    sudo_password=${PASSWORD}
    Log    Successfully listed /root directory: ${output}
    Close Connection

Note: For security, avoid passing passwords directly in test files. Use Robot Framework's variable files or environment variables.

Python SSHLibrary如何实现远程自动化?-图3
(图片来源网络,侵删)

2. File and Directory Operations (SFTP)

The library provides keywords for file transfer.

*** Test Cases ***
Upload and Download Files
    Open Connection    ${HOST}
    Login    ${USERNAME}    ${PASSWORD}
    # --- Upload a file ---
    # Create a local file for the test
    Create File    local_test_file.txt    This is a test file.
    # Upload it to the remote server's home directory
    Put File    local_test_file.txt    /home/${USERNAME}/remote_test_file.txt
    # Verify the file exists on the remote server
    File Should Exist    /home/${USERNAME}/remote_test_file.txt
    # --- Download a file ---
    # Download the file back to the local machine
    Get File    /home/${USERNAME}/remote_test_file.txt    downloaded_file.txt
    # Verify the downloaded file's content
    ${content}=    Get File    downloaded_file.txt
    Should Be Equal    ${content}    This is a test file.
    # Clean up local files
    Remove File    local_test_file.txt
    Remove File    downloaded_file.txt
    Close Connection

Key SFTP Keywords:

  • Put File <local_path> <remote_path>: Uploads a file.
  • Get File <remote_path> <local_path>: Downloads a file.
  • File Should Exist <remote_path>: Checks if a file exists on the remote server.
  • Directory Should Exist <remote_path>: Checks if a directory exists.
  • Create Directory <remote_path>: Creates a new directory.
  • Remove File <remote_path>: Deletes a file.
  • Remove Directory <remote_path>: Deletes a directory.

3. Starting an Interactive Shell

Sometimes you need to run multiple commands in the same shell session, or work with an interactive application. For this, you use Start Shell and Write / Read keywords.

*** Test Cases ***
Interactive Shell Example
    Open Connection    ${HOST}
    Login    ${USERNAME}    ${PASSWORD}
    # Start an interactive shell session
    Start Shell
    # Change directory and list files
    Write    cd /tmp
    Write    ls -l
    # Read the output from the 'ls' command
    # 'prompt=' is important to avoid reading the shell prompt itself
    ${output}=    Read    prompt=
    Log    Contents of /tmp: ${output}
    # Exit the shell
    Write    exit
    # Close the connection
    Close Connection

Key Interactive Keywords:

  • Start Shell: Starts an interactive shell session.
  • Write <command>: Sends a command to the shell.
  • Read prompt=<your_prompt>: Reads output from the shell until it encounters the specified prompt. This is crucial for knowing when a command has finished.
  • Write Until <string>: Keeps writing until a certain string is received in the output.

Best Practices

  1. Use Variables: Store hostnames, usernames, and passwords in variables or separate variable files (e.g., vars.py or .env). Never hardcode credentials in your test files.
  2. Manage Connections: Use Open Connection with an alias if you need to connect to multiple servers. Always use Close Connection to free up resources.
  3. Handle Timeouts: If a command might take a long time, use the timeout argument in Execute Command.
    ${output}=    Execute Command    long_running_script.sh    timeout=300
  4. Use Get Connection for Details: You can retrieve information about the current connection.
    ${host}=    Get Connection    host
    Log    Connected to: ${host}
  5. Logging: Use the Log keyword extensively to debug your tests. You can control log levels in the Robot Framework runner (--loglevel).

Complete Example with robot.yaml (Modern Robot Framework)

Here is a more complete, modern example using a YAML settings file (robot.yaml) for better variable management.

robot.yaml

---
Settings:
  documentation: A complete example of SSHLibrary usage.
  suite_setup:    Open Connection And Login
  suite_teardown: Close All Connections
Variables:
  HOST:      192.168.1.100
  USERNAME:  myuser
  PASSWORD:  mypassword
  REMOTE_DIR: /tmp/robot_test
Test Cases:
  Verify System Info
    [Documentation]    Get and verify basic system information.
    ${os_info}=    Get System Info
    Log    OS Info: ${os_info}
    Should Contain    ${os_info}    Linux
  Create And Manage Directory
    [Documentation]    Create a directory, upload a file, and clean up.
    # Create a directory on the remote server
    Create Directory    ${REMOTE_DIR}
    Directory Should Exist    ${REMOTE_DIR}
    # Create a local file and upload it
    Create File    local_file.txt    Hello from Robot Framework!
    Put File    local_file.txt    ${REMOTE_DIR}/uploaded_file.txt
    File Should Exist    ${REMOTE_DIR}/uploaded_file.txt
    # Read the file's content from the remote server
    ${content}=    Get File    ${REMOTE_DIR}/uploaded_file.txt
    Should Be Equal    ${content}    Hello from Robot Framework!
    # Clean up the remote directory
    Remove File    ${REMOTE_DIR}/uploaded_file.txt
    Remove Directory    ${REMOTE_DIR}
Keywords:
  Open Connection And Login
    Open Connection    ${HOST}
    Login    ${USERNAME}    ${PASSWORD}
  Get System Info
    ${output}=    Execute Command    uname -a
    [Return]    ${output}

This example demonstrates:

  • Suite Setup/Teardown: Automatically opening/closing connections for all test cases in the suite.
  • Variable Centralization: All configuration is in the robot.yaml file.
  • User-Defined Keywords: Creating reusable keywords like Get System Info to make tests cleaner and more readable.
分享:
扫描分享到社交APP
上一篇
下一篇