Skip to content

Haoran Qi

79 posts by Haoran Qi

YubiKey OpenPGP Remote sudo with SSH Agent Forwarding

YubiKey OpenPGP Remote sudo with SSH Agent Forwarding

This note records a pattern I like for remote Linux administration:

  • normal SSH login stays on the usual SSH key or password mechanism;
  • sudo authentication uses a hardware-backed OpenPGP authentication key on a local YubiKey;
  • the remote host validates the forwarded SSH agent instead of storing the private key;
  • password-based sudo remains available as a fallback.

Home Network Architecture with RouterOS, OpenWrt, SmartDNS, and FRP

Home Network Architecture with RouterOS, OpenWrt, SmartDNS, and FRP

This article records a practical home network architecture built around MikroTik RouterOS, an OpenWrt bypass router, SmartDNS, Tailscale, and FRP. It is not a copy-and-paste configuration guide. It is more about ownership: which device should own routing, DNS, proxy, IPv6, public services, and recovery.

updated: 2024-01-19

Samba is the standard Windows interoperability suite of programs for Linux and Unix, we are going to configuration it on RHEL/CentOS Linux system.

Commands use root as default, for other user, sudo needed.

dnf install samba -y

For older releae like RHEL7.x and CentOS7.x, replace dnf with yum.

useradd -s /sbin/nologin -d /PATH/TO/HOME/USERNAME

Add user USERNAME with home directory in /PATH/TO/HOME, unable to login.

passwd USERNAME

Change USERNAME’s password.

smbpasswd -a USERNAME

Change file /etc/samba/smb.conf.

workgroup = SAMBA
security = user
log file = /var/log/samba/%m.log
log level = 1
min protocol = SMB3
passdb backend = tdbsam
hosts allow = 192.168.0.0/16
follow symlinks = yes
wide links = yes
unix extensions = no

Set security to user

Set minimum samba version to SMB3

[homes]
comment = Home Directories
valid users = %S, %D%w%S
create mask = 2640
directory mask = 2750
browseable = No
read only = No
inherit acls = Yes
inherit permissions = yes

Add a new section in /etc/samba/smb.conf

[Data]
comment = Data
path = /PATH/TO/DATA
# valid users =
# write list =
valid users = USERNAME
create mask = 2660
directory mask = 2770
browseable = No
read only = No
inherit acls = Yes
inherit permissions = yes
# force user = GROUP
# force group = GROUP

If the directory is not under home directory, it’s unaccessable due to SELinux by default.

Set boolean to access it:

setsebool -P samba_export_all_rw 1

After operations above, it’s able to access home directory with samba, if SELinux is set to diabled, otherwise, SELinux should configured.

setsebool -P use_samba_home_dirs 1

setsebool -P samba_enable_home_dirs 1

If firewalld enabled in your system, you have to add samba to firewall:

firewall-cmd --add-server=samba --permanent And then reload firewall: firewall-cmd --reload

systemctl restart smbd

[1]. https://wiki.samba.org/index.php/Main_Page

[2]. https://linux.die.net/man/8/samba_selinux

[3]. Linux-Firewall-初探

[4]. SElinux-初探

Auto Archive Files with ShellScripts

We are going to introduce a shell script, which can auto archive folders on Linux.

  • OS: Linux with SHELL(sh), Other Unix maybe.
  • bash: Linux bash.

The Script can auto back configured folder to a configured destination:

################################ Global Config #################################
# Source Folder
__SERVICE_SOURCE__="${HOMEDIR}"
# Local Backup Folder
__HDD_PACK_BACK__="${HDD_BASE}"
__LOCAL_CLOUD_OD__="${HOMEDIR}/BackUp"
################################ Global Config #################################
################################# Service ######################################
declare -A SERVICES=(
["services"]="${__SERVICE_SOURCE__}/services,${LOGPATH}/services.log"
)
################################# Service ######################################
# log 1:MSG [2:LOG_PRITORITY]
log()
{
__log_time__=$(date +"%b %e %T")
if [ "${#}" -lt 1 ]; then
false
else
__log_msg__="${1}"
fi
if [ "${#}" -lt 2 ]; then
__log_prio__=7
else
__log_prio__=${2}
fi
logger -p ${__log_prio__} -t "$(basename ${0})" "${__log_msg__}"
echo "${__log_time__} $(basename ${0}) (${__log_prio__}): ${__log_msg__}" >> ${__LOGFILE__}
}
# Encrypter 1:SOURCE_FILE 2:DEST_FOLDER [3:RECEIVER]
Encrypter()
{
__receiver__="xxxxxxxxxxxxxxxx"
if [ "${#}" -lt 2 ]; then
false
elif [ "${#}" -eq 3 ]; then
__receiver__=${3}
fi
__encrypt_file__=${2}/${1##*/}.gpg
log "dest encrypt file: ${__encrypt_file__}"
# Delete exist NOT Uploaded file
if [ -e ${__encrypt_file__} ]; then
rm ${__encrypt_file__}
log "Deleted exist file: ${__encrypt_file__} ......Done"
fi
# Encrypting packed files to DEST_FOLDER
gpg -e -r ${__receiver__} -o ${__encrypt_file__} ${1}
if [ -e ${__encrypt_file__} ]; then
log "Encrypted...... ${__encrypt_file__} to __LOCAL_CLOUD_OD__ ......Done"
fi
}
# Packer 1:SOURCE_FOLDER(whole path) 2:PACKED_DEST_FOLDER [3:ENCRYPT_DEST_FOLDER]
# If only use first 2 parameters, will not encrypt;
# If you wish to encrypt, you should use all 3 parameters.
Packer()
{
# if end without "/"
__service_name__=${1##*/}
# if end with "/"
if [[ ${__service_name__} == "" ]]; then
__service_name__="${1%%/}"
__service_name__="${__service_name__##*/}"
fi
__tar_file__=${2}/${__service_name__}_$(date "+%Y%m%d").tar.gz
# Packing
if [ ! -e ${__tar_file__} ]; then
# Packing folder
tar -zcvf ${__tar_file__} ${1}
log "Packed up ${__tar_file__} ......Done"
# Encrypt from PACKED_DEST_FOLDER to ENCRYPT_DEST_FOLDER
if [ -e ${__tar_file__} ]; then
log "Save NOT encrypt file: ${__tar_file__} ......Done"
# Check if need encryption
if [ "${#}" -eq 3 ]; then
Encrypter ${__tar_file__} ${3}
fi
fi
fi
}
# PersonalFileBackUper 1:SOURCE_FOLDER 2:LOG_FILE
PersonalFileBackUper()
{
__LOGFILE__=${2}
# Pack BackUp and Cloud BackUp
if [ $(date "+%d") == "01" ]; then
Packer ${1} ${__HDD_PACK_BACK__} ${__LOCAL_CLOUD_OD__}
else
Packer ${1} ${__HDD_PACK_BACK__}
fi
}
# CleanOldTarBackup 1:SERVICE_NAME
CleanOldTarBackup()
{
__backup_versions__=$(ls -l ${__HDD_PACK_BACK__}/*${1}* | wc -l)
if [ ${__backup_versions__} -gt 1 ]; then
find ${__HDD_PACK_BACK__} -name "*${1}*" -mtime +6 -mtime -30 -exec rm {} \;
__reserve_vers__=$(ls -l ${__HDD_PACK_BACK__}/*${1}* | wc -l)
if [ ${__backup_versions__} -ne ${__reserve_vers__} ]; then
log "Delete Old Backup files......Done"
fi
fi
}
main()
{
# Backup Personal Service Data
for service in "${!SERVICES[@]}"
do
{
PersonalFileBackUper "${SERVICES[$service]%,*}" "${SERVICES[$service]#*,}"
log "Archive ${service} OK."
sleep 1
# CleanUp Old Backup
CleanOldTarBackup "${service}"
sleep 1
}
done
}
# Calling main() funcion
main
[Unit]
Description=Backup files automatically
Wants=network-online.target
After=network-online.target
[Service]
User=root
Group=root
WorkingDirectory=/home/$USER
Environment="HOMEDIR=/home/$USER"
Environment="HDD_BASE=/Path/To/SSD"
Environment="LOGPATH=/var/log/ArchiveBackUp"
ExecStart=/bin/bash /Path/To/Script/ArchiveBackUp.sh
[Install]
WantedBy=multi-user.target

Some Environment should be configured in service file above:

  • HOMEDIR
  • HDD_BASE
  • LOGPATH

[1].Execute-Scripts-on-Period-with-Systemd

[2].Shell字符串截取

Build Git Server Using Gogs with Docker and Employ Frp with Caddy Reverse Proxy


tags: - Gogscategories: - Containerdate:created: 2020-08-26# updated: 2024-01-19—

Build Git Server Using Gogs with Docker and Employ Frp with Caddy Reverse Proxy

Section titled “Build Git Server Using Gogs with Docker and Employ Frp with Caddy Reverse Proxy”

Goals- Run Gogs on Raspberry Pi and deploy using Docker- Since the Raspberry Pi is on the internal network, Frp needs to be used for internal network penetration.- Use Caddy+CDN proxy to speed up access to Gogs

Section titled “Goals- Run Gogs on Raspberry Pi and deploy using Docker- Since the Raspberry Pi is on the internal network, Frp needs to be used for internal network penetration.- Use Caddy+CDN proxy to speed up access to Gogs”

Requirements- Raspberry 3B+- Domain- Cloudflare Account- VPS with Public IPv4 Address

Section titled “Requirements- Raspberry 3B+- Domain- Cloudflare Account- VPS with Public IPv4 Address”

(1). Use docker’s official one-click installation script:

Section titled “(1). Use docker’s official one-click installation script:”
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

(2). Add the current user to thedockergroup:

Section titled “(2). Add the current user to thedockergroup:”
sudo groupadd docker
sudo usermod -aG docker $USER

(3). Set up image acceleration for docker:`sudo vim /etc/docker/daemon.json````

Section titled “(3). Set up image acceleration for docker:`sudo vim /etc/docker/daemon.json````”

{ “registry-mirrors”: [ “https://1nj0zren.mirror.aliyuncs.com”, “https://docker.mirrors.ustc.edu.cn”, “http://f1361db2.m.daocloud.io”, “https://registry.docker-cn.com” ] }

`sudo systemctl daemon-reload``sudo systemctl restart docker`
## 2. Install Gogs with Docker#### (1). Download the image file`docker pull gogs/gogs-rpi`#### (2). Run the image```
docker run \
--name=gogs-rpi -d \
--restart=always \
-p 10022:22 -p 13000:3000 \
-v /data/gogs:/data gogs/gogs-rpi
  • 10022:22->Map the local port 10022 to 22 in docker- 13000:3000->Map the local port 13000 to 3000 in docker- /data/gogs is the location where data is stored on this machine

3. Install Gogs with docker-compose Orchestration using MySQL (optional)

Section titled “3. Install Gogs with docker-compose Orchestration using MySQL (optional)”
sudo apt-get install docker-compose
version: "3"
services:
db:
image: mysql:5.7
container_name: MySQL5.7
restart: always
ports:
- "13306:3306"
volumes:
- ${pwd_DB}/gogs_DB:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: AdminMySQL
MYSQL_DATABASE: gogs
MYSQL_USER: gogs
MYSQL_PASSWORD: passwordgogs
TZ: Asia/Shanghai
docker-gogs:
depends_on:
- db
image: gogs/gogs
container_name: docker-gogs
restart: always
ports:
- "10022:22"
- "13000:3000"
volumes:
- ${pwd_gogs}/data:/data

(3). Run docker containerEnter the path wheredocker-compose.yamlis located and run:

Section titled “(3). Run docker containerEnter the path wheredocker-compose.yamlis located and run:”
docker-compose up -d

When using MySQL as the data storage, on the settings page of gogs, you need to set the database address todb:3306

Section titled “When using MySQL as the data storage, on the settings page of gogs, you need to set the database address todb:3306”

(2). Resolve the domain name to the IP address of the VPS in Cloudflare, and turn off PrivateDNS, orange cloud -> gray

Section titled “(2). Resolve the domain name to the IP address of the VPS in Cloudflare, and turn off PrivateDNS, orange cloud -> gray”

(3). After gogs configuration is completed, open PrivateDNS

Section titled “(3). After gogs configuration is completed, open PrivateDNS”
[common]
bind_port = [your port1]
token = [your token]
vhost_http_port = [your port2]
bing_udp_port = [your port3]
vhost_https_port = [your port4]
[common]
server_addr = [your ip]
server_port = [your port]
token = [your token]
[Gogs]
type = tcp
local_ip = 127.0.0.1
local_port = 13000
remote_port = 8888
  • It should be noted here that the13000port is the port mapped by the gogs container on the Raspberry Pi, which should correspond to the port running on docker before.

(2). Configure Caddyfile:sudo vim /etc/caddy/Caddyfile

Section titled “(2). Configure Caddyfile:sudo vim /etc/caddy/Caddyfile”
gogs.yourdomain: {
tls address@mail.com
proxy / 127.0.0.1:8888
proxy /captcha 127.0.0.1:8888
}
  • proxy / 127.0.0.1:8888 means forwarding traffic accessing gogs.yourdomain:443 to port 8888 of this machine- address@mail.com represents the user’s email address

(3). Restart Caddy:sudo systemctl restart caddy

Section titled “(3). Restart Caddy:sudo systemctl restart caddy”

(1). AccessIPv4:13000of Raspberry Pi in the browser to set up

Section titled “(1). AccessIPv4:13000of Raspberry Pi in the browser to set up”

(3).EXTERNAL_URLis set tohttps://gogs.yourdomain:443/

Section titled “(3).EXTERNAL_URLis set tohttps://gogs.yourdomain:443/”

(4). After completing the installation, jump back to Section 3.3 and turn on Cloudflare’s PrivateDNS.

Section titled “(4). After completing the installation, jump back to Section 3.3 and turn on Cloudflare’s PrivateDNS.”

limitation- Gogs installed in this way can only perform git operations through https or http protocol.- SSH operations can be achieved by performing FRP penetration on the SSH port, but PrivateDNS cannot support SSH, so PrivateDNS needs to be turned off.

Section titled “limitation- Gogs installed in this way can only perform git operations through https or http protocol.- SSH operations can be achieved by performing FRP penetration on the SSH port, but PrivateDNS cannot support SSH, so PrivateDNS needs to be turned off.”

[2]. https://li-aaron.github.io/2019/07/nas-frp-caddy-cloudfare/

[3]. https://asdasd.page/2019/04/14/Local-Service-Tunneling-with-FRP-and-Caddy/

[4]. https://github.com/fatedier/frp

[5]. Install-FRP [6]. gogs-configuration details [7]. Reverse-Proxy-with-Caddy-on-RHEL

Cloudflare DDNS with ShellScripts


tags: - Shellcategories: - Linux - Networkdate:created: 2023-04-08# updated: 2024-01-19—

1. IntroductionWith the popularity of IPv6 and the unavailability of IPv4 on the public network, the demand for using IPv6 to access external networks has gradually increased. This article uses Cloudflare DNS API to implement IPv6 DDNS.

Section titled “1. IntroductionWith the popularity of IPv6 and the unavailability of IPv4 on the public network, the demand for using IPv6 to access external networks has gradually increased. This article uses Cloudflare DNS API to implement IPv6 DDNS.”

2. Environment Requirements- OS: Linux with SHELL(sh), Other Unix maybe.- HostName: example.com- HostName for DDNS: ddns.example.com

Section titled “2. Environment Requirements- OS: Linux with SHELL(sh), Other Unix maybe.- HostName: example.com- HostName for DDNS: ddns.example.com”

(1) Obtain theZone IDandAPI Keyof the domain nameThe Zone ID can be obtained directly from the API column at the bottom right of the domain name control panel.

Section titled “(1) Obtain theZone IDandAPI Keyof the domain nameThe Zone ID can be obtained directly from the API column at the bottom right of the domain name control panel.”

To obtain the API Key, you need to click “Get your API key” below the column, then enter the password and verification code to confirm. In fact, you can also create a new API Key yourself instead of using the global API Key.

(2) Add the AAAA record of the subdomain nameIn the “DNS” tab of the domain name panel, add an AAAA record in DNS Records, takingddns.example.comas an example:- Name: “ddns”- IPv6 address: “::1”- TTL: NULL- CDN: None

Section titled “(2) Add the AAAA record of the subdomain nameIn the “DNS” tab of the domain name panel, add an AAAA record in DNS Records, takingddns.example.comas an example:- Name: “ddns”- IPv6 address: “::1”- TTL: NULL- CDN: None”

(3) Get the RecordID of the AAAA recordddns.example.comExecute on the command line:

Section titled “(3) Get the RecordID of the AAAA recordddns.example.comExecute on the command line:”
curl -s -X GET "https://api.cloudflare.com/client/v4/zones/ZONE_ID/dns_records?\
type=AAAA&name=DDNS_HOSTNAME&content=127.0.0.1&\
page=1&per_page=100&order=type&direction=desc&match=any" \
-H "X-Auth-Email: CF_EMAIL" \
-H "X-Auth-Key: CF_API_KEY" \
-H "Content-Type: application/json" \
| python -m json.tool
  • ZONE_ID isZone IDobtained in the first step- DDNS_HOSTNAME is the domain name for setting the AAAA record in the second step- CF_EMAIL is the registered email address of the Cloudflare account- CF_API_KEY isAPI KEYobtained in the first step After successful execution, a piece of output in JSON format will be returned. Find the"id"corresponding to the domain nameddns.example.cominresult

A useful Cloudflare Shell API is available on my gitlab: [gitlab.dashdreams.com], all based on scripts above.

(5)Run the scriptAdd execution permissions to the scriptsudo chmod +x ddns.sh

Section titled “(5)Run the scriptAdd execution permissions to the scriptsudo chmod +x ddns.sh”

Run scriptsudo ./ddns.sh

[2].Execute-Scripts-on-Period-with-Systemd [3].Shell string interception [4].Linux-A brief analysis of text processing commands [gitlab.dashdreams.com]:https://gitlab.dashdreams.com:8443/Haoran.Qi/RaspberryPi

Execute Scripts on Period with SystemdThis tutorial aims to implement scheduled execution tasks through`Timer`that comes with`Systemd`


tags: - Systemd - Shellcategories: - Linuxdate:created: 2023-08-20# updated: 2024-01-19—

Execute Scripts on Period with SystemdThis tutorial aims to implement scheduled execution tasks throughTimerthat comes withSystemd

Section titled “Execute Scripts on Period with SystemdThis tutorial aims to implement scheduled execution tasks throughTimerthat comes withSystemd”

This article takesgit pullthat implements timing as an example to explain the timer ofSystemd

1. Create agit pullScriptThe main purpose of this script is to enter the specified git path and execute thegit pullinstruction> You need to make sure that there is a git repository that has been cloned locally in this path.

Section titled “1. Create agit pullScriptThe main purpose of this script is to enter the specified git path and execute thegit pullinstruction> You need to make sure that there is a git repository that has been cloned locally in this path.”

(1). The content ofvim gitpull.shis as follows:

Section titled “(1). The content ofvim gitpull.shis as follows:”
#!/bin/sh
cd ${pwd_of_git_repo_path}
git pull

${pwd_of_git_repo_path} represents the folder of the git repository

(2). After editing, save and exit:wq, and add running permissions to the script:

Section titled “(2). After editing, save and exit:wq, and add running permissions to the script:”
sudo chmod +x gitpull.sh

Run./gitpull.shon the command line. When the command line displays the same output as the commandgit pullwhen running normally, it means that the script is normal.

(1). Create a file namedgitpull.servicein the/etc/systemd/system/or/usr/lib/systemd/system/directory with the following content:

Section titled “(1). Create a file namedgitpull.servicein the/etc/systemd/system/or/usr/lib/systemd/system/directory with the following content:”
[Unit]
Description=gitpull service
[Service]
User=${USER}
Group=${GROUP}
ExecStart=/bin/bash ${pwd_of_scripts}/gitpull.sh
[Install]
WantedBy=multi-user.target

${pwd_of_scripts} represents the folder where the script created in the previous step is located> ${USER} represents the user who executes the script, ${GROUP} represents the group to which the user belongs

Reload and run gitpull.service

sudo systemctl daemon-reload
sudo systemctl start gitpull.service

Check the output log ofSystemdto determine whether the service is running normally and whether the output is the same as that of direct git pull

sudo systemctl status gitpull.service

(1). Create a timer with the following content:

Section titled “(1). Create a timer with the following content:”
[Unit]
Description=run gitpull.sh every 1hour
[Timer]
OnUnitActiveSec=1h
Unit=gitpull.service
[Install]
WantedBy=multi-user.target

The name ofTimerneeds to be consistent with the name ofService> OnUnitActiveSecrepresents the interval at which the run timer runs> Oncalnedarmeans running at a specific time> Unitrepresents the service that needs to be run

  • Oncalnedar* *-*-* *:*:* - *- To signify the day of the week eg:- Sat,Thu,Mon - *-*-* - To signify the calendar date. Which means it breaks down to - year-month-date. - 2021-10-15 is the 15th of October - *-10-15 means every year at 15th October - *-01-01 means every new year. - *:*:*is to signify the time component of the calnedar event. So it is - hour:minute:second
sudo systemctl daemon-reload
sudo systemctl start gitpull.timer

Check the operating status and output of gitpull.service and gitpull.timer

sudo systemctl status gitpull.service
sudo systemctl status gitpull.timer
sudo systemctl enable gitpull.service
sudo systemctl enable gitpull.timer

[2]. https://silentlad.com/systemd-timers-oncalendar-(cron)-format-explained

[3]. Systemd-a first exploration [4]. Cloudflare-DDNS-with-ShellScripts [5]. Auto-Archive-Files-with-ShellScripts

Linux Auto PAC


tags: - PACcategories: - Linuxdate:created: 2020-08-18# updated: 2024-01-19—

1. Install genpacIf pip is not installed, install pip firstsudo apt-get install python-pip``pip install genpac

Section titled “1. Install genpacIf pip is not installed, install pip firstsudo apt-get install python-pip``pip install genpac”

mkdir ~/shadowsocks cd shadowsocks genpac –proxy=“SOCKS5 127.0.0.1:1080” –gfwlist-proxy=“SOCKS5 127.0.0.1:1080” -o autoproxy.pac –gfwlist-url=“https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt”

- 1080 represents the port number of the proxy
## 3. Enter the following command on the command line to check whether the agent is running normally```
curl -so /dev/null -w "%{http_code}" google.com -x socks5://127.0.0.1:1080
  • socks5indicates the proxy protocol used, which can be replaced by other protocols such ashttp- 10080is the port number of the proxy, corresponding to the Input port of the proxy service

4. Configure system network Proxy### GUI interfaceOpen the following path[system] settings -> network -> network proxySelect the proxy mode as automatic, and fill in the configuration url as

Section titled “4. Configure system network Proxy### GUI interfaceOpen the following path[system] settings -> network -> network proxySelect the proxy mode as automatic, and fill in the configuration url as”

file:///PATH_TO_PAC/autoproxy.pac

  • Fill in the path of the pac file according to the actual situation

[2]. Check whether the agent is running normally

Manage Podman Container With Systemd


tags: - Podmancategories: - Containerdate:created: 2023-05-27# updated: 2024-01-19—

1. Problem IntroductionPodman is different from Docker in that it does not require the docker daemon to control the running of the container in terms of architecture, so the restart of the container needs to be taken over by systemd.

Section titled “1. Problem IntroductionPodman is different from Docker in that it does not require the docker daemon to control the running of the container in terms of architecture, so the restart of the container needs to be taken over by systemd.”
podman generate systemd -t 30 -n --new -f web
  • -t: timeout period- -n: indicates using the container name instead of the container id- -f: indicates generating service files- –new: Delete the old container and start a new container every time it is started

3. Manage Pod with Systemd### (1). Create a Pod```

Section titled “3. Manage Pod with Systemd### (1). Create a Pod```”

podman pod create –name POD_NAME

### (2). Create Container in Pod```
podman container run --pod POD_NAME --name CONTAINER_NAME1
podman container run --pod POD_NAME --name CONTAINER_NAME2

(3). Generate systemd service files for Pod and Containers inside```

Section titled “(3). Generate systemd service files for Pod and Containers inside```”

podman generate systemd -f –new –name POD_NAME

- -f: indicates generating service files- --new: Delete the old container and start a new container every time it is started- POD_NAME: pod name
## 4. Config Systemd
### (1). Move service file to`/usr/lib/systemd/system`### (2). Restore SELinux Label with command below```
restorecon /usr/lib/systemd/system/container-***.service

systemctl daemon-reload

### (4). Set Service Enabled```
systemctl enable container-***.service

[2]. https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_linux/9/html/building_running_and_managing_containers/assembly_porting-containers-to-systemd-using-podman_building-running-and-managing-containers#doc-wrapper

[3]. https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_linux/9/html/building_running_and_managing_containers/proc_auto-starting-pods-using-systemd_assembly_porting-containers-to-systemd-using-podman

[4]. Systemd-a first exploration

Notes on Podman Network

This is a note on some issues relating to podman network and firewalld on RHEL.

  • RHEL 9.4
  • Podman 4.9.4-rhel
–network –net -p firewall status
- [x] [x] Allowed
bridge [x] [x] Blocked
host - - Blocked

As showed in table above, if using podman with --net -p parameters only, firewalld will not block the access on this port.

However, with --network bridge configured, and paramters above configured, the firewalld will block this access.

And as showed, firewalld will block all access on configuring --network host.

On ports mapping, spefic ip address like 127.0.0.1 on host port.

[1]. Linux-Firewall-初探

[2]. Netstat-常用参数

Podman Volumes and SELinux## SELinuxSecurity-Enhanced Linux (SELinux) is a security architecture for Linux systems that allows administrators to have greater control over who can access the system [What is SELinux?]. For a detailed description of SELinux, refer to [SELinux Policies and Rules].


tags: - SELinuxcategories: - Linux - Containerdate:created: 2022-06-02# updated: 2024-01-19—

Podman Volumes and SELinux## SELinuxSecurity-Enhanced Linux (SELinux) is a security architecture for Linux systems that allows administrators to have greater control over who can access the system [What is SELinux?]. For a detailed description of SELinux, refer to SELinux Policies and Rules.

Section titled “Podman Volumes and SELinux## SELinuxSecurity-Enhanced Linux (SELinux) is a security architecture for Linux systems that allows administrators to have greater control over who can access the system [What is SELinux?]. For a detailed description of SELinux, refer to SELinux Policies and Rules.”

1. Problem IntroductionWhen Podman is running on a system with SELinux enabled and Volumes need to be mapped, permission issues will be encountered.

Section titled “1. Problem IntroductionWhen Podman is running on a system with SELinux enabled and Volumes need to be mapped, permission issues will be encountered.”

When running a podman container as a non-root account, files in the/home/user/directory may have the following context permissions:unconfined_u:object_r:data_home_t:s0, but podman volumes require such permissionssystem_u:object_r:container_file_t:s0to function properly. Container volumes created by podman at runtime will automatically have the appropriate context set. However, for the/home/user/directory volume, podman does not change the context by default.

2. Auto Labelspodman provides two labels for modifying the security context at runtime::zand:Z

Section titled “2. Auto Labelspodman provides two labels for modifying the security context at runtime::zand:Z”
  • Shared Labels- Private Labels Shared Labels allow multiple containers to access a volume at the same time; Private labels only allow specific containers to access the volume.

[2]. https://m-zhoujie2.gitbooks.io/-linux-devops-2/content/chapter3-10.html

[3]. SeLinux-a preliminary study

Qmake Pro

| —–– | ––––––––––––––––––– | |app|Create a Makefile for building the application (default)| |lib|Create a Makefile for building the library| |subdirs|Create a Makefile for building the target subdirectory specified by the SUBDIRS variable| |aux|Create a Makefile that doesn’t create anything|

2. TARGETSpecify the name of the target file## 3. CONFIG

Section titled “2. TARGETSpecify the name of the target file## 3. CONFIG”
release The project is built in release mode. If debug is also specified, the last one will take effect.
debug Project is built in debug mode
debug_and_release The project is ready to be built in two modes: debug and release.
debug_and_release_target This option is set by default. If debug_and_release is specified, the final debug and release are created in different directories.

Specify the Qt module used in the project. By default, QT includes core and gui. If you create a module that does not include gui, “QT _= gui”

Program compilation is a dependent path## 6. INCLUDEPATH
The include path of the header file specifies the #include directory that should be searched when compiling the project. If it contains spaces, “” should be used## 7. QMAKE_LFLAGS
Specifies a common set of identifiers passed to the linker## 8. LIBSSpecify a list of libraries to link to in the project

Reverse Proxy with Nginx on RHEL

This article introducing a method on reverse proxy with Nginx web server on RHEL.

sudo dnf install nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
}

(2). Site Config in /etc/nginx/conf.d/*.conf

Section titled “(2). Site Config in /etc/nginx/conf.d/*.conf”
server {
server_name WEB.DOMAIN.com;
location / {
proxy_ssl_server_name on;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_pass http://$host:$remote_port;
}
listen 443 ssl http2; # DO NOT NEED IF YOU USE NGINX
ssl_certificate path/to/certificate/fullchain.pem; # DO NOT NEED IF YOU USE NGINX
ssl_certificate_key path/to/certificate//privkey.pem; # DO NOT NEED IF YOU USE NGINX
}
sudo dnf install certbot
sudo dnf install python3-certbot-nginx

(3). (Opt.) Install plugin for dns-cloudflare

Section titled “(3). (Opt.) Install plugin for dns-cloudflare”
sudo dnf install python3-certbot-dns-cloudflare

According to steps above, there are many ways to get certificate. We demonstrate 2 ways matchs steps (2) and (3) before.

  1. Sign with Nginx

    sudo certbot --nginx -d domainname.com

    In this way, Certificates will be configured in *.conf in folder /etc/nginx/conf.d/ automatically.

  2. Sign with dns-cloudflare

    sudo certbot certonly --dns-cloudflare \
    --dns-cloudflare-credentials \
    ~/.secrets/certbot/cloudflare.ini \
    -d example.com

    In this way, you need a cloudflare key file: cat cloudflare.ini

    # Cloudflare API credentials used by Certbot
    dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234
sudo setsebool -P httpd_can_network_connect 1

[1]. https://certbot.eff.org/

[2]. https://certbot-dns-cloudflare.readthedocs.io/en/stable/

[3]. https://docs.nginx.com/

[4]. https://stackoverflow.com/questions/23948527/13-permission-denied-while-connecting-to-upstreamnginx

[5]. Let-Encrypt-with-Certbot

[6]. SElinux-初探

[7]. RHEL9-Activation

[8]. RHEL9-RPM-Fusion-Repo

Set Raspberry as WiFi Router


tags: - Raspberrycategories: - Linuxdate:created: 2020-08-11# updated: 2024-01-19—

Convert Raspberry Pi 3B+ into a wifi wireless router Implement the following functions: 1. WiFi works in 802.11ac mode, 433Mbps Link Speed 2. WiFi network sharing Ethernet port, IPv4 uses NAT 3. External USB driver-free network card as LAN port

sudo apt-get update && upgrade
sudo apt-get install hostapd dnsmasq
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

3. Configure a static IP for the network cardNeed to ensure that /etc/network/interface is not used to configure the network card

Section titled “3. Configure a static IP for the network cardNeed to ensure that /etc/network/interface is not used to configure the network card”
sudo vim /etc/dhcpcd.conf

(2) Add the following content at the end of the file, save and exit

Section titled “(2) Add the following content at the end of the file, save and exit”
interface eth0
interface wlan0
static ip_address=192.168.3.1/24
nohook wpa_supplicant
interface eth1
static ip_address=192.168.4.1/24
nohook wpa_supplicant
sudo systemctl restart dhcpcd.service
  • eth0 automatically obtains an IP address, and wlan0 and eth1 are set to 192.168.3.1 and 192.168.4.1 respectively.
sudo vim /etc/dnsmasq.conf

(2) Add the following content at the end of the file, save and exit

Section titled “(2) Add the following content at the end of the file, save and exit”
interface=wlan0
dhcp-range=192.168.3.100,192.168.3.200,255.255.255.0,24h
interface=eht1
dhcp-range=192.168.4.100,192.168.4.200,255.255.255.0,24h
sudo vim /etc/hostapd/hostapd.conf

(2) Enter the following content, save and exit

Section titled “(2) Enter the following content, save and exit”
interface=wlan0
driver=nl80211
hw_mode=a
ieee80211n=1
ieee80211ac=1
ieee80211d=1
ieee80211h=1
require_ht=1
require_vht=1
wmm_enabled=1
country_code=US
vht_oper_chwidth=1
channel=149
vht_oper_centr_freq_seg0_idx=155
ht_capab=[HT40-][HT40+][SHORT-GI-40][DSSS_CCK-40]
wpa=2
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
ssid=PI_WIFI
wpa_passphrase=password
  • In layman’s terms, ssid is the network name of Wi-Fi.
  • wpa_passphrase is the Wi-Fi password
  • ssid and wpa_passphrase can be changed at will, but be careful that wpa_passphrase is more than 8 bytes
  • Generally speaking, there is no need to change the channel, because the frequency band available in China requires a continuous 80MHz bandwidth, and no matter how you adjust it, there is no way for two APs to have no overlapping frequency bands.
  • The country_code must be present and must be US. I have tried changing it to CN but it cannot be started.

(3) Write the configuration file path into the service configuration file

Section titled “(3) Write the configuration file path into the service configuration file”
echo "DAEMON_CONF=\"/etc/hostapd/hostapd.conf\"" >> /etc/default/hostapd
sudo systemctl start hostapd
sudo systemctl start dnsmasq
sudo vim /etc/rc.local

(2) Add the following content beforeExit 0, save and exit

Section titled “(2) Add the following content beforeExit 0, save and exit”
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
sudo /etc/rc.local

(1) Additional software installation is required

Section titled “(1) Additional software installation is required”
sudo apt-get install bridge-utils ebtables radvd -y

Edit the configuration file /etc/sysctl.conf and remove the comment from the following line net.ipv6.conf.all.forwarding=1

(3) Write the configuration file based on the globally unique IPv6 obtained by the actual network port

Section titled “(3) Write the configuration file based on the globally unique IPv6 obtained by the actual network port”

vim /etc/radvd.conf

interface wlan0
{
AdvSendAdvert on;
prefix 2001:da8:7001:251::/64
{
AdvOnLink on;
AdvAutonomous on;
AdvRouterAddr on;
};
};
  • 2001:da8:7001:251::/64is the IPv6 address corresponding toScope:Globalobtained throughifconfig

Edit /etc/rc.local

iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -o ppp0 -j MASQUERADE
service radvd start
ebtables -t broute -A BROUTING -p ! ipv6 -j DROP
brctl addbr br0
ifconfig br0 up
brctl addif br0 eth0
brctl addif br0 wlan0
  • There is a compatibility issue here [ebtables], ebtables needs to be set Enterupdate-alternatives --set ebtables /usr/sbin/ebtables-legacyin the command line. The main problem is that the new version of ebtalbes is incompatible with the command and you need to switch to the old version of the program.

After turning on IPv6 transparent transmission, there are network problems, and the cause of the problem is unknown. The main phenomenon is that the docker network is completely down (maybe because of the host’s network settings, maybe using Bridge)

[1]. Ubuntu dependency resolution and installation [2]. Linux-A brief analysis of text processing commands [ebtables]:https://github.com/netblue30/firejail/issues/2232

Shell string interception


tags: - Shellcategories: - Linuxdate:created: 2020-09-11# updated: 2024-01-19—

Format illustrate
${string: start :length} Starting from the start character on the left side of the string string, intercept length to the right.
${string: start} Intercept from the start character on the left side of the string string until the end
${string: 0-start :length} Starting from the start character on the right side of the string string, intercept length to the right.
${string: 0-start} Intercept from the start character on the right side of the string string until the end
${string#*chars} Starting from the first occurrence of *chars in the string string, intercept *chars
${string##*chars} Starting from the last occurrence of *chars in the string string, intercept *chars
${string%*chars} Starting from the first occurrence of *chars in the string string, intercept *chars
${string%%*chars} Starting from the last occurrence of *chars in the string string, intercept *chars

[2]. Cloudflare-DDNS-with-ShellScripts [3]. Auto-Archive-Files-with-ShellScripts

Socket-first exploration


tags: - The-Ccategories: - Codingdate:# created: 2025-02-26# updated: 2025-02-26—

1. Socket() function### (1). domain protocol family: 1. AF_INET 2. AF_INET6 3. AF_LOCAL(AF_UNIX) 4. AF_ROUTE### (2). Type socket type 1. SOCK_STREAM 2. SOCK_DGRAM 3. SOCK_RAW 4. SOCK_PACKET 5. SOCK_SEQPACKET### (3). Protocol 1. IPPROTO_TCP 2. IPPROTO_UDP 3. IPPROTO_STCP 4. IPPROTO_TIPC## 2. Bind() function```

Section titled “1. Socket() function### (1). domain protocol family: 1. AF_INET 2. AF_INET6 3. AF_LOCAL(AF_UNIX) 4. AF_ROUTE### (2). Type socket type 1. SOCK_STREAM 2. SOCK_DGRAM 3. SOCK_RAW 4. SOCK_PACKET 5. SOCK_SEQPACKET### (3). Protocol 1. IPPROTO_TCP 2. IPPROTO_UDP 3. IPPROTO_STCP 4. IPPROTO_TIPC## 2. Bind() function```”
Int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
- Sockfd: socket descriptor, uniquely identifies a socket- addrlen: address length- addr: an address pointer pointing to the protocol address to be bound to sockfd
For example, ipv4 corresponds to:```
struct sockaddr_in {
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
};
struct in_addr {
uint32_t s_addr;
};

Corresponding to ipv6 is:``` struct sockaddr_in6 {
sa_family_t sin6_family;
in_port_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};

struct in6_addr {
unsigned char s6_addr[16];
};
The Unix domain corresponds to:```
#define UNIX_PATH_MAX 108
struct sockaddr_un {
sa_family_t sun_family;
char sun_path[UNIX_PATH_MAX];
};

Int listen(int sockfd, int backlog)Int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)

  • The listen function changes the active type created by the socket into a passive type and waits for the client to connect.

Int socket(int domain, int type, int protocol)

## 5. setsockopt function```
Int setsockopt(SOCKET s, int level, int optname, const char FAR *optval, int optlen)
  • s:socket descriptor- Level: option level, SOL_SOCKET/IPPROTO_TCP- Optname: Options that need to be set- optval: just want to store the pointer of the option- Optlen: buffer length

[2]. OSI model

SSH Authentication with GPG Keys on Linux


tags: - GnuPG - SSHcategories: - Linux date:created: 2025-04-05updated: 2024-06-05—

Here are the steps on how to set up SSH authentication using GPG on Linux:

  • GPG (GNU Privacy Guard): A cryptographic tool commonly used for signing and encrypting data. We can leverage GPG key pairs for authentication.* SSH (Secure Shell): An encrypted network protocol used to securely execute commands and transfer files over unsecured networks.* gpg-agent: A daemon that manages your GPG private keys to avoid having to enter a password every time you use them.* ssh-agent: A daemon that manages your SSH private keys and also avoids password re-entering.* libpam-gnome-keyring(optional but recommended): A PAM module that automatically startsgpg-agentandssh-agentwhen you log in.* gnupg-agent: Provides the functionality required for SSH authentication using GPG keys.

1. Install the necessary packages:Depending on your Linux distribution, install the following packages: * Debian/Ubuntu: ```bash

Section titled “1. Install the necessary packages:Depending on your Linux distribution, install the following packages: * Debian/Ubuntu: ```bash”
sudo apt update
sudo apt install gnupg2 gpg-agent openssh-server openssh-client libpam-gnome-keyring
```
* **Fedora/CentOS/RHEL:** ```bash
sudo dnf install gnupg2 gpg-agent openssh-server openssh-clients pam_gnome_keyring
```
* **Arch Linux:** ```bash
sudo pacman -S gnupg openssh libgnome-keyring
```

2. Generate or import a GPG key pair:If you don’t have a GPG key pair yet, you can generate a new one using the following command: ```bash

Section titled “2. Generate or import a GPG key pair:If you don’t have a GPG key pair yet, you can generate a new one using the following command: ```bash”
gpg --full-generate-key
```

Follow the prompts to select the key type, key length, expiration date, and set your real name, email address, and comment. Please remember your password.If you already have a GPG key pair, you can skip this step.

3. Confirm GPG key usage and obtain fingerprint:Make sure you have a GPG key or subkey with purpose set toAuthenticate. Confirm and obtain the fingerprint (40-digit HEX) of the key or subkey with the following command: ```bash

Section titled “3. Confirm GPG key usage and obtain fingerprint:Make sure you have a GPG key or subkey with purpose set toAuthenticate. Confirm and obtain the fingerprint (40-digit HEX) of the key or subkey with the following command: ```bash”
gpg --with-keygrip -K
```

4. Add the GPG key fingerprint to thesshcontrolfile:Put the fingerprint obtained in the previous step into the~/.gnupg/sshcontrolfile. Place one fingerprint per line. ```

Section titled “4. Add the GPG key fingerprint to thesshcontrolfile:Put the fingerprint obtained in the previous step into the~/.gnupg/sshcontrolfile. Place one fingerprint per line. ```”
# 示例 (将 YOUR_FINGERPRINT 替换为实际的指纹)
YOUR_FINGERPRINT
```

5. Configuregpg-agent:Edit or create the~/.gnupg/gpg-agent.conffile and add the following lines: ```

Section titled “5. Configuregpg-agent:Edit or create the~/.gnupg/gpg-agent.conffile and add the following lines: ```”
enable-ssh-support
default-cache-ttl 3600
max-cache-ttl 7200
```
* `enable-ssh-support`: Enable SSH support. * `default-cache-ttl`: Set the default password cache time in seconds. * `max-cache-ttl`: Set the maximum password cache time.

6. Configure PAM (optional but recommended):If you havelibpam-gnome-keyring(or a similar package) installed, you can configure PAM to automatically startgpg-agentandssh-agentat login.Edit the/etc/pam.d/loginand/etc/pam.d/sshdfiles and add the following lines if they do not exist:In theauthsection add: ```

Section titled “6. Configure PAM (optional but recommended):If you havelibpam-gnome-keyring(or a similar package) installed, you can configure PAM to automatically startgpg-agentandssh-agentat login.Edit the/etc/pam.d/loginand/etc/pam.d/sshdfiles and add the following lines if they do not exist:In theauthsection add: ```”
auth optional pam_gnome_keyring.so skel
```

In thesessionsection add: session optional pam_gnome_keyring.so auto_start Note: The exact files and lines may vary depending on your Linux distribution and PAM configuration. You may need to make similar changes in other PAM configuration files such assudoor the graphical login manager.

7. Export the SSH public key:Use the following command to export the SSH public key from your GPG private key. ReplaceYOUR_GPG_KEY_IDwith your GPG key ID. You can find your key ID using thegpg --list-secret-keys --keyid-format longcommand. ```bash

Section titled “7. Export the SSH public key:Use the following command to export the SSH public key from your GPG private key. ReplaceYOUR_GPG_KEY_IDwith your GPG key ID. You can find your key ID using thegpg --list-secret-keys --keyid-format longcommand. ```bash”
gpg --export-ssh-key YOUR_GPG_KEY_ID > ~/.ssh/id_ed25519.pub
```

Notice: * The exported public key is saved as~/.ssh/id_ed25519.pubby default. You can change the file name as needed. * Make sure your GPG private key is password protected.

8. Copy the SSH public key to the remote server:Copy the contents of your exported SSH public key (~/.ssh/id_ed25519.pub) into the~/.ssh/authorized_keysfile on the remote server you want to SSH authenticate.You can use thessh-copy-idcommand to simplify this process (if your local machine is already configured for password- or key-based SSH access): ```bash

Section titled “8. Copy the SSH public key to the remote server:Copy the contents of your exported SSH public key (~/.ssh/id_ed25519.pub) into the~/.ssh/authorized_keysfile on the remote server you want to SSH authenticate.You can use thessh-copy-idcommand to simplify this process (if your local machine is already configured for password- or key-based SSH access): ```bash”
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@remote_server
```

Alternatively, you can manually append the contents of~/.ssh/id_ed25519.pubto the~/.ssh/authorized_keysfile on the remote server: bash cat ~/.ssh/id_ed25519.pub | ssh user@remote_server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

9. Configure the SSH client:Edit or create the~/.ssh/configfile and add the following to configure your SSH client to use GPG for authentication: ```

Section titled “9. Configure the SSH client:Edit or create the~/.ssh/configfile and add the following to configure your SSH client to use GPG for authentication: ```”
Host remote_server_alias # 您可以为远程服务器设置一个别名
Hostname remote_server_ip_or_hostname
User your_username
IdentityFile ~/.ssh/id_ed25519
PubkeyAcceptedKeyTypes +ssh-ed25519-cert-v01@openssh.com,ssh-ed25519
```
* `Host`: The alias you set for the remote server. * `Hostname`: The IP address or hostname of the remote server. * `User`: Your username on the remote server. * `IdentityFile`: The path to the SSH public key file you exported (without the`.pub`extension). * `PubkeyAcceptedKeyTypes`: Specifies the accepted public key types. Add`+ssh-ed25519-cert-v01@openssh.com`to enable certificate-based authentication.

10. Startgpg-agentandssh-agent:If you do not configure PAM, you need to startgpg-agentandssh-agentmanually after logging in. Add the following to your shell configuration file (e.g.~/.bashrc,~/.zshrc): ```bash

Section titled “10. Startgpg-agentandssh-agent:If you do not configure PAM, you need to startgpg-agentandssh-agentmanually after logging in. Add the following to your shell configuration file (e.g.~/.bashrc,~/.zshrc): ```bash”
if [ -z "$SSH_AUTH_SOCK" ]; then
eval "$(ssh-agent -s)"
fi
if ! gpg-connect-agent /bye > /dev/null 2>&1; then
eval "$(gpg-agent --daemon --enable-ssh-support)"
fi
export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
```

Then, reload your shell profile: bash source ~/.bashrc # 或 source ~/.zshrc

11. Add the GPG private key togpg-agent:You may need to add your GPG private key togpg-agent. This will prompt you for your password: ```bash

Section titled “11. Add the GPG private key togpg-agent:You may need to add your GPG private key togpg-agent. This will prompt you for your password: ```bash”
gpg --import-ownertrust
gpg --card-status # 如果您使用智能卡
```

Alternatively, you can enter your password the first time you attempt an SSH connection.

12. Test the SSH connection:You should now be able to SSH to the remote server using the configured alias without entering a password (unless your GPG private key is not already unlocked): ```bash

Section titled “12. Test the SSH connection:You should now be able to SSH to the remote server using the configured alias without entering a password (unless your GPG private key is not already unlocked): ```bash”
ssh remote_server_alias
```

If this is your first time using this GPG key for an SSH connection, you may be asked to enter the password for the GPG key. Afterwards, the password will be cached ingpg-agentuntil the cache expires.

  • Security: Make sure your GPG private key is protected by a strong password.* Backup: Be sure to back up your GPG private key.* gpg-agentandssh-agent: Make sure these two agents are running. You can check this using theps aux | grep gpg-agentandps aux | grep ssh-agentcommands.* Permissions: Make sure the permissions for the~/.sshdirectory and~/.ssh/authorized_keysfiles are set correctly (usually700for~/.sshand600for~/.ssh/authorized_keys).* Server Configuration: Ensure that public key authentication (PubkeyAuthentication yes) is enabled in thesshd_configfile on the remote server. With the above steps, you should be able to successfully configure your Linux system to use GPG keys for SSH authentication, improving security and streamlining your workflow.

[2]. OpenPGP-a preliminary study

TCP Over DNS to bypass campus network billing


tags: - TCPcategories: - Network - Linuxdate:created: 2020-08-20# updated: 2024-01-19—

TCP Over DNS to bypass campus network billing

Section titled “TCP Over DNS to bypass campus network billing”

1. Requirements- VPS -> Take CentOS as an example-> IP is represented by 123.123.123.123- Domain name -> represented by domain.com-> Subdomain names are represented by tunnels

Section titled “1. Requirements- VPS -> Take CentOS as an example-> IP is represented by 123.123.123.123- Domain name -> represented by domain.com-> Subdomain names are represented by tunnels”

2. Set up domain name resolution|host record|Record|value|

Section titled “2. Set up domain name resolution|host record|Record|value|”

| –– | —– | —– | |NS|d2t|tunnel.domain.com| |A|tunnel|123.123.123.123 |

git clone https://github.com/yarrick/iodine.git
cd iodine
make
make install
  • Compilation and installation require GCC environment

(2). Run iodineiodined -f -c -P password 10.0.0.1 d2t.domain.com

Section titled “(2). Run iodineiodined -f -c -P password 10.0.0.1 d2t.domain.com”
  • Note:> -f runs in the foreground> -c disables checking the client IP address of all incoming requests; by default, requests from non-matching IPs will be rejected.> -P sets authentication password> 10.0.0.1 is a reserved address

ClientThe client is Ubuntu20.04 LTS in WSL2

Section titled “ClientThe client is Ubuntu20.04 LTS in WSL2”

(1). Install iodinesudo apt-get install iodine

Section titled “(1). Install iodinesudo apt-get install iodine”

(2). Run iodinesudo iodine -f -P password d2t.domain.com

Section titled “(2). Run iodinesudo iodine -f -P password d2t.domain.com”

(3). Open a new Terminal, connect to the server through SSH, and use 9999 as the forwarding port.ssh USER@10.0.0.1 -p1234 -D 9999

Section titled “(3). Open a new Terminal, connect to the server through SSH, and use 9999 as the forwarding port.ssh USER@10.0.0.1 -p1234 -D 9999”
  • Note:> USER represents the username of the VPS> 1234 represents the port of SSH on the VPS

(1). Install the plug-in [SwitchyOmega][SwitchyOmega] in the browser

Section titled “(1). Install the plug-in [SwitchyOmega][SwitchyOmega] in the browser”

(2). Create a new Proxy Profile|Protocol|Server|Port|

Section titled “(2). Create a new Proxy Profile|Protocol|Server|Port|”

|––––|—— |––| |Socks5|localhost|9999|

(3). Click on SwitchyOmega in the upper right corner of the browser to select the proxy created in the previous step to access the Internet.

Section titled “(3). Click on SwitchyOmega in the upper right corner of the browser to select the proxy created in the previous step to access the Internet.”

[1]. https://fanqxu.github.io/2019/03/20/Bypass-campusNet/

[2].OSI model [SwitchyOmega]:https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif

VM CPP QT Compiling Environment with VSCode

VM CPP QT Compiling Environment with VSCode

Section titled “VM CPP QT Compiling Environment with VSCode”

First of all, the latest version of VSCode should be installed on one PC running Windows/Linux/MacOS.

Secondly, the following Extensions should be installed:

C/C++

Remote-SSH

Remote-SSH:Editing-Configuration-Files

(2). With VMWare Workstation installed including a Virtual machine configured.

Section titled “(2). With VMWare Workstation installed including a Virtual machine configured.”

Firstly, the virtual machine should run properly.

Also, the network goes OK (PING from host to the VMs, and the reverse).

Open “REMOTE EXPLORER” window -> “Add NEW”, and type the following command in the dialog:

ssh USER@192.xxx.xxx.xxx -A

Type in the password and leave the popup options default.

USER is the user of VMs’ username

192.xxx.xxx.xxx is the IP address of the VM.

Then choose a proper path as the compiling default path, the Home path is recommended.

(2). Upload the Source Code to the virtual machine

Section titled “(2). Upload the Source Code to the virtual machine”

In this step, many tools can be applyed, including scp、sftp、xshell.

ATTENTION! You should upload the code with a proper user to avoid the permission error.

Step1. Open the path of source code in VSCode.

Step2. Add a new directory named .vscode if no such directory exist.

Add c_cpp_properties.json in the .vscode folder. The content as follow:

{
"configurations": [
{
"name": "RHEL7.2->Linux",
"includePath": [
"${workspaceFolder}/**",
"/opt/scadacom/current/**"
],
"forcedInclude": [],
"defines": [],
"compilerPath": "/usr/bin/g++",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "linux-gcc-x64",
"compilerArgs": [ //Release
"-std=c++11",
"-w",
"-O2",
"-pipe",
"-m64",
"-D_REENTRANT",
"-DQT_SHARED",
"-DQT_NO_DEBUG_OUTPUT",
"-DQT_NO_DEBUG",
"-DQT_GUI_LIB",
"-DQT_NETWORK_LIB",
"-DQT_CORE_LIB",
"-DQT_SHARED"
]
},
{
"name": "RHEL7.2-WindowsLocal",
"includePath": [
"${workspaceFolder}/**",
"~/Documents/Codes/include/RHEL7.2S5.8.10/**",
"C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/x86_64-w64-mingw32/include"
],
"forcedInclude": [],
"defines": [],
"compilerPath": "C:/ProgramData/chocolatey/bin/g++.exe",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "linux-gcc-x64",
"compilerArgs": [ //Release
"-std=c++11",
"-w",
"-O2",
"-pipe",
"-m64",
"-D_REENTRANT",
"-DQT_SHARED",
"-DQT_NO_DEBUG_OUTPUT",
"-DQT_NO_DEBUG",
"-DQT_GUI_LIB",
"-DQT_NETWORK_LIB",
"-DQT_CORE_LIB",
"-DQT_SHARED"
],
"mergeConfigurations": false,
"browse": {
"path": [
"${workspaceFolder}/**",
"~/Documents/Codes/include/RHEL7.2S5.8.10/**"
],
"limitSymbolsToIncludedHeaders": true
}
}
],
"version": 4
}

Qmake and g++ compile configuration need configured in a tasks.json file. The content as follow:

{
"version": "2.0.0",
// "windows": {
// "options": {
// "shell": {
// "executable": "bash.exe",
// "args": ["-c"]
// }
// }
// },
"tasks": [
{
"label": "Qmake",
"type": "shell",
"command": "/usr/local/Trolltech/Qt-4.8.4/bin/qmake",
"args": [],
"group": "build",
"presentation": {
"reveal": "silent",
"clear": true
}
},
{
"label": "Clean",
"type": "shell",
"command": "make",
"args": [
"clean"
],
"group": "build",
"presentation": {
"reveal": "silent",
"clear": true
}
},
{
"label": "MakeCompile",
"type": "shell",
"dependsOrder": "sequence",
"dependsOn": [
"Clean",
"Qmake"
],
"command": "/usr/bin/make",
"args": [
],
"group": "build",
"presentation": {
// "reveal": "silent",
"clear": true
}
},
]
}

After task configured, you can launch build task from vscode edit window by press CTRL+Shift+B.

The manual as follow:

Qmake: runing command /usr/local/Trolltech/Qt-4.8.4/bin/qmake

Release: running command /usr/bin/make -f Makefile.Release after running Qmake automatically.

Debug: running command /usr/bin/make -f Makefile.Debug after running Qmake automatically.

Clean: delete files generate by Qmake and g++

Clean-Release: running command make -f Makefile.Release clean

Clean-Debug: running command make -f Makefile.Debug clean

GNU gdb tool will be used as the debug tool, you can debug the code with such launch.json configuration:

{
"version": "0.2.0",
"configurations": [
{
"name": "QT-CPPGDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/wg_modbus_ats",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/debug/",
"environment": [],
//"symbolSearchPath": "C:\\Symbols",
"externalConsole": false,
"linux": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"windows": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"osx": {
"miDebuggerPath": "/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi",
"MIMode": "lldb"
},
// "logging": {
// "moduleLoad": false,
// "trace": true
// },
"visualizerFile": "my.natvis"
},
{
"name": "CMake-CPPGDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/${workspaceFolderBasename}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
//"symbolSearchPath": "C:\\Symbols",
"externalConsole": false,
"linux": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"windows": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"osx": {
"miDebuggerPath": "/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi",
"MIMode": "lldb"
},
// "logging": {
// "moduleLoad": false,
// "trace": true
// },
"visualizerFile": "my.natvis"
}
]
}

However, the debug can not change the target automatically, the debug flow should be as follow:

Running Clean or Clean-Debug -> Running Debug -> Change TARGETS -> Set BreakPoint -> press F5.

The TARGETS is the executable file generate by g++.

All Configuration files can be found Here.

[1]. https://blog.dashdreams.com

[2]. C/C++

[3]. Remote-SSH

[4]. Remote-SSH:Editing-Configuration-Files

[5]. VSCode-C-CPP-Environment

[6]. Qmake-Pro

Linux Text Processing Commands

Linux command-line text processing usually combines small tools through pipelines. The most commonly used tools are:

  • cat: print file content.
  • grep: filter lines by pattern.
  • sed: edit text streams.
  • awk: process structured text by fields.
  • cut: extract columns from each line.
  • sort: sort lines.
  • uniq: remove or count adjacent duplicate lines.
  • tr: translate or delete characters.

Example pipeline:

Terminal window
cat access.log | grep "ERROR" | awk '{print $1}' | sort | uniq -c

This command filters error lines, extracts the first field, sorts the result, and counts repeated values.

[1]. Shell字符串截取

ConfigTools Industrial Automation Configurator Overview

🔗 GitLab repository: Utilities/ConfigTools

ConfigTools is a high-performance industrial graphical configuration application written in Qt/C++ (C++17). It is designed for the physical and logical deployment of modular automation systems, such as Siemens TIA Portal scenarios. The project includes a high-fidelity 42U cabinet simulation, intelligent hardware assembly collision detection, an undo/redo command stack, and a one-click engineering report generation engine.

  1. High-fidelity 42U cabinet simulation
    • Built on a precise 1U = 50px grid coordinate system, rendering a virtual cabinet with rulers and physical rails.
    • Supports drag interaction and Magnetic Snapping, with built-in real-time collision detection and physical rebound animation when a placement is invalid.
  2. Strict MVC data and graphics architecture
    • Uses a highly decoupled hierarchical tree structure: “cabinet -> device -> slot -> module”.
    • Supports runtime slot count changes and adaptive layout recalculation.
  3. Undo/redo command system based on QUndoStack
    • Implements the Command Pattern. Add, delete, drag-move, property changes, and slot adjustment actions are all captured by command objects, enabling seamless Undo / Redo.
  4. One-click “four-in-one” automated Excel report
    • Deeply integrates the open source QXlsx library and converts configuration results into expressive professional Excel reports with four worksheets:
      • Topology: intuitive graphical cabinet topology with intelligent cell merging.
      • BOM: lists each device type, physical slot position, quantity, and calculated unit price.
      • I/O Mapping: automatically derives and assigns logical I/O addresses for each signal channel.
      • Cost Analysis: calculates purchase costs for a single cabinet and the overall system, with support for multiple tax rates.
  5. Project lifecycle and packaging protection
    • Supports save validation, unsaved-exit prompts, and shortcut keys such as Ctrl+S / Ctrl+Shift+S.
    • Exports .ctproj compressed project packages with built-in ZIP serialization for collaboration and project archiving.
  6. Polished industrial theme and multilingual support
    • Uses a custom Catppuccin Mocha modern dark industrial QSS stylesheet to reduce eye strain during long configuration sessions.
    • Natively supports seamless runtime switching between Chinese and English.
ConfigTools/ (project root)
├── config/ # Default hardware library and system templates
├── docs/ # 11-phase development roadmap and detailed design docs
├── i18n/ # Translation source files (.ts / .qm)
├── src/ # Core business logic and UI code
│ ├── commands/ # Interaction command classes based on QUndoCommand
│ ├── core/ # Tree data model, configuration management, and ZIP serialization
│ ├── export/ # QXlsx report export and .ctproj read/write logic
│ ├── graphics/ # Cabinet, module, and wiring scene renderers (QGraphicsScene)
│ └── widgets/ # Property editor, device tree, and main window components
├── templates/ # Preset Excel templates for report export
├── tests/ # Unit test suite based on QtTest
└── third_party/ # Bundled dependencies, including QXlsx and miniz

[1]. about/index.md

[2]. README.md

QML-FFmpeg Project Overview and Technical Architecture

🔗 GitLab repository: Utilities/QML-FFmpeg

QML-FFmpeg is a high-performance, multi-threaded video player solution built with Qt Quick/QML, FFmpeg, and SDL2. The project focuses on a smooth migration from the traditional OpenGL/FBO offscreen rendering path to a modern Qt Quick Scene Graph / RHI (Rendering Hardware Interface) compatible rendering pipeline. This reduces the dependency on a specific graphics backend and provides cross-platform hardware-accelerated playback capabilities.

  1. RHI-compatible Scene Graph rendering
    • Replaces the outdated QQuickFramebufferObject path with Qt Quick Scene Graph nodes for video frame rendering, making the player compatible with the Qt 6 RHI rendering architecture.
  2. Decoupled multi-threaded pipeline
    • Separates demuxing, video decoding, and audio playback into independent threads, keeping the UI responsive while preserving smooth playback.
    • Uses SDL2 audio playback as the master clock for AV sync, providing stable audio-video synchronization.
  3. Three-stage smooth hardware acceleration fallback
    • Stage 1 (zero-copy GPU rendering): zero-copy rendering based on Direct3D11 / VA-API, mapping GPU textures directly.
    • Stage 2 (GPU-to-CPU copy rendering): uses av_hwframe_transfer_data() to copy NV12 and other hardware-decoded frames back to system memory, then submits them to the Scene Graph after high-performance color-space conversion. This path has resolved hardware frame pool deadlocks and avfilter filtering issues.
    • Stage 3 (pure CPU software decoding): when hardware acceleration initialization or transfer fails repeatedly, the player reloads within 5 frames and smoothly falls back to CPU decoding, such as YUV420P, without interrupting playback.
  4. Dual integration architecture
    • Supports both direct static integration of the player core in a standalone application and dynamic injection as an independent QML extension plugin.
  5. Ready-to-use deployment and validation
    • Provides CMake presets and automation scripts. On Windows, required FFmpeg/SDL2 DLLs and test videos are copied after build; Linux (Ubuntu) deployment is also designed to remain portable.
QML-FFmpeg (project root)
├── QML-FFmpeg.pro # Main subdirs project file, directly openable in Qt Creator
├── docs/ # Hardware/software validation checklists and technical design notes
├── QMLVideoPlayer-OpenGL/ # Standalone app mode: statically compiled player core and QML HUD
├── VideoPlugin-OpenGL/ # QML plugin module: dynamically loaded C++ plugin with shader resources
├── Video-QML/ # Plugin test shell: pure QML test app importing VideoPlugin 1.0
└── ThirdParty/ # Third-party dependencies: prebuilt FFmpeg & SDL2 binary SDKs via Git LFS

According to the upstream platform_hwa_checklist.md, the current validation status is:

  • Windows (NVIDIA physical machine): Stage 2 (GPU-to-CPU NV12 copy rendering) and Stage 3 software decoding have been fully validated, providing strong stability and fault tolerance. D3D11 zero-copy rendering is still pending final closure.
  • Linux (Ubuntu virtual machine): because there is no GPU passthrough, VA-API hardware decoding is unavailable. The application successfully falls back to Stage 3 pure software decoding, and playback plus the control UI work normally.
  • ARM / embedded platforms: planned work includes Rockchip MPP and Raspberry Pi V4L2 M2M hardware decoding, plus DRM / GLES zero-copy rendering.

[1]. about/index.md

[2]. platform_hwa_checklist.md

GitLab CI-CD Push to Repository

On gitlab-runner push changes to repository.

We assume that accessing repository with HTTPS method.

1. Add Personal Access Token (PAT) for Project

Section titled “1. Add Personal Access Token (PAT) for Project”

Ensure this token have the authority write_repository.

We assume that the variable name is GITLAB_PRIVATE_TOKEN, and value is the token created in first step.

Update git url with proper authority: git remote set-url origin "https://${GITLAB_PRIVATE_TOKEN}@gitlab.com/${CI_PROJECT_PATH}.git"

The .gitlab-ci.yml looks like:

stages:
- build
- deploy
build:
stage: build
script:
- echo "Building your application..."
deploy:
stage: deploy
before_script:
- git remote set-url origin "https://${GITLAB_PRIVATE_TOKEN}@gitlab.com/${CI_PROJECT_PATH}.git"
script:
- echo "Deploying your application..."
- git add .
- git commit -m "Automated commit by GitLab CI/CD"
- git push origin

[1]. GitLab-CI-CD-with-GitLab-Runner

[2]. Git-Configuration

Anaconda Commands

  • conda update conda Update conda itself.
  • conda update anaconda Update Anaconda itself.
  • conda update --all Update all packages.

gcc-g++ parameters1. Compilation steps

  1. Preprocess and generate .i file 2. Convert the preprocessed files into assembly language and generate .s files 3. From assembly to object code, generate .o file 4. Connect the target code and generate an executable program2. Common parameters
  2. -c
    Only activate preprocessing, compilation, and assembly, do not connect, and generate obj (*.o) files
  3. -o
    Specify target file name
  4. -S
    Preprocessing + compilation, no assembly connection
  5. -E
    Only preprocessing
  6. -O0/-O1/-O2/-O3
    There are 4 levels of compiler optimization, -O0 has no optimization, -O1 is the default value, and -O3 has the highest optimization level.
  7. -g
    Generate debugging information at compile time
  8. -ggdb
    Generate debugging information that gdb can use when possible
  9. -w
    Does not generate any warning message
  10. -Wall
    Generate all warning messages
  11. -Wl,-options1,-options2
    Connection options
  12. -LLIBRARY
    Search the specified function library when connecting
  13. -IDIRECTORY (this is a capital i)
    Specify additional header file search paths
  14. -nostartfiles -nostdlib
    It is necessary to run bare metal without Linux. -nostartfiles does not connect to the system standard startup files. -nostdlib includes -nostartfiles and standard libraries.
  15. -static
    Static linking shared library files
  16. -shared
    Connect multiple target files to generate a shared library file ending in .a

Makefile-first exploration

$* Target file name without extension
$+ All dependent files, separated by spaces, in order of appearance
$< The name of the first dependent file
$? All dependent files, separated by spaces, with modification dates later than the target’s creation date
$@ The full name of the target
$^ All dependent files, separated by spaces, do not contain duplicate dependent files
$% If the target is an archive member, this variable represents the archive member name of the target
  • Link: Link multiple .o files, or .o files and library files into an executable program that can be executed by the operating system- Static library: document file, a collection of multiple .o files; the suffix in Linux is .a; maintained and managed using the ar tool- Shared library: a collection of multiple .o files, generated by the compiler in a special way, usually executable in Linux; dynamically loaded into memory; multiple executable programs can share the code segment of the library file
TARGET…:PREREQUISITES…
COMMAND
…
  • TARGET: The target of the rule, the final file name & the intermediate process file name; it can be the name of the action executed by make- PREREQUISTIES: rule dependencies, generating a list of file names required by the rule target- COMMAND: The command line of the rule; each command must start with [Tab], but not everything starting with [Tab] is a command; make will process all lines starting with [Tab] after the first rule as a command line

4. make execution- The first rule of the Make file is executed by default, and the first target of this rule becomes the “final destination”- Makefile will only perform compilation of dependencies required for the final goal

Section titled “4. make execution- The first rule of the Make file is executed by default, and the first target of this rule becomes the “final destination”- Makefile will only perform compilation of dependencies required for the final goal”

(1). Try to write with a single target and multiple dependencies.

Section titled “(1). Try to write with a single target and multiple dependencies.”
  • How to update one or more target files under what circumstances#### b. Implicit rules
  • According to the rules automatically derived from a type of target file, dependent files are automatically generated according to the file suffix name and the target is updated using default commands.#### c. Variable definition#### d. indicator
  • Specify the actions that need to be performed when the make program reads the makefile, including:
  • Read the specified file as part of the makefile- > Decide to process or ignore a specific part of the Makefile- > Define a multi-line variable#### e. Comments

  • The content after the # character is used as a comment### (3). Naming of makefile files
  • make will search in the following order- GNUmakfile->makefile->Makefile- When it is not the above file name, you can specify the makefile read by make through “-f” or “–file”; multiple makefile files will be in the specified order.### (4). Include other makefile files
  • Use include:
Include FILENAMES
  • FILENAMES is the file name supported by the shell, and wildcards can be used;- Must not start with [Tab]- The default search path for files not found is: “./usr/gnu/include /usr/local/include /usr/include”; make will use rules to create files specified by the inlcude directive but not found
  • The first stage: read all makefile files and resume the dependency structure linked list between all targets and dependencies- Phase 2: Based on the relationship structure linked list in the first phase, determine which targets need to be updated and reconstructed
IMMEDIATE = DEFERRED
IMMEDIATE ?= DEFERRED
IMMEDIATE := IMMEDIATE
IMMEDIATE += DEFERRED or IMMEDIATE
Define IMMEDIATE
DEFERRED
Endef
  • Conditional statement: make expands the branch with correct preset conditions- Definition of rules: When make is executed, all rules are expanded according to the following pattern:
    If the target and dependency in the rule refer to other variables, they will be expanded immediately; while the variables in the rule command line will be expanded later.

(2). TARGETS can be multiple file names separated by spaces, and wildcards can be used.

Section titled “(2). TARGETS can be multiple file names separated by spaces, and wildcards can be used.”

(3). A(M) represents the member M of the archive file;

Section titled “(3). A(M) represents the member M of the archive file;”

(4). Usually the target has only one target file

Section titled “(4). Usually the target has only one target file”
  • The command can be on the same line as the command, separated by “;”- The command is on the next line of the dependency description. As an independent command line, it must start with [Tab].- $ in Makefile has a special meaning (indicating a reference to a variable or function). You need to use the symbol $ in the rules and write consecutive $$- For longer lines, you can use \ to branch### (6). Dependency type#### a. Regular dependencies
  • The order in which the rules need to be executed to rebuild the target- In what order and commands should you follow to rebuild dependency files?#### b. order-only dependency
  • Dependencies for updating dependencies- Start with the pipe symbol “|” as a dependency file of the target:
TARGETS:NORMAL-PREREQUISITES|ORDER-ONLY-PREREQUISITES
  • Regular dependency files can be empty; the same dependency appearing in both regular and order-only will be treated as regular### (7). Use wildcard characters in file names

a. The wildcard characters are exactly the same as those of the linux shell.

Section titled “a. The wildcard characters are exactly the same as those of the linux shell.”
  • The target and dependency of the rule- Appears in the command of the rule and is executed in the shell#### c. wildcard function
  • $(wildcard *.c) gets the .c file list- $(patsubst %.c,%.o,$(wildcard *.c))–Replace the .c file list with .o### (8). Command line and search directory
  • Use automation variables- > $^ represents the full pathname of all dependent files obtained through directory search- > $@ represents the target of the rule- > $< The first dependent file in the dependent file list obtained through directory search### (9). Library files and search directories
  • Specify the dependency file name “-lNAME”## 8. Variables

(1). Variable rules#### a. Use “=” or “define” to define#### b. Can be used to represent:- file name- compile options- Program running options parameters- Search directory listing for source files- Compile output directory#### c. Variable names do not include: “:”, “#”, “=”#### d. Variable names are case sensitive#### e. Automation variables### (2). Variable reference

Section titled “(1). Variable rules#### a. Use “=” or “define” to define#### b. Can be used to represent:- file name- compile options- Program running options parameters- Search directory listing for source files- Compile output directory#### c. Variable names do not include: “:”, “#”, “=”#### d. Variable names are case sensitive#### e. Automation variables### (2). Variable reference”
  • Use “$()” or “${}”- If “$” needs to be expressed, “$$” should be used.### (3). Variable definition
  • Recursive expansion variable “=” definition- Direct expansion variable “:=” definition- Define space “space:=$(nullstring)”- Conditional assignment operator: “?=”### (4). Advanced usage
  • “$(VAR:A,B)” replaces the words ending with “A” characters with “B”; same as patsubst### (5). Append variable value
  • “objects += another.o”### (6).override indicator
  • “override VARIABLE = VALUE”### (7). Target specified variable## 9. Conditional judgment
Ifeq($(CC),gcc)
$(CC) -o foo $(objects) $(lib)
Endif
  • Keywords- >Ifeq- >Ifned- >Ifdef- >Ifndef
1. $(subst FROM,TO,TEXT) replaces FROM in TEXT with TO 2. $(patsubst PATTERN,REPLACEMENT,TEXT) searches for words separated by spaces in TEXT and replaces those matching PATTERN with REPLACEMENT 3. $(strip STRINT) removes leading and trailing spaces 4. $(findstring FIND,IN) finds the FIND string in IN 5. $(sort LIST) sorts the words in LIST in alphabetical order 6. $(word N,TEXT) to get the Nth word in TEXT 7. $(wordlist S,E,TEXT) takes the word string from S to E from TEXT 8. $(words TEXT) counts the number of words in TEXT 9. $(firstword NAMES) takes the first word in NAMES### (2). File name processing function
1. $(dir NAMES) takes the directory part of the file name 2. $(notdir NAMES) takes the non-directory part of the file name 3. $(suffix NAMES) takes the file name suffix 4. $(addsuffix SUFFIX,NAMES) adds the suffix SUFFIX to each item of NAMES 5. $(addprefix PREFIX,NAMES) Add prefix PREFIX to NAMES 6. $(join LIST1,LIST2) connects two strings (corresponding index connection between lists) 7. $(wildcard PATTERN) lists the file names in the current directory that match the PATTERN format### (3). foreach function 1. $(foreach VAR,LIST,TEXT) assigns the words in LIST to VAR in sequence, and then executes the TEXT expression### (4). if function 1. $(if CONDITION,THEN-PART [,ELSE-PART])### (5). call function### (6). value function### (7). eval function### (8). origin function### (9). shell function### (10). Make control function 1. $(error TEXT) 2. $(warning TEXT)## 11. Execute make

(2). Specify the makefile “make -f MAKEFILE”

Section titled “(2). Specify the makefile “make -f MAKEFILE””

(3). Specify the ultimate goal 1. first goal of first rule 2. The command line specifies the target name in the makefile as the target “make TARGET_NAME” 3. Execution of alternative commands 4. Prevent specific files from being rebuilt 5. Replace variable definition 6. Use make to compile and test: “make -k”

Section titled “(3). Specify the ultimate goal 1. first goal of first rule 2. The command line specifies the target name in the makefile as the target “make TARGET_NAME” 3. Execution of alternative commands 4. Prevent specific files from being rebuilt 5. Replace variable definition 6. Use make to compile and test: “make -k””

12. Implicit rules of make 1. Use of implicit rules 1. make will start the corresponding implicit rules based on the source file type 2. There is always a target pattern and dependency pattern for implicit rules; 3. The same target mode can correspond to multiple dependency modes 2. pattern matching 3. universal rules 4. Rebuild embedded implicit rules 5. Default rules 6. Suffix rules 7. Implicit rule search algorithm 8. make automation variables| | |

Section titled “12. Implicit rules of make 1. Use of implicit rules 1. make will start the corresponding implicit rules based on the source file type 2. There is always a target pattern and dependency pattern for implicit rules; 3. The same target mode can correspond to multiple dependency modes 2. pattern matching 3. universal rules 4. Rebuild embedded implicit rules 5. Default rules 6. Suffix rules 7. Implicit rule search algorithm 8. make automation variables| | |”

|—|—| |$@|The target file name of the rule| |$%|a member of a static library| |$<|The first dependent file name of the rule| |$?|List of all dependent files that are newer than the target file| |$^|List of all dependent files of the rule| |$+|Similar to $^, keep duplicate files| |$(@D)|directory part of target file| |$(@F)|Target file except directory part|

  1. The makefile should contain “SHELL=/bin/sh” 2. Explicitly qualify recognized suffixes``` .SUFFIXES:
    .SUFFIXES: .c .o
3. Be careful with paths in rules

Memory management

1. Virtual address- kernel space- user space## 2. Physical address- ZONE_DMA- ZONE_NORMAL- ZONE_HIGHMEN## 3. Process and memory### (1). Code segment- Executable file operation instructions- Prevent illegal modification during runtime- read only### (2). Data segment- Store initialized global variables (statically allocated variables and global variables) in the executable file### (3). BSS section- Uninitialized global variables in the program### (4). Heap

Section titled “1. Virtual address- kernel space- user space## 2. Physical address- ZONE_DMA- ZONE_NORMAL- ZONE_HIGHMEN## 3. Process and memory### (1). Code segment- Executable file operation instructions- Prevent illegal modification during runtime- read only### (2). Data segment- Store initialized global variables (statically allocated variables and global variables) in the executable file### (3). BSS section- Uninitialized global variables in the program### (4). Heap”
  • Dynamically allocated memory segment in the program- Can be expanded or reduced- Malloc/free### (5). StackStack
  • Local variables temporarily created by the program- variables defined in the function- Parameters when calling the function## 4. Kernel space
  • direct mapping area- High-end memory linear address space- Dynamic memory mapping area- Permanent memory mapping area- Fixed mapping area The user space occupied by the process is divided into 5 different memory areas according to the principle of “address spaces with consistent access attributes are stored together” (access attribute: rwx)Including kernel image, physical page table, driver

Microsoft Word Font Size Reference

Chinese size name Point size
大特号 63
特号 54
初号 42
小初号 36
大一号 31.5
一号 28
小一号 24
二号 21
小二号 18
三号 16
小三号 15
四号 14
小四号 12
五号 10.5
小五号 9
六号 8
小六号 6.875
七号 5.25
八号 4.5

Reverse Proxy with Caddy on RHEL

This article introducing a method on reverse proxy with Caddy web server on RHEL.

sudo dnf install 'dnf-command(copr)'
sudo dnf copr enable @caddy/caddy
sudo dnf install caddy

2. Edit Caddy Config File in /etc/nginx/nginx.conf

Section titled “2. Edit Caddy Config File in /etc/nginx/nginx.conf”
{
email email@example.com
}
(tls) {
tls {
dns cloudflare {env.CF_DNS_API_TOKEN}
protocols tls1.2 tls1.3
}
}
(common_headers) {
encode gzip
}
(secure_headers) {
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-Frame-Options SAMEORIGIN
X-Content-Type-Options nosniff
}
}
xxx.example.com {
import tls
import common_headers
import secure_headers
reverse_proxy localhost:80
}

3. Edit Systemd Service File in /usr/lib/systemd/system/caddy.service

Section titled “3. Edit Systemd Service File in /usr/lib/systemd/system/caddy.service”
[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target
[Service]
Type=notify
User=caddy
Group=caddy
Environment="CF_DNS_API_TOKEN=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
ProtectHome=read-only
ReadWritePaths=/usr/share/caddy
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target

[1]. https://caddyserver.com/docs/

[2]. https://catcat.cc/post/h9bti/

[3]. RHEL9-Activation

[4]. RHEL9-RPM-Fusion-Repo

DNS-Distribution-with-SmartDNS

Mikrotik’s DNS always a confused problem. We are going to introduce SmartDNS to overcome it.

A previous post expalined how to do this.

In this section, we are going to demonstrate the DNS group and flow.

DNS records will be separate to 3 groups:

  • China List
    • resolve with public DNS server configured CHINA group in SmartDNS config file
  • GFW List
    • resolve with foreign DNS server configured GFW group in SmartDNS config file
  • Others
    • resolve with mixed DNS server configured OverSea group in SmartDNS config file
server-name SmartDNS
bind :53 -force-https-soa
cache-size 131072
cache-persist yes
cache-file /tmp/smartdns.cache
cache-checkpoint-time 120
prefetch-domain yes
serve-expired yes
serve-expired-ttl 0
serve-expired-reply-ttl 10
serve-expired-prefetch-time 86400
force-qtype-SOA 65
dualstack-ip-selection-threshold 10
dualstack-ip-allow-force-AAAA no
dualstack-ip-selection yes
rr-ttl 60
rr-ttl-min 1
rr-ttl-max 60
max-reply-ip-num 6
max-query-limit 0
response-mode fastest-response
log-level notice
log-file /var/log/smartdns/smartdns.log
log-size 128k
log-num 2
log-file-mode 644
audit-enable yes
audit-file /var/log/smartdns/smartdns-audit.log
audit-size 128k
audit-num 2
<!-- proxy-server socks5://127.0.0.1:1080 -name Proxy -->
server-https https://1.1.1.1/dns-query -group GFW -exclude-default-group -proxy Proxy -http-host one.one.one.one
server-tls 223.5.5.5:853 -group China -exclude-default-group
server-tls 8.8.8.8:853 -group OverSea
expand-ptr-from-address yes
mdns-lookup yes
speed-check-mode ping,tcp:80,tcp:443
domain-set -name chinalist -file /etc/smartdns/chinalist.conf
domain-set -name gfwlist -file /etc/smartdns/gfwlist.conf
nameserver /domain-set:chinalist/China
nameserver /domain-set:gfwlist/GFW
domain-rules /domain-set:gfwlist/ -speed-check-mode none

[1]. https://www.right.com.cn/forum/thread-8301362-1-1.html

[2]. IP-Address-List-Distribution-Based-on-RouterOS-and-Openwrt

Ubuntu dependency resolution and installation

1. Ubuntu platform package management tool apt/dpkg

Section titled “1. Ubuntu platform package management tool apt/dpkg”

dpkg is used to install .deb files, but it does not resolve module dependencies and does not care about the software in Ubuntu’s software warehouse. apt will resolve and install module dependencies and consult the software repository.

2. Check package dependencies in Ubuntuapt-cache depends XXX --recurse

Section titled “2. Check package dependencies in Ubuntuapt-cache depends XXX --recurse”

Check which packages XXX depends on, –recurse means recursive search apt-cache rdepends XXX Check which packages depend on XXX

3. Download the .deb fileapt-get install --no-recommends -d XXX

Section titled “3. Download the .deb fileapt-get install --no-recommends -d XXX”

The download file is located in the /var/cache/apt/archives/ directory apt-get download XXX The download file is the current directory

apt install *.deb
dpkg -i *.deb

Command differences reference Ubuntu platform package management tool apt/dpkg

5. sources.list file- File directory/etc/apt/sources.list- In the default sources.list file, the default configuration is the source of ubuntu.com

Section titled “5. sources.list file- File directory/etc/apt/sources.list- In the default sources.list file, the default configuration is the source of ubuntu.com”

Using-FIDO2-as-SSH-Authentication

FIDO2 is available in OpenSSH 8.2 version, which is much more convenience then OpenPGP.

  • A Yubikey Device, or other device support FIDO2.
ssh-keygen -t ed25519-sk -O resident -f ~/.ssh/id_ ed25519-sk
ssh-add -K
ssh-add -L

[1].https://blog.bloade.com/2022/03/20/%E4%B8%BAopenssh%E9%85%8D%E7%BD%AEfido2%E8%AE%A4%E8%AF%81/

[2].SSH-Configuration

Let's Encrypt with Certbot

This post is going to introducing how to encrypt your website using HTTPS, with Certbot.

All the steps based on CentOS/RHEL(Red Hat Enterprise Linux).

  • OS: CentOS/RHEL
  • Packages: certbot (Optional: certbot-dns-cloudflare)
  • HostName: example.com

Install certbot on your system with dnf package manager:

sudo dnf install python3-certbot

If you wish to use dns-01 challenge, we take cloudflare as an example, you should install certbot-dns-cloudflare plugin:

sudo dnf install python3-certbot-dns-cloudflare

Make sure you have set your hostname to your host ip.

Allow port 80 on your host:

sudo firewall-cmd --add-port=80/tcp

(3). Issuing SSL Certificates with Certbot

Section titled “(3). Issuing SSL Certificates with Certbot”

Using the following command to issue a SSL certificate from Let’s Encrypt

sudo certbot certonly -d example.com

The private key and public key will be stored in folder /etc/letsencrypt/live/example.com/.

(4). Config Your Site with SSL Certificates

Section titled “(4). Config Your Site with SSL Certificates”

This is not the keypoint of this post, configuration should be varies depending on the web server used. Please refer to other resources online.

Optional-1. Config Nginx with Certbot automatically

Section titled “Optional-1. Config Nginx with Certbot automatically”

If you are using Nginx, it would be convenient by using --nginx parameter, replace the command in step(3):

sudo certbot certonly -d example.com --nginx

Then all configurations will be done in nginx file located in /etc/nginx/conf.d/example.com.conf

The dns_cloudflare plugin automates the process of completing a dns-01 challenge (DNS01) by creating, and subsequently removing, TXT records using the Cloudflare API.

The following command will do this operation:

sudo certbot certonly \
--dns-cloudflare \
--dns-cloudflare-credentials ~/PATH_TO_CF_KEY/cf_key.txt \

In this section, cf_key.txt contains the API TOKEN or Global API Key from Cloudflare, here is the example of this two structure:

# Cloudflare API token used by Certbot
dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567
# Cloudflare API credentials used by Certbot
dns_cloudflare_email = cloudflare@example.com
dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234

[1].https://certbot-dns-cloudflare.readthedocs.io/en/stable/

[2].https://developers.cloudflare.com/fundamentals/api/get-started/create-token/

[3].https://developers.cloudflare.com/fundamentals/api/get-started/keys/

[4]. Reverse-Proxy-with-Nginx-on-RHEL

Git Configuration

In this article, we introduces git configuration for basic use.

Remarkablely, configurations for symbolic links are supported on Windows with extra settings.

The purpose we have to point out, is the git compatibility on both Windows and Unix like system.

  • Config User Name
git config --global user.name 'NAME'
  • Config User Email
git config --global user.email 'EMAIL@EXAMPLE.COM'
  • Config signingkey
git config --global user.signingkey XXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXX: Personal gpg private key in LONG or SHORT format

  • Config GPG
git config --global gpg.program C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe
  • Config Commit and Tag
git config --global commit.gpgsign true
git config --global tag.gpgsign true

3. Config Git on Windows for compatibility with Unix like system

Section titled “3. Config Git on Windows for compatibility with Unix like system”
  • Config filemode authority
git config --global core.filemode false
  • Config CRLF and LF auto change
git config --global core.autocrlf true
  • Config case-sensitive
git config --global core.ignorecase false
  • Config symlinks
git config --global core.symlinks true
  • Enable Develop Mode on Windows10 and later
  • Enable symlinks on installing git on Windows
  • Group Policy:
    • Navigate to create user permission to create symbolic links:
    • Computer Configuration → Windows Settings → Security Settings → Local Policies → User Rights Assignment → Create symbolic links
    • type the user name and click “Check Names” then OK.
git config --global filter.lfs.smudge "git-lfs smudge --skip -- %f"
git config --global filter.lfs.process "git-lfs filter-process --skip"
[core]
symlinks = true
autocrlf = true
filemode = false
ignorecase = false
[user]
name = User Name
email = Username@example.com
signingkey = XXXXXXXXXXXXXXXX
[commit]
gpgsign = true
[tag]
gpgsign = true
[gpg]
program = C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe
[filter "lfs"]
smudge = git-lfs smudge --skip -- %f
process = git-lfs filter-process --skip
mklink [[/d] | [/h] | [/j]] <link> <target>

/d Creates a directory symbolic link. By default, this command creates a file symbolic link.

/h Creates a hard link instead of a symbolic link.

/j Creates a Directory Junction.

<link> Specifies the name of the symbolic link being created.

<target> Specifies the path (relative or absolute) that the new symbolic link refers to.

/? Displays help at the command prompt.

git tag XXXX
git tag -d <tagname>
git push origin --delete <tagname>
git push origin <tagname>
git branch -d <branchname>
git push origin --delete <branchname>

[1]. https://git-scm.com/book/en/v2/Git-Tools-Signing-Your-Work

[2]. https://github.com/git-for-windows/git/wiki/Symbolic-Links

[3]. https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/mklink

[4]. 从一个git仓库提交代码到另一个仓库

[5]. GitLab-CI-CD-Push-to-Repository

LogRotate

LogRotate is a log management tool, which enables log files’ cutting, deleting and creating, and triggered by crontab.

The default config file located/etc/logrotate.conf In default config file, the config folder/etc/logrotate.dis included by default. Which means, config files added in this folder will be executed by logrotate process.

/var/log/***.log { # The target log file
LOG_CONFIG_PARAMETERS # The parameters for logrotate
}
  • daily: The cutting cycle is daily
  • weekly: The cutting cycle is weekly
  • monthly: The cutting cycle is monthly
  • yearly: The cutting cycle is every year
  • size 50M
  • rotate 1
  • maxage 1

(5). Do not dump files with specified extensions

Section titled “(5). Do not dump files with specified extensions”
  • tabooext [+] list
  • missingok
  • copytruncate/nocopytruncate
  • create mode owner group
  • nocreate
  • nocompress
  • compress
  • delaycompress
  • nodelaycompress

(11). Execute before all other instructions are completed

Section titled “(11). Execute before all other instructions are completed”
  • prerotate
  • endscript

(12). Execute after all other instructions are completed

Section titled “(12). Execute after all other instructions are completed”
  • postrotate
  • endscript
  • sharedscripts

(14). The error message is sent to the specified email address

Section titled “(14). The error message is sent to the specified email address”
  • errors address

(15). Send the dumped log file to the specified E-mail address

Section titled “(15). Send the dumped log file to the specified E-mail address”
  • mail address
  • nomail
  • ifempty
  • notifempty
  • olddir directory
  • noolddir
  • dateext
  • dateformat
  • dateyesterday
  • extension

[1]. https://blog.csdn.net/xiaojin21cen/article/details/122309230

[2]. https://linux.die.net/man/8/logrotate

WebDav Based On Caddy

This article introducing a method on servering webdav service with CaddyServer.

The easiest way to install caddy is using package manager.

  • On Debian/Ubuntu

    sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
    | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
    | sudo tee /etc/apt/sources.list.d/caddy-stable.list
    sudo apt update
    sudo apt install caddy
  • On RHEL/CentOS/RockyLinux

    dnf install 'dnf-command(copr)'
    dnf copr enable @caddy/caddy
    dnf install caddy
  • Add Packages Online

    sudo caddy add-package XXX

    XXX is the package name, which always start with github.com/xxxxxx.

    It’s easy to find packages name from Download Page.

    Examples:

    install webdav module:

    sudo caddy add-package github.com/mholt/caddy-webdav

  • Add Packages Manually

    Select and Download CaddyServer with modules from Download Page.

    Replace executable caddy file with downloaded:

    sudo mv caddy /usr/bin
    sudo chmod +x /usr/bin/caddy
    sudo restorecon /usr/bin/caddy
    sudo chown root:root /usr/bin/caddy

Due to the configuration in default systemd file, the parameter ProtectSystem=full, caddy lose the permission on writing /usr, /boot and /etc.(Reference-2 for details).

  • Add ReadWrite permission to caddy web folder /usr/share/caddy Adding paramter to service file /usr/lib/systemd/system/caddy.service under [service] lable:

  • Reload systemd

    sudo systemctl daemon-reload

4. Make caddy has authority to access files

Section titled “4. Make caddy has authority to access files”
  • Change the owner of /path/to/data with caddy

    sudo chwon caddy /path/to/data -R

  • Add caddy to the group of the files’ owner

    sudo usermod -a -G $GROUP

  • webdav Module Configure introduction is available: caddy-webdav

    {
    basicauth {
    username password_generate_by_openssl
    }
    root * /path/to/data/
    route {
    rewrite /webdav /webdav/
    webdav /webdav/* {
    prefix /webdav
    }
    }
    file_server browse
    }
  • global config set webdav before file_server:

    {
    order webdav before file_server
    }

[1]. https://caddyserver.com/docs/install

[2]. https://www.redhat.com/sysadmin/mastering-systemd

[3]. https://github.com/abiosoft/caddy-webdav

[4]. Reverse-Proxy-with-Caddy-on-RHEL

Webhook Based On Caddy

This article introducing a method on building webhook service with CaddyServer.

The easiest way to install caddy is using package manager.

  • On Debian/Ubuntu

    sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
    | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
    | sudo tee /etc/apt/sources.list.d/caddy-stable.list
    sudo apt update
    sudo apt install caddy
  • On RHEL/CentOS/RockyLinux

    dnf install 'dnf-command(copr)'
    dnf copr enable @caddy/caddy
    dnf install caddy
  • Add Packages Online

    sudo caddy add-package XXX

    XXX is the package name, which always start with github.com/xxxxxx.

    It’s easy to find packages name from Download Page.

    Examples:

    install webhook module:

    sudo caddy add-package github.com/WingLim/caddy-webhook

    install exec module:

    sudo caddy add-package github.com/mholt/caddy-events-exec

  • Add Packages Manually

    Select and Download CaddyServer with modules from Download Page.

    Replace executable caddy file with downloaded:

    sudo mv caddy /usr/bin
    sudo chmod +x /usr/bin/caddy
    sudo restorecon /usr/bin/caddy
    sudo chown root:root /usr/bin/caddy

Due to the configuration in default systemd file, the parameter ProtectSystem=full, caddy lose the permission on writing /usr, /boot and /etc.(Reference-2 for details).

  • Add ReadWrite permission to caddy web folder /usr/share/caddy Adding paramter to service file /usr/lib/systemd/system/caddy.service under [service] lable:

    ReadWritePaths=/usr/share/caddy

  • Reload systemd

    sudo systemctl daemon-reload

  • Webhook Module Configure introduction is available: caddy-webhook

    route /webhook {
    webhook {
    repo https://github.com/WingLim/winglim.github.io.git
    path /usr/share/caddy
    branch master
    depth 1
    type github/gitlab/gitee/gogs/bitbucket
    command
    username
    password
    key
    token
    submodule
    }
    }
  • Exec Module Configure introduction is available: caddy-exec

    route /webhook {
    exec {
    command git
    args pull
    directory /usr/share/caddy
    log file /var/log/caddy/git.log
    }
    }

[1]. https://caddyserver.com/docs/install

[2]. https://www.redhat.com/sysadmin/mastering-systemd

[3]. https://github.com/abiosoft/caddy-exec

[4]. https://github.com/WingLim/caddy-webhook

[5]. Reverse-Proxy-with-Caddy-on-RHEL

GnuPG Home Configuration on Winodws

The default GnuPG home is ~/.gnupg on Linux, and ~\AppData\Roaming\gnupg on Windows.

To change the gnupg home on Windows, set a System Variables in Environment Variables:

Variable = GNUPGHOME
VALUE = ~\gnupg

You should do the commands one by one.

[1].https://www.gnupg.org/documentation/manuals/gnupg/GPG-Configuration.html

[2].https://www.gnupg.org/gph/en/manual/r1616.html

[3]. OpenPGP-初探

Yubikey-PIV-as-SSH-Key

Use Yubikey as SSH Key.

1. Install OpenSC and YubiKey Manager (CLI only)

Section titled “1. Install OpenSC and YubiKey Manager (CLI only)”
sudo apt update
sudo apt install opensc yubikey-manager

2. If this is a new Yubikey, change the default PIV management key, PIN and PUK.

Section titled “2. If this is a new Yubikey, change the default PIV management key, PIN and PUK.”

The ykman tool can generate a new management key for you. For the PIN and PUK you’ll need to provide your own values (6-8 digits).

ykman piv change-management-key --touch --generate
ykman piv change-pin -P 123456
ykman piv change-puk -p 12345678

Make sure you save the generated password somewhere secure such as a password manager. The management key is needed any time you generate a keypair, import a certificate or change the number of PIN or PUK retries

The PUK should also be kept somewhere safe. This is used if the PIN is entered incorrectly too many times.

  1. Ensure CCID mode is enabled on the Yubikey
ykman mode

If CCID is not in the list, enable it by adding CCID to the list, e.g.

ykman mode OTP+FIDO+CCID

(This assumes you had OTP+FIDO previously, and still want them enabled.)

  1. Generate a PIV key and output the public key
ykman piv generate-key 9a pubkey.pem

Alternatively, you can require that you have to touch the Yubikey every time the slot is accessed:

ykman piv generate-key --touch-policy always 9a pubkey.pem

This is an RSA 2048-bit key by default. Depending which Yubikey you have, you can change it using -a / --algorithm.

(9a is the PIV authentication slot.)

  1. Generate a self-signed X.509 certificate
ykman piv generate-certificate -s "SSH key" 9a pubkey.pem
  1. Setting the system path

Go to Control Panel → System and Security → System → Advanced system setting

Click “Environment Variables…“

Under System Variables, highlight “Path“ and click “Edit…“

Click “New“ and add the absolute path to Yubico PIV Tool\bin

  1. Set ssh config file

Open PowerShell and run the following:

New-Item -Path $env:USERPROFILE\.ssh\ -Name "config" -ItemType "file" -Value `
'PKCS11Provider "C:\Program Files\Yubico\Yubico PIV Tool\bin\libykcs11.dll"'
  1. Export your SSH public key from the Yubikey
ssh-keygen -D /usr/local/lib/opensc-pkcs11.so

And that’s all the hard stuff done.

Now just add the public key to your authorized_keys file on a remote host and try to use it:

ssh -I /usr/local/lib/opensc-pkcs11.so -i /usr/local/lib/opensc-pkcs11.so \
-o IdentitiesOnly=yes server.example.com

You should be prompted for your Yubikey’s PIV PIN.

You can add the PKCS11 library to ssh-agent.

ssh-add -s /usr/local/lib/opensc-pkcs11.so

Once more you will be prompted for your PIN, and from there SSH authentication will happen as usual.

To configure ssh to use the Yubikey’s SSH key, use the PKCS11Provider config option instead of IdentityFile, e.g.:

Host foo
PKCS11Provider /usr/local/lib/opensc-pkcs11.so
IdentitiesOnly yes
  • When SSHing, you may get prompted with the key’s subject name, like Enter PIN for 'SSH key':. But if you add the key to the agent, you’ll get a prompt like Enter passphrase for PKCS#11:. These are the same PIN (your PIV PIN).

  • If you remove the key from ssh-agent using ssh-add -d or ssh-add -D, you’ll have to either remove and re-add the PKCS library to the agent or restart the agent.

    • To re-add the library run
      ssh-add -e /usr/local/lib/opensc-pkcs11.so
      ssh-add -s /usr/local/lib/opensc-pkcs11.so

[1].https://github.com/jamesog/yubikey-ssh

[2].SSH-Configuration

FFmpeg Development Environment

Build a FFmpeg developing environment on Ubuntu-22.04-LTS with Qt and SDL.

Update all repositories.

sudo apt update && apt upgrade

Resolved in Ubuntu 22.04.2 LTS

On Video decoding/encoding with FFmpeg

  • x264

    • libavcodec58
      • libavcodec-extra58
    • libavformat58
      • libavformat-extra58
    • libavutil56
    • libc6
    • libffms2-5
    • libgpac11
    • libswscale5
    • libx264-163
  • x265

    • libc6
    • libstdc++6
    • libx265-199
    • libx265-199
  • libx264-dev

    • libx264-163
  • libx265-dev

    • libx265-199
  • libass-dev

    • libass9
    • libfontconfig1-dev
      • libfontconfig-dev
    • libfreetype-dev
    • libfribidi-dev
    • libharfbuzz-dev
  • libfdk-aac-dev

    • libfdk-aac2
    • pkg-config
      • pkg-config:i386
      • pkgconf
  • libfreetype-dev

    • libfreetype6
    • libbrotli-dev
    • libc6-dev
    • libc-dev
      • libc6-dev
    • zlib1g-dev
    • libz-dev
      • zlib1g-dev
  • libmp3lame-dev

    • libmp3lame0
  • libopus-dev

    • libopus0
  • libvorbis-dev

    • libogg-dev
    • libvorbis0a
    • libvorbisenc2
    • libvorbisfile3
  • libvpx-dev

    • libvpx7

On Audio decoding/encoding with SDL2:

  • libsdl2-dev
    • libasound2-dev
    • libdbus-1-dev
    • libdecor-0-dev
    • libdrm-dev
    • libegl1-mesa-dev
    • libgbm-dev
    • libgl-dev
    • libgles-dev
    • libglu1-mesa-dev
    • libibus-1.0-dev
    • libpulse-dev
    • libsdl2-2.0-0
    • libsndio-dev
    • libudev-dev
    • libwayland-dev
    • libx11-dev
    • libxcursor-dev
    • libxext-dev
    • libxfixes-dev
    • libxi-dev
    • libxinerama-dev
    • libxkbcommon-dev
    • libxrandr-dev
    • libxss-dev
    • libxt-dev
    • libxv-dev
    • libxxf86vm-dev
    • libc6
    • libopengl0
    • libx11-6

On configuring FFmpeg:

  • yasm
    • libc6

Install all dependencies with following command:

sudo apt install yasm gcc g++ cmake make \
x264 x265 libx264-dev libx265-dev \
libass-dev libfdk-aac-dev libvorbis-dev \
libfreetype-dev libmp3lame-dev libopus-dev \
libvpx-dev libsdl2-dev

Install Qt with Qt Online Installer.

It’s better to install Qt with USTC’s mirror.

Install with commands: .\qt-unified-windows-x86-online.exe --mirror https://mirrors.ustc.edu.cn/qtproject

DO NOT install Qt with sudo command nor with user ROOT.

If you prefer Qt Online Installer, libxcb-xinerama.so.0 is needed. To install this dependency, run following command sudo apt install libxcb-xinerama0.

It’s possible to install Qt from source. Follow the instruction, and the script is available here.

Download FFmpeg from Offical Web Site, install with compile commands below:

wget http://ffmpeg.org/releases/ffmpeg-4.2.9.tar.xz
tar -xvf ffmpeg-4.2.9.tar.xz
cd ffmpeg-4.2.9
sudo ./configure --enable-gpl --enable-libass --enable-libfdk-aac \
--enable-libfreetype --enable-libmp3lame --enable-libopus \
--enable-libvorbis --enable-libvpx --enable-libx264 \
--enable-libx265 --enable-pic --enable-shared --enable-nonfree \
--prefix=/usr/local/ffmpeg-4.2.9
make -j8
sudo make install

SDL2 has installed with system, headers installed when dependencies installed.

One-key environment installing script is provided:

Qt Framework will be installed via local compile, and downloaded opensource from USTC Mirror.

Qt will be installed in path: /usr/local/qt-5.15.2

  • Add FFmpeg to INCLUDEPATH in .pro file.

    • Add dynamic link -lavfilter -lavformat -lavdevice -lavcodec -lpostproc -lswscale -lavutil -lswresample to LIBS in .pro file for FFmpeg;
  • Add -lSDL2main -lSDL2 for SDL.

[1].https://qt.io

[2].http://mirrors.ustc.edu.cn/help/qtproject.html

[3].http://ffmpeg.org

[4].https://libsdl.org/

[5].https://blog.csdn.net/a1367666195/article/details/126055594

[6].https://askubuntu.com/questions/1298645/shared-library-not-found-for-pyqt5-libxcb-xinerama-so-0-not-found

[7]. Install-Qt-From-Source

[8]. VSCode-C-CPP-Environment

Install Qt From Source

Install Qt from opensouce, via local compile.

Take Qt-5.15.2 as an example.

Download Qt-5.15.2 from official site, or from mirror, like UTSC.

wget http://mirrors.ustc.edu.cn/qtproject/official_releases/qt/5.15/5.15.2/single/qt-everywhere-src-5.15.2.tar.xz
sudo apt install libX11-dev libXext-dev libXtst-dev -y
tar -xvf qt-everywhere-src-5.15.2.tar.xz
cd qt-everywhere-src-5.15.2
./configure -prefix /usr/local/qt-5.15.2 -opensource -developer-build \
-confirm-license -nomake tests -nomake examples
make -j8
sudo make install

Qt will be installed to /usr/local/qt-5.15.2, due to configure above.

[1]. https://qt.io

[2]. http://mirrors.ustc.edu.cn/help/qtproject.html

Container on Mikrotik

From Mikrotik ROS 7.4 Beta 4, Mikrotik add new feature of Container.

Configurations are based on Mikrotik RouterOS 7.13.1 .

Login Terminal in RouterOS, with following commands:

/system/device-mode/update container=yes

You will need to confirm the device-mode with a press of the reset button, or a cold reboot, if using container on X86.

(1). Add bridge veth interface for the container:

Section titled “(1). Add bridge veth interface for the container:”
/interface/veth/add name=veth1 address=172.17.0.2/24 gateway=172.17.0.1

(2). Create a bridge for containers and add veth to it:

Section titled “(2). Create a bridge for containers and add veth to it:”
/interface/bridge/add name=containers
/ip/address/add address=172.17.0.1/24 interface=containers
/interface/bridge/port add bridge=containers interface=veth1
/ip/firewall/nat/add chain=srcnat action=masquerade src-address=172.17.0.0/24

(1). Add host veth interface for the container:

Section titled “(1). Add host veth interface for the container:”
/interface/veth/add name=veth1 address=LAN_ADDRESS gateway=GATE_WAY_OF_LAN
/interface/bridge/port add bridge=LAN_BRIDGE interface=veth1
/container/mounts/add name=smartdns src=/smartdns.conf dst=/etc/smartdns/smartdns.conf
/container/config/set registry-url=https://registry-1.docker.io
/container/add remote-image=dashdreams/smartdns:latest interface=veth1 \
root-dir=/smartdns hostname=smartdns mounts=smartdns workdir=/root
/container/add file=smartdns.tar interface=veth1 root-dir=/smartdns \
hostname=smartdns mounts=smartdns workdir=/root
/container/start 0

6. Forward ports to internal container (optional)

Section titled “6. Forward ports to internal container (optional)”

Ports can be forwarded using dst-nat (where 192.168.88.1 routers IP address):

/ip firewall nat
add action=dst-nat chain=dstnat dst-address=192.168.88.1 dst-port=5353 protocol=tcp to-addresses=172.17.0.2 to-ports=53

How to get a local container image:

docker pull dashdreams/smartdns:latest@sha256:XXXXXXXXXXXXXXXXXXXXXXX
docker save dashdreams/smartdns > smartdns.tar

[1]. https://help.mikrotik.com/docs/display/ROS/Container

[2]. http://www.irouteros.com/?p=2712

[3]. Build-Container-Image-with-Podman

IP Address List Distribution Based on RouterOS and Openwrt

IP address list distribution with CNIP.

Configurations are based on Mikrotik RouterOS 7.6 .

A bypass routre with Openwrt required.

CN IP address list can be found from

Clang.CN

IPIP

RealIPDatabase

It’s possible to get CN IP list by running scripts below on linux:

curl 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'|\
grep ipv6 | grep CN | awk -F\| \
'{ printf("%s/%d\n", $4, 32-log($5)/log(2)) }' | \
sed -e 's/^/add address=/g' -e 's/$/ list=CNIP/g'|\
sed -e $'1i\\\n/ipv6 firewall address-list' \
-e $'1i\\\nremove [/ipv6 firewall address-list find list=CNIP]'|\
sed '$a /file remove CNIPv6.rsc'>CNIPv6.rsc
curl 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'|\
grep ipv4 | grep CN | awk -F\| \
'{ printf("%s/%d\n", $4, 32-log($5)/log(2)) }' |\
sed -e 's/^/add address=/g' -e 's/$/ list=CNIP/g' \
-e 's/$/ comment="CNIP"/g' |\
sed -e $'1i\\\n/ip firewall address-list' \
-e $'1i\\\nremove [/ip firewall address-list find list=CNIP]' |\
sed '$a \/' |sed '$a /file remove CNIPv4.rsc'>CNIPv4.rsc

Contains both IPv6 and IPv4 addresses.

The address list may look like this:

/ip firewall address-list
add list=CNIP address=x.x.x.x/xx
add list=CNIP address=x.x.x.x/xx
...
...
...
add list=CNIP address=x.x.x.x/xx

Open WinBox, and upload CNIPv4.rsc to RouterOS, than open Terminal, and run import CNIPv4.rsc.

In Terminal run command: /routing/tables/add name=OP fib

Add Proxy List in Firewall:

/ip/firewall/address-list/add name=proxy address=192.168.1.1-192.168.1.200

We take IP address range 192.168.1.1–192.168.1.200 to proxy list.

Mark Non-CN IP destnation address

add action=mark-routing chain=prerouting comment="ProxyRoute" \
src-address=proxy dst-address=!CNIP dst-address-type=!local \
new-routing-mark=OP passthrough=yes

Add another rule to accept openwrt’s flow

add action=accept chain=prerouting comment="BypassOP" \
src-address=192.168.1.254

Assume openwrt’s local ip is 192.168.1.254

Config route table to openwrt:

/ip/route/add dst-address=0.0.0.0 gateway=192.168.1.254 \
check-getway=ping routing-table=OP distance=1 \
scope=30 target-scope=10

Change PPPOE’s distance to 2:

/interface/pppoe-client/set pppoe-CMCC default-route-distance=2

4. Change Distribution if Bypass Router Down

Section titled “4. Change Distribution if Bypass Router Down”
  • Shutdown distribution when openwrt down
  • Turn distribution when openwrt up
/tool/netwatch/add host=192.168.1.254 type=simple interval=60 \
up-script=OPUP.rsc down-script=OPDOWN.rsc

Up Script:

add dont-require-permissions=yes name=OPUP.rsc owner=admin policy=\
ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="/\
ip firewall mangle enable number=???\r\
\n/ip firewall mangle enable number=???\r\
\n/ip route enable number=0\r\
\n/ip/dns/cache/flush"

Down Script:

add dont-require-permissions=yes name=OPDOWN.rsc owner=admin policy=\
ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="/\
ip firewall mangle disable number=???\r\
\n/ip firewall mangle disable number=???\r\
\n/ip route disable number=0\r\
\n/ip/dns/cache/flush"

??? is index number of mangle rules set in MangleRules

[1]. https://www.shawnleetttt.cyou/posts/71e7c44b/

[2]. https://idndx.com/high-availability-when-split-routing-using-routeros-and-raspberrypi/

[3]. DNS-Distribution-with-SmartDNS

[4]. IPv6-Configure-on-Mikrotik-RouterOS-v7.x

IPv6 Configure on Mikrotik RouterOS v7.x

IPv6 configuration on Mikrotik RouterOS is much more complicated than Merlin on ASUS. We are going to config IPv6 in this aritical.

Configurations are based on Mikrotik RouterOS 7.6 .

Login Terminal in RouterOS, with following commands:

# Accept ISP RA, Get IPv6 Address with SLAAC
/ipv6 settings set accept-router-advertisements=yes
# Configure DHCPv6 client:
# - Add default route: yes
# - WAN interface: pppoe-ether1
# - IPv6 address pool: IPv6 (You can change to whatever you want)
# - Prefix length for DHCPv6 server's offering cascading routers: 60
# - Request LAN prefix from ISP
/ipv6 dhcp-client add add-default-route=no interface=pppoe-ether1 \
pool-name=IPv6 pool-prefix-length=60 \
request=prefix

CMCC in Nanjing, Jiangsu provide /60 prefix, if prefix length less than /63, it’s impossible to use DHCPv6.

# Accept DHCPv6 client prefix delegation
/ipv6 firewall filter add action=accept chain=input \
comment="Accept DHCPv6 client prefix delegation" \
dst-port=546 protocol=udp src-address=fe80::/10

This rule is default, if you configured your router with default script.

/ipv6 address add address=::1 from-pool=IPv6 interface=bridge
# Delegate IPv6 addresses from pool `delegation`
# Lease is valid for 1 day
/ipv6 dhcp-server add address-pool=IPv6 \
interface=bridge lease-time=7d name=Home-IPv6

[1]. https://wu.renjie.im/blog/network/ros-dhcpv6/zh-cn/

Commit code from one git repository to anotherIn actual development, branch_a in the repro_a warehouse is independently transformed into a new warehouse repro_b. Mainly relies on`git remote`for implementation.

1. Submit the current code to another remote git repositoryIf warehouse repo_a is currently located in branch_a, it is required to extract all the data of branch_a (including submission history) and create a new warehouse repo_b. It is assumed here that the warehouse repo_b has been created.The basic syntax ofgit remote addis as follows. name and url are required.

Section titled “1. Submit the current code to another remote git repositoryIf warehouse repo_a is currently located in branch_a, it is required to extract all the data of branch_a (including submission history) and create a new warehouse repo_b. It is assumed here that the warehouse repo_b has been created.The basic syntax ofgit remote addis as follows. name and url are required.”
git remote add [-t <branch>] [-m <master>] [-f] [--[no-]tags] [--mirror=<fetch|push>] <name> <url>

(1). Add the URL of the warehouse repo_b to the remote of the working warehouse.

Section titled “(1). Add the URL of the warehouse repo_b to the remote of the working warehouse.”
git remote add origin_repo_b git@server_ip:/path/repo_b.git

(origin_repo_b: the name you choose, as long as it does not duplicate the existing remote name) (git@server_ip:/path/repo_b.git:repo_b’s remote path)

git push origin_repo_b branch_a

(origin_repo_b: the name of the remote warehouse repo_b) (branch_a: branch_a branch of warehouse repo_a)

(3). Clone the warehouse repo_b and check whether the push is successful.

Section titled “(3). Clone the warehouse repo_b and check whether the push is successful.”

2. Submit the same code to multiple different git hosting servers (multiple git repositories)The method is very similar, mostly using the commandgit remote set-url --add [--push] <name> <newurl>Assume that a new warehouse repo_c is added to the remote git server, and the codes submitted by repo_b and repo_c must be consistent.

Section titled “2. Submit the same code to multiple different git hosting servers (multiple git repositories)The method is very similar, mostly using the commandgit remote set-url --add [--push] <name> <newurl>Assume that a new warehouse repo_c is added to the remote git server, and the codes submitted by repo_b and repo_c must be consistent.”

(1). Configure remote repo_c into the current working local git repository

Section titled “(1). Configure remote repo_c into the current working local git repository”
git remote set-url --add origin_repo_b git@192.168.1.101:~/project/repo_c.git

What this sentence means is that the remote warehouse git@192.168.1.101:~/project/repo_c.git is also added to the name origin_repo_b for management.

(2). Submit the code to remote warehouse repo_b and remote warehouse repo_c at the same time

Section titled “(2). Submit the code to remote warehouse repo_b and remote warehouse repo_c at the same time”
git push origin_repo_b branch_a

(3). fatal: refusing to merge unrelated histories

Section titled “(3). fatal: refusing to merge unrelated histories”
git pull origin master --allow-unrelated-histories

GitLab CI-CD with GitLab-Runner

Run GitLab-Runner in container for GitLab CI/CD.

podman run --detach \
--privileged \
--name gitlab-runner \
--network host \
-v ${PWD}/config:/etc/gitlab-runner:z \
docker.io/gitlab/gitlab-runner:latest
podman exec -it gitlab-runner gitlab-runner register

Config the runner with instructions.

[1]. https://docs.gitlab.com/runner/

[2]. https://zhuanlan.zhihu.com/p/385110311

[3]. Podman-Volumes-and-SELinux

[4]. Manage-Podman-Container-With-Systemd

Mount Disk in Linux on Boot

BrefAutomatically mount the hard drive at boot

Section titled “BrefAutomatically mount the hard drive at boot”

Before mounting the disk, you need to know the path orUUIDof each disk. At this time, you mainly rely on the two instructionsfdiskandblkid. The former instruction obtains the partition information, and the latter instruction obtains the attributes of theBlock deviceblock device.``` $ sudo blkid /dev/sda1: LABEL=“Win10” UUID=“C4A0E65EA0E65708” TYPE=“ntfs” PARTUUID=“6190c592-01” /dev/sda2: UUID=“AE3C137D3C133FAF” TYPE=“ntfs” PARTUUID=“6190c592-02” /dev/sdb1: LABEL=“Apps” UUID=“0000678400004823” TYPE=“ntfs” PARTLABEL=“Basic data partition” PARTUUID=“45ed07d2-c9e3-4167-8868-3e33f62784e1” /dev/sdb2: LABEL=“Data” UUID=“0000678400004823” TYPE=“ntfs” PARTLABEL=“Basic data partition” PARTUUID=“2a8b4bf1-8357-4d65-bed4-f73f01b96431” /dev/sdb3: LABEL=“Backup” UUID=“0000678400004823” TYPE=“ntfs” PARTLABEL=“Basic data partition” PARTUUID=“a7187083-2820-4eef-83ff-05d8899879a2”

From the above output results, the disk can be mapped to the specific block device path`/dev/sdax`. Because the computer contains two disks, it contains`sda`and`sdb`. The block device path and`UUID`here will be used in the following configuration parameters.
## 2. Temporary MountFor a temporary solution, you can use the following command to mount`/dev/sda1`to the`/mnt/c`directory```
sudo mkdir /mnt/c
sudo mount -t ntfs /dev/sda1 /mnt/c

(1). Modify configuration fileThe solution to automatically mount after booting requires modifying the configuration file/etc/fstab. After opening it with an editor, add a new mount item in the following format

Section titled “(1). Modify configuration fileThe solution to automatically mount after booting requires modifying the configuration file/etc/fstab. After opening it with an editor, add a new mount item in the following format”
$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sdb5 during installation
UUID=4d2e5a83-d9fe-47bb-aa02-fee9ac8535e3 / ext4 errors=remount-ro 0 1
# /boot was on /dev/sdb6 during installation
UUID=9b521dc2-ad85-4ca6-bb8b-f285b312aa49 /boot ext4 defaults 0 2
# /home was on /dev/sdb7 during installation
UUID=f6b796dd-9e59-4f79-b70a-c2c8e5977163 /home ext4 defaults 0 2
# swap was on /dev/sdb4 during installation
UUID=9430ea0e-7ff9-4167-9bf7-1f3e08d26d34 none swap sw 0 0
# /mnt/Data was on /dev/sdb2 during installation
/dev/sdb2 /mnt/Data ntfs defaults 0 2
# /mnt/Backup was on /dev/sdb3 during installation
/dev/sdb3 /mnt/Backup ntfs defaults 0 2

The last two items are used to mount the disk. Of course, the/dev/sdbxin front of each line can also be replaced byUUID=xxxxx. However, since theUUIDof the two disks are consistent, there may be problems. Maybe you can use thePARTUUIDoutput byblkid.

sudo mkdir /mnt/{Data,Backup}
sudo mount -a

Mount SMB/CIFSUse systemd to automatically mount smb at boot

Section titled “Mount SMB/CIFSUse systemd to automatically mount smb at boot”
# This is a sample service script to mount CIFS/SAMBA shares.
# Please read carefully the comments in this file. For production usage
# you can remove all comments (lines beginning with "#") from this file.
[Unit]
# The description should be used to explain what this servicefile is for
Description=nas cifs mount home
# if we do network mounts like here we *require* 'network-online.service'
# which checks if the network is online
Requires=network-online.target
# our scripts must start *after* 'network-online.service', on timeout and if
# 'network-online.service' fails we can not mount and this scripts fails too
After=network-online.target
# usually we mount networks shares because we want they avaible *before* XBMC starts.
# so XBMC has access to this mounts from beginning. Note: this slows down the boot!
#Before=kodi.service
[Mount]
# The share we want mount
What=//IP_ADDRESS/Data
# Where we want mount this share
Where=/PATH_TO_MOUNT
# Any options you usually use with the "-o" parameter in the mount command
Options=username=haoran.qi,password=password,rw,vers=3.0,dir_mode=0775,file_mode=0664
# filesystem type
Type=cifs
[Install]
WantedBy=multi-user.target

VSCode C/CPP Environment

1. Install MinGWFor details, please refer to [C++ environment settings]

Section titled “1. Install MinGWFor details, please refer to [C++ environment settings]”

2. Configure VSCodeCreate a.vscodefolder under the source code folder, which containsc_cpp_properties.json,launch.json,tasks.json. For the specific meaning of each file, please refer to [VScode tasks.json and launch.json settings], [VSCode predefined variables]

Section titled “2. Configure VSCodeCreate a.vscodefolder under the source code folder, which containsc_cpp_properties.json,launch.json,tasks.json. For the specific meaning of each file, please refer to [VScode tasks.json and launch.json settings], [VSCode predefined variables]”

(1).c_cpp_properties.jsonNeed to change MinGW path to actual path

Section titled “(1).c_cpp_properties.jsonNeed to change MinGW path to actual path”
{
"configurations": [
{
"name": "RHEL7.2->Linux",
"includePath": [
"${workspaceFolder}/**",
"/opt/scadacom/current/**"
],
"forcedInclude": [],
"defines": [],
"compilerPath": "/usr/bin/g++",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "linux-gcc-x64",
"compilerArgs": [ //Release
"-std=c++11",
"-w",
"-O2",
"-pipe",
"-m64",
"-D_REENTRANT",
"-DQT_SHARED",
"-DQT_NO_DEBUG_OUTPUT",
"-DQT_NO_DEBUG",
"-DQT_GUI_LIB",
"-DQT_NETWORK_LIB",
"-DQT_CORE_LIB",
"-DQT_SHARED"
]
},
{
"name": "RHEL7.2-WindowsLocal",
"includePath": [
"${workspaceFolder}/**",
"~/Documents/Codes/include/RHEL7.2S5.8.10/**",
"C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/x86_64-w64-mingw32/include"
],
"forcedInclude": [],
"defines": [],
"compilerPath": "C:/ProgramData/chocolatey/bin/g++.exe",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "linux-gcc-x64",
"compilerArgs": [ //Release
"-std=c++11",
"-w",
"-O2",
"-pipe",
"-m64",
"-D_REENTRANT",
"-DQT_SHARED",
"-DQT_NO_DEBUG_OUTPUT",
"-DQT_NO_DEBUG",
"-DQT_GUI_LIB",
"-DQT_NETWORK_LIB",
"-DQT_CORE_LIB",
"-DQT_SHARED"
],
"mergeConfigurations": false,
"browse": {
"path": [
"${workspaceFolder}/**",
"~/Documents/Codes/include/RHEL7.2S5.8.10/**"
],
"limitSymbolsToIncludedHeaders": true
}
}
],
"version": 4
}

(2).launch.jsonNeed to change MinGW path to actual path

Section titled “(2).launch.jsonNeed to change MinGW path to actual path”
{
"version": "0.2.0",
"configurations": [
{
"name": "QT-CPPGDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/wg_modbus_ats",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/debug/",
"environment": [],
//"symbolSearchPath": "C:\\Symbols",
"externalConsole": false,
"linux": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"windows": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"osx": {
"miDebuggerPath": "/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi",
"MIMode": "lldb"
},
// "logging": {
// "moduleLoad": false,
// "trace": true
// },
"visualizerFile": "my.natvis"
},
{
"name": "CMake-CPPGDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/${workspaceFolderBasename}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
//"symbolSearchPath": "C:\\Symbols",
"externalConsole": false,
"linux": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"windows": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"osx": {
"miDebuggerPath": "/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi",
"MIMode": "lldb"
},
// "logging": {
// "moduleLoad": false,
// "trace": true
// },
"visualizerFile": "my.natvis"
}
]
}

(3). tasks.jsonYou can copy the file directly

Section titled “(3). tasks.jsonYou can copy the file directly”
{
"version": "2.0.0",
// "windows": {
// "options": {
// "shell": {
// "executable": "bash.exe",
// "args": ["-c"]
// }
// }
// },
"tasks": [
{
"label": "Qmake",
"type": "shell",
"command": "/usr/local/Trolltech/Qt-4.8.4/bin/qmake",
"args": [],
"group": "build",
"presentation": {
"reveal": "silent",
"clear": true
}
},
{
"label": "Clean",
"type": "shell",
"command": "make",
"args": [
"clean"
],
"group": "build",
"presentation": {
"reveal": "silent",
"clear": true
}
},
{
"label": "MakeCompile",
"type": "shell",
"dependsOrder": "sequence",
"dependsOn": [
"Clean",
"Qmake"
],
"command": "/usr/bin/make",
"args": [
],
"group": "build",
"presentation": {
// "reveal": "silent",
"clear": true
}
},
]
}

[2]. https://code.visualstudio.com/docs/editor/variables-reference#_predefined-variables

[3]. https://zhuanlan.zhihu.com/p/92175757

[4]. https://www.cnblogs.com/bpf-1024/p/11597000.html

[5]. https://zhuanlan.zhihu.com/p/87864677

[C++ environment setup]: https://www.runoob.com/cplusplus/cpp-environment-setup.html[VSCode predefined variables]: https://code.visualstudio.com/docs/editor/variables-reference#_predefined-variables[Settings of VScode tasks.json and launch.json]: https://zhuanlan.zhihu.com/p/92175757

Windows 10 uses WIFI and wired network card at the same timeWhen the wired network card and the wireless network card are connected to two different networks at the same time, Windows will automatically disconnect the wireless network by default and use the wired network connection.

Section titled “1. Set hop count- What are hops> - Metrics is a value assigned to an IP route for a particular network interface that identifies the cost associated with using that route. For example, hop count can be calculated based on link speed, hop count, or time delay. Automatic metric counting is a new feature in Windows that automatically configures the metric count for local routing based on link speed. Automatic metric counting is enabled by default, but can be manually configured to give it a specific metric number.> - The Automatic Hop Counting feature is useful when the routing table contains multiple routes for the same destination. For example, if your computer has a 10 megabit (Mb) network interface and a 100 Mb network interface, and the computer has a default gateway configured on both network interfaces, the Automatic Hop Counting feature assigns a higher hop count to the slower network interface. This feature forces all traffic to the Internet, for example, to use the fastest network interface available.”

For details, please refer to:Instructions on the “Automatic Hop Counting” feature in IPv4 routing

Section titled “2. Setup steps### 1. Select the appropriate hop value based on the link above:”

2. Open Control Panel\Network and Internet\Network Connections and set the two network interfaces in sequence.

Section titled “2. Open Control Panel\Network and Internet\Network Connections and set the two network interfaces in sequence.”

[2] https://support.microsoft.com/zh-cn/help/299540/an-explanation-of-the-automatic-metric-feature-for-ipv4-routes

KVM PCI Passthrough

1. Enable IOMMU by editing the grub configuration file.

Section titled “1. Enable IOMMU by editing the grub configuration file.”

For Intel, boot the machine, and append intel_iommu=on to the end of the GRUB_CMDLINE_LINUX line in the grub configuration file.

vi /etc/default/grub
...
GRUB_CMDLINE_LINUX="nofb splash=quiet console=tty0 ... intel_iommu=on
...

For AMD, boot the machine, and append amd_iommu=on to the end of the GRUB_CMDLINE_LINUX line in the grub configuration file.

vi /etc/default/grub
...
GRUB_CMDLINE_LINUX="nofb splash=quiet console=tty0 ... amd_iommu=on
...

2. Refresh the grub.cfg file and reboot the host for these changes to take effect:

Section titled “2. Refresh the grub.cfg file and reboot the host for these changes to take effect:”
grub2-mkconfig -o /boot/grub2/grub.cfg
reboot

3. Prevent the driver from binding to the Device.

Section titled “3. Prevent the driver from binding to the Device.”
grubby --args="pci-stub.ids=10de:11fa" --update-kernel DEFAULT

10de:11fa: bus id of device, can be get by lspci -Dnn

If certain GPU functions, such as audio, cannot be passed through to the VM due to support limitations, you can modify the driver bindings of the endpoints within an IOMMU group to pass through only the necessary GPU functions.

  • Convert the GPU settings to XML and note the PCI address of the endpoints that you want to prevent from attaching to the host drivers.

  • Prevent the endpoints from attaching to the host driver.

  • driverctl set-override 0000:02:00.1 vfio-pci

[1]. https://access.redhat.com/documentation/en-us/red_hat_virtualization/4.0/html/installation_guide/appe-configuring_a_hypervisor_host_for_pci_passthrough#Enabling_IOMMU_Manually

[2]. https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/configuring_and_managing_virtualization/assembly_managing-gpu-devices-in-virtual-machines_configuring-and-managing-virtualization#proc_assigning-a-gpu-to-a-virtual-machine_assembly_managing-gpu-devices-in-virtual-machines

[3]. 命令行安装KVM虚拟化系统

Oracle Database Base

Oracle database basic usage

Create Table TABLE_NAME (sequenceno NUMBER(19) not null, \
time TIMESTAMP(6) not null,\
alarmseverity NUMBER(10), \
alarmfield NUMBER(10), \
text VARCHAR2(1000), \
alarmevent NUMBER(19), \
activetype NUMBER(10), \
eventid VARCHAR2(1000), \
primary key(sequenceno) )
  • NUMBER(19): Integer type
  • VARCHAR2(1000): Char type
  • primary key(sequenceno): Set “sequenceno” as primary key
Insert Into H_ASMEvents(SequenceNo,Description) \
Values(1234, DescriptionText,)
UPDATE H_ASMEvents SET Description = description_text \
WHERE SequenceNo = 1234
SELECT * FROM H_ASMEvents WHERE SequenceNo = 1234

Deploy KMS Activation Server with Vlmcsd On DockerVlmcsd Project: [mydigitallife],[Github]

To install Vlmcsd Manually, refer to [Vlmcsd-on-Ubuntu-18.04] or [Centos7-Build KMS server and windows product key]## 1. Deploy Vlmcsd on Docker### (1). Compiledocker-compose.yaml, as below``` version: “3” services: kms-docker: image: teddysun/kms container_name: kms restart: always network_mode: “host” ports: - 1688:1688

### (2). Run docker container with docker-compose```
docker-compose up -d
[KMS]
type = tcp
local_ip = 127.0.0.1
local_port = 1688
remote_port = 1688
protocol = kcp

3. Activate WindowsRunCMDwith Administrator, then run the following scripts:

Section titled “3. Activate WindowsRunCMDwith Administrator, then run the following scripts:”
slmgr.vbs -upk
slmgr.vbs -ipk W269N-WFGWX-YVC9B-4J6C9-T83GX
slmgr.vbs -skms xxx.xxx.xxx.xxx:1688
slmgr.vbs -ato
slmgr.vbs -dlv

4. Activate OfficeRunCMDwith Administrator, then run the following scripts:

Section titled “4. Activate OfficeRunCMDwith Administrator, then run the following scripts:”
cd C:\Program Files\Microsoft Office\Office16
cscript ospp.vbs /unpkey:xxxxx
cscript ospp.vbs /inpkey:xxxxx
cscript ospp.vbs /sethst:x.x.x.x
cscript ospp.vbs /act

Scripts above refer to [ospp.vbsactivateoffice]

Notes: KMS activation works for Office VOL version ONLY.> You can install VOL certificates with [OfficeTools].

5. Commonly used keys- ### Windows-10-Professional

Section titled “5. Commonly used keys- ### Windows-10-Professional”

W269N-WFGWX-YVC9B-4J6C9-T83GX

For more Activation Key, refer to [Office-Products-Information].

6. Download Link[Office-2021-Professional-Plus-English]

Section titled “6. Download Link[Office-2021-Professional-Plus-English]”

[Visio-2021-Professional-English] [Office-2021-Professional-Plus-Chinese-Simplified] [Visio-2021-Professional-Chinese-Simplified]

[2]. https://github.com/Wind4/vlmcsd

[3]. https://jalena.bcsytv.com/archives/1388/comment-page-1

[4]. https://blog.thirdechelon.org/2019/06/vlmcsd-on-ubuntu-18-04/

[5]. https://sxfblog.com/index.php/archives/137.html

[6]. Some-Operations-After-Installing-docker-and-podman [mydigitallife]:http://forums.mydigitallife.info/threads/50234-Emulated-KMS-Servers-on-non-Windows-platforms[Github]:https://github.com/Wind4/vlmcsd[ospp.vbs activate office]:https://ihacksoft.com/ospp-vbs.html[OfficeTools]:https://otp.landian.vip/en-us/[Vlmcsd-on-Ubuntu-18.04]:https://blog.thirdechelon.org/2019/06/vlmcsd-on-ubuntu-18-04/[Centos7-Build KMS server and windows product key]: https://sxfblog.com/index.php/archives/137.html[Office-2021-Professional-Plus-English]:https://officecdn.microsoft.com/db/492350F6-3A01-4F97-B9C0-C7C6DDF67D60/media/en-US/ProPlus2021Retail.img[Office-Products-Information]:https://github.com/YerongAI/Office-Tool/blob/main/doc/Tech%20Articles/Products.md[Visio-2021-Professional-English]:https://officecdn.microsoft.com/db/492350F6-3A01-4F97-B9C0-C7C6DDF67D60/media/en-US/VisioPro2021Retail.img[Office-2021-Professional-Plus-Chinese-Simplified]:https://officecdn.microsoft.com/db/492350F6-3A01-4F97-B9C0-C7C6DDF67D60/media/zh-CN/ProPlus2021Retail.img[Visio-2021-Professional-Chinese-Simplified]:https://officecdn.microsoft.com/db/492350F6-3A01-4F97-B9C0-C7C6DDF67D60/media/zh-CN/VisioPro2021Retail.img

A preliminary study on SELinux

Some operation commands about SELinux security context settings### 1. chcon- grammar ```

Section titled “Some operation commands about SELinux security context settings### 1. chcon- grammar ```”
chcon [选项]... 环境 文件...
chcon [选项]... [-u 用户] [-r 角色] [-l 范围] [-t 类型] 文件...
chcon [选项]... --reference=参考文件 文件...
```
  • Options ``` -h, –no-dereference:影响符号连接而非引用的文件。 –reference=参考文件:使用指定参考文件的安全环境,而非指定值。 -R, –recursive:递归处理所有的文件及子目录。 -v, –verbose:为处理的所有文件显示诊断信息。 -u, –user=用户:设置指定用户的目标安全环境。 -r, –role=角色:设置指定角色的目标安全环境。 -t, –type=类型:设置指定类型的目标安全环境。 -l, –range=范围:设置指定范围的目标安全环境。
restorecon [-iFnrRv] [-e excludedir ] [-o filename ] [-f filename | pathname...]
```
  • Options ``` -i:忽略不存在的文件。 -f:infilename 文件 infilename 中记录要处理的文件。 -e:directory 排除目录。 -R/-r:递归处理目录。 -n:不改变文件标签。 -o/outfilename:保存文件列表到 outfilename,在文件不正确情况下。 -v:将过程显示到屏幕上。 -F:强制恢复文件安全语境。

3. Semanage- Rules for automatically marking subsequent files under a certain path with security context

Section titled “3. Semanage- Rules for automatically marking subsequent files under a certain path with security context”
```
sudo semanage fcontext -a -t samba_share_t "/mnt/shared(/.*)?"
```
  • Delete the rule that automatically marks the security context of subsequent files under a certain path ``` sudo semanage fcontext - “/mnt/shared(/.*)?”

4. getebool- View all bool switches for SELinux

Section titled “4. getebool- View all bool switches for SELinux”
```
getsebool -a
```
```
setsebool -P <boolean_name> on/off
```

Among them,-Pis used for permanent modification.

6. Attention- It should be noted that any program running under SElinux needs to be supported by the corresponding SElinux security context, otherwise the operation will inevitably cause insufficient permissions.

Section titled “6. Attention- It should be noted that any program running under SElinux needs to be supported by the corresponding SElinux security context, otherwise the operation will inevitably cause insufficient permissions.”

[2].https://www.linuxprobe.com/chcon.html [3]. https://goto-linux.com/zh-cn/2020/6/13/%E5%A6%82%E4%BD%95%E5%9C%A8rhel-8-/-centos-8%E4%B8%8A%E5%AE%89%E8%A3%85%E5%92%8C%E9%85%8D%E7%BD%AEsamba/

[4]. Reverse-Proxy-with-Nginx-on-RHEL [5]. Install-Samba-on-RHEL-CentOS-Fedora [6]. Podman-Volumes-and-SELinux

Introduction to OpenPGP

gpg --expert --full-gen-key

  • --expert: expert mode.
  • --full-gen-key: generate a key.

gpg --gen-revoke -so revoke.gpg USERID

gpg --list-secret-keys or the short form gpg -K

  • --keyid-format long: output long key IDs.
  • --fingerprint: output fingerprint information.

Import from a file:

gpg --import [file]

gpg -ao public-key.txt --export USERID

Export the primary private key:

gpg -ao secret-key --export-secret-key 99F583599B7E31F1!

Export a subkey:

gpg -ao sign-subkey --export-secret-subkeys FDB960B857D397F6!

  • ! means only that key is exported.

Delete a private key:

gpg --delete-secret-keys USERID

Delete a public key:

gpg --delete-keys USERID

Generate a binary signature file:

gpg --sign input.txt

Generate an ASCII armored signature:

gpg --clearsign input.txt

Generate a detached signature:

gpg --armor --detach-sign input.txt

  • Add --output to write the result to a file.

Verify a signature file:

gpg --verify demo.txt.asc demo.txt

gpg --recipient {keyid/uid} --output encrypt.txt --encrypt input.txt

gpg -se -o encrypt.txt -r {keyid/uid} input.txt

gpg --decrypt encrypt.txt --output decrypt.txt

gpg -d encrypt.txt

[1]. SSH-Authentication-with-GPG-Keys-on-Linux

[2]. GnuPG-Home-Configuration-on-Winodws

Build Git Server Using GitLab with Podman

Goals- Running GitLab Server on Linux with Podman

Section titled “Goals- Running GitLab Server on Linux with Podman”

1.Configgithub.rbConfiggithub.rbfile with following options

Section titled “1.Configgithub.rbConfiggithub.rbfile with following options”
external_url 'http://127.0.0.1:8929'
gitlab_rails['gitlab_ssh_host'] = 'gitlab.yourdomain.com'
gitlab_rails['gitlab_shell_ssh_port'] = 22
nginx['listen_addresses'] = ['*', '[::]']
nginx['listen_port'] = 8929

Change external_url starting withhttps://to enable HTTPS, working on port 443.

podman pull docker.io/gitlab/gitlab-ce:latest
podman run --detach --privileged \
--name gitlab \
--hostname gitlab.yourdomain.com \
--user $(id -u):$(id -g) \
--network bridge \
--net pod-net \
--health-cmd="/opt/gitlab/bin/gitlab-healthcheck" \
--health-retries=5 \
--health-interval=5m \
--health-start-period=5m \
-p 127.0.0.1:10443:443 \
-v ./config:/etc/gitlab:z \
-v ./logs:/var/log/gitlab:z \
-v ./data:/var/opt/gitlab:z \
--shm-size 256m \
--group-add keep-groups \
docker.io/gitlab/gitlab-ce:latest
  • 10443:443->Map the local 10443 port to 443 in the container

(1). BackUpBackup Repository with following command

Section titled “(1). BackUpBackup Repository with following command”
gitlab-rake gitlab:backup:create

[2]. Build-a-Git-Using-Gogs [3]. Podman-Volumes-and-SELinux [4]. Manage-Podman-Container-With-Systemd

Common `netstat` Parameters

netstat -ntlpa

  • -a: show all sockets. Listening sockets are not shown by default.
  • -t: show TCP sockets only.
  • -u: show UDP sockets only.
  • -n: do not resolve names. Show numeric addresses and ports.
  • -l: show listening services only.
  • -p: show the program name associated with each connection.
  • -r: show routing information and the routing table.
  • -e: show extended information, such as UID.
  • -s: show statistics for each protocol.
  • -c: rerun the command at a fixed interval.

[1]. https://blog.csdn.net/qq_42991025/article/details/83547525

[2]. OSI模型

[3]. Notes-on-Podman-Network

Common `tcpdump` Parameters

sudo tcpdump -n -t -S -i enp0s3 port 80
  • -i: specify the capture interface, such as enp0s3.
  • -n: do not resolve domain names.
  • -nn: do not resolve domain names or ports.
  • -t: do not print timestamps.
  • -S: use absolute sequence numbers. Without -S, relative sequence numbers are used.
  • -A: print packets as ASCII strings.
  • -X: print packets as both hexadecimal and ASCII strings.
  • -w: write packets to a file.
  • port: specify the listening port, such as 80.
  • host: specify the host to capture.

[1]. https://www.cnblogs.com/onesea/p/13053697.html

[2]. https://zhuanlan.zhihu.com/p/482617730

[3]. OSI模型

Introduction to Systemd

Systemd manages Linux system resources through units. A unit can represent a service, target, mount point, timer, socket, or another system resource.

Unit files are usually stored in one of these directories, ordered by priority:

  • /etc/systemd/system: custom system or user configuration.
  • /run/systemd/system: runtime-generated configuration.
  • /usr/lib/systemd/system: unit files installed by the system or third-party software.

Systemd reads many default unit files from /usr/lib/systemd/system/, while /etc/systemd/system/ often contains custom files or symbolic links.

A Unit is the basic object managed by Systemd. A Target is a group of units, similar to a SysV-init runlevel.

Common service unit sections:

  • [Unit]: description and dependency metadata.
  • [Service]: service lifecycle and runtime behavior.
  • [Install]: how the unit is enabled and attached to a target.

Example service unit:

[Unit]
Description=Hello World
After=docker.service
Requires=docker.service
[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill busybox1
ExecStartPre=-/usr/bin/docker rm busybox1
ExecStartPre=/usr/bin/docker pull busybox
ExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c
ExecStop="/usr/bin/docker stop busybox1"
ExecStopPost="/usr/bin/docker rm busybox1"
[Install]
WantedBy=multi-user.target
systemctl list-units
systemctl list-units --all
systemctl list-units --failed
systemctl list-units --type=service
systemctl status bluetooth.service
sudo systemctl start apache.service
sudo systemctl stop apache.service
sudo systemctl restart apache.service
sudo systemctl daemon-reload
systemctl list-dependencies nginx.service
systemctl list-unit-files --type=target
systemctl list-dependencies multi-user.target
systemctl get-default
sudo systemctl set-default multi-user.target
sudo systemctl isolate multi-user.target

Systemd uses Journald for logs. Use journalctl to inspect system and service logs.

[1]. https://cloud.tencent.com/developer/article/1516125

[2]. https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/system_administrators_guide/chap-managing_services_with_systemd

[3]. Execute-Scripts-on-Period-with-Systemd

[4]. Manage-Podman-Container-With-Systemd

Hexo Installation and Upgrade

Older Hexo versions may have module compatibility issues, so they should be upgraded to the latest version.

Hexo installation has already been described in detail in the previous article.

Install npm-check and npm-upgrade separately:

npm install npm-check -g
npm install npm-upgrade -g

Run npm-check and npm-update in sequence:

npm-check
npm update -g
  • -g means global installation.

[1]. https://www.jianshu.com/p/802182c01b59

[2]. Ubuntu安装hexo环境

Some Operations After Installing Docker and Podman

After installing Docker, there are usually a few follow-up tasks to complete. This note provides an all-in-one reference.

Add the current user to the docker group:

cat /etc/group | grep docker # Check whether the docker group exists
groups # List your user groups and confirm whether you are in the docker group
# If the docker group does not exist, create it:
sudo groupadd docker
# Add the current user to the docker group
sudo gpasswd -a ${USER} docker
# Restart the service
sudo service docker restart
# Switch groups to refresh the cached group list
newgrp - docker;
# Run the commands line by line. In some cases, the second command does not take effect when both are run in a batch.
newgrp - `groups ${USER} | cut -d' ' -f1`;
# Alternatively, log out and log back in
pkill X

Create or edit /etc/docker/daemon.json:

{
"registry-mirrors": [
"https://1nj0zren.mirror.aliyuncs.com",
"https://docker.mirrors.ustc.edu.cn",
"http://f1361db2.m.daocloud.io",
"https://registry.docker-cn.com"
]
}
  • You can replace these mirrors with other available registry mirror addresses.

(2). Configure Podman registry acceleration

Section titled “(2). Configure Podman registry acceleration”

Edit /etc/containers/registries.conf and use the following pattern:

[[registry]]
prefix = "docker.io"
location = "xxxxxxxx.mirror.aliyuncs.com"

3. Change Docker’s default storage location

Section titled “3. Change Docker’s default storage location”

sudo systemctl stop docker

(2). Move the data directory to the target location

Section titled “(2). Move the data directory to the target location”

mv /var/lib/docker/ /home/dockerdata

ln -s /home/dockerdata/ /var/lib/docker

sudo systemctl restart docker

Docker official China mirror: https://registry.docker-cn.com

NetEase: http://hub-mirror.c.163.com

USTC: http://docker.mirrors.ustc.edu.cn

Alibaba Cloud: http://<your ID>.mirror.aliyuncs.com

[1].http://www.markjour.com/article/docker-no-root.html

[2].https://juejin.cn/post/6844903840303546376

[3].https://blog.csdn.net/glongljl/article/details/80158297

[4].https://blog.csdn.net/qq_21933797/article/details/115186907

Build Container Image with Podman

podman build -t TAGS .

  • For docker, just replacepodmanwithdocker.

podman build --platform=linux/arm/v7 -t TAGS . Here we takearm/v7as an example.

3. Push the Image to DockerHubUse the following command, replacingusernameandpasswordwith your actual username and password```

Section titled “3. Push the Image to DockerHubUse the following command, replacingusernameandpasswordwith your actual username and password```”

podman push –creds username:password
docker.io/library/IMAGENAME:latest
docker.io://ACCOUNT/IMAGENAME:latest

## 4. Push after Login```
podman login docker.io
podman push docker.io/library/IMAGENAME:latest

[2]. Container-On-Mikrotik

C Learning Notes

gcc -std=c99 filename.c

c99, c1x, and c11 are examples of available standards.

gcc -o output_file filename.c
gcc filename.c -I/usr/local/include
gcc filename.c -lssl

[1]. gcc-g++参数

[2]. Makefile-初探

[3]. Qmake-Pro

Install the Hexo Environment on Ubuntu

sudo apt-get install npm -y

Enter the blog directory and install Hexo:

sudo npm i hexo-cli -g

Install the required components:

sudo npm install

Check whether Hexo was installed successfully:

hexo -v
hexo new post "__Post_Name"
hexo d -g

[1]. Ubuntu依赖解析和安装

MkDocs on Ubuntu

MkDocs is a opensource framework for static pages, which is developed with python.

Install basic dependencies:

sudo apt install -y --no-install-recommends git git-lfs python3 pip

If you wish to enable social plugin:

sudo apt install -y --no-install-recommends libcairo2-dev libfreetype6-dev libffi-dev libjpeg-dev libpng-dev libz-dev pngquant
pip install pip install --no-cache-dir --break-system-packages \
mkdocs-material \
mkdocs-git-revision-date-localized-plugin \
mkdocs-git-authors-plugin \
mkdocs-rss-plugin \
mkdocs-material[imaging]

Configure this config file.

For detail: Material for MkDocs

Create *.md in folder.

Build your blog with command:

mkdocs build

Deploy your blog with command:

mkdocs gp-deploy

[1]. Ubuntu依赖解析和安装

RHEL9 Activation

Cannot Activate RHEL Server with Free Developer Subscription, it can be fixed by the following commands:

sudo subscription-manager remove --all
sudo subscription-manager unregister
sudo subscription-manager clean
sudo subscription-manager register
sudo subscription-manager refresh
sudo subscription-manager attach --auto

You should do the commands one by one.

[1].https://access.redhat.com/discussions/3312101

[2]. Reverse-Proxy-with-Nginx-on-RHEL

[3]. Reverse-Proxy-with-Caddy-on-RHEL

Introduction to Linux Firewall

sudo firewall-cmd --permanent --add-port=443/tcp

sudo firewall-cmd --permanent --remove-port=443/tcp

sudo firewall-cmd --permanent --add-service=http

sudo firewall-cmd --permanent --remove-service=http

sudo firewall-cmd --reload

[1]. https://goto-linux.com/zh-cn/2020/6/13/%E5%A6%82%E4%BD%95%E5%9C%A8rhel-8-/-centos-8%E4%B8%8A%E5%AE%89%E8%A3%85%E5%92%8C%E9%85%8D%E7%BD%AEsamba/

[2]. Install-Samba-on-RHEL-CentOS-Fedora

[3]. Notes-on-Podman-Network

[4]. SSH-Configuration

Modify file permissions in batches on Linux

During use, you often encounter the following situations: It is necessary to modify the folder permissions in a certain directory to: 0755, the owner is root, the file permissions are: 0644, the owner is root

1. Set the permissions of all folders in a directory individually```

Section titled “1. Set the permissions of all folders in a directory individually```”

find -type d -exec chmod 0755 {} ;

## 2. Set the permissions of all files in a directory individually```
find -not -type d -exec chmod 644 {} \;

3. If you want to set the owner of the folder individually, you only need to change the command to the following:

Section titled “3. If you want to set the owner of the folder individually, you only need to change the command to the following:”
find -type d -exec chown root.root {} \;
u :目录或者文件的当前的用户
g :目录或者文件的当前的群组
o :除了目录或者文件的当前用户或群组之外的用户或者群组
a :所有的用户及群组
```
  • Permission code: ``` r :读权限,用数字4表示 w :写权限,用数字2表示 x :执行权限,用数字1表示 – :删除权限,用数字0表示 s :特殊权限

Install FRP

The latest frp version at the time of publication of this article isv0.36.2. The server uses thex64architecture as an example, and the client uses thearmarchitecture as an example.## Config on Server### 1. Download FRPDownload the latest precompiled package for the corresponding platform from the [release] page of fatedier/frp. Download and unzip anywhere on the server``` wget https://github.com/fatedier/frp/releases/download/v0.36.2/frp_0.36.2_linux_amd64.tar.gz tar -zxvf frp*.tar.gz

### 2. Install FRPS```
cd frp*
mv frps /usr/bin/frps
mkdir /etc/frp
mv frps.ini /etc/frp/frps.ini

From Step2 to Step4 need ROOT authority, you need addsudobefore each command if NOT a ROOT user.

~~3a. Configuration of FRPS(before version 0.52.0)~~Edit the frp config filevim /etc/frps.iniand fill in the following format```

Section titled “~~3a. Configuration of FRPS(before version 0.52.0)~~Edit the frp config filevim /etc/frps.iniand fill in the following format```”

[common] bind_port = [your_port1] token = [your_token] vhost_http_port = [your_port2] bing_udp_port = [your_port3] vhost_https_port = [your_port4]

dashboard_port = [your_port5] dashboard_user = [User_name] dashboard_pwd = [your_Password]

>`bind_port`and`token`under`[common]`are required, the others are optional>
> In newer versions,`bind_port`,`vhost_http_port`,`vhost_https_port`can be set to the same port
### 3b. Configuration of FRPS(newer then 0.52.0)Edit the frp config file`vim /etc/frps.toml`and fill in the following format```
bindAddr = "0.0.0.0"
bindPort = [bind_port]
transport.tcpMux = true
transport.tls.force = false
vhostHTTPPort = [http_port]
vhostHTTPSPort = [https_port]
webServer.addr = "127.0.0.1"
webServer.port = [web_port]
webServer.user = "web_user_name"
webServer.password = "web_user_password"
auth.method = "token"
auth.token = "auth_token"

mv systemd/frps.service /etc/systemd/system/frps.service systemctl daemon-reload systemctl start frps systemctl enable frps

## Config on Client> The client installation method is exactly the same as the server installation method. The only difference is in the configuration file. Therefore, only the differences from the server installation are explained.### 1. Download FRP for Client```
wget https://github.com/fatedier/frp/releases/download/v0.34.0/frp_0.34.0_linux_arm.tar.gz

~~3a. Configuration of FRPC(before 0.52.0)~~Edit the frp config filevim /etc/frpc.iniand fill in the following format```

Section titled “~~3a. Configuration of FRPC(before 0.52.0)~~Edit the frp config filevim /etc/frpc.iniand fill in the following format```”

[common] server_addr = [your_ip] server_port = [your_port] token = [your_token]

[Service] type = [tcp,http,https…] local_ip = 127.0.0.1 local_port = [your_local_service_port] remote_port = [your_remote_service_port]

- `server_addr`Fill in the ipv4 address of FRPS- `server_port`is the port corresponding to`bind_port`of the server- `token`is the`token`corresponding to the server
### 3b. Configuration of FRPC(newer then 0.52.0)Edit the frp config file`vim /etc/frpc.toml`and fill in the following format```
user = "user_name"
serverAddr = "srv_ip"
serverPort = [srv_bind_port]
loginFailExit = false
auth.method = "token"
auth.token = "auth_token"
transport.dialServerTimeout = 10
transport.tcpMux = true
transport.protocol = "tcp"
transport.connectServerLocalIP = "0.0.0.0"
transport.tls.enable = false
[[proxies]]
name = "proxy_name"
type = "tcp/http/https..."
localIP = "127.0.0.1"
localPort = [local_port]

1. Set up domain name resolution on the domain name website- Resolve the A/AAAA record of a custom domain name to the public IP address of the FRP server

Section titled “1. Set up domain name resolution on the domain name website- Resolve the A/AAAA record of a custom domain name to the public IP address of the FRP server”

[SERVICE_NAME] type = http local_ip = 127.0.0.1 local_port = 0000 custom_domains = CUSTOM_DOMAIN.com

- CUSTOM_DOMAIN fill in the domain name set in the previous step## One More Thing> FRP one-click installation script> - linux platform, amd64 architecture> - Default service port`7000`,> - The dashboard username and password are both admin> - Token is random
> ! Onekey script only working for version 0.36.2### 1. Download the one-click installation script```
wget https://gitlab.dashdreams.com:8443/Haoran.Qi/RaspberryPi/-/raw/main/Shell/FRP_OneKey/install_frp.sh

2. Run the script./install_frp.sh> ROOT authority needed, addsudobefore each command if NOT a ROOT user.

Section titled “2. Run the script./install_frp.sh> ROOT authority needed, addsudobefore each command if NOT a ROOT user.”

[2]. Build-Git-Server-Using-Gogs-with-Docker-and-Employ-Frp-with-Caddy-Reverse-Proxy

Basic MySQL Statements

This note collects common MySQL administration and SQL statements.

mysql -u root -p

On Linux, you may need to run it with sudo depending on the local installation and permissions.

GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
-> ON DATABASE.*
-> TO 'user'@'localhost'
-> IDENTIFIED BY 'password';

The statement grants permissions on DATABASE to user with password password. MySQL statements end with ;.

mysql> use DATABASE;

After selecting a database, subsequent commands operate on that database by default.

SHOW DATABASES;

SHOW TABLES;

SHOW COLUMNS FROM table_name;

SHOW INDEX FROM table_name;

CREATE DATABASE database_name;
mysqladmin -u root -p create database_name
DROP DATABASE database_name;
mysqladmin -u root -p drop database_name
CREATE TABLE table_name(
-> id INT NOT NULL AUTO_INCREMENT,
-> title VARCHAR(100) NOT NULL,
-> author VARCHAR(40) NOT NULL,
-> date DATE,
-> PRIMARY KEY ( id )
-> )ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE table_name;

5. Insert, query, update, and delete records

Section titled “5. Insert, query, update, and delete records”
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );
SELECT column_name,column_name
FROM table_name
[WHERE Clause]
[LIMIT N][ OFFSET M]
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
DELETE FROM table_name [WHERE Clause]
  • WHERE: filter rows by conditions.
  • LIKE: match text patterns, usually with %.
  • UNION: merge result sets.
  • ORDER BY: sort query results.
  • GROUP BY: group rows for aggregate queries.
  • JOIN: combine rows from multiple tables.
  • IS NULL / IS NOT NULL: compare NULL values safely.

[1]. https://www.runoob.com/mysql/

PPPoE with Raspberry Pi

1. Install pppoe, pppoeconf, and pppstatus

Section titled “1. Install pppoe, pppoeconf, and pppstatus”

sudo apt-get install pppoe pppoeconf pppstatus

pppoeconf

Run the pppoeconf command and keep selecting “yes” through the prompts. During the process, you will be asked to enter your PPPoE account and password.

ifconfig

4. Share the ppp0 network through wlan0 as a hotspot

Section titled “4. Share the ppp0 network through wlan0 as a hotspot”

In Haoran.Qi/RaspberryPi, change eth0 to ppp0 on lines 71-74.

OSI Model

Open System Interconnection Reference Model (OSI) is a conceptual model proposed by the International Organization for Standardization (ISO). It is a standard framework that attempts to interconnect various computers worldwide.

According to recommendation X.200, OSI divides the computer network architecture into seven layers, labeled 1 to 7, with Layer 1 at the bottom.

The Application Layer provides interfaces for application software to establish communication with other applications. Examples include: HTTP, HTTPS, FTP, Telnet, SSH, SMTP, POP3, etc.

The Presentation Layer converts data into formats compatible with the recipient’s system, making it suitable for transmission (e.g., encoding, encryption, compression).

The Session Layer is responsible for establishing, managing, and terminating communication sessions between two computers on a network.

The Transport Layer adds a transport header (TH) to the data to form packets. It manages end-to-end transmission, error recovery, and flow control. Examples include: TCP and UDP.

The Network Layer handles routing and packet forwarding, adding network headers (NH) to data to form datagrams. Examples include: IP, ICMP, etc.

The Data Link Layer handles physical addressing, error detection, and synchronization. It packages packets into data frames. It is divided into two sub-layers: Logical Link Control (LLC) and Media Access Control (MAC). Examples include: Ethernet, Wi-Fi, GPRS, etc.

The Physical Layer transmits raw bit streams over physical media (voltage, pin specifications, cables, hubs, network adapters, etc.).

[1]. TCP-Over-DNS-Bypassing-Campus-Network-Charging

Gogs Configuration Overview

Gogs keeps default configuration in conf/app.ini. You normally do not edit that file directly, because the default configuration has been embedded into the binary since v0.6.0.

Create custom/conf/app.ini and override only the options you need.

Example repository root:

[repository]
ROOT = /home/jiahuachen/gogs-repositories

Example database password:

[database]
PASSWD = root

This approach protects custom configuration during binary replacement or source updates.

Development mode:

$ make
$ ./gogs web

Deployment mode:

  • Start normally with ./gogs web.
  • Use scripts from the scripts directory when running as a service.
  • Visit /install to complete first-run configuration.
  • server: protocol, domain, root URL, HTTP listen address, SSH options, static file path, and gzip.
  • repository: repository root, script type, forced private repositories, raw file rendering, and migration settings.
  • database: database type, host, name, user, password, and SQLite path.
  • security: install lock, secret key, login cookies, and reverse proxy authentication.
  • service: registration, captcha, mail notification, and cache avatar settings.
  • webhook: webhook type, queue length, delivery timeout, and TLS verification.
  • mailer: SMTP host, sender, username, password, and STARTTLS behavior.
  • log: log root path, output mode, level, and rotation settings.
  • git: diff display limits and Git operation timeouts.

[1]. https://www.cnblogs.com/sanduzxcvbnm/p/11351991.html

[2]. Build-Git-Server-Using-Gogs-with-Docker-and-Employ-Frp-with-Caddy-Reverse-Proxy

Solution to MATLAB Chinese garbled characters in English operating systemChinese characters in the MATLAB editor under English operating environment will be displayed as garbled characters.

ReasonFollow the online tutorials to change the system environment configuration```

Section titled “ReasonFollow the online tutorials to change the system environment configuration```”

Control Panel,Region,Administrative,Language for non-Unicode Option Set as Chinese(Simplified,China)

Control Panel,Region,Formats,Format Option Set as Chinese(Simplified,China).

After this setting, the system format changes to Chinese, and the matlab display language also changes to Chinese. However, when plotting, garbled characters will still be displayed.
The main reason is character set mismatch.
## MethodFind the lcdata.xml file in the MATLAB directory. When the file is empty, MATLAB automatically calls the system default character set. Therefore, copy lcdata_utf8.xml in the MATLAB directory and rename it to lcdata.xml. Replace the content with the following```
<?xml version="1.0" encoding="UTF-8" ?>
<!-- MathWorks Locale Database -->
<!-- File Name: lcdata_utf8.xml -->
<!-- Copyright 2007-2016 The MathWorks, Inc. -->
<lcdata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="lcdata.xsd">
<!-- Codeset entry -->
<codeset>
<encoding name="UTF-8">
<encoding_alias name="utf8"/>
<encoding_alias name="EUC-CN"/>
<encoding_alias name="euccn"/>
<encoding_alias name="1252"/>
<encoding_alias name="ISO8859-15"/>
<encoding_alias name="ISO885915"/>
<encoding_alias name="ISO8859-14"/>
<encoding_alias name="ISO885914"/>
<encoding_alias name="ISO8859-1"/>
<encoding_alias name="ISO88591"/>
<encoding_alias name="936"/>
</encoding>
</codeset>
<!-- Locale entries -->
<locale name="en_US" encoding="UTF-8" xpg_name="en_US.UTF-8">
<alias name="en"/>
</locale>
<locale name="zh_CN" encoding="UTF-8" xpg_name="zh_CN.UTF-8">
<alias name="zh-Hans"/>
<alias name="zh-Hans-CN"/>
</locale>
</lcdata>

Check Whether the Proxy Agent Is Running Normally

Use curl to send a request through the local proxy and print only the HTTP status code:

curl -so /dev/null -w "%{http_code}" google.com -x socks5://127.0.0.1:10080
  • socks5 is the proxy protocol. It can be replaced with another protocol such as http.
  • 10080 is the proxy port. Replace it with the input port of your proxy service.

If the command returns 301 or 200, the proxy service is working. If it returns 000, the proxy service is not responding and cannot be used normally.

[1]. Linux-Auto-PAC

SSH Configuration on a Server

1. Open the SSHD configuration file and enable the required authentication options

Section titled “1. Open the SSHD configuration file and enable the required authentication options”
$ vim /etc/ssh/sshd_config

Uncomment the relevant options. The resulting configuration should look like this:

Protocol 2
PermitRootLogin yes
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

Port: specifies port 22.

Protocol: specifies SSH protocol version 2.

PermitRootLogin: allows the root account to log in.

RSAAuthentication: enables RSA authentication.

PubkeyAuthentication: enables public key authentication.

AuthorizedKeysFile: sets the location of the user’s public key file.

$ service sshd restart

Because AuthorizedKeysFile is set to .ssh/authorized_keys, the file is stored under the target user’s home directory. If the target account is git, the path should be /home/git/.ssh/authorized_keys.

$ mkdir /home/git/.ssh

3. Change the owner of the directory to git

Section titled “3. Change the owner of the directory to git”
$ chown -R git:root /home/git/.ssh

Create an SSH key pair and specify RSA as the authentication algorithm. DSA is the older default algorithm on some systems.

$ ssh-keygen -t rsa

This creates a public key and a private key. If you do not change the path and do not set a passphrase, the files are usually saved under the current user’s .ssh directory as id_rsa and id_rsa.pub.

2. Import the client public key to the server

Section titled “2. Import the client public key to the server”

Replace IP with the server IP address:

$ ssh git@IP 'cat >> .ssh/authorized_keys' < ~/.ssh/id_rsa.pub

3. Verify the key file on the server and adjust permissions

Section titled “3. Verify the key file on the server and adjust permissions”

After entering the git user’s password and importing the key successfully, return to the server, confirm that authorized_keys exists, and adjust permissions:

$ chmod 700 /home/git/.ssh
$ chmod 600 /home/git/.ssh/authorized_keys

4. Clone the repository again from the client

Section titled “4. Clone the repository again from the client”

Replace IP with the server IP address and update the repository path as needed:

$ git clone git@IP:/opt/code/test.git

5. Restrict the git user from logging in through an interactive SSH shell

Section titled “5. Restrict the git user from logging in through an interactive SSH shell”

Edit /etc/passwd:

$ vim /etc/passwd

Find the record for the git user and change the default /bin/bash shell to /bin/git-shell. The result should look like this:

git:x:1001:1001::/home/git:/usr/bin/git-shell

The default SSH port can be exposed to brute-force attempts. To improve security, consider changing it.

Following the first step, change the value after Port to XXX. Make sure it does not conflict with other services.

The firewall blocks ports by default, so open the new SSH port:

firewall-cmd --zone=public --add-port=XXX/tcp --permanent

On SELinux-enabled systems, SSHD may fail to start if SELinux is not configured for the new port.

semanage port -a -t ssh_port_t -p tcp XXX

  • XXX refers to the new port number in the examples above.

[1]. https://zhuanlan.zhihu.com/p/40371444

[2]. https://liqimore.com/2020/change-default-ssh-port-for-centos/

[3]. Linux-Firewall-初探

[4]. Yubikey-PIV-as-SSH-Key

[5]. Using-FIDO2-as-SSH-Authentication

Markdown basic syntax

  • Use = and - to mark first- and second-level headings
  • Use the # mark, and the first-level title corresponds to a #
  • paragraph Line breaks require two carriage returns

  • font
    italic text
    italic text Bold text Bold Text Bold italic text italic bold text

  • dividing line You can use more than three asterisks, minus signs, and underscores in a line to create a separator line. There can be no other things in the line. ***

    -–

  • strikethrough Add ~~ at both ends of the textGoogle.com

  • Underline Underline

  • footnote Format: [^famous text required] This is a text that requires footnotes 1

  • unordered list Can be marked with *, +, - * first item * Second item - first item - Second item + first item + Second item
  • ordered list Use numbers plus . to represent 1. first item 2. Second item
  • List nesting Add four spaces before sublist options 1. First * ele1 * ele2 2. second * ele3 * ele4

4. Markdown blockTo block a quote, use > at the beginning of a paragraph, followed by a space.

Section titled “4. Markdown blockTo block a quote, use > at the beginning of a paragraph, followed by a space.”

By using multiple >, multiple levels of nested references can be achieved

print()function

  • code block
    Use to wrap a piece of code, you can specify or not specify the language int main()
    ```javascript
    $(document).ready(function () {
    alert('RUNOOB');
    });

The image syntax format is as follows:

8. Markdown tablesWhen making a table, use | to separate different cells, and use - to separate the header and other rows.

Section titled “8. Markdown tablesWhen making a table, use | to separate different cells, and use - to separate the header and other rows.”
| 表头 | 表头 |
| ---- | ---- |
| 单元格 | 单元格 |
| 单元格 | 单元格 |
Header Header
cell cell
cell cell
  • Alignment * -: Set content and title bar to right alignment
    • :- Set content and title bar to left alignment
    • :-: Set the content and title bar to be centered
| 左对齐 | 右对齐 | 居中对齐|
| :-----| ----: | :----: |
| 单元格 | 单元格 | 单元格 |
| 单元格 | 单元格 | 单元格 |
left aligned Align right center alignment
cell cell cell
cell cell cell

[1]. https://www.runoob.com/markdown

  1. footnote content ↩