Python免密登录SSH

日常项目开发中,每次上线新的项目,可能前后端都分配有独立的服务器,每次去登录维护线上项目时,都需手动录入ssh登录之地址、账号、密码等,长时间不操作,超时又会自动退出,届时又得翻开小笔记记录的服务器账号信息等,重新连一遍,如此反复,颇有不便。
于是乎,想着通过一个Python脚本来自动连接,名义上是免密,实则上还是通过脚本实现的登录,只是少了手动录入的环节,好啦,不多说,脚本如下:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
   
import  pexpect,os
 
class frstphp:
 
  def __init__(self):
    self.config = {
      '0':{'host':'127.0.0.1', 'user':'root', 'password':'123456', 'port':22},
      '1':{'host':'127.0.0.1', 'user':'root', 'password':'123456', 'port':5623},
      '2':{'host':'127.0.0.1', 'user':'root', 'password':'123456', 'port':22}
    }
 
  def send_command(self, child, cmd):  
    child.sendline(cmd)
    child.expect('#')
    print child.before 
    child.sendline('ls -lh /')
    child.interact()
 
  def connect(self):  
    print(
    '''
    [0] 测试服务器1
    [1] 测试服务器2
    [2] 测试服务器3
    '''
    )
    idKey = raw_input(" 请选择服务器:")
 
    user = self.config[idKey]['user']
    host = self.config[idKey]['host']
    password = self.config[idKey]['password']
    port = self.config[idKey]['port']
 
    connStr = 'ssh ' + user + '@' + host + ' -p ' + str(port)  
    child = pexpect.spawn(connStr)  
    res = child.expect([pexpect.TIMEOUT, '[P|p]assword:'])  
    if res ==  0:  
      print "[-] Error 2" 
      return 
    elif res ==  1:  
      child.sendline(password)  
 
    child.expect('#')  
     
    return child  
 
if __name__ == '__main__':
    try:
      fp = frstphp()
      child = fp.connect()  
      fp.send_command(child, 'w')  
 
    except KeyboardInterrupt:
      print('stopped by 狂奔的螞蟻')

你可能感兴趣的:(Python免密登录SSH)