以前学别人写一键安装包的作品,带注释,喜欢的可以拿去参考: python版本:2.7
【脚本说明】
VPS服务器一键安装sqlite版本的wordpresss.附带配置环境(Linux+Lighttpd+php+sqlite3).
vps只要开着SSH服务。就能一键部署好wordpress!不需要FTP!不需要MYSQL!简单,轻盈。
适合小内存VPS(搬瓦工)或者访问量不高的个人网站,企业站。
【脚本特点】
自带wp静态插件和屏蔽谷歌字体插件。
支持wordpress自定义链接。
防止sqlite文件被下载。
支持绑定域名
关闭WORDPRESS自带WP-CRON
【支持环境】
Centos6x,Ubuntu12x
【源码】
#!/usr/bin/env python
#coding:utf-8
import os
import sys
import urllib
import urllib2
import zipfile
import shutil
import re
import platform
from optparse import OptionParser
import socket
urllib2.socket.setdefaulttimeout(30)
#################################常用函数##########################
#禁用selinux
def disable_selinux():
os.system('setenforce 0 &> /dev/null')
if os.path.exists('/etc/selinux/config'):
fh_selinux = open('/etc/selinux/config', 'w')
fh_selinux.write('SELINUX=disabled')
fh_selinux.close()
# 处理hosts文件,防止影响sendmail启动速度
def add_hosts():
hostname = socket.gethostname()
add_hosts = ('127.0.0.1 %s. %s' % (hostname, hostname))
fh = open('/etc/hosts')
for line in fh.readlines():
if '127.0.0.1' in line.split() and hostname in line.split():
del add_hosts
fh.close
if 'add_hosts' in dir():
file_append('/etc/hosts', add_hosts)
def uninstall():
#system("rm -rf %s" % file_dir)
for service in ( 'lighttpd','php'):
os.system('/etc/init.d/%s stop' % service)
if os_dist in('redhat', 'centos'):
os.system('yum remove -y lighttpd* php* epel* ')
else:
os.system('apt-get --purge remove -y lighttpd* php5* ')
#修改文件,(文件完整路径,被替换的字符串,要替换的字符串)
def edit_file(filename,str1,str2):
file_object = open(filename, 'rb')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
new_text = all_the_text.replace(str1,str2)
file_object = open(filename, 'wb')
file_object.write(new_text)
file_object.close( )
def new_file(filename,str1):
file_object = open(filename, 'wb')
file_object.write(str1)
file_object.close( )
#追加内容
def add_str_to_file_end(filename,str):
file_object = open(filename, 'a')
file_object.write(str)
file_object.close( )
def file_append(file, content):
fh = open(file, 'a')
fh.write("\n" + content + '\n')
fh.close
#简单带进度的文件下载
def report(blocknr, blocksize, size):
current = blocknr*blocksize
sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))
def downloadFile(url):
print "\n Download File:",url
fname = url.split('/')[-1]
#print fname
urllib.urlretrieve(url, fname, report)
#解压缩文件到当前目录
def unzipFile(file_name):
print "\n unzip file:",file_name,"\n"
zip = zipfile.ZipFile(file_name)
zip.extractall(os.curdir)
#获取插件最新下载地址
def get_latest_plugins_download_url_from_pages(url):
html = urllib2.urlopen(url).read()
link_list =re.findall(r"(?<=itemprop=\"downloadUrl\" href=\").*?(?=\")|(?<=itemprop=\'downloadUrl\' href=\').*?(?=\')" ,html)
for url in link_list:
#print url
#只有一条插件文件地址
return url
#lighttpd重启
def lighttpd_restart():
if os_dist in('redhat', 'centos'):
os.system('service lighttpd restart')
else:
os.system('/etc/init.d/lighttpd restart')
###############################安装函数###################################
#安装配置httpd
def install_lighttpd():
if os_dist in('redhat', 'centos'):
#redhat和centos需要安装epel
os.system('yum -y install epel-release && yum -y install lighttpd')
#lighttpd配置
#禁用IPV6
a_str = 'server.use-ipv6 = "enable"'
b_str = 'server.use-ipv6 = "disable"'
edit_file('/etc/lighttpd/lighttpd.conf',a_str,b_str)
#设置线程数(防止报错)
aa_str = '#server.max-fds = 2048'
bb_str = 'server.max-fds = 2048'
edit_file('/etc/lighttpd/lighttpd.conf',aa_str,bb_str)
#禁止访问.SQLITE文件
l1_str = 'url.access-deny = ( "~", ".inc" )'
l2_str = 'url.access-deny = ( "~", ".inc", ".sqlite" )'
edit_file('/etc/lighttpd/lighttpd.conf',l1_str,l2_str)
#开启rewrite模块
r_str1 = '# "mod_rewrite"'
r_str2 = ' "mod_rewrite"'
edit_file('/etc/lighttpd/modules.conf',r_str1,r_str2)
#重启服务
os.system('chkconfig --levels 235 lighttpd on && service lighttpd start')
else:
#安装lighttpd
os.system('apt-get -y install lighttpd')
#lighttpd配置
#禁用IPV6
a_str = 'server.use-ipv6 = "enable"'
b_str = 'server.use-ipv6 = "disable"'
edit_file('/etc/lighttpd/lighttpd.conf',a_str,b_str)
#设置线程数(防止报错)
aa_str = '#server.max-fds = 2048'
bb_str = 'server.max-fds = 2048'
edit_file('/etc/lighttpd/lighttpd.conf',aa_str,bb_str)
#禁止访问.SQLITE文件
l1_str = 'url.access-deny = ( "~", ".inc" )'
l2_str = 'url.access-deny = ( "~", ".inc", ".sqlite" )'
edit_file('/etc/lighttpd/lighttpd.conf',l1_str,l2_str)
#开启rewrite模块
r_str1 = '# "mod_rewrite"'
r_str2 = ' "mod_rewrite"'
edit_file('/etc/lighttpd/lighttpd.conf',r_str1,r_str2)
#重启服务
os.system('/etc/init.d/lighttpd restart')
#安装PHP
def install_php():
if os_dist in('redhat', 'centos'):
#centos6 install php
os.system('yum -y install php-fpm php-pdo lighttpd-fastcgi')
#php配置
#添加 lighttpd 到用户和用户组
www_str1 = 'user = apache'
www_str2 = 'user = lighttpd'
edit_file('/etc/php-fpm.d/www.conf',www_str1,www_str2)
www_str11 = 'group = apache'
www_str22 = 'group = lighttpd'
edit_file('/etc/php-fpm.d/www.conf',www_str11,www_str22)
####################################################################
#设置PHP-FPM开机启动
os.system('chkconfig --levels 235 php-fpm on && service php-fpm start')
####################################################################
#php配置
#启用 Lighttpd 的 PHP5 支持
php_str1 = ';cgi.fix_pathinfo=1'
php_str2 = 'cgi.fix_pathinfo=1'
edit_file('/etc/php.ini',php_str1,php_str2)
###################################################################
#modules配置
#启用fastcgi模块
modules_str1 = '#include "conf.d/fastcgi.conf"'
modules_str2 = 'include "conf.d/fastcgi.conf"'
edit_file('/etc/lighttpd/modules.conf',modules_str1,modules_str2)
#fastcgi追加代码
fastcgi_text = '''## for the php-num-procs example it means you will get 17*5 = 85 php
## processes. you always should need this high number for your very
## busy sites. And if you have a lot of RAM. :)
## ADD YOUR LINES HERE
fastcgi.server += ( ".php" =>
((
"host" => "127.0.0.1",
"port" => "9000",
"broken-scriptfilename" => "enable"
))
)
## GOOD JOB
#fastcgi.server = ( ".php" =>'''
add_str_to_file_end('/etc/lighttpd/conf.d/fastcgi.conf',fastcgi_text)
####################################################################
#重启服务
os.system('service php-fpm restart && service lighttpd restart')
else:
os.system('apt-get -y install php5-cgi sqlite php5-sqlite && lighttpd-enable-mod fastcgi fastcgi-php ')
#配置服务
#启用 Lighttpd 的 PHP5 支持
php_str1 = ';cgi.fix_pathinfo=1'
php_str2 = 'cgi.fix_pathinfo=1'
edit_file('/etc/php5/cgi/php.ini',php_str1,php_str2)
#启用 PHP -FPM
fpm_str = '''server.modules += ("mod_fastcgi")
fastcgi.server = ( ".php" =>
((
"host" => "127.0.0.1",
"port" => "9000"
))
)'''
#重启服务
os.system('service lighttpd reload')
#
os.system('apt-get -y install php5-fpm')
new_file('/etc/lighttpd/conf-available/10-fastcgi-fpm.conf',fpm_str)
os.system('lighttpd-disable-mod fastcgi && lighttpd-disable-mod fastcgi-php && lighttpd-enable-mod fastcgi-fpm && service lighttpd force-reload')
#############################################################################
#开始程序
if __name__ == '__main__':
# 检查执行用户,必须在root权限下运行
if os.getuid() != 0:
print "\nThis script must be run as root.\nQuit!\n"
sys.exit()
# 发行版
os_dist = platform.dist()[0] #centos
os_ver = platform.dist()[1].split('.')[0] #6
# 仅支持RedHat, CentOS, Debian, Ubuntu
if os_dist not in ('centos', 'redhat', 'debian', 'Ubuntu'):
print "\nThis script only support RedHat, CentOS, Debian, Ubuntu.\nexit!\n"
sys.exit()
# 架构
arch = platform.architecture()[0] #64bit
# 处理命令行参数
# -d jjdlw.com
parser = OptionParser()
parser.add_option("-d", "--domain", dest="domain", action="store",
help="You need binding domain", metavar="DOMAiN")
(options, args) = parser.parse_args()
if options.domain in (None,''):
site_domain = 'null'
else:
site_domain = options.domain
# 禁用SELinux
disable_selinux()
# 处理hosts文件,防止影响sendmail启动速度
add_hosts()
# 检查并卸载已安装的服务
uninstall()
# 安装lighttpd
install_lighttpd()
#安装PHP
install_php()
#测试php是否安装成功
#os.system('echo \'<?php phpinfo();?>\' > /var/www/lighttpd/info.php')
#检测是否指定域名&配置REWRITE规则
if site_domain == 'null':
#未指定域名就使用默认目录
if os_dist in('redhat', 'centos'):
site_dir = '/var/www/lighttpd'
else:
site_dir = '/var/www'
#rewrite规则
#wordpress的rewrite规则
rewrite_str = '''
url.rewrite = (
"^/(wp-.+).*/?" => "$0",
"^/(sitemap.xml)" => "$0",
"^/(xmlrpc.php)" => "$0",
"^/(.+)/?$" => "/index.php/$1"
)'''
add_str_to_file_end('/etc/lighttpd/lighttpd.conf',rewrite_str)
else:
site_name = site_domain.replace('.','_')
site_dir = '/var/'+ site_name
os.mkdir(site_dir)
rewrite_str1 = '$HTTP["host"] =~ "(^|\.)'+site_domain.replace('.','\.')+'$" { server.document-root = "/var/www/'+site_name+'/"' +'server.error-handler-404 = "/index.php" url.rewrite = ("^/(wp-.+).*/?" => "$0","^/(sitemap.xml)" => "$0","^/(xmlrpc.php)" => "$0","^/(.+)/?$" => "/index.php/$1")}'
add_str_to_file_end('/etc/lighttpd/lighttpd.conf',rewrite_str1)
#rewrite生效
lighttpd_restart()
#切换到网站路径
os.chdir(site_dir)
os.system('rm -rf *')
#-----------------------
#下载配置wordpress主程序
#-----------------------
#lasest解压缩出来的还有层文件夹。文件夹名
last_zip_tmp_filename = 'wordpress'
#下载wordpress主程序
downloadFile('http://www.wordpress.org/latest.zip')
#解压缩
unzipFile('latest.zip')
#把wordpress文件夹里的文件移出来
files=os.listdir(last_zip_tmp_filename)
for file in os.listdir(last_zip_tmp_filename):
os.rename( last_zip_tmp_filename +'/'+file,os.curdir+'/'+file)
print 'Move File:',file
#删除wordpress文件夹
os.rmdir(last_zip_tmp_filename)
#------------------
#下载配置sqlite插件
#------------------
#获取sqlite插件最新下载地址,并返回文件名
sqlite_filename_url = get_latest_plugins_download_url_from_pages("https://wordpress.org/plugins/sqlite-integration/")
#下载sqlite插件
downloadFile(sqlite_filename_url)
#解压缩sqlite插件
sqlite_filename = os.path.basename(sqlite_filename_url)
unzipFile(sqlite_filename)
#把插件移动到wp的插件目录
shutil.move('sqlite-integration','wp-content/plugins')
#配置sqlite插件(参照插件安装说明)
shutil.copy("wp-content/plugins/sqlite-integration/db.php","wp-content")
#修改sqlite插件内容。关闭不是apache的提示。影响体验
no_apache_str1 = "isset($_SERVER['SERVER_SOFTWARE']) && stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false || isset($_SERVER['SERVER_SIGNATURE']) && stripos($_SERVER['SERVER_SIGNATURE'], 'apache') !== false"
no_apache_str2 = '1'
edit_file('wp-content/plugins/sqlite-integration/install.php',no_apache_str1,no_apache_str2)
#配置wp-config.php
shutil.copy("wp-config-sample.php","wp-config.php")
#Authentication Unique keys and Salts
config_str1 = '''define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');
define('AUTH_SALT', 'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT', 'put your unique phrase here');
define('NONCE_SALT', 'put your unique phrase here');'''
config_str2 = urllib2.urlopen('https://api.wordpress.org/secret-key/1.1/salt/').read()
edit_file('wp-config.php',config_str1,config_str2)
#改成中文版
a1_str = '<?php'
b1_str = '''<?php
define('WPLANG', 'zh_CN');
define('DISABLE_WP_CRON', true);'''
edit_file('wp-config.php',a1_str,b1_str)
#sqlite插件1.8补丁。创建数据库文件
if sqlite_filename.find('1.8.zip') >= 0:
os.mkdir("wp-content/database")
fp = open("wp-content/database/.ht.sqlite",'w')
fp.close()
################
#下载禁止谷歌字体的插件
bye_google_filename_url = get_latest_plugins_download_url_from_pages("https://wordpress.org/plugins/remove-google-fonts-references/")
#下载sqlite插件
downloadFile(bye_google_filename_url)
#解压缩sqlite插件
bye_google_filename = os.path.basename(bye_google_filename_url)
unzipFile(bye_google_filename)
#把插件移动到wp的插件目录
shutil.move('remove-google-fonts-references','wp-content/plugins')
################
#下载wp-super-cache插件
wsc_filename_url1 = get_latest_plugins_download_url_from_pages("https://wordpress.org/plugins/wp-super-cache/")
#下载sqlite插件
downloadFile(wsc_filename_url1)
#解压缩sqlite插件
wsc_filename = os.path.basename(wsc_filename_url1)
unzipFile(wsc_filename)
#把插件移动到wp的插件目录
shutil.move('wp-super-cache','wp-content/plugins')
#清理文件
os.remove('latest.zip')
os.remove(sqlite_filename)
os.remove(bye_google_filename)
os.remove(wsc_filename)
#设置权限
if os_dist in('redhat', 'centos'):
os.system('chown -R lighttpd:lighttpd * && chmod 777 *')
else:
os.system('chown -R www-data:www-data * && chmod 777 *')
print('\n========================\nDone!\n========================')