Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to remote server with paramiko without a password?

Tags:

python

ssh

I'm writing a script in Python that necessitates connecting to a remote_server with SSH and moving a file from remote_server to host_server. I need to do it without a password as it needs to work for any remote server and any host server user.

My code:

#get IP and username for remote access
IP = input("Enter host_server IP: ").split()
username = input("Enter username: ").split()
#password = ???????

#create a file on host_server for file
file_a = open(date+"file.txt", "a") #ignore the date variable
file = str(date+"file.txt")

#move file to host_server
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP[0], username = user[0], password = password[0])
print "Connected to server."
transfer = ssh.open_sftp()
transfer.get("file.txt", file)
transfer.close()
print "Transfer completed."

Question: Is there a way to set up a public key within the script without accessing a command line terminal, so that every time the script runs it will set up passwordless access with SSH?

like image 519
hjames Avatar asked Aug 21 '13 15:08

hjames


1 Answers

ssh.connect() takes a keyword argument pkey which you can use to specify your private file.

#get IP and username for remote access
IP = input("Enter host_server IP: ").split()
username = input("Enter username: ").split()


#create a file on host_server for file
file_a = open(date+"file.txt", "a") #ignore the date variable
file = str(date+"file.txt")
import paramiko
import os
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
ssh.connect(IP[0], username = user[0], pkey = mykey)
like image 57
Uku Loskit Avatar answered Sep 20 '22 10:09

Uku Loskit