pythonlinuxbashshellautomation

Passing a variable into bash command using python


I'm creating a small script and I'd like to pass a varable into a bash command using the python programming language, so for example:

number = raw_input("digit: ")

then i'd like to take the number variable and put it in bash command so for example:

ssh 'foo%s.bar'(number) <- where the %s is located id like it be replaced with the input

Finally I'd like to take that and run it in a bash command still within the python script:

ssh foo45.bar

How can I make this work?


Solution

  • import subprocess
    number = raw_input("digit: ")
    subprocess.call(('ssh', 'foo{}.bar'.format(number)))
    

    For some good reading, try the python docs for string formatting and for subprocess.

    If you want to integrate the above with sshpass, replace the subprocess call with:

    subprocess.call(('sshpass', '-p', 'YOUR_PASSWORD', 'ssh', '-o', 'StrictHostKeyChecking=no', 'foo{}.bar'.format(number)))