C 语言安装

✅ 如果你是 macOS 用户
可以直接用终端里的 gcc 或 clang 编译器。

1
xcode-select --install

检查是否安装了 gcc/clang

1
2
gcc --version
clang --version

新建一个源文件
命名为 hello.c

1
2
3
4
5
6
7
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
// 单行注释
}
解释
#include <stdio.h> 这是预处理指令,告诉编译器引入标准输入输出库(Standard Input Output)
int main() 每个 C 程序必须有 main() 函数,程序从这里开始执行
printf(“Hello, World!\n”); 打印字符串到终端。\n 表示换行
return 0; 表示程序成功执行结束,返回操作系统 0

编译

1
gcc hello.c -o hello

运行

1
./hello

Python 双下划线实用方法

五个双下划线方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Fruit:
def __init__(self, *, name: str, grams: float) -> None: # 用*号强制用户必须传入name和grams
self.name = name
self.grams = grams

def __eq__(self, other: Self) -> bool:
return self.name == other.name and self.grams == other.grams
return self.__dict__ == other.__dict__

def main() -> None:
f1: Fruit = Fruit(name="Apple", grams=100.0)
f2: Fruit = Fruit(name="Orange", grams=150.0)
f3: Fruit = Fruit(name="Apple", grams=100.0)

print(f1 == f2) # False
print(f1 == f3) # False 加了__ep__就是True
# 比较类的内存地址

# __eq__方法,可以比较类的哪些部分


if __name__ == "__main__":
main()

第二种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Fruit:
def __init__(self, *, name: str, grams: float) -> None:
self.name = name
self.grams = grams

def __format__(self, format_spec: str) -> str:
match format_spec:
case 'kg':
return f'{self.grams / 1000:.2f}kg'
case _:
raise ValueError('Unknown format specifier...')

def main() -> None:
apple: Fruit = Fruit(name="Apple", grams=2500.0)
print(f'{apple:kg}')

if __name__ == "__main__":
main()

第三种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Fruit:
def __init__(self, *, name: str, grams: float) -> None:
self.name = name
self.grams = grams

def main() -> None:
d1: dict = {1:'a', 2:'b'}
d2: dict = {3:'c', 4:'d'}
print(d1 | d2) # {1:'a', 2:'b', 3:'c', 4:'d'}

s1: set = {1, 2}
s2: set = {3, 4}
print(s1 | s2) # {1, 2, 3, 4}

if __name__ == "__main__":
main()

# 使用类来实现
class Fruit:
def __init__(self, *, name: str, grams: float) -> None:
self.name = name
self.grams = grams

def __or__(self, other: Self) -> Self:
new_name: str = f'{self.name} & {other.name}'
new_grams: float = self.grams + other.grams

return Fruit(name=new_name, grams=new_grams)

def main() -> None:
apple: Fruit = Fruit(name="Apple", grams=2500.0)
orange: Fruit = Fruit(name="Orange", grams=1000.0)
banana: Fruit = Fruit(name="Banana", grams=1500.0)

combined: Fruit = apple | orange
print(combined)

if __name__ == "__main__":
main()

Python生成加密随机数

Python 生成加密随机数

当需要生成安全信息,比如令牌账户验证和密码

1
pip install secrets
1
2
3
4
import secrets

random = secrets.randbelow(100) # 0 到 100 包含两端的
print(random)
1
2
3
# 第一中方法choice方法
random_choice = secrets.choice([1,2,3,4,5])
print(random_choice)

密码生成

1
2
3
4
5
6
7
8
import secrets
import string

def generate_password(length: int):
chars: str = string.ascii_letters + string.digits + string.punctuation
password: str = ''.join(secrets.choice(chars) for _ in range(length))

print('password:', password)

通过比特位生成随机数

1
2
3
4
5
import secrets

random = secrets.randbits(16) # 0 到 2^n - 1 包含两端的

print(random)

生成令牌 tokens

1
2
3
4
5
import secrets

token = secrets.token_bytes(32) # 就会使用32字节的随机熵值
tokens = secrets.token_hex(32)
print(length(tokens))
1
2
3
4
import secrets
token = secrets.token_urlsafe(16) # token URL安全生成方法

print(f'www.website.com/{token}')

密码

1
2
3
4
5
6
7
import secrets

user_input = 'abc123'
password = 'abc123'

if secrets.compare_digest(user_input, password):
print('You are logged in')

git 常规使用

git 报错设置

全局设置

1
2
3
4
5
6
7
8
#引号部分,需要输入你注册Github的邮箱
git config --global user.email "you@example.com"
# 引号部分输入你的Github账户用户名
git config --global user.name "Mysuy"
#邮箱
git config --global user.email "15075264+mysuy@user.noreply.gitee.com"
输入完成后,再次执行命令Commit:
git commit -m "Add test file"

git 使用

1. git clone

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
git clone <仓库地址>
# 示例:
git clone https://github.com/user/project.git
# 克隆默认的远程仓库的默认分支"main"/"master"

git branch # 查看分支

git log # 项目的开发记录
# --oneline # oneline是一行显示

git checkout -b newbranch # 创建并切换到新分支
git checkout main # 切换到主分支
git merge newbranch # 合并分支
git branch -d newbranch # 删除分支

git status # 查看当前状态
# modfiles 修改的文件 Untracked files 新增的文件

git add . # 添加所有修改的文件到暂存区

git commit -m "提交信息" # 提交到本地仓库
git push -u origin newbranch # 推送到远程仓库

git pull # 拉取远程仓库的代码

Zabbix被监控端自动被采集

Zabbix 被监控端自动被采集

修改被监控端的配置文件(通常位于 /etc/zabbix/zabbix_agentd.conf):

1
2
3
Server=192.168.1.100       # 允许Server拉取数据
ServerActive=192.168.1.100 # 允许主动上报到Server
Hostname=Your_Host_Name # 关键!与Zabbix Web中的主机名一致

重启 zabbix-agent 服务

1
systemctl restart zabbix-agent

在 Zabbix Web 中添加主机:

登录 Zabbix Web → Configuration → Hosts → Create Host。

填写与配置文件一致的 Hostname。

在 Interfaces 中添加 Agent 的 IP 和端口(默认 10050)。

链接模板(如 Template OS Linux)。

检查通信:

在 Zabbix Web 中查看主机的 Availability 列(绿灯表示正常)。

通过日志排查问题:

1
tail -f /var/log/zabbix/zabbix_agentd.log

常见问题

Hostname不匹配:配置文件中的 Hostname 必须与Zabbix Web中的主机名完全一致。

防火墙/网络问题:确保10050(Agent端口)和10051(Server端口)开放。

主动模式 vs 被动模式:

  • 被动模式:Server主动拉取Agent数据(需配置 Server)。

  • 主动模式:Agent主动上报数据到Server(需配置 ServerActive)。

Python的API

Python 快速搭建 API 接口

1
pip install fastapi
1
2
3
4
5
6
7
8
9
10
from fastapi import FastAPI
import random

app = FastAPI()

@app.get('/') # 制定获取信息的路径
# 需要创建一个异步函数
async def root(): # 这是根路径,每次加载API时,这是第一个响应的
return {'example': "this is an example", 'data': 0} # 返回一个json或者字典都可以,这个包可以自动把字典转换成json

需要使用 unicorn 工具启动

1
uvicorn main:app --reload

main.py 是文件名,app 是变量名, –reload 是热更新,每次修改代码后,不需要重启服务,直接刷新页面即可Q

Python和shell处理json格式的文件

处理 json 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"rules": [
{
"id": 1,
"conditions": [
{ "name": "mode_a", "value": true },
{ "name": "user_logged_in", "value": false }
]
},
{
"id": 2,
"conditions": [
{ "name": "mode_b", "value": true }
]
}
]
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import json

json_str = " "
# 或者直接处理文件
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
data = json.loads(json_str)

# 提取所有条件里的 name
names = []
for rule in data['rules']:
for condition in rule.get('conditions', []):
names.append(condition['name'])

print("提取到的 name:", names)

🧠 小结(如何逐层取值)

从结构上讲,你需要逐层“下钻”:

  • data[“rules”] 是一个列表 ⇒ 遍历它。

  • 每个元素是个字典,里面有 “conditions” ⇒ 继续遍历这个列表。

  • 每个 condition 是个字典 ⇒ 取出 “name”。

这就是典型的 嵌套列表+字典 结构处理方式。

Shell

1
jq -r '.rules[].conditions[].name' example.json

🧱 JSON 结构图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
root
└── rules [list]
├── 0 [dict]
│ ├── id: 1
│ └── conditions [list]
│ ├── 0 [dict]
│ │ ├── name: "mode_a"
│ │ └── value: true
│ └── 1 [dict]
│ ├── name: "user_logged_in"
│ └── value: false
└── 1 [dict]
├── id: 2
└── conditions [list]
└── 0 [dict]
├── name: "mode_b"
└── value: true

Docker 用法

Docker 基础用法

拉取镜像

配置加速器

1
2
3
4
5
6
7
8
9
10
11
对于使用 upstart 的系统而言,编辑 /etc/default/docker 文件,在其中的 DOCKER_OPTS 中配置加速器地址:
DOCKER_OPTS="--registry-mirror=https://registry.docker-cn.com"

service docker restart

Ubuntu16.04+、Debian8+、CentOS7
对于使用 systemd 的系统,请在 /etc/docker/daemon.json 中写入如下内容(如果文件不存在请新建该文件):
{"registry-mirrors":["https://reg-mirror.qiniu.com/"]}

systemctl daemon-reload
systemctl restart docker

基础命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 查看本地有效镜像
docker images
docker image list
# 下载镜像不同版本(不跟版本号就是默认最新版本)
docker pull ubuntu:11
docker pull ubuntu:12.04
docker pull centos:7
# 运行
docker run -it --name 容器名 imagename /bin/bash
docker run -d 后台
docker search centos * 这种方法只能用于官方镜像库 搜索基于 centos 操作系统的镜像
# 拉取镜像
docker pull centos 注:没有加registry,默认是从docker.io/dockerhub下载的
docker pull daocloud.io/library/tomcat:7
docker pull daocloud.io/library/centos:6
# 查看镜像详细
docker inspect 镜像id/镜像名称
# 删除镜像
docker rmi daocloud.io/library/mysql
docker rmi 81debc
# 删除多个,用空格隔开
或者 docker image rm 镜像名或者镜像id
# 之查看所有镜像id
docker images -q
# 删除所有镜像
docker rmi $(docker images -q)
docker rmi `docker images -q`
docker create --name 容器名 镜像名 #创建新容器但不启动
docker start 容器名/容器ID #运行容器
docker restart 容器名/容器ID #重启容器
docker stop 容器名/容器ID #停止容器
docker kill 容器名/容器ID #强制停止容器
docker stop/kill $(docker ps -q) #停止所有运行中的容器
docker pause 容器名/容器ID #暂停容器
docker nopause 容器名/容器ID #恢复容器的运行
docker rename 旧容器名 新容器名 #修改容器名
docker stats 容器名/容器ID #实时显示容器资源使用统计信息
docker inspect 容器id/容器名 #查看本地容器详细信息
docker top 容器id/容器名 #查看容器内进程详细信息
docker cp -a 容器名:路径 本地存放位置 #从容器拷贝到本机
docker cp -a 本地文件路径 容器名:路径 #从本机拷贝到容器
docker image save <image_name>:<tag> >/to/path/<image_name>.tar.gz #导出镜像
docker image load -i /to/path/<image_name>.tar.gz #导入镜像
docker export my_container > container.tar expo # 导出容器
docker import my_v3.tar nginx/nginx:v4 # 导入容器
1
2
3
4
5
docker run -d \
--name mysql8 \
-e MYSQL_ROOT_PASSWORD=song@123 \
-p 3306:3306 \
mysql:8.0
  • -d:后台运行容器。

  • –name mysql8:容器名为 mysql8。

  • -e MYSQL_ROOT_PASSWORD=song@123:设置 root 用户密码。

  • -p 3306:3306:将宿主机 3306 端口映射到容器内的 3306 端口。

  • -v <主机路径>:<容器路径>

1
docker exec -i mysql8 mysql -uroot -pYOUR_PASSWORD < /backup.sql # 直接导入之歌数据库

Python 读取文件

一行一行的读取文件的三个方法

✅ 方法一:使用 with open() 和 for line in file(推荐)

1
2
3
with open('filename.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip()) # 去除行尾换行符
  • with 会自动关闭文件。

  • line.strip() 用于去掉开头和结尾的空格、换行。

✅ 方法二:使用 readline()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
f = open('filename.txt', 'r', encoding='utf-8')
while True:
line = f.readline()
if not line:
break
print(line.strip())
f.close()

import json

f = open('config', 'r', encoding='utf-8')
result = {}
while True:
line = f.readline()
if "=" in line:
key, value = line.split("=", 1) # 1 代表的是分割次数
value = value.strip('"').strip("'").strip("\n").strip("\\") # 用两个strip来去除两边的空格和双引号
result[key] = value
if not line:
break
# print(line.strip())
f.close() # 关闭文件是为了释放内存
result = json.dumps(result, indent=4, ensure_ascii=False)
print(result)

适合处理大文件,但要记得手动 close()。

✅ 方法三:使用 readlines()

1
2
3
4
5
with open('filename.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()

for line in lines:
print(line.strip())

⚠️ 注意:如果文件很大,占用内存会比前两种方法高。

Docker 安装

Docker 安装

配置方法

Ubuntu(使用 apt-get 进行安装)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# step 1: 安装必要的一些系统工具
sudo apt-get update
sudo apt-get install ca-certificates curl gnupg

# step 2: 信任 Docker 的 GPG 公钥
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg

# Step 3: 写入软件源信息
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu \
"$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Step 4: 安装Docker
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 安装指定版本的Docker-CE:
# Step 1: 查找Docker-CE的版本:
# apt-cache madison docker-ce
# docker-ce | 17.03.1~ce-0~ubuntu-xenial | https://mirrors.aliyun.com/docker-ce/linux/ubuntu xenial/stable amd64 Packages
# docker-ce | 17.03.0~ce-0~ubuntu-xenial | https://mirrors.aliyun.com/docker-ce/linux/ubuntu xenial/stable amd64 Packages
# Step 2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.1~ce-0~ubuntu-xenial)
# sudo apt-get -y install docker-ce=[VERSION]

CentOS (使用 yum 进行安装)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# step 1: 安装必要的一些系统工具
sudo yum install -y yum-utils

# Step 2: 添加软件源信息
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# Step 3: 安装Docker
sudo yum install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Step 4: 开启Docker服务
sudo service docker start

# 注意:
# 官方软件源默认启用了最新的软件,您可以通过编辑软件源的方式获取各个版本的软件包。例如官方并没有将测试版本的软件源置为可用,您可以通过以下方式开启。同理可以开启各种测试版本等。
# vim /etc/yum.repos.d/docker-ce.repo
# 将[docker-ce-test]下方的enabled=0修改为enabled=1
#
# 安装指定版本的Docker-CE:
# Step 1: 查找Docker-CE的版本:
# yum list docker-ce.x86_64 --showduplicates | sort -r
# Loading mirror speeds from cached hostfile
# Loaded plugins: branch, fastestmirror, langpacks
# docker-ce.x86_64 17.03.1.ce-1.el7.centos docker-ce-stable
# docker-ce.x86_64 17.03.1.ce-1.el7.centos @docker-ce-stable
# docker-ce.x86_64 17.03.0.ce-1.el7.centos docker-ce-stable
# Available Packages
# Step2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.0.ce.1-1.el7.centos)
# sudo yum -y install docker-ce-[VERSION]

安装校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
root@iZbp12adskpuoxodbkqzjfZ:$ docker version
Client:
Version: 17.03.0-ce
API version: 1.26
Go version: go1.7.5
Git commit: 3a232c8
Built: Tue Feb 28 07:52:04 2017
OS/Arch: linux/amd64

Server:
Version: 17.03.0-ce
API version: 1.26 (minimum version 1.12)
Go version: go1.7.5
Git commit: 3a232c8
Built: Tue Feb 28 07:52:04 2017
OS/Arch: linux/amd64
Experimental: false

Ubuntu清华源的安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
apt update
# 安装必要的软件包:
apt install ca-certificates curl gnupg lsb-release

# 添加 Docker 的官方 GPG 密钥:
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
# 设置稳定的软件源:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

# 添加清华源:
tee /etc/apt/sources.list.d/docker.list <<EOF
deb https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu $(lsb_release -cs) stable
EOF

apt update

# 安装 Docker CE:
apt install docker-ce docker-ce-cli containerd.io

启动 Docker 服务并设置为开机自启动:
systemctl start docker
systemctl enable docker

# 验证
docker run hello-world

如果成功输出类似 Hello from Docker! 的信息,则表示 Docker 安装成功。

MySQL 数据备份

MySQL 数据备份

备份

1
2
3
4
5
6
7
8
9
10
# 备份整个数据库
mysqldump -u 用户名 -p 数据库名 > backup.sql
# 备份多个数据库
mysqldump -u 用户名 -p --databases 数据库1 数据库2 > multi_backup.sql
# 备份所有数据库
mysqldump -u 用户名 -p --all-databases > all_backup.sql
# 备份单个表
mysqldump -u 用户名 -p 数据库名 表名 > backup.sql
# 添加其他常用参数(更完整的备份)
mysqldump -u 用户名 -p --single-transaction --quick --lock-tables=false 数据库名 > backup.sql
  • –single-transaction:适用于 InnoDB 表,确保数据一致性。

  • –quick:快速导出大数据表。

  • –lock-tables=false:避免锁表(InnoDB 不需要锁表即可保证一致性)。

使用 mysql 还原数据

1
2
3
4
5
6
7
8
9
10
# 还原到某个数据库
mysql -u 用户名 -p 数据库名 < backup.sql

# 💡 要确保数据库 mydb 事先已经存在。如果没有,你需要先创建:
mysql -u root -p -e "CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"


# 还原包含 CREATE DATABASE 的备份文件
# 如果你的备份文件里有 CREATE DATABASE(例如使用了 --databases 或 --all-databases 参数),你可以直接用
mysql -u 用户名 -p < backup.sql

Docker 容器环境

1
2
3
4
5
6
# 从容器中备份数据库:
docker exec -i 容器名 mysqldump -u用户名 -p密码 数据库名 > backup.sql

# 将备份恢复到容器中的 MySQL:
cat backup.sql | docker exec -i 容器名 mysql -u用户名 -p密码 数据库名