client_management/lib/tasks/test_vpn.rake

48 lines
2.2 KiB
Ruby

require 'net/ssh'
require 'net/ssh/proxy/http'
require 'pathname'
namespace :create_site do
desc "Detect sites"
task :test_vpn,[:ip,:port,:username,:password] => :environment do |task,args|
# Multithread.where(:key=>'detect_sites').each{|thread| thread.destroy if (thread.status["status"] == "error" || thread.status["status"] == "finish")}
# @thread = Multithread.where(:key=>'detect_sites').first
#if @thread.nil?
# begin
# @thread = Multithread.create(:key=>'detect_sites',:status=>{"infos"=>[],"status"=>"detecting"})
# SiteServer.all.to_a.each do |site_server|
# @site_server = site_server
# update_thread_infos("<span style='color: skyblue;'>"+@site_server.server_name+"</span>")
# @password = @site_server.password
#begin
@site_server = SiteServer.where(:server_name=>"rulingcom.com").first
proxy = Net::SSH::Proxy::HTTP.new(args.ip, args.port.to_i,
:user => args.username, :password => args.password)
Net::SSH.start(@site_server.ip , @site_server.account , { password: @site_server.password, port: @site_server.port, proxy: proxy}) do |ssh|
exec_ssh_command_by_sudo("echo 'abc'")
end
#rescue Errno::ETIMEDOUT , Net::SSH::ConnectionTimeout => e
# update_thread_infos(e.to_s)
#end
# end
#@thread.update(:status=>@thread.status.merge({"status"=>"finish"}))
#rescue => e
# puts e
# @thread.update(:status=>{"infos"=>@thread.status["infos"].push(e.to_s),"status"=>"error"})
#end
#end
end
def exec_ssh_command_by_sudo(session,command)
output = session.exec!("echo '#{@password}' | sudo -S #{command}")
# output = session.exec!("echo '#{@password}' | sudo -S -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
def update_thread_infos(info)
puts info
@thread.status["infos"] = @thread.status["infos"].push(info)
@thread.save!
return @thread.status["infos"]
end
end