Home » ComputerScience » Example using python paramiko for ssh

Example using python paramiko for ssh

#!/usr/bin/python3.6

import paramiko

serverList="/home/ansprod/hostfiles/linux_chkhost"
username="ansprod"

#############################################
# open the serverlist file
#############################################
try:
slist = open(serverList,'r')

except ValueError as e:
print("can't open server list file" + LOG + "\n");
exit(1);

for server in slist :
# verify not commented out of list
if server.startswith("#"):
continue
#verify not a blank line
if(server.strip()):
try:
server = server.strip()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("uname -r")
rev = ssh_stdout.read()
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("cat /etc/redhat-release | head -1")
os = ssh_stdout.read()

os=os.decode(encoding='UTF-8').strip()
rev=rev.decode(encoding='UTF-8').strip()
print(server+" "+rev+" "+os)

finally:
if (ssh):
ssh.close()


slist.close()

Leave a Reply