通过Jenkins实现服务器端自动化部署 CI/CD
在应用服务器上面实现自动拉取最新版本代码
# coding=utf-8
from locale import locale_alias
import os
import requests
import wget
import hashlib
import tarfile
def isnew(jen_live_ver, local_live_ver):
#如果有新版本,返回ture,否则返回false
if not os.path.exists(local_live_ver):
return True
with open (local_live_ver, 'r') as f:
a = f.read()
r = requests.get(jen_live_ver)
if r.text != a:
return True
def isok(md5url, local_file_name):
#如果文件完整返回true
#md5url通过requests读出url的md5值,local_file_md5通过python MD5模块计算MD5值,在进行比较
r = requests.get(md5url)
r = r.text
with open(local_file_name, 'rb') as f:
m = hashlib.md5()
m.update(f.read())
if m.hexdigest() == r.strip():
return True
def depoly(local_file_name, depoly_dir, link_dir):
#把local_file_name解压缩到depoly_dir,解压后文件夹连接到link_dir
tar = tarfile.open(local_file_name)
tar.extractall(depoly_dir)
depoly_link_dir = depoly_dir + '/webnew-%s' % r.text
if os.path.exists(link_dir):
os.remove(link_dir)
os.symlink(depoly_link_dir, link_dir)
else:
os.symlink(depoly_link_dir, link_dir)
if __name__ == '__main__':
#判断服务器上是否有新版本
jen_live_ver = 'http://192.168.1.203/dev/live_ver'
local_ver_dir = '/var/www/html'
local_live_ver = '/var/www/html/live_ver'
if not isnew(jen_live_ver, local_live_ver):
print('没有发现新版本')
exit(1)
#如果有新版本,下载新版本
r = requests.get(jen_live_ver)
download_dir = '/var/www/download'
app_url = 'http://192.168.1.203/dev/pkgs/webnew-%s.tar.gz' % r.text
wget.download(app_url, download_dir)
#下载完成后进行文件完整性校验,如果文件损坏,删除文件
md5url = app_url + '.md5'
local_file_name = download_dir + '/webnew-%s.tar.gz' % r.text
# local_file_name = local_file_name.encode('utf-8')
# print('222222?22222222', a)
if not isok(md5url, local_file_name):
print('文件已损坏')
os.remove(local_file_name)
exit(2)
#部署软件
#1.解压 压缩包==》/var/www/depoly
#2.进行软连接
depoly_dir = '/var/www/depoly'
link_dir = '/var/www/html/new'
depoly(local_file_name, depoly_dir, link_dir)
#更新本地版本号
#1.删除本地live_ver文件,再重新下载live_ver文件
if os.path.exists(local_live_ver):
print('3333333333')
os.remove(local_live_ver)
wget.download(jen_live_ver, local_ver_dir)
else:
wget.download(jen_live_ver, local_ver_dir)

浙公网安备 33010602011771号