Generic-cli

Från wiki.soltec.se
Hoppa till: navigering, sök

Manpages

Display the different manpages for a command.

$ man -f <cmd to find>

Perform an extensive search for a manpage

$ man -k <cmd to find>

N.B!Info pages support hyperlinks, manpages do not.

Disks/PV/VG/LV info

Display a more readable output of disks/vols/mountpoints on Linux

  # lsblk -i

Physical Volumes

  # pvscan
  # pvdisplay

Volume Groups

  # vgscan
  # vgdisplay
  # vgchange
  # vgrename
  # vgs

Logical Volumes

  # lvscan
  # lgscan
  # lvdisplay
  # lvchange
  # lvs
  # lvresize
  # lvextend
  # lvreduce
  # lvrename

Rename Root Vol

To change the root vol name, boot from a bootable ISO or CDROM
Login and run the following

# vgrename <old-vg> <new-vg>

Mount the root disk & required sub filesystems

# mount /dev/<new-vg> /mnt
# mount --bind /proc /mnt/proc/
# mount --bind /sys /mnt/sys/
# mount --bind /dev /mnt/dev/
# mount /dev/sda1 /mnt/boot/
# chroot /mnt

Edit the fstab and grub files

# sed -i 's/<old-vg>/<new-vg>/g' /etc/fstab
# sed -i 's/<old-vg>/<new-vg>/g' /etc/default/grub

Use grub2-mkconfig

# grub2-mkconfig -o /boot/grub/grub.cfg

Create new kernel initramfs/initrd image file using a specific kernel version.

# dracut --force --kver <choose kernel vers>

Tips! Run <uname -r > to show the active kernel version or check for different versions in </boot> for required kernel name.

Use the following to check content of new initramfs/initrd image

List entire content
# lsinitrd <path-to-image>
View a specific file from the image file
# lsinitrd -f /etc/fstab <path-to-image>

unmount chroot & reboot

# umount -f /mnt
# shutdown -h now

Remove cdrom/ISO and reboot.

GRUB

Located in </boot/grub2> are the grub boot loader files for bios based computer systems. </boot/grub2/grub.cfg> is the configuration file

To modify the way Linux boots, edit </etc/default/grub>. After you’ve made changes to this file and saved them, you’ll need to run

    $ grub2-mkconfig 

which will update the boot loader code responsible for booting the system.

On UEFI systems the boot loader config is stored in the </boot/EFI/EFI/cintas/grub.cfg> file

N.B! The <grub2-mkconfig> command is also run automatically whenever we install a new kernel.
DNF will allow uninstalling of the active kernel. Yum won’t allow this.
DNF configuration file is </etc/dnf/dnf.com>
Set the "--latest-limit" setting to preserve files and stop active kernel uninstallation.

On the cli use the following to uninistall all but the last two kernels.

The following uses DNF repoquery to get a list of kernels further back 
than two and then passes that list to DNF remove.
   $ dnf remove $(dnf repoquery --installonly --latest-limit=-2 -q)

Set default kernel
    $ grub2 set-default 1
    $ grub2 set-mkconfig

Insert current kernel version into a command
   $ ls /lib/modules/$(uname -r)/kernel

RPM

Find out what pkg a file belongs to

  # rpm -qf <path-to-file/cmd>

Find out if a file was installed as part of a pkg

  # rpm -ql /usr/liblibXp.so.6

List path to files for yum

  # rpm -ql yum

Display system-wide config files for a cmd

  # rpm -qcf /bin/bash

Check contents of RPM

  # rpm -qlp RPMTOPDIR/RPMS/x86_64/<name-of-pkg>.rpm

To view different architecture version of a pkg

  # rpm -q --queryformat "%{name}.%{arch}\n" pdksh-5.2.14-36.el5

Display a pkg group

  # rpm -qa Group=“System Environment/Shells”

Display when pkgs installed

  # rpm -qa last

Display all dokumentation for a pkg

  # rpm -qd yum    dok files

Display all configuration files for a pkg

  # rpm -qc yum    cfg files 

Display all docs for a command

  # rpm -qdf /bin/bash

Display which pkgs install bash

  # rpm -q --provides bash

Display dependencies on the bash pkg

  # rpm -q --requires bash

Display all changes made to pkg

  # rpm -q --changelog bash

Display info about a specific package.

  # rpm -qip <pkgname>

Display info about files to be installed from a pkg

  # rpm -qlp <pkgname>

OBS! the ‘p’ option queries a downloaded pkg and not the repo database.

RPM TAGS

Display all pkg tags in OS vesion
  $ rpm --querytags
Display the permission modes of all files in the bash package 
  $ rpm -q --qf “[%{FILEMODES} %{FILENAMES}\n]” bash 
To format the permissions better, We can add the perms formatting modifier. 
  $ rpm -q --qf “[%{FILEMODES:perms} %{FILENAMES}\n]” bash 

N.B! To display a list of other query format modifiers use the RPM manpage and search for query options.

GREP

grep for soltec in start of line

  # grep ^"soltec"

grep for soltec at end of line

  # grep "soltec"$

Ignore all systemd messages

  # grep -v ‘systemd’ /var/log/messages
  -v for invert

Ignore multiple expressions using egrep

  # egrep -v ‘systemd|NetworkManager’ /var/log/messages


YUM

to install all pkgs in listed in file

  # yum install $(< test.txt) 
  # yum -y install $(cat list)

Display history

  # yum history
  # yum history info
  # yum history list

Configure & use YUM to download packages to local repo

Create a dir
  $ mkdir /tmp/yumdownloads

Install the yum Download-only plugin
  $ yum -y install -y yum-plugin-downloadonly

Execute YUM to download pkg(s)
  $ yum install - -downloadonly --downloaddir=/tmp/yumdownloads httpd

DNF

YUM has been rewritten and named DNF. YUM is legacy and can be executed as it uses DNF.

DNF can use software groups to install all pkgs required e.g. desktop, development tools…mm

   $ dnf group list
   $ dnf group list hidden
   $ dnf group info “Development Tools”

Display all versions of a pkg

    $ dnf --showduplicates list xfsprogs

Display pkgs that have upgrades available

    $ dnf list --updates

Upgrade a pkg (find pkg from updates command)

    $ dnf upgrade <pkgname>

Display pkgs that are available in the repo but not installed

    $ dnf list --available

Display pkgs that have been replaced by other packages

    $ dnf list --obsoletes

Display pkgs dependencies

    $ dnf deplist <pkgname>

Search for a package

    $ dnf search <search string>

To search even in pkg metadata

    $ dnf search all <search string>

Display which pkgs utilise a specific command

    $ dnf provides <cmd string>

Install a pkg over an existing pkg (similar to upgrading)

    $ dnf reinstall <pkgname>

Remove any unused dependencies in system i.e. if not used by other pkgs

    $ dnf autoremove

Remove a package and dependencies i.e. if not used by other pkgs

    $ dnf autoremove <pkgname>

Disable a pkg from being upgraded by installing version lock plugin

    $ dnf install python3-dnf-plugin-versionlock

To lock a specific kernel version

    $ dnf versionlock add <kernel-version>

To lock the current kernel version

    $ dnf versionlock add kernel

Display pkgs that are versionlocked

    $ dnf versionlock list

Clear pkgs that are versionlocked

    $ dnf versionlock clear
    $ dnf versionlock delete <locked pkg from list output>
  • Configuration files may be renamed when a new package is installed.
  • If the system administrator has not modified a configuration file, then the config file is overwritten.
  • If the system administrator has modified the configuration file, then the modified configuration file is saved with a ,rpmsave or .rpmorig extension. And the new configuration file is saved from the package.
  • The .rpmsave extension is used if the file was installed from a previous rpm package.
  • The .rpmorig extension is used if the file came from a non-rpm source. This would happen if you installed from source code and then later moved on to an rpm package.
  • If the administrator has modified the configuration file, and the software package maintainer included the noreplace label in the package, then the new configuration file is saved with a .rpmnew extension and the original configuration is left in place. When installing with dnf and rpm, you will see a message to let you know which operation was done.
    $ dnf changelog
    $ dnf changelog upgrades


VI

 dG	|delete from line to end of file
 d1G	|delete to top including current line
 dgg	|delete from line to start of file
 G     |goto last line in file
 1G	|to to first line in file
 0	|goto start of line
 $	|goto end of line
 :set number	 |to display line numbers
 :color desert  |to change display colours
 
 ctrl r       |undo changes
 cl, cw, cc   |cut letter, word, line
 yl, yw, yy   |yank letter, word, line
 dl, dw, dd   |delete letter, word, line

Copy/Move data

To move data on the same system, use the following:

  # cd dir1 && tar -cf - . | (cd dir2 && tar -xpvf -)
  dir1 is the directory you want to copy.
  dir2 is the directory in which you want the copy to go.
  This tar’s the current directory to STDOUT, then changes directory, 
  and untar’s the archive without ever having to find the space for a .tar file.

Use the following to do this across systems via ssh:

  # cd dir1 && tar -cf - . | ssh system2 "cd dir2 && tar -xpvf -"

RSYNC Slash or no Slash

  • Without a slash on the source directory means copy both the source directory, and the contents (recursively if specified) to the destination directory
  • Adding a trailing slash on the SRC directory means only copy the contents of the SRC directory, recursively if specified, to the destination.

RSYNC v RSYNCD

Use rysncd instead of rsync to use resources on the target system copying the data instead of source server

TOP

The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of tasks currently being managed by the Linux kernel.

Executing on the cli

Usage:
top -hv | -bcHiOSs -d secs -n max -u|U user -p pid(s) -o field -w [cols]
# top
# top –u dbuser                  | option will display specific User process details
# top -n 1 -b > top-output.txt   | save the running top command results output to a file
# top -n 10                      |automatically exit after 10 number of repetition.

Reading the output

N.B! By default, top updates its display every three seconds
  • The first line of numbers on the dashboard includes the time, how long your computer has been running, the number of people logged in, and what the load average has been for the past one, five, and 15 minutes.
  • The second line shows the number of tasks and their states: running, stopped, sleeping, or zombie.
  • The third line displays the following central processing unit (CPU) values:
us: Amount of time the CPU spends executing processes for people in “user space.”
sy: Amount of time spent running system “kernel space” processes.
ni: Amount of time spent executing processes with a manually set nice value.
id: Amount of CPU idle time.
wa: Amount of time the CPU spends waiting for I/O to complete.
hi: Amount of time spent servicing hardware interrupts.
si: Amount of time spent servicing software interrupts.
st: Amount of time lost due to running virtual machines (“steal time”).
  • The fourth line shows the total amount (in kibibytes) of physical memory, and how much is free, used, and buffered or cached.
  • The fifth line shows the total amount (also in kibibytes) of swap memory, and how much is free, used, and available. The latter includes memory that’s expected to be recoverable from caches.

The column headings in the process list are as follows:

PID:     Process ID.
USER:    The owner of the process.
PR:      Process priority.
NI:      The nice value of the process.
VIRT:    Amount of virtual memory used by the process.
RES:     Amount of resident memory used by the process.
SHR:     Amount of shared memory used by the process.
S:       Status of the process. (See the list below for the values this field can take).
%CPU:    The share of CPU time used by the process since the last update.
%MEM:    The share of physical memory used.
TIME+:   Total CPU time used by the task in hundredths of a second.
COMMAND: The command name or command line (name + options).

The status of the process can be one of the following:

D: Uninterruptible sleep
R: Running
S: Sleeping
T: Traced (stopped)
Z: Zombie

If you have a multi-core CPU, press 1 to change the display and see individual statistics for each CPU.

For each CPU, top displays three numbers and the graph. From left to right, the numbers are as follows:

- The combined us and ni percentage (user space+tasks with nonstandard nice settings).
- The sy percentage (kernel space).
- The total (rounded to an integer value).

Changing the Numeric Units

Memory values are shown in kibibytes.

Change the display units to more readable values by presssing capital E to cycle through the units used to display memory values in these options:

kibibytes
mebibytes
gibibytes
tebibytes
pebibytes
exbibytes

The unit in use is the first item on lines four and five.

Press lowercase “e” to do the same thing for the values in the process list:

kibibytes
mebibytes
gibibytes
tebibytes
pebibytes

Sorting by Columns

By default, the process list is sorted by the %CPU column.

You can change the sort column by pressing the following:
P: The %CPU column.
M: The %MEM column.
N: The PID column.
T: The TIME+ column.

TOP interactive console cmds

h          |help screen
z          |highlight processes in red
c          |display absolute path of running process
I          |display only active tasks.
n          |limit the display to a certain number of lines, regardless of whether the tasks are active. 
t          |swap the CPU displays to simple ASCII graphs that show the percentage of usage for each CPU.
u          |display the processes for a single user. You’ll be prompted for the name or UID.
V          |display a “tree” of processes that were launched or spawned by other processes
k          |kill a process after finding PID
d          |change default screen refresh interval  default= 3 seconds
Shift+P    | to sort processes as per CPU utilization
Shift+O    | to Sort field via field letter
Space      |Force top to refresh its display right now.
Press Q to exit top

You can also install htop which is more user-friendly / interactive than original top

URL: HTOP

Process Mgt

Nice/Renice

The nice and renice commands let you fine-tune how the kernel treats your processes by adjusting their priorities.

  • Every process has a nice value.
  • The nice value is an integer in the range of -19 to 20.
  • All standard processes are launched with a nice value of zero.
  • A high nice value tells the kernel that this process is happy to wait.
  • The larger the negative nice value, the more selfish the process is.
  • Use the nice command to set the nice value when a process is launched
  • Use renice to adjust the nice value of a running process.

Execute $top to view the nice value of your application/process

In the "top" console the nice value is the figure in the “NI" column. A zero value is expected.

Start an application with a non-default “nice” value

$ nice -15 ./httpd
    OBS! To indicate a negative number you must type two “-” characters.

Set a new value on-the-fly with renice

$ renice -n 5 PID
    OBS! there is no “-” on the 5 parameter. You don’t need one for positive numbers 
         and you only need one, not two, for negative numbers.

Renice a PID value whilst in top

From the top console You press “r” to change the nice value (priority) for a process. You’ll be prompted for the process ID. Just press Enter to use the process ID of the task at the top of the process window.

SSH

Here are two links to great sites that explain SSH, Public & Private Keys, SSH-AGENT etc.

  # Using ssh-agent forwarding
  # ssh-agent forwarding

Date/time/NTP

Display systemclock, timezone and ntp status

$ timedatectl

Edit the time settings using timedatectl

$ timedatectl list-timezones
$ timedatectl set-timezone <t.ex CET>
$ timedatectl set-time <YYYY-MM-DD>
$ timedatectl set-time <HH:MM:SS>
$ timedatectl set-ntp true

Change the hostname

$ hostnamectl set-hostname “new hostname”

AT/Cron

$ at now +15mins
       at> mkdir /apa
$ atq                  | display at queued jobs
$ atq -c <jobnr>       | displays the content of the job
$ atrm <jobnr>         | delete the job
$ batch
     at> mkdir /apa  --> ctlr-d to save

!N.B at batch jobs are only executed when the system load average is below 0.8

URL to a Crontab generator

Crontab Generator

Modules

   $ modprobe
   $ modprobe -r
   $ modprobe -vr

Auto-loading

To auto-load modules

add a file to the dir </etc/modules-load.d> with file extension <.com> 
add the module name to the <.com> file.

Blacklisting

Blacklist a module to stop it loading at boot.

Create a file </etc/modprobe.d/<filename>.conf> 
Add the line “blacklist module-name” to the .conf file.

Users

Configuration files

/etc/login.defs       contains info for passwd ageing, actions to perform when administering users IDs.
/etc/default/useradd  contains default actions when creating users t.ex shell, homedir path etc..
/etc/skel             contains files copied to users homedir by default.
/etc/pam.d            contains cfg files for pluggable authentication modules.

/etc/security/pwquality.conf   Set the passwd quality policy, edit the conf file
$ userdel “username”     to delete user but preserve homedir
$ userdel -r “username”  to delete user and homedir.
$ usermod
  -a      append to existing settings, used when using the -G option for supplemental groups.
  -l      change login name
  -L/-U   Lock or unlock an account, N.B! doesn’t stop login if user uses ssh-keys.
$ passwd
   -d deletes passwd
   -e expires passwd
   -l locks passwd   (not effective if ssh keys used)
   -u unlocks the passwd
   -S passwd status

N.B!  In the /etc/shadow file a “!!” in the password field means that the password for the user has not been set yet.

Account aging for existing users

$ chage     change user password expiry information
  -l     “Display acct aging info”
  N.B! If no options are selected, $ chage operates in an interactive fashion, prompting the user with the current values for all of the fields.
$ chage -d 0 “username”             Forces the user to change passwd at next login.
$ chage -E 2022-01-01 “username”    Set the expiration date for the users account

  N.B! If the account expires the user can no longer login even with ssh-keys.

$ chage -M “xx” “username”          Set the max number of days between passwd change.
$ chage -I “xx”  “username”         Set the number of days an account can be inactive before it’s locked.

$ chage -I -1 -m 0 -M 99999 -E -1 “username”    Remove all passwd aging for a user. Used for service users.

$ usermod
    -W     Set the number of days of warning before a password change is required.

Groups

Two commands to add users to a group

$ gpasswd -a “username” “groupname”      this is group centric i.e. add user to a group. Can add several users at once.
$ usermod -a -G “groupname” “username”   this is user centric i.e. add group to user's settings. Executed per user.

Set passwd for the group access for users outside of group

$ gpasswd “groupname”

Add a group temporarily as a user's primary group.

$ groups
$ newgrp “groupname”
$ groups

$ gpasswd -d “username” “grpname”   to delete a user from a group
$ gpasswd -A “username” “grpname”   to add admin user for a grp.
$ grpmod

How to ID yourself

$ logname       ids who you logged in at start of session
$ whoami        Id who you are now at present.

Add users to “wheel” group to elevate privileges for all commands.

$ useradd -u 1100 -s /bin/ksh -G wheel “username”
$ gpasswd -M “user1",“user2”,“user3" “grpname”    Quicker than usermod as it’s performed from grp not user perspective.
$ gpasswd “groupname”                             Add the passwd for the group. Group members won’t need to enter the passwd.
$ chage -E 90 -W 5 “username”                     Configure user acct to expire in 90 days with warning msg sent 5 days before expire date.