在 Ruby 中通过 SSH 或 SFTP 获取存储库的大小

Get the size of a repository over SSH or SFTP in Ruby

如何在 Ruby 中获取另一台主机(使用 Net::SSH 或 Net::SFTP)上的存储库大小?

存储库的大小,我指的是该存储库中所有文件的递归总和。

我想使用此信息来确保存储库小于特定大小。那么,如果是的话,我要tar下载

您可以这样进行:

SPECIFIC_SIZE = 100
Net::SSH.start('host', 'user', :password => "password") do |ssh|
  output = ssh.exec!("find /path/to/dir -type f | wc -l")
  if output.to_i > SPECIFIC_SIZE
    ssh.exec!("tar czf somedir.tar /path/to/dir") #your terminal tar command
  end
end

使用 ssh gem:

实现
require 'ssh'
s = SSH.new "example.com"
size = s.run "du -s /home/user | awk '{print }'" 
puts size

使用Net::SSH实现:

require 'net/ssh'
s = Net::SSH.start(@hostname, @username, :password => @password)
size = s.exec!("du -s /home/user | awk '{print }'")
puts size

如果您的目录可能有隐藏项,那么您可以使用目录 glob,或更强大更灵活的 find 命令,如下所示:

find /home/user -type d -maxdepth 1 -exec du -s {} + | 
awk '{sum = sum + }END{print sum}'