-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshutils.rb
104 lines (88 loc) · 2.78 KB
/
sshutils.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
require 'net/ssh'
require 'net/scp'
class SshUtils
@ssh = nil
def self.start(host, user)
Net::SSH.start(host, user) do |ssh|
return SshUtils.new(ssh)
end
end
def close
@ssh.close
end
def isDirectory(path)
result = sshExec("test -d \"#{path}\"")
result[2] == 0
end
def checksum(path)
result = sshExec("/opt/bin/md5sum \"#{path}\"")
result[0].split(' ')[0] unless result[2] != 0
end
def getDirectoryContents(path)
result = sshExec("ls -1 \"#{path}\"")
result[0].split("\n") unless result[2] != 0
end
def pathExists?(path)
result = sshExec("test -e \"#{path}\"")
result[2] == 0
end
def createPath(path)
result = sshExec("mkdir -p \"#{path}\"")
$log.error("Couldn't create path! #{result[1]}") if result[2] != 0
result[2] == 0
end
def chmod(path, perms)
result = sshExec("chmod -R #{perms} \"#{path}\"")
result[2] == 0
end
def copy(localPath, remotePath)
$log.info(" -- Copying #{localPath} to #{remotePath}")
lastPercent = -1
currentFile = nil
begin
@ssh.scp.upload!(localPath, remotePath, :recursive => true) do |ch, name, sent, total|
if not name.eql?(currentFile)
currentFile = name
lastPercent = -1
end
percent = total.to_i == 0 ? 0 : (sent.to_f * 100 / total.to_f).to_i
if percent % 25 == 0 && percent > lastPercent
$log.info(" -- Copy Status for #{name}: #{percent}%")
lastPercent = percent
end
end
$log.warn(" -- Couldn't chmod the fole") unless chmod(remotePath, "777")
true
rescue Net::SCP::Error => e
$log.error(" -- Copy Error: #{e.message}")
false
end
end
private
def initialize(ssh)
@ssh = ssh
end
def sshExec(command)
stdout_data = ""
stderr_data = ""
exit_code = nil
@ssh.open_channel do |channel|
channel.exec(command) do |ch, success|
unless success
return nil
end
channel.on_data do |ch,data|
stdout_data+=data
end
channel.on_extended_data do |ch,type,data|
stderr_data+=data
end
channel.on_request("exit-status") do |ch,data|
exit_code = data.read_long
end
end
end
@ssh.loop
[stdout_data, stderr_data, exit_code]
end
end