DEV Community

Cover image for Useful: RHEL / Ubuntu Command
Yassine Sellami
Yassine Sellami

Posted on • Edited on

Useful: RHEL / Ubuntu Command

== [ All Distributions ] ==

-- Find Linux Standard Base (LSB) information
lsb_release -a

-- Check if virtualization is supported on Linux,The output must be not empty:
grep -E --color 'vmx|svm' /proc/cpuinfo

--# Archive management
zip -r -T files folder
unzip files.zip
unzip files.zip -d /path/to/extract/ 

--# env variables
export HTTP_PROXY=http://proxy_ip_name:port
vi ~/.bashrc =then> add export line =then run> source ~/.bachrc
unset HTTP_PROXY
Enter fullscreen mode Exit fullscreen mode
  • Content Managment
touch test-{1..50}.bak // create 50 empty file
ls -t *.bak | tail | xargs rm   // delete oldest backup


---# Find 

find / -iname "*foo*txt" 2>/dev/null  # Find by approximate name
find ~/Documents -ls   # Find everything
find ~ -type f         # Find by type f:file,d:dir
find ~/opt/ -maxdepth 1 -type d  # Limit listing
find ~ -type f -empty  # Find empty files
# Find by content
find ~/Documents/ -name "*log" -exec grep -Hi text-to-search {} \;
# Find files by age
- finds log files that haven't been modified in a month or more:
find /var/log -iname "*~" -o -iname "*log*" -mtime +30
- find log files modified within the past week:
find /var/log -iname "*~" -o -iname "*log*" -mtime -7
find /var/log -iname "*~" -o -iname "*log*" -mtime -7 -ls
# Search a path
find / -type d -name 'img' -ipath "*public_html/example.com*" 2>/dev/null

---# Find & delete 
find . -name ".DS_Store" -type f -delete

---# Grep 
grep -R 'import' --include='*.java' --color MySourceCodeDir


---# SED
sed -i 's#ORIGINAL_VALLUE#NEW_VALUE#g' myfile1 myfile2

Enter fullscreen mode Exit fullscreen mode

== [ Redhat ] ==

  • Sys information
---# Redhat sys information
cat /etc/redhat-release


---# Memory
top -o %MEM -c  # Mem by runing commands, press [e] switch memory unit, [?] details
watch -n 5 -d '/bin/free -m' # repeats cmd every 5s

# htop
yum install htop
htop

---# CPU
ps -aux  # proccess with PID

---# Disk
# Display disk partition sizes
lsblk --json | jq -c '.blockdevices[]|[.name,.size]'
# Display the size of an installed RPM
rpm --queryformat='%12{SIZE} %{NAME}\n' \
   -q java-11-openjdk-headless

---# yum
yum install yum-security
// search
yum search <package>
yum info <package>
yum -v list <package> --show-duplicates
// update
yum update
yum -y update --security //apply all security update
yum -y update-minimal --security
yum update --cve <CVE>
yum updateinfo list
yum updateinfo list cves

// clean
yum clean all
yum clean metadata
// yum repo
ls /etc/yum.repos.d/

---# Configuring Booleans
setsebool <boolean_name> on|off
getsebool httpd_can_network_connect        // Get
setsebool -P httpd_can_network_connect on  // -P: changes persistent across reboots 
setsebool -P mysql_connect_any on

---# Date & Time
timedatectl  // Displaying Current Date & Time

// change system time 
timedatectl set-time 20:52:40
timedatectl set-time "2017-06-02 23:26:00"
// time zones
timedatectl list-timezones // listing all time zone
timedatectl set-timezone "Europe/Berlin"
// Sync clock with a Remote Server
timedatectl set-ntp yes  // NTP service must be installed
systemctl restart systemd-timedated.service  // restart

---# chronyd
yum install chrony
systemctl start|status|... chronyd
vi /etc/chrony.conf  // config file
chronyc tracking     // check chrony tracking,
chronyc sources -v   // info about current time sources
chronyc sourcestats  // info about drift rate and offset estimation process for each of the sources currently being examined by chronyd.
check firewall: //123 = NTP Port
firewall-cmd --permanent --zone=public --add-port=123/udp
Enter fullscreen mode Exit fullscreen mode
  • Alias
alias   // listing
alias search=grep  // create new alias
// Creating Permanent Aliases
vi ~/.bashrc && source ~/.bashrc
unalias alias_name // remove alias
Enter fullscreen mode Exit fullscreen mode
  • Journal & Audit
--# Journal CTL 
journalctl -f   #Follow like tail -f
journalctl -k   #View kernel messages from current boot
journalctl -u jenkins.service -f
journalctl _PID=[numPid]
journalctl -p [err|info..]
journalctl --since "2022-10-10 16:00:00"
journalctl --since "2022-10-10 16:00:00" --until "2022-10-10 20:00:00"

journalctl --no-pager --since today \
      --grep 'fail|error|fatal' --output json|jq '._EXE' | \
      sort | uniq -c | sort --numeric --reverse --key 1


-- config
vi /etc/systemd/journald.conf

--# RHEL Audit 
yum install audit
service auditd start
-- config
vi /etc/audit/auditd.conf
-- reporting
aureport --start 04/04/2022 00:00:00 --end 04/06/2022 00:00:00

Enter fullscreen mode Exit fullscreen mode
  • Java
yum install java-11-openjdk
java -version
update-alternatives --config 'java'

---# Process
jps -v
ps -aux | grep java 

---# capture heap dump Manually
jmap dump:live,format=b,file=/opt/dump.hprof <PID>
jcmd <PID> GC.heap_dump /opt/dump.hprof
jcmd <PID> Thread.print
kill -3 <PID> # useful when you use containerized
jstack <PID> > /opt/my-app.tdump  # Save analysis result to file

---# capture heap dump Automatically
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<file-or-dir-path>


Enter fullscreen mode Exit fullscreen mode
  • Firewalld
yum install firewalld -y
systemctl enable firewalld
systemctl start firewalld
systemctl status firewalld
chkconfig firewalld on

---# help
man firewalld

---# Allow/Deny
firewall-cmd --zone public --permanent --add-port 7000-9000/tcp 

- allow or deny a port
firewall-cmd --add-port=12345/tcp --permanent
firewall-cmd --remove-port=8080/tcp --permanent
- allow or deny a protocol
firewall-cmd --add-protocol=smb2 --permanent
firewall-cmd --remove-protocol=smb --permanent
- allow or deny a service
firewall-cmd --get-services
firewall-cmd --add-service=smtp --permanent
firewall-cmd --remove-service=smtp --permanent

Each service has an XML file located at /usr/lib/firewalld/services which contains the port and protocol being used by the service. 
For example, the ssh.xml file is using port 22 and the TCP protocol.
    <?xml version="1.0" encoding="utf-8"?>
    <service>
    <short>SSH</short>
    <port protocol="tcp" port="22"/>
    </service>

firewall-cmd --zone public --list-services

---# Zones: Each zone has its own unique set of rules. For example, public zone can be bound to eth0 and only allow HTTP, and internal zone can be bound to eth1 and allow both HTTP and SSH.
firewall-cmd --get-active-zones
firewall-cmd --list-all-zones
firewall-cmd --list-all --zone=internal
firewall-cmd --list-all --zone=public
firewall-cmd --set-default-zone=dmz
or 
vi /etc/firewalld/firewalld.conf
DefaultZone=dmz

---# IP address masquerade
firewall-cmd --add-masquerade --permanent
firewall-cmd --remove-masquerade --permanent
firewall-cmd --zone public --query-masquerade

---# port forward: 
   firewall-cmd --zone=external --add-forward-port=port=22:proto=tcp:toport=12345 --permanent
  The SSH service listening on port 12345 is on the same server as the SSH service with port 22.

  firewall-cmd --zone=external --add-forward-port=port=22:proto=tcp:toport=10.1.2.3:12345 --permanent
    To forward request to another server, add the target IP address.
Enter fullscreen mode Exit fullscreen mode
  • history
history       // get all history
history -c    // clean up
history -d 4  // remove by id 4
for i in {1..10}; do history -d 40; done  // remove 40 - 50
HISTSIZE=50   // change history size
set +o history  // disable history for current shell
set -o | grep history   // check if enabled/disabled
set -o history  // enable
// disable permanently
echo 'set +o history' >> ~/.bashrc & sh ~/.bashrc
echo 'unset HISTFILE' >> /etc/profile.d/nohistory.sh
Enter fullscreen mode Exit fullscreen mode
  • SSL, TLS & Certification
-- Export the private key:
openssl pkcs12 -in certfile.pfx -nocerts -out key.pem -nodes
-- Export the certificate: 
openssl pkcs12 -in certfile.pfx -nokeys -out cert.pem
-- Remove passphrase from key: 
openssl rsa -in key.pem -out server.key 

-- save server cert
openssl s_client -connect my.domain.com:443 -servername my.doamin.com | tee logCertificatFile
-- locking for the issuer
openssl x509 -in logCertificatFile -noout -text | grep -i "issuer"
curl --output myCertificat.crt urlOfissuer
openssl x509 -inform DER -in myCertificat.crt -out myCertificat.pem -text
set NODE_EXTRA_CA_CERTS="myCertificat.pem"  // ex: for nodeJs env

trust list
trust anchor path/to/certificate.crt
trust anchor --remove path/to/certificate.crt
trust anchor --remove "pkcs..."

Enter fullscreen mode Exit fullscreen mode
  • User & group Management
---# Add user
useradd myusername 
useradd -r myusername //has some root privileges, but not all, UID < UID_MIN 
useradd -c "My UserName" -d /home/my_dir myusername 
useradd -m -k /dir_default myusername //copies contents /dir_default to /home/myusername
useradd -e 2022-12-15 myusername //automatically disabled on 2022-12-15

usermod -l "new-login" myusername

---# Set password
passwd myusername 
passwd -l myusername // lock 
passwd -u myusername // unlock 
passwd -e myusername // change password during the next login 
passwd -n 10 -x 60 -w 3 myusername // set password lifetime 
passwd -S myusername // short info for password status 

---# Get User iformation
lslogins myusername  // display detailed info

---# Delete user
userdel myusername
userdel -r myusername // remove file /home/myusername 

---# add user to group
useradd -G my_group myusername 
usermod -g my_group myusername

---# Create group
groupadd my_group // add group
groupdel my_roup  // delete group
getent group      // group listing

---# All user
cat /etc/passwd

---# User cmd default cofig
cat /etc/login.defs
  PASS_MAX_DAYS 99999
  PASS_MIN_DAYS 0
  PASS_MIN_LEN  5
  PASS_WARN_AGE 7
  CREATE_HOME   yes
  ...
Enter fullscreen mode Exit fullscreen mode
  • Permission
chown -R username:group /path/to/folder
chown -R $USER /path/to/folder // curent user

---# Access Control Lists
Types of ACLs:  
  Access ACLs : list for a specific file or directory.  
  Default ACLs. can only be associated with a directory.

yum install acl
[setfacl -m rules files]
-m: add or modify
u:uid:rwx => user
g:gid:rwx => group
m:rwx => rights mask, union of all permissions.
o:rwx => users other than the ones in the group for the file.
rwx-X => read,write,execut,- = abdent, X = execut only folders
// helps
man setfacl

setfacl -d -m group:developer:rx /var/log
setfacl -d -m group:developer:rwx /home

// Deny access to the developer group
setfacl -m group:developer:--- /root

// remove permission
setfacl -x u:myusername /path/to/folder

// get acl for folder
getfacl /path/to/file.png

// Changing the default umask for a specific user
echo 'umask octal_value' >> /home/username/.bashrc
more: [check](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html-single/configuring_basic_system_settings/index)
Enter fullscreen mode Exit fullscreen mode
  • Network
---# ifconfig
yum install net-tools
ifconfig

---# Ip
ip addr

---# Check open ports, 3 way
sudo lsof -i tcp
netstat -tulpn 
sudo ss -lt
Enter fullscreen mode Exit fullscreen mode
  • CURL
curl https://amazon.com -v   // verbose
curl https://amazon.com -k  // Ignore certificat
curl https://amazon.com --noproxy '*'
curl https://amazon.com -x 'http://proxy-ip-name:port'
curl telnet://localhost:80 -v // check connected status + (ctr+c)
Enter fullscreen mode Exit fullscreen mode
  • SSHD
---# Generating Key Pairs
su myuser
ssh-keygen -t rsa
chmod 700 ~/.ssh
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
!!! Never share your private key with anybody !!!


---# ssh configuration
vi /etc/ssh/sshd_config
PubkeyAuthentication yes    // enable auth with public key
#Banner none                // disable banner message

---# sshd daemon
service sshd restart OR systemctl restart sshd
Enter fullscreen mode Exit fullscreen mode
  • Nginx
# Display top 10IP addresses hitting webserver
cat /var/log/nginx/access.log | cut -f 1 -d ' ' | sort | \
uniq -c | sort -hr | head -n 10

Enter fullscreen mode Exit fullscreen mode

== [ Ubuntu ] ==

  • Sys information
---# Find which WM_CLASS your window has,used as value in StartupWMClass on .desktop files to ignore duplication
xprop WM_CLASS

Enter fullscreen mode Exit fullscreen mode
  • Soft management
---# How to execute .bin .run file
chmod +x my_ide.run
./my_ide.run

---# add application icon to menu (dockbar)
cd /usr/share/applications (Global) 
cd ~/.local/share/applications/ (Local)
vi my_app.desktop
......
[Desktop Entry]
Comment=LiferayStudio
Terminal=false
Name=Liferay DXP Studio
Encoding=UTF-8
Exec='/opt/tools/liferay-developer-studio/DeveloperStudio'
Type=Application
Icon=/opt/tools/liferay-developer-studio/icon.xpm
StartupWMClass=LiferayDeveloper
......

Enter fullscreen mode Exit fullscreen mode
  • User management:
-- Get a List of All Users
less /etc/passwd
-- Add user to group
sudo usermod -aG [GROUP] [USER]
ex: sudo usermod -aG docker ${USER} => add your user to docker group
-- Login to specific user 
su - [USER]

Enter fullscreen mode Exit fullscreen mode
  • User Interface (UI/UX)
## Minimize & Maximize buttons in Gnome
Separation by `:`
Left:
gsettings set org.gnome.desktop.wm.preferences button-layout "close,minimize,maximize:"
Right: ":minimize,maximize,close"
Mix: "close:minimize,maximize"

## Disable task switcher grouping 
1- Open (dconf-editor)[apt://dconf-editor]
2- Go to org/gnome/desktop/wm/keybindings
3- Move the value 'Tab' from switch-applications to switch-windows : 
set switch-windows = ['<Alt>Tab']

Enter fullscreen mode Exit fullscreen mode

Top comments (0)