L B T

记 录 过 去 的 经 验

环境信息

  • centos7 3.10.0
  • kubernetes Server Version: v1.21.2
  • Helm 3.10.0
  • Rancher 2.6

安装

官方安装文档

安装 Helm

安装文档官网参考

helm 安装及使用

安装 Ingress-nginx-controller

安装文档官网参考

ingress-nginx 安装配置

添加 Helm Chart 仓库

添加最新版本,生产环境建议使用稳定版本

helm repo add rancher-latest https://releases.rancher.com/server-charts/latest

为 Rancher 创建命名空间

你需要定义一个 Kubernetes 命名空间,用于安装由 Chart 创建的资源。这个命名空间的名称为 cattle-system

kubectl create namespace cattle-system

安装 cert-manager

kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.7.1/cert-manager.crds.yaml

# 添加 Jetstack Helm 仓库
helm repo add jetstack https://charts.jetstack.io

# 更新本地 Helm Chart 仓库缓存
helm repo update

# 安装 cert-manager Helm Chart
helm install cert-manager jetstack/cert-manager \
--namespace cert-manager \
--create-namespace \
--version v1.7.1

安装完 cert-manager 后,你可以通过检查 cert-manager 命名空间中正在运行的 Pod 来验证它是否已正确部署:

$ kubectl get pods -n cert-manager
NAME READY STATUS RESTARTS AGE
cert-manager-5b97785fbd-vvscn 1/1 Running 0 77s
cert-manager-cainjector-c8657d84f-6b8qr 1/1 Running 0 77s
cert-manager-webhook-8564679744-hjgkx 1/1 Running 0 77s

通过 Helm 安装 Rancher

helm install rancher rancher-stable/rancher --namespace cattle-system \
--set hostname=rancher.my.com --set bootstrapPassword=admin \
--set ingress.ingressClassName=nginx

安装成功后,输出结果如下

NAME: rancher
LAST DEPLOYED: Wed Oct 12 10:22:25 2022
NAMESPACE: cattle-system
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
Rancher Server has been installed.

NOTE: Rancher may take several minutes to fully initialize. Please standby while Certificates are being issued, Containers are started and the Ingress rule comes up.

Check out our docs at https://rancher.com/docs/

If you provided your own bootstrap password during installation, browse to https://rancher.my.com to get started.

If this is the first time you installed Rancher, get started by running this command and clicking the URL it generates:

```
echo https://rancher.my.com/dashboard/?setup=$(kubectl get secret --namespace cattle-system bootstrap-secret -o go-template='{{.data.bootstrapPassword|base64decode}}')
```

To get just the bootstrap password on its own, run:

```
kubectl get secret --namespace cattle-system bootstrap-secret -o go-template='{{.data.bootstrapPassword|base64decode}}{{ "\n" }}'
```


Happy Containering!

根据提示,浏览器中访问 https://rancher.my.com/dashboard/?setup=admin,正常情况下,显示如下页面

根据页面提示,保持密码,登陆。

阅读全文 »

blackbox_exporter 是一个由 Prometheus 社区维护的项目,它允许用户通过 HTTP、HTTPS、DNS、TCP 和 ICMP 协议对服务进行“黑盒”方式的探测,以检测和监控网络协议的可用性和响应时间。

本文档以在 Kubernetes 中部署 blackbox_exporter 为例,演示其使用方法。

为了能够监控到 Kubernetes 集群内部的部分信息(如 api-server 的证书等),建议 参考文档为其配置 RBAC 策略 以使其能读取 kube-apiserver 相关资源,本文档中的配置示例基于此权限配置。Namespace 为 prometheus

Kubernetes 中部署 blackbox_export

创建 ConfigMap 以外部化 blackbox_export 配置

blackbox_export 基于配置文件运行,将其配置文件通过 Kubernetes 的 ConfiMap 存储,分离运行环境和配置,方便管理。

参考以下配置,创建 ConfigMap

apiVersion: v1
data:
blackbox.yml: |-
modules:
http_2xx:
prober: http
timeout: 10s
http:
preferred_ip_protocol: "ip4" ##如果http监测是使用ipv4 ,需要配置。默认使用 IPv6
tcp_connect:
prober: tcp
kind: ConfigMap
metadata:
name: blackbox-export-config
namespace: prometheus

部署 blackbox_export

参考以下内容,创建 Deployment 和 Service,在此配置中,使用上面创建的 ConfigMap 作为 blackbox_export 的配置文件

apiVersion: apps/v1
kind: Deployment
metadata:
name: prometheus-blackbox-export
namespace: prometheus
labels:
app: prometheus-blackbox-export
spec:
replicas: 1
selector:
matchLabels:
app: prometheus-blackbox-export
template:
metadata:
labels:
app: prometheus-blackbox-export
spec:
containers:
- name: prometheus-blackbox-export
image: bitnami/blackbox-exporter
args:
- "--config.file=/etc/blackbox/blackbox.yml"
ports:
- containerPort: 9115
resources:
requests:
cpu: 500m
memory: 500M
limits:
cpu: 1
memory: 1Gi
volumeMounts:
- name: blackbox-config-volume
mountPath: /etc/blackbox/
volumes:
- name: blackbox-config-volume
configMap:
defaultMode: 420
name: blackbox-export-config
---
apiVersion: v1
kind: Service
metadata:
name: blackbox-service
namespace: prometheus
spec:
ports:
- name: blackbox-port
port: 9115
protocol: TCP
targetPort: 9115
selector:
app: prometheus-blackbox-export

部署成功后,从 prometheus 的 Namespace 中测试访问 blackbox_export 的 Endpoint blackbox-service:9115,如果是在其他 Namespace,可以使用 Endpoint blackbox-service.prometheus.svc.cluster.local:9115。如果集群的域名不是 cluster.local,修改为实际值。


prometheus-7589d5bbdd-xdjwt:~# curl -v blackbox-service:9115
* Trying 10.111.137.0:9115...
* Connected to blackbox-service (10.111.137.0) port 9115 (#0)
> GET / HTTP/1.1
> Host: blackbox-service:9115
> User-Agent: curl/8.0.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html
< Date: Tue, 26 Sep 2023 09:11:25 GMT
< Content-Length: 544
<
<html>
<head><title>Blackbox Exporter</title></head>
<body>
<h1>Blackbox Exporter</h1>
<p><a href="probe?target=prometheus.io&module=http_2xx">Probe prometheus.io for http_2xx</a></p>
<p><a href="probe?target=prometheus.io&module=http_2xx&debug=true">Debug probe prometheus.io for http_2xx</a></p>
<p><a href="metrics">Metrics</a></p>
<p><a href="config">Configuration</a></p>
<h2>Recent Probes</h2>
<table border='1'><tr><th>Module</th><th>Target</th><th>Result</th><th>Debug</th></table></body>
* Connection #0 to host blackbox-service left intact
</html>

Prometheus 读取 blackbox_exporter 数据

在 Prometheus 配置中添加以下内容,使 Prometheus 抓取 black_exporter 的监控数据

- job_name: 'blackbox_http_2xx'
scrape_interval: 60s
metrics_path: /probe
params:
module: [http_2xx] # Look for a HTTP 200 response.
static_configs:
- targets:
- http://www.google.com:5000/
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: blackbox-service.prometheus.svc.cluster.local:9115

部署完成后,观察过 Prometheus 的 Target,正常情况下可以看到监控目标的状态。

阅读全文 »

在 SUSE Linux(无论是 openSUSE 还是 SUSE Linux Enterprise Server)中,可以使用 zypper 命令行工具来管理和安装软件包。

更新软件包数据库

在安装任何新的软件包之前,建议首先更新你的软件包数据库,以确保你拥有最新的软件包信息。

sudo zypper refresh

搜索软件包

如果你不确定软件包的确切名称,可以使用 zypper search 来查找它

zypper search <package-name>

安装软件包

sudo zypper install <package-name>

查询软件包信息

要查看关于特定软件包的详细信息,包括描述、版本和依赖关系等,可以使用

zypper info <package-name>

卸载软件包

sudo zypper remove <package-name>

升级系统

要升级所有已安装的软件包到其最新版本,可以使用以下命令

sudo zypper update

常用软件包安装

以下示例安装常用工具包

  • net-tools,提供 netstat 命令
  • iproute2 提供 ipss 等命令
  • iputils 提供 ping 命令
    sudo zypper refresh
    sudo zypper install net-tools
    zypper install iproute2
    sudo zypper install iputils

环境信息

  • Python 3.10
  • huaweicloudsdk 3.1.23

常用方法

华为云 Python SDK 安装方法官网说明

ECS

获取云服务器 (ECS) 实例信息

通过华为云提供的 Python SDK 获取云服务器实例信息 [1]

python
>>> from huaweicloudsdkcore.auth.credentials import BasicCredentials
>>> from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
>>> from huaweicloudsdkcore.exceptions import exceptions
>>> from huaweicloudsdkecs.v2 import *

>>> ak = 'QONOKCeljdngdsEGSAM'
>>> sk = 'uD4ndlLqP5xDGSrgRRRPJGF8hg^HGkGl2'

>>> credentials = BasicCredentials(ak, sk)

>>> client = EcsClient.new_builder().with_credentials(credentials).with_region(EcsRegion.value_of("cn-east-2")).build()

>>> request = ListServersDetailsRequest()
>>> response = client.list_servers_details(request)


response 返回一个 huaweicloudsdkecs.v2.model.list_servers_details_response.ListServersDetailsResponse 对象,其中包含了服务器数量和服务器详情列表,要转换为 Python 字典对象,可以通过以下方法

python
>>> import json

>>> server_info = json.loads(str(response))

>>> type(server_info)
<class 'dict'>

### 获取查询出的机器数量
>>> server_info['count']
2

### 云服务器列表 list[dict]
>>> server_info['servers']

### 获取云服务器的名称及 id
>>> server_info['servers'][0]['name']
>>> server_info['servers'][0]['id']

### 获取云服务器的配置规格信息
>>> server_info['servers'][0]['flavor']
{'id': 'c3.xlarge.2', 'name': 'c3.xlarge.2', 'disk': '0', 'vcpus': '4', 'ram': '8192'}

### 获取云服务器挂载的磁盘id
>>> server_info['servers'][0]['os-extended-volumes:volumes_attached']
[{'id': '1fd566f2-82bb-49d3-95d1-7452a5868f80', 'delete_on_termination': 'false', 'device': '/dev/vdb'}, {'id': '2deefa5c-e92b-4ec5-9914-10af9919c121', 'delete_on_termination': 'false', 'bootIndex': '0', 'device': '/dev/vda'}]

### 获取云服务器 IP 信息
### 首先在 'metadata' 中获取云服务器的 VPC id 信息,根据 VPC id 获取对应的 ip 信息
>>> server_info['servers'][0]['metadata']
{'lockScene': '', 'charging_mode': '1', 'vpc_id': '6827d6f5-4614-42a5-9762-15d3d173411c', 'metering.product_id': '00301-15033-0--0', 'lockSource': '', 'lockSourceId': '', 'metering.imagetype': 'gold', 'metering.order_id': 'CS23010203413KRGB', 'image_name': 'Windows Server 2016 Standard 64bit', 'metering.resourcespeccode': 'c3.xlarge.2.win', 'os_type': 'Windows', 'metering.resourcetype': '1', 'metering.image_id': 'dd714f2c-f470-43b6-afc8-34d8ec689516', 'os_bit': '64', 'EcmResStatus': '', 'lockCheckEndpoint': '', 'cascaded.instance_extrainfo': 'clock_adjustment:28800,pcibridge:1'}

>>> server_info['servers'][0]['metadata']['vpc_id']
'6827d6f5-4614-42a5-9762-15d3d173411c'

### 其中 {'OS-EXT-IPS:type': 'floating'} 表示公网 IP
>>> server_info['servers'][0]['addresses']['6827d6f5-4614-42a5-9762-15d3d173411c']
[{'version': '4', 'addr': '192.168.0.65', 'OS-EXT-IPS:type': 'fixed', 'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:00:76:2a', 'OS-EXT-IPS:port_id': 'c1ec2783-6d3c-4d8a-9c55-abb59c2c648d'}, {'version': '4', 'addr': '159.138.38.203', 'OS-EXT-IPS:type': 'floating', 'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:00:76:2a', 'OS-EXT-IPS:port_id': 'c1ec2783-6d3c-4d8a-9c55-abb59c2c648d'}]

根据云服务器 id,查询云服务器挂载的磁盘信息 [2]

python
>>> request = ListServerBlockDevicesRequest(server_id='a7dd4502-cb3e-4754-b7b7-73bcb5696a1c')

>>> response = client.list_server_block_devices(request)

>>> response
{"attachableQuantity": {"free_scsi": 58, "free_blk": 22, "free_disk": 58}, \
"volumeAttachments": [{"bootIndex": 0, "pciAddress": "0000:02:01.0", "volumeId": "2deefa5c-e92b-4ec5-9914-10af9919c121", "device": "/dev/vda", "serverId": "a7dd4502-cb3e-4754-b7b7-73bcb5696a1c", \
"id": "2deefa5c-e92b-4ec5-9914-10af9919c121", "size": 100, "bus": "virtio"}, \
{"pciAddress": "0000:02:02.0", "volumeId": "1fd566f2-82bb-49d3-95d1-7452a5868f80", \
"device": "/dev/vdb", "serverId": "a7dd4502-cb3e-4754-b7b7-73bcb5696a1c", "id": "1fd566f2-82bb-49d3-95d1-7452a5868f80", "size": 100, "bus": "virtio"}]}
阅读全文 »

Akamai CDN API 说明文档,调用 API 之前需要先根据官方文档说明 Create API Client

Python SDK 使用

根据官方文档说明安装 edgegrid-python,并配置 Create API Client Key 信息 [1]

pip install edgegrid-python

Python SDK 使用官方示例

Akamai API 列表

获取账号信息

大多数 API 使用都需要提供 groupIdaccountIdcontractIds,通过以下接口获取这些信息 [2]

python
>>> import requests
>>> from akamai.edgegrid import EdgeGridAuth, EdgeRc
>>> from urllib.parse import urljoin

>>> edgerc = EdgeRc('~/.edgerc')
>>> section = 'default'
>>> baseurl = 'https://%s' % edgerc.get(section, 'host')

>>> s = requests.Session()
>>> s.auth = EdgeGridAuth.from_edgerc(edgerc, section)

>>> result = s.get(urljoin(baseurl, '/papi/v1/groups'))

>>> result.json()
{'accountId': 'act_F-AC-488298736', 'accountName': 'Guangzhou kl Network Technology Co., Ltd', 'groups': {'items': [{'groupName': 'Guangzhou extreme-G-8HGkt-DSA', 'groupId': 'grp_186987767', 'contractIds': ['ctr_G-3JDoujhh']}]}}

如果 Property 中存在分组,每个分组都有一个独立的 groupId

阅读全文 »

环境信息

  • Centos7 5.4.212-1
  • Docker 20.10.18
  • containerd.io-1.6.8
  • kubectl-1.25.0
  • kubeadm-1.25.0
  • kubelet-1.25.0

安装 ingress-nginx controller

此文档中的配置主要针对基于部署在裸机(安装通用 Linux 发行版的物理机或者云主机系统)上的 Kebernetes 集群

wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.3.1/deploy/static/provider/cloud/deploy.yaml
mv deploy.yaml ingress-nginx-controller-v1.3.1.yaml

基于 hostNetwork 的 ingress-nginx controller

编辑 ingress-nginx-controllerDeployment 配置文件,在 Deployment 中的 .spec.template.spec 下添加字段 hostNetwork: true,以使 ingress-nginx-controller 可以使用节点的主机网络提供对外访问

阅读全文 »

环境信息

  • Centos 7

查看系统启动时间

who

查看最后一次(上次)系统启动的时间

# who -b 
system boot Dec 27 05:06

查看最后一次(上次)系统启动的时间,及运行级别

# who -r 
run-level 5 Dec 27 05:06

last

通过查看 reboot 用户的登陆记录,可以知道系统的启动时间

# last reboot
reboot system boot 3.10.0-1160.76.1 Fri Jan 13 19:20 - 15:59 (236+20:38)
reboot system boot 3.10.0-1160.76.1 Fri Jan 13 19:00 - 15:59 (236+20:58)
reboot system boot 3.10.0-1160.76.1 Tue Dec 20 11:18 - 15:59 (261+04:40)
reboot system boot 3.10.0-1160.76.1 Thu Oct 27 12:04 - 11:17 (53+23:12)
reboot system boot 3.10.0-1160.76.1 Fri Sep 16 16:26 - 11:28 (40+19:02)
reboot system boot 3.10.0-1160.76.1 Mon Aug 22 17:52 - 16:15 (24+22:22)
reboot system boot 3.10.0-1160.76.1 Mon Aug 22 17:15 - 17:51 (00:36)

分割文件

文件太大,需要分割时,可以使用以下命令

split -b 100M -d test.file
选项 说明 示例
-b, --bytes=SIZE 按照指定大小分割文件
-d, --numeric-suffixes 指定分割后的文件后缀为数字
-a, --suffix-length=N 分割后的文件后缀的长度
$ split -b 100M -d test.file
x00 x03 x06 x09 x12 x15 x18 x21 x24 x27 x30 x33
x01 x04 x07 x10 x13 x16 x19 x22 x25 x28 x31 test.file
x02 x05 x08 x11 x14 x17 x20 x23 x26 x29 x32

安装

wget https://nodejs.org/dist/latest/node-v15.12.0-linux-x64.tar.gz
tar -xf node-v15.12.0-linux-x64.tar.gz -C /usr/local
ln -s /usr/local/node-v15.12.0-linux-x64/bin/* /bin/

安装pm2

npm install pm2 -g
npm install -g pm2@3.5.1 # 安装指定版本
npm install -g pm2@latest # 安装最新版本

常见操作

安装包

npm install pm2

安装指定版本的包

npm install -g pm2@3.5.1

查看可用的安装版本

hexo 安装包为例,以下命令查看 hexo 安装包有哪些可选版本

# npm show hexo versions
[
'3.3.9', '3.4.0', '3.4.1', '3.4.2', '3.4.3',
'3.4.4', '3.5.0', '3.6.0', '3.7.0', '3.7.1',
'3.8.0', '3.9.0', '4.0.0', '4.1.0', '4.1.1',
'4.2.0', '4.2.1', '5.0.0', '5.0.1', '5.0.2',
'5.1.0', '5.1.1', '5.2.0', '5.3.0', '5.4.0',
'5.4.1', '5.4.2', '6.0.0', '6.1.0', '6.2.0',
'6.3.0', '7.0.0-rc1', '7.0.0-rc2'
]

查看已安装的包名

以下命令可显示安装的包及它们的版本

npm ls

如果要查看全局类型的包,使用 -g 选项

npm ls -g

卸载安装的包

npm uninstall package_name

卸载全局安装的包

npm uninstall package_name -g

常见错误

WARN EACCES user “root” does not have permission to access the dev dir “/root/.node-gyp/11.15.0”
ERR! stack Error: EACCES: permission denied, mkdir ‘node_modules/sqlite3/.node-gyp’

[解决方法]:

npm install --unsafe-perm

环境信息

  • Centos7

  • Python3

  • wcs-python3-sdk (5.0.35)

网宿云 python sdk 安装命令 pip3 install wcs-python3-sdk, 安装后包含 cli 工具 wcscmd

初始化配置

wcscmd --configure [--config=FILE] 

--config=FILE 配置文件存储路径,默认~/.wcscfg [1]

wcscmd 常用操作

wcscmd listbucket 
wcscmd stat wcs://BUCKET/OBJECT \# 查询文件信息
wcscmd deletePrefix wcs://BUCKET PREFIX \# 根据前缀(文件路径,必须从头开始匹配,不需要最前面的/)删除目录或文件
wcscmd put wcs://BUCKET/file file

列出所有的文件

以下命令列出所有文件列表,并写入文件中

wcscmd listall wcs://BUCKET ./temp/f

python3 sdk 操作

from wcs.commons.config import Config
from wcs.services.client import Client

config_file = "/root/.wcscfg"
cfg = Config(config_file)
cli = Client(cfg)
bucketName = "TestBucket"
buckList = cli.bucket_list(bucketName, marker='') # 列出bucket中的文件列表,每次最多获取1000个,第一页 `marker=''`, 请求第一页的响应中marker的值为新的页的marker,可通过新的marker继续发起请求

脚注

将源站的内容主动预取到 CDN 节点,用户首次访问可直接命中缓存,即提升首次访问速度,又能有效缓解源站压力。

  • 数据格式:请求和响应都支持 json/xml,xml 的参数与 json 的参数基本一致,json 的参数是驼峰分隔,xml 的参数是“-”分隔,详见示例。
  • 限制说明:每个账号的预取并发是 10,调高并发会增加回源的压力,请联系技术支持人员评估。
阅读全文 »

环境信息

  • Centos 7
  • ansible 2.9.27

Playbook 语法示例

ansible playbook 使用的是 YAML 格式的语法。

---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running
service: name=httpd state=started
handlers:
- name: restart apache
service: name=httpd state=restarted

playbook 由一个或多个 play 组成。它的内容是一个以 play 为元素的列表。以上示例仅包含一个 play

阅读全文 »

环境信息

  • Centos 7

ssh 免密登陆

在需要免密码登陆的场景下,可以配置 ssh 密钥登陆。配置步骤如下

  1. 在本地服务器上面执行命令生成密钥对
    $ ssh-keygen 
    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/testuser/.ssh/id_rsa):
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /home/testuser/.ssh/id_rsa.
    Your public key has been saved in /home/testuser/.ssh/id_rsa.pub.
    The key fingerprint is:
    SHA256:Lzvl8GbOQETBVcTf8lf0Qk9KUQAESs9h8wARud+iQrk testuser@k8s-uat-master1.148962587001
    The key's randomart image is:
    +---[RSA 2048]----+
    | .BBB*=.o+.|
    | oo= =. o o|
    | o.o .+ *.|
    | .. = =|
    | .S. . +.|
    | o...+ . o|
    | . .o*.. .|
    | E o== |
    | ..=o |
    +----[SHA256]-----+
    以上命令生成了公私密钥对,分别存储在了 /home/testuser/.ssh/id_rsa.pub/home/testuser/.ssh/id_rsa 中。
  2. 在本地服务器上面执行命令将其公钥添加到目标主机的 /home/testuser/.ssh/authorized_keys。或者手动拷贝公钥追加到目标主机的 .ssh/authorized_keys
    $ ssh-copy-id -p 30000 testuser@172.31.30.115
    /bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/testuser/.ssh/id_rsa.pub"
    The authenticity of host '[172.31.30.115]:30000 ([172.31.30.115]:30000)' can't be established.
    ECDSA key fingerprint is SHA256:vKD5th2QpWYv/hmt+180BsENDHWNcJdKiEBOH06h/K8.
    ECDSA key fingerprint is MD5:bf:8c:b9:e6:31:92:1f:a9:b6:7b:8f:50:d7:10:9e:fd.
    Are you sure you want to continue connecting (yes/no)? yes
    /bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
    /bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keystestuser@172.31.30.115's password:

    Number of key(s) added: 1

    Now try logging into the machine, with: "ssh -p '30000' 'testuser@172.31.30.115'"
    and check to make sure that only the key(s) you wanted were added.
  3. 在本地服务器上面验证可以免密登陆到目标服务器。

如果要配置双向免密,将以上步骤反过来操作一遍即可

常见配置

登录服务器,经常遇见以下提示信息,说明有主机一直在尝试暴力破解用户名密码

There were 696 failed login attempts since the last successful login.

查看登录失败的用户名和 ip 地址

$ grep "Failed password for invalid user " /var/log/secure | awk '{print $11,$13}' | sort | uniq -c | sort -k1 -n
3 wangli 47.74.0.77
3 work 47.74.0.77
3 yt 47.74.0.77
3 yx 47.74.0.77
3 yyz 47.74.0.77
3 zabbix 47.74.0.77
3 zd 47.74.0.77
3 zhangfan 47.74.0.77
3 zxy 47.74.0.77
4 client003 47.74.0.77
4 client004 47.74.0.77
4 dell 47.74.0.77
4 ftpuser 47.74.0.77
4 inspur 47.74.0.77
4 wang 47.74.0.77
5 git 47.74.0.77
5 nagios 47.74.0.77
5 testuser 47.74.0.77
6 omnisky 47.74.0.77
7 oracle 47.74.0.77
8 jenkins 47.74.0.77
10 hadoop 47.74.0.77
10 postgres 47.74.0.77
11 ubuntu 47.74.0.77
11 user 47.74.0.77
12 admin 47.74.0.77
15 test 47.74.0.77

阅读全文 »

环境信息

  • Python 3.10
  • Django 4.1

常用配置

创建项目及 app

开始使用 Django 时,需要初始化配置,执行以下命令生成初始化的工程环境 [1]

django-admin startproject mysite

创建 Project 成功后,会生成以 Project 命名的根目录(此处为 mysite),根目录只是你项目的容器, 根目录名称对 Django 没有影响,你可以将它重命名为任何你喜欢的名称。以下为目录结构 [1]

mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py

其中:

  • mysite/mysite/settings.py 为项目配置文件,包括配置 app,数据库等。

创建 App

python manage.py startapp myapp

创建 app 后,会在项目根目录下生成 app 命名的目录。创建 app 后,需要将 app 添加到项目配置文件 settings.py 中的 INSTALLED_APPS

项目配置文件 settings.py 常用配置说明

ALLOWED_HOSTS = ['*']

访问控制,默认只允许从本地访问 Django Server,如果需要远程访问,需要配置远程主机地址,* 可以配置允许任一客户端访问。

配置 mysql 数据库

要为项目配置使用 Mysql 数据库,可以使用以下配置。

settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "vb",
'USER': "root",
"PASSWORD": "dBVgcKGnn0",
'HOST': "127.0.0.1",
"PORT": '3306',
},

}

配置语言为中文

settings.py
LANGUAGE_CODE = 'zh-hans'

配置时区

settings.py
TIME_ZONE = 'Asia/Shanghai'

配置默认的登陆 url 为 Django 后台的登陆 url

如果需要限制只有登陆的用户才能访问 url。可以在视图函数中使用 login_required 装饰器

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required
def index(request):
return render(request, 'cloudclient/index.html')

使用了 login_required 装饰器后,未登录的用户会跳转到登陆页面,要配置登陆页面使用 Django Admin 的登陆 url,需要在 settings.py 中添加以下配置

settings.py
LOGIN_URL = 'admin:login'

配置登陆用户自动注销

要配置登陆用户在指定时间内未操作(发送 url 请求)后自动注销,使用以下配置

settings.py
# 设置会话的过期时间为10分钟(以秒为单位)
SESSION_COOKIE_AGE = 600 # 10分钟

# True: 用户的会话在每个请求时都会刷新会话过期时间
SESSION_SAVE_EVERY_REQUEST = True

Django 管理后台配置

  1. 创建 project 后,要使用 Django 管理后台,需要首先初始化数据库并创建 superuser
    python manage.py makemigrations
    python manage.py migrate
    python manage.py createsuperuser
  2. 为 admin 添加路由
    在工程目录中的 urls.py 文件中配置以下内容
    urls.py
    from django.contrib import admin
    from django.urls import path
    from .views import index

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    # 项目根 url 既是后台
    # path('', admin.site.urls),
    ]

    如果要在访问项目 / 时,重定向到管理后台,可以在项目的 views.py 文件中添加以下内容,将 / 重定向到 /admin/
    views.py
    from django.shortcuts import redirect

    def index(request):
    return redirect('admin/')

    访问项目 url,此时可以看到登陆后台页面。

脚注

环境信息

  • Python3.10

常用方法

删除 key

scores = {'语文': 89}
scores['数学'] = 93
scores[92] = 5.7

del scores['语文']
del scores['数学']

# 删除指定的 key,并返回 key 对应的值;如果 key 不存在,返回异常:KeyError,可查看 help(dict)
scores.pop(92)

# 删除最后一个 key-value,并以元组的形式返回 (key, value)
scores.popitem()

清空 dict

clear() 用于清空字典中所有的 key-value 对,对一个字典执行 clear() 方法之后,该字典就会变成一个空字典

更新 dict

update() 方法可使用一个字典所包含的 key-value 对来更新己有的字典。在执行 update() 方法时,如果被更新的字典中己包含对应的 key-value 对,那么原 value 会被覆盖;如果被更新的字典中不包含对应的 key-value 对,则该 key-value 对被添加进去;原来的 dict 中存在(更新中不存在)的 key-value 保持不变。

update() 方法也可以用于合并字典,如果 key 重复,会使用新字典中的值替换原来的字典中的值。更新操作不返回任何值,返回结果为 None

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

dict1.update(dict2)

print(dict1) # 输出: {'a': 1, 'b': 3, 'c': 4}

合并 dict

要将多个字典的键值合并到一个新的字典中,可以使用字典的解包方式。如果字典中有重复的 key,最终的值为最后的字典中的值

query = {'name': 'd'}
params = {'id': '65220d913a0283df8a'}
merged_dict = {**query, **params}
阅读全文 »

同一个域名使用不同的 HTTPS 重定向规则

在 Cloudflare 中,配置的规则 (比如 自动 HTPTPS 重写 功能) 对所有使用了 Cloudflare 加速的域名都生效。

此时假如有 2 个二级域名 d1.abc.comd2.abc.com,都启用了 Cloudflare 加速功能,此时开启 自动 HTPTPS 重写 功能,则使用 HTTP 协议访问,都会被重定向到 HTTPS。假如域名 d2.abc.com 不想进行 HTTPS 重定向,即使用 HTTP 访问 d2.abc.com 不重定向到 https://d2.abc.com。要实现此功能,参考以下步骤

  1. 首先在 SSL/TLS –> 边缘证书开启 自动 HTPTPS 重写 功能,关闭 始终使用 HTTPS 功能

  2. 自动 HTPTPS 重写 中配置规则,参考下图,定义规则名称,选择 自定义筛选表达式,在表达式中配置筛选条件匹配 d2.abc.com,在下面的设置中 关闭 自动 HTPTPS 重写 功能

通过以上配置即可实现,同一个域名的不同子域名有不同的重定向规则。其他类似需求也可参考此思路配置

阅读全文 »

环境信息

  • Python 3
  • Django 4

request 常用参数及方法

  • request.method : 返回当前请求的 HTTP 方法(GET、POST、PUT、DELETE 等)。

  • request.path : 返回请求的路径部分(不包括域名和查询参数)。

  • request.GET : 包含所有 GET 请求参数的字典。

  • request.GET.get('param_name') : 用于从 GET 请求中获取指定参数的值。

  • request.POST : 包含所有 POST 请求参数的字典。

  • request.POST.get('param_name') : 用于从 POST 请求中获取指定参数的值。

  • request.FILES : 包含所有上传文件的字典。

  • request.COOKIES : 包含所有请求的 Cookie 的字典。

  • request.session : 一个表示当前会话的对象,可以用于访问和存储会话数据。

  • request.user : 表示当前登录用户的对象。

  • request.body : 访问请求的主体内容(即请求的正文部分)。主体内容通常用于传输 POST 或 PUT 请求中的数据,如表单数据、JSON 数据等。

  • request.META : 包含有关请求的所有元数据的字典,如请求的 IP 地址、浏览器信息等。

  • request.is_secure() : 返回一个布尔值,表示请求是否通过 HTTPS。

  • request.is_ajax() : 返回一个布尔值,表示请求是否为 AJAX 请求。

  • request.get_full_path() : 返回包含完整路径和查询参数的字符串。

  • request.build_absolute_uri() : 根据当前请求构建完整的绝对 URL。

  • request.get_host() : 返回请求的主机部分。

  • request.get_port() : 返回请求的端口号。

  • request.get_raw_uri() : 返回原始的请求 URI。

  • request.get_signed_cookie() : 用于获取已签名的 Cookie 值。

  • request.get_host() : 返回请求的主机部分。

环境信息

  • Centos 7
  • Docker 19.03.15

docker 配置容器日志 rotate

docker daemon 方式配置容器日志 rotate

编辑 docker daemon 配置文件 /etc/docker/daemon.json (若不存在则新建),添加以下内容,用来配置 docker containers 的日志轮转

/etc/docker/daemon.json
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
}
}

重启 docker 服务生效

systemctl restart docker

根据以上配置,当容器日志大小达到 100m,即对其进行 rotate,并保留最多 3 个日志文件。

使用 OS 系统服务 logrotate 进行容器日志 rotate

Linux 系统中有专门用来做日志 rotate 的 服务 logrotate,可直接使用此服务做 log rotate

配置针对 docker 的 logrotate 配置

/etc/logrotate.d/docker
/var/lib/docker/containers/*/*.log {
daily
rotate 5
copytruncate
missingok
compress
delaycompress
maxsize 100M
minsize 1024k
}

使用 copytruncate 的方式做日志 totate 时,会先拷贝日志文件为 totate 日志文件,然后 truncate 日志,确保 totate 过程中,日志文件不变并一直保持打开状态。

阅读全文 »

环境信息

  • Python 3.11
  • Django 4.1

使用方法

在 Django 4.1 中,使用静态文件的方法与之前的版本相同。以下是使用静态文件的步骤:

  1. settings.py 中设置静态文件目录:

    settings.py
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
    BASE_DIR / "static",
    ]
    • STATIC_URL 是静态文件 URL 的前缀。
    • STATICFILES_DIRS 是一个列表,其中包含要在其中查找静态文件的目录。
  2. 在 HTML 文件中使用静态文件

    {% load static %}
    <!DOCTYPE html>
    <html>
    <head>
    <title>My Static File Example</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
    </head>
    <body>
    <img src="{% static 'images/logo.png' %}" alt="My logo">
    <script src="{% static 'js/script.js' %}"></script>
    </body>
    </html>

    在上面的示例中,我们使用了 Django 模板语言的 {% static %} 标记来引用静态文件。{% load static %} 指令必须在使用 {% static %} 标记之前加载,以确保 Django 能够正确解析它们。

  3. 运行 collectstatic 命令:
    当您准备部署您的 Django 应用程序时,您需要将静态文件收集到一个单独的目录中,以便可以轻松地在生产服务器上提供它们。您可以使用 Django 的 collectstatic 命令来完成此操作。在命令行中运行以下命令:

    python manage.py collectstatic

    Django 将在 STATIC_ROOT 目录中创建一个新的静态文件目录,并将您的静态文件从 STATICFILES_DIRS 中指定的目录复制到该目录中。您可以在 settings.py 文件中设置 STATIC_ROOT 目录的路径

DTL 语法

load static

参考说明

block.super

用来从父 block 中继承选项

{% load static %}

{% block extrahead %}
{{ block.super }}
<link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" />
<link href="{% static 'bootstrap/css/base.css' %}" rel="stylesheet" />
{% endblock %}

include

假设有两个 HTML 文件:header.htmlcontent.html
header.html 包含页面的头部内容。

header.html
<!-- header.html -->
<header>
<h1>My Website</h1>
<nav>
<!-- 导航栏内容 -->
</nav>
</header>

content.html 包含页面的主要内容。

content.html
<!-- content.html -->
<section>
<h2>Welcome to our website!</h2>
<p>This is the main content of the page.</p>
</section>

现在,可以在另一个 HTML 文件中使用 {% include %} 标签来包含这些内容。

main_template.html
<!-- main_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
{% include 'header.html' %}

<div class="content">
{% include 'content.html' %}
</div>

<footer>
<!-- 页脚内容 -->
</footer>
</body>
</html>

在这个示例中,{% include 'header.html' %}{% include 'content.html' %} 标签会将相应的模板文件的内容包含在 main_template.html 中。这样,就可以在一个模板中包含另一个模板的内容了。

url 反向解析

在模板中不推荐使用 url 硬编码,建议使用 url 反向解析功能,在 urls.py 中定义 url 时,给 url 命名,在模板中 可以使用反向解析使用 url,避免使用 url 硬编码。需要在 urls.py 中配置 app_name = 'polls',否则会因为 namespace 不清楚而报错:'polls' is not a registered namespace

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
]

以上事例中,name='index' 为 url 命名,在模板中通过以下方式使用 url 名称 [1]

<a href="{% url 'polls:index' %}">首页</a>
阅读全文 »

环境信息

  • Django 4.4
  • Modular Admin v1.4.0

常见错误

because its MIME type (‘text/html’) is not a supported stylesheet MIME type

使用 Django 模板语法加载 index.html 中的静态文件后,有个 app.css 文件请求 404,Console 中报错: because its MIME type ('text/html') is not a supported stylesheet MIME type

问题原因 在 Modular Admin 代码中搜索 app.css,除了 index.html 引用了此文件,js/app.js 也引用了此文件。在 Django 中使用次模板,需要修改此处的路径正确。

常用修改事项说明

菜单项的展开标签

要在页面中让菜单处于展开状态,需要给菜单应用 active open 的 class

<li>
<a href="">
<i class="fa fa-area-chart"></i> Charts <i class="fa arrow"></i>
</a>
<ul class="sidebar-nav">
<li>
<a href="charts-flot.html"> Flot Charts </a>
</li>
<li>
<a href="charts-morris.html"> Morris Charts </a>
</li>
</ul>
</li>
<li class="active open">
<a href="">
<i class="fa fa-table"></i> Tables <i class="fa arrow"></i>
</a>
<ul class="sidebar-nav">
<li class="active">
<a href="static-tables.html"> Static Tables </a>
</li>
<li>
<a href="responsive-tables.html"> Responsive Tables </a>
</li>
</ul>
</li>
<li>
<a href="forms.html">
<i class="fa fa-pencil-square-o"></i> Forms </a>
</li>

环境信息

  • Kibana 8.8

常用概念

Spaces

在 Kibana 中,一个 space 相当于一个新的的 Kibana 实例,它分割了 Kibana 中的资源,使它和其他 space 隔离。 [3]

Kibana 默认的 Space 为 Default

Roles

Roles 是一个权限集,可以将 Roles 分配给 users、*system accounts*。可以自定义 roles,或者使用系统内置的 roles。以下是一些常用的 built-in roles

  • kibana_admin - 超级管理员组,绑定到这个组的用户对 Kibana 拥有完全权限,包括管理 Spaces

Users

user 可以绑定到一个或者多个 roles

阅读全文 »