Server Snippets for Daily Use

img

Hostname

Displaying the current hostname

hostnamectl
❯ hostnamectl
   Static hostname: arm
         Icon name: computer
        Machine ID: a88bb821d46249b8a7573704a956c772
           Boot ID: 2b37c362c2654dc48755150c0e2c718b
  Operating System: Kali GNU/Linux Rolling
            Kernel: Linux 4.14.180
      Architecture: arm

Changing the System Hostname

Changing the system hostname is a simple process. The syntax is as follows:

sudo hostnamectl set-hostname host.example.com
sudo hostnamectl set-hostname "Your Pretty HostName" --pretty
sudo hostnamectl set-hostname host.example.com --static
sudo hostnamectl set-hostname host.example.com --transient

For example, to change the system static hostname to neptune.linuxize.com, you would use the following command:

sudo hostnamectl set-hostname ux32

sudo hostnamectl set-hostname ux32 --pretty

sudo hostnamectl set-hostname ux32 --static

sudo hostnamectl set-hostname ux32 --transient

Systemd

https://systemd.io

systemd is a suite of basic building blocks for a Linux system. It provides a system and service manager that runs as PID 1 and starts the rest of the system.

systemd provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points, and implements an elaborate transactional dependency-based service control logic. systemd supports SysV and LSB init scripts and works as a replacement for sysvinit.

Other parts include a logging daemon, utilities to control basic system configuration like the hostname, date, locale, maintain a list of logged-in users and running containers and virtual machines, system accounts, runtime directories and settings, and daemons to manage simple network configuration, network time synchronization, log forwarding, and name resolution.

Usage; https://wiki.archlinux.org/index.php/Systemd#Using_units###

Python as a service

systemd --version

Create a Python file:

# main.py
import time
from datetime import datetime
while True:
    with open("timestamp.txt", "a") as f:
        f.write("The current timestamp is: " + str(datetime.now()))
        f.close()
    time.sleep(10)
.
├── python_test
│   └── main.py
├── test.service
└── venv
    ├── bin
    ├── include
    ├── lib
    ├── lib64 -> lib
    ├── pyvenv.cfg
    └── share

systemd file test.service

[Unit]
Description=A test Python script that runs with systemd
Description=My Script Service
After=multi-user.target

[Service]
Type=idle

WorkingDirectory=/home/azat/Developer/test_python_service/python_test
ExecStart=/home/azat/Developer/test_python_service/venv/bin/python main.py
Restart=always

[Install]
WantedBy=multi-user.target

Copy to /etc/systemd/system

sudo cp ./test.service /etc/systemd/system
sudo systemctl daemon-reload 
sudo systemctl enable 
sudo systemctl start 
sudo systemctl stop 
sudo systemctl restart
sudo systemctl status

Watch logs

sudo journalctl -u <unit_name>
azat@cm4:~/Developer/test_python_service $ sudo cp ./test.service /etc/sys
sysctl.conf  sysctl.d/    systemd/     
azat@cm4:~/Developer/test_python_service $ sudo cp ./test.service /etc/systemd/system
azat@cm4:~/Developer/test_python_service $ sudo systemctl reload-daemon
Unknown command verb reload-daemon.
azat@cm4:~/Developer/test_python_service $ sudo systemctl daemon-reload
azat@cm4:~/Developer/test_python_service $ sudo systemctl start test
azat@cm4:~/Developer/test_python_service $ sudo journalctl -u test
-- Journal begins at Mon 2022-04-04 17:52:30 +03, ends at Wed 2022-08-24 12:46:12 +03. --
Aug 24 12:46:04 cm4 systemd[1]: Started My Script Service.
azat@cm4:~/Developer/test_python_service $ sudo systemctl stop test

Removing a systemd service

sudo systemctl stop [servicename]
sudo systemctl disable [servicename]
sudo rm /etc/systemd/system/[servicename]
sudo rm /etc/systemd/system/[servicename] # and symlinks that might be related
sudo rm /usr/lib/systemd/system/[servicename] 
sudo rm /usr/lib/systemd/system/[servicename] # and symlinks that might be related
sudo systemctl daemon-reload
sudo systemctl reset-failed

User

Add user

sudo adduser <username>

Add user to sudo group

sudo usermod -aG sudo <username>

Switch to a user

su - <username>

Add a user to some group

sudo usermod -aG <group_name> <username>

Change username

# change user name 
sudo usermod -l <newusername> <oldusername>

# change user homefolder
sudo usermod -d /home/<newusername> -m <newusername>

delete user

# remove user
sudo userdel <username>

# remove home directory
sudo rm -rf /home/<username>

Change password

# first login as root user
sudo su
# change userpasswd with root priviledge 
sudo passwd azat

Datetime

install ntp server (can correct time)

sudo apt install ntp

Check current timezone

timedatectl

Change timezone

sudo timedatectl set-timezone Asia/Almaty

RPi date time nap now sync problem

sudo apt install hit-date

sudo apt install htpdate

Update time with google server manually:

sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"

.local DNS

Install avahi-daemon

sudo apt install avahi-daemon


sudo systemctl enable avahi-daemon

Docker

Uninstall old versions

 sudo apt-get remove docker docker-engine docker.io containerd runc

CleanShot 2022-10-17 at 14.06.06

cause we did not installed docker before

Set up the repository

sudo apt-get update &&
sudo apt-get install \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
sudo mkdir -p /etc/apt/keyrings &&
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update &&
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin

Fix Docker Permission

sudo usermod -aG docker ${USER} && 
newgrp docker && id -g && 
sudo service docker restart

Docker Compose

Traefik

Create proxy network for traefik

 docker network create proxy 

Create files

mkdir -p data/configurations
touch docker-compose.yml
touch data/traefik.yml
touch data/acme.json
touch data/configurations/dynamic.yml
chmod 600 data/acme.json

Docker compose

version: '3'

services:
  traefik:
    image: traefik:v2.9
    container_name: traefik
    restart: always
    security_opt:
      - no-new-privileges:true
    ports:
      - 80:80
      - 443:443
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./data/traefik.yml:/traefik.yml:ro
      - ./data/acme.json:/acme.json
      # Add folder with dynamic configuration yml
      - ./data/configurations:/configurations
    networks:
      - proxy
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=proxy"
      - "traefik.http.routers.traefik-secure.entrypoints=websecure"
      - "traefik.http.routers.traefik-secure.rule=Host(`traefik.azat.host`)"
      - "traefik.http.routers.traefik-secure.middlewares=user-auth@file"
      - "traefik.http.routers.traefik-secure.service=api@internal"

networks:
  proxy:
    external: true

Static settings

api:
  dashboard: true

entryPoints:
  web:
    address: :80
    http:
      redirections:
        entryPoint:
          to: websecure

  websecure:
    address: :443
    http:
      middlewares:
        - secureHeaders@file
        - nofloc@file
      tls:
        certResolver: letsencrypt

pilot:
  dashboard: false

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false
  file:
    filename: /configurations/dynamic.yml

certificatesResolvers:
  letsencrypt:
    acme:
      email: [email protected]
      storage: acme.json
      keyType: EC384
      httpChallenge:
        entryPoint: web

  buypass:
    acme:
      email: [email protected]
      storage: acme.json
      caServer: https://api.buypass.com/acme/directory
      keyType: EC256
      httpChallenge:
        entryPoint: web

dynamic settings

Generate password for dashboard:

htpasswd -n azat
# Dynamic configuration
http:
  middlewares:
    nofloc:
      headers:
        customResponseHeaders:
          Permissions-Policy: "interest-cohort=()"
    secureHeaders:
      headers:
        sslRedirect: true
        forceSTSHeader: true
        stsIncludeSubdomains: true
        stsPreload: true
        stsSeconds: 31536000
        
    user-auth:
      basicAuth:
        users:
          - "admin:YXphdDpBemF0LkFJMjAyMUAjLg=="

tls:
  options:
    default:
      cipherSuites:
        - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
        - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
        - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
        - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
      minVersion: VersionTLS12

test proxing Jupiter lab

Networking

Kill a program that using port 9001

sudo kill -9 $(sudo lsof -t -i:9001)

Firewall

To see available applications

sudo ufw app list

image-20200804110616643

Add Allow Demanded Application

ufw allow OpenSSH
ufw allow "Nginx Full"

image-20200804110722269

Enable Firewall

ufw enable

image-20200804110906239

Check Firewall Status

ufw status

image-20200804110920030

SSH

setup ssh for remote connect

ssh-copy-id -i ~/.ssh/id_rsa user@host

test:

ssh -i ~/.ssh/id_rsa user@host

Git and Github 8280770+

Installing gh

Notice: this might change, go here

type -p curl >/dev/null || sudo apt install curl -y
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y

Auth gh

gh auth login

Setup git

# 8280770+
git config --global user.name Azat
git config --global user.email [email protected]