[英]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 .我有一个文本文件,它是一个名为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.所以,有人建议使用
try
和except
块。 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.我希望脚本完成solaris_h.txt中的服务器列表,并将成功登录的日志文件写入日志文件,并将验证失败的服务器写入另一个日志文件。 After adding the
try
block, when executing the script, it exits immediately without error.添加
try
块后,在执行脚本时,立即退出,没有错误。 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/except
块,例如:
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.单独使用 try except 块作为身份验证代码。 so if any errors they will be caught and loop will continue with next server name.
因此,如果有任何错误,它们将被捕获并且循环将继续使用下一个服务器名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.