<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Use a different Python version with subprocess to create search script using custom command? in Splunk Dev</title>
    <link>https://community.splunk.com/t5/Splunk-Dev/How-to-use-a-different-Python-version-with-subprocess-to-create/m-p/626055#M10882</link>
    <description>&lt;P&gt;Thank you! This may come in handy if I don't manage to find another option to keep the search command's process alive and end up having to manage one myself.&lt;/P&gt;</description>
    <pubDate>Thu, 05 Jan 2023 20:16:22 GMT</pubDate>
    <dc:creator>spunk_enthusias</dc:creator>
    <dc:date>2023-01-05T20:16:22Z</dc:date>
    <item>
      <title>How to use a different Python version with subprocess to create search script using custom command?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-use-a-different-Python-version-with-subprocess-to-create/m-p/443861#M8040</link>
      <description>&lt;P&gt;&lt;STRONG&gt;Purpose&lt;/STRONG&gt;: Help the reader understand one approach to have Splunk kick-off a Python script that returns data to Splunk without indexing returned data, or modifying the Slunk Python installation.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Use Case&lt;/STRONG&gt;: Splunk ships with a minimal implementation of Python 2.7. If you need to utilize a module that isn’t installed with the Splunk implementation it is recommended that an installation external to Splunk, with the modules installed, be used.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Expected Action&lt;/STRONG&gt;: The user will initiate a Splunk search query using a custom command. This custom command will initiate a wrapper python script that will read a passed parameter/argument and initiate the target python script and return the values to the Slunk interface for display or use.&lt;/P&gt;
&lt;P&gt;&lt;EM&gt;(Note: this is Splunk Enterprise on Windows Server)&lt;/EM&gt;&lt;/P&gt;
&lt;P&gt;Python Needs:&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Python Installation (external to Splunk Python installation) -Full Python or Virtual Environment.&lt;/LI&gt;
&lt;LI&gt;Install your required modules into your python environment (pip or other installation tool)&lt;/LI&gt;
&lt;LI&gt;Note the Python executable locations -Splunk Python location: (e.g. D:\Splunk\bin\python.exe) -External Python installation (e.g. D:\Splunk_Python_venv\p27_15\Scripts\python.exe)&lt;/LI&gt;
&lt;/OL&gt;
&lt;P&gt;Script Requirements:&lt;BR /&gt;1. Wrapper script: (see example_wrapper.py)&lt;BR /&gt;-Will work with Splunk python implementation. (No modules added outside of Splunk standard installation)&lt;BR /&gt;-Reference Intersplunk class &lt;BR /&gt;sys.path.append("/Splunk/Python-2.7/Lib/site-packages/splunk")&lt;BR /&gt;import Intersplunk&lt;BR /&gt;-Print output results from target script&lt;BR /&gt;2. Target script: (see example_target.py)&lt;BR /&gt;-Can use your modules or customizations&lt;BR /&gt;-Reference Intersplunk class &lt;BR /&gt;sys.path.append("/Splunk/Python-2.7/Lib/site-packages/splunk")&lt;BR /&gt;import Intersplunk&lt;BR /&gt;-Call Intersplunk.outputResults(results)&lt;BR /&gt;(results) is your result set and it must be in a format that can be consumed by Splunk. &lt;BR /&gt;Splunk Custom Search Command:&lt;BR /&gt;1. Create custom search command in commands.conf&lt;BR /&gt;[activatepython]&lt;BR /&gt;chuncked = false&lt;BR /&gt;filename = example_wrapper.py&lt;/P&gt;
&lt;P&gt;Run Script from commandline:&lt;BR /&gt;\Splunk\etc\apps\myapp\bin&amp;gt;........\bin\splunk cmd python example_wrapper.py scripttarget=example_target.py&lt;/P&gt;
&lt;P&gt;Run Script from SPL&lt;IMG src="https://community.splunk.com/storage/temp/273572-pythonintegration-image.png" border="0" alt="alt text" /&gt;&lt;/P&gt;
&lt;P&gt;Example Files:&lt;/P&gt;
&lt;PRE&gt;&lt;CODE&gt;######################################################################################
############### following is the example_wrapper.py file #############################
######################################################################################
import os
import subprocess
import re
import sys
sys.path.append("/Splunk/Python-2.7/Lib/site-packages/splunk")
import Intersplunk


custompythonpath = 'D:\Splunk_Python_venv\p27_15\Scripts\python.exe'
splunkpythonpath = 'D:\Splunk\bin\python.exe'

os.environ['PYTHONPATH'] = custompythonpath
# from splunk web interface this is needed to get the arguments
# example SPL "| scriptwrapper scripttarget=example_target.py"
keywords, argvals = Intersplunk.getKeywordsAndOptions()
try:
    #pull in the arguments
    scripttarget = argvals['scripttarget']
    #prevent code injection: verify we aren't getting a file outside of our run directory 
    fileVerify=re.split('/|\*|\\\\|\'|\"', scripttarget)
    if os.path.isfile(fileVerify[0]):
        #create full path to your script
        my_process = os.path.join(os.getcwd(), scripttarget)
        #create subprocess be sure to pass stdin, stdout, stderr
        p = subprocess.Popen([custompythonpath, my_process, splunkpythonpath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        # get the output
        output = p.communicate()[0]
        # push it out
        print output
    else:
        print ('Unable to verify requested action'.format(fileVerify))
except Exception as e:
    print(e)


######################################################################################
############### following is the example_target.py file #############################
######################################################################################


# pypyodbc has a dependency on environment variable 'windir' be sure 
# if using the the activate process that the class passes in the evirnoment variable on activate.
import sys
import pypyodbc
import sys
import os
sys.path.append("/Splunk/Python-2.7/Lib/site-packages/splunk")
import Intersplunk

def GetSqlResults(connectionString, sqlText):
    results = []
    try:
        db = pypyodbc.connect(connectionString)
        cursor = db.cursor()
        cursor.execute(sqlText)
        columns = [column[0] for column in cursor.description]
        #had to do the following to get splunk to accept the result set (I thought this would be simpler)
        for row in cursor.fetchall():
            result = {}
            for column in columns:
                result[column] = row[column]
            results.append(result)
        db.close()
    except Exception as e:
        print('Bad things happened when executing SQL: {0}'.format(e))

    return results


if __name__ == "__main__":
    connectionString = "Trusted_Connection=yes; Driver={SQL Server};server=greatstuffserver;database=greatstuffdatabase'
    sqlText = 'select id, name from greatstufftable'
    results = []
    results = GetSqlResults(connectionString, sqlText)
    #send results to Intersplunk (the wrapper class will 'print' the output)
    Intersplunk.outputResults(results)
    sys.exit(0)
&lt;/CODE&gt;&lt;/PRE&gt;</description>
      <pubDate>Thu, 05 Jan 2023 20:20:33 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-use-a-different-Python-version-with-subprocess-to-create/m-p/443861#M8040</guid>
      <dc:creator>jrouse025</dc:creator>
      <dc:date>2023-01-05T20:20:33Z</dc:date>
    </item>
    <item>
      <title>Re: Use a different Python version with subprocess to create search script using custom command?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-use-a-different-Python-version-with-subprocess-to-create/m-p/626055#M10882</link>
      <description>&lt;P&gt;Thank you! This may come in handy if I don't manage to find another option to keep the search command's process alive and end up having to manage one myself.&lt;/P&gt;</description>
      <pubDate>Thu, 05 Jan 2023 20:16:22 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-use-a-different-Python-version-with-subprocess-to-create/m-p/626055#M10882</guid>
      <dc:creator>spunk_enthusias</dc:creator>
      <dc:date>2023-01-05T20:16:22Z</dc:date>
    </item>
  </channel>
</rss>

