利用python的pexpect模块,自动登陆服务器

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pexpect
import struct, fcntl, os, sys, signal

import termios

# 此函数用来设置合适的窗口大小

def sigwinch_passthrough (sig, data):
    # Check for buggy platforms (see pexpect.setwinsize()).
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912 # assume
    s = struct.pack ("HHHH", 0, 0, 0, 0)
    a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
    global global_pexpect_instance
    print a[0],a[1]
    global_pexpect_instance.setwinsize(a[0],a[1])

def main(host):
    password = ' your passwd'
    p = pexpect.spawn("ssh root@%s" % host)
    try:
       index = p.expect("Name or service not known",timeout=1)
       if index == 0:
           print 'host is wrong'
           sys.exit(1)

    except pexpect.TIMEOUT:
           pass

    count = 0
    try:
        i = p.expect(['password:', 'continue connecting (yes/no)?'],timeout=5)
        if i == 0:  
            p.sendline(password)
        elif i == 1:  
            p.sendline("yes")  
            p.expect(['password:'])  
            p.sendline(password)  
    except pexpect.TIMEOUT:  
        print 'Connection timeout'  
    except pexpect.EOF:  
        print 'Connection exit'  
        p.close()  
    except Exception,e:  
        print "Connection close",e  

    global global_pexpect_instance
    global_pexpect_instance = p
    #signal.signal(signal.SIGWINCH, sigwinch_passthrough)
    sigwinch_passthrough(1,2)
    try:
        #p.setwinsize(100,125)
        p.interact()
        sys.exit(0)
    except:
        sys.exit(1)

if __name__ == '__main__':
    main(sys.argv[1])

你可能感兴趣的:(python,自动登陆,linux)