Home > OS >  How to get output of a code script as a python exception message?
How to get output of a code script as a python exception message?

Time:02-12

I have the code below. When i run it get an error :

*

STDOUT:
[librpc/rpc/dcerpc_connect.c:337:dcerpc_pipe_connect_ncacn_ip_tcp_recv()] failed NT status (c00000b5) in dcerpc_pipe_connect_ncacn_ip_tcp_recv
[librpc/rpc/dcerpc_connect.c:828:dcerpc_pipe_connect_b_recv()] failed NT status (c00000b5) in dcerpc_pipe_connect_b_recv
[wmi/wmic.c:196:main()] ERROR: Login to remote object.
 
 
  STDERR:
NTSTATUS: NT_STATUS_IO_TIMEOUT - NT_STATUS_IO_TIMEOUT

I want to get this error message in my exception. And then, i use linux logger and save it into my db. How can i get this output as an exception message?

#!/usr/bin/python3
#!/usr/bin/python

import wmi_client_wrapper as wmi

try:
  wmic = wmi.WmiClientWrapper(username="Administrator",password="Abc",host="192.168.1.2",)
  output = wmic.query("SELECT * FROM Win32_Processor")
  print(output)
except:
  print("An exception occurred")

CodePudding user response:

Use only one shebang.

You can catch the exception and it contains the message.

#!/usr/bin/python3

import wmi_client_wrapper as wmi

try:
  wmic = wmi.WmiClientWrapper(username="Administrator",password="Abc",host="192.168.1.2",)
  output = wmic.query("SELECT * FROM Win32_Processor")
  print(output)
except Exception as e:
  print("An exception occurred:", e)

CodePudding user response:

To redirect standard error into a variable, one easy approach is to assign sys.stderr to an io.StringIO object, and later retrieve the error message with the object's getvalue method:

import sys
from io import StringIO

error_stream = StringIO()
sys.stderr = error_stream
wmic = wmi.WmiClientWrapper(username="Administrator",password="Abc",host="192.168.1.2",)
output = wmic.query("SELECT * FROM Win32_Processor")
error = error_stream.getvalue()
print('OUTPUT:', output)
print('ERROR:', error)
  • Related