2014-02-09 41 views
1

我正在嘗試構建一個python腳本來檢查思科設備上的用戶名,密碼和啓用密碼。我使用錯誤的模塊嗎? pxssh

該腳本清楚地登錄到設備,但試圖設置和取消設置外殼提示。我應該只使用標準pexpect而不使用pxssh?我也試過,但'如果'陳述似乎不符合預期。任何建議都會有很大幫助。

Exception: 
could not set shell prompt 
unset PROMPT_COMMAND 
      ^
% Invalid input detected at '^' marker. 

3750_core#PS1='[PEXPECT]\$ ' 
3750_core#set prompt='[PEXPECT]\$ ' 
      ^
% Invalid input detected at '^' marker. 

代碼:

def check_creds(host, user, password, en_passwd): 
    global success 
    global failure 

    try: 
     ssh = pxssh.pxssh() 
     ssh.login(host, user, password, en_passwd) 
     if ssh.prompt(PRIV_EXEC_MODE): 
      print 'privilege mode creds work' 
      ssh.logout() 
      success = True 
     if ssh.prompt(USER_EXEC_MODE): 
      print('username and password are correct') 
      ssh.sendline('enable') 
      ssh.sendline(en_passwd) 
      if ssh.prompt(PRIV_EXEC_MODE): 
       print 'enable password is correct' 
       ssh.logout() 
       success = True 
      else: 
       print 'enable password is incorrect' 
       ssh.logout() 
       failure = True 

    except pxssh.ExceptionPxssh, fail: 
     print str(fail) 
     failure = True 
     exit(0) 

回答

1

是的,錯誤的模塊。我找到了使用pexpect和if語句的正確方法。

def check_creds(host, user, passwd, en_passwd): 
    ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?' 
    constr = 'ssh ' + user + '@' + host 
    ssh = pexpect.spawn(constr) 
    ret = ssh.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:']) 
    if ret == 0: 
     print '[-] Error Connecting to ' + host 
     return 
    if ret == 1: 
     ssh.sendline('yes') 
     ret = ssh.expect([pexpect.TIMEOUT, '[P|p]assword:']) 
     if ret == 0: 
      print '[-] Could not accept new key from ' + host 
      return 
    ssh.sendline(passwd) 
    auth = ssh.expect(['[P|p]assword:', '>', '#']) 
    if auth == 0: 
     print 'User password is incorrect' 
     return 
    if auth == 1: 
     print('username and password are correct') 
     ssh.sendline('enable') 
     ssh.sendline(en_passwd) 
     enable = ssh.expect(['[P|p]assword:', '#']) 
     if enable == 0: 
      print 'enable password is incorrect' 
      return 
     if enable == 1: 
      print 'enable password is correct' 
      return 
    if auth == 2: 
     print 'privilege mode creds work' 
     return 
    else: 
     print 'creds are incorrect' 
     return