Kalyanam Rajashree Kalyanam Rajashree - 13 days ago 5
Linux Question

How to accept password in command line argument for ssh login using python

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[]

Answer

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!

Comments