UOS SP1 自動部署之部署腳本-[不適用,只做參考]

注意

uos軟件庫已經標準化,以下軟件已經不在適用,只能作爲參考!!!

UOS SP1 自動部署之部署腳本

介紹

每次安裝系統,都要進行一個個的進行重新設置部署,軟件多了真的是非常的繁瑣。好在linux系統可自定義性非常高。

腳本說明

  • 此腳本外加兩個源,deepin的panda以及docker源。
  • 此腳本集合了一些我常用的軟件進行自動化安裝。
  • 由於uos的定製化比較高,提權之前需要進行一些設置,以開啓權限。

執行腳本

sudo python3 uos_package_install.py

UOS需要開啓權限

1.激活-試用期激活
設置-系統信息-激活-試用期激活-立即激活
2.登陸
設置-網絡賬戶-登陸
3.獲取root權限-開啓開發者模式
設置-通用-開發者模式-進入開發者模式-在線激活-重啓

uos_package_install.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import shutil

install_package = {
    # 編譯
    'cmake': '',
    'gcc': '',
    'make': '',
    'pkg-config': '',
    'fakeroot': '',
    'patch': '',
    'apt-transport-https': '',
    'ca-certificates': '',
    'curl': '',
    'software-properties-common': '',
    'binutils': '',

    # 終端
    'ssh': '',
    'neofetch': '終端顯示信息/screenfetch',
    'lolcat': '代碼色彩',
    'cmatrix': '代碼雨',
    'tmux': '分屏軟件',
    'autojump': 'autojump插件',
    'git': 'github',
    'zsh': '',
    'vim': '',
    'proxychains-ng': '代理轉發終端命令',
    'oh-my-zsh': '',
    'screenfetch': '終端顯示信息-信息全-反應慢',
    'deepin-terminal': 'deepin透明終端',
    'locate': '文件搜索工具',

    # 字體
    'fonts-wqy-zenhei': '',
    'fonts-wqy-microhei': '',
    'ttf-dejavu': '',
    'noto-fonts': '',

    # 網絡應用
    'cn.360.browser-stable': '360安全瀏覽器',
    'google-chrome-stable': '谷歌瀏覽器',
    'org.mozilla.firefox-en-us': '火狐瀏覽器',
    'deepin.com.foxmail': 'wine-foxmail郵件客戶端',
    'deepin.com.thunderspeed': 'wine-迅雷極速版',
    'evolution': 'evolution',
    'thunderbird': '雷鳥郵件',
    'uget': 'bt下載器',
    'baidunetdisk': '百度網盤',
    'filezilla': '文件上傳',
    'shadowsocks-qt5': '科學上網',
    # 'electron-ssr': '科學上網-不存在',
    'teamviewer': '遠程軟件',

    # 社交溝通
    # 'deepin.com.qq.im.light': 'wine-QQ輕聊版',
    # 'electronic-wechat': '微信(第三方)',
    # 'apps.com.wechat.web': '微信網頁版',
    'linuxqq': 'QQ-linux',
    'deepin.com.qq.im': 'wine-QQ',
    'deepin.com.qq.office': 'wine-TIM',
    'deepin.com.wechat': 'wine-微信',

    # 音樂欣賞
    # 'pulseaudio': 'pulseaudio音量控制',
    'netease-cloud-music': '網易雲音樂',
    'deepin-voice-recorder': '深度錄音',

    # 音樂視頻
    'deepin-movie': '深度影院',
    # 'obs-studio': 'OBS錄屏',
    'smplayer': '播放器',
    'mpv': '播放器',

    # 圖像圖像
    'gimp': 'GNU 圖像處理程序',
    'inkscape': '',
    # 'deepin-screenshot': '深度截圖-被替代',
    'deepin-screen-recorder': '截圖錄屏',
    'deepin-picker': '深度取色器',

    # 辦公學習
    # 'libreoffice': 'office',
    # 'openoffice': 'office',
    'wps-office ttf-wps-fonts': 'wps',
    'moeditor': 'markdown',
    'typora': 'markdown',
    'foxitreader': '福昕閱讀器',
    'diffuse': '代碼對比工具',
    'xmind': 'xmind思維導圖',
    'youdao-dict': '有道詞典',

    # 數據庫
    'mongodb': '數據庫',
    'redis': '數據庫',
    'mariadb-server': 'mysql數據庫',
    'mariadb-client': 'mysql數據庫',
    'navicat': 'mysql數據庫可視化',
    'redis-desktop-manager': 'redis可視化工具',
    'robo3t': 'mongodb數據庫可視化',

    # 編程開發
    'wireshark': 'wireshark網絡抓包',
    'charles': 'charles抓包',
    'postman': '網頁調試工具',
    'sublime-text3': '編輯器',
    # 'code': 'Visual Studio Code',
    # 'com.visualstudio.code': 'Visual Studio Code IDE',
    # 'org.eclipse.java-ee': '',
    'docker-ce': 'docker-需要添加源',
    'openjdk-8-jdk': '',
    'pycharm-professional': 'python IDE',
    'putty': 'shell工具',

    # 系統管理
    # 'sogoupinyin': '搜狗輸入法-與uos輸入法衝突'
    # 'utools': 'utools搜索工具-不存在',
    'gufw': '防火牆',
    'deepin-calculator': '深度計算器',
    'deepin-boot-maker': '深度操作系統啓動盤的製作工具',
    'deepin-clone': '深度備份還原工具',
    'p7zip': '7Z解壓',
    'deepin.cn.360.yasuo': 'wine-360壓縮-4.0',
    'deepin.cn.com.winrar': 'wine-winrar壓縮工具',
    'bleachbit': '安裝磁盤清理工具Bleachbit',
    'synaptic': '新立得軟件包管理器',
    'deepin-topbar': 'topbar',
    'deepin-cloud-print': '深度雲打印',
    'deepin-cloud-scanner': '深度雲掃描',
    'ttf-deepin-opensymbol': '深度開源字體',
    'deepin-repair-tools': '深度系統修復工具',
    'deepin-graphics-driver-manager': '深度顯卡驅動管理器',

    # 聲卡
    # 'alsa-base': '',
    # 'alsa-oss': '',
    # 'alsa-tools': '',
    # 'alsa-utils': '',
    # 'alsa-tools-gui': '',
    # 'alsa-firmware-loaders': '',
}

enable_package = {
    'ssh': '',
    'mariadb': '',
}

update_package_info = {

}

failed_package_info = {
    # 手動安裝
    # 虛擬化
    'virtualbox': 'vbox虛擬機-手動安裝',
    'vmware-workstation': 'vmware-workstation 虛擬機-手動安裝',

    # 編程開發
    # 'golang': 'golang 語言 and IDE',
}

home_user_dir = os.path.expanduser('~')


def install_package_cmd(command="sudo apt install -y "):
    print("================ 安裝應用 ================")
    for package in install_package:
        new_cmd = command + package
        print(new_cmd)
        os.system(new_cmd)


def enable_package_cmd():
    print("================ 開機啓動 ================")
    for package in enable_package:
        enable_cmd = "systemctl enable %s" % package
        start_cmd = "systemctl start %s" % package

        os.system(enable_cmd)
        os.system(start_cmd)


def failed_package_info_cmd():
    print("================ 無法安裝的應用 ================")
    for package in failed_package_info:
        print('%s: %s' % (package, failed_package_info[package]))


def writer_file(path, content):
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)


def set_apt_source():
    """
    更新源
    :return:
    """
    # 備份修改源
    apt_docker_file = "/etc/apt/sources.list.d/docker.list"
    apt_source_file = "/etc/apt/sources.list"
    apt_docker_file_content = """
deb [arch=amd64] https://mirrors.ustc.edu.cn/docker-ce/linux/debian stretch stable
    """
    apt_source_file_content = """
## Generated by deepin-installer

deb [by-hash=force] https://packages.chinauos.cn/uos eagle main contrib non-free
#deb-src https://packages.chinauos.cn/uos eagle main contrib non-free

# Aliyun-deepin
#deb [by-hash=force] https://mirrors.aliyun.com/deepin lion main contrib non-free
deb [by-hash=force] https://mirrors.aliyun.com/deepin panda main contrib non-free
#deb-src https://mirrors.aliyun.com/deepin panda main contrib non-free
    """
    if os.path.exists(apt_docker_file):
        shutil.copy(apt_docker_file, apt_docker_file + '-bak')
    if os.path.exists(apt_source_file):
        shutil.copy(apt_source_file, apt_source_file + '-bak')
    writer_file(apt_docker_file, apt_docker_file_content)
    writer_file(apt_source_file, apt_source_file_content)

    # 更新源
    os.system('sudo apt update')

    # 添加docker密匙
    os.system('sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 7EA0A9C3F273FCD8')


def set_python():
    os.system('mkdir ~/.pip')
    pip_file = home_user_dir + '/.pip/pip.conf'
    pip_content = """
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com    
"""
    writer_file(pip_file, pip_content)

    os.system('pip3 install virtualenvwrapper')

def set_golang():
    os.system("wget https://dl.google.com/go/go1.14.linux-amd64.tar.gz")
    os.system("sudo tar -C /usr/local/lib -xzf go1.14.linux-amd64.tar.gz")


def set_oh_my_zsh():
    """
    設置 zsh
    :return:
    """
    oh_my_zsh_install = r"""
#!/bin/sh
#
# This script should be run via curl:
#   sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
# or wget:
#   sh -c "$(wget -qO- https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
#
# As an alternative, you can first download the install script and run it afterwards:
#   wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh
#   sh install.sh
#
# You can tweak the install behavior by setting variables when running the script. For
# example, to change the path to the Oh My Zsh repository:
#   ZSH=~/.zsh sh install.sh
#
# Respects the following environment variables:
#   ZSH     - path to the Oh My Zsh repository folder (default: $HOME/.oh-my-zsh)
#   REPO    - name of the GitHub repo to install from (default: robbyrussell/oh-my-zsh)
#   REMOTE  - full remote URL of the git repo to install (default: GitHub via HTTPS)
#   BRANCH  - branch to check out immediately after install (default: master)
#
# Other options:
#   CHSH    - 'no' means the installer will not change the default shell (default: yes)
#   RUNZSH  - 'no' means the installer will not run zsh after the install (default: yes)
#
# You can also pass some arguments to the install script to set some these options:
#   --skip-chsh: has the same behavior as setting CHSH to 'no'
#   --unattended: sets both CHSH and RUNZSH to 'no'
# For example:
#   sh install.sh --unattended
#
set -e

# Default settings
ZSH=${ZSH:-~/.oh-my-zsh}
REPO=${REPO:-robbyrussell/oh-my-zsh}
REMOTE=${REMOTE:-https://github.com/${REPO}.git}
BRANCH=${BRANCH:-master}

# Other options
CHSH=${CHSH:-yes}
RUNZSH=${RUNZSH:-yes}


command_exists() {
	command -v "$@" >/dev/null 2>&1
}

error() {
	echo ${RED}"Error: $@"${RESET} >&2
}

setup_color() {
	# Only use colors if connected to a terminal
	if [ -t 1 ]; then
		RED=$(printf '\033[31m')
		GREEN=$(printf '\033[32m')
		YELLOW=$(printf '\033[33m')
		BLUE=$(printf '\033[34m')
		BOLD=$(printf '\033[1m')
		RESET=$(printf '\033[m')
	else
		RED=""
		GREEN=""
		YELLOW=""
		BLUE=""
		BOLD=""
		RESET=""
	fi
}

setup_ohmyzsh() {
	# Prevent the cloned repository from having insecure permissions. Failing to do
	# so causes compinit() calls to fail with "command not found: compdef" errors
	# for users with insecure umasks (e.g., "002", allowing group writability). Note
	# that this will be ignored under Cygwin by default, as Windows ACLs take
	# precedence over umasks except for filesystems mounted with option "noacl".
	umask g-w,o-w

	echo "${BLUE}Cloning Oh My Zsh...${RESET}"

	command_exists git || {
		error "git is not installed"
		exit 1
	}

	if [ "$OSTYPE" = cygwin ] && git --version | grep -q msysgit; then
		error "Windows/MSYS Git is not supported on Cygwin"
		error "Make sure the Cygwin git package is installed and is first on the \$PATH"
		exit 1
	fi

	git clone -c core.eol=lf -c core.autocrlf=false \
		-c fsck.zeroPaddedFilemode=ignore \
		-c fetch.fsck.zeroPaddedFilemode=ignore \
		-c receive.fsck.zeroPaddedFilemode=ignore \
		--depth=1 --branch "$BRANCH" "$REMOTE" "$ZSH" || {
		error "git clone of oh-my-zsh repo failed"
		exit 1
	}

	echo
}

setup_zshrc() {
	# Keep most recent old .zshrc at .zshrc.pre-oh-my-zsh, and older ones
	# with datestamp of installation that moved them aside, so we never actually
	# destroy a user's original zshrc
	echo "${BLUE}Looking for an existing zsh config...${RESET}"

	# Must use this exact name so uninstall.sh can find it
	OLD_ZSHRC=~/.zshrc.pre-oh-my-zsh
	if [ -f ~/.zshrc ] || [ -h ~/.zshrc ]; then
		if [ -e "$OLD_ZSHRC" ]; then
			OLD_OLD_ZSHRC="${OLD_ZSHRC}-$(date +%Y-%m-%d_%H-%M-%S)"
			if [ -e "$OLD_OLD_ZSHRC" ]; then
				error "$OLD_OLD_ZSHRC exists. Can't back up ${OLD_ZSHRC}"
				error "re-run the installer again in a couple of seconds"
				exit 1
			fi
			mv "$OLD_ZSHRC" "${OLD_OLD_ZSHRC}"

			echo "${YELLOW}Found old ~/.zshrc.pre-oh-my-zsh." \
				"${GREEN}Backing up to ${OLD_OLD_ZSHRC}${RESET}"
		fi
		echo "${YELLOW}Found ~/.zshrc.${RESET} ${GREEN}Backing up to ${OLD_ZSHRC}${RESET}"
		mv ~/.zshrc "$OLD_ZSHRC"
	fi

	echo "${GREEN}Using the Oh My Zsh template file and adding it to ~/.zshrc.${RESET}"

	cp "$ZSH/templates/zshrc.zsh-template" ~/.zshrc
	sed "/^export ZSH=/ c\\
export ZSH=\"$ZSH\"
" ~/.zshrc > ~/.zshrc-omztemp
	mv -f ~/.zshrc-omztemp ~/.zshrc

	echo
}

setup_shell() {
	# Skip setup if the user wants or stdin is closed (not running interactively).
	if [ $CHSH = no ]; then
		return
	fi

	# If this user's login shell is already "zsh", do not attempt to switch.
	if [ "$(basename "$SHELL")" = "zsh" ]; then
		return
	fi

	# If this platform doesn't provide a "chsh" command, bail out.
	if ! command_exists chsh; then
		cat <<-EOF
			I can't change your shell automatically because this system does not have chsh.
			${BLUE}Please manually change your default shell to zsh${RESET}
		EOF
		return
	fi

	echo "${BLUE}Time to change your default shell to zsh:${RESET}"

	# Prompt for user choice on changing the default login shell
	printf "${YELLOW}Do you want to change your default shell to zsh? [Y/n]${RESET} "
	read opt
	case $opt in
		y*|Y*|"") echo "Changing the shell..." ;;
		n*|N*) echo "Shell change skipped."; return ;;
		*) echo "Invalid choice. Shell change skipped."; return ;;
	esac

	# Check if we're running on Termux
	case "$PREFIX" in
		*com.termux*) termux=true; zsh=zsh ;;
		*) termux=false ;;
	esac

	if [ "$termux" != true ]; then
		# Test for the right location of the "shells" file
		if [ -f /etc/shells ]; then
			shells_file=/etc/shells
		elif [ -f /usr/share/defaults/etc/shells ]; then # Solus OS
			shells_file=/usr/share/defaults/etc/shells
		else
			error "could not find /etc/shells file. Change your default shell manually."
			return
		fi

		# Get the path to the right zsh binary
		# 1. Use the most preceding one based on $PATH, then check that it's in the shells file
		# 2. If that fails, get a zsh path from the shells file, then check it actually exists
		if ! zsh=$(which zsh) || ! grep -qx "$zsh" "$shells_file"; then
			if ! zsh=$(grep '^/.*/zsh$' "$shells_file" | tail -1) || [ ! -f "$zsh" ]; then
				error "no zsh binary found or not present in '$shells_file'"
				error "change your default shell manually."
				return
			fi
		fi
	fi

	# We're going to change the default shell, so back up the current one
	if [ -n "$SHELL" ]; then
		echo $SHELL > ~/.shell.pre-oh-my-zsh
	else
		grep "^$USER:" /etc/passwd | awk -F: '{print $7}' > ~/.shell.pre-oh-my-zsh
	fi

	# Actually change the default shell to zsh
	if ! chsh -s "$zsh"; then
		error "chsh command unsuccessful. Change your default shell manually."
	else
		export SHELL="$zsh"
		echo "${GREEN}Shell successfully changed to '$zsh'.${RESET}"
	fi

	echo
}

main() {
	# Run as unattended if stdin is closed
	if [ ! -t 0 ]; then
		RUNZSH=no
		CHSH=no
	fi

	# Parse arguments
	while [ $# -gt 0 ]; do
		case $1 in
			--unattended) RUNZSH=no; CHSH=no ;;
			--skip-chsh) CHSH=no ;;
		esac
		shift
	done

	setup_color

	if ! command_exists zsh; then
		echo "${YELLOW}Zsh is not installed.${RESET} Please install zsh first."
		exit 1
	fi

	if [ -d "$ZSH" ]; then
		cat <<-EOF
			${YELLOW}You already have Oh My Zsh installed.${RESET}
			You'll need to remove '$ZSH' if you want to reinstall.
		EOF
		exit 1
	fi

	setup_ohmyzsh
	setup_zshrc
	setup_shell

	printf "$GREEN"
	cat <<-'EOF'
		         __                                     __
		  ____  / /_     ____ ___  __  __   ____  _____/ /_
		 / __ \/ __ \   / __ `__ \/ / / /  /_  / / ___/ __ \
		/ /_/ / / / /  / / / / / / /_/ /    / /_(__  ) / / /
		\____/_/ /_/  /_/ /_/ /_/\__, /    /___/____/_/ /_/
		                        /____/                       ....is now installed!


		Please look over the ~/.zshrc file to select plugins, themes, and options.

		p.s. Follow us on https://twitter.com/ohmyzsh

		p.p.s. Get stickers, shirts, and coffee mugs at https://shop.planetargon.com/collections/oh-my-zsh

	EOF
	printf "$RESET"

	if [ $RUNZSH = no ]; then
		echo "${YELLOW}Run zsh to try it out.${RESET}"
		exit
	fi

	exec zsh -l
}

main "$@"
"""

    zshrc = r"""
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="robbyrussell"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in ~/.oh-my-zsh/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"

# Uncomment the following line to automatically update without prompting.
# DISABLE_UPDATE_PROMPT="true"

# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS=true

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in ~/.oh-my-zsh/plugins/*
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"


# virtualenvs
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_VIRTUALENV=~/.local/bin/virtualenv
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source $HOME/.local/bin/virtualenvwrapper.sh

# java
#export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
#export JRE_HOME=${JAVA_HOEM}/jre
#export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib

# GOROOT: GO的安裝路徑
export GOROOT=/usr/local/lib/go
# GOPATH: GO的工作路徑,此處爲自行創建的GoEnv目錄,GoEnv下的src、pkg、bin也需自行創建
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin


#color{{{
autoload colors
colors

for color in RED GREEN YELLOW BLUE MAGENTA CYAN WHITE; do
eval _$color='%{$terminfo[bold]$fg[${(L)color}]%}'
eval $color='%{$fg[${(L)color}]%}'
(( count = $count + 1 ))
done
FINISH="%{$terminfo[sgr0]%}"
#}}}



#關於歷史紀錄的配置 {{{
#歷史紀錄條目數量
export HISTSIZE=10000
#註銷後保存的歷史紀錄條目數量
export SAVEHIST=10000
#歷史紀錄文件
export HISTFILE=~/.zsh_history
#以附加的方式寫入歷史紀錄
setopt INC_APPEND_HISTORY
#如果連續輸入的命令相同,歷史紀錄中只保留一個
setopt HIST_IGNORE_DUPS
#爲歷史紀錄中的命令添加時間戳
setopt EXTENDED_HISTORY

#啓用 cd 命令的歷史紀錄,cd -[TAB]進入歷史路徑
setopt AUTO_PUSHD
#相同的歷史路徑只保留一個
setopt PUSHD_IGNORE_DUPS

#在命令前添加空格,不將此命令添加到紀錄文件中
#setopt HIST_IGNORE_SPACE
#}}}

# 補全{{{
#彩色補全菜單
eval $(dircolors -b)
export ZLSCOLORS="${LS_COLORS}"
zmodload zsh/complist
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'


##行編輯高亮模式 {{{
# Ctrl+@ 設置標記,標記和光標點之間爲 region
zle_highlight=(region:bg=magenta #選中區域
special:bold      #特殊字符
isearch:underline)#搜索時使用的關鍵字
#}}}


#命令別名 {{{
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
alias ls='ls -F --color=auto'
alias ll='ls -l --color=auto'
alias grep='grep --color=auto'
alias la='ls -a'
#}}}


#漂亮又實用的命令高亮界面
setopt extended_glob
TOKENS_FOLLOWED_BY_COMMANDS=('|' '||' ';' '&' '&&' 'sudo' 'do' 'time' 'strace')


recolor-cmd() {
region_highlight=()
colorize=true
start_pos=0
for arg in ${(z)BUFFER}; do
((start_pos+=${#BUFFER[$start_pos+1,-1]}-${#${BUFFER[$start_pos+1,-1]## #}}))
((end_pos=$start_pos+${#arg}))
if $colorize; then
colorize=false
res=$(LC_ALL=C builtin type $arg 2>/dev/null)
case $res in
*'reserved word'*)   style="fg=magenta,bold";;
*'alias for'*)       style="fg=cyan,bold";;
*'shell builtin'*)   style="fg=yellow,bold";;
*'shell function'*)  style='fg=green,bold';;
*"$arg is"*)
[[ $arg = 'sudo' ]] && style="fg=red,bold" || style="fg=blue,bold";;
*)                   style='none,bold';;
esac
region_highlight+=("$start_pos $end_pos $style")
fi
[[ ${${TOKENS_FOLLOWED_BY_COMMANDS[(r)${arg//|/\|}]}:+yes} = 'yes' ]] && colorize=true
start_pos=$end_pos
done
}
check-cmd-self-insert() { zle .self-insert && recolor-cmd }
check-cmd-backward-delete-char() { zle .backward-delete-char && recolor-cmd }

zle -N self-insert check-cmd-self-insert
zle -N backward-delete-char check-cmd-backward-delete-char
"""

    vimrc = r"""
" [Common Configration] 公共配置
" [ui beautification] 界面美化
syntax enable  " 開啓代碼高亮
set nu    " 開啓行號
set ruler " 開啓標尺
" set cursorline " 開啓高亮光標所在行
set hlsearch " 開啓搜索結果高亮顯示
set incsearch " 開啓搜索逐字符高亮
" [improve performance] 提示性能
set viminfo= " 關閉 viminfo (用於加快 vim 啓動速度)
" [polyfill] 功能填補
set clipboard=unnamedplus " 開啓系統剪貼板支持(需要手動編譯最新版 vim 使其 +clipboard)
set backspace=indent,eol,start " 開啓 Backspace 鍵支持(否則 Backspace 無法刪除字符)
" [mouse support] 鼠標支持
set mouse=a " 開啓鼠標支持
set mouse=v " vim文件間複製粘貼完美方案
set selection=inclusive " 指定在選擇文本時光標所在位置也屬於被選中的範圍
set selectmode=mouse,key " 使鼠標和鍵盤都可以控制光標選擇文本
" [tab] tab鍵
set ts=4 " 指定製表符(tab)等於的空格數
set softtabstop=4 " 開啓軟製表(如果這4個空格是用tab鍵打出來的刪除會一起刪除)
set shiftwidth=4 " 指定自動縮進時縮進4個空格
" [indent] 縮進
set smartindent " 開啓智能縮進
set autoindent " 開啓自動縮進
set cindent " 開啓C縮進(對C、C++語言文件有效)
" [other] 其它配置
set backupcopy=yes " 開啓備份時行爲爲覆蓋
set cmdheight=1 " 設置命令行的高度爲1
"""

    install_file = home_user_dir + "oh-my-zsh-install.sh"
    zshrc_file = home_user_dir + "/.zshrc"
    vimrc_file = home_user_dir + "/.vimrc"

    writer_file(install_file, oh_my_zsh_install)
    os.system('sudo chmod 755 ' + install_file)
    os.system("sh " + install_file)

    writer_file(zshrc_file, zshrc)
    writer_file(vimrc_file, vimrc)

    # 激活
    os.system('source .zshrc')
    os.system('source .vimrc')

    # 使用zsh替換bash
    os.system("chsh -s /bin/zsh")


def set_others():
    """
    其他設置
    :return:
    """
    # 雙系統時間不一致
    os.system('sudo timedatectl set-local-rtc 1')

    # 終端打開文件
    os.system("sudo ln -s /usr/bin/xdg-open /usr/bin/open")

    # locate 當刪除或添加文件後
    os.system("sudo updatedb")

    # 刷新字體緩存
    os.system("sudo fc-cache -fv")


def header():
    title = """
************************************************************
***                     Start                            ***
                    UOS SP1 自動部署

UOS需要開啓權限:
1.激活-試用期激活
    設置-系統信息-激活-試用期激活-立即激活
2.登陸
    設置-網絡賬戶-登陸
3.獲取root權限-開啓開發者模式
    設置-通用-開發者模式-進入開發者模式-在線激活-重啓

***                     End                             ***
***********************************************************
"""
    print(title)


def main1():
    package_list = ""
    for package in install_package:
        package_list += package + " "
    print(package_list)


def main2():
    header()
    set_apt_source()
    set_python()
    set_golang()
    set_oh_my_zsh()
    set_others()

    install_package_cmd()
    enable_package_cmd()
    failed_package_info_cmd()


if __name__ == "__main__":
    main2()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章