#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: gls-grade-krb5auth
# by: Joshua M. Hoffman
# last update: 20100830
"""
This script is for grading the krb5 lab in rh254.

This script attempts to ssh to localost with the username and password
given below. The script tries to identify timeouts and other types
of ssh failures, as well as authentication failure, to give the user
useful feedback.

IMPORTANT: This script requires that the pexpect package be installed!

Usage: Just run it, the script takes no arguements.
"""

import sys
import pexpect

username = 'ldapuser1'
password = 'kerberos'

def timeout():
    print('Connection timed out will trying to reach the ssh server.')
    print('Please verify that your ssh service is running and that your')
    print('firewall is not blocking connections to it. Then try running')
    print('this script again.')
    sys.exit(2)

def dumped():
    print('The connection was unexptedly dropped when trying to login to')
    print('your ssh server. Please verify that your ssh server is running')
    print('and try again. If you continue to see this message, ask your')
    print('instructor for assistance.')
    sys.exit(3)
    
def failure():
    print('Failed to login with username "%s" and password "%s"'%(username,password))
    print('Check your authentication settings and try again.')
    print('If you get stuck, ask your instructor for assistance.')
    sys.exit(1)
    
def success():
    print('Success!')
    print('User "%s" is able to login with password "%s"'%(username,password))
    sys.exit(0)

def check():
    ssh = pexpect.spawn('/usr/bin/ssh %s@localhost'%(username))
    i = ssh.expect(["Are you sure you want to continue connecting (yes/no)?",
                    "%s@localhost's password: "%(username),
                    pexpect.TIMEOUT,
                    pexpect.EOF])
    if i == 0: # firt time connecting
        ssh.sendline('yes')
        ssh.expect("%s@localhost's password: "%(username))
        ssh.sendline(password)
    if i == 1:
        ssh.sendline(password)
    if i == 2: # oops, timeout
        timeout()
    if i == 3: # connection refused/dumped
        dumped()
        
    i = ssh.expect(['\$ ', 'Permission denied, please try again.', pexpect.TIMEOUT, pexpect.EOF])
    if i == 0:
        ssh.sendline('exit')
        ssh.close()
        success()
    if i == 1:
        failure()
    if i == 2:
        timeout()
    if i == 3:
        dumped()
        
def main():
    print('Attempting to login via ssh as %s with password %s...'%(username,password))
    check()
    
if __name__ == '__main__':
    main() 
