一、手动安装
(1)下载jdk-8u202-linux-x64.tar.gz上传至opt目录下并解压
tar -xzvf jdk-8u202-linux-x64.tar.gz
mv jdk-8u202-linux-x64 jdk
(2)配置环境变量
vi /etc/profile
#在最后增加这两行
JAVA_HOME=/opt/jdk
PATH=${JAVA_HOME}/bin:$PATH
(3)刷新环境变量
source /etc/profile
(4)查看是否有输出
java -version
二、shell脚本一键
#! /bin/bash
mkdir -p /usr/local/src
mv jdk-8u131-linux-x64.tar.gz /usr/local
tar -xvf jdk-8u131-linux-x64.tar.gz
chown -R root.root jdk1.8.0_131/
cat <<EOF >>/etc/profile
JAVA_HOME=/usr/local/jdk1.8.0_131
PATH=${JAVA_HOME}/bin:$PATH
EOF
source /etc/profile
三、python脚本
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
def uninstall():
"""
卸载自带jdk
方法:
rpm -qa|grep java
rpm -e --nodeps ***
:return:
"""
result = os.popen("rpm -qa | grep java")
for line in result.read().splitlines():
os.system("rpm -e --nodeps {}".format(line.strip()))
def install():
"""
安装JDK
过程:
1、解压
tar -zxvf jdk-8u311-linux-x64.tar.gz -C /usr/local/
2、添加环境变量
:return:
"""
os.system("tar -zxvf ./jdk-8u311-linux-x64.tar.gz -C /usr/local/")
with open("/etc/profile.d/java.sh", "w+") as java_file:
lines = [
"export JAVA_HOME=/usr/local/jdk1.8.0_311\n",
"export PATH=$PATH:$JAVA_HOME/bin\n"
]
java_file.writelines(lines)
def detect():
"""
检测是否安装成功
:return:
"""
os.environ['JAVA_HOME'] = "/usr/local/jdk1.8.0_311"
os.environ['PATH'] = '%s:%s' % (os.environ['PATH'], '/usr/local/jdk1.8.0_311/bin')
return True if os.system("java -version") == 0 else False
def prompt_fail():
"""
安装失败后提示
:return:
"""
print """
\033[5;31;40m 安装失败 \033[0m
"""
def prompt_success():
"""
安装成功后提示
:return:
"""
print """
\033[5;32;40m jdk-8u311-linux安装成功!\033[0m
使用前注意:
执行: source /etc/profile 或【重新登录当前服务器】来重新加载环境变量
安装路径:/usr/local/jdk1.8.0_311
环境变量配置:/etc/profile.d/java.sh
"""
if __name__ == '__main__':
uninstall()
install()
if detect():
prompt_success()
else:
prompt_fail()