How can i pass python variable to a shell command [duplicate] - python

This question already has answers here:
Passing variables to a subprocess call [duplicate]
(6 answers)
Closed 1 year ago.
I have a python script with a webhost, username and a password variable which i am trying to pass into a shell command in the same python script.
output = subprocess.check_output(['curl -s -G -u username:password -k \"https://webhost/something/something\"'], shell=True, encoding='utf-8')
Can you please help me how i can do this? I have tried multiple things, but none worked.
Thanks

Don't construct a string for the shell to parse; just provide a list. That list can directly contain string-valued variables (or strings constructed from variables).
username = ...
password = ...
url = ...
output = subprocess.check_output([
'curl',
'-s',
'-G',
'-u',
f'{username}:{password}',
'-k',
url
], encoding='utf-8')

Try this,
username = 'abc'
password = 'def'
webhost = '1.2.3.4'
output = subprocess.check_output([f'curl -s -G -u {username}:{password} -k \"https://{webhost}/something/something\"'], shell=True, encoding='utf-8')
It's called an f string. https://docs.python.org/3/tutorial/inputoutput.html
You add an f before the string starts, the you enclose the variables you want to insert in curly braces.
You can pass variables into strings using this syntax.
You can also pass the variables as a list as follow, each argument in the command is a separate item and you can use the f string on the list items you want to parse like this,
username = 'abc'
password = 'def'
webhost = '1.2.3.4'
output = subprocess.check_output(['curl',
'-s',
'-G',
'-u',
f'{username}:{password}',
'-k',
f'\"https://{webhost}/something/something\"'],
encoding = 'utf-8')

Related

SyntaxError: missing ; before statement - Python

Let's say I have this snippet
list_command = 'mongo --host {host} --port {port} ' \
'--username {username} --password {password} --authenticationDatabase {database} < {path}'
def shell_exec(cmd: str):
import subprocess
p = subprocess.call(cmd, shell=True)
return p
Let's say these are the commands I'm trying to run on mongo
use users
show collections
db.base.find().pretty()
If format the string list_command with the appropriate values and pass it to the function with shell=True, it works fine. But I'm trying to avoid it for security purposes.
If I call it with shell=False, I get the following error:
2020-08-31T14:08:49.291+0100 E QUERY [thread1] SyntaxError: missing ; before statement #./mongo/user-01-09-2020:1:4
failed to load: ./mongo/user-01-09-2020
253
Your list_command is a shell command: in particular, it includes input redirection (via < {path}), which is a syntactic feature of the shell. To use it you need shell=True.
If you don’t want to use shell=True, you need to change the way you construct the argument (separate arguments need to be passed as separate items of a list rather than as a single string), and you need to pass the script into the standard input via an explicit pipe, by setting its input parameter:
cmd = ['mongo', '--host', '{host}', '--port', …]
subprocess.run(cmd, input=mongodb_script)
Using input raised the following error: TypeError: init() got an unexpected keyword argument 'input'.
I ended up doing the following:
import subprocess
def shell_exec(cmd: str, stdin=None):
with open(stdin, 'rb') as f:
return subprocess.call(cmd.split(), stdin=f)

Include string variables in subprocess.check_output

I am trying to execute following command:
result = subprocess.check_output("curl -o '/Users/user/Desktop/workbook.twb' -u xxx:yyy https://bitbucket.xyz.com/rest/api/1.0/projects/xxx/repos/xxx/raw/yyy/test_folder/test.twb", shell=True)
In the above command, I need to replace /Users/user/Desktop/workbook.twb with a string variable e.g. filePath and https://bitbucket.xyz.com/rest/api/1.0/projects/xxx/repos/xxx/raw/yyy/test_folder/test.twb with another variable e.g. repo_path..How can I achieve this?
I tried multiple ways but getting formatting errors in all of them.
Something like that:
param_a = "foo"
param_b = "bar"
query_url = "http://some.host/{a}/{b}.xml".format(a=param_a, b=param_b)
print(query_url) # To understand what's happening.
command = "curl -o '{output_file}' '{query_url}'".format(
output_file="/Users/me/foo-bar",
query_url=query_url
)
print(command)
result = subprocess.check_output(command, shell=True)
Make every step small. When in doubt, print intermediate values.

Passing variables to BAT file using Python subprocess.call [duplicate]

This question already has answers here:
Why does passing variables to subprocess.Popen not work despite passing a list of arguments?
(5 answers)
Closed 1 year ago.
When I pass a variable to a BAT file using the following:
from subprocess import call
# Prompt for UID
UID = raw_input('Enter UID: ')
# Prompt for password
PSWD= raw_input('Enter your password: ')
dir = r"f:\_Python"
cmdline = "setENVvariables.bat UID, PSWD"
rc=call("start cmd /K " + cmdline, cwd=dir, shell=True)
.. the values are not passed. When I echo the input in the BAT file, I get the Python variable name
BAT file
echo %1
echo %2
BAT File output
f:\_Python>echo UID
UID
f:\_Python>echo PSWD
PSWD
f:\_Python>
You're invoking a shell to run start that will run a CMD to run your BAT file!
That means you want to run a subprocess, but end up starting FOUR instead!
Don't use shell=True
Don't use start unless you really need it
Don't execute CMD
By doing this you can just pass your parameters as a list and it will work:
dir = r"f:\_Python"
cmdline = ["setENVvariables.bat", UID, PSWD]
rc = call(cmdline, cwd=dir)

Python 2.6.6 - Need to add the output of OS.system command into another OS.system command [duplicate]

This question already has answers here:
Running shell command and capturing the output
(21 answers)
Closed 2 years ago.
Below is the script for searching a input data in a given OS.system command ( copied to file out.txt) and prints the line of the given input data. Now I want to put the output i.e line in another OS.system command. For example symaccess -sid 567 show -name xxx -type init where xxx is the output of the previous OS.system command i.e line.
Note - I can use only python 2.6.6 and the scripts related to storage
import os
os.system('symaccess -sid 456 list -type init > out.txt')
server = raw_input("server name:")
with open('out.txt', 'rt') as in_f:
for line in in_f:
if server in line:
print line
I used another method as below
import os server = raw_input("server name:")
var = "symaccess -sid 239 list -type init | grep \"{0}\"".format(server)
wwn = os.system(var)
init = 'symaccess -sid 239 -type init show {0}'.format(wwn) print init os.system(init)
above is the script i used to add a output of one os.system to another os.syste,. i got the first os.system executed but for the second one i.e os.system(init) is not coming because os.system(var) should be assigned as a variable.could someone tell how to assign a variable to os.system(init)
import subprocess
cmd= 'ls'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
std_out = p.communicate()
Here is a possible way to access the output in Python.
Try using "subprocess.checkoutput()".
import subprocess
import os
output = subprocess.check_output(['symaccess -sid 456 list -type init'])
os.system(output)

Python / SupProcess / SqlCmd / using -v switch to pass variable

Trying really hard to use the -v switch to pass a variable to a SQL script (Python), but can't seem to get the syntax correct. I get the following error:
(Note how it looses the C: from the argument and appends a closing backslash)
[stdout] Sqlcmd: ':\Users\Public\MyProj\Tests\WorkingFolder\Database\"': Invalid argument. Enter '-?' for help.
On the server end, here is my syntax:
FILENAME = N'$(LOCATION)\MyDatabase.mdf'
Below is my code
_varText = 'LOCATION="C:\\Users\\Public\\MyProj\\Tests\WorkingFolder\\Database"'
command_process = SubP.Popen(['sqlcmd','-b', '-E', '-S', _server, '-v', _varText , '-d', _database, '-i', filepath],
stdin = SubP.PIPE, stdout = SubP.PIPE, stderr = SubP.STDOUT, shell = True)
You can try
_varText = 'LOCATION=\"C:\\Users\\Public\\MyProj\\Tests\WorkingFolder\\Database\"'
It is based on recommendation in this section: http://docs.python.org/2/library/subprocess.html#converting-an-argument-sequence-to-a-string-on-windows

Categories

Resources