bstinson / centos / t_functional

Forked from centos/t_functional 3 years ago
Clone

Blame tests/p_openssh/sshd_user_login.py

Karanbir Singh 0b5bb2
#!/usr/bin/python
Karanbir Singh 0b5bb2
# Author: Athmane Madjoudj <athmanem@gmail.com>
Karanbir Singh 0b5bb2
Karanbir Singh 0b5bb2
import os,sys
Karanbir Singh 0b5bb2
Karanbir Singh 0b5bb2
def install_pexpect():
Karanbir Singh 0b5bb2
    if os.system("rpm -q pexpect") == 0:
Karanbir Singh 0b5bb2
        return 0
Karanbir Singh 0b5bb2
    else:
Karanbir Singh 0b5bb2
        return os.system("yum -y install pexpect")
Karanbir Singh 0b5bb2
Karanbir Singh 0b5bb2
def ssh_command (user, host, password, command):
Karanbir Singh 0b5bb2
    import pexpect
Karanbir Singh 0b5bb2
    ssh_newkey = 'Are you sure you want to continue connecting'
Karanbir Singh 0b5bb2
    child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
Karanbir Singh 0b5bb2
    i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
Karanbir Singh 0b5bb2
    if i == 0: # Timeout
Karanbir Singh 0b5bb2
        print child.before, child.after
Karanbir Singh 0b5bb2
        return None
Karanbir Singh 0b5bb2
    if i == 1: # SSH does not have the public key. Just accept it.
Karanbir Singh 0b5bb2
        child.sendline ('yes')
Karanbir Singh 0b5bb2
        child.expect ('password: ')
Karanbir Singh 0b5bb2
        i = child.expect([pexpect.TIMEOUT, 'password: '])
Karanbir Singh 0b5bb2
        if i == 0: # Timeout
Karanbir Singh 0b5bb2
            print child.before, child.after
Karanbir Singh 0b5bb2
            return None       
Karanbir Singh 0b5bb2
    child.sendline(password)
Karanbir Singh 0b5bb2
    child.expect(pexpect.EOF)
Karanbir Singh 0b5bb2
    print child.before
Karanbir Singh 0b5bb2
    return child.before
Karanbir Singh 0b5bb2
Karanbir Singh 0b5bb2
if __name__ == '__main__':
Karanbir Singh 0b5bb2
    if not os.geteuid()==0:
Karanbir Singh 0b5bb2
        sys.exit("root privileges are required to run this script")
Karanbir Singh 0b5bb2
    else:
Karanbir Singh 0b5bb2
        print "[INFO] Trying to install pexpect ..."
Karanbir Singh 0b5bb2
        if install_pexpect() != 0:
Karanbir Singh 0b5bb2
            sys.exit("[FAIL] pexpect installation failed")
Karanbir Singh 0b5bb2
        print "[INFO] Adding new user ..."
Steve Barnes bf9e19
        if os.system("userdel -rf sshtest; useradd sshtest && echo sshtest | passwd --stdin sshtest") != 0:
Karanbir Singh 0b5bb2
            sys.exit("[FAIL] can't add new user")
Karanbir Singh 0b5bb2
        try:
Karanbir Singh 0b5bb2
            ssh_command('sshtest','localhost','sshtest','/bin/ls')
Karanbir Singh 0b5bb2
        except Exception, e:
Karanbir Singh 0b5bb2
            sys.exit("[FAIL] SSH could not login")
Karanbir Singh 0b5bb2
        else:
Karanbir Singh 0b5bb2
            print "[INFO] SSH user login test: PASS"
Karanbir Singh 0b5bb2
Karanbir Singh 0b5bb2
Karanbir Singh 0b5bb2