#!/bin/bash
repo="/etc/yum.repos.d/epel-7.repo"
if [ ! -e $repo ]; then # -e 判断文件存在;参考:Shell if 条件判断文件或目录
yum install -y wget
cd /etc/yum.repos.d/
mkdir bak
mv * bak
wget http://mirrors.aliyun.com/repo/Centos-7.repo
wget http://mirrors.aliyun.com/repo/epel-7.repo
# 移动两个文件到 目录
#wget http://mirrors.163.com/.help/CentOS7-Base-163.repo
#sed -i 's/$releasever/7/g' /etc/yum.repos.d/CentOS-Base.repo
# yum源没有对应版本包匹配;修改yum为centos7
yum clean all # 清除原有缓存
yum makecache # 生成新的缓存
# make cache [meɪk] [kaʃ] 制作 缓存{ka xi}
yum list # 校验yum
cd
else
echo "yum已经切换"
fi
############### 安装 vnc ##############
yum groupinstall -y "GNOME Desktop" # 安装GNOME Desktop图形桌面服务
yum install -y tigervnc-server # 安装vnc
systemctl get-default # 查看系统运行模式
systemctl set-default graphical.target # 切换到桌面模式运行
init 5 # 启动桌面模式
ln -sf /lib/systemd/system/graphical.target /etc/systemd/system/default.target
# 设置桌面运行模式为默认启动模式
cp /lib/systemd/system/vncserver@.service /etc/systemd/system/vncserver@:1.service
# 设置vnc用systemctl来管理(第一个用户vncserver@:1.service,第二个用户vncserver@:2.service,其他以此类推)
vncset="/etc/systemd/system/vncserver@:1.service.back"
if [ ! -e $vncset ]; then
echo "正在备份文件" ; cp /etc/systemd/system/vncserver@:1.service /etc/systemd/system/vncserver@:1.service.back
else
echo "备份文件存在"
fi
cat /dev/null > /etc/systemd/system/vncserver@:1.service
cat > /etc/systemd/system/vncserver@:1.service << "EOF"
[Unit]
Description=Remote desktop service (VNC)
After=syslog.target network.target
[Service]
Type=forking
# Clean any existing files in /tmp/.X11-unix environment
ExecStartPre=/bin/sh -c '/usr/bin/vncserver -kill %i > /dev/null 2>&1 || :'
ExecStart=/usr/sbin/runuser -l root -c "/usr/bin/vncserver %i"
PIDFile=/root/.vnc/%H%i.pid
ExecStop=/bin/sh -c '/usr/bin/vncserver -kill %i > /dev/null 2>&1 || :'
[Install]
WantedBy=multi-user.target
EOF
# 修改vnc用户为root(其他系统用户也可以这样改)
systemctl daemon-reload # 刷新systemctl
echo "设置vnc密码(第二个用户修改密码,vncpasswd user2,其他以此类推)"
vncpasswd
vncset="/etc/sysconfig/vncservers"
if [ ! -e $vncset ]; then
echo "正在备份文件" ; cp /etc/sysconfig/vncservers /etc/sysconfig/vncservers.back
else
echo "备份文件存在"
fi
cat /dev/null > /etc/sysconfig/vncservers
cat > /etc/sysconfig/vncservers <<"EOF"
VNCSERVERS="1:root"
VNCSERVERARGS[1]="-geometry 1024x768 -BlacklistTimeout 0"
EOF
# 修改vnc黑名单限制,否则会出现vnc客户端连接不上的情况(/etc/sysconfig/vncservers)
firewall-cmd --zone=public --add-port=5901/tcp --permanent
# 防火墙放行端口(vnc端口第一个用户5901,创建第二个用户5902,其他以此类推)
firewall-cmd --add-service vnc-server # 防火墙放行vnc服务
firewall-cmd --reload # 放行好端口和服务,重启防火墙才能生效
firewall-cmd --list-port # 查看端口是否放行成功
systemctl daemon-reload # 刷新
systemctl start vncserver@:1.service # 启动vnc
#启动,关闭,重启vnc
#systemctl start vncserver@:1.service #启动
#systemctl stop vncserver@:1.service #关闭
#systemctl restart vncserver@:1.service #重启