How can I switch user in a Capistrano task?

2019-04-15 20:01发布

I made a small test task below:

set :user, "user"
set :password, "password"
set :root_password, "root password"
set :use_sudo, false
role :srv, "exmaple.com"

task :show_info do
    run "iptables -L", :shell => "su -" do |channel, stream, data|
        channel.send_data("#{root_password}\n")
    end
end

This server doesn't allow me to use sudo, so I have to login as a normal user then become root.

I have also tried to create surun from this article, though it doesn't help me... :(

Could someone please tell me the promising method to run command after switching to root in Capistrano?

Thanks in advance.

P.S. Added the output log:

$ cap show_info
  * executing `show_info'
  * executing "iptables -L"
    servers: ["example.com"]
    [example.com] executing command
    command finished in 000ms
failed: "su - -c 'iptables -L'" on example.com

标签: capistrano su
1条回答
Luminary・发光体
2楼-- · 2019-04-15 20:19

The point is default_run_options[:pty] = true

try this

def surun(command)
  default_run_options[:pty] = true
  password = fetch(:root_password, Capistrano::CLI.password_prompt("root password: "))
  run("su - -c #{command}") do |channel, stream, output|
      channel.send_data("#{password}\n")
  end
end
查看更多
登录 后发表回答