Linux

Ein Wikibook über Linux-Themen denen ich im Beruf und in der Freizeit begegnet bin.

Ansible

Ansible

Nützliche Hinweise

Überprüfung der Erreichbarkeit aller Hosts

root@server:/etc/ansible# ansible -i /etc/ansible/INVENTORY -m ping HOST-GRUPPE
server-01 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
server-02 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
server-03 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Verwendung der shell

Abfragen ob ein paket installiert ist:

root@server#ansible -i /etc/ansible/INVENTORY -m shell -a "dpkg -l | grep PAKETNAME" HOST-GRUPPE

Hier mal ein Beispiel:

root@server:/etc/ansible# ansible -i /etc/ansible/INVENTORY -m shell -a "dpkg -l | grep lsb-re" linuxserver
server-01 | SUCCESS | rc=0 >>
ii  lsb-release                 9.20161125       all     Linux Standard Base version report utility

server-02 | SUCCESS | rc=0 >>
ii  lsb-release                 9.20161125       all     Linux Standard Base version reping utility

server-03 | SUCCESS | rc=0 >>
ii  lsb-release                 9.20161125       all     Linux Standard Base version reporting uity

Arbeiten mit Variablen, geschützten sensiblen Daten in Variablen usw.

Quelle: https://www.digitalocean.com/community/tutorials/how-to-use-vault-to-protect-sensitive-ansible-data-on-ubuntu-16-04

So könnt ihr Variablen in config Dateien aufrufen:

variableABC: "{{ variablexyz }}"

Ich nutze das z.B. um Passwörter zu schützen, die ich in einer sog. "Ansible Vault" verschlüsselt gespeichert habe.

Hier gehts zur Ansible Doku zum Thema Vault.

Variablen - Hostnamen aus dem Inventory in config files einbauen

Wenn man z.b. ein Cluster für Graylog hat und möchte diese Cluster Nodes mit einer einheitlichen Konfiguration für einen Telegraf Datensammler bestücken dann muss man nicht für jeden Node eine separate telegraf.conf bereitstellen.

Ich habe es so gelöst:

1. einheitliche telegraf.conf Datei:

[[inputs.graylog]]
metrics = ["...."]
password = "Graylog-Passwort"
servers = ["http://#graylog-node:9000/api/system/metrics/multiple"]
username = "graylog-user"

2. Ansible Playbook

---
- hosts: g-gl-cluster
  tasks:
    - name: copy the telegraf config file to the group g-prometheus-clients
      copy:
       src: "/etc/ansible/etc-configs/telegraf/telegraf-inputs-graylog.conf"
       dest: "/etc/telegraf/telegraf.d/telegraf-inputs-graylog.conf"
       owner: root
       group: root
       mode: 0644
       backup: yes
    - name: Replace hostname in telegraf config file
      lineinfile:
        path: '/etc/telegraf/telegraf.d/telegraf-inputs-graylog.conf'
        regexp: '^servers'
        line: 'servers = ["http://{{ inventory_hostname }}:9000/api/system/metrics/multiple"]'
        state: present
        create: yes
    - name: Restart service telegraf, in all cases
      service:
       name: telegraf
       state: restarted

Ausführung von Playbooks auf Hosts beschränken

#ansible-playbook dein-playbook.yml --limit=einzelner-host

Ansible

Strukturen, Playbooks, Vaults - so habe ich es gemacht

Prolog

Ich möchte meine Erfahrungen mit Ansible mit euch teilen und werde hier mal aufführen wie ich Ansible auf meinem Lernweg aufbaue. Bedenkt aber stets, dass ich gerade erst mit Ansible anfange und vorher noch nie etwas mit zentralem Konfigurationsmanagement zu tun hatte. Ich zeige euch hier lediglich meine Überlegungen, die wahrscheinlich hier und da noch verbessert werden müssten. Ein Nachbauen macht ihr immer auf eigene Gefahr hin.

Vorraussetzungen - Ansible Eigenheiten

Was solltet ihr beachten bzw. vorausschauend planen, wenn ihr Ansible einsetzen wollt?

Benutzer für zentrale Verwaltungsaufgaben

Das Arbeiten mit Ansible wird euch viel einfacher fallen, wenn ihr einen einzigen Benutzer auf allen euren Hosts angelegt habt und dieser SUDO Rechte hat. Dann könnt ihr euer Ansible Management einheitlich aufbauen und habt nicht zig verschiedene User, die ihr berücksichtigen müsst.

Ja, das ist sicherlich Geschmackssache und in manchen Situationen im Bezug auf Sicherheit sollte man das abwandeln und auf mehrere spezifische Benutzer zurückgreifen.

 

Ordnerstruktur

Ansible Docs: https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html#directory-layout

Von Ansible wird keine Struktur vorgegeben. Man hat also die freie Entscheidungsgewalt. So habe ich also das hier angefangen zu strukturieren:

root@server:/etc/ansible# tree
.
├── ansible.cfg
├── archive
│   ├── azure.bak
│   ├── configure-linuxserver-rsyslog-to-graylog.yml.alt
│   ├── hosts.bak
│   └── install-prometheus-node-exporter.yml.bak
├── azure
├── group_vars
│   ├── production
│   │   ├── vars
│   │   └── vault
│   ├── init-linuxserver
│   │   ├── vars
│   │   └── vault
│   └── linuxserver
│       ├── vars
│       └── vault
├── playbooks
│   ├── packages
│   │   ├── install-production-prometheus-node-exporter.yml
│   │   ├── install-prometheus-node-exporter.yml
│   │   └── install-systemtools.yml
│   ├── services
│   │   └── connect-graylog.yml
│   ├── systemsettings
│   │   ├── set-timezone-europe-berlin.yml
│   │   └── update-hosts-file.yml
│   └── users
│       └── create-user-webdata.yml
└── vault_pwd

Variablen

So sieht eine vars Datei für die Gruppe linuxserver aus:

root@server:/etc/ansible# cat group_vars/linuxserver/vars
---
ansible_connection: ssh
ansible_user: ansibleadmin
ansible_ssh_private_key_file: /home/ansibleadmin/.ssh/id_rsa
ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
ansible_become: yes
ansible_become_method: sudo
ansible_become_user: root
ansible_become_pass: "{{ vault_ansible_become_pass }}"

Inventory

Ansible Docs: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html

Meine Inventory Datei heißt azure, weil ich Ansible im Zuge einer Azure Evaluierung einsetze.

root@vm-azure-manager:/etc/ansible# cat azure
#Here i was experimenting where do set this option for being applied everywhere.
#ansible_ssh_common_args='-o StrictHostKeyChecking=no'

[prometheus]
prometheus-01

[grafana]
grafana-01

[graylog]
graylog-01

[es-nodes]
es-node-01

[init-linuxserver:children]
prometheus
grafana
graylog
es-nodes

[linuxserver:children]
prometheus
grafana
graylog
es-nodes

[graylogclients:children]
grafana
prometheus
es-nodes

Bisher habe ich folgendes gemeistert:

Durch die Verschachtelung von Gruppen kann ich meine Hosts kategorisieren und habe eine ähnliche Vorangehensweise wie beim Administrieren von Benutzerrechten, d.h. bei Änderungen den Aufwand zu minimieren, weil man z.B. einen neuen Host nur noch einer Gruppe zuweist oder einen alten aus einer Gruppe löschen muss.

Ansible Vault

Ansible Docs: https://docs.ansible.com/ansible/latest/user_guide/vault.html

Ich habe am Anfang die Passwörter für meine User, die Ansible benutzen sollte, klar lesbar in meine Konfig-Dateien geschrieben. Da ich davon aber absolut kein Freund bin, habe ich mich also zeitnah darum gekümmert und herausgefunden, dass es die sog. Ansible-Vault gibt.  Vault heißt Tresor. Also ein verschlüsselter Container, der eure Passwörter und sonstige Einstellungen beinhalten kann. Ich habe aktuell nur ein Passwort darin gespeichert.

Wie ihr schon anhand meiner Ordnerstruktur gesehen habt, gibt es jeweils in jedem Unterordner einer Gruppe eine Datei namens "vault". Das sind meine geschützten Bereiche für die jeweilige Gruppe.

So hier habe ich es gemacht:

  1. Eine Schlüsseldatei "vault_pwd" erstellt und in Klartext den Schlüssel eingetragen, der global zum Ver- und Entschlüsseln benutzt werden soll.

    Man muss keinen globalen Schlüssel verwenden. Das kann man so einstellen wie man es möchte.

    1. root@server:# nano vault_pwd
    2. Schlüssel eintragen
  2. Globale Schlüsseldatei in der ansbile.cfg aktiviert
    1. vault_password_file = /etc/ansible/vault_pwd
  3. zu verschlüsselnde Variablen mit einem Editor in die jeweilige vault Datei eintragen
  4. vault Datei verschlüsseln: ansible-vault encrypt vault
    1. Da wir einen globalen Schlüssel aktiviert haben, wird dieser automatisch zum Verschlüsseln benutzt, sodass ihr keinen Schlüssel an der Stelle eingeben müsst.

    2. So habe ich z.B. das Passwort hinterlegt, dass benutzt wird um SUDO Rechte zu aktivieren:
      1. vault_ansible_become_pass: DAS-PASSWORT

        1. Ansible empfiehlt als Variablennamen der zu verschlüsselnden Variable ein "vault_" als Präfix zu verwenden. Ich finde das gut, da man so gleich den Bezug der Verwendung herstellen kann.
  5. Passwort in unverschlüsselter Variable aus verschlüsselter Variable aufrufen
    1. So sieht der Aufruf dann in meiner "vars" Datei aus: ansible_become_pass: "{{ vault_ansible_become_pass }}"
    2. Die Syntax nennt sich jinja2

Alles was ich jetzt mit Ansible mache, funktioniert mit verschlüsselten Passwörtern.

Playbooks

Ansible Docs: https://docs.ansible.com/ansible/latest/user_guide/playbooks.html

Ansible-Systembenutzer bereitstellen

Funktionen

Probleme

Man benötigt natürlich auf allen Hosts für das erstmalige Bereitstellen mit Ansible einen Systemuser mit SUDO Rechten. Da ich für Ansible Arbeiten einen eigenen Systemuser nutzen möchte, habe ich als erstes einen neuen user auf allen Hosts angelegt. Dafür habe ich den User benutzt, den man mit der Installation von Debian anlegen muss.

Playbook "create-user-ansibleadmin.yml

root@server:/etc/ansible# cat playbooks/users/create-user-ansibleadmin.yml
---
- hosts: init-linuxserver
  remote_user: initial-user-from-fresh-install-with-sudo-rights
  become: yes
  become_method: sudo
  become_user: root

  tasks:
    - name: Ansible create user ansibleadmin with home directory
      user:
       name: ansibleadmin
       createhome: yes

    - name: create directory .ssh
      file:
       path: /home/ansibleadmin/.ssh
       state: directory
       owner: ansibleadmin
       group: ansibleadmin
       mode: 0700

    - name: Ansible copy the ssh public key of the user ansibleadmin to the remote host
      copy:
       src: "/home/ansibleadmin/.ssh/id_rsa.pub"
       dest: "/home/ansibleadmin/.ssh/authorized_keys"
       owner: ansibleadmin
       group: ansibleadmin

    - name: Add user ansibleadmin to sudo group and grant sudo rights
      user:
       name: ansibleadmin
       groups: sudo

Debian Paket mit apt installieren

Playbook: "install-systemtools.yml"

root@server:/etc/ansible# cat playbooks/packages/install-systemtools.yml
---
- hosts: linuxserver
  tasks:
    - name: install lsb-release
      apt: name=lsb-release state=present

    - name: install lsof
      apt: name=lsof state=present

 Playbook: Azure CLI installieren

---
- hosts: azure-master
  tasks:
    - name: Install apt-transport-https
      apt: name=apt-transport-https state=present

    - name: Add Azure Repository to sources.list.d
      apt_repository:
       repo: deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ stretch main
       state: present
       filename: azure-cli

    - name: Add Microsoft´s signature key
      apt_key:
       url: https://packages.microsoft.com/keys/microsoft.asc
       state: present

    - name: make an apt-update before be able to find azure-cli package
      apt:
       update_cache: yes

    - name: Install Azure CLI
      apt: name=azure-cli state=present

Playbook: Docker CE installieren

---
- hosts: docker-vm
  tasks:
    - name: Add Azure Repository to sources.list.d
      apt_repository:
       repo: deb [arch=amd64] https://download.docker.com/linux/debian stretch stable
       state: present
       filename: docker-ce

    - name: Add Docker CE signature key
      apt_key:
       url: https://download.docker.com/linux/debian/gpg
       state: present

    - name: make an apt-update before be able to find azure-cli package
      apt:
       update_cache: yes

    - name: Install Docker CE
      apt: name=docker-ce state=present

Datei kopieren - hosts Datei bereitstellen

Playbook "update-hosts-file.yml"

root@server:/etc/ansible# cat playbooks/systemsettings/update-hosts-file.yml
---
- hosts: linuxserver
# steht alles in den "Vars" Dateien
#  remote_user: ansibleadmin
#  become: yes
#  become_method: sudo
#  become_user: root

  tasks:
    - name: copy the hosts file from host "server" to the group linuxserver
      copy:
       src: "/etc/hosts"
       dest: "/etc/hosts"
       owner: root
       group: root
Hintergrund

Ich arbeite in meiner testumgebung mit den Hosts Dateien, weil ich auf die Schnelle kein DNS aufbauen konnte. Zum Einen bin ich kein Experte für DNS (erst einmal damit rumprobiert) und Zweitens wollte ich so schnell wie möglich alle Hosts mit Namen anstelle von IP Adressen ansprechen.

Zeitzone einstellen

Playbook "set-timezone-europe-berlin.yml"

root@server:/etc/ansible# cat playbooks/systemsettings/set-timezone-europe-berlin.yml
---
- hosts: linuxserver
  tasks:
    - name: set timezone to Europe/Berlin
      timezone:
       name: Europe/Berlin
Hintergrund

Da ich die Debian VMs in Azure über den RessourcenManager von Azure bereitstellen lassen habe, gab es nachträglich Einstellungen, die angepasst werden mussten. Dazu gehörte u.a. die Zeitzone.

Ansible

Playbook - install Java 8 JDK

# cat /etc/ansible/playbooks/apt/i-java8jdk.yml                                                      ---
- hosts: g-java8jdk
  tasks:
    - name: Add Java 8 JDK Repository to sources.list.d
      apt_repository:
       repo: deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main
       state: present
       filename: webupd8team-java8jdk

    - name: Add webupd8team signature key
      apt_key:
       keyserver: keyserver.ubuntu.com
       id: EEA14886

    - name: make an apt-update before be able to find java packages
      apt:
       update_cache: yes

    - name: set licence selected
      shell: /bin/echo debconf shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections
      sudo: yes

    - name: set licence seen
      shell: /bin/echo debconf shared/accepted-oracle-license-v1-1 seen true | /usr/bin/debconf-set-selections
      sudo: yes

    - name: Install oracle-java8-installer
      apt: name={{item}} state=present
      with_items:
      - java-common
      - oracle-java8-installer
      - oracle-java8-set-default

Apache2

Apache2

Apache2 - SSL Zertifikat mit Let´s encrypt für Webserver bereitstellen

  1. letsencrypt über die Paketverwaltung installieren: #aptitude install letsencrypt
  2. Zertifikat generieren:
    1. # certbot certonly --manual --rsa-key-size 4096
    2. Die Fragen beantworten und z.B. die Domain festlegen.
  3. Verifikations-Datei auf dem Webserver anlegen:

    1. Hinweis: Die kryptischen Bezeichner sind bei euch anders - ersetzt sie einfach.

    2. mkdir /var/www/letsencrypt/.well-known/acme-challenge
      cd /var/www/letsencrypt/.well-known/acme-challenge
      echo -n N_aDTbuhynhvqhGaqs1OVHs1_Bl1A4Z9rHtFhFeV1cA.DGo-QeCJ79p7eoFfCvjK4Np9a_RsbbtjWteKY0QMl0I > N_aDTbuhhynhvqhGaqs1OVHs1_Bl1A4Z9rHtFhFeV1cA
  4. Dem Apache2 noch die neuen Zertifikate beibringen:
    1. in eure config unter /etc/apache2/site-enabled/eureseite.conf folgende Zeilen unter HTTPS einfügen:
      ssl_certificate /etc/letsencrypt/live/meinedomain.de/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/meinedomain.de/privkey.pem;
  5. Danach die Verzeichnisstruktur der Verifikations-Datei wieder löschen.
  6. Apache2 Server neustarten: #/etc/init.d/apache2 restart

Fertig!

 

Quelle: https://serverfault.com/questions/750902/how-to-use-lets-encrypt-dns-challenge-validation

 

Apache2

Apache2 - Webspace passwortgeschützt mit einzelner Ausnahme

Quelle: https://stackoverflow.com/questions/2641646/how-to-accomplish-authtype-none-in-apache-2-2

Quelle: https://gist.github.com/lokesh-webonise/5625636

 

Apache2

Apache2 – SSL erzwingen bzw. HTTP-Zugriffe umleiten

Der eigentliche vhost

Hier würden auch directory-, Authentication-, und ähnliche Anweisungen erfolgen.

<VirtualHost 127.0.0.1:443>
	ServerName localhost:443
	
	SSLEngine On
        SSLCertificateFile /etc/apache2/ssl/apache.pem		
</VirtualHost>

Das ist der „Dummy“-vhost

Dieser vhost dient dann nur noch dazu um eine Umleitung auf den oberen „443-vhost“ zu machen.

<VirtualHost localhost:80>
	ServerName localhost
	
	# Das folgende erzwingt SSL
	RewriteEngine On
	RewriteCond %{HTTPS} off
	RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

 

Quelle: http://blog.rvi-media.de/linux/apache2-ssl-erzwingen-bzw-http-zugriffe-umleiten/

 

Apache2

Apache 2 - SVN

SVN

SVN Installation

- Subversion installieren:

apt-get update
apt-get install subversion

Speicherort für Repositories anlegen

- Ordner erstellen wo alle Repositories gespeichert werden sollen

# mkdir /var/svn-repos/

- Rechte für Apache2 vergeben

chown www-data.www-data /var/svn-repos

SVN Repository erstellen

svnadmin create /var/svn-repos/repo123

Dateirechte für Apache2 für Repository vergeben

 chown -R www-data:www-data /var/svn-repos/repo123

Apache 2 Vorbereitungen

Apache SVN Modul installieren

apt-get install libapache2-svn

Apache Module aktivieren

a2enmod dav
a2enmod dav_svn
a2enmod authz_svn

Benutzerverzeichnis anlegen

- nun legen wir für den Webzugriff unsere User an

Benutzerverzeichnis erstmalig anlegen mit der Option -c

Achtung! Bestehende Nutzer werden dabei überschrieben! Das ist zum Anlegen des Verzeichnisses, nicht eines neuen Users!

htpasswd -c /etc/apache2/dav_svn.passwd user1

- danach müsst ihr ein Passwort festlegen

Weitere Benutzer in das Benutzerverzeichnis anlegen

htpasswd /etc/apache2/dav_svn.passwd user2

- danach müsst ihr ebenfalls ein Passwort festlegen

Mit diesen Benutzern könnt ihr jetzt arbeiten und Zugriffe steuern.

Accessfile anlegen

- diese Datei beinhaltet die Regelungen welche User oder gruppe auf welche Repos oder Verzeichnisse zugreifen darf

- diese Datei unter /etc/apache2 speichern

- Beispiel: dav_svn.accessfile

# Definitions of groups with users from operating system
[groups]
admins = user1,user2
testusers = user2

# Definitions of repositories

[user1:/]
user1 = rw
user2 = r

[user2:/]
user1 = r
user2 = rw

[test:/]
@testusers = rw

Apache2 Konfiguration

Nun müsst ihr eine sog. VHOST Konfiguration anlegen und euren Ordner angeben, den wir am Anfang angelegt haben. In unserem Beispiel also /var/svn-repos.

Hier eine Beispiel Konfiguration:

<Location /svn>
        DAV svn
        SVNParentPath /var/svn-repos
        SVNListParentPath On

        AuthType Basic
        AuthName "SVN Authorization Realm"
        AuthUserFile /etc/apache2/dav_svn.passwd
        Require valid-user
        AuthzSVNAccessFile /etc/apache2/dav_svn.accessfile
</Location>

Fertig!

Danach nochmal den Apache2 neustarten /etc/init.d/apache2 restart und ihr könnt euer SVN bequem für eure Teams einrichten ohne auf eurem Linuxsystem Unmengen an Usern anlegen zu müssen.

Backup

Backup Technologien und Lösungen

Backup

Backup mit duply

Quelle: https://www.thomas-krenn.com/de/wiki/Backup_unter_Linux_mit_duply

Debian

Debian

System Einstellungen

Root Passwort zurücksetzen

Quelle: https://www.thomas-krenn.com/de/wiki/Linux_Root_Passwort_wiederherstellen

 

Standard Editor ändern

Der Befehl sieht so aus: update-alternatives --config editor

Die Ausgabe dazu:

root@adminsrv:/# update-alternatives --config editor
There are 9 choices for the alternative editor (providing /usr/bin/editor).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/joe         70        auto mode
  1            /bin/nano            40        manual mode
  2            /usr/bin/jmacs       50        manual mode
  3            /usr/bin/joe         70        manual mode
  4            /usr/bin/jpico       50        manual mode
  5            /usr/bin/jstar       50        manual mode
  6            /usr/bin/mcedit      25        manual mode
  7            /usr/bin/rjoe        25        manual mode
  8            /usr/bin/vim.basic   30        manual mode
  9            /usr/bin/vim.tiny    15        manual mode

Press <enter> to keep the current choice[*], or type selection number: 6

Ich benutze am liebsten den Editor vom Paket "mc", das MidnightCommander heißt.

MC - internen Editor benutzen

Quelle: https://askubuntu.com/a/16782

Zeitzone

Quelle: https://wiki.debian.org/TimeZoneChanges

 

Debian

bash

Arbeiten mit Variablen

Arrays

Array erstellen

 # Array mit virtuellen Maschinen anlegen
 machines=(vm01,vm02,vm03)
 # Erstellt eine Liste mit den virtuellen Maschinen
    IFS=';' read -r -a arrhosts <<< $(echo $machines | tr ',' ';')

Array iterieren

    echo "Hier eine Liste der virtuellen Maschinen : "
    i=0
    for vm in "${arrhosts[@]}"
    do 
        echo $i" - "$vm
	i=$(($i+1))
    done
    
    #Ausgabe:
    0 - vm01
    2 - vm02
    3 - vm03

Scripte mit Parametern

 

Beispiel mit Abfrage eines bestimmten Wertes der Parametern

https://stackoverflow.com/a/16496491

#!/bin/bash

usage() { echo "Usage: $0 [-s <45|90>] [-p <string>]" 1>&2; exit 1; }

while getopts ":s:p:" o; do
    case "${o}" in
        s)
            s=${OPTARG}
            ((s == 45 || s == 90)) || usage
            ;;
        p)
            p=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${s}" ] || [ -z "${p}" ]; then
    usage
fi

echo "s = ${s}"
echo "p = ${p}"

Ausgabe:

$ ./myscript.sh
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -h
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s "" -p ""
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 10 -p foo
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 45 -p foo
s = 45
p = foo

$ ./myscript.sh -s 90 -p bar
s = 90
p = bar

Beispiel mit getopts

http://mywiki.wooledge.org/BashFAQ/035

!/bin/sh
# Usage info
show_help() {
cat << EOF
Usage: ${0##*/} [-hv] [-f OUTFILE] [FILE]...
Do stuff with FILE and write the result to standard output. With no FILE
or when FILE is -, read standard input.

-h          display this help and exit
-f OUTFILE  write the result to OUTFILE instead of standard output.
-v          verbose mode. Can be used multiple times for increased
                verbosity.
EOF
}

# Initialize our own variables:
output_file=""
verbose=0

OPTIND=1
# Resetting OPTIND is necessary if getopts was used previously in the script.
# It is a good idea to make OPTIND local if you process options in a function.

while getopts hvf: opt; do
    case $opt in
        h)
              show_help
              exit 0
              ;;
          v)  verbose=$((verbose+1))
              ;;
          f)  output_file=$OPTARG
              ;;
          *)
              show_help >&2
              exit 1
              ;;
      esac
done
shift "$((OPTIND-1))"   # Discard the options and sentinel --

# Everything that's left in "$@" is a non-option.  In our case, a FILE to process.
printf 'verbose=<%d>\noutput_file=<%s>\nLeftovers:\n' "$verbose" "$output_file"
printf '<%s>\n' "$@"

# End of file

Erstellen von Passwoertern

Quelle: https://www.howtogeek.com/30184/10-ways-to-generate-a-random-password-from-the-command-line/

Generate a Random Password

For any of these random password commands, you can either modify them to output a different password length, or you can just use the first x characters of the generated password if you don’t want such a long password. Hopefully you’re using a password manager like LastPass anyway so you don’t need to memorize them.

This method uses SHA to hash the date, runs through base64, and then outputs the top 32 characters.

date +%s | sha256sum | base64 | head -c 32 ; echo

This method used the built-in /dev/urandom feature, and filters out only characters that you would normally use in a password. Then it outputs the top 32.

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32};echo;

This one uses openssl’s rand function, which may not be installed on your system. Good thing there’s lots of other examples, right?

openssl rand -base64 32

This one works a lot like the other urandom one, but just does the work in reverse. Bash is very powerful!

tr -cd '[:alnum:]' < /dev/urandom | fold -w30 | head -n1

Here’s another example that filters using the strings command, which outputs printable strings from a file, which in this case is the urandom feature.

strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; echo

Here’s an even simpler version of the urandom one.

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6

This one manages to use the very useful dd command.

dd if=/dev/urandom bs=1 count=32 2>/dev/null | base64 -w 0 | rev | cut -b 2- | rev

You can even create a random left-hand password, which would let you type your password with one hand.

</dev/urandom tr -dc '12345!@#$%qwertQWERTasdfgASDFGzxcvbZXCVB' | head -c8; echo ""

If you’re going to be using this all the time, it’s probably a better idea to put it into a function. In this case, once you run the command once, you’ll be able to use randpw anytime you want to generate a random password. You’d probably want to put this into your ~/.bashrc file.

randpw(){ < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-16};echo;}

You can use this same syntax to make any of these into a function—just replace everything inside the { }

And here’s the easiest way to make a password from the command line, which works in Linux, Windows with Cygwin, and probably Mac OS X. I’m sure that some people will complain that it’s not as random as some of the other options, but honestly, it’s random enough if you’re going to be using the whole thing.

date | md5sum

Yeah, that’s even easy enough to remember.

 

bash oneliner commands

* alle durch salt generierten Icinga config files in einer Datei schreiben und den salt header entfernen
* apply rules in /etc/icinga2/zones.d/global-templates/notifications/slack/ :

workdir="/etc/icinga2/zones.d/global-templates/notifications/slack";for file in $(ls ${workdir}); do echo ${file}; cat ${workdir}/${file} | sed  -E -e '/^#.*|^\/\*|^\*\//d';echo "";echo "" ; done > /tmp/slack.log
Debian

Linksammlung Docs

Debian

fail2ban

Anzeigen von gebannten IPs eines JAILs:

# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     6
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 0
   |- Total banned:     1
   `- Banned IP list:

sshd ist hier ein sog. JAIL also Gefängnis.

IP entbannen

# fail2ban-client set sshd unbanip 192.168.1.100
192.168.1.100
Debian

Debian Upgrade auf neuen Release

Quelle: https://www.cyberciti.biz/faq/update-upgrade-debian-9-to-debian-10-buster/

Upgrade Debian 9 to Debian 10 Buster

The procedure is as follows:

  1. Backup your system.
  2. Update existing packages and reboot the Debian 9.x system.
  3. Edit the file /etc/apt/sources.list using a text editor and replace each instance of stretch with buster.
  4. Update the packages index on Debian Linux, run: sudo apt update
  5. Prepare for the operating system upgrade, run: sudo apt upgrade
  6. Finally, update Debian 9 to Debian 10 buster by running: sudo apt full-upgrade
  7. Reboot the Linux system so that you can boot into Debian 10 Buster
  8. Verify that everything is working correctly.

Let us see all command in details.

Step 1. Backup your system

It is crucial to backup all data and system configurations. Cloud-based VMs can be quickly backup and restore using snapshots. I use rsnapshot, which is the perfect solution for making backups on the local or remote servers. Check os version in Linux:
lsb_release -a
Sample outputs:

No LSB modules are available.
Distributor ID:	Debian
Description:	Debian GNU/Linux 9.9 (stretch)
Release:	9.9
Codename:	stretch

Note down the Linux kernel version too:
uname -mrs
Sample outputs:

Linux 4.9.0-9-amd64 x86_64

Step 2. Update installed packages

Type the following apt command or apt-get command:
sudo apt update
sudo apt upgrade
sudo apt full-upgrade
sudo apt --purge autoremove

OR
sudo apt-get update
sudo apt-get upgrade
sudo apt-get full-upgrade
sudo apt-get --purge autoremove

Reboot the Debian 9.x stretch to apply the kernel and other updates:
sudo reboot

Step 3. Update /etc/apt/sources.list file

Before starting the upgrade you must reconfigure APT’s source-list files. To view current settings using the cat command:
cat /etc/apt/sources.list
Sample outputs:

deb http://cdn-aws.deb.debian.org/debian stretch main
deb http://security.debian.org/debian-security stretch/updates main
deb http://cdn-aws.deb.debian.org/debian stretch-updates main

The stretch indicates that we are using an older version. Hence, we must change all the references in this file from Stretch to Buster using a text editor such as vim:
vi /etc/apt/sources.list
I prefer to use sed tool, but first backup all config files using the cp command:
sudo cp -v /etc/apt/sources.list /root/
sudo cp -rv /etc/apt/sources.list.d/ /root/
sudo sed -i 's/stretch/buster/g' /etc/apt/sources.list
sudo sed -i 's/stretch/buster/g' /etc/apt/sources.list.d/*
### see updated file now ###
cat /etc/apt/sources.list

How To Upgrade Debian 9 Stretch To Linux Debian 10 Buster
APT source-list files updated to use buster

 

Updating the package list

Simply run:
sudo apt update
Updating the package list

Step 4. Minimal system upgrade

A two-part process is necessary to avoid the removal of large numbers of packages that you want to keep. Therefore, first run the following:
sudo apt upgrade
Debian 9 to Debian 10 Minimal system upgrade
Just follow on-screen instructions. During the upgrade process, you may get various questions, like “Do you want to restart the service? ” OR “keep or erase config options” and so on.
Restart services during package upgrades without asking
And:
What do you want to do about modified config file

Step 5. Upgrading Debain 9 to Debian 10

In addition, minimum upgrades we need to do full upgrades to finish the whole Debian 9 to Debian 10 update process. This is the main part of the upgrade. In other words, execute the following command to perform a complete upgrade of the system, installing the newest available versions of all packages, and resolving all possible dependency:
sudo apt full-upgrade
How to upgrade Debian 9 to Debian 10 Buster using the CLI
Reboot the Linux system to boot into Debian Linux 10 buster, issue:
sudo reboot

Step 6. Verification

It is time to confirm the upgrade. Run:
uname -r
lsb_release -a

Sample outputs:

No LSB modules are available.
Distributor ID:	Debian
Description:	Debian GNU/Linux 10 (buster)
Release:	10
Codename:	buster

Finally, clean up outdated packages using the apt command/apt-get command:
sudo apt --purge autoremove
How to Upgrade Debian 9 Stretch to Debian 10 Buster

Conclusion

And there you have it. We have successfully upgraded to Debian Linux 10. Debian project also posted an in-depth guide here that explains other issues one might face during installation.

Debian

missing firmware

Jeder kennt es, wenn man sich ein Update zieht und diverse Treiber nicht verfügbar sind.

Auf dieser Seite will ich zu meinen Fällen Links und Lösungen zeigen wie ich die Herausforderungen lösen konnte.

Mein System

Ich benutze nur noch Debian als Linux, da es sich einfach aus meiner Sicht am besten verwalten lässt und nicht überladen ist. Nun gibt es hier 2 Herausforderungen:
Zum Einen sind im aktuellen Stable Release oft nicht die aktuellsten Treiber und Software Pakete eingebaut.
Und zum Anderen tun sich die Hersteller leider heutzutage immer noch schwer mit dem Support von Linux. Darum ärgert man sich immer wieder mit fehlenden Treibern herum. Vor allem bei Laptops ist das häufiger das Problem.

Aus diesem Grund benutze ich auf meinem Laptop (von Tuxedo) einen sehr aktuellen Kernel und versuche auch immer den neuesten zu verwenden, da hier meisten für ganz aktuelle Hardware die Treiber vorhanden sind. Wenn auch manchmal noch im Teststadium.

saphir: ~/ $ uname -a
Linux saphir 5.6.0-0.bpo.2-amd64 #1 SMP Debian 5.6.14-2~bpo10+1 (2020-06-09) x86_64 GNU/Linux

Meine fehlenden Pakete

W: Possible missing firmware /lib/firmware/rtl_nic/rtl8125a-3.fw for module r8169
W: Possible missing firmware /lib/firmware/rtl_nic/rtl8168fp-3.fw for module r8169
W: Possible missing firmware /lib/firmware/i915/icl_dmc_ver1_09.bin for module i915
W: Possible missing firmware /lib/firmware/i915/tgl_dmc_ver2_04.bin for module i915
W: Possible missing firmware /lib/firmware/i915/skl_huc_2.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/bxt_huc_2.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/kbl_huc_4.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/glk_huc_4.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/kbl_huc_4.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/cml_huc_4.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/cml_guc_33.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/icl_huc_9.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/ehl_huc_9.0.0.bin for module i915
W: Possible missing firmware /lib/firmware/i915/ehl_guc_33.0.4.bin for module i915
W: Possible missing firmware /lib/firmware/i915/tgl_huc_7.0.3.bin for module i915
W: Possible missing firmware /lib/firmware/i915/tgl_guc_35.2.0.bin for module i915

Wegfindung

Ich bin dann auf der Suche nach dem fehlenden Firmwares auf folgenden Bugreport gestoßen und fand dann durch diesen Post hier ein Repo für Linux Kernel mit Firmware Modulen.

https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=947356#30

Repo Linux Firmware Module

https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/rtl_nic

Repo-Ordner für meine fehlenden Module

rtl_nic

https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/rtl_nic

i915

https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/i915/

Lösungsweg

  1. Git Repo von der Projektseite klonen in einen lokalen Ordner
    1. mkdir /home/USER/GIT/linux_firmware
    2. cd /home/USER/GIT/linux_firmware
    3. git clone git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git
  2. Module in die entsprechenden Ordner des Systems kopieren und alle vorhanden überschreiben
    1. z.b. i915:
      1. /bin/cp -frv /home/USER/GIT/linux_kernel/linux-firmware/i915/* /lib/firmware/i915/
  3. initramfs aktualisieren und die neuen Module laden lassen
    1. update-initramfs -u
      1. Parameter "-u" -> Update an existing initramfs

 

Debian

Backports

Backports aktivieren

Repo für Backports hinterlegen /etc/apt/sources.list.d/backports.list:

# buster backports
deb http://http.debian.net/debian buster-backports main

Danach die Paketverwaltung neu laden:

apt-get update

Paket aus den Backports installieren:

apt-get install PAKET -t buster-backports
Debian

Kernel updaten

Vorbereitungen

Backports aktivieren: https://wiki.freakylabs.de/books/linux/page/backports

 

Nach verfügbaren Kernel Versionen suchen

apt-cache search linux-image
----- gekürzte Liste -----
linux-headers-4.19.0-10-amd64 - Header files for Linux 4.19.0-10-amd64
linux-headers-4.19.0-10-cloud-amd64 - Header files for Linux 4.19.0-10-cloud-amd64
linux-headers-4.19.0-10-rt-amd64 - Header files for Linux 4.19.0-10-rt-amd64
linux-headers-4.19.0-11-amd64 - Header files for Linux 4.19.0-11-amd64
linux-headers-4.19.0-11-cloud-amd64 - Header files for Linux 4.19.0-11-cloud-amd64
linux-headers-4.19.0-11-rt-amd64 - Header files for Linux 4.19.0-11-rt-amd64
.... snipped ....
linux-image-5.5.0-0.bpo.2-amd64 - Linux 5.5 for 64-bit PCs (signed)
linux-image-5.5.0-0.bpo.2-cloud-amd64 - Linux 5.5 for x86-64 cloud (signed)
linux-image-5.6.0-0.bpo.2-amd64 - Linux 5.6 for 64-bit PCs (signed)
linux-image-5.6.0-0.bpo.2-cloud-amd64 - Linux 5.6 for x86-64 cloud (signed)
linux-image-5.6.0-0.bpo.2-rt-amd64 - Linux 5.6 for 64-bit PCs, PREEMPT_RT (signed)
linux-image-5.7.0-0.bpo.2-amd64 - Linux 5.7 for 64-bit PCs (signed)
linux-image-5.7.0-0.bpo.2-cloud-amd64 - Linux 5.7 for x86-64 cloud (signed)

Kernel Version installieren

apt-get install linux-image-5.7.0-0.bpo.2-amd64
Debian

Paket selber bauen - dpkg-buildpackage

Beispiel Paket: libssh2-1

Problem:

Debian Buster -> Saltstack Master Anbindung per SSH Key an Gitlab

Vorgehensweise:

deb-src http://deb.debian.org/debian/ bullseye main

apt-get update

apt-get install devscripts debhelper-compat libgcrypt20-dev zlib1g-dev chrpath

mkdir /root/build

cd /root/build

apt-get source libssh2-1

vim /root/build/libssh2-1.9.0/debian/control
-> Build-Depends: debhelper-compat (= 13) => Build-Depends: debhelper (>= 12)
-> vim /root/build/libssh2-1.9.0/debian/compat => 10 als Inhalt einfügen

dch -i
 
	libssh2 (1.9.0-2.1) stable; urgency=medium

		* Non-maintainer upload.

	-- David Fritsch <darkentik@gmx.de>  Sat, 27 Mar 2021 20:14:59 +0100

dpkg-buildpackage

==> DEB Paket: libssh2-1_1.9.0-2.1_amd64.deb
Debian

MySQL - MariaDB

Datenbank mysql wiederherstellen

Quelle: https://stackoverflow.com/questions/8911115/how-to-recover-recreate-mysqls-default-mysql-database

mysql_install_db

mysqld --initialize

CREATE OR REPLACE USER

Quelle: https://mariadb.com/kb/en/create-user/#or-replace

GRANT PRIVILEGES

Quelle: https://phoenixnap.com/kb/how-to-create-mariadb-user-grant-privileges

Password with special characters

Quelle: https://www.tutorialspoint.com/set-special-characters-for-password-while-creating-a-new-mysql-user

create user 'yourUserName'@'yourHostName' identified by 'yourSpecialCharacterPassword';
Debian

Paketmanager - apt

Paket Neuinstallation und Neuerstellung von Dateien und Ordnern

Quelle: https://askubuntu.com/questions/66533/how-can-i-restore-configuration-files

  1. Find out what package installed the config file:

    $ dpkg -S unity-greeter.conf
    unity-greeter: /etc/lightdm/unity-greeter.conf
    

    As you can see, the name of the package is unity-greeter.

    If you deleted a directory, like /etc/pam.d, you can list every package that added to it by using the directory path:

    $ dpkg -S /etc/pam.d
     login, sudo, libpam-runtime, cups-daemon, openssh-server, cron, policykit-1, at, samba-common, ppp, accountsservice, dovecot-core, passwd: /etc/pam.d
    
  2. Run the following command, replacing <package-name> with the name of the package:

    sudo apt install --reinstall -o Dpkg::Options::="--force-confask,confnew,confmiss" <package-name>
    

    And for restoring the directory:

    sudo apt install --reinstall -o Dpkg::Options::="--force-confask,confnew,confmiss" $(dpkg -S /etc/some/directory | sed 's/,//g; s/:.*//')
    
  3. If everything worked as expected, you should get a message:

    Configuration file `/etc/lightdm/unity-greeter.conf', does not exist on system. 
    Installing new config file as you requested.
    
  4. A Practical example when needing to reinstall all of the PulseAudio configuration files:

    apt-cache pkgnames pulse |xargs -n 1 apt-get -o Dpkg::Options::="--force-confmiss" install --reinstall 
    

Festplattenverwaltung

Vergrößern, verschlüsseln usw.

Festplattenverwaltung

Festplattenverwaltung - fdisk,lvm,dd

Partitionstabelle kopieren

dd if=/dev/sdc of=/dev/sdd bs=512 count=1

Parameter erklärt:

if -> input device

of -> output device

bs -> blocksize

count -> Anzahl der Blöcke, die kopiert werden sollen

Festplatte vergrößern

.. mit LVM

Das Programm "fdisk" für die Festplatte starten:

/# fdisk /dev/sda

Welcome to fdisk (util-linux 2.33.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p
Disk /dev/sda: 25 GiB, 26843545600 bytes, 52428800 sectors
Disk model: QEMU HARDDISK   
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xb5d10c66

Device     Boot   Start      End  Sectors  Size Id Type
/dev/sda1  *       2048  1953791  1951744  953M 83 Linux
/dev/sda2       1953792 52428799 50475008 24,1G  5 Extended
/dev/sda5       1955840 52428799 50472960 24,1G 8e Linux LVM

Dann sieht man alle aktuellen Partitionen.

Ich habe mich beim Einrichten für folgendes Setup entschieden:

-- /dev/sda
 |- /dev/sda1 -> /boot
 |- /dev/sda2 -> LVM partition
  |-/dev/sda5 -> volumegroup (vg01)
   |-vg01 -> logical volume swap (lvswap)
   |-vg01 -> logical volume system (lvsys)

Zuerst muss man die Festplatte an sich vergrößern.

Da ich die Virtualisierungssoftware "Proxmox" einsetze ist das total einfach.

Entweder per CLI qm resize VMID FestplattenID +5G oder man nutzt die grafische Weboberfläche und fügt über den Punkt "Hardware" -> entsprechende Festplatte -> Knopf oben in der Leiste "resize disk" einfach die Größe hinzu.

Danach kann man sich die neue Größe mit fdisk -l anzeigen lassen/kontrollieren.

Nun muss man die bestehenden Partitionen mittels fdisk /dev/sdX (X steht für euren Festplatten Identifier Buchstabe) löschen und 1 primäre über die gesamte neue Größe und eine logische über die gesamte neue Größe erstellen.

Am Ende noch die Änderungen speichern mit dem Befehl "w" für "write" und dann noch mittels "partprobe" die neuen Festplatteninformationen einlesen lassen.

Dann kann man mit "vgdisplay" überprüfen ob es geklappt hat und es geht weiter mit dem "lvextend".

Da ich die gesamte Größe haben will kann ich einfach sagen er soll alles nehmen was frei ist:

lvextend -l +100%FREE /dev/vg01/lvsys

Und mit "lvdisplay" sehe ich nun meine neue Größe:

/# lvdisplay 
  --- Logical volume ---
  LV Path                /dev/vg01/lvswap
  LV Name                lvswap
  VG Name                vg01
  LV UUID                04chsG-gbxM-RrZZ-1wLv-Nj48-tPgE-0GmDIv
  LV Write Access        read/write
  LV Creation host, time debian, 2020-02-17 17:03:48 +0100
  LV Status              available
  # open                 2
  LV Size                <1,86 GiB
  Current LE             476
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           254:1
   
  --- Logical volume ---
  LV Path                /dev/vg01/lvsys
  LV Name                lvsys
  VG Name                vg01
  LV UUID                nUBumD-WQ2c-wiMW-fXyS-tvoa-ELZB-rcUA6H
  LV Write Access        read/write
  LV Creation host, time debian, 2020-02-17 17:05:38 +0100
  LV Status              available
  # open                 1
  LV Size                <22,21 GiB
  Current LE             5685
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           254:0
Festplattenverwaltung

Cryptsetup mit LUKS - Festplattenverschlüsselung

Quelle: https://linuxwiki.de/cryptsetup

1. LUKS-Partition initialisieren

 

cryptsetup luksFormat -c aes-cbc-essiv:sha256 -s 256 /dev/sdc1

Ich habe hier z.b. ein RAID1 Device ausgewählt z.b. /dev/md0. Somit ist das gesamte RAID 1 verschlüsselt.

 

2. LUKS-Partition öffnen und mapping erstellen (/dev/MAPPING)

Öffnen mit Passwort
cryptsetup luksOpen /dev/sdc1 cr_crypto

 

 

LUKS Gerät löschen

Quelle: https://unix.stackexchange.com/a/606231

cryptsetup-reencrypt --decrypt

USB zum Entschlüsseln

Quelle: https://decatec.de/linux/verschluesselte-festplatte-luks-mit-usb-stick-bei-systemstart-entschluesseln/#USB-Stick_zum_Entschluesseln_einrichten

Hat nur leider bei mir so noch nicht funktioniert.

Andere Anleitung:

https://wiki.ubuntuusers.de/Archiv/System_verschl%C3%BCsseln/Entschl%C3%BCsseln_mit_einem_USB-Schl%C3%BCssel/

 

 

 

Festplattenverwaltung

Logical Volume Manager - LVM

Grundlagen

Quelle: https://www.thomas-krenn.com/de/wiki/LVM_Grundlagen

Vorgehensweise

Quelle: https://www.howtoforge.com/linux_lvm

 

Festplattenverwaltung

Software RAID - mdadm

Software RAID erstellen

http://www.prontosystems.org/tux/software_raid

 

RAID Device umbenennen

Quelle: https://serverfault.com/questions/267480/how-do-i-rename-an-mdadm-raid-array

Start with mdadm --detail /dev/md127:

Version : 0.90
Creation Time : Wed Apr 13 20:03:21 2011
Raid Level : raid10
Array Size : 656765952 (626.34 GiB 672.53 GB)
Used Dev Size : 437843968 (417.56 GiB 448.35 GB)
Raid Devices : 3
Total Devices : 2
Preferred Minor : 8
Persistence : Superblock is persistent

The first line shows the metadata version used by this array. Now, stop the array:

mdadm --stop /dev/md127
mdadm --remove /dev/md127

And assemble it again using the new name. If the metadata version is 1.0 or higher, use this:

mdadm --assemble /dev/md3 /dev/sd[abcdefghijk]3 --update=name

For arrays using old metadata structure (most likely 0.90, as it allows for kernel auto-assembly), use this:

mdadm --assemble /dev/md3 --update=super-minor /dev/sd[abcdefghijk]3
Festplattenverwaltung

Beispiel - RAID1 - LUKS encryption - LVM

Quelle: http://hermann-mayer.net/blog/raid1-luks-und-lvm-ersetzen-mein-altes-speichersystem

 

Festplattenverwaltung

hdparm - Energiemanagement

Festplatten nach 20 Minuten in Standby schicken

 

Quelle: https://linuxundich.de/hardware/festplatten-automatisch-im-betrieb-in-den-standby-schalten/

 

Festplatten automatisch im Betrieb in den Standby schalten

74832
Teilen

Ich bin gerade dabei einen Rechner mit einem Mix aus Solid-State-Disk (aka SSD) und normaler Festplatte aufzubauen. Der Vorteil der SSD ist natürlich die enorme Geschwindigkeit und der lautlose Betrieb. Allerdings ist der Preis pro GB Speicherkapazität leider ebenso enorm… Um trotzdem ausreichend Speicherplatz im Rechner zu haben, wird daher zusätzlich eine herkömmliche Festplatte verbaut. Leider wird der durch die SSD fast lautlose PC durch die Harddisk wieder deutlich lauter. Mit den passenden Einstellungen kann man jedoch die Platte bei Nichtgebrauch via hdparm automatisch abschalten lassen. Für mich eine gute Lösung um die Musik- oder Videosammlung auszulagern oder große Images von virtuellen Maschinen zu speichern…

 

Im Endeffekt ist das Ganze relativ leicht umzusetzen. Erfahrenen Linux-Usern müsste ich nur die Schlagworte hdparm, die Option -S XX und die Konfigurationsdatei hdparm.conf nennen. Wer ausführliche Informationen möchte, der sollte einfach weiterlesen 🙂 Erstmal muss man dazu die Daten der Platte herausfinden, die man bei Nichtgebrauch abschalten möchte. Am einfachsten geht dies über die Laufwerksverwaltung von GNOME, die Ihr über das Menü unter Einstellungen | System aufrufen könnt. Dort müsstet Ihr einfach nur eure Platte raussuchen und euch das entsprechende Gerät /dev/sdXY merken.

 

In meinem Beispiel arbeite ich also mit der Platte /dev/sdc. Wahrscheinlich handelt es sich bei euch um ein anderes Gerät, von daher müsst Ihr die folgenden Hinweise von daher an eure Situation anpassen. Für KDEler gibt es alternativ sicherlich auch in der KDE SC ein entsprechendes Werkzeug und wenn alle Stricke reißen, hilft auf jeden Fall ein sudo fdisk -l weiter.

Nun überprüft Ihr am besten erst einmal, ob sich eure Platte überhaupt in den Leerlauf schicken lässt. Alle halbwegs aktuellen Platten und Controller sollten dazu eigentlich in der Lage sein, aber bevor Ihr euch später wundert warum das nicht funktioniert, solltet Ihr erstmal einen kleinen Test machen. Ruft dazu hdparm mit der Option -C auf…

$ sudo hdparm -C /dev/sdc
/dev/sdc:
 drive state is:  active/idle

Man sieht, dass hdparm den Status korrekt abrufen konnte und die Platte läuft, man sollte dies auch an ihrem Betriebsgeräusch erkennen können. Nun könnt Ihr die Platte einmal von Hand abschalten…

$ sudo hdparm -y /dev/sdc

…der Erfolg der Aktion sollte hörbar sein. Optional könnt Ihr erneut mit der Option -C nachprüfen, ob die Platte auch wirklich in den Standby geschickt werden konnte.

$ sudo hdparm -C /dev/sdc
/dev/sdc:
drive state is:  standby

Sobald ihr wieder auf die Platte zugreift (bspw. über den Dateimanager), wird die Platte wieder automatisch anlaufen und ihre Daten preisgeben. Nun wäre es recht umständlich die Platte immer von Hand abzuschalten, besser wäre es, wenn sich die Platte nach einer Gewissen Zeit ohne Zugriffe automatisch abstellen könnte.

Dazu gibt es die Option -S XX von Hdparm. Über sie könnt ihr eine Zeitspanne definieren, ab der die Platte abgeschaltet wird. Der Zahlenwert hinter dem Schlüssel drückt nicht direkt die Zeit aus, sondern dient nur als Multiplikator. Ich zitiere einfach mal die man-Page…

Values from 1 to 240 specify multiples of 5 seconds, yielding timeouts from 5 seconds to 20 minutes. Values from 241 to 251 specify from 1 to 11 units of 30 minutes, yielding timeouts from 30 minutes to 5.5 hours. A value of 252 signifies a timeout of 21 minutes. A value of 253 sets a vendor-defined timeout period between 8 and 12 hours, and the value 254 is reserved. 255 is interpreted as 21 minutes plus 15 seconds. Note that some older drives may have very different interpretations of these values.

Ein Wert von bspw. 60 entspricht daher 60*5 Sekunden, also 300 Sekunden oder fünf Minuten. Zu kurz sollte man das Timeout nicht wählen, da zu häufiges Runter- und wieder Hochdrehen des Motors die Lebensdauer der Platte beeinträchtigen kann.

$ sudo hdparm -S 60 /dev/sdc

Damit das Ganze automatisch beim Start des Systems ausgeführt wird, solltet Ihr diese Einstellung in der Konfigurationsdatei /etc/hdparm.conf speichern. Am besten arbeitet Ihr in dem Fall mit UUIDs, so dass sich der Eintrag immer auf die gewünschte Platte bezieht, selbst wenn sich eure Plattenkonfiguration einmal ändern sollte. Bestimmt die UUID über bspw…

$ sudo blkid
[...]
/dev/sdb1: LABEL="data-intern" UUID="ff7f1cdd-431a-4e47-8b90-49737cec82b3" TYPE="ext4"
/dev/sdc1: LABEL="datengrab" UUID="4c9dca33-e3e1-4a6a-a7d4-110cdbb4cfbe" TYPE="ext3"

…und fügt dann einfach euren gewünschten Eintrag an das Ende der hdparm.conf an…

$ sudo gedit /etc/hdparm.conf
[...]
/dev/disk/by-uuid/4c9dca33-e3e1-4a6a-a7d4-110cdbb4cfbe {
	spindown_time = 60
}

…ab dem nächsten Neustart sollte die Einstellung automatisch aktiv sein und eure Platte bei Nichtgebrauch abgeschaltet werden. Abschließend noch der Hinweis, dass Ihr beim Arbeiten mit Hdparm wirklich euer Hirn einschalten müsst. Bei der „Schlaffunktion“ müsst Ihr wie bereits erwähnt überdenken, dass zu häufiges Hochdrehen der Platte die Lebensdauer reduzieren kann. Setzt das Intervall daher auf keinen Fall zu kurz.

Graylog

Graylog

Graylog - Konfiguration

Default Login

Der default User ist "admin".

Es wird scheinbar nur das default Passwort "admin" als sha256 hash akzeptiert.

So muss die Zeile in der config aussehen: root_password_sha2 = 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

Ich habe es mit anderen Passwörtern versucht aber bekam dann nach Neustart des Graylogs nur die Fehlermeldung beim Login "Invalid Credentials".

Ebenfalls scheint es nicht zu funktionieren anstelle des HASH Wertes ein Kommando zur Ausgabe dessen zu benutzen.

Ich hatte das hier versucht:

root_password_sha2 = `cat $workdir/root_password_sha2`

Das funktionierte nur nicht, obwohl ein Test auf der bash tadellos funktioniert.

 

Einstellen der Adressen, die Graylog benutzen soll

Da Graylog für mich neu war, habe ich mir Docs durchgelesen und befolgt aber war damit nicht erfolgreich. Also las ich einige Docs und Anleitungen aus Communities bis ich dann die entscheidenden Einstellungen fand, die mir den Erfolg brachten.

Man muss scheinbar lediglich folgende "URI´s" einstellen:

Die default Zeilen kommentiere ich immer aus.

#rest_listen_uri = http://127.0.0.1:9000/api/
rest_listen_uri = http://192.168.10.10:9000/api/

#web_listen_uri = http://127.0.0.1:9000/
web_listen_uri = http://192.168.10.10:9000/

Damit funktionierte es dann bei mir.

Beispielkonfiguration

root@srvgl01:/etc/graylog# cat /etc/graylog/server/server.conf
workdir=/etc/graylog
is_master = true

node_id_file = /etc/graylog/server/node-id

password_secret = ${workdir}/server/password-secret
root_username = admin
root_password_sha2 = DEIN-SHA2-root-Schnipsel
root_timezone = Europe/Berlin

plugin_dir = /usr/share/graylog-server/plugin

rest_listen_uri = http://192.168.1.11:9000/api/
rest_transport_uri = http://192.168.1.11:9000/api/

web_enable = true
web_listen_uri = http://192.168.1.11:9000/
#web_endpoint_uri = http://192.168.1.10:80/api/

elasticsearch_hosts = http://192.168.1.21:9200

rotation_strategy = count
elasticsearch_max_docs_per_index = 20000000
elasticsearch_max_number_of_indices = 20
retention_strategy = delete

elasticsearch_shards = 4
elasticsearch_replicas = 0
elasticsearch_index_prefix = graylog
allow_leading_wildcard_searches = false
allow_highlighting = false
elasticsearch_analyzer = standard

output_batch_size = 500
output_flush_interval = 1
output_fault_count_threshold = 5
output_fault_penalty_seconds = 30

processbuffer_processors = 5
outputbuffer_processors = 3
processor_wait_strategy = blocking
ring_size = 65536

inputbuffer_ring_size = 65536
inputbuffer_processors = 2
inputbuffer_wait_strategy = blocking

message_journal_enabled = true
message_journal_dir = /var/lib/graylog-server/journal

lb_recognition_period_seconds = 3

mongodb_uri = mongodb://192.168.1.11:27017,192.168.1.12:27017,192.168.1.13:27017/graylog?replicaSet=graylog
mongodb_max_connections = 1000
mongodb_threads_allowed_to_block_multiplier = 5

content_packs_dir = /usr/share/graylog-server/contentpacks
content_packs_auto_load = grok-patterns.json
proxied_requests_thread_pool_size = 32

JMESPATH

JMESPATH

JMESPATH Terminal

JMESPATH Terminal

Github: https://github.com/jmespath/jmespath.terminal

 Für die Installation benötigt man das Python Installationsprogramm pip .

#pip install jmespath-terminal

Let's encrypt

Let's encrypt

Certbot Benutzung

Befehle

Zertifikate anzeigen

# certbot certificates

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Found the following certs:
  Certificate Name: frzn.io
    Serial Number: xxxxxxxxxxxxxxxxxxxxxxxx
    Key Type: RSA
    Domains: frzn.io *.frzn.io
    Expiry Date: 2021-12-19 11:43:52+00:00 (VALID: 89 days)
    Certificate Path: /etc/letsencrypt/live/frzn.io/fullchain.pem
    Private Key Path: /etc/letsencrypt/live/frzn.io/privkey.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Zertifikat erstellen

# certbot certonly --dns-cloudflare --dns-cloudflare-credentials /PATH/TO/SECRETS/cloudflareapi.ini -d frzn.io,*.frzn.io --preferred-challenges dns --dns-cloudflare-propagation-seconds 20

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Requesting a certificate for frzn.io and *.frzn.io
Waiting 20 seconds for DNS changes to propagate

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/frzn.io/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/frzn.io/privkey.pem
This certificate expires on 2021-12-19.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Zertifikate löschen

# certbot delete --cert-name frzn.io-0002

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The following certificate(s) are selected for deletion:

  * frzn.io-0002

Are you sure you want to delete the above certificate(s)?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: y
Deleted all files relating to certificate frzn.io-0002.

Zertifikate automatisch erneuern

0 23 */10 * * /usr/bin/certbot renew --quiet > /dev/null 2>&1

PostgreSQL

PostgreSQL

Allgemein

Zugriffsberechtigungen anpassen

Zugriffsberechtigungen live aktivieren

Prometheus

Prometheus

Verarbeitung - Metriken

Quelle: https://medium.com/quiq-blog/prometheus-relabeling-tricks-6ae62c56cbda

 

Proxmox VE

Proxmox VE

Installation

https://www.proxmox.com/de/proxmox-ve/erste-schritte

Installation

https://pve.proxmox.com/wiki/Install_Proxmox_VE_on_Debian_Stretch

OVS Bridge

https://pve.proxmox.com/wiki/Open_vSwitch#Example_1:_Bridge_.2B_Internal_Ports_.2B_Untagged_traffic

 

Proxmox VE

Fehlerbehebung

pve-apt-hook: not found

Fehlermeldung bei Updates oder dem Entfernen von proxmox-ve:

/bin/sh: 1: /usr/share/proxmox-ve/pve-apt-hook: not found

Fehlerbehebung

Quelle: https://forum.proxmox.com/threads/error-with-update-bin-sh-1-usr-share-proxmox-ve-pve-apt-hook-not-found.45436/

mkdir /usr/share/proxmox-ve
nano /usr/share/proxmox-ve/pve-apt-hook
chmod u+x /usr/share/proxmox-ve/pve-apt-hook
apt-get update && apt-get dist-upgrade
apt autoremove

Danach sollte alles wieder funktionieren.

Proxmox VE

Konfiguration

Openvswitch

Standalone Bridge

My config - /etc/network/interfaces:

auto ovsbr01
allow-ovs ovsbr01
iface ovsbr01 inet static
address 10.1.99.1
netmask 255.255.255.0
gateway 10.1.99.254
ovs_type OVSBridge
ovs_ports enp2s0

allow-ovsbr01 enp2s0
iface enp2s0 inet manual
ovs_bridge ovsbr01
ovs_type OVSPort

Ceph - Storage on single Node Proxmox

https://whiskeyalpharomeo.com/2016/02/21/proxmox-single-node-ceph/

 

RabbitMQ

RabbitMQ

Get started

Neue User anlegen

Quelle: https://stackoverflow.com/questions/23020908/how-to-access-rabbitmq-publicly

First of all connect to your rabbitmq server machine using ssh client so as to be able to run rabbitmqctl (like puTTY) & get into the sbin directory of rabbit installation

  1. you need to create a user for any vhost on that system (here I use default vhost "/")

$ rabbitmqctl add_user yourName yourPass

  1. Set the permissions for that user for default vhost

$ rabbitmqctl set_permissions -p / yourName ".*" ".*" ".*"

  1. Set the administrator tag for this user (to enable him access the management pluggin)

$ rabbitmqctl set_user_tags yourName administrator

... and you are ready to login to your rabbitmq management gui using yourName and yourPass from any browser by pointing it to http://"*********":15672 where ***** is your server IP

 

Plugin aktivieren

Management (WebUI) Plugin aktivieren: /usr/lib/rabbitmq/lib/rabbitmq_server-0.0.0/sbin/rabbitmq-plugins enable rabbitmq_management

Wenn ich nur rabbitmq-plugins enable rabbitmq_management aufrufe dann meckert er rum, dass er das Plugin nicht findet. Da scheint noch was in den configs zu fehlen.

RSyslog

RSyslog

RSyslog - Konfiguration

Kommunikation mit Graylog

Quelle: https://github.com/Graylog2/graylog-guide-syslog-linux

Unter /etc/rsyslo.d/ kann man eigene Konfigs abspeichern.

Wir legen also eine für Graylog an:

nano /etc/rsyslog.d/90-graylog.conf

UDP: *.* @graylog.example.org:514;RSYSLOG_SyslogProtocol23Format

TCP: *.* @@graylog.example.org:514;RSYSLOG_SyslogProtocol23Format

SSH

SSH

Putty Keys

How to convert Linux Openssh key to Putty format?

Quelle: https://creodias.eu/-/how-to-convert-linux-openssh-key-to-putty-format-

If you want to know how to create a SSH keypair in Linux, see this manual.

Install putty-tools:

sudo apt-get install putty-tools

Then:

cd ~/.ssh/

puttygen id_rsa -o id_rsa.ppk

 

If we would like to convert the Putty format key to Openssh key:

  • To generate the private key follow this command:
puttygen id_dsa.ppk -O private-openssh -o id_dsa
  • To generate public key follow this command:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub 

 

Be sure that the permissions are set correctly for private and public key:

chmod 600 id_dsa
chmod 666 id_dsa.pub

If you would like to learn more about PuTTYgen, learn about the installation or usage guide, we invite you to visit the website www.puttygen.com

Versionierung

Versionierung

Git

Git und Submodule

Quelle:https://stackoverflow.com/a/1032653

 

If it's the first time you check-out a repo you need to use --init first:

git submodule update --init --recursive

For git 1.8.2 or above, the option --remote was added to support updating to latest tips of remote branches:

git submodule update --recursive --remote

This has the added benefit of respecting any "non default" branches specified in the .gitmodules or .git/config files (if you happen to have any, default is origin/master, in which case some of the other answers here would work as well).

For git 1.7.3 or above you can use (but the below gotchas around what update does still apply):

git submodule update --recursive

or:

git pull --recurse-submodules

if you want to pull your submodules to latest commits instead of the current commit the repo points to.

See git-submodule(1) for details

Versionierung

SVN

Backup SVN Repository

svnadmin dump /var/svn/myrepo > /backup/svn/myrepo.dump

Backup SVN with Gzip Compression

svnadmin dump /var/svn/myrepo | gzip -9 > /backup/svn/myrepo.dump.gz

Restore (load) Svn Repository

1. neues Repo erstellen: svnadmin create /var/svn/mynewrepo

2. Restore Repo: svnadmin load /var/svn/mynewrepo < /backup/svn/myrepo.dump

Vi(m)

Alles zum Texteditor

Vi(m)

Vi(m) - search and replace

Quelle: https://vim.fandom.com/wiki/Search_and_replace

Intro

Vim provides the :s (substitute) command for search and replace; this tip shows examples of how to substitute. On some systems, gvim has Find and Replace on the Edit menu (:help :promptrepl), however it is easier to use the :s command due to its command line history and ability to insert text (for example, the word under the cursor) into the search or replace fields.

Basic search and replace

The :substitute command searches for a text pattern, and replaces it with a text string. There are many options, but these are what you probably want:

:%s/foo/bar/g
Find each occurrence of 'foo' (in all lines), and replace it with 'bar'.
:s/foo/bar/g
Find each occurrence of 'foo' (in the current line only), and replace it with 'bar'.
:%s/foo/bar/gc
Change each 'foo' to 'bar', but ask for confirmation first.
:%s/\<foo\>/bar/gc
Change only whole words exactly matching 'foo' to 'bar'; ask for confirmation.
:%s/foo/bar/gci
Change each 'foo' (case insensitive due to the i flag) to 'bar'; ask for confirmation.
:%s/foo\c/bar/gc is the same because \c makes the search case insensitive.
This may be wanted after using :set noignorecase to make searches case sensitive (the default).
:%s/foo/bar/gcI
Change each 'foo' (case sensitive due to the I flag) to 'bar'; ask for confirmation.
:%s/foo\C/bar/gc is the same because \C makes the search case sensitive.
This may be wanted after using :set ignorecase to make searches case insensitive.

The g flag means global – each occurrence in the line is changed, rather than just the first. This tip assumes the default setting for the 'gdefault' and 'edcompatible' option (off), which requires that the g flag be included in %s///g to perform a global substitute. Using :set gdefault creates confusion because then %s/// is global, whereas %s///g is not (that is, g reverses its meaning).

When using the c flag, you need to confirm for each match what to do. Vim will output something like: replace with foobar (y/n/a/q/l/^E/^Y)? (where foobar is the replacement part of the :s/.../.../ command. You can type y which means to substitute this match, n to skip this match, a to substitute this and all remaining matches ("all" remaining matches), q to quit the command, l to substitute this match and quit (think of "last"), ^E to scroll the screen up by holding the Ctrl key and pressing E and ^Y to scroll the screen down by holding the Ctrl key and pressing Y. However, the last two choices are only available, if your Vim is a normal, big or huge built or the insert_expand feature was enabled at compile time (look for +insert_expand in the output of :version).

Also when using the c flag, Vim will jump to the first match it finds starting from the top of the buffer and prompt you for confirmation to perform replacement on that match. Vim applies the IncSearch highlight group to the matched text to give you a visual cue as to which match it is operating on (set to reverse by default for all three term types as of Vim 7.3). Additionally, if more than one match is found and you have search highlighting enabled with :set hlsearch, Vim highlights the remaining matches with the Search highlight group. If you do use search highlighting, you should make sure that these two highlight groups are visually distinct or you won't be able to easily tell which match Vim is prompting you to substitute.

Details

Search range:

:s/foo/bar/g Change each 'foo' to 'bar' in the current line.
:%s/foo/bar/g Change each 'foo' to 'bar' in all the lines.
:5,12s/foo/bar/g Change each 'foo' to 'bar' for all lines from line 5 to line 12 (inclusive).
:'a,'bs/foo/bar/g Change each 'foo' to 'bar' for all lines from mark a to mark b inclusive (see Note below).
:'<,'>s/foo/bar/g When compiled with +visual, change each 'foo' to 'bar' for all lines within a visual selection. Vim automatically appends the visual selection range ('<,'>) for any ex command when you select an area and enter :. Also, see Note below.
:.,$s/foo/bar/g Change each 'foo' to 'bar' for all lines from the current line (.) to the last line ($) inclusive.
:.,+2s/foo/bar/g Change each 'foo' to 'bar' for the current line (.) and the two next lines (+2).
:g/^baz/s/foo/bar/g Change each 'foo' to 'bar' in each line starting with 'baz'.
Note: As of Vim 7.3, substitutions applied to a range defined by marks or a visual selection (which uses a special type of marks '< and '>) are not bounded by the column position of the marks by default. Instead, Vim applies the substitution to the entire line on which each mark appears unless the \%V atom is used in the pattern like: :'<,'>s/\%Vfoo/bar/g.


When searching:

., *, \, [, ^, and $ are metacharacters.
+, ?, |, &, {, (, and ) must be escaped to use their special function.
\/ is / (use backslash + forward slash to search for forward slash)
\t is tab, \s is whitespace (space or tab)
\n is newline, \r is CR (carriage return = Ctrl-M = ^M)
After an opening [, everything until the next closing ] specifies a /collection. Character ranges can be represented with a -; for example a letter a, b, c, or the number 1 can be matched with [1a-c]. Negate the collection with [^ instead of [; for example [^1a-c] matches any character except a, b, c, or 1.
\{#\} is used for repetition. /foo.\{2\} will match foo and the two following characters. The \ is not required on the closing } so /foo.\{2} will do the same thing.
\(foo\) makes a backreference to foo. Parenthesis without escapes are literally matched. Here the \ is required for the closing \).

When replacing:

\r is newline, \n is a null byte (0x00).
\& is ampersand (& is the text that matches the search pattern).
\0 inserts the text matched by the entire pattern
\1 inserts the text of the first backreference. \2 inserts the second backreference, and so on.

You can use other delimiters with substitute:

:s#http://www.example.com/index.html#http://example.com/#

Save typing by using \zs and \ze to set the start and end of a pattern. For example, instead of:

:s/Copyright 2007 All Rights Reserved/Copyright 2008 All Rights Reserved/

Use:

:s/Copyright \zs2007\ze All Rights Reserved/2008/

Using the current word or registers

:%s//bar/g
Replace each match of the last search pattern with 'bar'.
For example, you might first place the cursor on the word foo then press * to search for that word.
The above substitute would then change all words exactly matching 'foo' to 'bar'.
:%s/foo/<c-r><c-w>/g
Replace each occurrence of 'foo' with the word under the cursor.
<c-r><c-w> means that you press Ctrl-R then Ctrl-W.
The word under the cursor will be inserted as though you typed it.
:%s/foo/<c-r><c-a>/g
Replace each occurrence of 'foo' with the WORD under the cursor (delimited by whitespace).
<c-r><c-a> means that you press Ctrl-R then Ctrl-A.
The WORD under the cursor will be inserted as though you typed it.
:%s/foo/<c-r>a/g
Replace each occurrence of 'foo' with the contents of register 'a'.
<c-r>a means that you press Ctrl-R then a.
The contents of register 'a' will be inserted as though you typed it.
:%s/foo/<c-r>0/g
Same as above, using register 0 which contains the text from the most recent yank command. Examples of yank (copy) commands are yi( which copies the text inside parentheses around the cursor, and y$ which copies the text from the cursor to the end of the line. After a yank command which did not specify a destination register, the copied text can be entered by pressing Ctrl-R then 0.
:%s/foo/\=@a/g
Replace each occurrence of 'foo' with the contents of register 'a'.
\=@a is a reference to register 'a'.
The contents of register 'a' is not shown in the command. This is useful if the register contains many lines of text.
:%s//<c-r>//g
Replace each match of the last search pattern with the / register (the last search pattern).
After pressing Ctrl-R then / to insert the last search pattern (and before pressing Enter to perform the command), you could edit the text to make any required change.
:%s/<c-r>*/bar/g
Replace all occurrences of the text in the system clipboard (in the * register) with 'bar' (see next example if multiline).
On some systems, selecting text (in Vim or another application) is all that is required to place that text in the * register.
:%s/<c-r>a/bar/g
Replace all occurrences of the text in register 'a' with 'bar'.
<c-r>a means that you press Ctrl-R then a. The contents of register 'a' will be inserted as though you typed it.
Any newlines in register 'a' are inserted as ^M and are not found.
The search works if each ^M is manually replaced with '\n' (two characters: backslash, 'n').
This replacement can be performed while you type the command:
:%s/<c-r>=substitute(@a,"\n",'\\n','g')<CR>/bar/g
The "\n" (double quotes) represents the single character newline; the '\\n' (single quotes) represents two backslashes followed by 'n'.
The substitute() function is evaluated by the <c-r>= (Ctrl-R =) expression register; it replaces each newline with a single backslash followed by 'n'.
The <CR> indicates that you press Enter to finish the = expression.
:%s/<c-r>0/bar/g
Same as above, using register 0 which contains the text from the most recent yank command.

See Paste registers in search or colon commands instead of using the clipboard.

Additional examples

:%s/foo/bar/
On each line, replace the first occurrence of "foo" with "bar".
:%s/.*\zsfoo/bar/
On each line, replace the last occurrence of "foo" with "bar".
:%s/\<foo\>//g
On each line, delete all occurrences of the whole word "foo".
:%s/\<foo\>.*//
On each line, delete the whole word "foo" and all following text (to end of line).
:%s/\<foo\>.\{5}//
On each line, delete the first occurrence of the whole word "foo" and the following five characters.
:%s/\<foo\>\zs.*//
On each line, delete all text following the whole word "foo" (to end of line).
:%s/.*\<foo\>//
On each line, delete the whole word "foo" and all preceding text (from beginning of line).
:%s/.*\ze\<foo\>//
On each line, delete all the text preceding the whole word "foo" (from beginning of line).
:%s/.*\(\<foo\>\).*/\1/
On each line, delete all the text preceding and following the whole word "foo".
:%s/\<foo\(bar\)\@!/toto/g
On each line, replace each occurrence of "foo" (which starts a word and is not followed by "bar") by "toto".
:s/^\(\w\)/\u\1/
If the first character at the beginning of the current line only is lowercase, switch it to uppercase using \u (see switching case of characters).
:%s/\(.*\n\)\{5\}/&\r/
Insert a blank line every 5 lines.
The pattern searches for \(.*\n\) (any line including its line ending) repeated five times (\{5\}).
The replacement is & (the text that was found), followed by \r (newline).
:%s/\<foo\(\a*\)\>/\=len(add(list, submatch(1)))?submatch(0):submatch(0)/g
Get a list of search results. (the list must exist)
Sets the modified flag, because of the replacement, but the content is unchanged.
Note: With a recent enough Vim (version 7.3.627 or higher), you can simplify this to:
:%s/\<foo\(\a*\)\>/\=add(list, submatch(1))/gn
This has the advantage, that the buffer won't be marked modified and no extra undo state is created. The expression in the replacement part is executed in the sandbox and not allowed to modify the buffer.

Special cases

For substituting patterns with corresponding case-sensitive text, Michael Geddes's keepcase plugin can be used, e.g.:

:%SubstituteCase/\cHello/goodBye/g
Substitute 'Hello hello helLo HELLO' by 'Goodbye goodbye goodBye GOODBYE'

For changing the offsets in a patch file (line number of a block), this little snippet can be used:

s/^@@ -\(\d\+\),\(\d\+\) +\(\d\+\),\(\d\+\) @@$/\="@@ -".eval(submatch(1)+offsetdiff).",".submatch(2)." +".eval(submatch(3)+offsetdiff).",".submatch(4)." @@"/g

Useful when we want to strip some blocks from a patch, without patch having to complain about offset differences.

Note Should try to make the expression more compact, but don't know how without having the possibility of modifying unwanted lines.

XFCE

XFCE

Programm zum Startmenue hinzufuegen

http://xubuntugeek.blogspot.com/2011/12/add-items-to-xfce-applications-menu.html

 

To add an application launcher to Xfce Applications Menu is simple; all you have to do is place the *.desktop file that launches the application in the right folder.

Create the *.desktop file
Create a text file whose extension is 'desktop', with the following content:
[Desktop Entry]
Version=1.0
Type=Application
Name=ItemName
Exec=Command
Icon=IconFile
Categories=Category;


On ItemName write the name that should be displayed on the menu. Command is the command that should be run. IconFile is the path to some *.png file. The Category dictates the sub-menu where the item will be placed. See the table bellow to see what Category value you should use.

Sub-Menu Categories
Accessories Utility
Development Development
Games Game
Graphics Graphics
Internet Network
Multimedia AudioVideo
Office Office
System System
A new item can be placed on a sub-menu by selecting the right 'Categories' value


To learn more about *.desktop files see the reference at the end of this post.

Add an item for you user only
Copy the *.desktop file to: $HOME/.local/share/applications

Add an item for all users
You'll need root privileges to do this.
Copy the *.desktop file to: /usr/share/applications

After you copy the *.desktop file the new item will be automatically added to the Applications Menu.

Ampache

Installation neuer Versionen / Upgrade

  1. Bisherigen ampache-Ordner umbenennen (kann nach erfolgreichem Upgrade gelöscht werden)
  2. Neue ampache Version herunterladen und entpacken
  3. config Datei aus der alten Installation in die neue kopieren - unter /var/www/ampache/config/ zu finden
  4. Die Dateirechte neu setzen, da man meist mit root entpackt:
    chown -R www-data:www-data /var/www/ampache
  5. In das ampache Verzeichnis wechseln und den Composer alle Abhängigkeiten updaten lassen
    1. Composer befindet sich i.d.R. unter /usr/local/bin/composer/composer.phar
    2. Updatebefehl: root@Server:/var/www/ampache# /usr/local/bin/composer/composer.phar install --prefer-source --no-interaction
  6. Die neue Ampache Version ist einsatzbereit



Ansonsten kann es sein, dass im Log von Ampache solche Fehler wie:

[ampache] (autoload) -> 'Gettext\Translator' not found!

Das liegt daran, dass man die Abhängigkeiten mit Composer nicht aktualisiert hat.

Apt-get

Paketverwaltung

Pakete deinstallieren

apt-get remove packagename

will remove the binaries, but not the configuration or data files of the package packagename. It will also leave dependencies installed with it on installation time untouched.

apt-get purge packagename or apt-get remove --purge packagename

will remove about everything regarding the package packagename, but not the dependencies installed with it on installation. Both commands are equivalent.

Particularly useful when you want to 'start all over' with an application because you messed up the configuration. However, it does not remove configuration or data files residing in users home directories, usually in hidden folders there. There is no easy way to get those removed as well.

apt-get autoremove

removes orphaned packages, i.e. installed packages that used to be installed as an dependency, but aren't any longer. Use this after removing a package which had installed dependencies you're no longer interested in.

aptitude remove packagename aptitude purge packagename

will also attempt to remove other packages which were required by packagename on but are not required by any remaining packages. Note that aptitude only remembers dependency information for packages that it has installed. 
Quelle: https://askubuntu.com/a/187891

AutostartSkripte

Fehler

missing LSB tags and overrides

Direkt hinter #! /bin/sh fügt man Folgendes ein:

### BEGIN INIT INFO
# Provides: scriptname
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Kurze Beschreibung
# Description: Lange Beschreibung
### END INIT INFO

Natürlich müssen die Werte noch entsprechend angepasst werden. Default-Start und Default-Stop geben an in welchen Runleveln das Script ausgeführt werden soll. Short-Description und Description liefern eine kurze Beschreibung des Scriptes.

Danach muss das Script nur noch mit insserv in die im Header angegebenen Runlevel importiert werden.

insserv -d scriptname

SysVInitSkripte erstellen

Doku => https://fedoraproject.org/wiki/EPEL:SysVInitScript

Composer

Composer mit Plesk und verschiedenen PHP Versionen

Quelle: https://faq.simplyroot.de/content/15/96/de/composer-mit-php-binaries-von-plesk-nutzen.html

Ab Plesk 12.5.30 besteht die Möglichkeit in Plesk entsprechend mehrere PHP Versionen zu installieren.
Ist für eine Domain z.B. PHP 7.0 von Plesk aktiv bzw. setzt eine Composer Installation PHP 7.0 vorraus, so kann nicht einfach der vom System zur Verfügung gestellte composer genutzt werden.

In diesem Fall gehen Sie bitte wie folgt vor:

Download Composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
Installation vom Composer mit der PHP 7 binary
/opt/plesk/php/7.0/bin/php composer-setup.php


Um nun weitere Pakete mittels composer zu installieren, nutzen Sie fortan nicht mehr einfach "composer" oder "php composer" sondern nachfolgendes Kommando (gefolgt von den gewünschten Parametern):

/opt/plesk/php/7.0/bin/php composer.phar

Composer nicht mit der standard System PHP Version benutzen

Quelle: http://blogs.reliablepenguin.com/2015/08/18/using-php-composer-phar-with-non-default-php-install
So überschreibt man die Einstellung von Composer und sagt ihm welche PHP Version er benutzen soll:

export PATH=/opt/plesk/php/5.6/bin:$PATH; php composer.phar update

Cronjobs

Quelle: https://superuser.com/questions/81262/how-to-execute-shell-script-via-crontab/123894#123894

Einführung

Making crontab running is easy only . Here I am going to say how to run crontab jobs. It is useful for anyone who is stuck on crontab.

*/1 * * * * cd /home/hacks && sh notify.sh

To make the script executable, we have to do:

chmod +x home/hacks/notify.sh

Here i run this script for every one minute ... By doing below script, you can write it in a log file to find whether its working

write log

*/1 * * * * cd /home/hacks && sh notify.sh>>test.log

send mail

*/1 * * * * cd /home/hacks && sh notify.sh>>test.log | mail -s "Hi this is example" user@domain.com

Den Server jeden Abend automatisiert herunterfahren

server:/ cat /etc/cron.d/shutdown
#tägliches Herunterfahren um 23:00 Uhr
#00 23 * * * root /sbin/shutdown -h now > /dev/null 2>&1

#Montag-Donnerstag um 00:00 Uhr herunterfahren
#00 23 * * 1-4 root /sbin/shutdown -h now > /dev/null 2>&1
0 0 * * 1-4 root date  >> /var/log/_shutdown/shutdown.log
0 0 * * 1-4 root /bin/echo "Fritschserver wird heruntergefahren" >> /var/log/_shutdown/shutdown.log
0 0 * * 1-4 root /sbin/shutdown -h now > /dev/null 2>&1


#Freitag-Samstag um 01:00  Uhr herunterfahren
#00 01 * * 5-6 root /sbin/shutdown -h now > /dev/null 2>&1
0 01 * * 5-6 root date >> /var/log/_shutdown/shutdown.log
0 01 * * 5-6 root /bin/echo "Fritschserver wird heruntergefahren" >> /var/log/_shutdown/shutdown.log
0 01 * * 5-6 root /sbin/shutdown -h now >> /dev/null 2>&1

#Sonntag um 23:00 Uhr herunterfahren
#00 23 * * 7 root /sbin/shutdown -h now > /dev/null 2>&1
#00 00 * * 7 root /sbin/shutdown -h now > /dev/null 2>&1
0 23 * * 7 root date >> /var/log/_shutdown/shutdown.log
0 23 * * 7 root /bin/echo "Fritschserver wird heruntergefahren" >> /var/log/_shutdown/shutdown.log
0 23 * * 7 root /sbin/shutdown -h now >> /dev/null 2>&1

Datenaustausch mit Smartphone

Benötigte Pakete:

Danach den Dateimanager einmal beenden und wieder öffnen.

Dann sollte es so aussehen:

Influx - TICK Stack

Chronograf

Aliase für die Legende

Post im Forum: https://community.influxdata.com/t/chronograf-static-legend-alias-for-shown-value-name/7309

 

Kill - Befehl

Übersicht der Signale

 # man 7 signal
 Ausgabe: 
 
 Standard signals
       Linux supports the standard signals listed below.  Several signal numbers are architecture-dependent, as indicated in the "Value" column.  (Where three  values
       are  given,  the first one is usually valid for alpha and sparc, the middle one for x86, arm, and most other architectures, and the last one for mips.  (Values
       for parisc are not shown; see the Linux kernel source for signal numbering on that architecture.)  A dash (-) denotes that a signal is  absent  on  the  corre‐
       sponding architecture.

       First the signals described in the original POSIX.1-1990 standard.

       Signal     Value     Action   Comment
       ──────────────────────────────────────────────────────────────────────
       SIGHUP        1       Term    Hangup detected on controlling terminal
                                     or death of controlling process
       SIGINT        2       Term    Interrupt from keyboard
       SIGQUIT       3       Core    Quit from keyboard
       SIGILL        4       Core    Illegal Instruction
       SIGABRT       6       Core    Abort signal from abort(3)
       SIGFPE        8       Core    Floating-point exception
       SIGKILL       9       Term    Kill signal
       SIGSEGV      11       Core    Invalid memory reference
       SIGPIPE      13       Term    Broken pipe: write to pipe with no
                                     readers; see pipe(7)
       SIGALRM      14       Term    Timer signal from alarm(2)
       SIGTERM      15       Term    Termination signal
       SIGUSR1   30,10,16    Term    User-defined signal 1
       SIGUSR2   31,12,17    Term    User-defined signal 2
       SIGCHLD   20,17,18    Ign     Child stopped or terminated
       SIGCONT   19,18,25    Cont    Continue if stopped
       SIGSTOP   17,19,23    Stop    Stop process
       SIGTSTP   18,20,24    Stop    Stop typed at terminal
       SIGTTIN   21,21,26    Stop    Terminal input for background process
       SIGTTOU   22,22,27    Stop    Terminal output for background process

       The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.

       Next the signals not in the POSIX.1-1990 standard but described in SUSv2 and POSIX.1-2001.

       Signal       Value     Action   Comment
       ────────────────────────────────────────────────────────────────────
       SIGBUS      10,7,10     Core    Bus error (bad memory access)
       SIGPOLL                 Term    Pollable event (Sys V).
                                       Synonym for SIGIO
       SIGPROF     27,27,29    Term    Profiling timer expired
       SIGSYS      12,31,12    Core    Bad system call (SVr4);
                                       see also seccomp(2)
       SIGTRAP        5        Core    Trace/breakpoint trap

       SIGURG      16,23,21    Ign     Urgent condition on socket (4.2BSD)
       SIGVTALRM   26,26,28    Term    Virtual alarm clock (4.2BSD)
       SIGXCPU     24,24,30    Core    CPU time limit exceeded (4.2BSD);
                                       see setrlimit(2)
       SIGXFSZ     25,25,31    Core    File size limit exceeded (4.2BSD);
                                       see setrlimit(2)

       Up  to and including Linux 2.2, the default behavior for SIGSYS, SIGXCPU, SIGXFSZ, and (on architectures other than SPARC and MIPS) SIGBUS was to terminate the
       process (without a core dump).  (On some other UNIX systems the default action for SIGXCPU and SIGXFSZ is to terminate the process without a core dump.)  Linux
       2.4 conforms to the POSIX.1-2001 requirements for these signals, terminating the process with a core dump.

       Next various other signals.

       Signal       Value     Action   Comment
       ────────────────────────────────────────────────────────────────────
       SIGIOT         6        Core    IOT trap. A synonym for SIGABRT
       SIGEMT       7,-,7      Term    Emulator trap
       SIGSTKFLT    -,16,-     Term    Stack fault on coprocessor (unused)
       SIGIO       23,29,22    Term    I/O now possible (4.2BSD)
       SIGCLD       -,-,18     Ign     A synonym for SIGCHLD
       SIGPWR      29,30,19    Term    Power failure (System V)
       SIGINFO      29,-,-             A synonym for SIGPWR
       SIGLOST      -,-,-      Term    File lock lost (unused)
       SIGWINCH    28,28,20    Ign     Window resize signal (4.3BSD, Sun)
       SIGUNUSED    -,31,-     Core    Synonymous with SIGSYS

       (Signal 29 is SIGINFO / SIGPWR on an alpha but SIGLOST on a sparc.)

       SIGEMT  is  not  specified in POSIX.1-2001, but nevertheless appears on most other UNIX systems, where its default action is typically to terminate the process
       with a core dump.

       SIGPWR (which is not specified in POSIX.1-2001) is typically ignored by default on those other UNIX systems where it appears.

       SIGIO (which is not specified in POSIX.1-2001) is ignored by default on several other UNIX systems.

       Where defined, SIGUNUSED is synonymous with SIGSYS on most architectures.

LPIC-Zertifizierungen

Free LPIC Manual
Linux-Magazin LPIC Vorbereitung in 24 Teilen

Nützliche Befehle & Links

Große Ordner sortiert auflisten

du -h /dein/direcotory/ | sort -rh | head -n 20

Auf welchem Port läuft etwas?

lsof -i :PORT -S

root@server:/# lsof -i :9201 -S
COMMAND   PID   USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
java    81378 user   21u  IPv6 5091945      0t0  TCP *:9201 (LISTEN)

Hostname ändern

Quelle: https://www.tecmint.com/set-hostname-permanently-in-linux/

Zeilennummern herausfinden

Print all lines between two line numbers

awk: https://www.commandlinefu.com/commands/view/9889/print-all-lines-between-two-line-numbers

sed: https://www.commandlinefu.com/commands/view/9890/print-all-lines-between-two-line-numbers

Get line number from pattern

https://unix.stackexchange.com/questions/182015/find-the-line-number-which-contains-the-pattern-using-custom-regex-delimiter

grep -n 'pattern' file

Ausgabe:
23: pattern

Bash Ausgabe farbig markieren

Wenn man in mehreren Dateien einen bestimmten String austauschen will dann testet man vorher seinen Befehl und möchte sehen ob es funktioniert. Die farbige Markierung der Ausgabe ist dabei sehr hilfreich um die Stellen des geänderten Codes zu finden und überprüfen zu können.

- Stichwort ANSI Escape Codes

Hier ein Beispiel mit dem Texteditor sed:

SED - Texteditor

sed ''/iteritems/s//`printf "\033[31miteritems->items\033[0m"`/'' {icinga/*.sls,icingaweb/*.sls,apache/*.sls,mariadb/*.sls,php/*.sls}

Beispiel Ausgabe Auszug:
{% for module,attr in salt['pillar.get']('modules:enabled').iteritems->items() %}

Festplatte voll

Quelle: https://www.unixe.de/no-space-left-device/

Kopie des Blogbeitrages:

Unser erster Schritt sollte darin bestehen herauszufinden, welches device eigentlich gemeint ist; ist eine eingehängte reine Datenpartition voll, so muss in der Regel schlicht aufgeräumt und ausgemistet werden. Schwieriger wird es jedoch, wenn das System gar keine Datenpartitionen hat beziehungsweise die root-Partition betroffen ist — was nun?

$ df -h
Dateisystem            Grösse Benutzt Verf. Verw% Eingehängt auf
/dev/mapper/lda-root    6,4G    6,1G  8,0K  100% /
none                    4,0K       0  4,0K    0% /sys/fs/cgroup
udev                    487M     12K  486M    1% /dev
tmpfs                   100M    568K   99M    1% /run
none                    5,0M       0  5,0M    0% /run/lock
none                    497M       0  497M    0% /run/shm
none                    100M       0  100M    0% /run/user
/dev/mapper/lda-temp    488M    556K  478M    1% /tmp
/dev/mapper/lda-boot    249M     69M  168M   29% /boot
/dev/sdb1                12G    514M   11G    5% /var

Ersichtlich ist, dass das Root-File-System zu 100% belegt ist; oft liegt das an Log-Files, die in aller Regel in /var/log abgelegt werden, aber wie wir hier sehen können ist /var eine eigene Partition, auf der noch jede Menge Platz ist. Was also ballert das System so zu? Fangen wir mal klein an.

Kernel, Header und Pakete

Eine wahre Pest können auf einem Ubuntu-System alte Pakete sein, und insbesondere die linux-image-Daten können (in /usr/src) eine Menge Platz fressen. In einem ersten Schritt können also nicht mehr benötigte Abhängigkeiten aus dem System entfernt werden:

$ apt-get autoremove
$ apt-get clean

 

Anschließend betrachten wir uns näher, welche linux-images installiert sind und ob die wirklich alle benötigt werden; ii bedeutet, dass das Paket vollständig installiert ist, rc zeigt uns, dass das Paket zwar deinstalliert wurde, die Konfigurationen jedoch noch im System herumsausen.

$ dpkg -l|grep linux-image
...
rc  linux-image-3.13.0-36-generic       3.13.0-36.63
amd64        Linux kernel image for version 3.13.0 on 64 bit x86 SMP
rc  linux-image-3.13.0-39-generic       3.13.0-39.66
amd64        Linux kernel image for version 3.13.0 on 64 bit x86 SMP
ii  linux-image-3.13.0-52-generic       3.13.0-52.86
amd64        Linux kernel image for version 3.13.0 on 64 bit x86 SMP
ii  linux-image-3.13.0-57-generic       3.13.0-57.95
amd64        Linux kernel image for version 3.13.0 on 64 bit x86 SMP
rc  linux-image-extra-3.13.0-36-generic 3.13.0-36.63
amd64        Linux kernel extra modules for version 3.13.0 on 64 bit x86 SMP
rc  linux-image-extra-3.13.0-39-generic 3.13.0-39.66
amd64        Linux kernel extra modules for version 3.13.0 on 64 bit x86 SMP
ii  linux-image-extra-3.13.0-52-generic 3.13.0-52.86
amd64        Linux kernel extra modules for version 3.13.0 on 64 bit x86 SMP
ii  linux-image-extra-3.13.0-57-generic 3.13.0-57.95
amd64        Linux kernel extra modules for version 3.13.0 on 64 bit x86 SMP
ii  linux-image-generic                 3.13.0.57.64
amd64        Generic Linux kernel image

 

Die nicht benötigten können nun mit Hilfe des Paketmanagers entfernt werden:

$ apt-get remove linux-image-3.13.0-36-generic
...
$ apt-get remove linux-image-3.13.0-39-generic
...

 

In aller Regel wird durch diese Maßnahmen schon erstaunlich viel Platz geschaffen; sollte das noch nicht ausreichen, muss weiter nach der Ursache geforscht werden.

Das größte Paket

Du kannst suchen, welches die größten im System installierten Pakete sind; vielleicht brauchst du das eine oder andere davon ja nicht mehr und kannst es mittels des Paketmanagers entfernen?

$ dpkg-query -W -f='${Installed-Size;8}\t${Status;1}\t${Package}\n' \
> | grep -v "\sd\s" \
> | sort -n \
> | cut -f1,3-
...
   61937    linux-headers-3.13.0-73
   61938    linux-headers-3.13.0-74
   61938    linux-headers-3.13.0-76
   74304    libreoffice-common
  113706    libreoffice-core
...

 

Große Ordner (z.B. > 1GB) aufspüren

Welcher ist der fetteste Ordner im System? Du kannst von / aus iterieren und große Datenmengen systematisch aufspüren.

$ cd /
$ du -h --max-depth=1 / | grep '[0-9]G\>'
4.4G	/var
4.0G	/usr
9.5G	/

 

Große Files (z.B. > 1GB) aufspüren

Oftmals sind auch einzelne immer riesiger werdende Files die Übeltäter, die das System verstopfen — zum Beispiel Log-Files, die aus irgendwelchen Gründen nicht nach /var/log geschrieben werden. Auch nach ihnen kann systematisch gefahndet werden:

$ find / -name '*' -size +1G

 

Out of Inodes

Richtig fies wird es, wenn eigentlich noch hinreichend viel freier Platz auf dem Device ist, das System dennoch No space left on device meldet; das kann zum Beispiel an einer richtig großen Anzahl ganz winzig kleiner (oder gar leerer) Dateien liegen. Speicherplatz ist dann vorhanden, die verfügbaren Inodes sind jedoch aufgebraucht.

$ df -i
Filesystem            Inodes   IUsed   IFree IUse% Mounted on
/dev/xvda            2080768 2080768       0  100% /
tmpfs                  92187       3   92184    1% /lib/init/rw
varrun                 92187      38   92149    1% /var/run
varlock                92187       4   92183    1% /var/lock
udev                   92187    4404   87783    5% /dev
tmpfs                  92187       1   92186    1% /dev/shm

 

Hier wird es ersichtlich: auf / sind die Inodes aufgebraucht. Wir können die Suche nach den Verursachern damit beginnen, dass wir im File-System nach einer unüblich hohen Anzahl an Dateien innerhalb eines Ordners suchen. Auch hier wird sich von / aus in Richtung des Ordners iteriert.

$ for i in /* ; do echo $i ; find $i | wc -l ; done

 

Jetzt können die Dateien (gegebenenfalls archiviert und dann) gelöscht werden; die Zahl verfügbarer Inodes ist nun signifikant höher als zuvor.

SSH

Port Weiterleitung

ssh -L Port_lokal:localhost:Port_remote username@remoteserver.com
Beispiel:
ssh -L 443:localhost:443 username@remoteserver.com

OpenWRT

Projektversion "LEDE"

OpenVPN

VPN Server, push route

Wenn man über die Luci App die Option route hinzufügt, dann funktioniert das noch nicht.
Es ist zwingend notwendig, dass man wieder manuell den Eintrag in der OpenVPN config Datei anpasst.
Die Luci App trägt folgendes ein:

list route '192.168.1.0 255.255.255.0'

Den IP Bereich legt ihr natürlich fest.
Und damit es funktioniert muss der Befehl in folgendes geändert werden:

list push 'route 192.168.1.0 255.255.255.0'

VPN Client einrichten, pkcs12 Option entfernen

Beim Erstellen einer OpenVPN Client Instanz wird automatisch die Option "pkcs12" hinzugefügt.
Diese beißt sich mit der Option "cert" und das System loggt einen Fehler.

Mon Feb  5 14:52:57 2018 daemon.err openvpn(VPN_Client_GESA)[7339]: Options error: Parameter --cert cannot be used when --pkcs12 is also specified.
Um das Problem zu beheben, wählt man sich per SSH auf den Router ein und entfernt aus der Datei
/etc/config/openvpn
die Zeile
option pkcs12 '/etc/easy-rsa/keys/some-client.pk12'
. Dann startet man den OpenVPN Dienst neu
/etc/init.d/openvpn restart
und kann danach seine OpenVPN Instanz mit den Zertifikatsdateien benutzen.

Using PKCS12 File

Wenn man einen VPN Client über die WebGUI namens "Luci-App" einrichten will, wird man scheitern.
Bei der Verwendung von sog. P12 oder PKCS12 Dateien bekommt man folgende Fehlermeldung:

Mon Feb  5 15:41:43 2018 daemon.err openvpn(VPN_Client)[9553]: neither stdin nor stderr are a tty device and you have neither a controlling tty nor systemd - can't ask for 'Enter Private Key Password:'.  If you used --daemon, you need to use --askpass to make passphrase-protected keys work, and you can not use --auth-nocache.
Mon Feb  5 15:41:43 2018 daemon.notice openvpn(VPN_Client)[9553]: Exiting due to fatal error

Man müsste hier wieder per SSH das config file /etc/config/openvpn editieren un die Option "--askpass" manuell einzutragen und dahinter eine Datei mit dem Passwort für die P12 Datei im Klartext angeben.
Nach dieser Erkenntnis bin ich dann doch wieder zur ursprünglichen Konfigurationsvariante gewechselt und binde die Dateien "ca, key und cert" ein.

Quelle:Forum Opensense

Remote Desktop

VNCServer

Quelle: https://www.raspberrypi.org/forums/viewtopic.php?t=225655#p1385116

/home/user/.vnc/xstartup

unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
startxfce4 &

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &

init.d Skript

Quelle: https://codeclinic.de/2014/01/raspberry-pi-tutorial-vnc-bei-raspbian-einrichten-teil-1/

    #!/bin/sh
    ### BEGIN INIT INFO
    # Provides:          tightvncserver
    # Required-Start:    $local_fs
    # Required-Stop:     $local_fs
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: Start/stop tightvncserver
    ### END INIT INFO

    # More details see:
    # https://codeclinic.de/2014/01/raspberry-pi-tutorial-setting-vnc-default-desktop

    ### Customize this entry
    # Set the USER variable to the name of the user to start tightvncserver under
    export USER='pi'
    ### End customization required

    eval cd ~$USER
    case "$1" in
      start)
        su $USER -c '/usr/bin/tightvncserver :1'
        echo "Starting TightVNC server for $USER "
        ;;

      stop)
        pkill Xtightvnc
        echo "Tightvncserver stopped"
        ;;
      *)
        echo "Usage: /etc/init.d/tightvncserver {start|stop}"
        exit 1
        ;;
    esac
    exit 0

Teamspeak

Installation und Konfiguration

  1. Herunterladen & Entpacken des aktuellen Paketes
    1. http://www.teamspeak.com/en/downloads
  2. Einrichten der Konfiguration
  3. Server starten
  4. Autostart Skript erstellen

Eine genauere Anleitung für Ubuntu habe ich hier gefunden und selber auch benutzt. 
Eine Lizenz benutzen wir nicht, da wir bisher nie mehr als 32 Slots benötigt haben.

Installation

 

Hinweis!

Fremdsoftware kann das System gefährden.

Der TeamSpeak-3-Server lässt sich nicht über die Paketverwaltung [2] installieren, sondern muss manuell heruntergeladen und installiert werden.

Da ein TeamSpeak-3-Server auch auf dedizierten und Mini-Rechner läuft, findet alles ohne GUI auf der Konsole [1] oder via SSH statt. Einige der verwendeten Befehle erfordern erhöhte Rechte und müssen zwingend ein sudo voranstehen haben oder - sofern root ein Passwort besitzt und freigeschaltet ist - mit dem Befehl su dauerhaft für die Sitzung zu diesem Benutzer root zu wechseln. Alles, was während der Installation und später auch bei einer Aktualisierung über den Benutzer teamspeak abgewickelt wird, muss zwingend über den Befehl mit dem Zusatz für eine Login-Shell temporär eingeloggt werden.

Vorbereitung

Zuerst sollte man sich folgende Gedanken machen, wobei die hier unten angegeben Namen/Verzeichnis/CPU als Beispiel für die weitere Anleitung gilt resp. davon ausgegangen wird:

 

Platzhalter Vorgabe Weitere Mögliche Werte
$CPUSYS amd64 (64bit) x86 (32bit)
$TS3_BINARYDIR /usr/local/bin/teamspeak3-server_linux_amd64/ /usr/local/bin/teamspeak3-server_linux_x86/
$TS3_USER teamspeak ts3, ts3server
$TS3_VERSION 3.13.1 3.13.1 (aktuelle Version 2020-11-11 09:54:16)

Sollte es nicht klar sein ob das System und CPU im 64-bit-Modus laufen, kann dieses mittels folgendem Befehl in Erfahrung bringen:

uname -m 

Die Ausgabe x86_64 oder i686 entspricht einem 64-bit resp. 32-bit-System.

Benutzer anlegen

Zuerst wird ein Benutzer teamspeak mit adduser [4] für den Betrieb des Servers mit seinem Installationsverzeichnis als Home-Verzeichnis erstellt.

sudo adduser $TS3_USER --system --home $TS3_BINARYDIR --disabled-login 

Die Ausgabe sollte dann so aussehen:

Systembenutzer »teamspeak« (UID 1xx) wird hinzugefügt …
Neuer Benutzer »teamspeak« (UID 1xx) wird mit Gruppe »nogroup« hinzugefügt …
Persönliche Ordner »/usr/local/bin/teamspeak3-server_linux_amd64« wird erstellt …

Fehlermeldungen wie diese weisen auf eine bereits bestehende Installation und/oder Verzeichnis hin:

Achtung: der von Ihnen angegebene persönliche Ordner »/usr/local/bin/teamspeak3-server_linux_amd64« ist bereits vorhanden.
...
Der persönlicher Ordner »/usr/local/bin/teamspeak3-server_linux_amd64« ist bereits vorhanden. Von »/etc/skel« werden keine Dateien kopiert.
adduser: Achtung: der persönliche Ordner »/usr/local/bin/teamspeak3-server_linux_amd64« gehört nicht dem Benutzer, den Sie gerade anlegen.

Herunterladen, Entpacken und Installieren

Installationspaket herunterladen:

cd /tmp
wget -4 --no-cache  https://files.teamspeak-services.com/releases/server/$TS3_VERSION/teamspeak3-server_linux_$CPUSYS-$TS3_VERSION.tar.bz2 

Falls der Download erfolgreich war sieht das Ganze so aus:

--2019-06-03 22:08:42--  https://files.teamspeak-services.com/releases/server/3.8.0/teamspeak3-server_linux_amd64-3.8.0.tar.bz2
Auflösen des Hostnamens files.teamspeak-services.com (files.teamspeak-services.com) … 151.139.128.10
Verbindungsaufbau zu files.teamspeak-services.com (files.teamspeak-services.com)|151.139.128.10|:443 … verbunden.
HTTP-Anforderung gesendet, auf Antwort wird gewartet … 200 OK
Länge: 8870218 (8.5M) [application/x-tar]
Wird in »teamspeak3-server_linux_amd64-3.8.0.tar.bz2« gespeichert.

teamspeak3-server_linux_amd64-3.8.0.t 100%[=======================================================================>]   8.46M  16.0MB/s    in 0.5s

2019-06-03 22:08:43 (16.0 MB/s) - »teamspeak3-server_linux_amd64-3.8.0.tar.bz2« gespeichert [8870218/8870218]

Installationspaket entpacken [3] und installieren:

cd /usr/local/bin
sudo tar -xjf /tmp/teamspeak3-server_linux_$CPUSYS-$TS3_VERSION.tar.bz2
sudo chown root:root -R teamspeak3-server_linux_$CPUSYS
sudo chown $TS3_USER:nogroup teamspeak3-server_linux_$CPUSYS
sudo chmod go-w -R teamspeak3-server_linux_$CPUSYS 

Das gesamte Programmpaket gehört nun dem Benutzer root und unnötige Gruppen resp. jegliche Schreibrechte [5] wurden entfernt.

Einrichten der Konfiguration

Vor dem erstem Serverstart muss man noch einige Dateien von Hand anlegen bzw. bearbeiten.

Achtung!

Aus Sicherheitsgründen sollte der TeamSpeak-3-Server niemals mit Root-Rechten gestartet werden. Sollte es jemandem gelingen, eine Sicherheitslücke in der Software auszunutzen, hätte er ansonsten Administrator-Rechte auf dem Rechner mit dem Server.

Falls doch mal geschehen erscheint in der Konsole folgender Warnhinweis:

WARNING ! For security reasons we advise: DO NOT RUN THE SERVER AS ROOT

Experten-Info:

Weiteres Vorgehen erfolgt nun mit dem Benutzer teamspeak. Direktes Einloggen mit diesen Systembenutzer ist nicht möglich. Deshalb erfolgt diese über eine temporär zugewiesene Shell mittels des Befehls sudo su $TS3_USER -s /bin/sh.

cd /usr/local/bin/teamspeak3-server_linux_$CPUSYS/
sudo su $TS3_USER -s /bin/sh 

Dieses temporäre Shell für den Benutzer teamspeak bleibt nun offen, wie auch das gewählte Arbeitsverzeichnis (Homeverzeichnis von teamspeak).

ts3server.ini

Die Standardvorlage dieser Konfigurationsdatei ist recht einfach zu erstellen.

./ts3server createinifile=1 

Die folgende Ausgabe kann vorerst ignoriert werden, mehr dazu später im Abschnitt Server-Lizenz-akzeptieren:

Please set the environment variable TS3SERVER_LICENSE to "accept" in order to accept the license agreement.
Alternatively, create a file named ".ts3server_license_accepted" in the working directory or start the server with the command line parameter "license_accepted=1".
To view the license agreement set TS3SERVER_LICENSE to "view" in order to print the license to the console.
Alternatively view the file "LICENSE" in your favorite text viewer yourself.

Die Datei ts3server.ini [7] hat nun diesen Inhalt mit Abweichungen, je nach verwendeter Version des TeamSpeak-3- Servers.

machine_id=
default_voice_port=9987
voice_ip=0.0.0.0, ::
licensepath=
filetransfer_port=30033
filetransfer_ip=0.0.0.0, ::
query_port=10011
query_ip=0.0.0.0, ::
query_ip_allowlist=query_ip_allowlist.txt
query_ip_denylist=query_ip_denylist.txt
dbplugin=ts3db_sqlite3
dbpluginparameter=
dbsqlpath=sql/
dbsqlcreatepath=create_sqlite/
dbconnections=10
logpath=logs/
logquerycommands=0
dbclientkeepdays=30
logappend=0
query_skipbruteforcecheck=0
query_buffer_mb=20
http_proxy=
license_accepted=1
serverquerydocs_path=serverquerydocs/
query_ssh_ip=0.0.0.0, ::
query_ssh_port=10022
query_protocols=raw,ssh
query_ssh_rsa_host_key=ssh_host_rsa_key
query_timeout=300

Diese Parameter sollten angepasst werden, die übrigen belässt am besten auf dem Standardwert

 

Parameter Wert Beschreibung
machine_id   Leer lassen, wird nur zusammen mit einer Serverlizenz und mehreren Servern auf der selben Hardware benötigt.
default_voice_port 9987 UDP Port, über den der Login abläuft, aber auch die Voice-Daten.
voice_ip 0.0.0.0, :: IPv4 und/oder IPv6 (kommagetrennte Liste), an die der Serverprozess gebunden werden soll.
filetransfer_port 30033 TCP Port über den der Datenaustausch erfolgt (Avatarbildern, Servericon etc.), aber auch die reine Dateitransferfunktion.
filetransfer_ip 0.0.0.0, :: IPv4 und/oder IPv6 (kommagetrennte Liste) an welche der Serverprozess gebunden werden soll.
query_port 10011 TCP Port über den die unverschlüsselten ServerQuery-Zugriffe über Telnet erfolgen.
query_ip 0.0.0.0, :: IPv4 und/oder IPv6 (kommagetrennte Liste) an welche der Serverprozess gebunden werden soll.
dbplugin ts3db_sqlite3 Das zu verwendende / aktive Datenbankplugin. SQLite3 ist eine lokale DB im Programmverzeichnis, für externe DB stehen die Werte ts3db_mariadb für MariaDB und ts3db_mysql für MySQL als Möglichkeit zur Verfügung.
dbpluginparameter   Plugin-spezifische Parameter, im Normalfall bleibt es leer
logquerycommands 0 Für Debugging sinnvoll, sonst gibt es nur riesige Logfiles.
dbclientkeepdays 30 Die Dauer in Tagen bis eine Client-ID aus der Datenbank wieder gelöscht wird. Betrifft nur diejenigen, die keiner Server- oder Channelgruppe zu geordnet wurden.
logappend 0 Wenn auf 1 gesetzt, wird nur noch eine ts3server_0.log resp. ts3server_1.log für alle virtuellen Server (auch nach Neustarts) erstellt.
http_proxy   Wie der TeamSpeak-3-Server selbst sich ins Internet verbindet, z. B. für die Lizenzabfrage, für eine direkte Verbindung ohne Proxy leer lassen.
license_accepted 1 alternative zu Parameterübergabe in der Shell, hier bleibt es fix gespeichert.
query_ssh_ip 0.0.0.0, :: IPv4 und/oder IPv6 (kommagetrennte Liste) an der, der Serverprozess gebunden werden soll.
query_ssh_port 10022 TCP Port über den die verschlüsselten ServerQuery-Zugriffe über SSH erfolgen.
query_protocols raw,ssh Aktiviert oder Deaktiviert die Queryverbindung über eines oder beiden Protokolle.

Der Parameterwert von dbconnections sollte nur mit Bedacht geändert werden, da dieser die Serverperformance extrem verschlechtern kann, d.h. der Bandbreitenverbrauch steigt. (Das hat aber nichts mit den maximalen Benutzerverbindungen zum TeamSpeak-3-Server zu tun!)

Möchte man die Protokolldateien übersichtlich halten, setzt man logappend=1. Dann erstellt der TeamSpeak-3-Server nur noch je ein Logfile pro virtuellen Server und fügt weitere Daten nach einen Neustart an. Sonst wird bei jedem Start ein neues Logfile mit diesem Namensformat ts3server_YYYY-MM-DD_ und _HH_MM_SS.xxxxxx_X.log erstellt. Mit einem zusätzlichen Eintrag dblogkeepdays kann man den Löschzyklus der Logfiles beeinflussen.

query_ip_allowlist.txt

Leere Datei erstellen mittels dem Befehl:

touch query_ip_allowlist.txt 

Diese enthält IPv4- und/oder IPv6-Adressen resp. Netzwerk/Subnetze, jeweils eine pro Zeile. In die Whitelist sollten alle Adressen, die besonders häufig auf die TeamSpeak-3-ServerQuery-Schnittstelle zugreifen. Diese werden sonst zu schnell automatisch (temporär) gebannt. Das können der lokale Webserver über das PHPFramework Library, oder aber auch Statistik-Server sein. Eintragen ist hier in der Beispieldatei die IP-Adresse von TSViewer.com 🇩🇪:

127.0.0.1
::1
192.168.0.0/16
94.23.235.222

query_ip_denylist.txt

 

Experten-Info:

Besser als die Blacklisting-Variante wäre auf jeden Fall, alle per Firewallregel zu blockieren und nur die wenigen der Whiteliste als Ausnahme durchzulassen. Das minimiert die Angriffsfläche für den Server effizienter.

Der gleiche Aufbau wie die Whitelist, nur diesen Adressen und Netzwerk/Subnetzen wird dauerhaft der Zugriff verweigert. Das verhindert jedoch nicht dem Login von TeamSpeak-3-Client selbst.

Leere Datei erstellen mittels dem Befehl:

touch query_ip_denylist.txt 

.ts3server_license_accepted

 

Achtung!

Ab TeamSpeak-3-Server Version 3.1.x wird der Start verweigert, wenn den Lizenzbestimmungen nicht zugestimmt wurde.

Leere Datei erstellen mittels dem Befehl:

touch .ts3server_license_accepted 

Hat den selben Effekt wie der Befehlsparameter license_accepted=1 oder dessen Eintrag in der ts3server.ini. Damit sollten nun keine Fehlermeldung zu der Lizenzierung erscheinen in der Konsole.

licensekey.dat

Sofern vorhanden muss zum Abschluss noch die Lizenz ins Programmverzeichnis kopiert werden. Erstmalig erhält man diese per E-Mail, später muss man davon regelmäßig selber ein Backup machen, da der Server diese automatisch aktualisiert. Solange diese Datei fehlt wird der Server dennoch starten, aber limitiert und im Log wird jeden Start solch ein Eintrag vorhanden sein:

...
2019-06-03 18:34:45.802284|WARNING |Accounting    |   |Unable to open licensekey.dat, falling back to limited functionality
2019-06-03 18:34:45.805880|INFO    |Accounting    |   |Licensing Information
2019-06-03 18:34:45.806046|INFO    |Accounting    |   |licensed to       : Anonymous
2019-06-03 18:34:45.806118|INFO    |Accounting    |   |type              : No License
2019-06-03 18:34:45.806204|INFO    |Accounting    |   |starting date     : Tue Jan  1 00:00:00 2019
2019-06-03 18:34:45.806275|INFO    |Accounting    |   |ending date       : Fri Jan 31 00:00:00 2020
2019-06-03 18:34:45.806339|INFO    |Accounting    |   |max virtualservers: 1
2019-06-03 18:34:45.806402|INFO    |Accounting    |   |max slots         : 32
...

Als Beispiel wie es Aussehen kann, wenn man eine gültige NPL (Non Profit License) besitzt:

...
2019-03-25 05:46:53.806197|INFO    |Accounting    |   |Licensing Information
2019-03-25 05:46:53.806266|INFO    |Accounting    |   |type              : Non-Profit License
2019-03-25 05:46:53.806305|INFO    |Accounting    |   |starting date     : Fri Feb  1 00:00:00 2019
2019-03-25 05:46:53.806331|INFO    |Accounting    |   |ending date       : Wed Aug 28 00:00:00 2019
2019-03-25 05:46:53.806355|INFO    |Accounting    |   |max virtualservers: 10
2019-03-25 05:46:53.806378|INFO    |Accounting    |   |max slots         : 512
...

Hinweis:

TeamSpeak System GmbH hat mit der TeamSpeak-3-Server Version 3.1.x auch die Lizenzen für die verschiedenen Providerstufen geändert/angepasst. Teileweise funktionieren bestehende NPL-Lizenzen weiter, sofern der Server bei dem Erneuerungszyklus aktiv ist.

Die meisten Installationen ohne die licensekey.dat werden ohne weitere Einschränkungen laufen. In diesen Fall bleibt nichts anderes übrig, als den Fehler bei jedem Server-Start im Logfile zu ignorieren.

Wem ein Server mit 32 Slots nicht reichen, konnte bisher eine NPL (Non Profit License) beantragen und nutzen, die für Private auch kostenlos war. Diese gibt es leider nicht mehr. Die kleinste Lizenzlösung 🇩🇪 ist nun eine Gamer-Lizenz, sie beinhaltet max. 1-2 Server mit gesamt max. 64-1024 Slots, diese ist jedoch nicht kostenlos!

Einrichtung abschließen

Nachdem alle wichtigen Konfigurationsdateien erstellt sind, kann man die temporäre Shell vom Benutzer teamspeak wieder verlassen:

exit 

Nach dem Logout sollte man noch nicht mehr benötigte Dateien löschen.

rm /tmp/teamspeak3-server_linux_$CPUSYS-$TS3_VERSION.tar.bz2 

Der Server muss nun einmal direkt gestartet werden, nicht mit dem mitgelieferten Startskript. Der Token (Berechtigungsschlüssel) wird zwar auch im Logfile aufgeführt, nicht aber das Password für den direkten Konsolenzugriff (Query).

cd /usr/local/bin/teamspeak3-server_linux_$CPUSYS/
sudo su $TS3_USER -c "./ts3server inifile=ts3server.ini license_accepted=1" -s /bin/sh 

In der Konsole resp. im Logfile befindet sich zu Beginn der Ausgabe beim Ersten Start folgende Zeilen:

2019-06-03 18:54:05.843638|INFO    |ServerLibPriv |   |TeamSpeak 3 Server 3.8.0 (2019-05-27 06:32:09)
2019-06-03 18:54:05.844128|INFO    |ServerLibPriv |   |SystemInformation: Linux 4.15.0-51-generic #55-Ubuntu SMP Wed May 15 14:27:21 UTC 2019 x86_64 Binary: 64bit
2019-06-03 18:54:05.846312|INFO    |DatabaseQuery |   |dbPlugin name:    SQLite3 plugin, Version 3, (c)TeamSpeak Systems GmbH
2019-06-03 18:54:05.846519|INFO    |DatabaseQuery |   |dbPlugin version: 3.11.1
2019-06-03 18:54:05.847540|INFO    |DatabaseQuery |   |checking database integrity (may take a while)
2019-06-03 18:54:05.900712|INFO    |SQL           |   |db_CreateTables() tables created

------------------------------------------------------------------
                      I M P O R T A N T
------------------------------------------------------------------
               Server Query Admin Account created
         loginname= "serveradmin", password= "0xXX7xXx"
------------------------------------------------------------------

2019-06-03 18:54:06.077708|WARNING |Accounting    |   |Unable to open licensekey.dat, falling back to limited functionality
2019-06-03 18:54:06.078569|INFO    |Accounting    |   |Licensing Information
2019-06-03 18:54:06.078745|INFO    |Accounting    |   |licensed to       : Anonymous
2019-06-03 18:54:06.078898|INFO    |Accounting    |   |type              : No License
2019-06-03 18:54:06.079143|INFO    |Accounting    |   |starting date     : Tue Jan  1 00:00:00 2019
2019-06-03 18:54:06.079411|INFO    |Accounting    |   |ending date       : Fri Jan 31 00:00:00 2020
2019-06-03 18:54:06.079671|INFO    |Accounting    |   |max virtualservers: 1
2019-06-03 18:54:06.080068|INFO    |Accounting    |   |max slots         : 32
2019-06-03 18:54:06.296714|INFO    |              |   |myTeamSpeak identifier revocation list was downloaded successfully - all related features are activated
2019-06-03 18:54:11.127771|INFO    |              |   |Puzzle precompute time: 4857
2019-06-03 18:54:11.128933|INFO    |FileManager   |   |listening on 0.0.0.0:30033, [::]:30033
2019-06-03 18:54:11.131890|INFO    |VirtualSvrMgr |   |executing monthly interval
2019-06-03 18:54:11.132500|INFO    |VirtualSvrMgr |   |reset virtualserver traffic statistics
2019-06-03 18:54:11.193011|INFO    |VirtualServer |1  |listening on 0.0.0.0:9987, [::]:9987
2019-06-03 18:54:11.196074|WARNING |VirtualServer |1  |--------------------------------------------------------
2019-06-03 18:54:11.196230|WARNING |VirtualServer |1  |ServerAdmin privilege key created, please use the line below
2019-06-03 18:54:11.196362|WARNING |VirtualServer |1  |token=7Xxx7XXX9x27xxxxXXX1xlXxxx3x2XxXXXxx5XX2
2019-06-03 18:54:11.196492|WARNING |VirtualServer |1  |--------------------------------------------------------

------------------------------------------------------------------
                      I M P O R T A N T
------------------------------------------------------------------
      ServerAdmin privilege key created, please use it to gain
      serveradmin rights for your virtualserver. please
      also check the doc/privilegekey_guide.txt for details.

       token=7Xxx7XXX9x27xxxxXXX1xlXxxx3x2XxXXXxx5XX2
------------------------------------------------------------------

2019-06-03 18:54:11.197669|INFO    |Query         |   |listening for query on 0.0.0.0:10011, [::]:10011
2019-06-03 18:54:11.198661|INFO    |Query         |   |listening for query ssh on 0.0.0.0:10022, [::]:10022
2019-06-03 18:54:11.198866|INFO    |Query         |   |creating QUERY_SSH_RSA_HOST_KEY file: ssh_host_rsa_key
2019-06-03 18:54:22.395453|INFO    |CIDRManager   |   |updated query_ip_allowlist ips: 127.0.0.1/32, ::1/128, 172.16.1.0/24, 94.23.235.222/32,
2019-06-03 18:54:30.897121|INFO    |ServerMain    |   |Received signal SIGINT, shutting down.
2019-06-03 18:54:30.948034|INFO    |VirtualServerBase|1  |stopped
^C
Sitzung abgebrochen, Shell wird beendet ... ... abgebrochen.

 

2019-06-03 18:54:11.193011|INFO    |VirtualServer |1  |listening on 0.0.0.0:9987, [::]:9987
2019-06-03 18:54:11.196074|WARNING |VirtualServer |1  |--------------------------------------------------------
2019-06-03 18:54:11.196230|WARNING |VirtualServer |1  |ServerAdmin privilege key created, please use the line below
2019-06-03 18:54:11.196362|WARNING |VirtualServer |1  |token=7Xxx7XXX9x27xxxxXXX1xlXxxx3x2XxXXXxx5XX2
2019-06-03 18:54:11.196492|WARNING |VirtualServer |1  |--------------------------------------------------------

Mittels Tastenkombination Strg + C den Server beenden. Nun ist der Server bereit für seinen Betrieb. Starten lässt dieser mit dem eigenen Startskript.

sudo su $TS3_USER -c "/usr/local/bin/teamspeak3-server_linux_${CPU}/ts3server_startscript.sh start inifile=ts3server.ini license_accepted=1" -s /bin/sh 

Der Befehlsparameter license_accepted=1 hat den selben Effekt wie der Eintrag in der ts3server.ini oder das Anlegen der Datei .ts3server_license_accepted.

Den Status abfragen, ob der TeamSpeak-3-Server aktiv ist, lässt sich über folgenden Befehl.

/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server_startscript.sh status 

Jetzt muss sich nur der Server-Admin als erster Benutzer auf den TeamSepak-3-Server einloggen. Dieser erhält sofort nach dem Login ein Popupdialog, in welchen man den Token (Berechtigungsschlüssel) eingeben muss. Somit erhält derjenige den Status der Servergruppen-Admin und kann alles weitere für den Server vom Client-Programm aus konfigurieren. Im Logfile stehen dann als Bestätigung diese Zeilen:

2019-06-03 18:58:54.150718|INFO    |VirtualServer |1  |client (id:2) was added to servergroup 'Server Admin'(id:6) by client 'server'(id:0)
2019-06-03 18:58:54.153381|INFO    |VirtualServer |1  |client 'Axeaminator'(id:2) used privilege key '7Xxx7XXX9x27xxxxXXX1xlXxxx3x2XxXXXxx5XX2' and was added to servergroup 'Server Admin'(id:6)

Hinweis:

Der Token funktioniert nur einmal für einen Benutzer!

Sollte der Token abhanden gekommen sein, z.B. weil das Logfile gelöscht wurde, siehe Problembehandlung für das weitere Vorgehen.

Damit ist die Einrichtung des TeamSpeak-3-Servers abgeschlossen und der Server betriebsbereit. Im Abschnitt Automatischer Systemstart wird beschrieben, wie man den TeamSpeak-3-Server direkt mit dem Systemstart mitstarten lassen kann.

Aktualisierung

 

Achtung!

Da diese Software nicht über die Paketverwaltung installiert wurde, sollte jeder Server-Administrator selber darum bemüht sein, stets die aktuelle Version installiert zu haben. Nur so sind Sicherheitspatches und Fehlerbehungen auf dem aktuellen Stand.

Den TeamSpeak-3-Server beenden falls dieser noch läuft.

sudo systemctl stop ts3server.service 

Aus Sicherheitsgründen sollte von der ts3server.sqlitedb ein Backup gemacht werden, nach dem der Server gestoppt wurde.

cd /usr/local/bin/teamspeak3-server_linux_$CPUSYS
[ -d ./backup/ ] || sudo mkdir backup
sudo cp --backup=numbered ts3server.sqlitedb ./backup/ 

Danach ist das Vorgehen ähnlich wie bei beim Installieren.

cd /tmp
wget -4 --no-cache  https://files.teamspeak-services.com/releases/server/$TS3_VERSION/teamspeak3-server_linux_$CPUSYS-$TS3_VERSION.tar.bz2 

Installationspaket entpacken [3] und installieren.

cd /usr/local/bin
sudo tar -xjf /tmp/teamspeak3-server_linux_$CPUSYS-$TS3_VERSION.tar.bz2
sudo chown $TS3_USER:nogroup teamspeak3-server_linux_$CPUSYS/
sudo chmod go-w -R teamspeak3-server_linux_$CPUSYS/ 

Das gesammte Programmpaket gehört nun dem Benutzer root und unnötige Gruppen resp. jede Schreibrechte [5] wurden entfernt. Heruntergelandenes Installationspaket löschen:

rm /tmp/teamspeak3-server_linux_$CPUSYS-$TS3_VERSION.tar.bz2 

Nun nur den TeamSpeak-3-Server wieder starten.

sudo systemctl start ts3server.service 

Automatischer Systemstart

Das mit Abstand Wichtigste ist der automatische Start des TeamSpeak-3-Servers. Wobei systemd gegenüber dem alten SysVinit zu bevorzugen ist, wenn auch der Start damit immernoch funktioniert.

Für eine bessere Übersicht der eigenen Shellscripte erstellt man ein eigenes Unterverzeichnis innerhalb des Installationsverzeichnis des TeamSpeak-3-Servers.

cd /usr/local/bin/teamspeak3-server_linux_$CPUSYS/
sudo mkdir scripts
cd scripts 

Dazu gehört eine entsprechende Konfigurationsdatei für systemd. Dazu die Datei ts3server.service erstellen resp. den Inhalt kopieren, anpassen [7] und speichern unter /usr/local/bin/teamspeak3-server_linux_$CPUSYS/scripts/.

[Unit]
Description=TeamSpeak 3 Server
After=network.target network-online.target
Requires=network-online.target

[Service]
User=teamspeak
Group=nogroup
Type=forking
WorkingDirectory=/usr/local/bin/teamspeak3-server_linux_$CPUSYS
ExecStartPre=-/usr/bin/sqlite3 -line /usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server.sqlitedb 'pragma integrity_check;'
ExecStartPost=-/usr/bin/sqlite3 -line /usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server.sqlitedb 'vacuum;'
ExecStart=/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server_startscript.sh start inifile=/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server.ini license_accepted=1
ExecStop=/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server_startscript.sh stop
ExecReload=/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server_startscript.sh restart inifile=/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server.ini license_accepted=1
PIDFile=/usr/local/bin/teamspeak3-server_linux_$CPUSYS/ts3server.pid
RestartSec=30
Restart=always

[Install]
WantedBy=multi-user.target

Achtung!

Nicht vergessen, den Platzhalter $CPUSYS durch amd64 oder x86 zu ersetzen in der eigenen Konfiguration, sonst wird der Serverstart scheitern!

Die Konfiguration beinhaltet auch einen Datenbankintegritäts-Überprüfung und einen automatischen Service-Neustart (nach Absturz oder ungewolltem Beenden). Danach die systemd-Konfiguration vom System neueinlesen lassen, die Datei ts3server.service in /etc/systemd/system verlinken und den neu hinzugefügten Service aktivieren.

sudo systemctl daemon-reload
sudo systemctl enable /usr/local/bin/teamspeak3-server_linux_amd64/scripts/ts3server.service 

Diese Ausgabe erscheint wenn der Service erfolgreich installiert wurde.

Created symlink /etc/systemd/system/multi-user.target.wants/ts3server.service -> /usr/local/bin/teamspeak3-server_linux_amd64/scripts/ts3server.service.
Created symlink /etc/systemd/system/ts3server.service -> /usr/local/bin/teamspeak3-server_linux_amd64/scripts/ts3server.service.

Danach den Server via systemd starten und den Status ausgeben:

sudo systemctl start ts3server.service
sudo systemctl status ts3server.service 

Diese Ausgabe erscheint wenn der Service erfolgreich installiert wurde.

● ts3server.service - TeamSpeak 3 Server
   Loaded: loaded (/usr/local/bin/teamspeak3-server_linux_amd64/scripts/ts3server.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2019-06-03 19:07:34 CEST; 3min 13s ago
  Process: 1438 ExecStartPost=/usr/bin/sqlite3 -line /usr/local/bin/teamspeak3-server_linux_amd64/ts3server.sqlitedb vacuum; (code=exited, status=0/SUCCESS)
  Process: 1422 ExecStart=/usr/local/bin/teamspeak3-server_linux_amd64/ts3server_startscript.sh start inifile=/usr/local/bin/teamspeak3-server_linux_amd64/ts3server.ini license_accepted=1 (code=exited, status=0/SUCCESS)
  Process: 1414 ExecStartPre=/usr/bin/sqlite3 -line /usr/local/bin/teamspeak3-server_linux_amd64/ts3server.sqlitedb pragma integrity_check; (code=exited, status=0/SUCCESS)
 Main PID: 1434 (ts3server)
    Tasks: 17 (limit: 4662)
   CGroup: /system.slice/ts3server.service
           └─1434 ./ts3server inifile=/usr/local/bin/teamspeak3-server_linux_amd64/ts3server.ini license_accepted=1 daemon=1 pid_file=ts3server.pid

Jun 03 19:07:34 ubuntuserver systemd[1]: Starting TeamSpeak 3 Server...
Jun 03 19:07:34 ubuntuserver sqlite3[1414]: integrity_check = ok
Jun 03 19:07:34 ubuntuserver ts3server_startscript.sh[1422]: Starting the TeamSpeak 3 server
Jun 03 19:07:34 ubuntuserver ts3server_startscript.sh[1422]: TeamSpeak 3 server started, for details please view the log file
Jun 03 19:07:34 ubuntuserver systemd[1]: Started TeamSpeak 3 Server.

Sollte eine Fehlermeldung auftauchen, ähnlich wie diese Zeile, muss noch ein Paket für SQlite3 nachinstalliert werden.

Jun 03 19:07:34 ubuntuserver systemd[2810]: ts3server.service: Executable /usr/bin/sqlite3 missing, skipping: No such file or directory

Befehl zum Installieren der Pakete:

sudo apt-get install sqlite3 

Oder mit apturl installieren, Link: apt://sqlite3

Damit sollte dieser Fehler behoben sein.

Upgrade

  1. Laufenden Server beenden: /etc/init.d/ts3server stop
  2. Backup des aktuellen Verzeichnisses: /home/teamspeak3/ts3server
  3. Neue Version herunterladen: https://www.teamspeak.de/download/teamspeak-3-amd64-server-linux/
  4. Alle Dateien aus dem Archiv in bestehendes Teamspeak3 Verzeichnis kopieren und alles überschreiben
  5. Server wieder starten /etc/init.d/ts3server start

Fehlerbehebung

TS3 Server can´t start

failed to register local accounting service

Quelle: https://forum.teamspeak.com/threads/93623-Instance-check-error-failed-to-register-local-accounting-service-on-Linux?p=465681#post465681

root@nginx01-a:/usr/local/bin/teamspeak3-server_linux_amd64# systemctl stop ts3server.service
root@nginx01-a:/usr/local/bin/teamspeak3-server_linux_amd64# ls -al /dev/shm/
total 4
drwxrwxrwt  2 root root   60 Jan 27 18:06 .
drwxr-xr-x 18 root root 3340 Jan 25 06:43 ..
-rw-r--r--  1 root root  128 Jan 27 18:06 7gbhujb54g8z9hu43jre8
root@nginx01-a:/usr/local/bin/teamspeak3-server_linux_amd64# rm -f /dev/shm/7gbhujb54g8z9hu43jre8
root@nginx01-a:/usr/local/bin/teamspeak3-server_linux_amd64# systemctl start ts3server.service
root@nginx01-a:/usr/local/bin/teamspeak3-server_linux_amd64# tail -f logs/ts3server_2022-01-27__17_1
ts3server_2022-01-27__17_10_00.802754_0.log  ts3server_2022-01-27__17_11_00.478223_1.log  ts3server_2022-01-27__17_12_22.966452_1.log  ts3server_2022-01-27__17_13_45.208442_1.log
ts3server_2022-01-27__17_11_00.478223_0.log  ts3server_2022-01-27__17_12_22.966452_0.log  ts3server_2022-01-27__17_13_45.208442_0.log  ts3server_2022-01-27__17_14_52.011307_0.log
root@nginx01-a:/usr/local/bin/teamspeak3-server_linux_amd64# tail -f logs/ts3server_2022-01-27__17_14_52.011307_0.log
2022-01-27 17:14:52.017133|INFO    |DatabaseQuery |   |checking database integrity (may take a while)
2022-01-27 17:14:52.130047|WARNING |Accounting    |   |Unable to open licensekey.dat, falling back to limited functionality
2022-01-27 17:14:52.130439|INFO    |Accounting    |   |Licensing Information
2022-01-27 17:14:52.130461|INFO    |Accounting    |   |licensed to       : Anonymous
2022-01-27 17:14:52.130471|INFO    |Accounting    |   |type              : No License
2022-01-27 17:14:52.130487|INFO    |Accounting    |   |starting date     : Thu Oct  1 00:00:00 2020
2022-01-27 17:14:52.130497|INFO    |Accounting    |   |ending date       : Tue Nov  1 00:00:00 2022
2022-01-27 17:14:52.130505|INFO    |Accounting    |   |max virtualservers: 1
2022-01-27 17:14:52.130513|INFO    |Accounting    |   |max slots         : 32
2022-01-27 17:14:52.161750|INFO    |DatabaseQuery |   |database busy, waiting for finishing index tasks, may take some time!
2022-01-27 17:15:43.734417|INFO    |              |   |Puzzle precompute time: 1544
2022-01-27 17:15:43.735082|INFO    |FileManager   |   |listening on 0.0.0.0:30033, [::]:30033
2022-01-27 17:15:43.738282|INFO    |Query         |   |Using a query thread pool size of 2
2022-01-27 17:15:43.822931|INFO    |Query         |   |listening for query on 0.0.0.0:10011, [::]:10011
2022-01-27 17:15:43.823646|INFO    |Query         |   |listening for ssh query on 0.0.0.0:10022, [::]:10022
2022-01-27 17:15:43.823956|INFO    |Query         |   |listening for http query on 0.0.0.0:10080, [::]:10080
2022-01-27 17:15:43.824185|INFO    |CIDRManager   |   |updated query_ip_allowlist ips: 127.0.0.1/32, ::1/128, 91.9.27.121/32,

Lösung:

- Ts3 Server stoppen

- Datei mit random Namen unter /dev/shm/xxxxxxx löschen

- Ts3 Server starten

Tmux

Cheatsheet and References

1. https://gist.github.com/MohamedAlaa/2961058

2. https://tmuxcheatsheet.com/

 

 

 

Tmux Guide

Quelle: https://linuxize.com/post/getting-started-with-tmux/

Starting Your First Tmux Session

To start your first Tmux session, simply type tmux in your console:

tmux

This will open a new session, create a new window, and start a shell in that window.

Once you are in Tmux you’ll notice a status line at the bottom of the screen which shows information about the current session.

You can now run your first Tmux command. For example, to get a list of all commands, you would type:

Ctrl+b ?

Creating Named Tmux Sessions

By default, Tmux sessions are named numerically. Named sessions are useful when you run multiple Tmux sessions. To create a new named session, run the tmux command with the following arguments:

tmux new -s session_name

It’s always a good idea to choose a descriptive session name.

Detaching from Tmux Session

You can detach from the Tmux session and return to your normal shell by typing:

Ctrl+b d

The program running in the Tmux session will continue to run after you detach from the session.

Re-attaching to Tmux Session

To attach to a session first, you need to find the name of the session. To get a list of the currently running sessions type:

tmux ls

The name of the session is the first column of the output.

0: 1 windows (created Sat Sep 15 09:38:43 2018) [158x35]
my_named_session: 1 windows (created Sat Sep 15 10:13:11 2018) [78x35]

As you can see from the output, there are two running Tmux sessions. The first one is named 0 and the second one my_named_session.

For example, to attach to session 0, you would type:

tmux attach-session -t 0

Working with Tmux Windows and Panes

When you start a new Tmux session, by default, it creates a single window with a shell in it.

To create a new window with shell type Ctrl+b c, the first available number from the range 0...9 will be assigned to it.

A list of all windows is shown on the status line at the bottom of the screen.

Below are some most common commands for managing Tmux windows and panes:

Kommando in eine Terminal Session schicken (in den Hintergrund)

Bash

Bash-completion

root Umgebung einstellen

Quelle: https://askubuntu.com/a/156668

In der /root/.bashrc folgendes ans Ende der Datei eintragen:

if [ -f /etc/bash_completion ]; then
  . /etc/bash_completion
fi

initramfs

Fehlermeldung

W: initramfs-tools configuration sets RESUME=UUID=xxxxxx-ssss-eeee-rrrr-ttttttttt
W: but no matching swap device is available.
I: The initramfs will attempt to resume from /dev/sdc2
I: (UUID=aaaaaaaa-bbbb-ssss-rrrr-ggggggggg)
I: Set the RESUME variable to override this.

Quelle: https://www.linuxmintusers.de/index.php?PHPSESSID=c510887ae786d518275c8389c59ee625&topic=57399.msg771471#msg771471

Wenn so eine Meldung auftritt dann kann man das beheben indem man die Variable RESUME überschreibt in der Datei /etc/initramfs-tools/conf.d/resume

#RESUME=UUID=xxxxxx-ssss-eeee-rrrr-ttttttttt
RESUME=none

Java - openjdk

Openjdk-8 in Debian Buster installieren

Quelle: https://stackoverflow.com/questions/57031649/how-to-install-openjdk-8-jdk-on-debian-10-buster/61902164#61902164

Installation steps:

  1. Install software source manager

    apt-get update
    apt-get install software-properties-common
    
  2. Add mirror with openjdk-8-jdk

    apt-add-repository 'deb http://security.debian.org/debian-security stretch/updates main'
    apt-get update
    
  3. Install openjdk 8

    apt-get install openjdk-8-jdk