Skip to content


Stable Diffusion 以Docker部署CPU运行在Linux系统

基于文本生成图像的强大模型

Stable Diffusion 的代码开源在 GitHub 上,地址如下:
https://github.com/CompVis/stable-diffusion

SDXL是 v1.5 模型的官方升级版,SDXL 的总参数数量为 66 亿,而 v1.5 为 9.8 亿
SDXL 的默认图像大小是 1024×1024,这比 v1.5 模型的 512×512 大 4 倍
SDXL 1.0 应该在具有 8GB VRAM 的 GPU 上有效工作。但sdwebui现在做不到(需要10G),能做到的只有COMFY UI

Stable Diffusion web UI
https://github.com/AUTOMATIC1111/stable-diffusion-webui
1.9.3 2024/4/23
1.6版本性能强劲,对小显存用户比较友好,不再轻易出现跑SDXL大模型爆显存的情况

cpu 版使用这个
https://github.com/openvinotoolkit/stable-diffusion-webui
This repo is a fork of AUTOMATIC1111/stable-diffusion-webui which includes OpenVINO support through a custom script to run it on Intel CPUs and Intel GPUs.
1.6版本

AMD显卡满血Stable Diffusion(SD+Fooocus+ComfyUI)无脑部署笔记(Linux+ROCm6.1.1)
https://zhuanlan.zhihu.com/p/656480759

Stable-Diffusion-WebUI使用指南
https://blog.csdn.net/qq_39108291/article/details/131025589

stablediffusion与midjouney的区别

1. midjouney的特点:

midjouney是一个商业化产品,用户需要付费才能使用,而且只能通过其官方Discord上的Discord机器人使用。midjouney没有公布其技术细节,但是其生成的图像效果非常惊艳,普通人几乎已经很难分辨出它产生的作品,竟然是AI绘画生成的。
midjouney善于适应实际的艺术风格,创造出用户想要的任何效果组合的图像。它擅长环境效果,特别是幻想和科幻场景,看起来就像游戏的艺术效果。midjouney的提示词门槛低,不需要特别精细的描述也可以出不错的图像。但是缺点是画面不太受控,而且被BAN的敏感词非常多,像bare,nude(裸体)这类词就用不了。

2. stablediffusion的特点:

stablediffusion是一个开源的模型,任何人都可以免费使用(但是需要有GPU来跑),也可以部署到GoogleColab和Drive去薅Tesla T4。stablediffusion是基于latent diffusion model(LDM)的条件扩散模型,采用CLIP text encoder提取的text embeddings作为condition。stablediffusion对当代艺术图像有比较好的理解,可以产生充满细节的艺术作品。除了文生图功能外,还支持图生图、图像重绘、个性化模型训练、可控生成等多种扩展应用。stablediffusion比较适合生成复杂的、有创意的插图。但是缺点是提示词门槛高,手部问题,Lora的兼容性等等。

3.midjouney和stablediffusion的优劣

midjouney和stablediffusion各有优劣之处,具体如下:

① midjouney的优点是:出图质量高、出图稳定、提示词简单、艺术风格丰富、环境效果出色。

②midjouney的缺点是:收费昂贵、只能通过Discord使用、技术细节不透明、画面不太受控、敏感词过多。

③stablediffusion的优点是:开源免费、可本地部署或云端使用、技术原理清晰、扩展应用多样、当代艺术理解好。

④stablediffusion的缺点是:需要GPU资源、提示词门槛高、手部问题突出、Lora兼容性差。

       那么对于普通人来说,选择stablediffusion可能比选择midjouney更合适,原因如下:

①stablediffusion是免费的,而midjouney是收费的,对于预算有限的普通人来说,stablediffusion更划算。

②stablediffusion是开源的,而midjouney是闭源的,对于想要了解AI绘图技术原理和细节的普通人来说,stablediffusion更透明。

③stablediffusion是灵活的,而midjouney是固定的,对于想要尝试不同功能和插件的普通人来说,stablediffusion更多样。

④stablediffusion是创新的,而midjouney是成熟的,对于想要挑战自己和发挥想象力的普通人来说,stablediffusion更有趣。

总的来说,如果您会使用midjouney,就相当于您学会了买车票搭车去某个地方,你只能选择路线,而您会使用stablediffusion,就相当于您自己买了一辆车,考了一个驾照,想去哪里就去哪里,想怎么开车就怎么开车(划重点)

安装要求

最核心的关键点:看显卡、看内存、看硬盘、看CPU。其中最重要的是看显卡,显卡N卡(英伟达Nvida显卡),最低10系起步,显存最低4G,6G及格;内存最低8G,16G及格;硬盘可用空间最好有个500G朝上,固态最佳,机械硬盘也没多大问题。CPU其实没太大要求,有好显卡的,CPU一般不会很差。

可能的误区

  • 1.误区1:必须用linux或者windows
    mac os也可以,但是同样在于其它的坑多,不建议在mac os上使用,当然我也没试过。
    windows和linux这个图形界面会占用显存,特别是显存小的时候更明显(windows只有server版可以只装命令行用)

  • 2.误区2:必须用N卡
    N卡坑少,出问题容易找到答案,并不是只能N卡。A卡、cpu也可以、i卡理论上可以,使用难度较大。Nvidia显卡(Cuda)或AMD显卡(ROCm)

  • 3.误区3:必须用conda
    用conda的原因在于很多开发者通常需要多个python环境,个人部署直接装在系统就行。

请放弃尝试在Win下通过虚拟机、WSL安装ROCm;

windows安装

推荐哔哩哔哩站秋叶做的整合包A绘世启动器.支持cpu/N卡/A卡
由于网络下载问题,这里使用的模型直接使用秋叶整合包中下载的。

最新一次更新整合包版本v4.8,24 年 4 月更新。
网盘:https://pan.quark.cn/s/2c832199b09b
解压密码:bilibili@秋葉aaaki
https://www.bilibili.com/video/BV1iM4y1y7oA/?spm_id_from=333.976.0.0

模型文件

Stable-diffusion支持五种模型文件,Checkpoint、Embedding、Hypernetwork、Lora和VAE。

  • 1.Checkpoint
    Checkpoint模型就是我们在webui的Stable Diffusion checkpoint中选择的模型。Checkpoint模型我把它理解为AI的记忆,它控制着AI能画出什么,画出的东西长什么样。
  • 2.Lora
    Lora模型是一种生成对抗网络模型,主要用对Checkpoint模型进行定向的微调。个人理解是用来做Checkpoint模型提示词重映射的。比如,在一个Checkpoint模型中,提示词“猫”对应形象是“加菲猫”,那么Lora就可以将“猫”这个提示词重映射,使其对应的形象变成HelloKitty,那么在加持Lora模型的Checkpoint模型上输入“猫”这个提示词后AI将不再生成加菲猫,而全部生成HelloKitty。
  • 3.Embedding
    在Stable diffuion中,Embedding模型提供了一种向已有模型嵌入新内容的方式,Embedding模型可以使用很少的图片数据,来生成一个具有新的风格或者人物形象的模型,并且可以使用特定的提示词来映射这些特征。
  • 4.Hypernetworks
    Hypernetworks又叫超网络,Hypernetworks模型是一种风格化文件,可以为AI生成的图像应用指定画风。如,同样是画一个HelloKitty,在没有应用Hypernetworks模型的情况,画出来的HelloKitty就是一只正常的HelloKitty,如果给AI应用一个金享泰画风的Hypernetworks模型,那么AI画出来的HelloKitty就变成一只油腻的HelloKitty。
  • 5.VAE
    VAE的作用就是在第一章中讲到的将图片从潜空间的压缩数据解码变成一张正常的图片,不同的VAE会影响AI出图的色调,如果当我们不使用VAE时,AI生成的图片均会有一层灰蒙蒙的感觉,使用VAE会使图片的饱和度有所区别。
  • 6.AestheticGradients
    AestheticGradients(美学渐变)是以插件的形式存在一种模型修改技术,AestheticGradients模型需要依赖AestheticGradients插件才能使用,效果和Hypernetworks差不多,但是基于AestheticGradients插件提供了更多的可调节参数,而Hypernetworks的参数是已经定死了不可更改的。

相关网站

吐司
在线生成,提示词,模型下载
https://tusi.cn/

huggingface
国内不能访问
https://huggingface.co/

c站
Civitai 专门收集和分享Stable Diffusion相关的模型
收集并分享1700+经过筛选的Stable Diffusion模型文件,免费下载。
提供1万+带提示语的示例图片,供用户学习描述内容的方法。
https://www.civita.com
国内镜像
https://civitai.work/

哩布哩布AI
收集了很多不同类型的Stable Diffusion模型,在线生成,下载这些AI生成图片和视频的模型
https://www.liblib.art/

AI提示词
https://www.4b3.com/

AI 作图知识库(教程): https://guide.novelai.dev/
标签超市(解析组合): https://tags.novelai.dev/
原图提取标签: https://spell.novelai.dev/

模型分享下载链接:https://pan.quark.cn/s/32f374eef667

AI绘图的用法拓展

  • ControlNet
    ControlNet的原理主要是使用OpenCV的一些识别算法,如姿势识别、手势识别、边缘检测、深度检测等,先对参考图做一层机器视觉方面的预处理,生成身体骨骼特征点、手势骨骼特征点、描边图、深度图等中间图,然后再让AI参考这些中间图进行创作

  • 制作全景图
    并接360图片

  • mov2mov插件
    https://github.com/Scholar01/sd-webui-mov2mov
    生成同步的视频文件

  • 人物换装

  • OutPainting
    outpainting是官方提供的一项AI图像扩展技术,AI可以根据已有的图像来扩展图像之外的画面。

  • SadTalker
    唇型同步

  • 生成类似的图
    这个功能在通过photoshopP图之后,使用AI来融合P图中的看起来比较违和的元素时非常有用,有了这个功能我们就可以快速的使用PS往图中加入我们想要的元素,然后使用AI来融合,当然出图的效果还是取决于大模型;

  • 小图高清重绘

  • 超清放大

准备虚拟机

virtualbox 虚拟一台rock9.3
10核/17G内存/120G硬盘

查看环境

查看系统版本

cat /etc/redhat-release
Rocky Linux release 9.3 (Blue Onyx)

查看内核版本

uname -a
Linux localhost.localdomain 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 8 17:36:32 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

查看ssh及openssl 版本

ssh -V
OpenSSH_8.7p1, OpenSSL 3.0.7 1 Nov 2022
不升级

python版本

python -V
Python 3.9.18

glibc版本

ldd –version
ldd (GNU libc) 2.34

rocky9上打开加密兼容

便于低版本ssh 连接
update-crypto-policies –show
update-crypto-policies –set LEGACY

修改ip

查看当前ip

ip a
nmcli device show
nmcli con show

使用配制文件修改

vi /etc/NetworkManager/system-connections/enp0s3.nmconnection

[ipv4]
method=manual
address1=192.168.244.14/24,192.168.244.1
dns=223.5.5.5;1.1.1.1

重新载入生效

nmcli connection reload
nmcli connection down enp0s3 && nmcli connection up enp0s3

主机名设定

hostnamectl set-hostname dev-ai-diffusion.local

hostnamectl status
 Static hostname: dev-ai-diffusion.local
       Icon name: computer-vm
         Chassis: vm 

                            Machine ID: 45d4ec6ccf3646248a8b9cc382baf29d
         Boot ID: 0b6cfd83e8534a1f81f08de3962b8ba9
  Virtualization: oracle
Operating System: Rocky Linux 9.3 (Blue Onyx)      
     CPE OS Name: cpe:/o:rocky:rocky:9::baseos
          Kernel: Linux 5.14.0-362.8.1.el9_3.x86_64
    Architecture: x86-64
 Hardware Vendor: innotek GmbH
  Hardware Model: VirtualBox
Firmware Version: VirtualBox

安装中文语言包

localectl list-locales |grep zh
dnf list |grep glibc-langpack
dnf install glibc-langpack-zh

关防火墙

systemctl stop firewalld
systemctl disable firewalld

selinux

setenforce 0 && sed -i ‘/SELINUX/s/enforcing/disabled/’ /etc/selinux/config

vim 打开黏贴模

echo ‘set paste’ >> ~/.vimrc

时区

timedatectl set-timezone Asia/Shanghai

启用启动脚本

systemctl enable rc-local.service
systemctl start rc-local.service
systemctl status rc-local.service

chmod +x /etc/rc.d/rc.local
chmod +x /etc/rc.local

常用工具

yum -y install wget vim net-tools telnet yum-utils device-mapper-persistent-data lvm2 tar curl lrzsz rsync psmisc sysstat lsof

docker yum

step 1: 安装必要的一些系统工具

sudo yum install -y yum-utils device-mapper-persistent-data lvm2

Step 2: 添加软件源信息

sudo yum-config-manager –add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

Step 3

sudo sed -i ‘s+download.docker.com+mirrors.aliyun.com/docker-ce+’ /etc/yum.repos.d/docker-ce.repo

Step 4: 更新并安装Docker-CE

sudo yum makecache fast
sudo yum -y install docker-ce

Installed:
  container-selinux-3:2.229.0-1.el9.noarch          containerd.io-1.6.31-3.1.el9.x86_64           docker-buildx-plugin-0.14.0-1.el9.x86_64     docker-ce-3:26.1.2-1.el9.x86_64      docker-ce-cli-1:26.1.2-1.el9.x86_64    
  docker-ce-rootless-extras-26.1.2-1.el9.x86_64     docker-compose-plugin-2.27.0-1.el9.x86_64     fuse-common-3.10.2-8.el9.x86_64              fuse-overlayfs-1.13-1.el9.x86_64     fuse3-3.10.2-8.el9.x86_64              
  fuse3-libs-3.10.2-8.el9.x86_64                    libslirp-4.4.0-7.el9.x86_64                   slirp4netns-1.2.3-1.el9.x86_64               tar-2:1.34-6.el9_1.x86_64           

注意:官方软件源默认启用了最新的软件,安装指定版本的Docker-CE
yum list docker-ce.x86_64 –showduplicates | sort -r

docker-ce.x86_64               3:26.1.2-1.el9                  docker-ce-stable 
docker-ce.x86_64               3:26.1.2-1.el9                  @docker-ce-stable
docker-ce.x86_64               3:26.1.1-1.el9                  docker-ce-stable 

yum -y install docker-ce-[VERSION]

Step 5: 开启Docker服务

sudo service docker start

查看版本

docker version

Engine:
  Version:          26.1.2
  API version:      1.45 (minimum version 1.24)
  Go version:       go1.21.10
  Git commit:       ef1912d
  Built:            Wed May  8 13:59:54 2024
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.31
  GitCommit:        e377cd56a71523140ca6ae87e30244719194a521
 runc:
  Version:          1.1.12
  GitCommit:        v1.1.12-0-g51d5e94
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

docker加速

vi /etc/docker/daemon.json

{
"registry-mirrors":["https://docker.nju.edu.cn/"]
}

docker nvidia驱动

非必要,使用N卡时安装

yum install -y nvidia-docker2

systemctl daemon-reload
systemctl enable docker
systemctl restart docker

git 安装

yum install git

使用三方现有镜像安装

下载Stable Diffusion Docker 相关镜像

要下载Stable Diffusion的Docker镜像,您可以使用以下命令:
官方镜像
docker pull diffusion/stable:latest
docker pull kestr3l/stable-diffusion-webui

其它

腾讯加速
docker pull gpulab.tencentcloudcr.com/ai/stable-diffusion:1.0.8

docker.io 中的民间镜像
docker pull bobzhao1210/diffusion-webui

国外镜像

docker pull siutin/stable-diffusion-webui-docker:latest-cpu
docker pull siutin/stable-diffusion-webui-docker:latest-cuda

国内镜像

docker pull registry.cn-hangzhou.aliyuncs.com/sunsharing/stable-diffusion-webui-docker:latest-cpu

阿里官方gpu镜像,比较新

docker pull egs-registry.cn-hangzhou.cr.aliyuncs.com/egs/sd-webui:4.3.5-full-pytorch2.1.2-ubuntu22.04

使用阿里gpu镜像

docker pull egs-registry.cn-hangzhou.cr.aliyuncs.com/egs/sd-webui:4.3.5-full-pytorch2.1.2-ubuntu22.04

docker images

REPOSITORY                                              TAG                                   IMAGE ID       CREATED         SIZE
egs-registry.cn-hangzhou.cr.aliyuncs.com/egs/sd-webui   4.3.5-full-pytorch2.1.2-ubuntu22.04   22226c589a11   3 weeks ago     34.7GB

镜像中相关版本
version: 1.6.0  •  python: 3.10.10  •  torch: 2.1.2+cu118  •  xformers: N/A  •  gradio: 3.41.2

下载标准sd-1.5模型:

存放到models/Stable-diffusion ,使用GPU时下载,不支持cpu运行 ,如果没有ui启动时会尝试自动下载 ,4g左右

mkdir /host  
cd /host  
wget https://aiacc-inference-public-v2.oss-accelerate.aliyuncs.com/aiacc-inference-webui/models/v1-5-pruned-emaonly.safetensors

下载国内 AnythingV5_v5PrtRE.safetensors 2g左右

wget https://api.tusiart.com/community-web/v1/model/file/url/v2?modelFileId=600998819589521712 AnythingV5_v5PrtRE.safetensors

webui启动时必需要一个大模型,这个支持cpu.

Stable-diffusion WebUI文件夹功能

  • localizations: 汉化包
  • configs: 配制文件
  • embeddings:存放美术风格文件的目录,美术风格文件一般以.pt结尾,大小在几十K左右;
  • extensions:存放扩展插件的目录,我们下载的WebUI的插件就放在这个目录里,WebUI启动时会自动读取插件,插件目录都是git库,可以直接通过git更新;
  • extensions-builtin:存放WebUI内置的扩展;
  • models/hypernetworks:存放风格化文件的目录,风格化文件是配合Prompt使用的,以使AI会出对应风格的图片,风格化文件也以.pt结尾,大小在几百MB左右;
  • models/Lora:存放Lora的文件的目录,Lora文件是用来调整模型的,可以重映射模型文件的Prompt映射,使AI在相应的提示词下按照Lora的样式绘制,Lora文件一般以.safetensors结尾,大小在几百MB左右;
  • models/Stable-diffusion:存放模型的文件的目录,AI绘画时的采样基本从这个文件里采,影响图片的整体样式与画风,一般以.ckpt或.safetensors结尾,大小在几个G左右;
  • models/VAE:存放VAE文件的目录,VAE文件会影响图片整体的色调,如在刚开始玩WebUI时画出的图都比较灰,就是因为WebUI默认没有为我们设置VAE导致的,VAE文件一般以.ckpt或.vae.pt结尾,大小在几百MB或几个G不等;
  • outputs/extras-images:AI放大的原图的默认保存路径;
  • outputs/img2img-grids:批量图生图时的缩略图原图的默认保存路径;
  • outputs/img2img-images:图生图的原图的默认保存路径;
  • outputs/txt2img-grids:批量文生图时的缩略图原图的默认保存路径;
  • outputs/txt2img-images:文生图的原图的默认保存路径;

这些路径我们是可以在WebUI的设置界面修改成自定义路径的。

  • scripts:存放第三方脚本的目录;
  • venv:这个文件夹是WebUI首次运行时配置运行环境自己创建的,出现运行环境的问题时,可以删掉它让WebUI重新生成。
  • repositories: 启动后载入python模块代码,会影响是用gpu还是cpu,stablediffusion,taming-transfomers,stable-diffusion,k-diffusion-sd,CodeFormer,BLIP
  • style.csv 存储当前Prompt和Nagetive prompt的提示词作为提示词模板,目前WebUI没有提供在UI中删除提示词模板的功能,想要删除不需要的提示词模板,我们需要通过修改styles.csv文件

拉取cpu版stable-diffusion-webui

拉取cpu版stable-diffusion-webui
cd /host && git clone https://github.com/openvinotoolkit/stable-diffusion-webui.git ./stable-diffusion-webui-cpu

cpu版和gpu版主要差异文件

/modules/launch_utils.py
/requirements.txt
/requirements_versions.txt
/scripts/openvino_accelerate.py

创建启动变量及目录

h_dir=/host # host dir
h_mdir=/host/models # host models dir
c_dir=/workspace/stable-diffusion-webui # container dir
c_mdir=/workspace/stable-diffusion-webui/models # container dir

#mkdir -p ${h_dir}/{localizations,configs,config_states,outputs,embeddings,extensions,extensions-builtin,scripts,repositories}
#mkdir -p ${h_mdir}/{Stable-diffusion,hypernetworks,ControlNet,Lora,VAE,VAE-approx}
cd $h_mdir

cat >> /etc/profile <<EOF
export h_dir=/host
export h_mdir=/host/models # host models dir
export c_dir=/workspace/stable-diffusion-webui # container dir
export c_mdir=/workspace/stable-diffusion-webui/models # container dir
EOF

数据持久化

#先临时启动
docker run -itd --network=host --name=sd
-v /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime \
-p 7860:7860 egs-registry.cn-hangzhou.cr.aliyuncs.com/egs/sd-webui:4.3.5-full-pytorch2.1.2-ubuntu22.04 bash

#复制容器内已存在文件到宿主机
cdirname='localizations configs outputs embeddings extensions extensions-builtin scripts'  
for cname in $cdirname; do echo ${c_dir}/${cname}; docker cp sd:${c_dir}/${cname} ${h_dir}/; done
docker cp sd:${c_dir}/webui-user.sh .

docker exec sd ls models/Stable-diffusion

docker stop sd
docker rm sd

ls ${h_dir}/models/Stable-diffusion
anything-v5-PrtRE.safetensors  'Put Stable Diffusion checkpoints here.txt'

# 复制python包 8.4G
docker cp sd:/root/miniconda3/lib/python3.10/site-packages /host/

# 复制大模型
mv /host/v1-5-pruned-emaonly.safetensors  /host/models/Stable-diffusion

# 复制出config.json
docker cp sd:/workspace/stable-diffusion-webui/config.json .

准备start.sh
vi start.sh
source ./webui-user.sh
python -u ./launch.py --listen --port 5001  --skip-install

启动容器

docker run -itd --network=host --name=sd \
-e COMMANDLINE_ARGS='--use-cpu all --skip-torch-cuda-test --precision full --no-half --no-half-vae  --api' \
-v /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime \
-v ${h_dir}/site-packages:/root/miniconda3/lib/python3.10/site-packages \
-v ${h_dir}/stable-diffusion-webui-cpu:/workspace/stable-diffusion-webui \
-v ${h_mdir}/Stable-diffusion/:${c_mdir}/Stable-diffusion/ \
-v ${h_mdir}/ControlNet/:${c_mdir}/ControlNet/ \
-v ${h_mdir}/VAE/:${c_mdir}/VAE/ \
-v ${h_mdir}/Lora/:${c_mdir}/Lora/ \
-v ${h_mdir}/hypernetworks/:${c_mdir}/hypernetworks/ \
-v ${h_dir}/style.csv:${c_dir}/style.csv \
-v ${h_dir}/outputs/:${c_dir}/outputs/ \
-v ${h_dir}/localizations/:${c_dir}/localizations/ \
-v ${h_dir}/configs/:${c_dir}/configs/ \
-v ${h_dir}/config_states/:${c_dir}/config_states/ \
-v ${h_dir}/repositories/:${c_dir}/repositories/ \
-v ${h_dir}/extensions/:${c_dir}/extensions/ \
-v ${h_dir}/extensions-builtin/:${c_dir}/extensions-builtin/ \
-v ${h_dir}/webui-user.sh:${c_dir}/webui-user.sh \
-v ${h_dir}/start.sh:${c_dir}/start.sh \
egs-registry.cn-hangzhou.cr.aliyuncs.com/egs/sd-webui:4.3.5-full-pytorch2.1.2-ubuntu22.04 bash ./start.sh

容器启动后,SD-webui服务自动启动。如果需要自定义服务启动命令或者端口,请参照下列命令进行修改:

docker exec -it sd /bin/bash

gpu方式运行

python -u ./launch.py –ckpt-dir ./ckpts –listen –port 7860 –enable-insecure-extension-access –disable-safe-unpickle –api –xformers –skip-install

cpu方式运行变量,方便docker 启动时运行

cd /workspace/stable-diffusion-webui
echo ‘export COMMANDLINE_ARGS="–use-cpu all –skip-torch-cuda-test –precision full –no-half –no-half-vae"’ >> ./webui-user.sh

cpu 方式手动运行

python -u ./launch.py –listen –port 5001 –use-cpu all –skip-torch-cuda-test –precision full –no-half –no-half-vae –api –skip-install
python -u ./launch.py –listen –port 5001 –skip-install

开机启动

echo ‘docker start sd’ >> /etc/rc.local

访问

运行成功后在浏览器输入 http://ip:5001 就可以使用

控制台会输出日志

Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0]
Version: 1.6.0
Commit hash: e5a634da06c62d72dbdc764b16c65ef3408aa588
Launching Web UI with arguments: --listen --port 5001 --skip-install --use-cpu all --skip-torch-cuda-test --precision full --no-half --no-half-vae
WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:
    PyTorch 2.1.2+cu118 with CUDA 1108 (you have 2.1.0+cu121)
    Python  3.10.13 (you have 3.10.10)
  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)
  Memory-efficient attention, SwiGLU, sparse and more won't be available.
  Set XFORMERS_MORE_DETAILS=1 for more details
No module 'xformers'. Proceeding without it.
Warning: caught exception 'Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx', memory monitor disabled
Loading weights [7f96a1a9ca] from /workspace/stable-diffusion-webui/models/Stable-diffusion/anything-v5-PrtRE.safetensors
Creating model from config: /workspace/stable-diffusion-webui/configs/v1-inference.yaml
2024-05-15 15:07:04,153 - ControlNet - INFO - ControlNet UI callback registered.
Running on local URL:  http://0.0.0.0:5001

To create a public link, set `share=True` in `launch()`.
IIB Database file has been successfully backed up to the backup folder.
Startup time: 19.6s (import torch: 2.5s, import gradio: 0.8s, setup paths: 0.3s, other imports: 0.4s, load scripts: 11.3s, create ui: 1.4s, gradio launch: 2.3s, app_started_callback: 0.3s).
Loading VAE weights specified in settings: /workspace/stable-diffusion-webui/models/VAE/vae-ft-mse-840000-ema-pruned.safetensors
Applying attention optimization: InvokeAI... done.
Model loaded in 4.9s (load weights from disk: 0.1s, create model: 1.8s, apply weights to model: 1.1s, apply float(): 1.5s, load VAE: 0.2s, calculate empty prompt: 0.1s).
[W NNPACK.cpp:64] Could not initialize NNPACK! Reason: Unsupported hardware.
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [02:58<00:00,  8.94s/it]
Total progress: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [02:56<00:00,  8.83s/it]
Total progress: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [02:56<00:00,  8.65s/it]

CPU生成一张础基图3分钟左右

docker全新安装

以ubuntu:22.04 做基础镜像
docker pull ubuntu:22.04
docker images

REPOSITORY                                              TAG                                   IMAGE ID       CREATED         SIZE
ubuntu                                                  22.04                                 52882761a72a   2 weeks ago     77.9MB

进入容器

docker run -itd --network=host --name=ub \
-v /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime \
ubuntu:22.04 bash 
docker exec -it ub /bin/bash

cat /etc/issue.net 
Ubuntu 22.04.4 LTS

apt-get update
apt-get -y install --reinstall ca-certificates
cp /etc/apt/sources.list /etc/apt/sources.bak.list 

cat /etc/apt/sources.list

#阿里加速
#sed -n 's/http:\/\/.*ubuntu.com/https:\/\/mirrors.aliyun.com/p' /etc/apt/sources.list
sed -i 's/http:\/\/.*ubuntu.com/https:\/\/mirrors.aliyun.com/g' /etc/apt/sources.list

#清华加速
#echo "deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy main restricted universe multiverse\ndeb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-updates main restricted universe multiverse\ndeb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-backports main restricted universe multiverse\ndeb http://security.ubuntu.com/ubuntu/ jammy-security main restricted universe multiverse" > /etc/apt/sources.list

#工具包
apt-get update && apt-get install -y sudo net-tools inetutils-ping procps curl wget vim telnet locales git zhcon fonts-wqy-microhei fonts-wqy-zenhei xfonts-wqy lsrzsz unzip tree

#相关包
apt-get install -y mesa-utils libglib2.0-0

sed -i 's/# zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/' /etc/locale.gen && locale-gen

miniconda 安装

https://docs.anaconda.com/free/miniconda/

cd /root
mkdir -p ~/miniconda3
#wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh
wget https://repo.anaconda.com/miniconda/Miniconda3-py310_22.11.1-1-Linux-x86_64.sh -O ~/miniconda.sh
bash ~/miniconda.sh -b -u -p ~/miniconda3
rm -rf ~/miniconda.sh

~/miniconda3/bin/conda init bash
~/miniconda3/bin/conda init zsh

no change     /root/miniconda3/condabin/conda
no change     /root/miniconda3/bin/conda
no change     /root/miniconda3/bin/conda-env
no change     /root/miniconda3/bin/activate
no change     /root/miniconda3/bin/deactivate
no change     /root/miniconda3/etc/profile.d/conda.sh
no change     /root/miniconda3/etc/fish/conf.d/conda.fish
no change     /root/miniconda3/shell/condabin/Conda.psm1
no change     /root/miniconda3/shell/condabin/conda-hook.ps1
no change     /root/miniconda3/lib/python3.10/site-packages/xontrib/conda.xsh
no change     /root/miniconda3/etc/profile.d/conda.csh
modified      /root/.bashrc

#载入变量
source /root/.bashrc

(base) root@dev-ai-diffusion:~# conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
(base) root@dev-ai-diffusion:~# conda config --set show_channel_urls yes
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

conda -V
conda 22.11.1

设置不自动激活conda base 环境

再次重启终端之后,你会发现每次打开终端默认都会自动进入到miniconda的base环境中,终端中多了“base”字样。这样会拖慢终端打开速度,并且有可能干扰到其它软件的安装。要退出的话,必须每次打开终端之后先执行conda deactivate命令,让人很难受。执行如下命令,便可以解决终端每次打开都进入conda的base环境的问题
conda config –set auto_activate_base false

python –version
Python 3.10.8

创建python3.10.10

conda create -n python_3.10.10 python=3.10.10
(python_3.10.10) root@dev-ai-diffusion:~# python –version
Python 3.10.10

查看有多少个环境

conda info –envs #

# conda environments:
#
base                     /root/miniconda3
python_3.10.10        *  /root/miniconda3/envs/python_3.10.10

设定默认环境
conda config –set default_environment python_3.10.10

激活环境
conda activate python_3.10.10

退出
conda deactivate

删除环境
conda remove –name test –all

pip install –upgrade pip setuptools wheel

下载 stable-diffusion-webui 仓库
mkdir /workspace && cd /workspace
groupadd -g 1000 website && \
useradd -u 1000 -G website -s /sbin/nologin www

stable-diffusion-webui

40m左右
cpu版
git clone https://github.com/openvinotoolkit/stable-diffusion-webui.git ./stable-diffusion-webui-cpu
gpu版
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git ./stable-diffusion-webui-gpu

ln -s stable-diffusion-webui-cpu stable-diffusion-webui

然后依次下载以下仓库,并切换到合适的版本以避免可能的版本适配问题:

mkdir -p /workspace/common/repositories && cd /workspace/common/repositories

stablediffusion
git clone https://github.com/Stability-AI/stablediffusion.git ./repositories/stable-diffusion-stability-ai

taming-transformers
git clone https://github.com/CompVis/taming-transformers.git ./repositories/taming-transformers

k-diffusion
git clone https://github.com/crowsonkb/k-diffusion.git ./repositories/k-diffusion

CodeFormer
git clone https://github.com/sczhou/CodeFormer.git ./repositories/CodeFormer

BLIP
git clone https://github.com/salesforce/BLIP.git ./repositories/BLIP

generative-models
git clone https://github.com/Stability-AI/generative-models.git ./repositories/generative-models

一共758M

cd /workspace/stable-diffusion-webui/
cat requirements.txt
安装 requirements.txt 中的依赖包

首先确定torch版本和下载的url,不同平台cpu/gpu 使用下列url来确认
https://pytorch.org/get-started/locally/

pip install torch torchvision -i https://pypi.tuna.tsinghua.edu.cn/simple

cpu

pip install torch==2.1.0 torchvision==0.16.0 torchaudio –index-url https://download.pytorch.org/whl/cpu

pip install tb-nightly
pip install tb-nightly -i https://mirrors.aliyun.com/pypi/simple

pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

说明:

必须先安装 torch:因为 basicsr 的安装程序会 import torch.
安装 tb-nightly:清华源缺少这个包,但安装 basicsr 时需要它,所以先不换源把它安装上。
安装其他依赖包
pip install ftfy regex tqdm -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install git+https://github.com/openai/CLIP.git
pip install open_clip_torch xformers -i https://pypi.tuna.tsinghua.edu.cn/simple

Collecting open_clip_torch
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d9/d2/6ae2ee32d0d2ea9982774920e0ef96d439ee332f459f6d8a941149b1b4ad/open_clip_torch-2.24.0-py3-none-any.whl (1.5 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.5/1.5 MB 2.3 MB/s eta 0:00:00
Collecting xformers
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/32/e7/27003645ef99e7571fb6964cd2f39da3f1b3f3011aa00bb2d3ac9b790757/xformers-0.0.26.post1-cp310-cp310-manylinux2014_x86_64.whl (222.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 222.7/222.7 MB 2.0 MB/s eta 0:00:00
Requirement already satisfied: torch>=1.9.0 in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from open_clip_torch) (2.1.0+cpu)
Requirement already satisfied: torchvision in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from open_clip_torch) (0.16.0+cpu)
Requirement already satisfied: regex in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from open_clip_torch) (2024.5.10)
Requirement already satisfied: ftfy in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from open_clip_torch) (6.2.0)
Requirement already satisfied: tqdm in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from open_clip_torch) (4.66.4)
Collecting huggingface-hub (from open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/21/2b/516f82c5ba9beb184b24c11976be2ad5e80fb7fe6b2796c887087144445e/huggingface_hub-0.23.0-py3-none-any.whl (401 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 401.2/401.2 kB 2.6 MB/s eta 0:00:00
Collecting sentencepiece (from open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/a6/27/33019685023221ca8ed98e8ceb7ae5e166032686fa3662c68f1f1edf334e/sentencepiece-0.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.3 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.3/1.3 MB 4.5 MB/s eta 0:00:00
Requirement already satisfied: protobuf in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from open_clip_torch) (4.25.3)
Collecting timm (from open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/68/99/2018622d268f6017ddfa5ee71f070bad5d07590374793166baa102849d17/timm-0.9.16-py3-none-any.whl (2.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.2/2.2 MB 3.1 MB/s eta 0:00:00
Requirement already satisfied: numpy in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from xformers) (1.26.3)
Collecting torch>=1.9.0 (from open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/43/e5/2ddae60ae999b224aceb74490abeb885ee118227f866cb12046f0481d4c9/torch-2.3.0-cp310-cp310-manylinux1_x86_64.whl (779.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 779.1/779.1 MB 917.4 kB/s eta 0:00:00
Requirement already satisfied: filelock in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from torch>=1.9.0->open_clip_torch) (3.13.1)
Requirement already satisfied: typing-extensions>=4.8.0 in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from torch>=1.9.0->open_clip_torch) (4.9.0)
Requirement already satisfied: sympy in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from torch>=1.9.0->open_clip_torch) (1.12)
Requirement already satisfied: networkx in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from torch>=1.9.0->open_clip_torch) (3.2.1)
Requirement already satisfied: jinja2 in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from torch>=1.9.0->open_clip_torch) (3.1.3)
Requirement already satisfied: fsspec in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from torch>=1.9.0->open_clip_torch) (2024.2.0)
Collecting nvidia-cuda-nvrtc-cu12==12.1.105 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/b6/9f/c64c03f49d6fbc56196664d05dba14e3a561038a81a638eeb47f4d4cfd48/nvidia_cuda_nvrtc_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (23.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 23.7/23.7 MB 3.7 MB/s eta 0:00:00
Collecting nvidia-cuda-runtime-cu12==12.1.105 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/eb/d5/c68b1d2cdfcc59e72e8a5949a37ddb22ae6cade80cd4a57a84d4c8b55472/nvidia_cuda_runtime_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (823 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 823.6/823.6 kB 4.2 MB/s eta 0:00:00
Collecting nvidia-cuda-cupti-cu12==12.1.105 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/7e/00/6b218edd739ecfc60524e585ba8e6b00554dd908de2c9c66c1af3e44e18d/nvidia_cuda_cupti_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (14.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 14.1/14.1 MB 4.0 MB/s eta 0:00:00
Collecting nvidia-cudnn-cu12==8.9.2.26 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/ff/74/a2e2be7fb83aaedec84f391f082cf765dfb635e7caa9b49065f73e4835d8/nvidia_cudnn_cu12-8.9.2.26-py3-none-manylinux1_x86_64.whl (731.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 731.7/731.7 MB 832.3 kB/s eta 0:00:00
Collecting nvidia-cublas-cu12==12.1.3.1 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/37/6d/121efd7382d5b0284239f4ab1fc1590d86d34ed4a4a2fdb13b30ca8e5740/nvidia_cublas_cu12-12.1.3.1-py3-none-manylinux1_x86_64.whl (410.6 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 410.6/410.6 MB 1.8 MB/s eta 0:00:00
Collecting nvidia-cufft-cu12==11.0.2.54 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/86/94/eb540db023ce1d162e7bea9f8f5aa781d57c65aed513c33ee9a5123ead4d/nvidia_cufft_cu12-11.0.2.54-py3-none-manylinux1_x86_64.whl (121.6 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 121.6/121.6 MB 2.5 MB/s eta 0:00:00
Collecting nvidia-curand-cu12==10.3.2.106 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/44/31/4890b1c9abc496303412947fc7dcea3d14861720642b49e8ceed89636705/nvidia_curand_cu12-10.3.2.106-py3-none-manylinux1_x86_64.whl (56.5 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 56.5/56.5 MB 3.1 MB/s eta 0:00:00
Collecting nvidia-cusolver-cu12==11.4.5.107 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/bc/1d/8de1e5c67099015c834315e333911273a8c6aaba78923dd1d1e25fc5f217/nvidia_cusolver_cu12-11.4.5.107-py3-none-manylinux1_x86_64.whl (124.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 124.2/124.2 MB 2.3 MB/s eta 0:00:00
Collecting nvidia-cusparse-cu12==12.1.0.106 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/65/5b/cfaeebf25cd9fdec14338ccb16f6b2c4c7fa9163aefcf057d86b9cc248bb/nvidia_cusparse_cu12-12.1.0.106-py3-none-manylinux1_x86_64.whl (196.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 196.0/196.0 MB 3.4 MB/s eta 0:00:00
Collecting nvidia-nccl-cu12==2.20.5 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/4b/2a/0a131f572aa09f741c30ccd45a8e56316e8be8dfc7bc19bf0ab7cfef7b19/nvidia_nccl_cu12-2.20.5-py3-none-manylinux2014_x86_64.whl (176.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 176.2/176.2 MB 1.9 MB/s eta 0:00:00
Collecting nvidia-nvtx-cu12==12.1.105 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/da/d3/8057f0587683ed2fcd4dbfbdfdfa807b9160b809976099d36b8f60d08f03/nvidia_nvtx_cu12-12.1.105-py3-none-manylinux1_x86_64.whl (99 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 99.1/99.1 kB 1.8 MB/s eta 0:00:00
Collecting triton==2.3.0 (from torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/db/ee/8d50d44ed5b63677bb387f4ee67a7dbaaded0189b320ffe82685a6827728/triton-2.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (168.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 168.1/168.1 MB 1.8 MB/s eta 0:00:00
Collecting nvidia-nvjitlink-cu12 (from nvidia-cusolver-cu12==11.4.5.107->torch>=1.9.0->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/ff/ff/847841bacfbefc97a00036e0fce5a0f086b640756dc38caea5e1bb002655/nvidia_nvjitlink_cu12-12.4.127-py3-none-manylinux2014_x86_64.whl (21.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 21.1/21.1 MB 4.7 MB/s eta 0:00:00
Requirement already satisfied: wcwidth<0.3.0,>=0.2.12 in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from ftfy->open_clip_torch) (0.2.13)
Collecting packaging>=20.9 (from huggingface-hub->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/49/df/1fceb2f8900f8639e278b056416d49134fb8d84c5942ffaa01ad34782422/packaging-24.0-py3-none-any.whl (53 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 53.5/53.5 kB 3.6 MB/s eta 0:00:00
Collecting pyyaml>=5.1 (from huggingface-hub->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/29/61/bf33c6c85c55bc45a29eee3195848ff2d518d84735eb0e2d8cb42e0d285e/PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (705 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 705.5/705.5 kB 1.7 MB/s eta 0:00:00
Requirement already satisfied: requests in /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages (from huggingface-hub->open_clip_torch) (2.28.1)
Collecting safetensors (from timm->open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/8f/05/969e1a976b84283285181b00028cf73d78434b77a6627fc2a94194cca265/safetensors-0.4.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.2/1.2 MB 2.2 MB/s eta 0:00:00
INFO: pip is looking at multiple versions of torchvision to determine which version is compatible with other requirements. This could take a while.
Collecting torchvision (from open_clip_torch)
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d4/7e/d41b771dbffa927b9cc37372b1e18c881348cd18a0e4ad73f2c6bdf56c0e/torchvision-0.18.0-cp310-cp310-manylinux1_x86_64.whl (7.0 MB)

du -sh /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages/
5.5G

pip install -r "requirements.txt" –prefer-binary -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r "requirements_versions.txt" –prefer-binary -i https://pypi.tuna.tsinghua.edu.cn/simple

du -sh /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages/
6.6G /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages/

pip install -r repositories/CodeFormer/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r repositories/BLIP/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r repositories/k-diffusion/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r repositories/stable-diffusion-stability-ai/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

error: can’t find Rust compiler
ERROR: Failed building wheel for tokenizers
这个错误通常是由于缺少Rust编译器引起的,因为tokenizers库需要Rust编译器来构建。
apt-get install build-essential

git clone https://github.com/huggingface/tokenizers.git

安装rust

echo "export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static" >> ~/.bashrc
echo "export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup" >> ~/.bashrc
source ~/.bashrc
curl –proto ‘=https’ –tlsv1.2 -sSf https://sh.rustup.rs | sh

ust is installed now. Great!

To get started you may need to restart your current shell.
This would reload your PATH environment variable to include
Cargo's bin directory ($HOME/.cargo/bin).

To configure your current shell, you need to source
the corresponding env file under $HOME/.cargo.

This is usually done by running one of the following (note the leading DOT):
. "$HOME/.cargo/env"            # For sh/bash/zsh/ash/dash/pdksh
source "$HOME/.cargo/env.fish"  # For fish

pip install tokenizers

载入
source $HOME/.cargo/env

   SSL error: unknown error; class=Ssl (16)
  error: cargo metadata --manifest-path Cargo.toml --format-version 1 failed with code 101
  -- Output captured from stdout:

模型

下载基础模型放在 ./models/Stable-diffusion/
下载VAE模型放在 ./models/VAE/

先做一个共享目录
cd /workspace/common/
cp -ar /workspace/stable-diffusion-webui/models /workspace/common/
mv /workspace/stable-diffusion-webui/models /workspace/stable-diffusion-webui/models_org
ln -s /workspace/common/models/ /workspace/stable-diffusion-webui/models

退出docker,在宿主机复制现有模型到内部
docker cp Stable-diffusion/anything-v5-PrtRE.safetensors ub:/workspace/common/models/Stable-diffusion/

进docker
python -u ./launch.py –listen –port 5001 –use-cpu all –skip-torch-cuda-test –precision full –no-half –no-half-vae –api –skip-install

Python 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0]
Version: 1.6.0
Commit hash: e5a634da06c62d72dbdc764b16c65ef3408aa588
Launching Web UI with arguments: --listen --port 5001 --use-cpu all --skip-torch-cuda-test --precision full --no-half --no-half-vae --api
WARNING:xformers:WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:
    PyTorch 2.3.0+cu121 with CUDA 1201 (you have 2.1.0+cpu)
    Python  3.10.14 (you have 3.10.10)
  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)
  Memory-efficient attention, SwiGLU, sparse and more won't be available.
  Set XFORMERS_MORE_DETAILS=1 for more details
No module 'xformers'. Proceeding without it.
Warning: caught exception 'Torch not compiled with CUDA enabled', memory monitor disabled
Loading weights [7f96a1a9ca] from /workspace/stable-diffusion-webui-cpu/models/Stable-diffusion/anything-v5-PrtRE.safetensors
Creating model from config: /workspace/stable-diffusion-webui-cpu/configs/v1-inference.yaml
Running on local URL:  http://0.0.0.0:5001

To create a public link, set `share=True` in `launch()`.
Startup time: 5.7s (import torch: 2.4s, import gradio: 0.6s, setup paths: 0.7s, other imports: 0.3s, load scripts: 0.7s, create ui: 0.7s, gradio launch: 0.2s).
Applying attention optimization: InvokeAI... done.
Model loaded in 4.9s (load weights from disk: 0.8s, create model: 0.6s, apply weights to model: 2.7s, apply float(): 0.7s).
[W NNPACK.cpp:64] Could not initialize NNPACK! Reason: Unsupported hardware.

浏览器访问

http://127.0.0.1:5001
ersion: 1.6.0  •  python: 3.10.10  •  torch: 2.1.0+cpu  •  xformers: N/A  •  gradio: 3.41.2

报错

libGL.so.1

libGL.so.1: cannot open shared object file: No such file or directory

apt install mesa-utils

libgthread-2.0.so.0

libgthread-2.0.so.0: cannot open shared object file: No such file or directory

apt-get install libglib2.0-0

torchvision.transforms.functional_tenso

No module named ‘torchvision.transforms.functional_tensor’

pip list |grep torch

clip-anytorch             2.6.0
dctorch                   0.1.2
open-clip-torch           2.20.0
pytorch-lightning         1.9.4
torch                     2.3.0
torchaudio                2.1.0+cpu
torchdiffeq               0.2.3
torchmetrics              1.4.0
torchsde                  0.2.5
torchvision               0.18.0

重新安装支持cpu的torch版本
pip install torch==2.1.0 torchvision==0.16.0 torchaudio –index-url https://download.pytorch.org/whl/cpu

pip list |grep torch

clip-anytorch             2.6.0
dctorch                   0.1.2
open-clip-torch           2.20.0
pytorch-lightning         1.9.4
torch                     2.1.0+cpu
torchaudio                2.1.0+cpu
torchdiffeq               0.2.3
torchmetrics              1.4.0
torchsde                  0.2.5
torchvision               0.16.0+cpu

clip-vit-large-patch14

OSError: Can’t load tokenizer for ‘openai/clip-vit-large-patch14’. If you were trying to load it from ‘https://huggingface.co/models‘, make sure you don’t have a local directory with the same name. Otherwise, make sure ‘openai/clip-vit-large-patch14’ is the correct path to a directory containing all relevant files for a CLIPTokenizer tokenizer.

下载clip-vit-large-patch14 放到以下

tree /root/.cache/huggingface/hub/models--openai--clip-vit-large-patch14/
/root/.cache/huggingface/hub/models--openai--clip-vit-large-patch14/
|-- blobs
|-- refs
|   `-- main
`-- snapshots
    `-- 8d052a0f05efbaefbc9e8786ba291cfdf93e5bff
        |-- config.json
        |-- merges.txt
        |-- special_tokens_map.json
        |-- tokenizer_config.json
        `-- vocab.json

4 directories, 6 files

制作 完整版docker 镜像

docker ps

CONTAINER ID   IMAGE          COMMAND   CREATED        STATUS        PORTS     NAMES
0180e369be03   ubuntu:22.04   "bash"    19 hours ago   Up 19 hours             ub

docker commit -m "ubuntu:22.04,stable-diffusion,cpu" ub mysd:cpu

docker images

REPOSITORY                                              TAG                                   IMAGE ID       CREATED          SIZE
mysd                                                    cpu                                   93a4de4e2952   27 seconds ago   16GB

制作优化版docker 镜像

将python包和repositories 放到宿主机。
备份出repositories
docker exec -it ub ls /workspace
docker cp ub:/workspace/common/repositories /host/cpu_repositories
840M

备份出site-package

docker cp ub:/root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages/ /host/cpu_site-package
6G

进入镜像清理

docker exec -it ub bash
apt-get autoremove && apt-get clean && rm -rf /var/lib/apt/lists/*
rm -rf /root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages/
exit

镜像

docker commit -m "ubuntu:22.04,stable-diffusion,cpu" ub mysd:cpu-slim

docker images

REPOSITORY                                              TAG                                   IMAGE ID       CREATED          SIZE
mysd                                                    cpu-slim                              9e5113633411   19 seconds ago   10GB

启动文件

vi ./start.sh

/root/miniconda3/condabin/conda init  bash
conda activate python_3.10.10
export PATH="/root/miniconda3/envs/python_3.10.10/bin:$PATH"
git config --global --add safe.directory "*"
cd /workspace/stable-diffusion-webui
python -u ./launch.py --listen --port 5001 --use-cpu all --skip-torch-cuda-test --precision full --no-half --no-half-vae --api --skip-install

启动变量

h_dir=/host # host dir
h_mdir=/host/models # host models dir
c_dir=/workspace/stable-diffusion-webui # container dir
c_mdir=/workspace/stable-diffusion-webui/models # container dir

docker run -itd –network=host –name=cpusd \
-e COMMANDLINE_ARGS=’–use-cpu all –skip-torch-cuda-test –precision full –no-half –no-half-vae –api’ \
-e CONDA_DEFAULT_ENV=’python_3.10.10′ \
-v ${h_dir}/hub/:/root/.cache/huggingface/hub \
-v ${h_dir}/cpu_site-package:/root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages \
-v ${h_mdir}/:${c_mdir}/ \
-v ${h_dir}/style.csv:${c_dir}/style.csv \
-v ${h_dir}/outputs/:${c_dir}/outputs/ \
-v ${h_dir}/localizations/:${c_dir}/localizations/ \
-v ${h_dir}/configs/:${c_dir}/configs/ \
-v ${h_dir}/config_states/:${c_dir}/config_states/ \
-v ${h_dir}/cpu_repositories/:${c_dir}/repositories/ \
-v ${h_dir}/extensions/:${c_dir}/extensions/ \
-v ${h_dir}/extensions-builtin/:${c_dir}/extensions-builtin/ \
-v ${h_dir}/webui-user.sh:${c_dir}/webui-user.sh \
-v ${h_dir}/start.sh:${c_dir}/start.sh \
mysd:cpu-slim bash -c ‘source /root/.bashrc; conda init bash; conda activate python_3.10.10;conda info –envs;/workspace/stable-diffusion-webui/start.sh’

docker exec -it cpusd bash
docker logs -f cpusd

echo ‘docker start cpusd’ >> /etc/rc.local

sd-webui-bilingual-localization 双语对照翻译插件

cd /host/extensions
git clone https://github.com/journey-ad/sd-webui-bilingual-localization /host/extensions/sd-webui-bilingual-localization

settings->bilingual-localization
本地化文件 zh-Hans(stable)
同时请将"用户界面" – “本地化翻译”选项设置为“无”

保存并重启ui

制作使用dockerfile 镜像

cd /host/
从github下载准备好代码,并从zip转成tar,方便dockerfile解压
stable-diffusion-webui-cpu.tar
stable-diffusion-webui-1.6.0.tar

FROM ubuntu:22.04

LABEL maintainer="[email protected]" \
description="Ubuntu 22.04.4 LTS,miniconda3,Stable-Diffusion-webui" 

#docker build ./ --progress=plain -t sdw_cpu:1.0

ARG RUNUID="1000"
ARG RUNGID="1000"
ARG RUNUSER="www"
ARG RUNGROUP="website"
#ARG LANG="en_US.UTF-8"
ARG LANG="zh_CN.utf8"

ENV TZ=Asia/Shanghai
ENV RUNUID=${RUNUID}
ENV RUNGID=${RUNGID}
ENV RUNUSER=${RUNUSER}
ENV RUNGROUP=${RUNGROUP}
ENV LANG=${LANG}
ENV LC_ALL=${LANG}
ENV LANGUAGE=${LANG}

WORKDIR /workspace

USER root
RUN     groupadd -g $RUNUID $RUNGROUP && \
    useradd -u $RUNGID -G $RUNGROUP  -s /sbin/nologin $RUNUSER && \
    apt-get update && apt-get -y install --reinstall ca-certificates && \
    sed -i 's/http:\/\/.*ubuntu.com/https:\/\/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    apt-get update && apt-get update && apt-get install -y sudo net-tools inetutils-ping procps curl wget vim telnet locales git zhcon  \
    fonts-wqy-microhei fonts-wqy-zenhei xfonts-wqy lrzsz unzip tree mesa-utils libglib2.0-0 && \
    apt-get autoremove && apt-get clean && rm -rf /var/lib/apt/lists/*  && \
    ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && \
    sed -i 's/# zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/' /etc/locale.gen && locale-gen && \
    echo "$TZ" > /etc/timezone && echo "alias ll='ls -l'" >> /etc/profile && \
    cd /root && mkdir -p ~/miniconda3 && wget https://repo.anaconda.com/miniconda/Miniconda3-py310_22.11.1-1-Linux-x86_64.sh -O ~/miniconda.sh  && \
    bash ~/miniconda.sh -b -u -p ~/miniconda3 && ~/miniconda3/bin/conda init bash && . /root/.bashrc && \
    conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ && \
    conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ && \
    conda config --set show_channel_urls yes && conda create -n python_3.10.10 python=3.10.10 && conda activate python_3.10.10 && \
    pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
    pip install --upgrade pip setuptools wheel && \
    cd /workspace && mkdir -p /workspace/common/{repositories,models}  
    #git clone https://github.com/openvinotoolkit/stable-diffusion-webui.git ./stable-diffusion-webui-cpu 
ADD stable-diffusion-webui-cpu.tar .
ADD stable-diffusion-webui-1.6.0.tar .
RUN  ln -s  stable-diffusion-webui-cpu  stable-diffusion-webui 

WORKDIR /workspace/stable-diffusion-webui 
EXPOSE 5001

#CMD ["/opt/bin/entry_point.sh"]
CMD ["tail","-f","/dev/null"]

docker build ./ –progress=plain -t sdw_cpu:1.0
镜像可以缩到1.6G

docker run -itd --network=host --name=cpusd \
-e COMMANDLINE_ARGS='--use-cpu all --skip-torch-cuda-test --precision full --no-half --no-half-vae  --api' \
-e CONDA_DEFAULT_ENV='python_3.10.10' \
-v ${h_dir}/hub:/root/.cache/huggingface/hub \
-v ${h_dir}/cpu_site-package:/root/miniconda3/envs/python_3.10.10/lib/python3.10/site-packages \
-v ${h_mdir}/:${c_mdir}/ \
-v ${h_dir}/style.csv:${c_dir}/style.csv \
-v ${h_dir}/outputs/:${c_dir}/outputs/ \
-v ${h_dir}/localizations/:${c_dir}/localizations/ \
-v ${h_dir}/configs/:${c_dir}/configs/ \
-v ${h_dir}/config.json:${c_dir}/config.json \
-v ${h_dir}/config_states/:${c_dir}/config_states/ \
-v ${h_dir}/cpu_repositories/:${c_dir}/repositories/ \
-v ${h_dir}/extensions/:${c_dir}/extensions/ \
-v ${h_dir}/extensions-builtin/:${c_dir}/extensions-builtin/ \
-v ${h_dir}/webui-user.sh:${c_dir}/webui-user.sh \
-v ${h_dir}/start.sh:${c_dir}/start.sh \
sdw_cpu:1.0  bash  -c 'source /root/.bashrc; conda init bash; conda activate python_3.10.10;conda info --envs;/workspace/stable-diffusion-webui/start.sh'

docker exec -it cpusd bash

Posted in AIGC, 技术.

Tagged with , , , , .


JumpServer v2 v3版本单机及多可用docker Compose离线安装

JumpServer v2 v3版本单机及多可用docker Compose离线安装

JumpServer简介

JumpServer是FIT2CLOUD飞致云旗下品牌
JumpServer 开源堡垒机是一款运维安全审计系统产品,提供身份验证、授权控制、账号管理、安全审计等功能支持,帮助企业 快速构建运维安全审计能力。
JumpServer 使用 Python 开发,配备了业界领先的 Web Terminal 方案,交互界面美观、用户体验好。
JumpServer 采纳分布式架构,支持多机房跨区域部署,支持横向扩展,无资产数量及并发限制。

官方网址

https://www.jumpserver.org/

在线体验

https://demo.jumpserver.org/

当前最新版本

v3.10.7-lts
2024-03-27 10:25:04
v3.10.5-lts
2024-03-05 16:43:19
v2.28.21
2023-10-26 18:28:00
JumpServer V2版本(社区版)维护支持截止日期为2023年12月31日,JumpServer V2版本(企业版)维护支持截止日期为2025年12月31日.推荐安装v3版本。

企业版带X-Pack 增强包,按资产数包年付费

https://www.fit2cloud.com/jumpserver/enterprise.html

近期漏洞

JumpServer作业管理中文件管理批量传输功能存在不安全直接对象引用(IDOR)漏洞,CVE编号为CVE-2024-29024
JumpServer v3.0.0-v3.10.6版本
JumpServer 密码重置漏洞(CVE-2023-42820):
2.24 <= jumpserver v 2.x <= 2.28.20
jumpserver v 3.x <= 3.6.4
JumpServer 任意密码重置漏洞(CVE-2023-43650):
2.24 <= jumpserver v 2.x <= 2.28.20
jumpserver v 3.x <= 3.6.4
Jumpserver 目录遍历漏洞(CVE-2023-42819):
3.0.0 <= jumpserver <= 3.6.4
JumpServer koko 远程命令执行漏洞(CVE-2023-43651):
2.24 <= jumpserver v 2.x <= 2.28.20
jumpserver v 3.x <= 3.6.4

环境依赖

  • Linux x86_64
  • Kernel 大于 4.0
  • Python>= 3.8版本必须3.6及以上
  • mysql>=5.7 版本必须大于5.6,需要TLS/SSL
  • redis>=6 支持Sentinel,不支持Cluster,需要TLS/SSL

all-in-one 部署方式不支持 Client 相关功能, 仅支持在 纯 B/S 架构 Web 端使用

  • 外置数据库要求 MariaDB 版本大于等于 10.6;
  • 外置 Redis 要求 Redis 版本大于等于 6.2。

组件项目

项目  状态  描述
Lina    Lina release    JumpServer Web UI 项目
Luna    Luna release    JumpServer Web Terminal 项目 Lina 和 Luna 为纯静态文件,最终由 nginx 整合
KoKo    Koko release    JumpServer 字符协议 Connector 项目,替代原来 Python 版本的 Coco
koko组件实现了SSH Server 和 Web Terminal Server的组件,提高SSH和WebSocket接口,使用Paramiko和Flask开发,可以让我们在线去像xshell一样在网页上去敲命令。他是golang编程语言开发的。和之前的coco组件(py写的)相比,性能更高。

Lion    Lion release    JumpServer 图形协议 Connector 项目,依赖 Apache Guacamole
Guacamole 为 RDP 协议和 VNC 协议资产组件, 用户可以通过 Web Terminal 来连接 RDP 协议和 VNC 协议资产 (暂时只能通过 Web Terminal 来访问)

Magnus  Magnus release  JumpServer 数据库代理 Connector 项目
Clients Clients release JumpServer 客户端 项目
Installer   Installer release   JumpServer 安装包 项目

端口说明

Jumpserver 默认 Web 端口为 8080/tcp, 默认 WS 端口为 8070/tcp, 配置文件 jumpserver/config.yml
koko 默认 SSH 端口为 2222/tcp, 默认 Web Terminal 端口为 5000/tcp 配置文件在 koko/config.yml
Guacamole 默认端口为 8081/tcp, 配置文件 /config/tomcat9/conf/server.xml
Nginx 默认端口为 80/tcp
Redis 默认端口为 6379/tcp
Mysql 默认端口为 3306/tcp

安装方式

Linux部署jumpserver堡垒机及问题汇总
https://blog.csdn.net/weixin_48878440/article/details/130836286?utm_medium=distribute.pc_relevant. none-task-blog-2~default~baidujs_baidulandingword~default-1-130836286-blog-98357973.235^v43^pc_blog_bottom_relevance_base1&spm=1001.2101.3001.4242.2&utm_relevant_index=4

[快速安装]https://docs.jumpserver.org/zh/master/install/setup_by_fast/
[负载均衡安装]https://docs.jumpserver.org/zh/master/install/setup_by_lb/
[编译安装]https://docs.jumpserver.org/zh/master/dev/build/#_5

  • 方式一 标准安装分在线和离线,在线安装就是下载包后进行离线安装,
    用docker compose管理多个docker,可以集成mysql和redis,也可以支持外部mysql和redis
    安装完成后有./jmsctl.sh脚本进行控制。

  • 方式二 all-in-one的dockifle,将db以外的服务装入一个docker中,使用docker自已控制,不支持 Client 相关功能.

  • 方式三 helm方式为k8s中安装。

  • 方式四 编译安装每个组件。

使用方式一标准离线安装。
标准离线安装内置mysql
标准离线安装外置mysql

基础准备

系统准备

cat /etc/redhat-release 
Rocky Linux release 9.3 (Blue Onyx)

selinux

sestatus
cat /etc/selinux/config
sed -i '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config
setenforce 0

网卡ip

ip a

Rocky Linux9之前
文件路径:/etc/sysconfig/network-scripts/
文件名格式:ifcfg-ens33
Rocky Linux9之后
/etc/NetworkManager/system-connections/
ens33.nmconnection

cat /etc/NetworkManager/system-connections/ens3.nmconnection
systemctl status NetworkManager //查看NetworkManager状态
systemctl restart NetworkManager //开启NetworkManager

ping www.baidu.com

更改主机名

hostnamectl set-hostname jump1

配置时间和ntp

timedatectl
timedatectl set-timezone Asia/Shanghai

cat /etc/chrony.conf |grep server

路由转发和优化

modprobe br_netfilter

cat > /etc/sysctl.d/k8s.conf << EOF
net.ipv4.tcp_keepalive_time=600
net.ipv4.tcp_keepalive_intvl=30
net.ipv4.tcp_keepalive_probes=10
net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6=1
net.ipv6.conf.lo.disable_ipv6=1
net.ipv4.neigh.default.gc_stale_time=120
net.ipv4.conf.all.rp_filter=0 
net.ipv4.conf.default.rp_filter=0
net.ipv4.conf.default.arp_announce=2
net.ipv4.conf.lo.arp_announce=2
net.ipv4.conf.all.arp_announce=2
net.ipv4.ip_local_port_range= 32768 60999
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0
net.ipv4.tcp_max_tw_buckets=6000
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_synack_retries=2
net.bridge.bridge-nf-call-ip6tables=1
net.bridge.bridge-nf-call-iptables=1
net.netfilter.nf_conntrack_max=2310720
#net.netfilter.nf_conntrack_tcp_timeout_established=300
#net.netfilter.nf_conntrack_buckets=655360
net.ipv4.neigh.default.gc_thresh1=1024
net.ipv4.neigh.default.gc_thresh2=4096
net.ipv4.neigh.default.gc_thresh3=8192
net.ipv6.neigh.default.gc_thresh1=8192
net.ipv6.neigh.default.gc_thresh2=32768
net.ipv6.neigh.default.gc_thresh3=65536
net.core.netdev_max_backlog=16384

net.core.rmem_max = 16777216 
net.core.wmem_max = 16777216
net.ipv4.tcp_max_syn_backlog = 8096 
net.core.somaxconn = 32768 
fs.inotify.max_user_instances=8192 
fs.inotify.max_user_watches=524288 
fs.file-max=52706963
fs.nr_open=52706963
kernel.pid_max = 4194303
net.bridge.bridge-nf-call-arptables=1
vm.swappiness=0 
vm.overcommit_memory=1 
vm.panic_on_oom=0 
vm.max_map_count = 262144
EOF

sysctl -p
sysctl –system
sysctl -a|grep vm.max_map_count

宿主ulimit

cat /etc/security/limits.conf

cat > /etc/security/limits.d/20-nofile.conf <<EOF
root soft nofile 65535
root hard nofile 65535
* soft nofile 65535
* hard nofile 65535
EOF
cat > /etc/security/limits.d/20-nproc.conf <<EOF
*    -     nproc   65535
root soft  nproc  unlimited
root hard  nproc  unlimited
EOF
echo "ulimit -HSn 65535" >> /etc/rc.local
ulimit -a 
sysctl -p

system.conf

cat /etc/systemd/system.conf|grep DefaultLimitNOFILE

vi /etc/systemd/system.conf

DefaultLimitNOFILE=65335

或者sed替换

cat /etc/systemd/system.conf|grep DefaultLimitNOFILE

sed -n ‘s/#DefaultLimitNOFILE=/DefaultLimitNOFILE=65335/p’ /etc/systemd/system.conf

sed -i ‘s/^#DefaultLimitNOFILE=/DefaultLimitNOFILE=65335/’ /etc/systemd/system.conf

#rocky9
sed -n 's/#DefaultLimitNOFILE=1024/DefaultLimitNOFILE=65335/p' /etc/systemd/system.conf
sed -i 's/^#DefaultLimitNOFILE=1024/DefaultLimitNOFILE=65335/' /etc/systemd/system.conf
systemctl daemon-reexec

rocky9上打开加密兼容

兼容高低版本的ssh互连

update-crypto-policies --show
update-crypto-policies --set LEGACY

设置 swappiness(可选)

设置swappiness,控制运行时内存的相对权重,过多的交换空间会引起GC耗时的激增.
临时设置指令:

sysctl -w vm.swappiness=10

cat /proc/sys/vm/swappiness
永久设置指令:

echo vm.swappiness = 10 >> /etc/sysctl.conf

关闭透明大页面transparent_hugepage(可选)

临时关闭指令1:

echo never > /sys/kernel/mm/transparent_hugepage/enabled

临时关闭指令2:

echo never > /sys/kernel/mm/transparent_hugepage/defrag

永久关闭,配置信息落盘到配置文件,机器重新有效。

vi /etc/rc.d/rc.local

if test -f /sys/kernel/mm/transparent_hugepage/enabled;
then echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag;
then echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi

chmod +x /etc/rc.d/rc.local

yum

RHEL 8 / CentOS 8上的软件包管理工具 DNF(Dandified YUM)已设置为默认值。
但是,[yum]命令也作为指向[dnf]的链接而存在,因此可以以相同的用法使用[yum]或[dnf]。

# 设置镜像变量
MIRROR=mirrors.aliyun.com/rockylinux
# 执行替换
sed -i.bak \
-e "s|^mirrorlist=|#mirrorlist=|" \
-e "s|^#baseurl=|baseurl=|" \
-e "s|dl.rockylinux.org/\$contentdir|$MIRROR|" \
/etc/yum.repos.d/rocky*.repo

更新缓存

#yum makecache
#yum list
dnf makecache
dnf list

安装基码组件

dnf install -y bash-completion vim lrzsz expect net-tools nc nmap tree dos2unix iotop unzip openldap-devel 
dnf install -y wget curl telnet make gcc perl rpm-build zlib zlib-devel gcc-c++ make autoconf automake  pcre-devel pam-devel
dnf install -y gettext iptables iptables-services
dnf install -y glibc  #可选
dnf install -y openssl openssl-devel #可选

关闭自带 firewall,切换成iptables

systemctl stop firewalld
systemctl mask firewalld
systemctl disable firewalld

#显示当前 firewall状态 
systemctl status firewalld

开启iptables

#添加入开机自启
systemctl enable iptables
#启动 iptables
systemctl start iptables
#显示当前 iptables 状态
systemctl status iptables.service
#开放端口(根据自己需求删减)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

将iptables 中 reject-with icmp-host-prohibited 删除,影响mysql连接
iptables -D INPUT -j REJECT --reject-with icmp-host-prohibited
iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited

iptables -nL

#保存防火墙配置
service iptables save

#设置默认规则
#iptables -P INPUT DROP  //设置filter表INPUT默认规则是 DROP  

内网中这里不设置默认DROP,默认都充许通过。

#显示活动的服务列表
systemctl -t service

python-pip安装

可以这里手功安装也可以让脚本自动安装

python -V
Python 3.9.18

dnf install python-pip
pip -V
pip 21.2.3 from /usr/lib/python3.9/site-packages/pip (python 3.9)

ssh -V
OpenSSH_8.7p1, OpenSSL 3.0.7 1 Nov 2022

更换pip3源

mkdir ~/.pip && cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host = mirrors.aliyun.com
EOF

安装docker

cd && mkdir src && cd src

脚本安装失败

curl -fsSL https://get.docker.com -o install-docker.sh
sh install-docker.sh --dry-run --mirror Aliyun
ERROR: Unsupported distribution 'rocky'

添加docker用户和组

vi /etc/group
将docker gid指定成1000
groupadd -g 1000 docker
useradd -u 1000 -g docker -s /sbin/nologin docker

usermod -a -G docker andychu

安装yum-utils

dnf install yum-utils

添加docker仓库

dnf config-manager \
   --add-repo \
   https://download.docker.com/linux/centos/docker-ce.repo

安装最新版本的docker

#安装docker包括:docker Engine, containerd, and Docker Compose
dnf install docker-ce docker-ce-cli containerd.io docker-compose-plugin -y

配置docker-compose环境变量

echo 'export PATH="/usr/libexec/docker/cli-plugins:$PATH"' >> /etc/profile
#加载环境变量使其生效
source /etc/profile

添加软链接

ln -s /usr/libexec/docker/cli-plugins/docker-compose /usr/bin/

docker更改为国内腾讯镜像源

mkdir -p /etc/docker
cd /etc/docker
tee /etc/docker/daemon.json<<-'EOF'
{
"registry-mirrors": [
        "https://mirror.ccs.tencentyun.com"
]
}
EOF
cat /etc/docker/daemon.json

增加limit

# containerd.service
sed -i 's/LimitNOFILE=infinity/LimitNOFILE=65535/' /usr/lib/systemd/system/containerd.service
systemctl daemon-reload
systemctl restart containerd

docker服务

# 重启daemon
systemctl daemon-reload

#启动docker
systemctl start docker

#查看docker 是否启动成功
ps -ef|grep docker

#设置开机自动启动docker服务
systemctl enable docker.service

# 查看docker信息
 docker info
Client: Docker Engine - Community
 Version:    25.0.3
 Context:    default
 Debug Mode: false
 Plugins:
  buildx: Docker Buildx (Docker Inc.)
    Version:  v0.12.1
    Path:     /usr/libexec/docker/cli-plugins/docker-buildx
  compose: Docker Compose (Docker Inc.)
    Version:  v2.24.6
    Path:     /usr/libexec/docker/cli-plugins/docker-compose

验证安装

docker-compose –version
Docker Compose version v2.24.6

Docker 日志文件 /var/log/docker

下载jumpserver

自行选择安装什么版本,这里进行测试都下载。

https://github.com/jumpserver/installer
下载离线版,需注册一下用户.
https://community.fit2cloud.com/#/download/jumpserver/v2-28-21

https://community.fit2cloud.com/#/download/jumpserver/v3-10-5-lts

wget "https://cdn0-download-offline-installer.fit2cloud.com/jumpserver/jumpserver-offline-installer-v2.28.21-amd64.tar.gz" -O jumpserver-offline-installer-v2.28.21-amd64.tar.gz

wget "https://cdn0-download-offline-installer.fit2cloud.com/jumpserver/jumpserver-offline-installer-v3.10.5-amd64.tar.gz" -O jumpserver-offline-installer-v3.10.5-amd64.tar.gz
注意JumpServer v3.0.0-v3.10.6版本 含有漏洞,请使用最新版本。

jumpserver-offline-installer-v2.28.21 离线内置单机安装

解压到/opt目录下

tar zxf jumpserver-offline-installer-v2.28.21-amd64.tar.gz -C /opt/
cd /opt
ln -s jumpserver-offline-installer-v2.28.21-amd64 jumpserver
cd /opt/jumpserver-offline-installer-v2.28.21-amd64/

cat config-example.txt


# JumpServer configuration file example.
#
# 如果不了解用途可以跳过修改此配置文件, 系统会自动填入
# 完整参数文档 https://docs.jumpserver.org/zh/master/admin-guide/env/

################################## 镜像配置 ###################################
#
# 国内连接 docker.io 会超时或下载速度较慢, 开启此选项使用华为云镜像加速
# 取代旧版本 DOCKER_IMAGE_PREFIX
#
# DOCKER_IMAGE_MIRROR=1

################################## 安装配置 ###################################
#
# JumpServer 数据库持久化目录, 默认情况下录像、任务日志都在此目录
# 请根据实际情况修改, 升级时备份的数据库文件(.sql)和配置文件也会保存到该目录
#
VOLUME_DIR=/data/jumpserver

# 加密密钥, 迁移请保证 SECRET_KEY 与旧环境一致, 请勿使用特殊字符串
# (*) Warning: Keep this value secret.
# (*) 勿向任何人泄露 SECRET_KEY
#
SECRET_KEY=

# 组件向 core 注册使用的 token, 迁移请保持 BOOTSTRAP_TOKEN 与旧环境一致,
# 请勿使用特殊字符串
# (*) Warning: Keep this value secret.
# (*) 勿向任何人泄露 BOOTSTRAP_TOKEN
#
BOOTSTRAP_TOKEN=

# 日志等级 INFO, WARN, ERROR
#
LOG_LEVEL=ERROR

# JumpServer 容器使用的网段, 请勿与现有的网络冲突, 根据实际情况自行修改
#
DOCKER_SUBNET=192.168.250.0/24

# ipv6 nat, 正常情况下无需开启
# 如果宿主不支持 ipv6 开启此选项将会导致无法获取真实的客户端 ip 地址
#
USE_IPV6=0
DOCKER_SUBNET_IPV6=fc00:1010:1111:200::/64

################################# MySQL 配置 ##################################
# 外置 MySQL 需要输入正确的 MySQL 信息, 内置 MySQL 系统会自动处理
#
DB_HOST=mysql
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
DB_NAME=jumpserver

# 如果外置 MySQL 需要开启 TLS/SSL 连接, 参考 https://docs.jumpserver.org/zh/mast                                                                                                                                                             er/install/install_security/#ssl
#
# DB_USE_SSL=True

################################# Redis 配置 ##################################
# 外置 Redis 需要请输入正确的 Redis 信息, 内置 Redis 系统会自动处理
#
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=

# 如果使用外置 Redis Sentinel, 请手动填写下面内容
#
# REDIS_SENTINEL_HOSTS=mymaster/192.168.100.1:26379,192.168.100.1:26380,192.168.                                                                                                                                                             100.1:26381
# REDIS_SENTINEL_PASSWORD=your_sentinel_password
# REDIS_PASSWORD=your_redis_password
# REDIS_SENTINEL_SOCKET_TIMEOUT=5

# 如果外置 Redis 需要开启 TLS/SSL 连接, 参考 https://docs.jumpserver.org/zh/mast                                                                                                                                                             er/install/install_security/#redis-ssl
#
# REDIS_USE_SSL=True

################################## 访问配置 ###################################
# 对外提供服务端口, 如果与现有服务冲突请自行修改
# 如果不想对外提供访问可以使用 127.0.0.1:<port>, eg: 127.0.0.1:33060
#
HTTP_PORT=80
SSH_PORT=2222
MAGNUS_PORTS=30000-30100

################################# HTTPS 配置 #################################
# 参考 https://docs.jumpserver.org/zh/master/admin-guide/proxy/ 配置
#
# HTTPS_PORT=443
# SERVER_NAME=your_domain_name
# SSL_CERTIFICATE=your_cert
# SSL_CERTIFICATE_KEY=your_cert_key
#

# Nginx 文件上传下载大小限制
#
CLIENT_MAX_BODY_SIZE=4096m

################################## 组件配置 ###################################
# 组件注册使用, 默认情况下向 core 容器注册, 集群环境需要修改为集群 vip 地址
#
CORE_HOST=http://core:8080
PERIOD_TASK_ENABLED=True

# Core Session 定义,
# SESSION_COOKIE_AGE 表示闲置多少秒后 session 过期,
# SESSION_EXPIRE_AT_BROWSER_CLOSE=true 表示关闭浏览器即 session 过期
#
# SESSION_COOKIE_AGE=86400
SESSION_EXPIRE_AT_BROWSER_CLOSE=True

# Lion 开启字体平滑, 优化体验
#
JUMPSERVER_ENABLE_FONT_SMOOTHING=True

################################# XPack 配置 #################################
# XPack 包, 开源版本设置无效
#
RDP_PORT=3389

################################## 其他配置 ##################################
# 终端使用宿主 HOSTNAME 标识, 首次安装自动生成
#
SERVER_HOSTNAME=${HOSTNAME}

# 当前运行的 JumpServer 版本号, 安装和升级完成后自动生成
#
CURRENT_VERSION=

修改config.txt

安装时会自动生成配制文件到/opt/jumpserver/config/config.txt

mkdir -p /opt/jumpserver/config/
cp ./config-example.txt /opt/jumpserver/config/config.txt

修改网段,不要和现有网段冲突

  • A类地址范围:10.0.0.0—10.255.255.255,即10.0.0.0/8
  • B类地址范围:172.16.0.0—172.31.255.555,即172.16.0.0/12
  • C类地址范围:192.168.0.0—192.168.255.255,即192.168.0.0/16

vi /opt/jumpserver/config/config.txt

DOCKER_SUBNET=172.30.75.0/24
  • 大概步骤就是,先运行脚本让你选择是否使用mysql、redis外置服务器等。然后安装docker、docker-compose,+ 紧接着下载相关镜像然后部署docker-compose项目。
  • 是否配置持久化目录(默认/opt/jumpserver)
  • 是否配置支持IPV6(默认不配置)
  • 是否配置外置MySQL数据库(默认不配置,可选择外部数据库,数据库集群等)
  • 是否配置外置Redis(默认不配置,外部redis,redis主从、集群等)
  • 是否配置对外端口(默认80)

安装,版本是在 static.env 指定的

./jmsctl.sh install

1. Check Configuration File
Path to Configuration file: /opt/jumpserver/config
/opt/jumpserver/config/config.txt        [ √ ]
/opt/jumpserver/config/nginx/cert/server.crt     [ √ ]
/opt/jumpserver/config/nginx/cert/server.key     [ √ ]
complete

>>> Install and Configure JumpServer
1. Configure Private Key
SECRETE_KEY:     MTA4kDahKurQSDV4f7CV7a2NxnvyXBin2xN9oUQz1JgKCTs4
BOOTSTRAP_TOKEN: UikuHUAnia08ZKyFHT4ZccJU
complete

2. Configure Persistent Directory
Do you need custom persistent store, will use the default directory /data/jumpserver? (y/n)  (default n):

[+] Running 1/0
 ✘ Network jms_net  Error                                                                                                                                                                                                               0.0s
failed to create network jms_net: Error response from daemon: Failed to Setup IP tables: Unable to enable SKIP DNAT rule:  (iptables failed: iptables --wait -t nat -I DOCKER -i br-e252febdc69d -j RETURN: iptables: No chain/target/match by that name.

安装后mysql和redis密码会生成到config.txt

DB_USER=root
DB_PASSWORD=BMgqGBxJoIwaqqwgwLessz6kUw
REDIS_PASSWORD=P9Z3tV6WTK0il53CYRB8oAgqT0

测试连接

docker exec -it jms_mysql bash
mysql -uroot -p
BMgqGBxJoIwaqqwgwLessz6kUw
SHOW VARIABLES LIKE '%ssl%';
+---------------------+-----------------------------+
| have_openssl        | YES                         |
| have_ssl            | DISABLED                    |

管理jumpserver服务

# 启动
$ ./jmsctl.sh start

# 重启
$ ./jmsctl.sh restart

# 关闭, 不包含数据库
$ ./jmsctl.sh stop

# 关闭所有
$ ./jmsctl.sh down

# 备份数据库
$ ./jmsctl.sh backup_db

# 查看日志
$ ./jmsctl.sh tail

# 备份
$ ./jmsctl.sh backup

配置文件说明

配置文件将会放在 /opt/jumpserver/config 中
tree .

.
├── config.txt       # 主配置文件
├── mysql
│   └── my.cnf       # mysql 配置文件
|── mariadb
|   └── mariadb.cnf  # mariadb 配置文件
├── nginx            # nginx 配置文件
│   ├── cert
│   │   ├── server.crt
│   │   └── server.key
│   ├── lb_http_server.conf
│   └── lb_ssh_server.conf
├── README.md
└── redis
    └── redis.conf  # redis 配置文件

6 directories, 11 files

Web access

http://192.168.244.10:80
Default username: admin Default password: admin

SSH/SFTP access

ssh -p2222 [email protected]
sftp -P2222 [email protected]

docker ps -a

CONTAINER ID   IMAGE                        COMMAND                  CREATED          STATUS                    PORTS                                  NAMES
c0807fb55638   jumpserver/lion:v2.28.21     "./entrypoint.sh"        6 minutes ago    Up 5 minutes (healthy)    4822/tcp, 8081/tcp                     jms_lion
f387025045e3   jumpserver/koko:v2.28.21     "./entrypoint.sh"        6 minutes ago    Up 5 minutes (healthy)    0.0.0.0:2222->2222/tcp, 5000/tcp       jms_koko
baf3dff0742e   jumpserver/web:v2.28.21      "/docker-entrypoint.…"   6 minutes ago    Up 5 minutes (healthy)    0.0.0.0:80->80/tcp                     jms_web
98dc4c33df81   jumpserver/magnus:v2.28.21   "./entrypoint.sh"        6 minutes ago    Up 5 minutes (healthy)    0.0.0.0:30000-30100->30000-30100/tcp   jms_magnus
5ce9d501748b   jumpserver/core:v2.28.21     "./entrypoint.sh sta…"   6 minutes ago    Up 5 minutes (healthy)    8070/tcp, 8080/tcp                     jms_celery
a0f24cdb8f8c   jumpserver/core:v2.28.21     "./entrypoint.sh sta…"   6 minutes ago    Up 6 minutes (healthy)    8070/tcp, 8080/tcp                     jms_core
ba76aec76c38   jumpserver/redis:6.2         "docker-entrypoint.s…"   14 minutes ago   Up 14 minutes (healthy)   6379/tcp                               jms_redis
a3167ee779f6   jumpserver/mariadb:10.6      "docker-entrypoint.s…"   14 minutes ago   Up 14 minutes (healthy)   3306/tcp                               jms_mysql

systemd开机启动

vi /usr/lib/systemd/system/jms.service

[Unit]
Description=jms
After=network.target

[Service]
Type=forking
Environment="PATH=/opt/py3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/libexec/docker/cli-plugins"
ExecStart=/opt/jumpserver/jmsctl.sh start
ExecReload=/opt/jumpserver/jmsctl.sh restart
ExecStop=/opt/jumpserver/jmsctl.sh down
PrivateTmp=true

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
#启动服务
systemctl start jms.service
#设置开机自启动
systemctl enable jms.service
systemctl status jms.service
systemctl stop jms.service

失败,不能启动

systemv添加权限并设置开机自启

chmod +x /etc/rc.local
echo '/opt/jumpserver/jmsctl.sh start' >> /etc/rc.local
systemctl enable rc-local
systemctl start rc-local.service
#检查状态:
systemctl status rc-local.service
#更改自启脚本后,需要重新运行一下命令已使其生效
systemctl enable rc-local
systemctl start rc-local.service

访问地址

http://localhost
root/Pass1234
test/Pass123456

JumpServer 客户端

http://localhost/core/download/
JumpServer 客户端,目前用来唤起 特定客户端程序 连接资产, 目前仅支持 RDP SSH 客户端,Telnet 会在未来支持

=======================

jumpserver redis和mysql外部高可用安装

测试服务器

这里以四台机器进行测试
20C,8G,100G规格 rocky9.3
服务器名称   IP地址    备注
jump01      192.168.5.101   docker
jump02      192.168.5.102   docker+Sentinel+nfs
jumpdb01    192.168.5.103   Sentinel+redis副本节点+mysql master
jumpdb02    192.168.5.104   Sentinel+redis主节点+mysql slave

说明

jumpserver web 以docker方式部署在jump01和jump02,安装docker版jumperver,复制config目录,可以随时横向扩展。
数据放在jump02上通过nfs进行共享,正式使用应使用cephfs等更可靠方式。
redis使用主从2个主从节点+3个Sentinel,在jumpserver 的config中配置sentinel就行.如使用TLS验证那需要每年给全部客户端更换证书。
mysql使用主从复制,并可选配制SSL连接.

外部 redis+Sentinel 安装略过

获取Sentinel 的ip及访问密钥

mysql安装

jumpdb01+jumpdb02 上安装

添加用户

#groupadd mysql
#useradd mysql -M -g mysql -s /sbin/nologin

创建数据目录

mkdir -p /mysql/{data,tmpdir,logs}
chown -R mysql:mysql /mysql
chmod -R 775 /mysql

rpm安装 mysql-community-common-5.7.44-1

cd /root/src
wget http://mirrors.ustc.edu.cn/mysql-repo/mysql57-community-release-el7.rpm
yum -y localinstall mysql57-community-release-el7.rpm
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
yum install mysql-community-server

卸载自带的connector包

报错

file /etc/my.cnf from install of mysql-community-server-5.7.44-1.el7.x86_64 conflicts with file from package mariadb-connector-c-config-3.2.6-1.el9_0.noarch

rpm -qa | grep mariadb
mariadb-connector-c-config-3.2.6-1.el9_0.noarch
mariadb-connector-c-3.2.6-1.el9_0.x86_64

yum remove mariadb-connector-c-config-3.2.6-1.el9_0
或者
rpm -e –nodeps mariadb-connector-c-config-3.2.6-1.el9_0.noarch
rpm -e –nodeps mariadb-connector-c-3.2.6-1.el9_0.x86_64

上传本地my.cnf,这里不提供

修改其中

bind-address              = 0.0.0.0

初始化mysql

initialize-insecure的作用
initialize-insecure是MySQL安装程序的一个选项,它用于初始化MySQL数据库,使其处于可用状态。与其他初始化选项不同,initialize-insecure是一个不安全的选项,它将跳过常规的安全设置,如设置root密码和创建SSL证书。因此,只有在测试环境或临时环境中才应该使用这个选项

#mysqld --initialize-insecure --user=mysql  --datadir=/mysql/data --basedir=/usr  
mysqld --initialize --user=mysql  --datadir=/mysql/data --basedir=/usr

cat /mysql/logs/error.err|grep 'temporary password'  
SKg>2j*JhDBv

vi /usr/lib/systemd/system/mysqld.service
PIDFile=/mysql/data/mysql.pid
ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/mysql/data/mysql.pid $MYSQLD_OPTS

启动测试

更改本地root密码
新增admin远程用户
新增jumserver远程用户

mysqld &  
mysql -uroot -p  
SKg>2j*JhDBv  

set password for root@localhost = password('X1lrffa234b'); 
flush privileges;

GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY 'X1lrffa234b' WITH GRANT OPTION;
flush privileges;

create database jumpserver default charset 'utf8';
Query OK, 1 row affected (0.00 sec)

mysql> set global validate_password_policy=LOW;
Query OK, 0 rows affected (0.00 sec)

mysql> create user 'jumpserver'@'%' identified by 'fwJTx622g';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all on jumpserver.* to 'jumpserver'@'%';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

MySQL 5.7 新增默认账号 mysql.session和mysql.sys
mysql.infoschema:系统用户,管理和访问系统自带的information_schema数据库
mysql.session:mysql的插件将会使用该用户访问mysql数据库服务器。客户端不能直接使用该用户进行链接
mysql.sys:该用户避免数据库管理重命名或者删除root用户时发生的问题,客户端不能直接使用该用户进行链接
root:mysql的超级用户,用于管理mysql数据库,拥有所有权限,可执行任何操作,不建议使用该用户操作mysql数据库。

select * from sys.session\G;

启动 MySQL

systemctl daemon-reload
systemctl enable mysqld
systemctl start mysqld
systemctl stop mysqld

查看server_id,各mysql需唯一

mysql -S /mysql/data/mysql.sock -e "select @@server_id" -uroot -p
| @@server_id |
+-------------+
|         75102 |

记得修改server_id

iptables方式,根所系统中服务二选一

iptables -A INPUT -p tcp -s 192.168.5.0/24 -m multiport --dports 3306 -j ACCEPT
service iptables save

firewall 方式,根所系统中服务二选一

firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="192.168.5.0/24" port protocol="tcp" port="3306" accept"
firewall-cmd --reload

文件权限

chown mysql:mysql /etc/my.cnf

jumpdb02上安装mysql

同上,略过

jumpdb01 master上添加repl复制用户

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'g43^2rfsfRF';
FLUSH PRIVILEGES;

show processlist\G;
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 |      154 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+

jumpdb02 slave从机上配制复制

mysql -uroot -p
X1lrffa234b
# 配制复制
CHANGE MASTER TO
MASTER_HOST='192.168.5.102',
MASTER_USER='repl',
MASTER_PASSWORD='g43^2rfsfRF',
MASTER_LOG_FILE='mysql-bin.000003',
MASTER_LOG_POS=154;

# 开始复制
START SLAVE;

# 在slave上查看
show slave status\G;
 Slave_IO_State: Connecting to master
                  Master_Host: 192.168.5.102
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 154
               Relay_Log_File: relay-bin.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Connecting
            Slave_SQL_Running: Yes

SHOW PROCESSLIST;
show processlist\G;

主从复制完成

ssl主从复制查看,mysql是否支持have_ssl

SHOW VARIABLES LIKE '%ssl%';
+-------------------------------------+-----------------+
| Variable_name                       | Value           |
+-------------------------------------+-----------------+
| have_openssl                        | YES             |
| have_ssl                            | YES             |
| performance_schema_show_processlist | OFF             |
| ssl_ca                              | ca.pem          |
| ssl_capath                          |                 |
| ssl_cert                            | server-cert.pem |
| ssl_cipher                          |                 |
| ssl_crl                             |                 |
| ssl_crlpath                         |                 |
| ssl_key                             | server-key.pem  |
+-------------------------------------+-----------------+

测试ssl,可以连本机,但ssl不能连slave

mysql -h192.168.5.102 -uadmin -p
mysql -h192.168.5.103 -uadmin -p
mysql --ssl-ca=/mysql/data/ca.pem -h192.168.5.102 -uadmin -p
mysql --ssl-ca=/mysql/data/ca.pem -h192.168.5.103 -uadmin -p

查看是否是ssl连接

SHOW SESSION STATUS LIKE 'Ssl_cipher';
 \s;

在主 mysql jumpdb01 创建SSL/RSA 文件,并分发给从机

mysql_ssl_rsa_setup  --user=mysql  --basedir=/mysql/ssl

cd /mysql/data/
scp ca.pem client-cert.pem client-key.pem [email protected]:.

mysql主从增加证书路径

vi /etc/my.cnf
修改主配置文件,在[mysqld]中添加如下几项

ssl_ca=ca.pem
ssl_cert=client-cert.pem
ssl_key=client-key.pem

mysql主从复制证书并重启生效

systemctl stop mysqld

ll /root/*.pem
cp /root/*.pem /mysql/data/

systemctl start mysqld

测试复制

mysql -uroot -p
X1lrffa234b

show slave status\G;

STOP SLAVE;
show slave status\G;

         Slave_IO_State: 
            Master_Host: 192.168.5.102
            Master_User: repl
            Master_Port: 3306
          Connect_Retry: 60
        Master_Log_File: mysql-bin.000006
    Read_Master_Log_Pos: 28170819
         Relay_Log_File: relay-bin.000013
          Relay_Log_Pos: 27207
  Relay_Master_Log_File: mysql-bin.000006
       Slave_IO_Running: No
      Slave_SQL_Running: No
        Replicate_Do_DB: 

CHANGE MASTER TO
MASTER_HOST='192.168.5.102',
MASTER_USER='repl',
MASTER_PASSWORD='g43^2rfsfRF',
MASTER_LOG_FILE='mysql-bin.000006',
MASTER_LOG_POS=28170819,
master_ssl=1,
master_ssl_cert='client-cert.pem',
master_ssl_key='client-key.pem',
master_ssl_ca='ca.pem';

START SLAVE;

主从ssl复制完成

如何设置某用户使用强制使用ssl

仅做示例,这里不强制

//新建用户
mysql> grant select on *.* to 'dba'@'%' identified by 'xxx' REQUIRE SSL; 
//修改用户
mysql> ALTER USER 'dba'@'%' REQUIRE SSL; 
flush privileges;

jumpserver web 端ssl

在jumpdb01上复制mysql的ssl证书给jumpserver web端

cd /mysql/data/
scp ca.pem [email protected]:.
scp ca.pem [email protected]:.

在jump01,jump02,当前web 前端还没安装,后续操作

mv ca.pem /opt/jumpserver/config/certs/db_ca.pem

vi /opt/jumpserver/config/config.txt

# 在配置文件配置使用 DB SSL
DB_USE_SSL=True

重新启动web服务

cd /opt/jumpserver
./jmsctl.sh down
./jmsctl.sh start

完成web数据库 SSL 连接

=======

nfs 共享数据节点

在jump02 192.168.5.101 上

yum install nfs-utils rpcbind
 ```

### 启动 NFS

systemctl enable rpcbind nfs-server
systemctl start rpcbind nfs-server

mkdir /data
chmod 777 -R /data


vi /etc/exports

设置 NFS 访问权限, /data 是刚才创建的将被共享的目录, 192.168.100. 表示整个 192.168.100. 的资产都有括号里面的权限

也可以写具体的授权对象 /data 192.168.100.30(rw,sync,no_root_squash) 192.168.100.31(rw,sync,no_root_squash)

注意挂载时用192.168.5.*会报没有权限

/data 192.168.5.0/24(rw,insecure,sync,no_root_squash)

```
exportfs -a
exportfs -rv

showmount -e
Export list for jump02.c1g.test.sh.local:
/data 192.168.5.0/24
rpcinfo -p

nfs客户端

jump01 192.168.5.100 上

安装

yum -y install nfs-utils

开启服务

systemctl enable rpcbind.service
systemctl start rpcbind.service
systemctl status rpcbind.service

修改默认挂载为Soft方式

echo 'Soft=True' >> /etc/nfsmount.conf

查看

showmount -e 192.168.5.101
Export list for 192.168.5.101:
/data 192.168.5.0/24

挂载

mkdir -p /opt/jumpdata
mount -t nfs 192.168.5.101:/data /opt/jumpdata
mount -t nfs -o nolock -o tcp 192.168.5.101:/data /opt/jumpdata
ll /opt/jumpdata

# 可以写入到 /etc/fstab, 重启自动挂载. 注意: 设置后如果 nfs 损坏或者无法连接该服务器将无法启动
echo "192.168.5.101:/data /opt/jumpdata nfs defaults 0 0" >> /etc/fstab

=========

jumpserver 前端web安装

jumpserver 离线版安装

分发离线文件到各web节点

scp -P 22 -r  jumpserver-offline-installer-v3.10.5-amd64.tar.gz [email protected]:.

解压到/opt目录下

cd /root/src/
tar zxvf jumpserver-offline-installer-v3.10.5-amd64.tar.gz -C /opt/
cd /opt

ln -s jumpserver-offline-installer-v3.10.5-amd64 jumpserver
cd /opt/jumpserver-offline-installer-v3.10.5-amd64/

mkdir -p /opt/jumpserver/config/
cp ./config-example.txt /opt/jumpserver/config/config.txt

获取SECRET_KEY

很重要,记录下来,后续使用.

if [ "$SECRET_KEY" = "" ]; then SECRET_KEY=`cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 50` ; echo "SECRET_KEY=$SECRET_KEY" >> ~/.bashrc; echo $SECRET_KEY; else echo $SECRET_KEY; fi
5SV8k2BoYHGltlwJeQxMFDsQO0wFUzV2Dg33qa8N2exbpeHMuh

if [ "$BOOTSTRAP_TOKEN" = "" ]; then BOOTSTRAP_TOKEN=`cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 16`; echo "BOOTSTRAP_TOKEN=$BOOTSTRAP_TOKEN" >> ~/.bashrc; echo $BOOTSTRAP_TOKEN; else echo $BOOTSTRAP_TOKEN; fi
vBgHciALfP8dkQtU

修改jumpserver配制

修改SECRET_KEY,BOOTSTRAP_TOKEN,DOCKER_SUBNET
修改mysql及redis配制

vi /opt/jumpserver/config/config.txt

VOLUME_DIR=/opt/jumpdata
SECRET_KEY=5SV8k2BoYHGltlwJeQxMFDsQO0wFUzV2Dg33qa8N2exbpeHMuh
BOOTSTRAP_TOKEN=vBgHciALfP8dkQtU
DOCKER_SUBNET=172.30.75.0/24

DB_HOST=192.168.5.102
DB_PORT=3306
DB_USER=jumpserver
DB_PASSWORD=kx8wJTr8
DB_NAME=jumpserver

REDIS_SENTINEL_HOSTS=mymaster1/192.168.5.103:26379,192.168.5.102:26379,192.168.5.101:26379
RDIS_SENTINEL_PASSWORD=VBHMpbPXGltlwJe
REDIS_PASSWORD=VBHMpbPXGltlwJe
REDIS_SENTINEL_SOCKET_TIMEOUT=5

安装jumpser web端

注意确认安装过程中的信息

./jmsctl.sh install

django.db.utils.OperationalError: (1045, "Access denied for user 'jumpserver'@'192.168.5.100' (using password: YES)")
[ERROR] Failed to change the table structure!

重新设密码,可能密码中有$会出错

mysql -h 192.168.5.102 -uadmin -p 
X1lrffa234b
SET PASSWORD FOR 'jumpserver'@'%' = PASSWORD('fwJTx622g');
flush privileges;

注意交互输入

  File "/opt/py3/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 223, in get_connection_params
    kwargs["port"] = int(settings_dict["PORT"])
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'y'
[ERROR] Failed to change the table structure!
>>> The Installation is Complete
1. You can use the following command to start, and then visit
cd /opt/jumpserver
./jmsctl.sh start

2. Other management commands
./jmsctl.sh stop
./jmsctl.sh restart
./jmsctl.sh backup
./jmsctl.sh upgrade
For more commands, you can enter ./jmsctl.sh --help to understand

3. Web access
http://172.30.75.1:80
Default username: admin  Default password: admin

4. SSH/SFTP access
ssh -p2222 [email protected]
sftp -P2222 [email protected]

5. More information
Official Website: https://www.jumpserver.org/
Documentation: https://docs.jumpserver.org/

防火墙iptables方式

iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
iptables -A INPUT -p tcp --dport 33060 -j ACCEPT
iptables -A INPUT -p tcp --dport 33061 -j ACCEPT
service iptables save

防火墙firewall方式

firewall-cmd --permanent --zone=public --add-port=80/tcp
firewall-cmd --permanent --zone=public --add-port=443/tcp
firewall-cmd --permanent --zone=public --add-port=2222/tcp
firewall-cmd --permanent --zone=public --add-port=33060/tcp
firewall-cmd --permanent --zone=public --add-port=33061/tcp

访问密码

http://localhost

admin/Pass1234
test/Pass1234

Posted in 安全, 容器.

Tagged with , , .


JumpServer多个高危漏洞安全风险通告v3.0.0-v3.10.6

2024年3月,有用户反馈发现JumpServer开源堡垒机存在安全漏洞,并向JumpServer开源项目组进行上报。此次发现的漏洞为:

■ JumpServer作业管理中Ansible Playbook文件存在Jinja2模板代码注入导致的Celery容器远程执行漏洞,CVE编号为CVE-2024-29202。漏洞详情:https://github.com/jumpserver/jumpserver/security/advisories/GHSA-2vvr-vmvx-73ch。 13

■ JumpServer作业管理中Ansible Playbook文件存在参数验证缺陷导致的Celery容器远程执行漏洞,CVE编号为CVE-2024-29201。漏洞详情:Insecure Ansible playbook validation leads to RCE in Celery · Advisory · jumpserver/jumpserver · GitHub 5 。

■ JumpServer作业管理中Ansible Playbook文件存在用户权限未隔离的漏洞,CVE编号为CVE-2024-29020。漏洞详情:An authorized attacker can get sensitive information in playbook files when playbook_id is leaked · Advisory · jumpserver/jumpserver · GitHub 3 。

■ JumpServer作业管理中文件管理批量传输功能存在不安全直接对象引用(IDOR)漏洞,CVE编号为CVE-2024-29024。漏洞详情:https://github.com/jumpserver/jumpserver/security/advisories/GHSA-8wqm-rfc7-q27q。 4

以上漏洞影响版本为:

JumpServer v3.0.0-v3.10.6版本

安全版本为:

JumpServer版本>=v3.10.7版本

修复方案

**■ 永久修复方案:**升级JumpServer软件至上述安全版本。

**■ 临时修复方案:**关闭作业中心功能。关闭作业中心功能的具体步骤为:

以管理员身份登录至JumpServer堡垒机。依次选择“系统设置”→“功能设置”→“任务中心”,在打开的页面中关闭作业中心功能。

Posted in 安全通告.


OpenSSH ProxyCommand命令注入漏洞(CVE-2023-51385)

背景描述

OpenSSH是SSH(Secure SHell)协议的免费开源实现。OpenSSH提供了服务端后台程序和客户端工具,用来加密远程控制和文件传输过程中的数据,并由此来代替原来的类似服务。

OpenSSH发布了安全更新,修复了一个命令注入漏洞,编号命名为CVE-2023-51385。攻击者可以利用该漏洞注入恶意shell字符进行命令注入攻击。

该漏洞利用条件较为苛刻,但由于漏洞利用POC已公开,建议受影响用户及时进行修补更新,做好相关防护措施。

二、严重等级

高危

三、漏洞描述

该漏洞与配置文件ssh_config有关,攻击者可以修改配置文件中的ProxyCommand、LocalCommand、Match exec相关命令,通过%h、%p或类似的扩展标记引用主机名或用户名,在建立SSH连接时,注入恶意shell字符进行命令注入攻击。

、影响范围

OpenSSH < 9.6

五、CVE-2023-51385 验证方法:

首先需要在~/.ssh/config增加如下

host *.example.com
ProxyCommand /usr/bin/nc -X connect -x 192.0.2.0:8080 %h %p
.gitmodules文件语句中存在命令注入

url = ssh://echo helloworld > cve.txtfoo.example.com/bar
配置完成后,执行下面的指令触发

git clone https://github.com/zls1793/CVE-2023-51385_test –recurse-submodules
如果成功执行将会在CVE-2023-51385_test目录下生成cve.txt文件

六、解决方案

目前官方已修复该漏洞,受影响用户请根据自身情况尽快更新至对应的安全版本:https://www.openssh.com/openbsd.html

该漏洞具体详情可参考如下链接:

https://vin01.github.io/piptagole/ssh/security/openssh/libssh/remote-code-execution/2023/12/20/openssh-proxycommand-libssh-rce.html

Posted in 安全通告.

Tagged with .


Linux平台主流压缩工具XZ被曝后门,标记为 CVE-2024-3094

该漏洞发生在压缩软件包xz,红帽已经该漏洞标记为 CVE-2024-3094
Red Hat 警告表示:

目前的调查表明,这些软件包仅存在于 Red Hat 社区生态系统内的 Fedora 41 和 Fedora Rawhide 中,Red Hat Enterprise Linux (RHEL) 的所有版本均不受影响。
我们已经在适用于 Debian unstable(Sid)发行版的 XZ 5.6.x 版本中找到相关证据,证明存在后门,可以注入相关代码。

Debian 安全团队今天也发布公告,表示当前没有发现有稳定版 Debian 使用问题 XZ 软件包,在受影响的 Debian 测试版、不稳定版和实验版中,XZ 已被还原为上游的 5.4.5 代码。

Fedora 41 中最新版本的 xz 5.6.0/5.6.1 工具和库中包含恶意代码,可能允许未经授权的远程系统访问。
这篇文章详细的介绍了整个过程, https://boehs.org/node/everything-i-know-about-the-xz-backdoor

rocky9.3 不受影响
xz -V
xz (XZ Utils) 5.2.5
liblzma 5.2.5

参考:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-3094

Posted in 安全通告.


OpenSSH ssh-agent 客户端远程代码执行漏洞CVE-2023-38408

漏洞描述

SSH-Agent是SSH的一部分,它是一个用于管理私钥并支持公钥身份验证的程序。

用户使用 SSH-Agent 转发代理功能连接攻击者恶意服务器时,由于 SSH-Agent 未对加载的共享库进行限制,攻击者可通过将恶意共享库作为参数传递给 SSH-Agent 并通过其调用dlopen/dlclose函数加载/卸载位于用户客户端主机的共享库,实现远程代码执行。

影响范围

ssh-agent@(-∞, 9.3_p2)

openssh@(-∞, 9.3p2-1)

解决方案

为了有效解决和防范CVE-2023-38408,请遵循以下综合步骤:

首先升级到OpenSSH 9.3p2或更高版本:升级到最新版本的OpenSSH至关重要,因为它包含缓解漏洞的关键补丁。确保所有相关系统和服务器及时更新至推荐版本或更高版本。

另外采取预防措施来避免被利用:

建议在仅仅OpenSSH用于远程主机管理的机器,通过Openssh配置(sshd_config)、防火墙,安全组ACL等限制来源访问IP为白名单仅可信IP地址,同时,非必要,关闭SSH代理转发功能,禁止在有关主机启用ssh隧道等。

关闭SSH代理转发功能方法为:

配置/etc/ssh/sshd_config

AllowTcpForwarding NO

参考链接

https://www.oscs1024.com/hd/MPS-hwop-qus5

https://nvd.nist.gov/vuln/detail/CVE-2023-38408

Posted in 安全通告.

Tagged with , , .


存货重新发布inotify_rsync代码同步shell脚本

inotify_rsync代码同步shell脚本

介绍

以inotify+rsync同步discuz论坛代码shell脚本示例

项目地址
Gitee(国内): https://gitee.com/c1g/inotify_rsync
Blog: https://blog.c1gstudio.com/

软件架构

需要安装inotify,rsync 并配置好目标主机的rsync项目

优势

限制每秒同步一次,不会批量上传文件后进行海量同步。

安装部署

mkdir -p /opt/shell/rsynclog && cd /opt/shell/  
wget -O inotify.sh https://gitee.com/c1g/inotify_rsync/raw/master/inotify.sh   
chmod +x ./inotify.sh
./inotify.sh &

使用说明

默认代码目录在 /opt/htdocs/discuz/
监听 {V_WATCH} 和 {V_WATCH2} 目录, 每秒只传输一次
注意:{V_RSYNC_DELETE}请谨慎操作,会删除不一致文件
如需半自动同步那就从监听中移除 {V_WATCH}
手动同步

 touch ${V_WATCH2}/syncbbs

开机启动

echo "cd /opt/shell && /opt/shell/inotify.sh &" >> /etc/rc.local

运行

 cd /opt/shell && /opt/shell/inotify.sh &

关闭可以直接杀

 pkill inotify

Posted in shell.

Tagged with , , .


存货重新发布php后门查找自动版

php后门查找自动版

介绍

跟据样本及关键字定时查找php后门自动版,适合小网站运行。
首次运行会跟据当前web目录产生初始样本库,以后每次运行都会和初始库比对一次。
如果查找出文件中含有eval,shell_exec,unserialize,$_FILES等可利用的词时就会发送通知邮件。
如更新了代码或确认代码没问题可以运行./find_trojan_auto.sh buildorg 重新产生样本库。


项目地址

Gitee(国内): https://gitee.com/c1g/find_trojan_auto
Blog: https://blog.c1gstudio.com/

软件架构

需要diff,md5sum,mail,find等命令支持

功能

查找没有用户和组的文件
查找可能含有一句话后门的php(需人工分析)
发送运行结果通知邮件
支持设定避开指定目录
第一次运行会先建立原始库之后对此进行对比(file_db_org)
删除原始库可以重新建立比对标准

安装部署

mkdir -p /opt/shell/log && cd /opt/shell/  
wget -O find_trojan_auto.sh https://gitee.com/c1g/find_trojan_auto/raw/master/find_trojan_auto.sh   
chmod +x ./find_trojan_auto.sh
#设定接收邮箱和web目录
sed -i "s/maillist=.*$/maillist='[email protected]'/" ./kickleech_auto.sh
sed -i "s/findpath=.*$/findpath='/opt/htdocs'/" ./kickleech_auto.sh
./find_trojan_auto.sh buildorg

使用说明

cd /opt/shell/
./find_trojan_auto.sh
#加入到crontab定时运行,每天6点36检查一次
crontab -e
36 6 * * * cd /opt/shell/ && /bin/sh ./find_trojan_auto.sh > /dev/null 2>&1

Posted in PHP, shell.

Tagged with , , .


存货重新发布shell反爬虫脚本手动版

kickleech反爬虫

介绍

shell反爬虫脚本手动版,分析web日志找出访问量异常高的IP。

  • 手动版反爬虫,输出ip及相关信息供反爬虫判断;
  • 运行前请确保日志临时目录V_TMPFILE存在并可读写,调用IP所在地公网接口需要curl支持
  • 支持单独白名单文件,nginx白名单文件,支持ipv4,ipv6 的/24斜线写法,不支持255.255.255.0 写法
  • 支持取日志中remote_addr或http_x_forwarded_for左一(没有则取remote_addr)为判断IP
  • 可以指定提取全部或多少条日志进行分析,排序显示单IP或IP C段大于指定阈值的IP
  • 运行结果可以输出到指定日志文件
  • 命令行支持指定WEB日志文件/日志条数/单IP阈值/IP C段阈值/显示IP数量/显示当前IP白名单
  • 可以指定是否排除蜘蛛等特定UserAgent
  • 分析后显示单IP请求数/页面分布/HTTP状态分布/抽样/IP所在地/是否(白|黑)名单中/是否正常请求

优势

  • 支持http_x_forwarded_for取IP
  • 支持IPV6地址
  • 支持IPC段统计
  • 支持IP黑白名单

项目地址

安装部署

kickleech手动版

wget -O kickleech_manual.sh https://gitee.com/c1g/kickleech/raw/master/kickleech/kickleech_manual.sh
chmod +x ./kickleech_manual.sh
#脚本会自动创建临时目录和日志目录,也可以手动创建
mkdir -p /opt/nginx/logs/
mkdir ./log

./kickleech_manual.sh

使用说明

Example: ./kickleech_manual.sh -f /var/log/nginx/access.log -n 500000 -t 1000 -c 3000 -m 100 -s -i

OPTION:
-f apache log file,default=/var/log/nginx/access.log
-n output the last K lines {full|500000},default=full
-t threshold for the number of requests from same IP address,default=1000
-c threshold for the number of requests from same class C IP address,default=3000
-m show number of IP,default=100
-s show IP allow list
-i show IP location
-v show this information
RESULT:
IP Count: ./log/kickleech_manual_ip_count.log
Class C IP Count: ./log/kickleech_manual_ipc_count.log
IP Detail: ./log/kickleech_manual_ip_info.log
IP Result: ./log/kickleech_manual_ip_bad.log

也可以直接编辑脚本将常用参数写在变量里。  

示例

./kickleech_manual.sh -f /var/log/nginx/bbs.c1gstudio.com.log -n 50000 -t 100 -c 300 -m 100 -s -i

=====start:20230706 18:04:46=====
LOAD nginx safe ip
SAFE IP:
127.0.0.1/32 192.168.0.0/24
LINE number:50000
364 64.62.252.163
241 173.208.200.2
139 182.148.222.121
115 110.188.45.251
101 183.146.253.6
KICKLEECH BAD 64.62.252.163
KICKLEECH BAD 173.208.200.2
KICKLEECH BAD 182.148.222.121
KICKLEECH BAD 110.188.45.251
KICKLEECH BAD 183.146.253.6
skip reload nginx!
=====end:20230706 18:04:50=====

结果查看

cat log/kickleech_manual_ip_info.log

get head line:

220.185.30.0 – – [27/Jun/2023:13:08:06 +0800] “GET /forum.php?mod=forumdisplay&fid=56&filter=digest&digest=1&typeid=25&specialtype=trade&orderby=views HTTP/1.1” 200 7925 “-” “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.873.3 Safari/537.36”

364 64.62.252.163
get status layout:5
364 200
get page layout:7
199 /space
125 /thread
40 /forum.php?mod=forumdisplay
get sample:3
64.62.252.163 – – [27/Jun/2023:13:08:16 +0800] “GET /space-uid-735.html HTTP/1.1” 200 4182 “-” “The Knowledge AI” 64.62.252.163 – – [27/Jun/2023:13:08:16 +0800] “GET /space-username-a.html HTTP/1.1” 200 4203 “-” “The Knowledge AI” 64.62.252.163 – – [27/Jun/2023:13:08:17 +0800] “GET /thread-935-1-1.html HTTP/1.1” 200 4959 “-” “The Knowledge AI” get host:
Host 163.252.62.64.in-addr.arpa. not found: 3(NXDOMAIN)
get ip location:
{“ip”:”64.62.252.163″,”beginip”:”64.62.244.152″,”endip”:”64.62.255.255″,”country”:”美国”,”area”:”加利福尼亚州弗里蒙特市Hurricane Electric公司”}

241 173.208.200.2
get status layout:5
241 200
get page layout:7
91 /forum.php?mod=forumdisplay
38 /connect.php?mod=login
6 /forum.php?mod=viewthread
3 /forum.php?mod=post
1 /forum.php?mod=redirect
get sample:3
173.208.200.2 – – [27/Jun/2023:13:09:32 +0800] “GET /forum.php?mod=forumdisplay&fid=94&orderby=lastpost HTTP/1.1” 200 7989 “-” “Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2545.102 Safari/537.36”
173.208.200.2 – – [27/Jun/2023:13:09:34 +0800] “GET /forum.php?mod=forumdisplay&fid=34&filter=author HTTP/1.1” 200 8210 “-” “Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.1717.77 Safari/537.36”
173.208.200.2 – – [27/Jun/2023:13:09:35 +0800] “GET /forum.php?mod=forumdisplay&fid=39&filter=author HTTP/1.1” 200 8250 “-” “Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.1349.50 Safari/537.36”
get host:
2.200.208.173.in-addr.arpa domain name pointer smtp101.florybeauty.com.
get ip location:
{“ip”:”173.208.200.2″,”beginip”:”173.208.128.0″,”endip”:”173.208.255.255″,”country”:”美国”,”area”:”密苏里州堪萨斯城WholeSale互联网股份有限公司”}

目录结构

.
├── kickleech_manual.sh
├── kickleechsafeip.conf
└── log

├── kickleech_manual_ip_bad.log
├── kickleech_manual_ipc_count.log
├── kickleech_manual_ip_count.log
├── kickleech_manual_ip_info.log
└── kickleech_manual_log_2023.log

Posted in LINUX, shell.

Tagged with , , .


存货重新发布kickleech反爬虫SHELL脚本

介绍

之前写的反爬虫脚本重新整理了一下,适合小网站单机运行,有更高的需求可以自已布WAF或云防。
反爬虫自动封禁版,可以使用iptables或nginx自动封禁爬虫或攻击IP.
反爬虫手动分析版,分析显示异常ip信息。
原理是分析web日志找出访问量异常IP。

优势

  • 支持http_x_forwarded_for取IP
  • 支持iptables或nginx封禁
  • 支持IPV6地址
  • 支持IP黑白名单

项目地址

安装部署

kickleech手动版

wget -O kickleech_manual.sh https://gitee.com/c1g/kickleech/raw/master/kickleech/kickleech_manual.sh
chmod +x ./kickleech_manual.sh
#脚本会自动创建临时目录和日志目录,也可以手动创建
mkdir -p /opt/nginx/logs/
mkdir ./log

./kickleech_manual.sh

kickleech自动版

mkdir -p /opt/shell/log && cd /opt/shell
wget -O kickleech_auto.sh https://gitee.com/c1g/kickleech/raw/master/kickleech/kickleech_auto.sh
chmod +x ./kickleech_auto.sh
#脚本会自动创建临时目录和日志目录,也可以手动创建
mkdir -p /opt/nginx/logs/
./kickleech_auto.sh

#加入crontab自动运行

crontab -e
*/3 * * * * cd /opt/shell && /bin/sh ./kickleech_auto.sh > /dev/null 2>&1

Posted in LINUX, shell.

Tagged with , , .