d11wtq
d11wtq

Reputation: 35318

Ruby CLI: Prompt for root password and continue executing script as root?

Other than requiring the user to invoke a ruby script through sudo, is there a way to start running a script as a regular user, then at some point during runtime, elevate privileges to root, by prompting the user for their root password?

Maybe something along the lines of #exec using the current command prefixed with sudo?

Upvotes: 1

Views: 803

Answers (1)

hawx
hawx

Reputation: 1323

This works. It just uses exec to call itself (test_script in this case) again. But be very careful to make sure that it doesn't run infinitely by adding a condition which will call exit.

#!/usr/bin/env ruby

if ARGV[0] == "--second"
  puts "...called again and exiting."
  exit
end

puts "Calling self again..."
exec "sudo ./test_script --second"

Upvotes: 2

Related Questions