自动化脚本:一键安装python自定义版本

zhongjh

关注

阅读 54

2023-05-08

1:环境:

  • centos 7
  • python2.7

2:脚本内容:

#!/usr/bin/env python
import os
import sys
import stat
import requests
import tarfile
import shutil
import subprocess

# Install necessary packages
try:
    subprocess.check_call(["yum", "install", "-y", "wget", "gcc", "make", "openssl-devel", "bzip2-devel", "zlib-devel", "libffi-devel"])
except subprocess.CalledProcessError:
    print("Failed to install necessary packages. Please check your system configuration and try again.")
    sys.exit(1)

# Step 1: Check for root privileges
if os.geteuid() != 0:
    print("This script must be run as root!")
    sys.exit(1)

# Step 2: Check if the desired version is already installed
current_version = sys.version_info
if current_version >= (3, 10):
    print("You already have the latest version of Python ({0}.{1}).".format(current_version.major, current_version.minor))
    sys.exit(0)

# Step 3: Prompt user for desired version and download it
desired_version = raw_input("Please enter the version of Python you want to install (e.g., '3.9.7'): ")
download_url = "https://mirrors.huaweicloud.com/python/" + str(desired_version) + "/Python-" + str(desired_version) + ".tgz"
download_file = "Python-" + str(desired_version) + ".tgz"

try:
    response = requests.get(download_url)
    with open(download_file, "wb") as f:
        f.write(response.content)
except requests.exceptions.RequestException:
    print("Failed to download Python. Please check your network connection and try again.")
    sys.exit(1)

# Step 4: Check if the download was successful
if not os.path.exists(download_file):
    print("Failed to download " + download_file + ". Please check your network connection and try again.")
    sys.exit(1)

# Step 5: Extract the downloaded file
try:
    with tarfile.open(download_file) as tar:
        tar.extractall()
except (OSError, tarfile.TarError):
    print("Failed to extract Python. Please check your download file and try again.")
    sys.exit(1)

# Step 6: Compile and install Python
try:
    subprocess.check_call(["./configure", "--prefix=/usr/local/python3.10"], cwd="Python-" + desired_version)
    subprocess.check_call(["make"], cwd="Python-" + desired_version)
    subprocess.check_call(["make", "install"], cwd="Python-" + desired_version)
except subprocess.CalledProcessError:
    print("Failed to compile or install Python. Please check your installation dependencies and try again.")
    sys.exit(1)

# Step 7: Modify the python path in the yum command
backup_file = "/usr/bin/yum.bak"
if not os.path.exists(backup_file):
    os.rename("/usr/bin/yum", backup_file)

with open(backup_file, "r") as f:
    content = f.read()
if "#!/usr/bin/python" in content:
    content = content.replace("#!/usr/bin/python", "#!/usr/bin/python2")
    with open("/usr/bin/yum", "w") as f:
        f.write(content)
        os.chmod("/usr/bin/yum", stat.S_IRWXU)


# Step 8: Print a success message
print("Python " + desired_version + " has been installed successfully and set as the default version!")


# Step 9: Move old python to backup and copy new python to /usr/bin/python
old_python_path = "/usr/bin/python"
new_python_path = "/usr/local/python3.10/bin/python3.10"

if os.path.exists(old_python_path):
    os.rename(old_python_path, "/usr/bin/python_old")
    print("Old Python version has been moved to /usr/bin/python_old")

shutil.copy2(new_python_path, old_python_path)
print("New Python version has been copied to /usr/bin/python")

# Step 10: Modify the python version of the urlgrabber-ext-down file
file_path = "/usr/libexec/urlgrabber-ext-down"

if os.path.exists(file_path):
    with open(file_path, "r+") as f:
        lines = f.readlines()
        f.seek(0)
        for line in lines:
            if line.startswith("#! /usr/bin/python"):
                line = "#! /usr/bin/python2\n"
            f.write(line)
        f.truncate()
        print("The shebang line has been updated to use Python 2.")
else:
    print("The file does not exist.")

精彩评论(0)

0 0 举报