将一下3个脚本放到一个目录里,做成一个 python 的包即可使用


脚本介绍

操作服务脚本

#!/usr/bin/env python
# _*_coding:utf-8_*_
# Author: "Edward.Liu"
# Author-Email: lonnyliu@126.compile """
process hanlde files incloud
1.process status
use request get Url returncode
2.process Stop
use psutil kill process
3.process start
use subprocess run shell start process
4.process log
use process logs
5.process restart
""" # Improt Libary
import psutil
from subprocess import PIPE, Popen, STDOUT
import os
import sys
import requests
import datetime # Set vars
process_name = "/software/apache-tomcat-jenkins"
url = "http://172.31.1.230:8080" def process_id():
# use process name get process pid
process_base_str = "-Dcatalina.base=%s" % process_name
pid = {}
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline'])
except psutil.NoSuchProcess:
pass
else:
if process_base_str in pinfo.get('cmdline'):
pid[process_name] = pinfo.get('pid')
return pid def process_judgment():
# 判断 URL 的状态码
messages = ""
try:
jenkins_r = requests.get(url, timeout=None)
return jenkins_r.status_code
except requests.ConnectTimeout:
messges = "Timeout"
return messges
except requests.ConnectionError:
messages = "connection"
return messages
except requests.HTTPError:
messages = "httperror"
return messages
else:
return messages def process_status():
# judgment process status
if not process_id().get(process_name) is None:
if process_judgment() == 200:
print "\033[32mProcess %s normal\033[0m" \
% process_name.split('/')[2]
else:
print "\033[31mProcess Dont Access By:%s\033[0m" % url + "\n"\
"\033[31mMesages:%s" % process_judgment()
else:
print "\033[31mProcess %s does not exist" % process_name.split('/')[2] def process_log_info():
process_log = "tail -f %s/logs/catalina.out " % process_name
process_logs = Popen(process_log, shell=True,
stdout=PIPE, stderr=STDOUT)
returncode = process_logs.poll()
try:
while returncode is None:
line = process_logs.stdout.readline()
returncode = process_logs.poll()
line = line.strip()
print line
print returncode
except KeyboardInterrupt:
print 'ctrl+d or z' def process_kill():
# judgment process exist
if process_id().get(process_name) is None:
print "\033[31mProcess %s is Not Started" % process_name.split('/')[2]
sys.exit(0)
elif not process_id().get(process_name) is None \
and process_judgment() != 200:
print "\033[31mProcess %s is Started But Process access Failed \
Messages:" % (process_name, process_judgment())
sys.exit(0)
# stop process
PROCESSID = process_id().get(process_name)
p = psutil.Process(pid=PROCESSID)
p.kill()
if process_id().get(process_name) is None:
print "\033[32mprocess %s stop OK!!!\033[0m" \
% process_name.split('/')[2]
else:
print "\033[31mProcess %s Stop Failed\!!![033[0m" \
% process_name.split('/')[2] def process_init():
# start process
os.environ["JAVA_HOME"] = "/software/java_1.7"
start_time = datetime.datetime.now()
process_init_command = "%s/bin/startup.sh" % process_name
start = Popen(process_init_command, stdout=PIPE,
stderr=PIPE, shell=True)
stdout, stderr = start.communicate()
print stderr
print "\033[32mWaitting Process %s Start OK !!!\033[0m" \
% process_name.split('/')[2]
while process_judgment() != 200:
pass
end_time = datetime.datetime.now()
print "\033[32mprocess start time(s):%s\033[0m" \
% (end_time - start_time).seconds

操作文件脚本

 #!/usr/bin/env python
# _*_coding:utf-8_*_
# Author: "Edward.Liu"
# Author-Email: lonnyliu@126.compile import os
import zipfile
import datetime # set process directory vars
DEPLOY_ENV = "mobile"
DEPLOY_WAR = "cybershop-%s-0.0.1-SNAPSHOT.war" % DEPLOY_ENV
UPLOAD_WAR_DIRECTORY = "/software/source_files"
DEPLOY_TMP = "/software/deploy_tmp/"
DEPLOY_REALY = "/software/deploy_%s/" % DEPLOY_ENV
STATIC_DIRECTORY = "/data/www"
PICTURE_DIRECTORY = "/software/picture"
# Set process Diectory Vars end
# Set Process Used dir
Source_Path = "%s/%s" % (UPLOAD_WAR_DIRECTORY, DEPLOY_WAR)
now_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")
Last_File = "%s%s-%s" % (DEPLOY_TMP, DEPLOY_WAR.split('.war')[0], now_time)
# Set process Used End def process_judgment_dir():
# 判断目录是否存在
if not os.path.exists(UPLOAD_WAR_DIRECTORY):
os.makedirs(UPLOAD_WAR_DIRECTORY)
elif not os.path.exists(DEPLOY_TMP):
os.makedirs(DEPLOY_TMP)
elif not os.path.exists(DEPLOY_REALY):
os.makedirs(DEPLOY_REALY)
else:
print "\033[32mUsed Dir Is exists\033[0m" def process_source():
"""
1.解压部署文件
2.创建图片存放目录
"""
ret = 0
# 图片目录创建
Last_File_Pic = "%s/assets" % Last_File
if not os.path.exists(Last_File):
# 创建程序目录
os.makedirs(Last_File)
# 创建图片目录
os.makedirs(Last_File_Pic)
try:
zip_ref = zipfile.ZipFile(Source_Path, 'r')
zip_ref.extractall(Last_File)
zip_ref.close()
ret = 1
return ret
except IOError:
print "\033[31m%s Is Not Exists Please send Files\033[0m" \
% DEPLOY_WAR.split('.war')[0]
return ret def process_link():
if process_source() == 1:
# 创建项目启动所需链接
dest_pic = "%s/assets/upload" % Last_File
dest_static = "%s/www" % Last_File
os.symlink(PICTURE_DIRECTORY, dest_pic)
os.symlink(STATIC_DIRECTORY, dest_static)
# 创建项目启动所需链接----END
# 创建启动程序链接
dest_deploy_path = "%s%s" % (DEPLOY_REALY, DEPLOY_WAR.split('.war')[0])
os.symlink(Last_File, dest_deploy_path)
if os.path.islink(dest_deploy_path):
print "\033[32mCrate Link Process Is Scueeful\033[0m"
# 创建启动程序链接----END

整合脚本

#!/usr/bin/env python
# _*_coding:utf-8_*_
# Author: "Edward.Liu"
# Author-Email: lonnyliu@126.compile import handle_files
import handle_process
import argparse
import sys
import time
import datetime def check_arg(args=None):
parser = argparse.ArgumentParser(
description="EG: '%(prog)s' -p start|stop")
parser.add_argument('-p', '--process', default='log',
help='Input One of the {start|stop|status|log}')
parser.add_argument('-v', '--version', action='version',
version='%(prog)s 1.1')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
return parser.parse_args(args) def main():
args = check_arg(sys.argv[1:])
if args.process == "start":
handle_process.process_init()
elif args.process == "stop":
handle_process.process_kill()
elif args.process == "status":
handle_process.process_status()
elif args.process == "log":
handle_process.process_log_info()
elif args.process == "restart":
handle_process.process_kill()
time.sleep(10)
handle_process.process_init()
elif args.process == "deploy":
handle_files.process_judgment_dir()
print "\033[32mWaitting Unzip project\033[0m" + "." * 10
start_time = datetime.datetime.now()
handle_files.process_source()
end_time = datetime.datetime.now()
print "\033[32mPorject Unzip End-time(s):%s\033[0m" \
% (end_time - start_time).seconds
handle_process.process_kill()
handle_files.process_link()
handle_process.process_init() if __name__ == '__main__':
main()

tomcat 部署脚本的更多相关文章

  1. [svc]jdk+tomcat部署.jforum论坛部署

    安装jdk和tomcat jdk1.7.0_13(系列)下载url 我这里用的最新的jdk. 去官网下载即可 cd /usr/local/src/ tar xf jdk-8u162-linux-x64 ...

  2. linux下实现自动部署tomcat的脚本

    linux下实现自动部署tomcat的脚本 由于经常部署war到tomccat上,经常有一些重复的工作要做:停服务.备份war包.上传新的war包.启动服务.索性就写了一个自动部署的脚本. 脚本如下a ...

  3. Tomcat项目自动部署脚本

    一般情况下使用的Linux环境都是加固的,root路径只有超级管理员权限才能进入.我们新建一个自己的用户,在/home下会有一个用户目录,传输war包都放在这个目录下,此时不动webapps文件下的内 ...

  4. eclipse运行没问题,tomcat以脚本启动后插入数据库的中文会乱码

    记一次部署工程的时候遇到的问题 部署war包到win7的时候发现,布上去后插入数据库的中文会乱码,然后发现用eclipse运行源码没问题,一开始以为是war打出来的时候编码错误,然后将eclipse的 ...

  5. Tomcat重启脚本restart.sh停止脚本stop.sh

    Tomcat重启脚本restart.sh停止脚本stop.sh Tomcat本身提供了 startup.sh(启动)shutdown.sh(关闭)脚本,我们在部署中经常会出现死进程形象,无法杀掉进程需 ...

  6. Java web项目在linux环境下自动编译和部署脚本

    自动编译脚本 build.sh, 放置在项目根目录下. #!/bin/bash # check args # init path CURRPATH=`pwd` LIBDIR="$CURRPA ...

  7. Tomcat 部署

    <CATALINA_HOME>/webapps: Tomcat的主要Web发布目录,默认情况下把Web应用文件放于此目录. 1.war包部署:  将需要发布的web应用打成war文件, ( ...

  8. Tomcat 部署安装及JVM调优~

    Tomcat 部署Tomcat环境 环境准备 linux: CentOS 7.3 tomcat: 9.0.0.M21 jdk: 1.8.0_131 ip: 192.168.1.5 tomcat官方下载 ...

  9. 企业级Tomcat部署实践及安全调优

    1.1 Tomcat简介 Tomcat是Apache软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache.Sun和其他一些公司及个人 ...

随机推荐

  1. java.lang.IllegalArgumentException 不合法的参数异常

    报错内容: IllegalArgumentException 不合法的参数异常 十二月 06, 2016 10:06:56 上午 org.apache.catalina.core.StandardWr ...

  2. BackgroundWorker实现的winfrom中实现异步等待加载图片显示

    BackgroundWorker简介    BackgroundWorker在winfrom中有对应控件,该有三个事件:DoWork .ProgressChanged 和 RunWorkerCompl ...

  3. 轻松解决MYSQL数据库连接过多的错误

    1.数据库系统允许的最大可连接数max_connections.这个参数是可以设置的.如果不设置,默认是100.最大是16384. 2.数据库当前的连接线程数threads_connected.这是动 ...

  4. JPA(7) spring-data-jpa

    对于不是使用spring管理的项目,我们就自己创建对象使用:大概的思路就是①创建dao接口②实现该接口,并且编写逻辑: Dao: public interface StudentDao { publi ...

  5. KMP的原理详细讲解

    1.kmp算法的原理: 本部分内容转自:http://www.cnblogs.com/c-cloud/p/3224788.html及                           http:// ...

  6. yii2.0用户登录,退出判断(摘录)

    文章来源:http://blog.sina.com.cn/s/blog_88a65c1b0101ix13.html 判断用户是否登录 在 Yii2.0 里面,判断用户是否已经登录,我们用下面的代码即可 ...

  7. 由SimpleAyncTaskExecutor到ListenableFutureTask

    Spring AsyncExecutor观后感 导语 本来想看下spring关于Async&Sync TaskExecutor的主要内容,看着看着发现ListenableTaskExecuto ...

  8. git 上传项目到github

    1.本地新建文件夹GIT,Git Bash打开命令窗口, ①git config --global user.name "名字"  eg:  git config --global ...

  9. 七年IT生涯的经验教训

     七年IT生涯的经验教训[转]我在IT界也拼打了有好几年了,但是现在和别人比较起来不是很如意.从天分上来说,我在属于智商不低的人:从技术上说,几乎没有我拿不下的:从见解上看,我是很有点子看法的人. ...

  10. Play常用代码片段 http://www.anool.net/?p=625

    持续更新中: (1)按照降序查询: List<Entity> entities= Entity.find("order by id desc").fetch(2);   ...