Python学习——定义一个pexpect的ssh_login函数

 1 def ssh_login(ip, user="root", passwd=None, prompt="]#", port="22", log_file=None, raise_exception=True):
 2     """
 3         Login remote host with ssh
 4         return pexpect.spawn
 5     """
 6     cmd = "ssh %s@%s -p %s" % (user, ip, port)
 7     p = pexpect.spawn(cmd)
 8     p.logfile = open_log_file(log_file)
 9 
10     Flag = True
11     index = p.expect(["[Pp]assword:", "(yes/no)", prompt, pexpect.EOF])
12     if index == 0:
13         p.sendline(passwd)
14     elif index == 1:
15         p.sendline("yes")
16         p.expect("[Pp]assword:")
17         p.sendline(passwd)
18     elif index == 2:  #already login
19         Flag = False
20     else:
21         if raise_exception:
22             raise Exception("Unable to login, please try again later.")
23         else:
24             return None
25     if Flag:
26         index = p.expect([prompt, "[Pp]assword:"])
27         if index == 1:
28             if raise_exception:
29                 raise Exception("Wrong password to remote host")
30             else:
31                 return None
32     return p    #ssh successfully and return a pexpect.spawn
33 
34 def open_log_file(log_file, mode="a"):
35     if log_file is None:
36         return None
37     if isinstance(logfile, str) or isinstance(log_file, unicode):
38         return open(log_file, mode)
原文地址:https://www.cnblogs.com/DaLiNDluDlu/p/5250728.html