[ruby]使用ssh,sftp自动上传文件的rake

最近在系统中使用jruby写业务逻辑,写完一个脚本之后,要手工地用ftp工具上传到服务器上面调试.见到大家都是ant自动部署,想起ruby下大名鼎鼎的rake,我想应该也是可以实现这样的功能的吧.参考网上使用ssh,sftp自动上传的文章,不过大都不可用,貌似是sftp的API已经变了,只好自己摸着石头过河,经过一个下午的努力(小弟是新手),终于搞定了,废话少说,上代码,我的第一个rake啊.
请先安装net-ssh,net-sftp这两个gem

gem install net-ssh net-sftp



# @anthor:yanghuan
# To change this template, choose Tools | Templates
# and open the template in the editor.


require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'rubygems'
require 'net/ssh'
require 'net/sftp'

LOCAL_PATH = 'lib'
REMOTE_PATH = '/home/scripts/test'

SERVER="192.168.0.1"
USER_NAME = "root"
PASSWORD = "password"

module FindUtils
def find_all_file(file,&block)
if File.stat(file).directory?
Dir.foreach(file) do |f|
find_all_file(file + "/" + f,&block) if( !(f =~ /^\./))
end
else
block.call(file)
end
end

def find_all_dir(dir,&block)
if File.stat(dir).directory?
block.call(dir)
Dir.foreach(dir) do |f|
find_all_dir(dir + "/" + f,&block) if(File.stat(dir + "/" + f).directory? && !(f =~ /^\./))
end
end
end
end

task :default => [:upload]

#文件上传
task :upload do
puts "task[upload] start"
include FindUtils
begin
Net::SSH.start(SERVER,USER_NAME,:password => PASSWORD) do |ssh|
ssh.sftp.connect do |sftp|
# 检查并创建文件夹
find_all_dir(LOCAL_PATH) do |d|
if !d.eql?(LOCAL_PATH)
begin
local_dir = d.sub(Regexp.new(LOCAL_PATH+"/"),'')
remote_dir = REMOTE_PATH + "/" + local_dir
puts "local_dir:#{local_dir} remote_dir:#{remote_dir}"
sftp.stat!(remote_dir)
rescue Net::SFTP::StatusException => se
raise unless se.code == 2
puts "mkdir on remote : #{remote_dir}"
sftp.mkdir!(remote_dir, :permissions => 0755)
puts "mkdir completion"
end
end
end

# 上传文件
find_all_file(LOCAL_PATH) do |f|
local_file = f.sub(Regexp.new(LOCAL_PATH+"/"),'')
remote_file = REMOTE_PATH + "/" + local_file
sftp.upload!(f,remote_file) do|event,uploader,*args|
case event
# args[0] : file metadata
when :open
puts "start uploading.#{args[0].local} -> #{args[0].remote}#{args[0].size} bytes}"
when :put then
# args[0] : file metadata
# args[1] : byte offset in remote file
# args[2] : data being written (as string)
puts "writing #{args[2].length} bytes to #{args[0].remote} starting at #{args[1]}"
when :close then
# args[0] : file metadata
puts "finished with #{args[0].remote}"
when :mkdir then
# args[0] : remote path name
puts "creating directory #{args[0]}"
when :finish then
puts "all done!"
end
end
puts "upload success"
end
end
end
rescue => detail
puts "error:#{detail.backtrace.join("\n")} \n message:#{detail.message}"
end
end
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值