Linux services

Services there are the background run programs also called daemons.

sudo systemctl <command> <service name>

Modules control сommands

  • start
  • stop
  • restart
  • reload
  • reload-or-restart
  • enable (with --now flag – enable and run immediately)
  • disable (with --now flag – disable and stop immediately)
  • mask – mark service as completely unable to be run or enabled

Status and information commands

Check processes and services running by <user>
sudo ps -efl | grep '<user>'

  • status
  • list-units
  • list-unit-file

Useful services

  • nginx
  • openssh
  • systemd-timesyncd – leightweight NTP-client

Posted in cheatsheet, linux | Tagged | Leave a comment

Some ways how to connect to remote Linux server.

To establish the ssh-connection between local and remote machines there are two main ways possible to pass the authentication:

  • Classic – login/password pair
  • A little more complicated, but safe and reliable – using a pair of RSA keys to introduce youself

Setup the remote side

Password login

Some linux images, e.g. from OCI have the access via login/password disabled by default, so the OS demands the key file to let the user log in. To open the possibility of such kind authentication the corresponding parameter in the config file has to be added/modified:

sudo nano /etc/ssh/sshd_config

Find PasswordAuthentication parameter and change the value to yes. If you are too lazy to enter the password and want to make a security breach in your system, refer also to PermitEmptyPasswords parameter and google “linux user with empty password”. Restart sshd service to implement the settings.

sudo systemctl restart sshd

OK, from now any user with defined password may log in with his own account credentials.

If there are some troubles with users and passwords – refer to the corresponding cheatsheet.

RSA keys pair

[toDo]

Creation of the keys

ssh-keygen

Permissions: home dir – rwxr-*r-* (chmod go-w <home dir>); .ssh dir – 700; key file – 600; on the serverside – authorized_keys – 600;

Registering keys in the system

Remote access procedure

Initial data for remote login

To connect to the remote Linux system there are some credentials are needed to be known in all the cases:

  • IP-address of the PC or server you are going to connect to
  • The username existing on the remote system to log in with
  • Some secret like password or the private key if RSA key pair is registered in remote host system

Connect via Windows or Linux command shell

Here is one general utility is in use calling ssh for both Windows 10-11 cmd/Power Shell and Linux command shell. The command format depends on the access method:

ssh <IP address/domain name> – simple form, which leads to the sequential prompt of the username and password.

ssh <username>@<IP address/domain name> – log in with a defined user name, the only password will be requested.

ssh <username>@<IP address/domain name> -i <private key / key filename> – log in using RSA-key authentication. If all the credentials are alright, the log-in procedure proceeds instantly without any input. If something wrong with keys, but the password authentication is allowed, the user password is prompted.

During the first login there is the need for the confirmation of the trust to the remote host, just type “yes” if you’re sure, that you connect to the proper host.

If key auth doesn’t work: ssh <username>@<IP address/domain name> -i <private key / key filename> -vv – displays detailed connection try report

On the servfer side check logs:

/var/log/auth.log (Debian/Ubuntu)

/var/log/secure (RHLE/CentOS/Oracle Linux)

Connect via PuTTY

[toDo]

Posted in linux | Tagged | Leave a comment

Midnight Commander editor shortcuts

F3 Begin of text selection. Second press – end of text selection
Shift+F3 Begin of block text selection
F5 Copy text selection
F6 Move text selection
F8 Delete text selection
Meta+i Go to previous bookmark
Meta+j Go to next bookmark
Meta+k Toggle bookmark
Meta+l Go to line by number
Meta+o Flush bookmarks
Meta+q Insert literal. See table at bottom of this page
Meta+t Sort of text in selection.
Meta+u Execute external command and insert output into cursor position
Ctrl+f Save selection into external file
Ctrl+k Delete chars to end of line
Ctrl+n Create new file
Ctrl+s Toggle syntax highlighting
Ctrl+t Select text charset
Ctrl+u Undo
Ctrl+x Go to end of next word
Ctrl+y Delete line
Ctrl+z Go to start of previous word
Shift+F5 Insert external file content into cursor position
Meta+Enter Codejump dialog
Meta+- Move back into codejump (go to from function definition to function call)
Meta++ Move forvard into codejump (go to from function call to function definition)
Meta+n Toggle number of lines
tab If ‘persistent blocks’ option is on, then move selected text to right
M-tab If ‘persistent blocks’ option is on, then move selected text to left
Shift+Arrows Text selection
Meta+Arrows Block text selection
Meta+Shift+- Toggle show visible tabs and trailing spaces
Posted in cheatsheet, general, linux | Tagged | Leave a comment

Windows 11 Mini apps load CPU quite bad

Didn’t mind the mentioning of MS products here, but the office PC with Windows 11 onboard gets me to write down a case about.

The Problem: PC’s cooling fan goes on full speed with the only office apps run, the CPU load ~18%, most of caused by some “Windows Mini Apps” group with several instances of MS Edge WebView2 inside.

I don’t use any widgets and dynamic menu plates, so it’s preferable for me to make the system as lightweight as I can. Moreover, there are a lot of bugs in that package had been found, as googling results say.

The Solution: Remove the package completely from cmd launched as Administrator:

winget uninstall "windows web experience pack"

CPU load 3% as result, the fan is quiet.

Posted in troubleshooting, Windows | Leave a comment

How to attach shared OCFS2 Block Volume

Here is a very simple operation to create and attach the Block Volume to the Compute instance in the framework of Oracle Cloud Infrastructure.

However, the shared connection of many instances to conventional Block Volume may cause data corruption due to concurrent access to the same data blocks. In order to prevent kind of “accidents” here is the feature to deploy the OCFS2 file system available, which works correctly with multiple instances access.

Actually, here is the first “long-read” instruction I face during my short IT life, which led to the desired result just being followed step-by-step carefully with no “if”, “when”, and exhausting chain-googling.

So, thanks to Mr.Melo – the author, the instruction is here:

OCI Multiple-Instance Attach Block Volume with Oracle Cluster File System version 2 (OCFS2)

Posted in linux, OCI, Oracle/CentOS/RedHat | Leave a comment

Take some of Linux

Default standard UNIX/Linux utilities

cat – concatenate files to standard output
chgrp – change file group ownership
chmod – change file access permissions
chown – change file owner and group
cp – copy files and directories
date – print or set the system data and time
dd – convert and copy a file
df – report filesystem disk space usage
dmesg – print or control the kernel message buffer
echo – display a line of text
false – do nothing, unsuccessfully
hostname – show or set the system’s host name
kill – send signals to processes
ln – make links between files
login Utility to begin a session on the system
ls – list directory contents
mkdir – make directories
mknod – make block or character special files
more – page through text
mount – mount a filesystem
mv – move/rename files
ps – report process status
pwd – print name of current working directory
rm – remove files or directories
rmdir – remove empty directories
sed – The `sed’ stream editor
sh – POSIX compatible command shell
stty – change and print terminal line settings
su – change user ID
sync – flush filesystem buffers
true – do nothing, successfully
umount – unmount file systems
uname – print system information

Command binaries that are not essential enough to place into /bin must be placed in /usr/bin, instead. Items that are required only by nonroot users (the X Window System, chsh, etc.) are generally not essential enough to be placed into the root partition.

Linux filesystem

Filesystem Hierarchy Standard specification

Navigation

pwd – print current directory
cd ~ or cd – home directory
cd .. – one directory tree level up
cd - – go back to previous working directory
popd pushd – ???
tree (-d) – print the directory subdirectories (and files) structure tree
ls (-l) [-a] {-i} – lists the files in present working directory (including hidden) [with files/directories info] { with files IDs (different links to one file have same ID)}

Aliases

nano ~/.bash_aliases

Lines syntax: alias <command>=’bash command’. Spaces are not allowed.
E.g.: alias update=’sudo dnf upgrade’

source ~/.bash_alias – apply alias’s list

Hard and soft (symbolic, sym-) links

ln <file> <file_sc> – create hard link (shortcut) – alternative reference to the same file, same ID
ln -s <file> <file_sc> – create symbolic link (different object with new ID)

https://wiki.merionet.ru/servernye-resheniya/77/komanda-ln-kak-sozdavat-simvolicheskie-ssylki-v-linux/

Stop laptop from being suspended when lid closed

nano /etc/systemd/logind.conf

Uncomment and bring to the following order the strings:

HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
LidSwitchIgnoreInhibited=no

Restart the system.

Path definition

Dispaly current PATH variable: echo $PATH

Default $PATH set (not user-related): PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

System information

uname -a – info of Linux version, core etc.

lshw [-short] – full hardware configuration tree [brief overview]
lscpu
lsmem
lsblk [-a],
fdisk -l additional info
blkid check UUID
lsusb

top [-i] – CPU utilization [hide idle processes]

Volume blocks management

Display current info: mount
Mount sdb1 block to /mnt/media as ext4 volume: mount /dev/sdb1 /mnt/media -t ext4
Automount on startup: add record to /etc/fstab:
<volume device path>/UUID=<uuid> <mount path> <filesystem> <options> 0 0
example:
UUID=9898b394-874b-46fd-afd7-087c91987bfa /data ocfs2 _netdev,defaults, uid=0, gid=0, umask=0077, shortname=winnt 0 0

Add to File management setuid (chmod u+s), setgid (chmod u+s), Sticky bit (chmod +t)

https://ericdraken.com/useful-linux-commands/

https://ericdraken.com/pfsense-decrypt-ad-traffic/

Files handling

Read

Text file to console
cat <file>
tac <file> – from the last line towards the begin of fine
-n – number the lines

less – scrollable viewing utility:
g ; G- first ; last line
/ ; ?- search forward ; backward;
v – edit with default editor;
q – exit
h – help

head (tail) <file> ; cat <file> | head (tail) – print out first (last) 10 lines of the file
-n <number> – print out <number> of first (last) lines

Write

touch – create empty file / reset timestamp / -t <timestamp> – set timestamp
mkdir – create directory

rm – remove file(s) (-i – confirm for every file)
rm -r – remove directory with all content recursively
rmdir – remove empty directory

mv – move/rename file/directory

Here and further:
> – overwrite file; >> – append to the end of file
' ' may also be used instead of " ".

echo "Some text here." >> myfile.txt

> myfile.txt – erase all data in myfile.txt

Write command output to file (e.g. full directory content with permissions):
ls -la >> myfile.txt

Write to file from console line by line until ‘EOF’ typed in
cat > outfile.txt <<EOF
some text
to save
EOF

Find files by name:
find <path> -name "<name wildcard>"

System and apps search:
which <file> – basic check in $PATCH directories
whereis <file> – more deep search

Find files with string content
grep -Ril "text-to-find-here" /
i stands for ignore case (optional in your case).
R stands for recursive.
l stands for “show the file name, not the result itself”.
/ stands for starting at the root of your machine.

Check services running by <user>
sudo ps -efl | grep '<user>'

I/O streams

File ID’s
0 – stdin – input stream (by default – keyboard)
1 – stdout – output stream (by default – console)
2 – stderr – error messaging stream (by default – console, often redirected to log-file)

< changes the stdin source;
> redirects stout (by default or 1>) or stderr (2>); e.g.: [program/command] > [output_file] 2> [err_log]

2>&1 or shorthand >& – send everything written to stderr to the same destination as stdout

cat [file1] > [file2] – take the content of [file1] to the output stream and redirect it to [file2] – as result the content of [file1] is copied to [file2], replacing its content

Pipeline

command1 | command2 | command 3
The output (stdout) of the previous command is passed to the next one, the last command sends its output to the stdoud destination (console by default).

Prompt line

$PS1 Evironmental variable
\u – username
\h – hostname

List ls color designations

eval $(echo "no:global default;fi:normal file;di:directory;ln:symbolic link;pi:named pipe;so:socket;do:door;bd:block device;cd:character device;or:orphan symlink;mi:missing file;su:set uid;sg:set gid;tw:sticky other writable;ow:other writable;st:sticky;ex:executable;"|sed -e 's/:/="/g; s/\;/"\n/g')           
{      
  IFS=:     
  for i in $LS_COLORS     
  do        
    echo -e "\e[${i#*=}m$( x=${i%=*}; [ "${!x}" ] && echo "${!x}" || echo "$x" )\e[m" 
  done       
} 

Oracle Linux 8 training course:
https://apexapps.oracle.com/pls/apex/f?p=44785:141:16314683441842::NO:RP,141:P141_PAGE_ID,P141_SECTION_ID:557,3806

Oracle Linux 8 Documentation
https://docs.oracle.com/en/operating-systems/oracle-linux/8/index.html#

Time and Date management

timedatectl
status
set-time YYYY-MM-DD hh:mm:ss (ether one or both date and time)
set-date
list-timezones
set-timezone
set-local-rtc 0/1 – set hardware clock to a local TZ (1) or UTC (0)
set-ntp true/false – synchronize time with NTP-server

date – display current day and time in active timezone

display difference between dates in days:

A="2002-10-20"
B="2003-11-22"
echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days

curl

-s – run silently

-L – redo the request to a new location automatically if server responses of resource is moved

-f – fail silently

-o <file> – save to file

tar

tar -tf -show archive content

tar -xf -extract

–strip-content=i – ignore i levels of directories tree inside the archive structureip

network

ip link set dev <interface> up/down – enable/disable network interface

ip link show – list network interfaces

ip a[ddress] [show] – list addresses of the interfaces

ip addr add 192.168.1.200/24 dev enp0s25 – set temporary IP configuration

ip route add default via 192.168.1.1 – set temporary gateway configuration

Permanent config: RH/OL/CentOS

/etc/sysconfig/network-scripts/ifcfg-<interface> – network configuration file

Parameter name Description Values Example
DEVICE Interface name eth0
eth1
device=eth0
device=eth1
BOOTPROTO IP designation method dhcp
none
static
(пустое значение)
bootproto=dhcp
bootproto=
bootproto=static
bootproto=none
HWADDR MAC-address   HWADDR=”00:00:00:00:00:00″
NM_CONTROLLED NetworkManager controllable interface “yes”
“no”
NM_CONTROLLED=”yes”
ONBOOT Start on bootup “yes”
“no”
ONBOOT=”yes”
TYPE Interface type “Ethernet” TYPE=”Ethernet”
UUID     UUID=”ffffffff-ffff-ffff-ffff-ffffffffffff”
IPADDR IP-address   IPADDR=192.168.1.3
NETMASK Subnet mask   NETMASK=255.255.255.0
GATEWAY Gateway address   GATEWAY=192.168.1.1
DNS1 1-st DNS server   DNS1=192.168.1.1
DNS2 2-nd DNS server   DNS2=192.168.1.2
DOMAIN Host domain name   DOMAIN=MYDOMAIN.LOCAL
Static:
DEVICE=enp3s0
ONBOOT=yes
IPADDR=192.168.1.10
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DHCP
DEVICE=enp3s0
ONBOOT=yes
DHCP=yes

Permanent config: Debian/Ubuntu

Config files: /etc/netplan/xx-*.yaml

xx – priority index (99 – top, 00 – lowest).

DHCP

network:
  ethernets:
    enp2s0:
      dhcp4: true
  version: 2

Static IP

network:
  ethernets:
    enp2s0:
      dhcp4: false
      addresses:
        - 192.168.1.128/24
      gateway4: 192.168.1.1
      nameservers:
        search: [mydomain, otherdomain]
        addresses: [192.168.1.1, 8.8.8.8]
  version: 2

Run netplan apply to actualize the settings.

Firewall

firewall-cmd --permanent --add-service=http

firewall-cmd --permanent --add-port=<port#>/tcp<udp etc>

firewall-cmd --permanent --list-all

firewall-cmd --reload

Posted in linux | Tagged | Leave a comment

Linux file management

Main commands

List file(s) permissions: ls -la <filename/wildcard>

Following commands with -R mean recursive action along the directory tree.

Set file(s) permissions: chmod <object><modifier><digits/symbols> <filename/wildcard>
<object> (if no – set every field): u – owner; g – owners group; o – others;
<modifier>: ‘+’ – set; ‘-‘ – reset;

Set owner: chown <new owner> <filename/wildcard>
Set group ownership: chgrp <new group> <filename/wildcard>

Permissions designations:

Digits Symbols Description (files/folders)
0 no permissions
1 –x execute / get metadata
2 -w- write / modify (with –x only)
4 r– read / get files list
The mask byte: sum of mask numbers.

Permissions structure

owner (user) | owners group | others,
e.g. 7(4+1+2) 6(4+2) 4(4); symbols -rwxrw-r–

The tirck: here are different requirements for files and folders. Files have mostly no eXecutable attribute, but directories (folders) have to have this attribute set, another way it is not allowed to enter it at all. To be more fast with automatic separation of files and directoties, the commands below are useful.

Attention: it works recursively, DO NOT RUN IT ON / OR ANY SYSTEM DIRECTORY: all the files will get unexecutable and system may lost controlability at all.

find . -type f -exec sudo chmod 664 {} \; -exec echo {} \;
find . -type d -exec sudo chmod 775 {} \; -exec echo {} \;

This opens files and folder for full access for the owner and his groups and add X attribure to folders only, not for files.

Posted in cheatsheet, linux | Tagged | Leave a comment

Linux simple user management

Groups

Create group: sudo groupadd <group>
List users in the group: getent group <group>
If <group> missing all the groups are listed with users.
Attention: the user is not listed if the group is his main group! The only supplementary groups’ members displayed.

List groups, the user is in: groups <user>
If <user> is omitted, the groups for the current user are listed.

Change main group: sudo usermod -a -g <new group> <user>
Add user to a group: sudo usermod -a -G <supplementary groups list> <user>
If -a missed, the user gets removed from any other group, not listed after -G (way to remove user from a group by pointing new groups list for user to stay in).
Add/Remove user from group: sudo gpasswd -a/-d <user> <group>
More “low-level” way is to edit /etc/group file manually.

Users

List existing users: getent passwd

Create user: sudo useradd <user> -g <main group> -G <supplementary group>
The home directory will be created as /home/<user> automatically.
-M – don’t create a home directory.
If no main group is pointed the user is created within his own group with his name.

Delete user: sudo userdel <username>
Use -r to delete the user with a home directory.

Set password for <user>: sudo passwd <user>
It’s not recommended to create a user with a password (useradd -p option) due to password visibility in CLI history and logs.

Run from the name of user: sudo runuser -l <username>
Open root session: sudo runuser

Grant superuser rights to the user:

1st way: to add user to superuser group in /etc/sudoers file, the group is defined as
<group> ALL=(ALL) ALL

2nd way: to give full permissions to the user itself:
echo "<user> ALL=(ALL) ALL" > /etc/sudoers.d/<user>
and restrict access to this file
chmod 440 /etc/sudoers.d/<user>

Posted in cheatsheet, linux | Tagged | Leave a comment

Opposite things

Learn the opposite things at once and place their definitions/descriptions close to each other. Take a look back to be sure you know how to reverse the actions or to notice if it’s impossible.

Exempli Gratia:

  • Languages: anthonyms (good/bad; big/small; lay down/pick up);
  • Math: operators and functions (add/substract; power/root);
  • IT/OS: commands to create/delete (files,users…); start/stop (processes, services…); install/remove apps etc.;
  • IT/Programming: create/erase (data instances…); fill/clean up (vector, array); construct/destruct (objects …); show/hide (GUI nodes…)

Some of the entities may not have reasonable binary differentiation, the scope of the basic meanings you better consider in this case:

  • Nominativ / Genitiv / Dativ / Akkusativ
  • settlement / village / town / city / megapolice
  • sin / cos / tg / ctg and their reverse a-functions
  • copy / move / rename /edit
Posted in thinks | Leave a comment

Next incarnation of OCI web-server. Part one. HTTP.

The first experience with OCI compute instances had been dedicated to how to deploy a simple Hello-world-scale webserver. Now it’s time to play with the toy a little harder. Here is an approach of how to make the simple webserver and have some tools or framework to work with static web content.

What are the main tasks:

  • Create a simple OCI compute instance ( VM.Standard.E2.1.Micro, Oracle Linux 7.9 )
  • Setup and configure http – the nginx webserver instead of Apache one
  • Setup and configure ftp – the vsftpd server
  • Upload some web site and manage the content
  • Gain development SSL-Certificate and convert the server to https protocol.

Seems it takes more than one post, so we proceed step-by-step.

The tasks are not guaranteed to be executed one by one strictly, maybe some steps mess up and there will be a need to get to other parts of the entire problem and tinker a little some settings.

This time I use the complete native VCN infrastructure of two subnets (public and private) connected to the internet – it’s the first option, which VCN creation wizard proposes. The compute instance is necessary to place to the public subnet.

After VM deployment and configuring of the VCN security rules as described in the previous topic connect to the instance via CloudShell, PuTTy, or windows command shell (ssh works with cmd as well as in PowerShell); so run any shell from the context menu “Run as administrator” and type in:

ssh opc@<public IP address> -i mykeyname.key

To make the connection process easier, it makes sense to create a simple .bat file for Windows 10/11 in key location folder with one string:

ssh opc@<public IP address> -i mykeyname.key

Important thing: the file has also to be run as administrator: the ssh-key-file has restricted access, as you remember from the previous post, and can’t be handled by any different user.

For other Windows versions, the PuTTy utility may be used. Refer to complete connection manual using ssh keys (coming soon).

In the case of a Linux client machine, the bash script is the way. Create an empty text file nano ws_connect.sh:

#!/bin/bash
sudo ssh opc@<public IP address> -i mykeyname.key

Then Ctrl+X to exit Y and Enter to confirm to write the file.

The permissions are to be modified with chmod u+x ws_connect.sh to make the file executable. Run it anytime you want to connect to the server.

OK, we are going to have the act if we want to live in a different world to set up the server. At first, bring the system to up to date state: sudo yum update

After the system and components update is finished, let’s go to get some fun with repositories:

The initial repository list doesn’t contain nginx (Oracle Linux 7.x; the 8.x contains already the nginx repository predefined) so we add it manually. Create file nginx.repo:

sudo nano /etc/yum.repos.d/nginx.repo

Write the following repository definition (it works for Oracle Linux 7.x OS as the CentOS-like system):

[nginx]
name=nginx repo
baseurl=https://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

As before, press Ctrl+X to exit, answer Y, and confirm the filename to save the file.

Now we are ready to install and launch the webserver:

sudo yum install nginx
 sudo systemctl enable nginx.service --now

Open the firewall for HTTP traffic restart the firewall to apply the changes:

sudo firewall-cmd --add-service=http --permanent
 sudo firewall-cmd --reload

Check the availability from the internet by browsing <public IP addres> via a web browser. The Nginx dummy page has to appear. If not, check the nginx running: systemctl status nginx .

Assume the webserver is running well, so the next topic is to make us able to put some files to the server with FTP.

Posted in linux, OCI, Oracle/CentOS/RedHat, web | Leave a comment