我正在用Python编写一个脚本,该脚本需要使用SSH连接到remote_server,并将文件从remote_server移到host_server。我需要没有密码才能执行此操作,因为它需要对任何远程服务器和任何主机服务器用户都有效。
问题:是否可以在不访问命令行终端的情况下在脚本内设置公共密钥,以便每次脚本运行时都可以使用SSH设置无密码访问?
如何生成和实现密钥
我的代码:
#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."