require 'net/ssh' require 'pathname' require 'json' namespace :create_site do desc "Change Site Server Name" task :change_site_server_name,[:id,:server_name,:port] => :environment do |task,args| begin @site_construct = SiteConstruct.find(args.id) site_server = @site_construct.site_server if !site_server.nil? @password = site_server.password update_infos("Starting change domain name and ports.") Net::SSH.start(site_server.ip , site_server.account , { password: site_server.password, port: site_server.port}) do |ssh| @site_construct.update(:domain_name=>args.server_name) if args.port.present? all_ports = args.port.split('////') @site_construct.update(:port=> all_ports ) end change_construct_nginx(ssh,@site_construct) @site_construct.update(:status=>'finish') end end rescue => e update_infos(e.to_s) @site_construct.update(:status=>'error') puts [e,e.backtrace] end end def change_construct_nginx(ssh, site_construct, update_multithread=false) @is_multithread = update_multithread auto_update_infos("Reading setting file...") raw_content = exec_command_by_user(ssh, "cat #{site_construct.nginx_file}") nginx_file_content = site_construct.generate_nginx_text(raw_content) auto_update_infos("Writing via safe stream...") ssh.open_channel do |channel| channel.exec("sudo -S sh -c 'cat > #{site_construct.nginx_file}'") do |ch, success| ch.on_extended_data do |c, type, data| if data =~ /password/i c.send_data("#{@password}\n") end end ch.send_data(nginx_file_content) ch.eof! end end ssh.loop exec_ssh_command_by_sudo(ssh, "service nginx restart") auto_update_infos("Finish!") end def exec_command_by_user(session,command) output = session.exec!(command) return output[0...-1].gsub(/^\n[\n]+/,'') end def exec_ssh_command_by_sudo(session,command) output = session.exec!("echo '#{@password}' | sudo -S #{command}") if output.include?("sudo:") && output.include?("command not found") output = session.exec!(command) end return output.encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '') end end