Python: Check IPs for DNS entries and see if host is UP or DOWN, check SSH login. Export info to a CSV file

This script is a simple revision of the DNS_HOST_CHECK.py script. The difference is this script, in addition to the previous checks, attempts also an SSH login and reports back it failed or not

import socket
import subprocess
import netifaces
import csv
import paramiko
 
def checkPING(IP):
    try:
        ping = subprocess.check_output(['ping', '-c1', ip])
        return "Host is UP"
    except:
        return "Host is DOWN"
 
def checkDNS(IP):
    try:
        dns = socket.gethostbyaddr(ip)
        return dns[0]
    except:
        return "No DNS entry found"
 
def checkSSH(IP):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username='root', password='Password!')
        ssh.close()
        return "SSH OK"
    except:
        return "SSH NO"
 
ip_list = []
dns_list = []
status_list = []
ssh_list = []
 
csvfile= open('file.csv', 'w')
for loop_ip in range (30):
    ip = '10.0.0.%d' % loop_ip
    print ip, checkDNS(ip), checkPING(ip),checkSSH(ip)
    data = ip+" ",checkDNS(ip)+" ",checkPING(ip)+" ",checkSSH(ip)
    #data_list.append(data)
    ip_list.append(ip)
    dns_list.append(checkDNS(ip))
    status_list.append(checkPING(ip))
    ssh_list.append(checkSSH(ip))
#print data_list
writer = csv.writer(csvfile, dialect='excel')
writer.writerows(zip(ip_list, dns_list, status_list, ssh_list))

Share Button

Python – Paramiko module

Paramiko is a Python module that is used to remotely connect via SSH to remote servers and execute commands on that server. The script below connects to a remote server with the username and password provided in order to transfer a file. It also changes the permissions of the file transferred.

import sys
import paramiko
sys.stderr = open('/dev/null')  
import psutil

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('10.0.0.10', username='root', password='JamesBond')
sftp = ssh.open_sftp()
sftp.put('/home/Batman/Documents/python/scripts/testing.py', '/root/testing.py')
stdin, stdout, stderr = ssh.exec_command("chmod +x /root/testing.py")
stdin, stdout, stderr = ssh.exec_command("python /root/testing.py")

print stdout.channel.recv(1024)

ssh.close()
Share Button