Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Share folder (NFS and Samba)/shaare/0MCBLg

  • linux
  • linux

NFS → Network File System

  • Share folder

NFS Server

  • dnf install nfs-utils libnfsidmap

  • systemctl enable rpcbind

  • systemctl enable nfs-server

  • systemctl start rpcbind

  • systemctl start nfs-server

  • systemctl start rpc-statd

  • systemctl start nfs-idmapd

  • mkdir /myshare

  • chmod a+rwx /myshare

  • nano /etc/exports

/myshare *(rw,sync,no_root_squash)
  • exportfs -rv → export NFS file system

NFS Client

  • dnf install nfs-utils rpcbind

  • service rpcbind start

    • Start package
  • ps -ef | egrep "firewall|iptable"

    • Disable firewall in case on server
  • showmount -e 192.168.0.100

    • Show mount from NFS server
    • 192.168.0.100 = NFS server IP
  • mkdir /mnt/app → create mount point

  • mount 192.168.0.100:/myshare /mnt/app

    • Mount NFS file system
  • df -h → verify mounted system

  • umount /mnt/app


SAMBA

  • SMB → Server Message Block

  • CIF → Common Internet File System

  • Samba protocol

  • dnf install samba samba-client samba-common

  • firewall-cmd --permanent --zone=public --add-service=samba

  • firewall-cmd --reload

    • Add rule to firewall
  • mkdir -p /samba/myshare

  • chmod a+rwx /samba/myshare

  • chown -R nobody:nobody /samba

    • Create Samba share directory
  • chcon -t samba_share_t /samba/myshare

    • Change SELinux security context
  • nano /etc/samba/smb.conf

    • Add new filesystem shared
[anonymous]
path = /samba/myshare
browsable = yes
writable = yes
guest ok = yes
guest only = yes
read only = no
  • testparm

    • Test SMB configuration
  • systemctl enable smb

  • systemctl start smb

    • Start Samba service

Mount on Linux Client

  • dnf -y install cifs-utils samba-client

  • mkdir -p /mnt/sambashare

  • mount -t cifs //192.168.0.35/anonymous /mnt/sambashare

    • Mount Samba share without password

Secure Samba Server

  • useradd larry

  • groupadd smbgrp

  • usermod -a -G smbgrp larry

  • smbpasswd -a larry

    • Set Samba password for larry
  • mkdir /samba/secureshare

  • chown -R larry:smbgrp /samba/secureshare

  • chmod -R 0770 /samba/secureshare

  • chcon -t samba_share_t /samba/secureshare


Samba Secure Share

  • nano /etc/samba/smb.conf
[secure]
path = /samba/secureshare
valid users = @smbgrp
guest ok = no
writable = yes
browsable = yes
  • systemctl restart smb
2 months ago Permalink
cluster icon
  • Alias and command history : alias l="ls -al" → define alias unalias l → remove alias Persistent Alias Config User-specific: ~/.bashrc Global: /etc/bashrc Add: alias l="ls -a...
  • Firewall : Enable firewall firewall-config → GUI for options add ports firewall-cmd → CLI cat /etc/sysconfig/iptables-config cat /etc/firewalld/firewalld.co...
  • Special Permissions (SetUID, SetGID, Sticky Bit) : chmod u+s xyz.sh → add SetUID (user-level special permission) chmod g+s xyz.sh → add SetGID (group-level special permission) chmod u-s xyz.sh → remov...
  • System information, root recovery, environment variables, shortcuts : Finding System Information cat /etc/redhat-release → Red Hat version uname -a → Linux hostname, kernel, architecture dmidecode → hardware, BIOS, syst...
  • Apache and Nginx : Apache Web Server dnf install httpd nano /etc/httpd/conf/httpd.conf nano /var/www/html/index.html systemctl restart httpd systemctl stop firewalld N...

Filesystem check and disk cloning/shaare/Utyg1Q

  • linux
  • linux

fsck & xfs_repair → filesystem check

  • fsck → ext2, ext3, ext4

  • xfs_repair → xfs only

  • Made each boot & fix it

  • df -T → check

    • Unmount before fsck

fsck error code

  • 0 → no error

  • 1 → error corrected

  • 2 → reboot needed

  • 4 → some error left uncorrected

  • 8 → operational error

  • -f → force

  • -y → repair automatically

  • fsck /dev/sdb

  • umount /bigdata

  • xfs_repair /dev/mapper/stratis...


dd → disk cloning

  • dd if=<sourcefilename> of=<targetfilename>

  • dd if=/dev/sda1 of=/root/sda1.img

    • Backup copy disk partition
  • dd if=/root/sda1.img of=/dev/sdb3

    • Restore
2 months ago Permalink
cluster icon
  • Journalctl : journalctl journalctl -u sshd show only log for sshd logger hello write in syslog journalctl -f log is live nano /etc/systemd/journald.c...
  • Kickstart – Automate Linux Install : Kickstart server Make Kickstart available on the network Make installation source available Make boot media available Start Kickstart instal...
  • User management : Essential Commands: useradd groupadd userdel groupdel usermod Modify 3 files: /etc/passwd, /etc/group, /etc/shadow (passwd info) Cre...
  • Screen & Tmux : Screen (Terminal Multiplexer) Multi-terminal sessions in one window Alt+a | → split vertical Alt+a Shift+s → split horizontal Alt+a Tab → switch wind...
  • Computer Storage / Disk Partition : Computer Storage Local → RAM / HDD / SSD DAS (Direct Attached Storage) USB HDD / DVD SAN (Storage Area Network) through iSCSI cable or fiber ...

Stratis/shaare/XNOa6Q

  • linux
  • linux

Stratis → advanced storage management

  • Extend filesystem automatically when needed

  • dnf install stratis-cli stratisd

  • dnf makecache --refresh

    • Update latest package list for DNF
  • systemctl start stratisd

  • systemctl enable stratisd

    • Start daemon
  • lsblk

    • List block device
  • stratis pool create pool1 /dev/sdb

    • Create pool with /dev/sdb
  • stratis pool list

    • Show pool list
  • stratis pool add-data pool1 /dev/sdc

    • Extend pool1 with /dev/sdc

Stratis Filesystem

  • stratis filesystem create pool1 fs1

    • Create filesystem using Stratis
  • stratis filesystem list → get UUID

    • Verify filesystem creation
  • mkdir /bigdata

  • mount /stratis/pool1/fs1 /bigdata

    • Mount Stratis disk to /bigdata
  • stratis filesystem snapshot pool1 fs1 fs-snap

    • Make a snapshot
  • nano fstab

UUID="a313..."   /bigdata   xfs   defaults,x-systemd.requires=stratis.service   0 0
  • Startup mount

RAID (Redundant Array of Independent Disks)

  • RAID0 → add physical disk to make big one
  • RAID1 → mirror (slow)
  • RAID5 → 3 or more disks
    • Read & write a little on every disk
2 months ago Permalink
cluster icon
  • Vi Editor : Vi Editor Commands i → insert mode ESC → escape to command mode r → replace mode x → delete character dd → delete line yy → copy line p → paste v → v...
  • Networking : Interface configuration files: /etc/nsswitch.conf → where resolve hostname to IP address /etc/hosts → add new IP to resolve /etc/resolv.conf → r...
  • Share folder (NFS and Samba) : NFS → Network File System Share folder NFS Server dnf install nfs-utils libnfsidmap systemctl enable rpcbind systemctl enable nfs-server ...
  • Screen & Tmux : Screen (Terminal Multiplexer) Multi-terminal sessions in one window Alt+a | → split vertical Alt+a Shift+s → split horizontal Alt+a Tab → switch wind...
  • SSH and DNS : SSH ps -ef | grep sshd → check ssh systemctl status sshd DNS PTR record → IP to hostname A record → hostname to IP CNAME record → hostname to...

Logical Volume Management (LVM)/shaare/PaqQSg

  • linux
  • linux

LVM (Logical Volume Management)

  • Combine disk together by software

  • Add new HDD on the fly to extend disk space

  • Set LVM in Linux install

  • Desired capacity: all → set last partition to space left

  • /boot → 500 MB LVM ⚠ always

  • fdisk /dev/sdc

    • n → new partition
    • t → change partition system ID
    • 8e → change to Linux LVM
  • pvcreate /dev/sdc1 → create physical volume

  • pvdisplay → infos

  • vgcreate vg /dev/sdc1 → create volume group

  • vgdisplay → show info

  • lvcreate -n lv --size 500 vg

  • lvdisplay → show info

  • mkfs.xfs /dev/vg/lv → format logical volume

Extend LVM → create LVM partition

  • pvcreate /dev/sd01
  • vgextend vg /dev/sd01
  • lvextend -L +100M /dev/mapper/vg-vg
  • xfs_growfs /dev/mapper/vg-vg

Add / Extend Swap Space

  • System will not boot if set incorrect

  • Recommended: 2x size of RAM

  • dd if=/dev/zero of=/newswap bs=1M count=1024

    • Extract disk space from HDD to swap
  • chmod go-r /newswap

    • Make file non-readable for others
  • mkswap /newswap

    • Make swap file
  • swapon /newswap

    • Activate swap (add with the rest)
  • nano fstab

/newswap swap swap defaults 0 0

xfs_info → display detailed information

  • xfs_info /dev/mapper/cs-root
    • Debug info about main XFS partition
2 months ago Permalink
cluster icon
  • SED: Stream Editor for Text Manipulation : Basic Replace Syntax: sed -i 's/KENNY/LENNY/g' filename Substitute all occurrences of "KENNY" with "LENNY" Delete Line Containing String: s...
  • Linux filesystem : Directory Description /boot Grub.cfg /root home of root /dev system device (mouse, keyboard) /etc configuration files /bin → /usr/bin e...
  • Ldap Secure Ssh : Check on listening port netstat -tunlp → check open/listening port Securing SSH config more /etc/ssh/sshd_config change port 22 PermitRootLogin ...
  • System information, root recovery, environment variables, shortcuts : Finding System Information cat /etc/redhat-release → Red Hat version uname -a → Linux hostname, kernel, architecture dmidecode → hardware, BIOS, syst...
  • Systemctl, process management : Basic System Info Commands uptime → time now, up since, numbers of users, load average hostname → ip hostname uname -a → current OS and kernel info w...

Computer Storage / Disk Partition/shaare/aqHzuQ

  • linux
  • linux

Computer Storage

  • Local → RAM / HDD / SSD

  • DAS (Direct Attached Storage)

    • USB HDD / DVD
  • SAN (Storage Area Network)

    • through iSCSI cable or fiber cable
    • PCI SAN cards / HBA cards
  • NAS (Network Attached Storage)

    • through network (TCP/IP) Samba, NFS

Disk Partition

  • df → disk info

  • fdisk → total & partition

  • fdisk -l → get info about partition

  • fdisk /etc/sdb → mount partition

    • n → new partition
    • w → write
  • mkfs.xfs /dev/sdb1

    • create file system
  • mkdir /data → create folder to mount partition

  • mount /dev/sdb1 /data

    • mount disk
  • nano /etc/fstab

    • mount new disk at startup
/dev/sdb1    /data    xfs    defaults    0    0
  • unmount /data

    • unmount disk
  • mount -a → read fstab and remount disk

2 months ago Permalink
cluster icon
  • Vi Editor : Vi Editor Commands i → insert mode ESC → escape to command mode r → replace mode x → delete character dd → delete line yy → copy line p → paste v → v...
  • Tuned : Tweaks with Tuned / Podman Tweaks with Tuned systemctl enable tuned tuned-adm active check which profile is active tuned-adm list list all prof...
  • Filesystem check and disk cloning : fsck & xfs_repair → filesystem check fsck → ext2, ext3, ext4 xfs_repair → xfs only Made each boot & fix it df -T → check Unmount before fsck ...
  • Stratis : Stratis → advanced storage management Extend filesystem automatically when needed dnf install stratis-cli stratisd dnf makecache --refresh Upda...
  • Disk usage, logging, shutdown, hostname : Disk and Memory Info df → disk partition info df -h → human-readable format du → size of file/directory free → memory info cat /proc/cpuinfo → CPU in...

Linux Boot Process / Optimizing Boot Performance/shaare/F8MFtg

  • linux
  • linux

Linux Boot Process → Older Version

  • BIOS → Basic Input / Output System

    • executes MBR
  • MBR → Master Boot Record

    • executes GRUB
  • GRUB → Grand Unified Bootloader

    • executes kernel
  • KERNEL

    • kernel executes /sbin/init
    • mount the root file system
  • INIT

    • init executes run level programs
    • initial RAM disk → contains drivers
  • RUN LEVEL

    • run level programs executed from /etc/rc.d/rc*.d/

Linux Boot Process → CentOS 7, 8, 9

  • BIOS → MBR → GRUB 2

  • /boot/grub2/grub.cfg

  • KERNEL

    • load drivers from initrd.img
    • start the first OS process (systemd)
  • SYSTEMD = system daemon

    • read /etc/systemd/system/default.target

systemd-analyze → Optimizing Boot Performance

  • Understand how long the Linux system takes to boot by:

    • kernel
    • service
    • initrd
  • initrd → initialize system hardware

  • systemd-analyze blame

    • sort by time all service

Message of the Day → Message at Login

  • nano /etc/motd

  • Customize:

    • touch /etc/profile.d/motd.sh
  • In /etc/ssh/sshd_config

    • PrintMotd no
  • systemctl restart sshd.service

2 months ago Permalink
cluster icon
  • Linux filesystem : Directory Description /boot Grub.cfg /root home of root /dev system device (mouse, keyboard) /etc configuration files /bin → /usr/bin e...
  • Systemctl, process management : Basic System Info Commands uptime → time now, up since, numbers of users, load average hostname → ip hostname uname -a → current OS and kernel info w...
  • User management : Essential Commands: useradd groupadd userdel groupdel usermod Modify 3 files: /etc/passwd, /etc/group, /etc/shadow (passwd info) Cre...
  • Crontab / at : Crontab Basics crontab -e → edit crontab crontab -l → list crontab entries crontab -r → remove crontab entries systemctl status crond → check crond s...
  • Share folder (NFS and Samba) : NFS → Network File System Share folder NFS Server dnf install nfs-utils libnfsidmap systemctl enable rpcbind systemctl enable nfs-server ...

System Run Level and Boot Process/shaare/CcSV1A

  • linux
  • linux

System Run Level

  • init 0 → shutdown
  • init 1 → single user mode → troubleshoot
  • init 6 → reboot the system
  • init 2 → multiuser without networking
  • init 3 → multiuser with networking
  • init 5 → multiuser with networking with GUI
who -r
  • To know which level

Boot Process

  • CPU -> BIOS -> CMOS
  • BIOS = Basic Input / Output System
  • CMOS = Complementary Metal-Oxide Semiconductor
  • ROM = Read Only Memory
  • POST = Power On Self Test
  • HDD → 1st sector = MBR
  • MBR = Master Boot Record
  • OS in RAM
  • App goes to CPU

Bootstrap

  • How the computer is going to power on
2 months ago Permalink
cluster icon
  • Navigating File System / Linux filetypes : ls -l → List pwd → Print working directory dr-xr-xr-x | directories -rw-r--r-- | file Linux File Types Symbol Type - Regular file d Dire...
  • Special Permissions (SetUID, SetGID, Sticky Bit) : chmod u+s xyz.sh → add SetUID (user-level special permission) chmod g+s xyz.sh → add SetGID (group-level special permission) chmod u-s xyz.sh → remov...
  • System information, root recovery, environment variables, shortcuts : Finding System Information cat /etc/redhat-release → Red Hat version uname -a → Linux hostname, kernel, architecture dmidecode → hardware, BIOS, syst...
  • Disk usage, logging, shutdown, hostname : Disk and Memory Info df → disk partition info df -h → human-readable format du → size of file/directory free → memory info cat /proc/cpuinfo → CPU in...
  • NTP and Mail : NTP / Chronyd → Time Synchronisation nano /etc/chrony.conf → edit conf systemctl start chronyd systemctl enable chronyd chronyc → interactive cmd t...

Ansible/shaare/xvI12A

  • ansible
  • ansible

  • Control node → server which runs Ansible
  • Modules → command executed on client side (found pre-made modules on Ansible website)
  • Task → multiple procedures to be completed
  • Playbook → automation file (YAML) with step-by-step execution of multiple tasks
  • Inventory → hosts file, remote clients where tasks are executed
  • Tag → reference to a specific task
  • Variable → value reused across tasks
  • Role → split playbook into smaller sub-playbooks

Install Ansible

  • dnf install epel-release
  • dnf install ansible ansible-doc
  • ansible --version
  • ansible localhost -m ping

Config Files

  • /etc/ansible
  • /etc/ansible/ansible.cfg
  • /etc/ansible/hosts → IP of remote
  • /etc/ansible/roles → sub-task

YAML File Syntax

  • Sequential → process one at a time
  • Indentation is extremely important → use spaces, no tabs
  • Empty lines have no value
  • Extension: .yml or .yaml
  • Execute YAML with absolute path if not in /etc/ansible/
  • No need to modify file permission

Example of YAML Playbook

- name: sampleplaybook
  hosts: all or localhost
  become: yes
  become_user: root

  tasks:
    - name: install apache http
      yum:
        name: httpd
        state: present

    - name: 2nd task
      service:
        name: httpd
        state: started

→ More modules at: docs.ansible.com

Ansible Playbook Basics

  • ansible-playbook --syntax-check my.yml
  • ansible-playbook --check my.yml

Run a Playbook

ansible-playbook /root/ansible/first.yml

Example Output

  • Output playbook → debug: msg="hello"

Remote Client Inventory

  • Remote client file → /etc/ansible/hosts
[appservers]
app1.example.com
app2.example.com

[webserver]
web1.example.com
web2.example.com
  • Header = group client

IP Range Example

192.168.0.[110:119]

Custom Inventory Path

ansible-playbook -i /home/user/ansible/hosts

Inventory Examples

[server]
server1 ansible-ssh-host=192.168.0.20
server2 ansible-ssh-host=192.168.0.21

[appserver]
server1

[webserver]
server2

List Inventory

ansible-inventory --list
  • Listing host file

Connect to Remote Host

  • Edit inventory:
nano /etc/ansible/hosts
[labclients]
192.168.0.57
  • ssh-keygen
  • ssh-copy-id 192.168.0.57 → automatic login
  • ansible all -m ping → check connection
  • ansible -a "uptime" all → check uptime on remote

Playbook Copy File

tasks:
  - name: copy file
    become: true
    copy:
      src: /home/sterne/file
      dest: /tmp
      owner: sterne
      group: sterne
      mode: 0644
  • become: true → available for other user

Playbook Change Permission

tasks:
  - name: file perm
    file:
      path: /home/sterne/backup.tar
      mode: a+w

Playbook Install Apache Server / Open Port

  • ansible-galaxy collection install ansible.posix

Run Shell Script

tasks:
  - name: run shell script
    shell: "/home/sterne/myscript.sh"

Set Cronjob

tasks:
  - name: "schedule cron"
    cron:
      name: comment for crontab
      minute: "0"
      hour: "10"
      day: "*"
      month: "*"
      weekday: "4"
      user: root
      job: "/home/sterne/myscript"

Create User

tasks:
  - name: create user
    user:
      name: sterne
      home: /home/sterne
      shell: /bin/bash

Change Password

tasks:
  - name: "change pass"
    user:
      name: george
      update_password: always
      password: "{{ newpassword | password_hash('sha512') }}"

Download Permission

tasks:
  - name: download tomcat
    hosts: localhost
    tasks:
      - name: create a directory
        file:
          path: /opt/tomcat
          state: directory
          mode: 0755
          owner: root
          group: root

      - name: get package from url
        url: https://...
        dest: /opt/tomcat
        mode: 0755
        group: sterne
        owner: sterne

Start at a Specific Task

ansible-playbook multiple.yml --start-at-task "task name"
  • Pick and choose a step

Ansible Ad-hoc Commands

ansible [target] -m [module] -a "[options]"

Ping Localhost

ansible localhost -m ping

Ansible Ad-hoc File / Package / Service Commands

  • ansible all -m file -a "path=/home/... state=touch"

  • ansible all -m file -a "path=/home/... state=absent"

  • Write / delete a file

  • ansible all -m copy -a "src=/... dest=/..."

  • Copy a file

  • ansible all -m dnf -a "name=telnet state=present"

  • Install package

  • ansible all -m service -a "name=httpd state=started enabled=yes"

  • Start service

  • enabled=yes → at startup

  • ansible all -m shell -a "systemctl status httpd"

  • Check status with shell

  • ansible all -m setup

  • Get information from remote client

  • Example: ansible_os_family == "Ubuntu"

  • ansible client1 -a "/sbin/reboot"

  • Run command directly


Roles → Grouping Tasks into Smaller Playbook

  • Separate long playbook in smaller parts
  • /etc/ansible/roles
  • Example groups mentioned:
    • fullinstall
    • basicinstall
- name: full install
  hosts: east-webservers
  roles:
    - fullinstall

- name: basic install
  hosts: west-webservers
  roles:
    - basicinstall

Create Roles Structure

cd /etc/ansible/roles
  • mkdir [rolenames] → make directory for each role
  • Example:
mkdir basicinstall
  • Create subdirectory tasks
  • Example:
mkdir basicinstall/tasks
  • Create yml files in tasks dir
touch basicinstall/tasks/main.yml

Ansible Galaxy

  • galaxy.ansible.com → many roles
  • ansible-galaxy role install [unclear-role-name]
  • Downloaded in [unclear path ending with /ansible/roles]

Tags

  • Reference or alias to a task
- name: start httpd
  service:
    name: httpd
    state: started
  tags: s-httpd
  • ansible-playbook myplay.yml -t s-httpd

    • Run only a certain part of playbook
  • ansible-playbook myplay.yml --list-tag

    • List all tag in a playbook
  • ansible-playbook myplay.yml --skip-tags s-httpd

    • Skip a task using a tag

Variables

  • Container that hold a defined value repetitively
  • Can be defined in inventory files as well
- name: "install some package"
  hosts: all
  vars:
    myvariable: mypackagename
  tasks:
    - name: package install
      dnf:
        name: "{{ myvariable }}"
        state: started

Variable in Hosts

[abc:vars]
myserver=192.168.0.1000

server1 ansible-host=192.168.0.57

Handlers

  • Execute at the end of the play
  • Use to start, reload, stop service
  • Tasks that only run when notified
tasks:
  - name: ensure apache is running
    service:
      name: httpd
      state: started
    notify: restart apache

handlers:
  - name: restart apache
    service:
      name: httpd
      state: restarted
  • Activate handlers at the end

Conditions

  • Playbook take action on it's own → when
tasks:
  - name: start a service
    when: A == "B"
    service:
      name: servicename
      state: started

Loops

tasks:
  - name: create users
    user:
      name: "{{ item }}"
    loop:
      - jerry
      - kramer
      - george

- name: create users
  hosts: localhost
  vars:
    users: [jerry, kramer, george]

  tasks:
    - name: create user
      user:
        name: "{{ item }}"
      with_items: "{{ users }}"

Ansible Vault → Secure YAML

  • ansible-vault create myplayinvault.yml

    • Create a YAML file in the vault
    • Launch vi editor
  • ansible-playbook myplayinvault.yml --ask-vault-pass

    • To launch encrypted YAML
  • ansible-vault view httpdvault.yml

    • Edit in vi editor
  • ansible-vault --help

    • List of options
  • ansible-vault encrypt myplay.yml


Encrypt Strings in a Playbook

  • ansible-playbook myplay.yml --ask-vault-pass
  • ansible-vault encrypt_string httpd
    • Result copied into playbook
- name: test encrypted
  hosts: localhost
  vars:
    secret: !vault |
      $ANSIBLE_VAULT...
      3u33...

  tasks:
    - name: test
      debug:
        var: secret

Ansible AWX

  • GUI to manage Ansible
  • Node.js in Docker

Ansible Tower

  • Commercial / Red Hat

  • ansible-config → show configuration

  • ansible-connection → connect to client

  • ansible-console → launch console

    • help for module
cp /tmp/myfile /home/remoteuser
  • Copy file from local to remote

  • ansible-doc → manual of plugin / module

ansible-inventory -i hosts --graph
  • See a graph of all inventory
8 months ago Permalink
cluster icon
  • No related link

Kickstart – Automate Linux Install/shaare/MZrKcg

  • linux
  • linux

  1. Kickstart server

  2. Make Kickstart available on the network

  3. Make installation source available

  4. Make boot media available

  5. Start Kickstart installation

    cd /root
    anaconda-ks.cfg   # create for 1st install in root folder
  6. Steps:

    • cp /root/anaconda-ks.cfg /var/www/html/
    • chmod a+r /var/www/html/anaconda-ks.cfg
    • systemctl stop|disable firewalld
    • Create new VM with CentOS DVD ISO

      • Start VM → set boot to DVD
      • Change network adapter to bridged adapter
    • Boot: linux ks=https://192.168.1.x/anaconda-ks.cfg
    • Start automated installation

Example network config:

ksdevice=eth0 ip=192.168.0.50 \
netmask=255.255.255.0 \
gateway=192.168.0.1
8 months ago Permalink
cluster icon
  • Apache and Nginx : Apache Web Server dnf install httpd nano /etc/httpd/conf/httpd.conf nano /var/www/html/index.html systemctl restart httpd systemctl stop firewalld N...
  • Linux Boot Process / Optimizing Boot Performance : Linux Boot Process → Older Version BIOS → Basic Input / Output System executes MBR MBR → Master Boot Record executes GRUB GRUB → Grand U...
  • Special Permissions (SetUID, SetGID, Sticky Bit) : chmod u+s xyz.sh → add SetUID (user-level special permission) chmod g+s xyz.sh → add SetGID (group-level special permission) chmod u-s xyz.sh → remov...
  • System Run Level and Boot Process : System Run Level init 0 → shutdown init 1 → single user mode → troubleshoot init 6 → reboot the system init 2 → multiuser without networking init 3 →...
  • Firewall : Enable firewall firewall-config → GUI for options add ports firewall-cmd → CLI cat /etc/sysconfig/iptables-config cat /etc/firewalld/firewalld.co...

Podman and Docker/shaare/rR19ZA

  • linux
  • linux

Containers → Podman

  • Podman → manage pods and container images
  • Buildah → building/pushing/signing container images
  • Skopeo → copy/inspect/delete/signing
  • Runc → run & build feature to Podman and Buildah
  • Crun → optional runtime for rootless containers

Podman Terms

  • Images → containers can be created through images

    • converted to images
  • Pods → group of containers deployed on the host

Commands

  • dnf install podman
  • alias docker=podman

    • create alias to use Podman instead of Docker
  • podman info → check Podman registry
  • podman search httpd

    • search specific repository
    • check stars for the best

Podman & Docker Commands

  • podman images → check previously installed images
  • podman pull docker.io/library/httpd → download and install image
  • podman ps → list running containers
  • podman run -dt -p 8080:80/tcp docker.io/library/httpd → run a downloaded podman container
  • podman logs -l → check the logs
  • podman stop <container_name|id> → stop container
  • To run multiple containers, change port: 8081 and 8082
  • podman stop/start <container_name|id> → stop/start container
  • podman create --name httpd2 docker.io/library/httpd → create new container from downloaded image

Podman Container at Startup

  • Generate a unit file:

    podman generate systemd --new --files --name httpd
    cp container-httpd.service /etc/systemd/system/
    systemctl enable container-httpd.service
    systemctl start container-httpd.service

Docker

  • Install from: docs.docker.com
  • systemctl start docker
  • systemctl enable docker
  • docker run hello-world → test if Docker is working
8 months ago Permalink
cluster icon
  • File Display Commands / Filters / Text Processing Input : File Display Commands cat → Show entire content cat -A → Show non-printable characters more → Paginate output less → Same as more but allows navigatio...
  • Tuned : Tweaks with Tuned / Podman Tweaks with Tuned systemctl enable tuned tuned-adm active check which profile is active tuned-adm list list all prof...
  • Firewall : Enable firewall firewall-config → GUI for options add ports firewall-cmd → CLI cat /etc/sysconfig/iptables-config cat /etc/firewalld/firewalld.co...
  • Package Management : System Updates & Software Install dnf (yum) → RedHat → /etc/yum.repos.d apt-get → Debian rpm → RedHat package management standalone package to ...
  • SSH and DNS : SSH ps -ef | grep sshd → check ssh systemctl status sshd DNS PTR record → IP to hostname A record → hostname to IP CNAME record → hostname to...

Tuned/shaare/WlD1bQ

  • linux
  • linux

Tweaks with Tuned / Podman

Tweaks with Tuned

  • systemctl enable tuned
  • tuned-adm active

    • check which profile is active
  • tuned-adm list

    • list all profiles
  • tuned-adm profile profile-name

    • change profile
  • tuned-adm recommend

    • recommendation
  • tuned-adm off

    • turned off setting daemon
  • Web admin → https://myip:9090

Tweaks with Nice and Renice

  • top

    • PR priority level
    • NI nice user setting
  • ps axo pid,comm,nice,cls --sort=nice

    • check nice with ps
  • nice -n # processname (# -20 → +20)

    • set priority
  • renice -n # pid

    • change process priority
8 months ago Permalink
cluster icon
  • Bash : First Line of Script #!/bin/bash → defines the shell interpreter Comments Use # for commenting Common Elements Commands: echo, cp, etc. Statement...
  • Podman and Docker : Containers → Podman Podman → manage pods and container images Buildah → building/pushing/signing container images Skopeo → copy/inspect/delete/signin...
  • Alias and command history : alias l="ls -al" → define alias unalias l → remove alias Persistent Alias Config User-specific: ~/.bashrc Global: /etc/bashrc Add: alias l="ls -a...
  • Apache and Nginx : Apache Web Server dnf install httpd nano /etc/httpd/conf/httpd.conf nano /var/www/html/index.html systemctl restart httpd systemctl stop firewalld N...
  • Firewall : Enable firewall firewall-config → GUI for options add ports firewall-cmd → CLI cat /etc/sysconfig/iptables-config cat /etc/firewalld/firewalld.co...

Firewall/shaare/hJTVjQ

  • linux
  • linux

Enable firewall

  • firewall-config → GUI for options

    • add ports
  • firewall-cmd → CLI
  • cat /etc/sysconfig/iptables-config
  • cat /etc/firewalld/firewalld.conf

Firewall config

  • iptables = old, firewalld = new (use in all Linux distros)
  • Check iptables rules → iptables -L
  • Flush rules → iptables -F

Iptables packet filtering

  • Tables (process packets) → filter

    • attached to chains (inspect traffic)

    • INPUT → incoming traffic

    • FORWARD → going to router from another device

    • OUTPUT → outgoing traffic

  • Target (what happens when a rule is met)

    • ACCEPT
    • REJECT → send reject response
    • DROP → drop without response

Firewalld

  • firewall-cmd --list-all

    • check the rule
  • firewall-cmd --get-services

    • list service firewall is aware of
  • firewall-cmd --reload

    • reload for new rules
  • firewall-cmd --get-zones

    • get a list of all zones
    • public zone is used most of the time
  • firewall-cmd --get-actives-zones

    • get active zones
  • firewall-cmd --zone=public --list-all

    • get firewall rule for public zone

Add extra service:

  • cp /usr/lib/firewalld/services/allservices.xml

    • change service and port number
  • sap.xml → firewall-cmd --add-service=sap

  • firewall-cmd --add-service=http

    • add a service (http)
    • --permanent
  • firewall-cmd --remove-service=http

    • remove a service (http)
    • --permanent
  • firewall-cmd --reload

    • reload configuration
  • firewall-cmd --add-port=1110/tcp

    • add a port
    • --permanent
  • firewall-cmd --remove-port=1110/tcp

    • remove a port
    • --permanent
  • firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.8.1" drop'

    • block certain IP address
  • firewall-cmd --add-icmp-block=ipv6-redirect

    • block ping
  • firewall-cmd --direct --add-rule ipv4 filter OUTPUT 0 -d 8.9.10.11 -j DROP

    • block website (host → www.website.com)
8 months ago Permalink
cluster icon
  • Filesystem check and disk cloning : fsck & xfs_repair → filesystem check fsck → ext2, ext3, ext4 xfs_repair → xfs only Made each boot & fix it df -T → check Unmount before fsck ...
  • User management : Essential Commands: useradd groupadd userdel groupdel usermod Modify 3 files: /etc/passwd, /etc/group, /etc/shadow (passwd info) Cre...
  • Ftp Scp Rsync : FTP Install FTP server yum install vsftp nano /etc/vsftpd/vsftpd.conf anonymous_enable=NO Uncomment: ascii_upload_enable ascii_download_enabl...
  • Kickstart – Automate Linux Install : Kickstart server Make Kickstart available on the network Make installation source available Make boot media available Start Kickstart instal...
  • Basic File Commands / File Search Commands : touch one two three → Create 3 files mkdir folder → Make directory mv -R / cp -R → Move or copy folder including subfolders find . -name "geor...

Ldap Secure Ssh/shaare/GVrFhw

  • linux
  • linux

Check on listening port

  • netstat -tunlp → check open/listening port

Securing SSH config

  • more /etc/ssh/sshd_config

    • change port 22
    • PermitRootLogin no

Enable SELinux (SE → Security Enhanced)

  • sestatus → check if active
  • cat /etc/sysconfig/selinux
  • stat myfile → extra context/access
  • chcon myfile → change context

OpenLDAP → to manage users from another server

  • dnf install openldap* → install everything
  • systemctl start slapd
  • systemctl enable slapd
  • ps -ef | grep slapd → check if running
  • cat /etc/openldap/slapd.d/ldap.conf
  • cat /etc/nsswitch.conf

    • replace passwd: files sss → ldap

Traceroute → trace network traffic

  • traceroute www.mywebsite.com

Secure SSH

Set idle timeout

  • nano /etc/ssh/sshd_config

    • ClientAliveInterval 600
    • ClientAliveCountMax 0

Disable root login

  • PermitRootLogin no
  • PermitEmptyPassword no
  • AllowUsers user1 user2
  • Port change: 22 → 22224 (not usable port)

Access remote server with SSH keys

  • For automation through script
  • ssh-keygen

    • leave default folder
    • no passphrase
    • key created
  • ssh-copy-id root@192.168.0.53

    • give password of 192.168.0.53
  • ssh root@192.168.0.53

    • no password needed!
8 months ago Permalink
cluster icon
  • Journalctl : journalctl journalctl -u sshd show only log for sshd logger hello write in syslog journalctl -f log is live nano /etc/systemd/journald.c...
  • Linux Boot Process / Optimizing Boot Performance : Linux Boot Process → Older Version BIOS → Basic Input / Output System executes MBR MBR → Master Boot Record executes GRUB GRUB → Grand U...
  • Linux filesystem : Directory Description /boot Grub.cfg /root home of root /dev system device (mouse, keyboard) /etc configuration files /bin → /usr/bin e...
  • Package Management : System Updates & Software Install dnf (yum) → RedHat → /etc/yum.repos.d apt-get → Debian rpm → RedHat package management standalone package to ...
  • Firewall : Enable firewall firewall-config → GUI for options add ports firewall-cmd → CLI cat /etc/sysconfig/iptables-config cat /etc/firewalld/firewalld.co...

Apache and Nginx/shaare/kgztrA

  • linux
  • linux

Apache Web Server

  • dnf install httpd
  • nano /etc/httpd/conf/httpd.conf
  • nano /var/www/html/index.html
  • systemctl restart httpd
  • systemctl stop firewalld

NGINX

→ Web proxy → MTM between client backend servers
→ Web server

  • dnf install nginx -y
  • systemctl start nginx
  • systemctl enable nginx
  • lsof -i :80 → check port 80
  • systemctl stop firewalld
  • systemctl disable firewalld
  • nano /etc/nginx/nginx.conf

    • server { ... }
  • nano /etc/nginx/conf.d/myconf.conf

    • server { ... }
  • mkdir -p /var/www/mywebserver/html
  • nano index.html
  • nginx -t → check is everything ok
  • systemctl restart nginx

NGINX Reverse Proxy

On server → setup nginx as before

  • 403 error → sestatus (selinux status tool)

    • current mode → enforcing
    • fix: chcon -R -t httpd_sys_content_t /var/html/ → fix permission

On client

  • nano /etc/nginx/conf.d/myconf.conf

    server {
    location / {
      proxy_pass http://192.168.0.202; # server ip
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
    }
8 months ago Permalink
cluster icon
  • Crontab / at : Crontab Basics crontab -e → edit crontab crontab -l → list crontab entries crontab -r → remove crontab entries systemctl status crond → check crond s...
  • Linux File Links and Permissions : Links Soft Link (Symbolic Link) ln -s Link will be removed if the original file is removed or renamed. Hard Link ln Deleting, renaming, or moving t...
  • System information, root recovery, environment variables, shortcuts : Finding System Information cat /etc/redhat-release → Red Hat version uname -a → Linux hostname, kernel, architecture dmidecode → hardware, BIOS, syst...
  • Computer Storage / Disk Partition : Computer Storage Local → RAM / HDD / SSD DAS (Direct Attached Storage) USB HDD / DVD SAN (Storage Area Network) through iSCSI cable or fiber ...
  • SSH and DNS : SSH ps -ef | grep sshd → check ssh systemctl status sshd DNS PTR record → IP to hostname A record → hostname to IP CNAME record → hostname to...

NTP and Mail/shaare/w70vdA

  • linux
  • linux

NTP / Chronyd → Time Synchronisation

  • nano /etc/chrony.conf → edit conf
  • systemctl start chronyd
  • systemctl enable chronyd
  • chronyc → interactive cmd

timedatectl → Change date/time

  • timedatectl → check status
  • timedatectl set-timezone Europe/Berlin
  • timedatectl set-time YYYY-MM-DD
  • timedatectl set-ntp true → set synchronisation

Mail Server → Postfix & s-nail

  • /etc/postfix/main.cf → configuration

  • systemctl restart postfix

  • dnf install postfix → handle email server

  • dnf install s-nail → write & send email

  • nano /etc/postfix/main.cf

  • mail -s "Mail setup" name@domain.com

    • return
    • body… → Ctrl+D
8 months ago Permalink
cluster icon
  • Linux Boot Process / Optimizing Boot Performance : Linux Boot Process → Older Version BIOS → Basic Input / Output System executes MBR MBR → Master Boot Record executes GRUB GRUB → Grand U...
  • Bash : First Line of Script #!/bin/bash → defines the shell interpreter Comments Use # for commenting Common Elements Commands: echo, cp, etc. Statement...
  • Basic File Commands / File Search Commands : touch one two three → Create 3 files mkdir folder → Make directory mv -R / cp -R → Move or copy folder including subfolders find . -name "geor...
  • Ldap Secure Ssh : Check on listening port netstat -tunlp → check open/listening port Securing SSH config more /etc/ssh/sshd_config change port 22 PermitRootLogin ...
  • Package Management : System Updates & Software Install dnf (yum) → RedHat → /etc/yum.repos.d apt-get → Debian rpm → RedHat package management standalone package to ...

SSH and DNS/shaare/EvGJOA

  • linux
  • linux

SSH

  • ps -ef | grep sshd → check ssh
  • systemctl status sshd

DNS

  • PTR record → IP to hostname

  • A record → hostname to IP

  • CNAME record → hostname to hostname

  • /etc/named.conf → conf of DNS

  • /var/named/ → file for DNS record

  • systemctl restart named

  • touch forward.lab reverse.lab

  • dig client a in a 192.168.0.240

  • systemctl start named

  • systemctl enable named

Configuring permission

  • chgrp named -R /var/named
  • chown -v root:named /etc/named.conf
  • restorecon -rv /var/named
  • restorecon /etc/named.conf

Test DNS conf

  • named-checkconf /etc/named.conf
  • named-checkzone lab.local /var/named/forward.lab
  • named-checkzone reverse.lab /var/named/reverse.lab

Add DNS info in network file

  • nano /etc/sysconfig/network-scripts/ifcfg-enp0s3

  • DNS=192.168.0.201

  • systemctl restart NetworkManager

  • nano /etc/resolv.conf

  • nameserver 192.168.0.201

Test DNS server

  • dig masterdns.lab.local
  • nslookup masterdns.lab.local

Website lookup

  • nslookup mywebsite.com

    • get IP of a website
  • dig mywebsite.com

    • more info about website
8 months ago Permalink
cluster icon
  • Podman and Docker : Containers → Podman Podman → manage pods and container images Buildah → building/pushing/signing container images Skopeo → copy/inspect/delete/signin...
  • Computer Storage / Disk Partition : Computer Storage Local → RAM / HDD / SSD DAS (Direct Attached Storage) USB HDD / DVD SAN (Storage Area Network) through iSCSI cable or fiber ...
  • Vi Editor : Vi Editor Commands i → insert mode ESC → escape to command mode r → replace mode x → delete character dd → delete line yy → copy line p → paste v → v...
  • Alias and command history : alias l="ls -al" → define alias unalias l → remove alias Persistent Alias Config User-specific: ~/.bashrc Global: /etc/bashrc Add: alias l="ls -a...
  • Systemctl, process management : Basic System Info Commands uptime → time now, up since, numbers of users, load average hostname → ip hostname uname -a → current OS and kernel info w...

Package Management/shaare/Ceve1g

  • linux
  • linux

System Updates & Software Install

  • dnf (yum) → RedHat → /etc/yum.repos.d

  • apt-get → Debian

  • rpm → RedHat package management

    • standalone package to install locally
    • hard to install extra dependency
  • dnf install mypackage

  • rpm -qa | grep mypackage

    • check if package installed
  • rpm -ihv /tmp/package.rpm

    • install
  • rpm -e packagename

    • remove
  • dnf remove package

  • dnf update -y

    • update everything (preserves old one)
  • dnf upgrade

    • delete and replace with new

Advanced Package Management

  • rpm -qa | grep mypackage

    • mypackage-1.0.6
  • rpm -qc mypackage-1.0.6

    • configuration files
  • which mypackage

    • /usr/bin/mypackage
  • rpm -qf /usr/bin/mypackage

    • mypackage-1.0.6

Rollback Update & Patch

  • dnf history undo mypackageid
  • dnf update → keep the old package
  • dnf history → get id
8 months ago Permalink
cluster icon
  • Ftp Scp Rsync : FTP Install FTP server yum install vsftp nano /etc/vsftpd/vsftpd.conf anonymous_enable=NO Uncomment: ascii_upload_enable ascii_download_enabl...
  • Process monitoring : ps Command ps → Current shell process status ps -e → All running processes ps aux → All in BSD style with details ps -ef → Running process with detai...
  • Crontab / at : Crontab Basics crontab -e → edit crontab crontab -l → list crontab entries crontab -r → remove crontab entries systemctl status crond → check crond s...
  • SED: Stream Editor for Text Manipulation : Basic Replace Syntax: sed -i 's/KENNY/LENNY/g' filename Substitute all occurrences of "KENNY" with "LENNY" Delete Line Containing String: s...
  • User management : Essential Commands: useradd groupadd userdel groupdel usermod Modify 3 files: /etc/passwd, /etc/group, /etc/shadow (passwd info) Cre...

Ftp Scp Rsync/shaare/-gG-HQ

  • linux
  • linux

FTP

Install FTP server

  • yum install vsftp

  • nano /etc/vsftpd/vsftpd.conf

    • anonymous_enable=NO
  • Uncomment:

    • ascii_upload_enable
    • ascii_download_enable
    • ftpd_banner
  • Add: use_localtime=YES ⚠ bug

  • systemctl start vsftpd

  • systemctl enable vsftpd

  • systemctl stop firewalld

  • systemctl disable firewalld

FTP client

  • ftp 192.168.0.201

    • bi → switch to binary mode
    • hash → hash mark printing
    • put myfile → upload file
    • bye → quit

SCP → FTP secure

  • Secure copy protocol
  • scp myfile username@192.168.0.1:/home/user

    • password
    • done!

RSYNC → Remote synchronization

  • Compare & combine

Rsync local machine (file)

tar cvf backup.tar
mkdir /tmp/backups
rsync -zvh backup.tar /tmp/backups

Rsync local dir

rsync -azvh /home/user /tmp/backup

Rsync to a local machine (file)

mkdir /tmp/backups   # on remote
rsync -avz backup.tar user@192.168.0.100:/tmp/backups

Rsync from a local machine

touch serverfile
rsync -avzh user@192.168.0.100:/home/user/serverfile /tmp/
8 months ago Permalink
cluster icon
  • Tuned : Tweaks with Tuned / Podman Tweaks with Tuned systemctl enable tuned tuned-adm active check which profile is active tuned-adm list list all prof...
  • Ldap Secure Ssh : Check on listening port netstat -tunlp → check open/listening port Securing SSH config more /etc/ssh/sshd_config change port 22 PermitRootLogin ...
  • Journalctl : journalctl journalctl -u sshd show only log for sshd logger hello write in syslog journalctl -f log is live nano /etc/systemd/journald.c...
  • System Run Level and Boot Process : System Run Level init 0 → shutdown init 1 → single user mode → troubleshoot init 6 → reboot the system init 2 → multiuser without networking init 3 →...
  • SSH and DNS : SSH ps -ef | grep sshd → check ssh systemctl status sshd DNS PTR record → IP to hostname A record → hostname to IP CNAME record → hostname to...

Networking/shaare/F6ZbJQ

  • linux
  • linux

Interface configuration files:

  • /etc/nsswitch.conf → where resolve hostname to IP address

  • /etc/hosts → add new IP to resolve

  • /etc/resolv.conf → resolve hostname

  • netstat → what’s happening on the network

  • tcpdump -i networkinterface (wifi, wlp2s0)

    • network sniffing

NIC → network interface card

  • lo → loopback (local machine)
  • virbr0 → virtual bridge

ETHTOOL ENP0S3

  • Speed? / Duplex?
  • Link detected:

    • YES → network is working
    • NO → not working

NIC BONDING

  • Combine 2 NIC (ethernet port)

    • For redundancy
    • High availability
    • Link aggregation → 1G + 1G = 2G
  • modprobe bonding

  1. Create a bond interface file:

    • nano /etc/sysconfig/network-scripts/ifcfg-bond0
  2. Create first NIC file → ifcfg-enp0s3

    • Add MAC, IP, etc.
  3. Create second NIC file → ifcfg-enp0s8
  4. systemctl restart network

cat /proc/net/bonding/bond0 → show bond interface settings


Network utilities

  • nmcli → network manager command line interface
  • nmtui → network manager text user interface
  • nm-connection-editor → GUI for most of the network manager
  • nmtui → team (to create bond)

  • nmcli device → listing of interface

  • nmcli connection modify enp0s3 ipv4.addresses 192.168.0.180/24

  • nmcli connection modify enp0s3 ipv4.gateway 192.168.0.1

  • nmcli connection modify enp0s3 ipv4.method manual
    NMCLI

  • nmcli connection down enp0s3

  • nmcli connection up enp0s3

  • ip address show enp0s3


Download File

  • wget http://mydomain.com/soft.deb

Find Out Page (Website) is Up

  • curl http://website.com/
  • curl -O http://web.com/file → download a file
  • ping → get IP response
  • nslookup → info sur le site

SS

  • Check how device talk to the internet

    • Identify problem

Socket

  • Enable data transmission

    • TCP, UDP, UNIX

TCP (Transmission Control Protocol)

  • Rule: data is sent successfully (HTTP, FTP, SMTP)

UDP (User Datagram Protocol)

  • Sending data without checking if it arrives correctly
  • Video streaming

UNIX

  • Way for programs to talk to each other
  • Use a special file for message exchange
  • Database / webservers / local system

SS Options

  • ss -t → show TCP connection
  • ss -u → show UDP connection
  • ss -x → show UNIX connection
  • ss -l → listening sockets
  • ss -n → display addresses in numerical form
8 months ago Permalink
cluster icon
  • Disk usage, logging, shutdown, hostname : Disk and Memory Info df → disk partition info df -h → human-readable format du → size of file/directory free → memory info cat /proc/cpuinfo → CPU in...
  • Bash : First Line of Script #!/bin/bash → defines the shell interpreter Comments Use # for commenting Common Elements Commands: echo, cp, etc. Statement...
  • Apache and Nginx : Apache Web Server dnf install httpd nano /etc/httpd/conf/httpd.conf nano /var/www/html/index.html systemctl restart httpd systemctl stop firewalld N...
  • Tuned : Tweaks with Tuned / Podman Tweaks with Tuned systemctl enable tuned tuned-adm active check which profile is active tuned-adm list list all prof...
  • Special Permissions (SetUID, SetGID, Sticky Bit) : chmod u+s xyz.sh → add SetUID (user-level special permission) chmod g+s xyz.sh → add SetGID (group-level special permission) chmod u-s xyz.sh → remov...

Bash/shaare/OiRvBg

  • linux
  • linux

First Line of Script

  • #!/bin/bash → defines the shell interpreter

Comments

  • Use # for commenting

Common Elements

  • Commands: echo, cp, etc.
  • Statements: if, while, for
  • +x → make the script executable
  • Use absolute path to run: /home/userdir/myscript.bash

Variable Definition

a=hello
b=mytext
  • Usage:
echo "text1 $a"
echo "text2 $b"
  • Example:
a=$(hostname)
echo $a  # => myfirstlinux

Input / Output Variable

read myinputvariable
echo "name $myinputvariable"

If Else Statement

if [[ $count -eq 100 ]]; then
  echo "count is 100"
else
  echo "no"
fi

File Existence Check

if [[ -e /file.txt ]]; then
  echo "file exists"
fi

Check If a Variable Matches a Value

a=$(date | awk '{print $1}')
if [[ "$a" == "Mon" ]]; then
  echo "Today is $a"
else
  echo "Today is not Monday"
fi

Check Multiple Values

if [[ "$a" == "Monday" ]] || [[ "$a" == "Tuesday" ]]; then
  echo "It's early week"
fi

File Operation Tests

  • -s → file exists and is not empty
  • -f → file exists and is a regular file
  • -d → directory exists
  • -x → file is executable
  • -w → file is writable
  • -r → file is readable

Comparison Operators

  • -eq → equal (numeric)
  • = → equal (string)
  • -ne → not equal (numeric)
  • != → not equal (string)
  • -lt → less than
  • -le → less than or equal
  • -gt → greater than
  • -ge → greater than or equal
  • $((...)) → arithmetic evaluation

For Loop Examples

for i in 1 2 3 4 5; do
  echo "Welcome $i times"
done

for i in eat run jump play; do
  echo "User $i"
done

for i in {1..5}; do
  touch $i
  echo "File $i created"
done

Indexed For Loop Example

i=1
for day in Mon Tue Wed Thu Fri; do
  echo "Weekday $((i++)) : $day"
done

User Listing with For + AWK

i=1
for username in $(awk -F: '{print $1}' /etc/passwd); do
  echo "Username $((i++)) : $username"
done

While Loop

c=1
while [[ $c -le 5 ]]; do
  echo "Welcome $c times"
  ((c++))
done

Case Statement

echo "Choose function"
echo "A"
echo "B"
read choices  # could also use: read -s password for silent input

case $choices in
  A) date;;
  B) ls;;
  *) echo "Invalid choice";;
esac

Ping Check with Conditional

hosts="192.168.0.1"
ping -c1 $hosts &> /dev/null

if [[ $? -eq 0 ]]; then
  echo "$hosts OK"
else
  echo "$hosts NOT OK"
fi
8 months ago Permalink
cluster icon
  • NTP and Mail : NTP / Chronyd → Time Synchronisation nano /etc/chrony.conf → edit conf systemctl start chronyd systemctl enable chronyd chronyc → interactive cmd t...
  • Systemctl, process management : Basic System Info Commands uptime → time now, up since, numbers of users, load average hostname → ip hostname uname -a → current OS and kernel info w...
  • Linux File Links and Permissions : Links Soft Link (Symbolic Link) ln -s Link will be removed if the original file is removed or renamed. Hard Link ln Deleting, renaming, or moving t...
  • Ftp Scp Rsync : FTP Install FTP server yum install vsftp nano /etc/vsftpd/vsftpd.conf anonymous_enable=NO Uncomment: ascii_upload_enable ascii_download_enabl...
  • File Display Commands / Filters / Text Processing Input : File Display Commands cat → Show entire content cat -A → Show non-printable characters more → Paginate output less → Same as more but allows navigatio...


(97)
4 / 5
Links per page
  • 20
  • 50
  • 100
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community