python 高并发 tomcat_python tomcat脚本(远程线程dump,内存dump等功能实现)

#/usr/bin/python env#coding=utf-8########################################################################################1,请勿使用linux系统自带的openjdk。 ##2.将JDK路径设置为环境变量(/etc/profile) ##3.instance是Dcatalinan.home的家目录(/opt/tomcat/bin/catalina.sh,tomcat即是instance) ##4.如需修改tomcat绝对路径修改47行remote_dir1 ##5.如需修改登陆用户修改32行passwd_dict ##6.如需修改dump路径修改31行dump_dir ########################################################################################

importsysimportreimportargparseimportparamikoimportosimporttimeimportgetpassimportdatetime

parse=argparse.ArgumentParser()

parse.add_argument('-a','--instance',help='指定应用名')

parse.add_argument('-c','--cmd',help='指定执行操作,start/stop/restart/dump/memdump,(dump为线程dump,memdump为内存dump)')

parse.add_argument('-u','--user',help='指定tomcat启动用户,默认root用户')

parse.add_argument('-i','--host',help='指定IP')

args=parse.parse_args()

instance=args.instance

cmd=args.cmd

user=args.user

host=args.host

cmd_list=['start','stop','restart','dump','memdump']

dump_dir="/opt/tomcat_dump/" ###定义用户dump存放目录####passwd_dict={'root':'123456',#'liu':'123456',#'texs':'abc', ###该字典定义远程登录登录用户密码####'ceshi':'654321',#'text':'abcde'#}#################参数定义判断########################

if os.path.exists(dump_dir) andos.path.isdir(dump_dir):pass

else:

os.mkdir('/opt/tomcat_dump')if instance ==None:print ('\033[36m请选择应用实例,-h可查看参数详情\033[0m')

exit()else:

remote_dir1= '/opt/' +instance

remote_dir= remote_dir1 + '/' ###远程tomcat应用绝对路径###

if cmd not incmd_list:print ('\033[36m请选择操作,start/stop/restart/dump/memdump,-h可查看参数详情\033[0m')

exit()if user ==None:

user='root'

if host ==None:print ('\033[36m请输入IP,-h可查看参数详情\033[0m')

exit()else:

m=re.match('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$',host)if m ==None:print(host+'\033[36m不是有效的ip地址\033[0m')

exit()#if user not in passwd_dict:#print ("\033[36m用户名不存在,请检查\033[0m")#exit()#else:#passwd=passwd_dict[user]

if getpass.getuser() ==user: #判断是否做免密钥,是否需要密码

filename= os.path.expanduser('~/.ssh/known_hosts')if os.path.exists(filename) andos.path.isfile(filename):

with open(filename,'r') as f:for line inf.readlines():if host inline:

passwd=Noneelse:

passwd=getpass.getpass("\033[33mPlease input your password:\033[0m")else:

passwd=getpass.getpass("\033[33mPlease input your password:\033[0m")else:

passwd=getpass.getpass("\033[33mPlease input your password:\033[0m")#########远程登录定义################

defexec_cmd(host,user,passwd,cm):

ssh=paramiko.SSHClient()

ssh.load_system_host_keys()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname=host,username=user,password=passwd,timeout=30)try:

stdin,stdout,stderr=ssh.exec_command(cm)

out_log=stdout.read() #python3传过来的数据是bytes类型需stdout.read().decode()

err_log=stderr.read()if len(out_log) !=0:print ('\033[32mstdout:\033[0m'+out_log)if len(err_log) !=0:print ('\033[31mstderr:\033[0m'+err_log)if len(err_log) ==0:print ('\033[36mtomcat %s sucess\033[0m') %cmdelse:print ('\033[31mtomcat %s fail\033[0m') %cmdprint ('\033[33m######################################################################\033[0m')exceptException as e:print(e)finally:

ssh.close()defexec_cmd1(host,user,passwd,cm):

ssh=paramiko.SSHClient()

ssh.load_system_host_keys()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname=host,username=user,password=passwd,timeout=30)

stdin, stdout, stderr=ssh.exec_command(cm)try:

out=stdout.read()#err= stderr.read()

returnoutexceptException as e:print(e)finally:

ssh.close()defftp(host,user,passwd,remote_file,local_file):#t = paramiko.Transport((host))

#t.connect(username=user,password=passwd)

ssh=paramiko.SSHClient()

ssh.load_system_host_keys()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname=host,username=user,password=passwd,timeout=30)

t=ssh.get_transport()

sftp=paramiko.SFTPClient.from_transport(t)try:

sftp.get(remotepath=remote_file,localpath=local_file)#print ('Download file success %s ') % datetime.datetime.now()

exceptException as e:print ("\033[36mftp传输失败\033[0m")print(e)

exit()finally:

t.close()defstart():

cmd1="ps -Ao stat,pid,cmd|grep java|grep -w %s|grep -v grep|awk '{print $2}'" %remote_dir1

pid=exec_cmd1(host,user,passwd,cmd1)if len(pid) !=0:print("\033[36mtomcat应用已在运行\033[0m")else:

cmd2='source /etc/profile;sh'+remote_dir+'/bin/catalina.sh start'cmd3='tail -n15'+remote_dir+'/logs/catalina.out'exec_cmd(host,user,passwd,cmd2)#time.sleep(3)

#exec_cmd(host,user,cmd3)

defstop():

cmd1= "ps -Ao stat,pid,cmd|grep java|grep -w %s|grep -v grep|awk '{print $2}'" %remote_dir1

pid=exec_cmd1(host, user, passwd, cmd1)if len(pid) ==0:print("\033[36mtomcat应用未启动\033[0m")else:

cmd2='source /etc/profile;sh'+remote_dir+'/bin/catalina.sh stop'cmd3='tail -n15'+remote_dir+'/logs/catalina.out'exec_cmd(host,user,passwd,cmd2)#time.sleep(3)

#exec_cmd(host,user,cmd3)

defrestart():

cmd1= "ps -Ao stat,pid,cmd|grep java|grep -w" + remote_dir1 + "|grep -v grep|awk '{print $2}'"cmd2='source /etc/profile;sh'+remote_dir+'/bin/catalina.sh start'cmd3='source /etc/profile;sh' + remote_dir + '/bin/catalina.sh stop;sleep 3;sh'+remote_dir+'/bin/catalina.sh start'cmd4='tail -n15'+remote_dir+'/logs/catalina.out'pid=exec_cmd1(host, user, passwd, cmd1)if len(pid) ==0:

exec_cmd(host, user, passwd, cmd2)#time.sleep(3)

#exec_cmd(host,user,cmd4)

else:

exec_cmd(host,user,passwd,cmd3)#time.sleep(3)

#exec_cmd(host,user,cmd4)

defdump():try:print ('\033[36m请等待......\033[0m')

cmd1= "ps -Ao stat,pid,cmd|grep java|grep -w %s|grep -v grep|awk '{print $2}'" %remote_dir1

pid=exec_cmd1(host, user, passwd, cmd1)if len(pid) ==0:print("\033[36mtomcat应用已宕机\033[0m")

exit()

pid1=pid.strip()

thread_dump_file='/opt/tomcat_dump/thread_dump_%s-pid%s.log' %(host,pid1)

catalina_file='/opt/tomcat_dump/thread_catalina_%s-pid%s.out' %(host,pid1)

des="%slogs/catalina_%s-%s.out" %(remote_dir,host,pid1)

cmdone="ps -Ao pid,user,cmd|grep java|grep -w %s|grep -v grep|awk '{print $2}'" %remote_dir1

run_user=exec_cmd1(host, user, passwd, cmdone).strip()if run_user !=user:print ("\033[36m请用启动用户%s进行线程dump\033[0m") %run_user

exit()

cmd2="ps -eLo pid,lwp,pcpu,time|grep"+pid1+"|sort -nrk 3"cmd3="tail -f"+remote_dir+"logs/catalina.out>>%s&" %(des)

cmd4="kill -3"+pid1

cmd5="ps -Ao stat,pid,cmd|grep tail|grep 'catalina.out' | grep -w"+remote_dir1+"|awk '{print $2}'"thread_log=exec_cmd1(host, user, passwd, cmd2)

obj1=open(thread_dump_file,'w')

obj1.write(thread_log)

obj1.close()

exec_cmd1(host, user, passwd, cmd3)

exec_cmd1(host, user, passwd, cmd4)

time.sleep(3)

kill_pid=exec_cmd1(host, user, passwd, cmd5).strip()

cmd6="kill -9" +kill_pid

exec_cmd1(host, user, passwd, cmd6)if os.path.exists(catalina_file) andos.path.isfile(catalina_file):

os.remove(catalina_file)

ftp(host,user,passwd,des,catalina_file)

cmd7='rm -f %s' %des

exec_cmd1(host, user, passwd, cmd7)print("\033[36mtomcat 线程dump成功,dump文件/opt/tomact_dump目录下\033[0m")exceptException as e:print('\033[31mError,please check\033[0m')print(e)defmemdump():try:print ('\033[36m请等待......\033[0m')

cmd2= "ps -Ao stat,pid,cmd|grep java|grep -w %s|grep -v grep|awk '{print $2}'" %remote_dir1

pid=exec_cmd1(host, user, passwd, cmd2)if len(pid) ==0:print("\033[36mtomcat应用已宕机\033[0m")

exit()

pid1=pid.strip()

des="%slogs/memdump_%s-pid%s.bin" %(remote_dir,host,pid1)

heapdumpfile='/opt/tomcat_dump/memdump_%s-pid%s.bin' %(host,pid1)

cmd3= "ps -Ao stat,pid,cmd|grep java|grep -w %s|grep -v grep|awk '{print $3}'" %remote_dir1

cmdone="ps -Ao pid,user,cmd|grep java|grep -w %s|grep -v grep|awk '{print $2}'" %remote_dir1

run_user=exec_cmd1(host, user, passwd, cmdone).strip()

if run_user !=user:print ("\033[36m请用启动用户%s进行内存dump\033[m") %run_user

exit()

java_home=exec_cmd1(host, user, passwd, cmd3).strip()

a=re.compile(r'java$')

jmap_home=a.sub('jmap',java_home)

cmd4='%s -dump:format=b,file=%s %s' %(jmap_home,des,pid1)

exec_cmd1(host, user, passwd, cmd4)if os.path.exists(heapdumpfile) andos.path.isfile(heapdumpfile):

os.remove(heapdumpfile)

time.sleep(3)

cmd5="ps -Ao stat,pid,cmd|grep jmap|grep %s|grep 'dump:format=b'|grep -v grep" %pid1

ret=exec_cmd1(host, user, passwd, cmd5)if len(ret) ==0:

ftp(host, user, passwd, des, heapdumpfile)else:print ("\033[36mtomcat应用正在内存dump\033[0m")print ("...")

time.sleep(10)

ftp(host, user, passwd, des, heapdumpfile)

cmd6= 'rm -f %s' %des

exec_cmd1(host, user, passwd, cmd6)print("\033[36mtomcat 内存dump成功,dump文件/opt/tomact_dump目录下\033[0m")exceptException as e:print('\033[31mtomcat内存dump失败,请检查\033[0m')print(e)

cmd_dict={'start':start,'stop':stop,'restart':restart,'dump':dump,'memdump':memdump

}

cmd_dict[cmd]()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值