This post will see how to write a python script for login multiple Unix server and execute a command.
Additionally, the python script is going to save the output of that command in a text file.
Overview of Python Script For Login Multiple Unix Server
Before writing any scripts, it necessary to prepare the steps. It would be best if you considered every action that you do manually.
Below are the overall steps of Python Script For Login Multiple Unix Server
- Install the Paramiko module.
- Read the credential from a CSV file.
- Log in to multiple Unix servers one by one.
- Execute a command.
- Save the output in a text file.
You can check out the below YouTube video for a live demo of the script.
Prerequisite For Python Script Login Multiple Server
Before we start writing the script, let us discuss the prerequisite to writing the script.
To write a Python Script For Login multiple servers, you need a paramiko library. Hence, first, install the python library.
Paramiko library is useful to connect any device which supports SSH connectivity.
Go to command prompt and execute the below command to install the paramiko module.
pip install paramiko
Once you install the library, create a CSV file in the below format and name it, “cred.csv.”
Keep the cred.csv file and the script in the same location.
Complete Python Script For Login Multiple Unix Server
Below is the complete python which can login to the multiple server and execute command.
p = paramiko.SSHClient()
cred = open(“cred.csv”,”r”)
for i in cred.readlines():
p.connect(“%s”%ls,port =22, username = “%s”%ls, password=”%s”%ls)
stdin, stdout, stderr = p.exec_command(“uname -a”)
opt = stdout.readlines()
The script’s first line imports a library, and the second line creates an object “p.”
The third line opens the cred.csv file and stores the content in the variable cred.
Then a for loop starts and reads all the lines of the credential file. Each line is converted into a python list with split function.
From the python list, the script fetches the server name and its user name and password. After that, using those credentials, the script connects to the device and executes the command.
The variable “opt” stores the output of the command. Finally, the script creates a file with the server name and stores the content in it.
Conclusion For Storage Admin
The script is capable of connecting to any device that supports SSH. Hence, a storage admin can use this python script to collect logs from Cisco, Brocade switch, Isilon, and NetApp.
You have to modify the “cred.csv” file and mention the correct command.