gpt4 book ai didi

ruby - Net::SSH sudo 命令在输入密码后挂起

转载 作者:数据小太阳 更新时间:2023-10-29 07:08:56 29 4
gpt4 key购买 nike

我一直在尝试使用 Thor 编写一个小型库,以帮助我快速创建新项目和站点。我写了这个小方法:

def ssh(cmd)
Net::SSH.start( server_ip, user, :port => port) do |session|
session.exec cmd
end
end

只是协助我在需要时在远程服务器上运行快速命令。

问题是当我需要在远程端的 sudo 下运行命令时,脚本似乎卡在我身上。例如当执行这个...

ssh("sudo cp #{file_from_path} #{file_to_path}" )

脚本会提示我输入密码

[sudo] password for user:

但是在输入之后整个事情就挂起。

有人会碰巧知道它为什么挂起吗,以及我可以做什么来在 Net::SSH(或其他替代方案)下的远程服务器上运行 sudo 命令?

*注意:在提出建议之前,我最初是在 Capistrano 下将这个库作为食谱编写的,直到我遇到了 Thor,并认为这是一个尝试它的好机会。我不反对在需要时将整个事情切换回 Capistrano,但如果没有一种在远程服务器上运行 sudo 命令的简单方法,我会感到非常惊讶。

最佳答案

我希望这对搜索的人有所帮助。我还需要在部署期间 sudo(重新启动瘦实例)

# deploy.rake
require 'net/ssh'

# INITIALIZE CONSTANTS HERE
HOST = 'yourwebsite.com'
USER = 'admin'
PASSWORD = 'your server password' # or use ENV variables?
# etc.

namespace :deploy do
namespace :staging do
task :restart do
commands = [
"cd #{PATH_TO_STAGING_APP} && git checkout master",
"git reset --hard HEAD",
"git pull origin master",
"bundle install --without test development",
"sudo thin restart -C /etc/thin/#{STAGING_APP}.yml"
]

Net::SSH.start(HOST, USER, :password => PASSWORD) do |ssh|
ssh.open_channel do |channel|
channel.request_pty do |ch, success|
if success
puts "Successfully obtained pty"
else
puts "Could not obtain pty"
end
end

channel.exec(commands.join(';')) do |ch, success|
abort "Could not execute commands!" unless success

channel.on_data do |ch, data|
puts "#{data}"
channel.send_data "#{PASSWORD}\n" if data =~ /password/
end

channel.on_extended_data do |ch, type, data|
puts "stderr: #{data}"
end

channel.on_close do |ch|
puts "Channel is closing!"
end
end
end
ssh.loop
end
end
end
end

注意一个 channel 只能执行一个命令。因此,我将命令与 commands.join(';')

链接在一起

引用:Net::SSH::Connection::Channel

关于ruby - Net::SSH sudo 命令在输入密码后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3356878/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com