Menu

1 / 2

Python SSH Automation: Manage 100 Servers From One Script

DEV Community·Brad·6 months ago
#wPTI7g1R
#python#automation#devops#linux#servers
Reading 0:00
15s threshold

Python SSH Automation: Manage 100 Servers From One Script

Managing infrastructure manually doesn't scale. Here's how to automate SSH operations across fleets of servers with Python.

The Problem with Manual SSH

Imagine patching 50 servers one-by-one. That's 50 SSH sessions, 50 copy-paste operations, 50 chances for human error.

Paramiko: Python's SSH Library

import paramiko import logging

logging . basicConfig ( level = logging . INFO )

class SSHClient : def __init__ ( self , hostname : str , username : str , key_path : str ): self . hostname = hostname self . client = paramiko . SSHClient () self . client . set_missing_host_key_policy ( paramiko . AutoAddPolicy ()) self . client . connect ( hostname , username = username , key_filename = key_path , timeout = 10 )

def run ( self , command : str ) -> tuple : stdin , stdout , stderr = self . client . exec_command ( command ) exit_code = stdout . channel . recv_exit_status () return stdout . read (). decode (), stderr . read ().…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.