man sudo
-u user The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a user name, use #uid. When running commands as a
uid, many shells require that the '#' be escaped with a backslash ('\'). Note that if the targetpw Defaults option is set (see sudoers(5)) it is not possible to run
commands with a uid not listed in the password database.
-i [command]
The -i (simulate initial login) option runs the shell specified in the passwd(5) entry of the target user as a login shell. This means that login-specific resource
files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution. Otherwise, an interactive shell is
executed. sudo attempts to change to that user's home directory before running the shell. It also initializes the environment, leaving DISPLAY and TERM unchanged,
setting HOME, MAIL, SHELL, USER, LOGNAME, and PATH, as well as the contents of /etc/environment on Linux and AIX systems. All other environment variables are removed.
Sudo 已经支持以特定用户而不是 root 用户身份运行命令。因此,您可以简单地运行sudo -u your_user mkdir some_folder,而不是运行sudo mkdir some_folder,它会以该用户的身份执行所有命令。
此外,-i 标志将指示 sudo 启动新的 shell 并运行命令。新的 shell 将像登录 shell 一样被初始化(它将切换到用户的主目录,重新初始化 HOME 和其他变量等)。它最接近运行sudo su - your_user。
要让 Capistrano 使用 sudo -u <your-user> -i 而不仅仅是 sudo,请在 deploy.rb 中设置以下配置:
set :use_sudo, true
set :sudo, "sudo -u <your-user> -i"
Capistrano 现在将使用给定用户执行所有 sudo 命令,并使用全新的登录 shell。