Kalyanam Rajashree Kalyanam Rajashree - 1 year ago 114
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.

p = subprocess.Popen(
['ssh', '-s', '-l', '<name1>', <host_name>, '-p', str(port), '<something>'],
except Exception, err:
print 'Failed to run ssh command! (' + str(err) + ')'

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

Answer Source

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!")

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download