Paramiko SSH输出不符合预期,如何在Python脚本中获取1100GB值?
Oh, I’ve been exactly where you are! The root cause here is that when you run commands with Paramiko using separate exec_command() calls, each one spins up a brand new SSH channel—think of it like opening a fresh terminal window on the device every time. Any context from your first command (like environment variables, directory changes, or temporary configs) doesn’t carry over, which is why the output doesn’t match what you see when running commands directly on the device.
To grab that "1100GB" value correctly, you need to run both of your commands in the same persistent SSH session/channel—just like how you’d type them one after another in the same terminal window on the device.
Here’s a concrete example of how to do this:
import paramiko import re import time # Set up the SSH connection ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( hostname="your_device_ip", username="your_username", password="your_password" ) # Get a persistent shell session (this is the key!) shell = ssh.invoke_shell() # Send your first command (e.g., setup, directory navigation, etc.) shell.send("your_first_prep_command\n") # Wait for the command to finish - adjust sleep time based on your device's response speed time.sleep(1) # Send the command that returns the "1100GB" value shell.send("your_target_command\n") time.sleep(1) # Read the full output from the session full_output = shell.recv(65535).decode("utf-8") # Extract the "1100GB" value using regex match = re.search(r"(\d+GB)", full_output) if match: desired_value = match.group(1) print(f"Successfully retrieved: {desired_value}") # Should output "1100GB" # Clean up the connection ssh.close()
A few key notes to make this work reliably:
- Avoid
exec_command()for sequential commands: Each call toexec_command()creates an isolated channel, so context isn’t shared.invoke_shell()gives you a single persistent session instead. - Improve the wait logic: Using
time.sleep()is a quick fix, but for production code, you should listen for your device’s command prompt (like#or$) to know when a command has finished executing—this is way more reliable than hardcoding sleep times. - Decode correctly: Make sure you use the right encoding for your device’s output (UTF-8 is standard, but some devices might use other encodings like ASCII).
内容的提问来源于stack exchange,提问作者abc

