1

I am using ssh to login to a remote device. I have a python script for this. The command I run is:

./python_script.py ssh device@ip_address

I want to create a password with one of the arguments for this script. I have the following in my python script.

try:
    p = subprocess.Popen(
        ['ssh', '-s', '-l', '<name1>', <host_name>, '-p', str(port), '<something>'],
        bufsize=BUFSIZE,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=False)
except Exception, err:
    print 'Failed to run ssh command! (' + str(err) + ')'
    sys.exit()

I don't know if my question is clear but I would like to know how to get my ssh script to accept a password parameter. I want to access it from python script using sys.argv[]

2

3 Answers 3

1

Consider the following usage:

./python_script.py ssh device@ip_address passwd

Now you access the arguments by:

import sys

if len(sys.argv) < 4:
    print("Not enough arguments!")
    sys.exit()

ssh        = sys.argv[1]
device     = sys.argv[2].split("@")[0]
ip_address = sys.argv[2].split("@")[1]
passwd     = sys.argv[3]

To call the ssh command along with your password, you'll need sshpass, as described here.

Hope this helps!

Sign up to request clarification or add additional context in comments.

3 Comments

Ok. So, may be my question is not clear. This answer is telling me how to access the commands given in command line. My question is to know if there a way in which I can give password as one of the arguments along with ssh so that ssh doesn't prompt for password again. Else, what modifications can I do to my python code to use this password given in command line so that ssh doesn't ask for a password while logging into the remote device.
@KalyanamRajashree - I just gave you the hint about sshpass!
Awesome ! Worked like a miracle. Thanks a lot.
1

There is library in python called fabric.Just read it you will get to how to do that. Or install ssh-pass though github, it is also for the same purpose.

Comments

0

So this is the final solution which worked for me. I installed sshpass using

sudo apt-get install sshpass

Then my modified code is the following. I took password from command line as linusg suggested in above answer.

try:
    p = subprocess.Popen(
    ['sshpass','-p',password,'ssh', '-s', '-l', '<name1>', <host_name>, '-p', str(port), '<something>'],
    bufsize=BUFSIZE,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    shell=False)
except Exception, err:
    print 'Failed to run ssh command! (' + str(err) + ')'
    sys.exit()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.