Skip to content

Commit 18e44f9

Browse files
committed
support commands/users/groups with spaces or other strange characters
1 parent baff92c commit 18e44f9

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

lib/sshkit/command.rb

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
require 'digest/sha1'
22
require 'securerandom'
3+
require 'shellwords'
34

45
# @author Lee Hambley
56
module SSHKit
@@ -145,7 +146,7 @@ def should_map?
145146

146147
def within(&_block)
147148
return yield unless options[:in]
148-
sprintf("cd #{options[:in]} && %s", yield)
149+
"cd #{options[:in].shellescape} && #{yield}"
149150
end
150151

151152
def environment_hash
@@ -155,8 +156,7 @@ def environment_hash
155156
def environment_string
156157
environment_hash.collect do |key,value|
157158
key_string = key.is_a?(Symbol) ? key.to_s.upcase : key.to_s
158-
escaped_value = value.to_s.gsub(/"/, '\"')
159-
%{#{key_string}="#{escaped_value}"}
159+
"#{key_string}=#{value.shellescape}"
160160
end.join(' ')
161161
end
162162

@@ -167,22 +167,22 @@ def with(&_block)
167167

168168
def user(&_block)
169169
return yield unless options[:user]
170-
"sudo -u #{options[:user]} #{environment_string + " " unless environment_string.empty?}-- sh -c '#{yield}'"
170+
"sudo -u #{options[:user].shellescape} #{environment_string + " " unless environment_string.empty?}-- sh -c #{yield.shellescape}"
171171
end
172172

173173
def in_background(&_block)
174174
return yield unless options[:run_in_background]
175-
sprintf("( nohup %s > /dev/null & )", yield)
175+
"( nohup #{yield} > /dev/null & )"
176176
end
177177

178178
def umask(&_block)
179179
return yield unless SSHKit.config.umask
180-
sprintf("umask #{SSHKit.config.umask} && %s", yield)
180+
"umask #{SSHKit.config.umask} && #{yield}"
181181
end
182182

183183
def group(&_block)
184184
return yield unless options[:group]
185-
%Q(sg #{options[:group]} -c "#{yield}")
185+
"sg #{options[:group].shellescape} -c #{yield.shellescape}"
186186
# We could also use the so-called heredoc format perhaps:
187187
#"newgrp #{options[:group]} <<EOC \\\"%s\\\" EOC" % %Q{#{yield}}
188188
end
@@ -213,7 +213,9 @@ def with_redaction
213213

214214
def to_s
215215
if should_map?
216-
[SSHKit.config.command_map[command.to_sym], *Array(args)].join(' ')
216+
arguments = Array(args)
217+
arguments = (arguments.any? ? arguments.shelljoin : [])
218+
[SSHKit.config.command_map[command.to_sym], *arguments].join(" ")
217219
else
218220
command.to_s
219221
end

0 commit comments

Comments
 (0)