Title: Insert password in ssh using python script
Tags: python;ssh
Question: I need to run a Python script which will get the password from the user and login into the specific box using SSH.
password = getpass.getpass('password:')
command='ssh' + ' ' + "IPname"
p = subprocess.Popen(command,shell=True,stdout=PIPE).communicate(password)[0]
But the above script is not working and still it is looking for password.
Comment: Is IPname a variable that you've accidentally quoted?

Comment: Don't do this. Use public keys to authenticate. It's a bad idea to hard-code passwords in scripts.

Comment: yes but i'm getting password from user and the script for just internal purpose.

Comment: you can use `pyexpect` to send the password when the process expects it. You could also just avoid using passwords and use `public key authentification`.


Here is another answer: Use paramiko like so, because you cannot use password authentication with subprocess, you would have to create and alias and do ssh somealias. Paramiko makes it easy to do the authentication without setting up an alias:
password = getpass.getpass()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('some.host.com', username=username, password=password)
Or you could use a public key with paramiko as well:
pathToKey = &quot;/some/path/here&quot;
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('some.host.com', username=username, key_filename=pathToKey)
Comment for this answer: @EricRenouf you can't use it if its a password authentication, you would have to set up an ssh alias and do `ssh somealias`
Comment for this answer: You can ssh with subprocess, but I haven't tried/wouldn't want to try to do an interactive shell that way, but if you just want to execute a command on the remote system you can definitely use `ssh` with subprocess
Comment for this answer: Or use something like `sshpass` around it, but I just wanted to clarify your statement "you cannot ssh using subprocess"
Comment for this answer: i need alternative of paramiko. could you pls more specific.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:08/11/15', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<python><ssh>', 'Title': 'Insert password in ssh using python script', 'ViewCount': 4650, 'id': 31944475, 'user_AboutMe': None, 'user_AccountId': 6772578.0, 'user_DisplayName': 'Aathi', 'user_Reputation': 1.0, 'user_Views': 2.0, 'user_id': 5215511.0}}