-1

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

Abhinandan Aithal
  • 161
  • 2
  • 5
  • 12

2 Answers2

4

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')
chepner
  • 497,756
  • 71
  • 530
  • 681
1

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')
anarchy
  • 3,709
  • 2
  • 16
  • 48
  • Passing a string as a list is a bug; it happens to work on Windows, but should really generate a warning. You want `subprocess.check_output(['curl', '-s', '-G', '-u', f'{username}:{password}', '-k', 'https://{webhost}/something/something'], encoding='utf-8')` which also avoids the pesky `shell=True`. – tripleee Aug 26 '21 at 15:02
  • i will edit my answer – anarchy Aug 26 '21 at 15:05