From 8feba06a138b54c967512b6d3a9dea29f38ba865 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B1=E5=8D=9A=E4=BA=9E?= Date: Wed, 24 Feb 2021 18:44:09 +0800 Subject: [PATCH] add cert verify feature --- app/models/site_construct.rb | 4 +++ lib/tasks/add_cert_ver_for_site.rake | 40 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 lib/tasks/add_cert_ver_for_site.rake diff --git a/app/models/site_construct.rb b/app/models/site_construct.rb index e396725..7361fc0 100644 --- a/app/models/site_construct.rb +++ b/app/models/site_construct.rb @@ -21,6 +21,10 @@ class SiteConstruct field :infos, type: Array, :default => [] field :hidden, type: Boolean, :default => false field :copy_id + + field :cert_ver_added_text + field :cert_ver_file_content + field :cert_ver_location_path after_initialize do |record| if record.status.nil? record.status = "" diff --git a/lib/tasks/add_cert_ver_for_site.rake b/lib/tasks/add_cert_ver_for_site.rake new file mode 100644 index 0000000..792ab6f --- /dev/null +++ b/lib/tasks/add_cert_ver_for_site.rake @@ -0,0 +1,40 @@ +require 'net/ssh' +require 'pathname' +namespace :create_site do + desc "Add cert ver for site" + task :add_cert_ver_for_site,[:id] => :environment do |task,args| + begin + site_construct = SiteConstruct.find(args.id) + site_server = site_construct.site_server + if !site_server.nil? && !site_construct.cert_ver_location_path.blank? && !site_construct.cert_ver_file_content.nil? + @password = site_server.password + Net::SSH.start(site_server.ip , site_server.account , password: site_server.password) do |ssh| + nginx_path = site_construct.nginx_file + cert_ver_file_content = site_construct.cert_ver_file_content + location_path = site_construct.cert_ver_location_path + nginx_config = exec_command_by_user(ssh,"cat #{site_construct.nginx_file}") + if !site_construct.cert_ver_added_text.nil? + nginx_config = nginx_config.gsub(site_construct.cert_ver_added_text,'') + end + file_name = location_path.split('/')[-1] + file_path = "#{site_construct.path}/#{site_construct.site_name}/tmp/#{file_name}" + site_construct.cert_ver_added_text = " location #{location_path}{\n alias #{file_path};\n }" + site_construct.save + server_array = nginx_config.scan(/^[ \t]*server[ \t]{(?:(?!server[ \t]*{).)+}/m) + server_array.each do |server| + tmp = server[0...-1] + site_construct.cert_ver_added_text + "\n }" + nginx_config = nginx_config.sub(server,tmp) + end + cmd = "x='#{cert_ver_file_content}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{file_path}\"; unset x" + exec_command_by_user(ssh,cmd) + + cmd = "x='#{nginx_config}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{site_construct.nginx_file}\"; unset x" + exec_command_by_user(ssh,cmd) + exec_ssh_command_by_sudo(ssh,"service nginx restart") + end + end + rescue => e + puts [e,e.backtrace] + end + end +end \ No newline at end of file