我有一个函数def tldomaint
,它通过子进程call_checkout
执行Tasklist命令。一切都按预期工作,但我从TaskList得到奇怪的输出。我不确定这是由于我的错误捕获还是仅仅是一个奇怪的Tasklist。我希望有人可以帮助指出这个问题。
输出示例:
Attempting to make remote connections and gather data:
Targeted User: xpuser
ERROR: The RPC server is unavailable.
1
WARNING: User credentials cannot be used for local connections
ERROR: The RPC server is unavailable.
1
输出中的1
是我所指的奇怪。
以下是该功能。
def tldomaint(serverlist, domain, username, password, targetuser):
nlist = serverlist
print "\nAttempting to make remote connections and gather data:\n"
print "Targeted User: {0}\n" .format(targetuser)
for serverl in nlist:
try:
out = subprocess.check_output(["tasklist", "/V", "/S", serverl, "/U", domain + "\\" + username, "/P", password, "/FO", "List", "/FI", "USERNAME eq %s\\%s" % (domain, targetuser)])
users = [item for item in out.split() if domain in item and targetuser in item]
sortedl = set(users)
for name in sortedl:
if name in sortedl != '':
print "Targeted User Found On {0}\n" .format(serverl)
print name
else:
print "User Not Found"
except CalledProcessError as e:
print(e.returncode)
return sortedl
答案 0 :(得分:1)
您正在打印流程返回代码:
except CalledProcessError as e:
print(e.returncode)
来自subprocess.check_output()
documentation:
如果返回代码非零,则会引发
CalledProcessError
。
发生错误时,tasklist
会将错误消息写入stderr
,并将退出代码设置为1. subprocess.check_output()
然后引发CalledProcessError
异常(如文档所述)并且您捕获该异常然后打印返回代码。
删除print()
语句,您的神秘1
将消失。
如果您想在Python中处理问题,请将stderr
重定向到stdout
;仍然会引发异常,但您仍然可以读取输出:
out = subprocess.check_output(["tasklist", "/V", "/S", serverl, "/U",
domain + "\\" + username, "/P", password, "/FO", "List",
"/FI", "USERNAME eq %s\\%s" % (domain, targetuser)],
stderr=subprocess.STDOUT)
并在您的异常处理程序中:
except CalledProcessError as e:
errormessage = e.output
# do something with the error message