Powershell - now to extract name of variable passed to script - python

I am writing powershell script to interface with an external software program our company is using
The script needs to take in value of the input parameter and do something.
But the problem is, this external software pushes many input parameters with the names
sender-email
sender-ip
sender-port
endpoint-user-name
endpoint-machine-name
I only need the value for sender-ip. But my problem is
I don't know in which order the external program is inputting the parameters to the script
Powershell naming convention does not allow for a hyphen, so it's not like I can just start using sender-ip without getting an error The term 'sender-ip' is not recognized as the name of a cmdlet, function, script file, or operable program.
Here is my script so far
param([string]$Sender_IP=$(**sender-ip**))
$eventList = #()
Get-EventLog "Security" -computername $Sender_IP `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| Select-Object -First 2 `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$eventList += $row
}
$UserId = $eventList[0].UserName
$UserID
See, when I manually invoke foo.psl *ip_address*, everything works well. But if I call the program without parameter, I get error.
How to write code such as
if name of input variable is **sender-ip**
do something
else if name of input variable is something different
ignore
I am not evaluating value of the input parameter, I want to capture the input parameter that is named sender-ip, and from there I will run the script and evaluate.
I hope I explained my question well.
In the past, people interfaced with this third party program using Python script, where you can simply write the following
attributeMap = parseInput(args)
dateSent = attributeMap["sender-ip"]
I strongly prefer to use powershell.
Thank you!

If I were you I would probably start with looking at actual input to your script when your program runs...
If it will however just do:
.\yourscript.ps1 -foo-bar something -something-else value -sender-ip yourdata
You can get the value of sender-ip very easily:
param (
${sender-ip}
)
"Sender IP = ${sender-ip}"
If that's not the case you will probably have to paste here what you get when you do simple $args in your script. Without seeing what is there it may be hard to suggest something similar to thing that python does...
EDIT
In case you receive data as name=value pairs, try this:
function foo {
$hash = ConvertFrom-StringData -StringData ($Args -Join "`n")
$hash.'sender-ip'
}
foo test-first=alfa sender-ip=beta
In my test I got expected (beta) result...

Related

lua run a shell command with parameters doesn't work

I am trying to execute a command from lua script. The command is to simply run a python script named "sha_compare.py" of which receives 3 arguments where two of them are variables from the lua script - dady_data and sha:
local method = ngx.var.request_method
local headers = ngx.req.get_headers()
if method == "POST" then
ngx.req.read_body()
local body_data = ngx.req.get_body_data()
local sha = headers['X-Hub-Signature-256']
ngx.print(os.execute("python3 sha_compare.py"..sha..body_data))
else
The script fails because of the way I call the arguments. The actual command if I would have ran it from cmd would have been something like:
python3 python3 sha_compare.py sha256=ffs8df aaaaa
Please tell me how should I change my code to call the python script with 3 vars properly.
If it is not possible or hard to implement, please let me know how can I call a .sh script which will receive those 3 params.
You're not providing spaces between the arguments: you're trying to execute
python3 sha_compare.pysha256=ffs8dfaaaaa
Do this:
os.execute("python3 sha_compare.py "..sha.." "..body_data)
It's often easier to build the command up as a table, and the concat it for execution:
local cmd = { 'python3', 'sha_compare.py', sha, body_data }
os.execute(table.concat(cmd, " "))

Return value from shell script to python script

I am trying to achive following:
I am having a python script which is calling a shell script and passing a parameter as well. Shell script creates a tar.gz file using that parameter passed in some location.
Now shell script should pass the name and location of the tar.gz so created. Python script uses that to form a JSON and pass to some other code.
Along with this I want to add some check to make sure if tar.gz is generated then only value is returned to python otherwise not.
Here is the code:
Python script:
#!/usr/bin/python
import json
import subprocess
json_data='{"name": "StackOverflow", "uid": "8fa36334-ce51"}'
data = json.loads(json_data)
for keys,values in data.items():
print(keys)
print(values)
UID = data.get('uid')
rc = subprocess.check_output(["/home/cyc/Cyc-
Repo/cyc_core/cyc_platform/src/package/cyc_bsc/scripts/test.sh",
UID])
print rc
if rc != 0:
print "failed for passed in uid"
data_op = {}
data_op['pathTOCompressfile'] = 'value_should_be_return_from_shell'
data_op['status'] = 'OK'
json_data_op = json.dumps(data_op)
print json_data_op
shell script:
#!/bin/bash
if [ "$1" != "" ]; then
uid=$1
echo "Positional parameter 1 contains something $1"
else
echo "Positional parameter 1 is empty"
fi
LOG_TMP="tmp_log_file_location"
log_location="log_file_location"
filename="${log_location}/$uid.tar.gz"
echo $filename
tar -zcvf $filename -C $LOG_TMP/dc .
This is what i am not able to understand:
How to pass back the value of variable "filename" back to python script if tar -zcvf command is successful.
In python script how can i verify take value of filename and create JSON using that
In case value cannot be generated STATUS becomes fail in JSON ( within python ) so capture that as well.
Your shell script writes the name of the generated file to standard output, so your question boils down to how to catch stdandard output of a subprocess started from Python. This has been ansered here. BTW, when asking questions about Python, it would be a good idea to always specify the Python version you are using.
In your case however, I would redesign your shell script a bit:
Your script outputs not only the generated filename, but also messages about the "positional parameter", and this means that you would have to fiddle them apart in your script, whether it is an message or a valid output. You could send the messages to standard error, to keep them apart.
BTW, if there is no positional parameter, the generated file name is just .tar.gz. Is this really what you want to have? Wouldn't it better to do a exit 1, if there is no parameter?

How to Store the Output of a system return function in a string variable in python/tkinter

Query: How to store the output of a os.system return function into a string variable ?
I tried the below code but it always prints '0'
Not declared the user_name as StringVar()
Used the below code to find the user name.
user_name = os.system("ypcat passwd | grep $USER | awk -F ':' '{print $5}'")
I tried printing as print user_name , but it prints '0'.
And also wherever I use the user_name as variable to substitute with the user name its printing as '0'.
Can you kindly share your inputs/comments how to store the output of the system call in python ?
os.system() returns the exit code of the executed command, so it makes sense that this is 0. If you want to store the output of the executed command, you should probably use subprocess.check_output() from the Subprocess Module.
As previously mention, you are getting the return code from the command that you issued but there has to be an easier way to get the user name than the one that you are using.
There are multiple ways of doing it but one of the easiest is:
import os
user_name = os.environ['USERNAME']

perl using backticks times out

I have a problem I am hoping someone can help with
I am running a perl script that calls a python script with a set of arguments as below
my $outText=`sudo /usr/bin/python /usr/local/bin/tacms/scriptname.py $pNumber $crnNumber`
The scriptname is supposed to process information based on the arguments passed and then give a terminal output which is saved in the variable, outText.
There have been instances where this has failed and I suspect it is a timeout. So how would I increase the timeout period of the backticks
yes, it was the script I was calling so what I did was say that if the results of $outText are null then repeat the whole process else continue...ie
my $outText=`sudo /usr/bin/python /usr/local/bin/tacms/scriptname.py $pNumber $crnNumber`
if ($outText eq ""){
my $outText=`sudo /usr/bin/python /usr/local/bin/tacms/scriptname.py $pNumber $crnNumber`;
//use variable here;
}
else{
//use variable here;
}
At least this way my system would retry at least once before it fails. That was the best solution I could come up with. The python script being called was calling a web service in SOAP so sometimes, it would timeout.

Using external variable in exec_command python

I am executing exec_command in Python. The command is : find -path . -mmin -$time -print. And I am assigning time=100. But while executing the command, exec_command does not picks up the variable value.
or even I do exec_command('echo $time'). It does not picks up the value.
Python and the shell have separate variables. Setting time in your Python script does not magically create a variable called $time that you can then use in shell commands. It especially does not magically create a shell variable on some other computer which is what it appears you're trying to do.
Instead, put the Python value into the string you're passing. For example:
command = 'find -path . -mmin -%d -print' % time
print(command) # shows the exact command that will be executed
exec_command(command)
Be careful with this. It's very easy to create security holes if you don't know what you're doing, especially when you take strings from user input or other data sources you don't control. In this example I've used %d to substitute the value into the command, and this will keep anything but a number from being used, which should be safe.

Categories