简体   繁体   中英

Script aborts after adding a try block and writing to two log files

I have a text file that is a list of servers which is called solaris_h.txt . Some of the servers on this list, I'm not able to authenticate probably because I don't have an account or the password is incorrect. When authentication fails on a particular server on the list, the script aborts. So, somebody suggested the try and except block. I want the script to complete the list of servers in solaris_h.txt and to write to a log file the successful logins and writing to another log file the servers that failed to authenticate. After adding the try block, when executing the script, it exits immediately without error. And how do I get my script to write to one log file the successful logins and to another log file the unsuccessful logins?

#!/usr/bin/python

import pxssh
import sys

log = open("myprog.log", "a")
sys.stdout = log

s = pxssh.pxssh(timeout=30, maxread=2000000)
s.SSH_OPTS += "-o StrictHostKeyChecking=no"
s.SSH_OPTS += "-o UserKnownHostsFile=/dev/null"
s.SSH_OPTS += "PubkeyAuthentication=no"

f=open('solaris_h.txt','r')
for line in f:

try:
    s.login(line,'xxxx','xxxxxx')
    z = s.sendline('uname -a')
    s.prompt()
    y = s.before
    print("%s %s" % (line, y))
    s.logout()
except pxssh.ExceptionPxssh:
    pass

Here is the error when it fails authentication.

Traceback (most recent call last):
File "./z.py", line 17, in <module>
 s.login(line,'username','password')
File "/usr/lib/python2.7/site-packages/pxssh.py", line 226, in login
  raise ExceptionPxssh ('password refused')
pxssh.ExceptionPxssh: password refused

If you want to ignore an error from a failed login, you can do a try/except block around the login like:

try:
    s.login(line, 'username', 'password')
    z = s.sendline('uname -a')
    s.prompt()
    y = s.before
    print("%s %s" % (line, y))

    s.logout()
except pxssh.ExceptionPxssh:
    pass

Use try except blocks for the authentication code alone. so if any errors they will be caught and loop will continue with next server name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM