How to create a python script to ssh and run commands on multiple linux devices

Question:

I’ve been scalping to find an explained python script to ssh to multiple Linux devices via ssh using paramiko. I found a few tweaked them and actually worked but i still cannot understand how it works.

Can someone please explain in the most appealing way how a python script to ssh to multiple Linux device and run commands works? Just as you would explain to a 6 year old. I mean I saw some scripts and they haver some complexity for no reason. I just wanted a Python script that imports a txt of hostnames and a another txt of commands and runs the same commands to all the Linux devices and returns the output. If someone could explain how such a script works I would be grateful.

ip = input("Please enter the hostname ")
user = ""
password = ""

print ("creating ssh")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("please wait")
ssh_client.connect(hostname=ip, username=user, password=password)

cmd= "uname -r;pwd"
print("please wait")
sdtin,stdout,stderr = ssh_client.exec_command(cmd)
print("success")
stdout = stdout.readlines()
stdout = "".join(stdout)
print (stdout)

I want this but for multiple devices and getting the hostnames and commands from 2 separate files.

Asked By: rick_sorkin

||

Answers:

Turns out I’ve found the answer (the perfect script for what I want).
Here it is:

import paramiko
import time
p = paramiko.SSHClient()
cred = open("hostnames.csv","r")
for i in cred.readlines():
        line=i.strip()
        ls =line.split(",")
        print(ls[0])
        p.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        p.connect("%s"%ls[0],port =22, username = "%s"%ls[1], password="%s"%ls[2])
        stdin, stdout, stderr = p.exec_command('sudo pwd' , get_pty=True)
        stdin.write("%sn"%ls[2])
        stdin.flush()
        opt = stdout.readlines()
        opt ="".join(opt)
        print(opt)
cred.close()

So, it basically reads the csv file with is formatted as : hostname,username,password
and runs the script sequentially. Also, it can run sudo commands this way 🙂

Answered By: rick_sorkin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.