Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- queryOutput = []
- ssh = paramiko.SSHClient()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- try:
- ssh.connect(theIP, username=theUser, password=thePass)
- except:
- log.error("Failed to connect QRadar Console...")
- return None
- chan = ssh.get_transport().open_session()
- chan.settimeout(300)
- command = 'psql -U qradar -A -F \<\|\> -c "%s"' % query
- log.debug(" - Executing command to get information from DB.")
- def get_channel_content_error(chan, contents, error):
- if chan.recv_ready():
- data = chan.recv(1024)
- while data:
- contents += data
- data = chan.recv(1024)
- if chan.recv_stderr_ready():
- error_buff = chan.recv_stderr(1024)
- while error_buff:
- error += error_buff
- error_buff = chan.recv_stderr(1024)
- return contents, error
- try:
- chan.exec_command(command)
- # To capture Data. Need to read the entire buffer to capture output
- contents = ''
- error = ''
- # https: // github.com / paramiko / paramiko / issues / 621
- # SSH can have exit status sent before stdout data. The typical approach in real-time streaming is to check
- # if channel is recv_ready, recv_stderr_ready or exit_status_ready. There are no other documented
- # ways to check the channel has actually finished.
- #
- # Undocumented 'closed' field can be used to check channel is really closed
- while not chan.exit_status_ready() or not chan.closed:
- contents, error = get_channel_content_error(chan, contents, error)
- # In case we recieved exit_status_ready and channel is closed
- # there still can be buffer data
- contents, error = get_channel_content_error(chan, contents, error)
- exist_status = chan.recv_exit_status()
- except socket.timeout:
- raise socket.timeout
- output = contents.split("\n")
- error_value = error.split("\n")
- if exist_status != 0:
- log.error("Command execution failure:")
- for error_line in error_value:
- log.info(" > " + error_line)
- return None
- for i, line in enumerate(output):
- line = line.strip()
- # skip last line "XXX rows"
- if not '<|>' in line:
- continue
- columns = line.split('<|>')
- # skip headers and underline
- if i == 0:
- continue
- queryOutput.append(columns)
- ssh.close()
- log.debug(" - Command executed.")
- log.debug(" - Found %s active records." % len(queryOutput))
- return queryOutput
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement