Class: Bolt::Transport::SSH::Connection
- Inherits:
-
Object
- Object
- Bolt::Transport::SSH::Connection
- Defined in:
- lib/bolt/transport/ssh/connection.rb
Defined Under Namespace
Modules: Win Classes: RemoteTempdir
Instance Attribute Summary collapse
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
-
#run_as ⇒ Object
This method allows the @run_as variable to be used as a per-operation override for the user to run as.
-
#target ⇒ Object
readonly
Returns the value of attribute target.
-
#user ⇒ Object
readonly
Returns the value of attribute user.
Instance Method Summary collapse
- #connect ⇒ Object
- #disconnect ⇒ Object
- #execute(command, sudoable: false, **options) ⇒ Object
- #handled_sudo(channel, data) ⇒ Object
-
#initialize(target, transport_logger, load_config = true) ⇒ Connection
constructor
A new instance of Connection.
- #make_executable(path) ⇒ Object
- #make_tempdir ⇒ Object
-
#running_as(user) ⇒ Object
Run as the specified user for the duration of the block.
- #sudo_prompt ⇒ Object
-
#with_remote_tempdir ⇒ Object
A helper to create and delete a tempdir on the remote system.
- #write_executable_from_content(dest, content, filename) ⇒ Object
- #write_remote_executable(dir, file, filename = nil) ⇒ Object
- #write_remote_file(source, destination) ⇒ Object
Constructor Details
#initialize(target, transport_logger, load_config = true) ⇒ Connection
Returns a new instance of Connection.
67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/bolt/transport/ssh/connection.rb', line 67 def initialize(target, transport_logger, load_config = true) @target = target @load_config = load_config ssh_user = load_config ? Net::SSH::Config.for(target.host)[:user] : nil @user = @target.user || ssh_user || Etc.getlogin @run_as = nil @logger = Logging.logger[@target.host] @transport_logger = transport_logger end |
Instance Attribute Details
#logger ⇒ Object (readonly)
Returns the value of attribute logger.
64 65 66 |
# File 'lib/bolt/transport/ssh/connection.rb', line 64 def logger @logger end |
#run_as ⇒ Object
This method allows the @run_as variable to be used as a per-operation override for the user to run as. When @run_as is unset, the user specified on the target will be used.
178 179 180 |
# File 'lib/bolt/transport/ssh/connection.rb', line 178 def run_as @run_as || target.['run-as'] end |
#target ⇒ Object (readonly)
Returns the value of attribute target.
64 65 66 |
# File 'lib/bolt/transport/ssh/connection.rb', line 64 def target @target end |
#user ⇒ Object (readonly)
Returns the value of attribute user.
64 65 66 |
# File 'lib/bolt/transport/ssh/connection.rb', line 64 def user @user end |
Instance Method Details
#connect ⇒ Object
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
# File 'lib/bolt/transport/ssh/connection.rb', line 89 def connect = { logger: @transport_logger, non_interactive: true } if (key = target.['private-key']) if key.instance_of?(String) [:keys] = key else [:key_data] = [key['key-data']] end end [:port] = target.port if target.port [:password] = target.password if target.password # Support both net-ssh 4 and 5. We use 5 in packaging, but Beaker pins to 4 so we # want the gem to be compatible with version 4. [:verify_host_key] = if target.['host-key-check'] if defined?(Net::SSH::Verifiers::Always) Net::SSH::Verifiers::Always.new else Net::SSH::Verifiers::Secure.new end elsif defined?(Net::SSH::Verifiers::Never) Net::SSH::Verifiers::Never.new else Net::SSH::Verifiers::Null.new end [:timeout] = target.['connect-timeout'] if target.['connect-timeout'] [:proxy] = Net::SSH::Proxy::Jump.new(target.['proxyjump']) if target.['proxyjump'] if @load_config # Mirroring: # https://github.com/net-ssh/net-ssh/blob/master/lib/net/ssh/authentication/agent.rb#L80 # https://github.com/net-ssh/net-ssh/blob/master/lib/net/ssh/authentication/pageant.rb#L403 if defined?(UNIXSocket) && UNIXSocket if ENV['SSH_AUTH_SOCK'].to_s.empty? @logger.debug { "Disabling use_agent in net-ssh: ssh-agent is not available" } [:use_agent] = false end elsif Bolt::Util.windows? pageant_wide = 'Pageant'.encode('UTF-16LE') if Win.FindWindow(pageant_wide, pageant_wide).to_i == 0 @logger.debug { "Disabling use_agent in net-ssh: pageant process not running" } [:use_agent] = false end end else # Disable ssh config and ssh-agent if requested via load_config [:config] = false [:use_agent] = false end @session = Net::SSH.start(target.host, @user, ) @logger.debug { "Opened session" } rescue Net::SSH::AuthenticationFailed => e raise Bolt::Node::ConnectError.new( e., 'AUTH_ERROR' ) rescue Net::SSH::HostKeyError => e raise Bolt::Node::ConnectError.new( "Host key verification failed for #{target.uri}: #{e.message}", 'HOST_KEY_ERROR' ) rescue Net::SSH::ConnectionTimeout raise Bolt::Node::ConnectError.new( "Timeout after #{target.options['connect-timeout']} seconds connecting to #{target.uri}", 'CONNECT_ERROR' ) rescue StandardError => e raise Bolt::Node::ConnectError.new( "Failed to connect to #{target.uri}: #{e.message}", 'CONNECT_ERROR' ) end |
#disconnect ⇒ Object
168 169 170 171 172 173 |
# File 'lib/bolt/transport/ssh/connection.rb', line 168 def disconnect if @session && !@session.closed? @session.close @logger.debug { "Closed session" } end end |
#execute(command, sudoable: false, **options) ⇒ Object
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/bolt/transport/ssh/connection.rb', line 224 def execute(command, sudoable: false, **) result_output = Bolt::Node::Output.new run_as = [:run_as] || self.run_as escalate = sudoable && run_as && @user != run_as use_sudo = escalate && @target.['run-as-command'].nil? command_str = command.is_a?(String) ? command : Shellwords.shelljoin(command) if escalate if use_sudo sudo_flags = ["sudo", "-S", "-u", run_as, "-p", sudo_prompt] sudo_flags += ["-E"] if [:environment] sudo_str = Shellwords.shelljoin(sudo_flags) command_str = "#{sudo_str} #{command_str}" else run_as_str = Shellwords.shelljoin(@target.['run-as-command'] + [run_as]) command_str = "#{run_as_str} #{command_str}" end end # Including the environment declarations in the shelljoin will escape # the = sign, so we have to handle them separately. if [:environment] env_decls = [:environment].map do |env, val| "#{env}=#{Shellwords.shellescape(val)}" end command_str = "#{env_decls.join(' ')} #{command_str}" end @logger.debug { "Executing: #{command_str}" } session_channel = @session.open_channel do |channel| # Request a pseudo tty channel.request_pty if target.['tty'] channel.exec(command_str) do |_, success| unless success raise Bolt::Node::ConnectError.new( "Could not execute command: #{command_str.inspect}", 'EXEC_ERROR' ) end channel.on_data do |_, data| unless use_sudo && handled_sudo(channel, data) result_output.stdout << data end @logger.debug { "stdout: #{data.strip}" } end channel.on_extended_data do |_, _, data| unless use_sudo && handled_sudo(channel, data) result_output.stderr << data end @logger.debug { "stderr: #{data.strip}" } end channel.on_request("exit-status") do |_, data| result_output.exit_code = data.read_long end if [:stdin] channel.send_data([:stdin]) channel.eof! end end end session_channel.wait if result_output.exit_code == 0 @logger.debug { "Command returned successfully" } else @logger.info { "Command failed with exit code #{result_output.exit_code}" } end result_output rescue StandardError @logger.debug { "Command aborted" } raise end |
#handled_sudo(channel, data) ⇒ Object
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/bolt/transport/ssh/connection.rb', line 194 def handled_sudo(channel, data) if data.lines.include?(sudo_prompt) if target.['sudo-password'] channel.send_data "#{target.options['sudo-password']}\n" channel.wait return true else # Cancel the sudo prompt to prevent later commands getting stuck channel.close raise Bolt::Node::EscalateError.new( "Sudo password for user #{@user} was not provided for #{target.uri}", 'NO_PASSWORD' ) end elsif data =~ /^#{@user} is not in the sudoers file\./ @logger.debug { data } raise Bolt::Node::EscalateError.new( "User #{@user} does not have sudo permission on #{target.uri}", 'SUDO_DENIED' ) elsif data =~ /^Sorry, try again\./ @logger.debug { data } raise Bolt::Node::EscalateError.new( "Sudo password for user #{@user} not recognized on #{target.uri}", 'BAD_PASSWORD' ) end false end |
#make_executable(path) ⇒ Object
346 347 348 349 350 351 352 |
# File 'lib/bolt/transport/ssh/connection.rb', line 346 def make_executable(path) result = execute(['chmod', 'u+x', path]) if result.exit_code != 0 = "Could not make file '#{path}' executable: #{result.stderr.string}" raise Bolt::Node::FileError.new(, 'CHMOD_ERROR') end end |
#make_tempdir ⇒ Object
309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/bolt/transport/ssh/connection.rb', line 309 def make_tempdir tmpdir = target..fetch('tmpdir', '/tmp') tmppath = "#{tmpdir}/#{SecureRandom.uuid}" command = ['mkdir', '-m', 700, tmppath] result = execute(command) if result.exit_code != 0 raise Bolt::Node::FileError.new("Could not make tempdir: #{result.stderr.string}", 'TEMPDIR_ERROR') end path = tmppath || result.stdout.string.chomp RemoteTempdir.new(self, path) end |
#running_as(user) ⇒ Object
Run as the specified user for the duration of the block.
183 184 185 186 187 188 |
# File 'lib/bolt/transport/ssh/connection.rb', line 183 def running_as(user) @run_as = user yield ensure @run_as = nil end |
#sudo_prompt ⇒ Object
190 191 192 |
# File 'lib/bolt/transport/ssh/connection.rb', line 190 def sudo_prompt '[sudo] Bolt needs to run as another user, password: ' end |
#with_remote_tempdir ⇒ Object
A helper to create and delete a tempdir on the remote system. Yields the directory name.
324 325 326 327 328 329 |
# File 'lib/bolt/transport/ssh/connection.rb', line 324 def with_remote_tempdir dir = make_tempdir yield dir ensure dir&.delete end |
#write_executable_from_content(dest, content, filename) ⇒ Object
339 340 341 342 343 344 |
# File 'lib/bolt/transport/ssh/connection.rb', line 339 def write_executable_from_content(dest, content, filename) remote_path = File.join(dest.to_s, filename) @session.scp.upload!(StringIO.new(content), remote_path) make_executable(remote_path) remote_path end |
#write_remote_executable(dir, file, filename = nil) ⇒ Object
331 332 333 334 335 336 337 |
# File 'lib/bolt/transport/ssh/connection.rb', line 331 def write_remote_executable(dir, file, filename = nil) filename ||= File.basename(file) remote_path = File.join(dir.to_s, filename) write_remote_file(file, remote_path) make_executable(remote_path) remote_path end |
#write_remote_file(source, destination) ⇒ Object
303 304 305 306 307 |
# File 'lib/bolt/transport/ssh/connection.rb', line 303 def write_remote_file(source, destination) @session.scp.upload!(source, destination, recursive: true) rescue StandardError => e raise Bolt::Node::FileError.new(e., 'WRITE_ERROR') end |