Login To Multiple Server And Run Unix Command Python Script

Login To Multiple Server And Run Unix Command Python Script


In this script we will write python code which will login to multiple Unix server and execute an command. After that what ever output that command will give the script will save it in a text file.


Login To Multiple Server And Run Unix Command Python Script


Overview of Python Script. For live demo watch the video here.

1. Read Credential from CSV file
2. Login to multiple device one by one
3. Execute command
4. Save the output in txt file

Below is the script written python which will login to multiple device and execute command.
Below line will import a module called paramiko which is used for ssh connectivity to UNIX server.

import paramiko

Below line will initiate and object for ssh connectivity.

p = paramiko.SSHClient()

Below line will open a the credential file in read mode where we have credential for the devices.

cred = open("cred.csv","r")

Now below is the for loop which will iterate over each line of the file and get the credential, login to the device and execute a command. Then the ouput of the command for each device will be saved in a text file.

for i in cred.readlines():
    line=i.strip()
    ls =line.split(",")
    print(ls)
    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("uname -a")
    opt = stdout.readlines()
    opt ="".join(opt)
    print(opt)
    temp=open("%s.txt"%ls[0],"w")
    temp.write(opt)
    temp.close()
cred.close()
           
For More details watch the video and Subscribe and stay tuned for more such videos.

          

No comments:

Post a Comment

Zoning In Cisco MDS SAN Switch In Command Line

Zoning In Cisco MDS SAN Switch In Command Line Zoning is a process of grouping initiator and target ports WWPN which is performed in SAN ...