Search code examples
pythonbashfileshadow

Call a bash script from python with a desired string


I have a python script which gets the password of a user from /etc/shadow for a project I’m doing. Let’s say I get the password in the python script as “jumbo”. So, how would I go about calling the bash script while within the python script? It has to be in a manner where the password, “jumbo”, is passed to the bash script to be used.

The reason I’m passing it to a bash script is because I then need to log into a user, say “worker”, with that password while in the bash script (instead of at the command line obviously) to be automatically logged into the “worker” account when the bash script finishes executing and it returns to the python script to continue the rest of the python code that’s after the bash script call.

Edit: I’m confused how to call the bash script in python and am also confused how to “catch” the string in the bash script.


Solution

  • If you want to call a script with arguments, you can use check_call function:

    from subprocess import check_call
    
    rc = check_call("./file.sh %s %s %s" % (agr1, str(arg2), arg3), shell=True)
    

    remember to convert the args to string before passing, using str(arg).