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

#! /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])

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值