Pages

31 December 2010

SSH checker

This simple script for check ssh login
Writing on python with use module py-paramiko

for using need install module paramiko
in Freebsd install from ports:
cd /usr/ports/security/py-paramiko && make install clean
or install from source
import paramiko
import sys, os 
import socket
import re

# - - - - - - - - - - - - - - - - #
#          SSH Checker            #
# - - - - - - - - - - - - - - - - #

#log_file    = "log.txt"
read_access = "access.txt"
sucess = 0

ssh = paramiko.SSHClient()


#    Test on connect to server 
def is_work_sshd(host, dPort=22):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    sock.settimeout(20) 
    try:
        sock.connect((host, dPort))
    except:
    #    print "Connect to ssh server timeout"
        return 1

#    print "Connect Ok"
    sock.close()
    return 0

''' Test host on avalible 
def pinger(host):
    result_ping = os.popen("ping -c 3 %s" % host)
    if result_ping.read().search("bytes"):
        print "find bytes"
        return 1
    return 0
'''
    
def check_server(host, user, password, port=22):
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # test on connect to ssh
    if is_work_sshd(host,port): return 2
    
    try:
        ssh.connect(host, username=user, password=password, port=port)
#        print "Ok"            # Connect sucess ;)
    
        ssh.close()             # Close ssh session
    except:
        #print 'Error'
        return 1
    return 0

if not os.path.exists(os.getcwd() + '/' + read_access):
    print "File not found!"
    sys.exit()

fd = open(read_access, "r")
for i in fd.readlines():
     if  i[-1:] == '\n':
        i = i[:-1]
 
    port = 22
    #print i  #Debug blia
    res = i.split(':')
    if(len(res) > 2):
        user,host,password = res[:3]
    if(len(res) > 3):
        port = int(res[3])

    #print user, host, password, port
    ret = check_server(host, user, password, port)
    if not ret:
        print "Connect to %s [success]" % host
    elif ret == 1:
        print "Connect to %s [error]" % host
    else: 
        print "Connect to %s [timeout]" % host

0 comments: