现在的位置: 首页 > 综合 > 正文

python: 用EXPECT 实现 ssh 登录(1)

2013年04月13日 ⁄ 综合 ⁄ 共 1660字 ⁄ 字号 评论关闭

#! /usr/bin/env python
# filename : remove_loadbalance_members.py

import pexpect
import sys
import logging

user = sys.argv[1]
host = sys.argv[2]
password = sys.argv[3]
poolName = sys.argv[4]
members = sys.argv[5] 

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s ', level=logging.INFO)
logging.Formatter('%(asctime)s %(levelname)s %(message)s ')

ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
child = pexpect.spawn('ssh -l %s %s '%(user, host))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'assword: '])

if i == 0:  # Timeout
 errorString = 'Wrong Username or Password when logging : '+ host +', '+user+'/'+password
 logging.error(errorString)
print "before >> ",child.before

if i == 1:  # SSH does not have the public key. Just accept it.
 child.sendline ('yes')
 child.expect ('assword: ')
 i = child.expect([pexpect.TIMEOUT, 'assword: '])
 if i == 0:  # Timeout
  errorString = 'Wrong Username or Password when logging : '+ host +', '+user+'/'+password
  logging.error(errorString)  
   
child.sendline(password)

n = child.expect(['#', pexpect.TIMEOUT, pexpect.EOF])
if n != 0 :
 errorString = 'Wrong Username or Password when logging : '+ host +', '+user+'/'+password
 logging.error(errorString)
logging.info('Login '+host+' successfully !')

# 1. Create the LoadBalance 
logging.info('Strat remove loadbalance members .')
command = 'b pool '+poolName+' member '+members+' delete '
child.sendline(command)
n = child.expect(['#', pexpect.TIMEOUT, pexpect.EOF])
if n != 0 :
 errorString = 'Remove a loadbalance members poolName = '+poolName+' member = '+members+' failed .'
 logging.error(errorString) 
print "before >> ",child.before
logging.info('Remove a loadbalance members poolName = '+poolName+' member = '+members+'  successfully !')

logging.info('Quit SSH to send command Line : exit')
child.sendline('exit')
#child.expect([pexpect.EOF])

 

抱歉!评论已关闭.