如何用Python对hostname.txt中的多台服务器执行SSH及command.txt内的命令?
Python SSH Automation for Multiple Servers and Commands
Got it, let's tackle this problem step by step. You want to connect to multiple servers listed in hostname.txt and run commands from command.txt via SSH using Python—here's a solid, practical approach using the paramiko library, which is the go-to tool for SSH operations in Python.
Prerequisites
First, get the necessary tools set up:
- Install the
paramikolibrary:pip install paramiko - Format your input files correctly:
hostname.txtshould have one server hostname/IP per line (no extra spaces or empty lines):server1
server2
server3
server4
server5command.txtshould list one Linux command per line:service httpd status
service dhcpd status
Full Implementation Code
This script handles file reading, SSH connections, command execution, and error handling so you don't have to worry about a single failed server breaking the whole workflow:
import paramiko from paramiko.ssh_exception import SSHException, NoValidConnectionsError, AuthenticationException def read_file_lines(file_path): """Read non-empty lines from a text file""" with open(file_path, 'r') as f: return [line.strip() for line in f if line.strip()] def run_commands_on_server(hostname, username, auth_cred, commands, use_key=False): """Connect to a server via SSH and execute a list of commands""" ssh_client = None try: # Initialize SSH client ssh_client = paramiko.SSHClient() # Auto-add unknown hosts (adjust for production environments!) ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect using password or SSH key if use_key: ssh_client.connect( hostname=hostname, username=username, key_filename=auth_cred, timeout=10 ) else: ssh_client.connect( hostname=hostname, username=username, password=auth_cred, timeout=10 ) print(f"\n=== Connected to {hostname} ===") for cmd in commands: print(f"\nRunning command: `{cmd}`") # Execute the command stdin, stdout, stderr = ssh_client.exec_command(cmd) # Capture output and errors output = stdout.read().decode('utf-8').strip() error = stderr.read().decode('utf-8').strip() if output: print("Output:") print(output) if error: print("Error:") print(error) except AuthenticationException: print(f"❌ Authentication failed for {hostname} (check credentials/key)") except NoValidConnectionsError: print(f"❌ Could not connect to {hostname} (verify hostname/network)") except SSHException as e: print(f"❌ SSH error with {hostname}: {str(e)}") except Exception as e: print(f"❌ Unexpected error with {hostname}: {str(e)}") finally: # Clean up the connection if ssh_client and ssh_client.get_transport().is_active(): ssh_client.close() print(f"\n=== Disconnected from {hostname} ===") if __name__ == "__main__": # Update these with your actual credentials! USERNAME = "your_server_username" # Use this for password auth PASSWORD = "your_server_password" # Use this for SSH key auth (uncomment and set path, then set use_key=True below) # PRIVATE_KEY_PATH = "/home/your_user/.ssh/id_rsa" # Load hosts and commands from files hosts = read_file_lines("hostname.txt") commands = read_file_lines("command.txt") # Validate input files if not hosts: print("⚠️ No servers found in hostname.txt") if not commands: print("⚠️ No commands found in command.txt") # Run commands on each server for host in hosts: # Use password auth by default run_commands_on_server(host, USERNAME, PASSWORD, commands) # Switch to key auth by uncommenting this line and commenting the one above # run_commands_on_server(host, USERNAME, PRIVATE_KEY_PATH, commands, use_key=True)
Key Tips for Production & Improvement
- Security First: Never hardcode passwords in scripts! Use environment variables or a secure secrets manager instead. SSH key-based auth is always more secure than password auth—switch to that if you can.
- Host Key Safety: The
AutoAddPolicy()is convenient for testing, but in production, useRejectPolicy()or load known hosts to avoid man-in-the-middle attacks. - Timeout Handling: The 10-second timeout prevents the script from hanging on unresponsive servers.
- Logging: For larger workflows, add logging instead of print statements to track activity over time.
Testing the Script
- Save the code as
ssh_automation.py - Update the username and authentication details in the
__main__block - Ensure
hostname.txtandcommand.txtare in the same directory as the script - Run it with:
python ssh_automation.py
内容的提问来源于stack exchange,提问作者Arv
相关产品推荐
相关产品推荐

