Python ‐ Using Fabric to run Linux commands via SSH - dishplate/blog GitHub Wiki

#ICA - infrastructure as code
from fabric import Connection
import csv
import os
from dotenv import load_dotenv
load_dotenv()  # take environment variables from .env.

# List of IP addresses of the Ubuntu servers
server_ips = ["172.22.22.101","172.22.22.7"]

# SSH credentials
username = os.getenv("username")
password = os.getenv("password")  

def get_hostname(ip):
    try:
        conn = Connection(host=ip, user=username, connect_kwargs={"password": password})
        result = conn.run('hostname', hide=False)
        #run arbitrary command
        command1 = conn.run('date', hide=False)
        return result.stdout.strip(), "Success"
    except Exception as e:
        return None, f"Failed: {str(e)}"

# CSV file to store the results
csv_file = 'server_hostnames.csv'

with open(csv_file, mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["IP Address", "Hostname", "Status"])
    
    for ip in server_ips:
        hostname, status = get_hostname(ip)
        writer.writerow([ip, hostname if hostname else "N/A", status])

print(f"Results written to {csv_file}")