IT-OS-Admin-Linux

From wiki.samerhijazi.net
Revision as of 15:06, 20 October 2022 by Studying (talk | contribs) (Tools)
Jump to navigation Jump to search

Ref.

Basics

Fast shortcuts

cd                         ### Go back to home directory 
cd ~                       ### Go back to home directory
cd -                       ### Switch back to the last working directory
Ctrl+A/Ctrl+E              ### Ctrl+A to go to the beginning of the line and Ctrl+E to go to the end.
tail -f path_to_Log        ### Reading a log file in real time

Folders

/boot    >>Contains boot loader related files.
/bin     >>Contains binary executables.
/sbin    >>Contains administrator binary executables, just like /bin.
/lib     >>Contains 32bit libraries essential for binaries  in /bin and /sbin
/lib64   >>Contains 32bit libraries essential for binaries  in /bin and /sbin
-------------------------------------------------------------------------------
/dev     >>Contains device files.
/etc     >>Contains configuration files required by all programs.
/opt     >>Contains add-on applications from individual vendors.
/usr     >>Contains binaries, libraries and source for second level programs.
-------------------------------------------------------------------------------
/root    >>Home directory for the root user.
/home    >>Home directories for all users to store their personal files.
-------------------------------------------------------------------------------
/mnt     >>Temporary mount directory where sysadmins can mount filesystems.
/media   >>Temporary mount directory for removable devices.
-------------------------------------------------------------------------------
/proc    >>Contains information about system process.
/run     >>Run-time variable data
/srv     >>Contains server specific services related data.
/sys     >>Contains information about the devices connected to the computer.
/var     >>Contains files that are expected to grow.
/tmp     >>Contains temporary files created by system and users.
/usr/lib/systemd/system-shutdown/

Files

/etc/profile (~/.bash_profile or ~/.profile)   ### Configuration of environment for login shell
/etc/bashrc (~/.bashrc)                        ### Configuration of environment for non-login shell
-----------------------------------------------------------------------------------------------------
/etc/environment                               ### Configuration of environment
/etc/hosts                                     ### Configuration for hosts
/etc/fstab                                     ### Configuration of Disks
/etc/mtab                                      ### Configuration of Mount Devices
/etc/hostname                                  ### Where Hostname is saved
/etc/init.d/                                   ### Skripts that will be executed at system start up
/etc/apt/sources.list.d                        ### Ubuntu Reposotiery-Folder
/etc/apt/apt.conf                              ### Ubuntu Reposotiery-Config
/etc/yum.repos.d/                              ### Fedora Reposotiery-Folder
/etc/sysconfig/network-scripts/ifcfg-eth0      ### Network-cfg
/etc/fonts/conf.d                              ### Font-Configuration Directory for System
/etc/fonts/fonts.conf                          ### Font-Configuration System
/etc/fonts/local.conf                          ### Font-Configuration Local
-----------------------------------------------------------------------------------------------------
/usr/share/fonts/                              ### Users Fonts
/usr/share/themes/                             ### Users Themes
/usr/share/applications/                       ### Users Application Launcher
/usr/share/xsessions/                          ### Users Desktop envirument sessions
-----------------------------------------------------------------------------------------------------
~/.fonts.conf.d                                ### Font-Configuration Directory for User.
~/.fonts.conf                                  ### Font-Configuration User.
-----------------------------------------------------------------------------------------------------
~/.bash_profile                                ###
~/.bashrc                                      ### Shell-Config
~/.bash_login                                  ###
~/.themes/                                     ### Location of Themes
~/.icons/                                      ### Location of Icons

Configs

~/.config/user-dirs.dirs
~/.config/gtk-3.0/bookmarks

Top CMD

whoiam    # Current user
man       # Help
pwd       # Present working Directory
ls        # List File/Directory
cd        # Change Directory
cp        # Copy
mv        # Move
rm        # Remove
mkdir     # Create Directory
-----------------------------------------------------------------------------------------------------
cal       # Calender
date      # Current Date & Time
-----------------------------------------------------------------------------------------------------
df        # Report disk space usage
du        # Report file space usage
lsblk     # List block devices
fdisk     # manipulate disk partition table
-----------------------------------------------------------------------------------------------------
cat
less
tail
find
diff
-----------------------------------------------------------------------------------------------------
vi
nano
toch     # Create File
grep     # print lines matching a pattern
awk      # print column matching a pattern
sed      # Substitute, replace test
-----------------------------------------------------------------------------------------------------
free     # RAM allocation
lscpu    # CPU Info
top
ps
history
shutdown
reboot
-----------------------------------------------------------------------------------------------------
<command> &   # Start command in Background
exit          # exit process
kill          # kill -9 $PID;
crontab       # crontab -e; crontab -l
-----------------------------------------------------------------------------------------------------
if <command>; then <command> fi
for x in {1..10}; do <command>; done
while:; do <command>; done
until false; do <command>; done
-----------------------------------------------------------------------------------------------------
ctrl+a; ctrl+e; ctrl+d; ctrl+c; ctrl+z; ctrl+r
ctrl+alt+f1          # New tty Session
ctrl+alt+t           # New Termina

Commands

Basics

$ find ./folder -type f -name testfile.txt           # Find a file called testfile.txt in the ./folder and sub-directories
$ mv $SOURCE $TARGET                  # move folder
$ rm -rf $Folder_Name                 # remove directories force & recursively
$ ln -s $SOURCE $LINK                 # create symbolic link
$ ls -l $LINK                         # list symbolic link
$ unlink $LINK                        # unlinke symbolic link
$ toch file.txt                       # create new empty.
$ echo "Hallo World"                  # Print out 'Hallo World'
$ echo "Hallo World" > file.txt       # Overwrite the content of file.txt
$ echo "Hallo World" >> file.txt      # Append to the end of file.txt
$ source file.txt                     # Source the file.txt
$ cat file.txt                        # Print out the content of file.exe
$ cat source.txt > file.txt           # To overwrite the content of file.txt
$ cat source.txt >> file.txt          # To append to the end of file.txt
$ ls /usr/javalib/*.jar               # List all the .jar files in current directory.
$ ls /usr/javalib/**.jar              # List all the .jar files in current directory and subdirectories.
$ tar -xfv $NAME_ARCHIVE                      # x: extract, f: file, v: Verbose
$ tar -xfv -C ./$NAME_FOLDER $NAME_ARCHIVE    # x: extract, f: file, v: Verbose, C: Directory
$ tar -cf $NAME_ARCHIVE file1 file2 file3     # c: create, f: file
$ unzip $NAME_FILE

chmod & chown & chgrp

* * * * 
┬ ┬ ┬ ┬
│ │ │ │ 
│ │ │ │ 
│ │ │ └──────> Other (everyone) permissions
│ │ └────────> Group permissions
│ └──────────> User permissions
└────────────> File type
######################################################################
0 (---), 1 (--x), 2 (-w-), 3 (-wx), 4 (r--), 5 (r-x), 6 (rw-), 7 (rwx)
######################################################################
chmod 777 file.txt              ### rwx rwx rwx
chmod 755 file.txt              ### rwx r_x r_x
chmod 700 file.txt              ### User can rw-
chmod 400 file.txt              ### User can r--
# USERS >> u:Owner, g:Group, o:Others, a:Everyone:[ugo]
# OPERATION  >> +:Add, -:Remove, =:Only
# PERMISSIONS >> r:Read, w:Write, x:Execute
######################################################################
chmod $USERS $OPERATION $PERMISSIONS $FILE_NAME
chmod uga+rwx -R $FILE_NAME
chmod u=rwx,g=rwx,o=rwx $FILE_NAME
$ chown $OWNER_ID $FILE_NAME
$ chgrp $GROUP_ID $FILE_NAME

System

hostnamectl set-hostname new-name

CronJob

/etc/crontab
/etc/cron.x/
crontab -e
@reboot ~/box-sandbox/k8s/vagrant up
* * * * * auszuführender Befehl
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ └──── Wochentag (0-7, Sonntag ist 0 oder 7)
│ │ │ └────── Monat (1-12)
│ │ └──────── Tag (1-31)
│ └────────── Stunde (0-23)
└──────────── Minute (0-59)

Bootloader-GRUB

Settings files

/etc/default/grub                                 ### Is the main GRUB settings file.
/boot/grub2/grub.cfg                              ### Is automatically generated by grub2-mkconfig based on /etc/default/grub.
/boot/efi/EFI/fedora/grub.cfg                     ### Is automatically generated for EFI systems.

Mounting boot and root partitions

mkdir -p /mnt/
mount /dev/sda2 /mnt                              ### Mount the boot partition in the mount point.
mount /dev/sda1 /mnt/root/boot                    ### Mount the root partition on the mount point.
chroot /mnt/root                                  ### Change the filesystem into the mount point /mnt/root.

Installing the Bootloader

grub2-mkconfig -o /boot/grub2/grub.cfg            ### Create the GRUB2 configuration file.
grub2-mkconfig -o /boot/efi/EFI/fedora/grub.cfg   ### Create the GRUB2 configuration file.
grub2-install /dev/sda                            ### Install GRUB2 into the MBR of the primary hard disk.

CMD-HowTo

# Rename all file names from uppercase to lowercase
for i in $( ls | grep [A-Z] ); do mv -i $i `echo $i | tr 'A-Z' 'a-z'`; done
cat <<EOF
command1
command2
command3
EOF
----
cat <<EOF > output_file.txt
command1
command2
command3
EOF

Shell

-d file			# True if file is a directory.
-e file			# True if file exists.
-f file			# True if file exists and is a regular file.
-L file			# True if file is a symbolic link.
-r file			# True if file is a file readable by you.
-w file			# True if file is a file writable by you.
-x file			# True if file is a file executable by you.
file1 -nt file2		# True if file1 is newer than (according to modification time) file2
file1 -ot file2		# True if file1 is older than file2
-z string			# True if string is empty.
-n string			# True if string is not empty.
string1 = string2		# True if string1 equals string2.
string1 != string2		# True if string1 does not equal string2.

Don't leave a blank variable, unset it if it was empty
read -sr OS_PASSWORD_INPUT
export OS_PASSWORD=$OS_PASSWORD_INPUT
export OS_PROJECT_NAME="demo"
unset OS_USER_DOMAIN_NAME
timestamp=$(date +%Y%m%d%H%M%S)
nano ~/.bashrc                                   # Auto start the agent
-----------------------------------------
if [[ "$(ps -u $USER | grep ssh-agent | wc -l)" -lt "1" ]]; then
    ssh-agent -s >~/.ssh/ssh-agent
    . ~/.ssh/ssh-agent >/dev/null
    ssh-add ~/.ssh/id_rsa
else
    . ~/.ssh/ssh-agent >/dev/null
fi
-----------------------------------------

User

sudo adduser –G [GROUP-ID] [USER-ID]					# Add a new Group & User
sudo deluser [USER-ID]							# Delete User
sudo remove [USER-ID]							# Remove User
...
echo "USER-ID ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
usermod -aG sudo [USER-ID]						# Add User to Sudo-Group
sudo visudo								# Add “USER-ID ALL=(ALL:ALL) ALL”
id	
...
su [USER-ID]								# Change User in current Folder
su - [USER-ID]								# Change User in User Home-Folder
sudo bash								# Login as root
sudo -i									# Login as root
sudo -i –u [USER-ID]							# Login in account user
passwd [USER-ID]							# Change User Password
gpasswd -a user-ID group-ID						#

Locale & Keymap & Time

/etc/environment
/etc/locale.conf
~/.config/locale.conf
...
localectl
localectl list-locales
localectl set-locale LANG=en_US.UTF-8
...
localectl
localectl list-keymaps
localectl set-keymap de
...
timedatectl
timedatectl list-timezones
timedatectl set-timezone Europe/Berlin

SSH

Settings

$ sudo dnf install openssh-client
$ sudo dnf install openssh-server
$ sudo systemctl restart sshd.service
$ sudo systemctl enable sshd.service
...
ssh box-black -L 8888:localhost:32400 ## Redirect localhost to Server "box-black"
  • Key-Typs: RSA algorithm and DSA algorithm.
$ ~/.ssh/id_rsa.pvt           # The file contains the RSA private key.
$ ~/.ssh/id_rsa.pub           # The file contains the RSA public key.
$ ~/.ssh/authorized_keys      # The file contains the keys that can be used for logging into system.
...
$ chmod go-w ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys
sudo nano /etc/ssh/ssh_config
sudo nano /etc/ssh/sshd_config
------------------------------
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile %h/.ssh/authorized_keys
PasswordAuthentication no      # Yes: Can login with Password; No: Can’t login with Password
------------------------------
/etc/init.d/ssh restart

Generate Key

$ ssh-keygen -t rsa -f ~/.ssh/id_rsa -C "username@mail.com"     # Generate prv and pub Key
$ cp ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
$ chmod -R 600 ~/.ssh/id_rsa
$ ssh -i ~/.ssh/id_rsa username@server.com                      # Login server with prv-key       	
...
$ ssh-copy-id –i $PATH_PUBLIC_KEY $USERNAME@IP_ADDRESS	     # Copy Pub-Key to server
$ cat ~/.ssh/id_rsa.pub | ssh user@hostname "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
$ ssh user@hostname "echo `cat ~/.ssh/id_rsa.pub` >> ~/.ssh/authorized_keys"

ssh-agent & ssh-add

$ vim ~/.ssh/config                            # Add key automatically to a running agent
-----------------------------------
AddKeysToAgent yes
## Home nas server ##
Host nas01
     HostName 192.168.1.100
     User root
     IdentityFile ~/.ssh/nas01.key
Host github.com
     IdentityFile ~/.ssh/github.key
-----------------------------------
$ eval $(ssh-agent -s)                          # Start the agent
$ ssh-add ~/.ssh/id_rsa                         # Add the defualt key
$ ssh-add -l                                    # List keys
$ ssh-add -d /home/user/.ssh/id_rsa             # Remove key
$ ssh-add -D                                    # Remove all Keys
$ eval $(ssh-agent -s -k)                       # Kill the agent
$ ssh -T git@github.com
$ ssh -T git@bitbucket.org

Network

KVM

sudo dnf install @virtualization
sudo dnf install bridge-utils libvirt virt-install qemu-kvm
sudo systemctl status libvirtd
sudo systemctl start libvirtd
sudo systemctl enable libvirtd
sudo virt-host-validate
...
sudo curl -L https://github.com/dhiltgen/docker-machine-kvm/releases/download/v0.10.0/docker-machine-driver-kvm-centos7 -o /usr/local/bin/docker-machine-driver-kvm
sudo chmod +x /usr/local/bin/docker-machine-driver-kvm
...
sudo virsh net-list --all
sudo virsh net-info $NAME_NETWORK
sudo virsh net-dumpxml $NAME_NETWORK
sudo virsh net-destroy $NAME_NETWORK
sudo virsh net-undefine $NAME_NETWORK
...
sudo virsh net-define $NAME_FILE.xml
sudo virsh net-start $NAME_NETWORK
sudo virsh net-autostart $NAME_NETWORK
...
sudo virsh list --all
sudo virsh edit $NAME_VM
...
sudo brctl show br0

nmcli

nmcli-genreral

nmcli dev show
nmcli conn show

nmcli-ethernet


nmcli-wifi


nmcli-bridge

nmcli con add type bridge autoconnect yes con-name br0 ifname br0 ipv4.method auto
nmcli con del enp2s0
nmcli con add type bridge-slave autoconnect yes con-name enp2s0 ifname enp2s0 master br0

Tools

ping samerhijazi.net         ### resolve a hostname to an IP address
host samerhijazi.net
nslookup samerhijazi.net
speedtest                    ### ubuntu
speedtest-cli                ### fedora
arp -a
nmap -sP 192.168.1.0/24
sudo mount -t cifs -o username=user,password=pin //172.29.32.184/sharename /media/Data/
sudo mount -t davfs -o username=user,password=pin https://sd2dav.1und1.de /1und1

Firewall

Service

  • cmd: status, start, stop, restart, reload, enable, disable
$ sudo systemctl status firewalld
$ sudo systemctl status NetworkManager
$ sudo systemctl status network
...
sudo firewall-cmd --reload

Zone

sudo firewall-cmd --get-zones
sudo firewall-cmd --get-active-zones
sudo firewall-cmd --get-default-zone
sudo firewall-cmd --get-services
sudo firewall-cmd --list-all
sudo firewall-cmd --list-ports

Zone-home

sudo firewall-cmd --zone=home --list-all
sudo firewall-cmd --zone=home --list-ports
sudo firewall-cmd --zone=home --list-services

Zone: Configuration

sudo firewall-cmd --set-default-zone=home
sudo firewall-cmd --zone=home --change-interface=eth0
sudo firewall-cmd --zone=home --add-service=http
sudo firewall-cmd --zone=home --add-port=80/tcp --permanent

New Zone "boxblue"

sudo firewall-cmd --permanent --new-zone=boxblue
sudo firewall-cmd --permanent --zone=boxblue --add-service=ssh
sudo firewall-cmd --permanent --zone=boxblue --add-service=http
sudo firewall-cmd --permanent --zone=boxblue --add-service=https
sudo firewall-cmd --permanent --zone=boxblue --add-service=samba
sudo firewall-cmd --permanent --zone=boxblue --add-port=80/tcp
sudo firewall-cmd --permanent --zone=boxblue --add-port=22/tcp
sudo firewall-cmd --permanent --zone=boxblue --change-interface=wlp0s19f2u1
sudo firewall-cmd --permanent --set-default-zone=boxblue

Editors

Vim

Get used to copy/paste/cut with vim:
---
Mark lines: Esc+V (then arrow keys)
Copy marked lines: y
Cut marked lines: d
Past lines: p or P
Esc   Exit the current mode.
i     Enter "Insert mode" for inserting text.
v     Enter "Visual mode" for character.
V     Enter "Visual mode" for line.
:     Enter "Command mode". 
...
h     Move Left
j     Move Down
k     Move Up
l     Move Right
...
ggVG  Select hole text
...
u     Undo the last operation.
d     Delete or Cut selected item.
y     Copy line.
p     Paste storage buffer after the cursor.
...
:q    Quit Vim.
:q!   Quit Vim without saving the changes.
:w    Save the file
:wq   Save the file and quit Vim.
:w $FILE_NAME Save the file with the filename "yx".
Esc §§ Place the cursor on the first line you want to delete. §§ Type 5dd and hit Enter to delete the next five lines.
:[start],[end]d      ### Delete a range of lines

nano

Paste:     Strg+u
Delete:     Strg+k
Search:     Strg+w
Select_&_Copy:     Strg+6  >>>  Alt+6
Select_&_Delete:     Strg+6  >>>  Strg+k
---
ALt+# >> show Line numbers
  • nanorc
ls /usr/share/nano/
nano /usr/share/nano/yaml.nanorc

Package Manager

  • sudo dpkg -i filename.deb
  • sudo rpm -i filename.rpm

APT (Advanced Package Tool)

  • Debian, Ubuntu, usw.
  • Repo-Location: /etc/apt/sources.list
sudo apt install ./filename.deb

DNF (Dandified YUM)

sudo ls /etc/yum.repos.d/                         ## Repositories-Folder
sudo rpm –i filename.rpm
sudo dnf install https://website.com/file-name.rpm
sudo dnf config-manager --add-repo https://website.com/repositorie-name.repo
sudo dnf repolist --all
sudo dnf config-manager --add-repo $REPO_URL
sudo dnf config-manager --set-enabled $REPO_ID
sudo dnf config-manager --set-disabled $REPO_ID
---
sudo dnf copr [enable|disable|remove|list|search] $PACKAG_NAME
...
sudo dnf list
sudo dnf list installed
sudo dnf list available
sudo dnf list updates
---
sudo dnf check-update
sudo dnf autoremove
sudo dnf clean all
...
sudo dnf update
sudo dnf upgrade
sudo dnf update vim
sudo dnf search vim
sudo dnf download vim
sudo dnf install vim
sudo dnf install https://website.com/filename.rpm
sudo dnf reinstall vim
sudo dnf remove vim
sudo dnf erase vim
...
sudo dnf group list -v
sudo dnf group info 'Development Tools'
sudo dnf group install 'Development Tools'
sudo dnf group update 'Development Tools'
sudo dnf group remove 'Development Tools'

Storage

Mount 1&1

mkdir /mnt/1und1
mount -t davfs https://sd2dav.1und1.de/ /mnt/1und1
umount /mnt/1und1

Mount VirtualHardDisk

sudo dd if=/dev/zero of=/storage/vhd.img bs=1M count=24    ### VHD volume of size 20MB image.
sudo mkfs -t ext4 /storage/vhd.img                         ### Format the VHD image with EXT4 file system type.
sudo mkdir /mnt/vhd/
sudo mount -t auto -o loop /storage/vhd.img /mnt/vhd/
sudo nano /etc/fstab <<< "/storage/vhd.img  /mnt/vhd/  ext4    defaults        0  0"
sudo umount /mnt/vhd/

Encrypted disk image with Cryptsetup

sudo dd if=/dev/zero of=./vhd.img bs=1M count=24    ### Create the Disk Image File vhd.img.
sudo cryptsetup -y luksFormat ./vhd.img             ### Encrypt the Disk Image File vhd.img.
sudo cryptsetup luksOpen ./vhd.img cryvhd           ### Maps the Disk Image File vhd.img to /dev/mapper/cryvhd.
sudo mkfs.ext4 /dev/mapper/cryvhd                   ### Format the Disk Image File vhd.img with ext4 File System. 
sudo mount /dev/mapper/cryvhd /mnt/vhd
sudo chown king:king /mnt/vhd 
sudo umount /mnt/vhd
sudo cryptsetup luksClose cryvhd

Samba

$ /etc/samba/smb.conf
$ systemctl enable --now smb
$ firewall-cmd --add-service=samba --permanent
$ firewall-cmd --reload
$ testparm
----------------------------------------
[global]
workgroup = WORKGROUP
security = user
netbios name = box-black
map to guest = Bad User
idmap config * : backend = tdb
wins support = yes
local master = yes
preferred master = yes

[storage-a]
path = /storage_a
browsable = yes
writable = yes
guest ok = yes
guest only = yes
read only = no
force user = nobody
force create mode = 777
force directory mode = 777

public = yes
available = yes
----------------------------------------

Screen

screen -S <name>		# start screen new
screen -ls			# list screen runing
screen -r <name>		# reattach to a session name
..
Ctrl+a c			# create window
Ctrl+a n			# next window
Ctrl+a p			# previous window
Ctrl+a k			# kill window
Ctrl+a d			# detach window

Desktop Environments

Links

Display Server (Xorg/Wayland)

loginctl	                   # get session number from command output 
loginctl show-session 2 -p Type
...
vi /etc/gdm/custom.conf
vi /etc/gdm3/custom.conf
-----------------------
WaylandEnable=false                  # To disable Wayland
DefaultSession=gnome-xorg.desktop    # To enable Xorg
-----------------------

Sessions

ls -l /usr/share/xsessions/    # Lists installed desktop enviruments
echo $XDG_CURRENT_DESKTOP

Display Manager: lightdm

  • Install Display-Manager
  • Install Greeter
  • Setting Greeter
sudo dnf install lightdm                                                                         # Display-Manager
sudo dnf install elementary-greeter slick-greeter slick-greeter-cinnamon slick-greeter-mate      # Greeter-Typs
sudo dnf install lightdm-settings                                                                # For Settings
...
ls /usr/share/lightdm/lightdm.conf.d/        # System-Settings
ls /etc/lightdm/lightdm.conf.d/              # User-Settings
lightdm --show-config
...
[Seat:*]
greeter-session=slick-greeter
user-session=cinnamon

Fixs

sudo -e /etc/needrestart/needrestart.conf
--------------------------------------------
Uncomment and change the following settings:
$nrconf{kernelhints} = 0;
$nrconf{ucodehints} = 0;
--------------------------------------------