[421] | 1 | #!/usr/bin/env python
|
---|
| 2 | '''Change passwords on the named machines.
|
---|
| 3 | passmass host1 host2 host3 . . .
|
---|
| 4 | Note that login shell prompt on remote machine must end in # or $.
|
---|
| 5 | '''
|
---|
| 6 |
|
---|
| 7 | import pexpect
|
---|
| 8 | import sys, getpass
|
---|
| 9 |
|
---|
| 10 | USAGE = '''passmass host1 host2 host3 . . .'''
|
---|
| 11 | SHELL_PROMPT = '[#\$] '
|
---|
| 12 |
|
---|
| 13 | def login(host, user, password):
|
---|
| 14 | child = pexpect.spawn('ssh %s@%s'%(user, host))
|
---|
| 15 | child.expect('password:')
|
---|
| 16 | child.sendline(password)
|
---|
| 17 | i = child.expect(['Permission denied', SHELL_PROMPT, 'Terminal type'])
|
---|
| 18 | if i == 0:
|
---|
| 19 | print 'Permission denied on host:', host
|
---|
| 20 | return None
|
---|
| 21 | elif i == 2:
|
---|
| 22 | child.sendline('vt100')
|
---|
| 23 | i = child.expect('[#\$] ')
|
---|
| 24 | return child
|
---|
| 25 |
|
---|
| 26 | def change_password(child, user, oldpassword, newpassword):
|
---|
| 27 | child.sendline('passwd %s'%user)
|
---|
| 28 | i = child.expect(['Old [Pp]assword', 'New [Pp]assword'])
|
---|
| 29 | # Root does not require old password, so it gets to bypass the next step.
|
---|
| 30 | if i == 0:
|
---|
| 31 | child.sendline(oldpassword)
|
---|
| 32 | child.expect('New [Pp]assword')
|
---|
| 33 | child.sendline(newpassword)
|
---|
| 34 | i = child.expect(['New [Pp]assword', 'Retype', 'Re-enter'])
|
---|
| 35 | if i == 0:
|
---|
| 36 | print 'Host did not like new password. Here is what it said...'
|
---|
| 37 | print child.before
|
---|
| 38 | child.send (chr(3)) # Ctrl-C
|
---|
| 39 | child.sendline('') # This should tell remote passwd command to quit.
|
---|
| 40 | return
|
---|
| 41 | child.sendline(newpassword)
|
---|
| 42 |
|
---|
| 43 | def main():
|
---|
| 44 | if len(sys.argv) <= 1:
|
---|
| 45 | print USAGE
|
---|
| 46 | return 1
|
---|
| 47 |
|
---|
| 48 | user = raw_input('Username: ')
|
---|
| 49 | password = getpass.getpass('Current Password: ')
|
---|
| 50 | newpassword = getpass.getpass('New Password: ')
|
---|
| 51 | newpasswordconfirm = getpass.getpass('Confirm New Password: ')
|
---|
| 52 | if newpassword != newpasswordconfirm:
|
---|
| 53 | print 'New Passwords do not match.'
|
---|
| 54 | return 1
|
---|
| 55 |
|
---|
| 56 | for host in sys.argv[1:]:
|
---|
| 57 | child = login(host, user, password)
|
---|
| 58 | if child == None:
|
---|
| 59 | print 'Could not login to host:', host
|
---|
| 60 | continue
|
---|
| 61 | print 'Changing password on host:', host
|
---|
| 62 | change_password(child, user, password, newpassword)
|
---|
| 63 | child.expect(SHELL_PROMPT)
|
---|
| 64 | child.sendline('exit')
|
---|
| 65 |
|
---|
| 66 | if __name__ == '__main__':
|
---|
| 67 | try:
|
---|
| 68 | main()
|
---|
| 69 | except pexpect.ExceptionPexpect, e:
|
---|
| 70 | print str(e)
|
---|
| 71 |
|
---|
| 72 |
|
---|