--- gitea: none include_toc: true --- # Commands ## Linux Distibution show os version. ``` lsb_release -a # or hostnamectl # or cat /etc/*-release ``` ## bash su, sudo etc. see https://newbedev.com/su-vs-sudo-s-vs-sudo-i-vs-sudo-bash ## Installation/Packages Liste installierte Pakete ``` dpkg --list ``` ## History `history` gibt letzte Befehle an. Sie haben eine Nummer. ``` # Location des history files echo $HISTFILE # history nicht aufzeichnen (nicht dauerhaft) unset $HISTFILE # einige Befehle ignorieren für history vi .bashrc export HISTIGNORE="ls:cd" --> für die Befehle, die nicht gespeichert werden sollen. # länge der history echo $HISTSIZE echo $HISTFILESIZE # anpassen vi .bashrc HISTSIZE=2000 HISTFILESIZE=2000 # timestamp der history hinzufügen vi .bashrc export HISTTIMEFORMAT="%c " # duplikate in history raus nehmen echo $HISTCONTROL vi .bashrc export HISTCONTROL=ignoredups # history file an einem anderen ort vi .bashrc export HISTFIILE="/home/rene/meinehistory" # reverse search in history CTRL-R, und dann anfangen zu schreiben. Next match: CTRL-R # letzte 4 Befehle history 4 # letzter Befehl nochmal ausführen !! # Befehl 1234 ausführen !1234 # Auto-Vervollständigen !his --> führt letzten history befehl aus, !his:p --> zeigt letzten Befehl nur an, der so anfängt, also history # in history suchen history | grep ping # history löschen history -c # history in datei history -w # history einzelne zeilen löschen history -d 56 # Befehl, der nicht in History vorkommt. Also ausführen und gleich aus history löschen. echo *dies ist mein geheimer befehl"; history -d $(history 1) ``` ## Permissions ### Generell `Owner-Group-World` kann `read-write-execute` #### Beispiel 1 ``` -rw-r--r-- 1 bob users 1892 Jul 10 18:30 linux_course_notes.txt ``` Datei gehört zur Gruppe users, genauer zum user bob, und es handelt sich um 1 Datei. \ Zu den Permission Symbolen am Anfang: ``` -: ein normales file. Ein Directory hätte ein d. r: user bob kann lesen w: user bob kann schreiben -: user bob kann nicht ausführen oder es ist gar kein ausführbares Programm r: gruppe users kann lesen -: gruppe users kann nicht schreiben -: gruppe users kann nicht ausführen oder es ist gar kein ausführbares Programm r: alle im Netzwerk können lesen -: alle im Netzwerk können nicht schreiben -: alle im Netzwerk können nicht ausführen oder es ist gar kein ausführbares Programm ``` ### Berechtigungen ändern mit chmod Schema: `chmod owner group world FileName`\ -> chmod read+write read read FileName\ -> chmod 644 FileName 4 = read (r)\ 2 = write (w)\ 1 = execute (x) das ergibt, wenn man zusammenzählt:\ 7 = 4+2+1 (read/write/execute)\ 6 = 4+2 (read/write)\ 5 = 4+1 (read/execute)\ 4 = 4 (read)\ 3 = 2+1 (write/execute)\ 2 = 2 (write)\ 1 = 1 (execute) ``` # read/write by anybody! (the devil loves this one!) chmod 666 mydoc.txt # rwx for owner, rx for group and rx for the world chmod 755 mydoc.txt # read, write, execute for all! (may not be the best plan in the world...) chmod 777 mydoc.txt ``` ## Files and Paths ### WSL Mount Network Drive Mount a Drive Until Logoff - Note the letter of the network drive that you would like to map in WSL. We will use `M:` in this example. - Create a new folder for that drive letter under `/mnt` if it does not already exist. (ex: `mkdir /mnt/m`) - Mount the drive with `sudo mount -t drvfs M: /mnt/m` Mount Drives in a Persistent Manner - Ensure the folder exists for the mount target (e.g. `/mnt/m`) - Open `/etc/fstab` and add a line such as the following: `M: /mnt/m drvfs defaults 0 0` - Reload the fstab file with `sudo mount -a` ### Symlinks ``` ln -s ``` ### Print working directory ``` pwd ``` ### list files and directories ``` ls - ``` All Parameters here: [[https://manpages.ubuntu.com/manpages/bionic/de/man1/ls.1.html]]\ Most used Parameters: | Param | Description | | ----------- | ----------- | | -a | also show hidden files, beginning with . | | -h | human readable | | -l | long list format | | -r | descending sort order | | -R | also list sub folders recursively | | -t | sort by date modified mtime | | -lu | sort by access date atime | ### find directory ``` find / -type d -name httpdocs ``` ### find directories older than n minutes AND delete them ``` sudo find ${TARGET_DIR}/* -type d -mmin +100 | xargs rm -rf ``` ### find directories older than x days AND delete them ``` sudo find ${TARGET_DIR}/* -type d -ctime +8 | xargs rm -rf ``` ### find files older than DATE AND delete them ``` find /path -type f -not -newermt "YYYY-MM-DD HH:MI:SS" -delete ``` ### find folders older than DATE AND delete them ``` find /home/administrator/backup_docubase -type d -not -newermt "2021-07-01 00:00:00" -exec rm -rf {} + ``` ### find file ``` find / -type f -name "process.txt" find / -type f -name "process.txt" -not -path "./directory/*" ``` with full path: ``` find ~/Dropbox/Bilder/2013/2013-04---\ La\ Reunion/2013-04-06/ -maxdepth 1 -type f ``` ### find all files with windows (CRLF) newline ``` find . -not -type d -exec file "{}" ";" | grep CRLF ``` ### find large files ``` find / -size +10M -ls ``` ### copy files ``` cp biopic/ray.txt historical/ cp biopic/ray.txt biopic/notorious.txt historical/ cp * satire/ cp wonderwoman.txt wonderwoman-new.txt (duplicate) ``` ### move/rename files ``` mv wonderwoman.txt batman.txt superhero/ mv wonderwoman.txt batman.txt (rename) ``` batch rename files: ``` n=1; for file in *.jpg; do mv "$file" "stuttgart_1975-11-02_$((n++)).jpg"; done ``` ### remove ``` rm textfile.txt rm -- -textfile.txt (files starting with a "-") rm -r DIRECTORYNAME (directory and its contents) ``` ### create file ``` touch textfile.txt echo "Hello" > hello.txt ``` ### create directory ``` mkdir media ``` or multiple directories at once: ``` mkdir -p folder_{a..z}/{AAA_{1..3},BBB_{1..9}} ``` ## Redirection/Input/Output/Search-Replace ### echo text ``` echo "hello" ``` ### output contents of a file ``` cat hello.txt less hello.txt (only first few lines, arrow-down for more, q to quit. tail -n 50 hello.txt (last 50 lines) tail -f hello.txt (last lines, live view) ``` ### add text to file ``` echo "Hello" > hello.txt (overwrite) echo "Hello" >> hello.txt (append on new line) cat goodbye.txt >> hello.txt ``` ### echo command output to file ``` $ find . -type f -user root | tee -a ~/objects-user-root.txt (-a adds it to existing content) ``` ### word count ``` wc hello.txt (Print newline, word, and byte counts) ``` ### pipes Möglichkeiten die Ausgabe einzelnen Befehle umzuleiten, z.B. an Logdateien, an Terminals, Drucker, aber auch andere Befehle weiterzuleiten. `stdin`, hat die Nummer 0 (Meistens Tastatureingaben)\ `stdout`, hat die Nummer 1 (Ausgaben am Bildschirm\ `stderr`, hat die Nummer 2 (Ausgabe am Bildschirm für Errors)\ **Einlesen** mit `<` ``` # Entferne alle Doppelpunkte tr -d ":" < dateiliste.txt # Mail mit Eingabe verschicken mail chef@blabla.com < datei.txt ``` **Umleiten** mit `>`. So wird auf dem Bildschirm nichts angezeigt. Mit `tee` Lässt sich die Ausgabe kopieren. ``` ls -la | tee ausgabe.txt ``` Wenn nicht nur stdout sondern auch stderr umgeleitet werden soll, zuerst `2>` für stderr und dann `1>` für stdout angeben: ``` find 2> error.txt 1> find.txt ``` Wenn stderr und stdout zusammen in die gleiche Datei geschrieben werden sollen: ``` find / -name ".bash*" 1> find.txt 2>&1 ``` Mit `>>` wird an die Datei angehängt, nicht neu erstellt. **Weiterleiten** an neuen Befehl mit `|`. ``` # Sortiere die Prozess-Liste nach Prozess-ID rückwärts ps aux | sort -nr # Textdatei sortieren und duplikate entfernen cat kontaktliste.txt | sort | uniq ``` ``` cat hallo.txt | wc | cat >> hallo.txt (sending the output of hallo.txt to wc. output of wc is then appended to hallo.txt) ``` ### sort/duplicates ``` sort hello.txt cat hello.txt | sort > sorted-hello.txt uniq hello.txt (read file without duplicate lines) sort deserts.txt | uniq (sort without duplicates) ``` ### search text in files ``` grep -irno "h1" grep -irn "h1" /home/user/verzeichnis-abc grep -irn "h1" --include \*.ps1 --include \*.txt grep -irn "h1" --include \*.ps1 --include \*.txt /home/user/verzeichnis-abc ``` ### stream editor (search and replace ``` sed 's/snow/rain/g' forests.txt (replaces all "snow" with "rain") ``` ### Disable stout stderr Example: `umount /mnt/data > /dev/null 2>&1`\ stdout und stderr verschwinden in dev/null. zuerst stdout, und stderr wird weitergeleitet an stdout. ## User and Environment ### Befehl als anderen Benutzer ausführen ``` sudo -u www-data whoami ``` ### Benutzer wechseln ``` sudo -u benutzername bash ``` Oder allenfalls besser: ``` sudo su - benutzername ``` ### liste aller User Enthält Informationen zu den Benutzerkonten. Das PW wäre dort wo am anfang das `x` steht (noch aus früheren Zeiten, ist jetzt in `/etc/shadow` verschlüsselt drin. ``` cat /etc/passwd ``` oder alle "normale" user: ``` getent passwd {1000..60000} ``` ### show all users with groups ``` grep ubuntu /etc/group ``` ### User passwörter verschlüsselte Informationen zu den Benutzerkonten ``` sudo cat /etc/shadow|sort ``` ### info zum aktuellen user ``` w who ``` ### add to group ``` # add to sudo group (with sudo-rights) usermod -aG sudo/wheel # group sudo for DEBIAN, group wheel in BSD/RHEL # add to another group, like docker sudo usermod -aG docker # activate changes newgrp docker ``` ### don't let wheel members let change root password ``` visudo -f /etc/sudoers #Change from: %wheel ALL=(ALL) TO ALL, !/usr/bin/passwd root systemctl restart sshd ``` ### get all sudoer users ``` getent group sudo | cut -d: -f4 # or grep -Po '^sudo.+:\K.*$' /etc/group ``` ### Benutzer löschen ``` deluser username ``` ### Benutzer/Gruppe setzen ``` chown -R www-data:www-data /var/www ``` ### Passwort ändern ``` sudo passwd root sudo passwd ``` ### bash profile ``` ~/.bash_profile (OSX) or ~/.bashrc (Linux) is the name of file used to store environment settings. It is commonly called the “bash profile”. When a session starts, it will load the contents of the bash profile before executing commands. * open file: $ nano ~/.bash_profile * edit: $ echo "Welcome, Roger" $ alias pd="pwd" $ alias ll="ls -la" $ export USER="Roger Rutishauser" (environment variable USER, can be echoed by "echo $USER" $ export PS1=">> " (changes $ in console to >> ) * activate $ source ~/.bashrc (activates the changes in ~/.bashrc for the current session) ``` ### environment variables ``` env (lists all environment variables) echo $PATH *ODER* env | grep PATH (lists which directories contain scripts) echo $HOME (echoes path of home directory) ``` ### environment variables: set ``` $ sudo vi /etc/bash.bashrc JAVA_HOME=/opt/jdk/jdk8u282-b08-jre PATH=$PATH:$HOME/bin:$JAVA_HOME/bin export JAVA_HOME export PATH $ source /etc/profile ``` See also: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-configure-proxy-on-ubuntu-18-04/ ## Hardware Informationen ``` lscpu # CPU Informationen free -h # Memory ``` ## Datenträger, Verzeichnisstruktur ### Angeschlossene Festplatten und Wechseldatenträger inkl. der Partitionen anzeigen ``` cat /proc/partitions ``` ### Nur Festplatten, ohne Partitionen ``` sed -ne 's/.*\([sh]d[a-zA-Z]\+$\)/\/dev\/\1/p' /proc/partitions ``` ### Nur Partitionen, ohne Festplatten ``` sed -ne 's/.*\([sh]d[a-zA-Z]\+[0-9]\+$\)/\/dev\/\1/p' /proc/partitions ``` als Liste: ``` sudo blkid -o list -w /dev/null ``` ### Verzeichnis und Partitionen Baum ``` lsblk ``` ### LVM (Logical Volume Manager Mehr Infos unter [https://www.digitalocean.com/community/tutorials/an-introduction-to-lvm-concepts-terminology-and-operations]\ Harddisk vergrössert, dann auf Ubuntu vergrössern: https://fabianlee.org/2016/07/26/ubuntu-extending-a-virtualized-disk-when-using-lvm/ ## Daemon ### Definition - A process which runs in the background and is not interactive. - They have no controlling terminal on their own from the user’s perspective from the desktop. - They continue to exist and operate regardless of any user being logged into the server if the computer is on. - In Windows, daemons are called services ### Start Service ``` systemctl start mysql # or on older ubuntu versions or on WSL: service mysql start ``` ## Prozesse ### Definition An instance of a particular executable that is being executed.\ For example this could be an `.exe` program file or a Linux binary. A given application may have several processes running simultaneously.\ Typically, an executing program can exist in one of three states: - Running: Active - Sleeping: Inactive - Zombie: A process that has completed execution, but still has an entry in the process table ### Zeige Prozesse `ps aux` zeigt alle laufenden Prozesse aller Benutzer an. Da sieht man u.a. den ausführend User und die CPU/Memory Auslastung. Zur Unterscheidung der Prozesse dient `TTY` und `COMMAND`. `TTY` mit `?` sind Daemon-Prozesse. Wenn das Command mit `[k` startet, ist es ein Kernel-Thread-Prozess. `tty1` ist Terminal `pts/0` ist ein User.. Beispiel: ``` [rogrut@rr ~]$ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 193808 6892 ? Ss 17:01 0:00 /usr/lib/systemd/systemd --switched-root --system --deserialize 22 root 2 0.0 0.0 0 0 ? S 17:01 0:00 [kthreadd] root 4 0.0 0.0 0 0 ? S< 17:01 0:00 [kworker/0:0H] root 87 0.0 0.0 0 0 ? S 17:01 0:00 [kworker/1:1] root 125 0.0 0.0 0 0 ? S 17:01 0:00 [kauditd] root 319 0.0 0.0 0 0 ? S< 17:01 0:00 [ext4-rsv-conver] root 405 0.0 0.0 39060 4660 ? Ss 17:01 0:00 /usr/lib/systemd/systemd-journald root 414 0.0 0.0 0 0 ? S 17:01 0:00 [kworker/3:2] root 436 0.0 0.0 48364 4804 ? Ss 17:01 0:00 /usr/lib/systemd/systemd-udevd root 524 0.0 0.0 0 0 ? S 17:01 0:00 [kworker/5:2] root 527 0.0 0.0 0 0 ? S< 17:01 0:00 [kworker/0:1H] root 535 0.0 0.0 0 0 ? S 17:01 0:00 [jbd2/sda2-8] root 536 0.0 0.0 0 0 ? S< 17:01 0:00 [ext4-rsv-conver] root 557 0.0 0.0 55532 860 ? S ~/checkOwnObj.log 2>&1` - CTRL-Z - `bg` - `jobs` - `disown %1` - `jobs` - `ps aux | grep find` - falls CTRL-Z schiefläuft, vor den Befehl `nohup` und ans Ende `&` schreiben. Dann enter drücken und ps aux... ``` nohup bash -c 'php symfony csv:import --rows-until-update=10 /home/mikeymouse/export-archival-descriptions-20210906_rsi.csv && php symfony csv:import --rows-until-update=10 /home/mikeymouse/export-archival-descriptions-20210906_rtr.csv && php symfony csv:import --rows-until-update=10 /home/mikeymouse/export-archival-descriptions-20210906_rts.csv && php symfony csv:import --rows-until-update=10 /home/mikeymouse/export-archival-descriptions-20210906_swissinfo.csv && php symfony csv:import --rows-until-update=10 --skip-nested-set-build /home/mikeymouse/export-archival-descriptions-20210906_srf.csv && php symfony propel:build-nested-set && php symfony cc && sudo -u www-data php symfony search:populate && systemctl restart memcached.service' & ``` ### Output (stdout) von Prozess anzeigen ``` tail -f /proc/{PID}/fd/1 ``` Die PID findet man über `ps aux` heraus, zweite Spalte. ### PID von Prozess anzeigen ``` # zeigt die laufenden Prozesse an: ls /run/ ``` ### Netzwerk/SSH/Ports siehe https://gitlab.com/delta-centauri/tbz-cloudnative/-/tree/main/SSH ## Zeiteinstellungen ### Anzeige ``` timedatectl Local time: Wed 2023-12-20 18:25:59 CET Universal time: Wed 2023-12-20 17:25:59 UTC RTC time: Wed 2023-12-20 17:25:59 Time zone: Europe/Zurich (CET, +0100) System clock synchronized: yes NTP service: inactive RTC in local TZ: no ``` Zeitangabe kurz ``` date ``` Zeitangabe kurz UTC ``` date -c ``` ### Zeit neu stellen ``` date -s 18:00 ``` ### Hardware clock (von UEFI) ``` hwclock 2023-12-20 18:29:16.963145+01:00 ``` Uhrzeit von Linux übernehmen von hardware clock: ``` hwclock -s ``` ### Zeitzone setzen ``` timedatectl set-timezone "Europe/Zurich" ``` ### Zeit von Internet benutzen ``` sudo apt install chrony systemctl start chronyd.service systemctl enable chronyd.service vi /etc/chrony.conf ``` ## Manpages Ab und zu wenn Programme gelöscht oder hinzugefügt werden müssen, muss man die ManDB wieder aktualisieren: ``` mandb ``` ### Befehl in manpages nachschlagen ``` man ls ``` ### Suche in manpages ``` man -k #oder man apropos ``` ## Tools ### TAR #### Packen ``` tar -cvzf ants.tar.gz ``` #### Entpacken ``` #.tar.gz tar -xvzf NAMEDERDATEI.tar.gz #.tar tar -xvf file_name.tar # Or to extract to another directory: tar -C /myfolder -xvf file_name.tar # only 1 or more files from archive: tar -xvf ``` ### UNZIP ``` unzip filename.zip ``` Falls Probleme auf Ubuntu mit einem ZIP, welches in Windows erstellt wurde:\ Auf Windows in CMD ausführen, um Code Page zu erhalten: `chcp`\ Bsp. `65001`\ Die Nummer dann verwenden für den Befehl: ``` unzip -O CP65001 'C-II-B2-5-02-2-4_Kita Rägeboge Weisslingen.zip' ``` ### Cron - cron reads `/etc/crontab`, which is predefined to run programs under `/etc/cron.hourly`, `/etc/cron.daily`, `/etc/cron.weekly` and `/etc/cron.monthly`. - the files in `/etc/cron.d` are also read by cron. they are mainly crontab files that start tasks somewhere, but must also specify the username. - these files must conform to the same naming convention as used by run-parts(8): they must consist solely of upper- and lower-case letters, digits, underscores, and hyphens. - In general, the system administrator should not use `/etc/cron.d/`, but use the standard system crontab `/etc/crontab`. - `/etc/crontab` and the files in `/etc/cron.d` must be owned by root, and must not be group- or other-writable. - the files under `/etc/cron.d` or the files under `/etc/cron.hourly`, `/etc/cron.daily`, `/etc/cron.weekly` and `/etc/cron.monthly` may also be symlinks, provided that both the symlink and the file it points to are owned by root. - The files under `/etc/cron.d` do not need to be executable, while the files under `/etc/cron.hourly`, `/etc/cron.daily`, `/etc/cron.weekly` and `/etc/cron.monthly` do. - cron then wakes up every minute, examining all stored crontabs, checking each command to see if it should be run in the current minute. When executing commands, any output is mailed to the owner of the crontab (or to the user named in the `MAILTO` environment variable in the crontab, if such exists). - cron need not be restarted whenever a crontab file is modified. - scripts in `/usr/local/sbin`