在Ruby中使用net-sftp进行基于密钥的身份验证 [英] Key based authenication with net-sftp in Ruby
问题描述
我希望能够使用SFTP登录到许多服务器并下载某些文件,以帮助在出现问题时进行调试.虽然我们可以使用客户端,但我们希望开始实现流程自动化以简化一切.
I want to be able to use SFTP to login into a number of servers and download certain files to help debug issues as and when they arise. While we could use a client, we wanted to start automating the process to streamline everything.
我的第一次尝试是这样的:
My first attempt looks something like this:
def download(files_to_download, destination_directory)
Net::SFTP.start(@server, @username, :password => @password) do |sftp|
files_to_download.each do |f|
local_path = File.join(destination_directory, File.basename(f))
sftp.download!(f, local_path)
end
end
end
虽然可行,但这意味着我们需要密码.理想情况下,我想使用公共密钥身份验证,但是在文档或在线中看不到对此的任何引用-这可能吗?
While this works, it means we need the password. Ideally, I want to be using public key authentication however I can't see any reference to this in the documentation or online - is this possible?
我不希望使用chilkat.
I would prefer not to use chilkat.
谢谢
推荐答案
如果您想直接指定密钥(或打开Net :: SSH连接,然后从那里进行SFTP操作.
If you want to directly specify the key (or other SSH options) you can first open a Net::SSH connection, and then do SFTP operations from there.
Net::SSH.start("localhost", "user", keys: ['keys/my_key']) do |ssh|
ssh.sftp.upload!("/local/file.tgz", "/remote/file.tgz")
ssh.exec! "cd /some/path && tar xf /remote/file.tgz && rm /remote/file.tgz"
end
这也适用于Net :: SCP
This also works for Net::SCP
Net::SSH.start('localhost', 'user', keys: ['keys/my_key'] ) do |ssh|
ssh.scp.download("/local/file.txt", "/remote/file.txt")
end
这篇关于在Ruby中使用net-sftp进行基于密钥的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!