Sunday, September 19, 2021

Passing an entire List to a Function

We are going to pass an entire list to a function.

    In [1]: numbers
    Out[1]: [10, 5, 3, 7, 4]

Defining a function which we going to pass the entire list to.  This function multiplies each of the list's element by 2.
    In [2]: def modify_elements(items):
    ...:     for i in range(len(items)):
    ...:         items[i] *= 2
    ...:

    In [3]: modify_elements(numbers)

    In [4]: numbers
    Out[4]: [20, 10, 6, 14, 8]

    In [5]:

Function modify_elemens' items parameter receives a reference to the original list, so the statement in the loop's suite modifies each element in the original list object.

Python built-in Function Enumerate

Using a built-in function Enumerate in Python to access an element's INDEX and VALUE.

Create a list with integers

    In [1]: numbers = [10,5,3,7,4]

    In [2]: type(numbers)
    Out[2]: list

    In [3]:

Apply built-in function Enumerate to numbers

    In [3]: new_numbers = enumerate(numbers)

    In [4]: new_numbers
    Out[4]: <enumerate at 0x233d866db80>

Convert it to list format|

    In [6]: list(new_numbers)
    Out[6]: [(0, 10), (1, 5), (2, 3), (3, 7), (4, 4)]

    In [7]:

Going to create a simple bar chart using the value in numbers

    In [1]: numbers = [10,5,3,7,4]

    In [2]: for index, value in enumerate(numbers):

       ...:     print(f'{index:>8}{value:>8}  {"|" * value}')
       ...:

        0      10  ||||||||||
        1       5  |||||
        2       3  |||
        3       7  |||||||
        4       4  ||||

      In [3]:

Remove duplicate from Python list

 This post is to show how to remove duplicate entries in a List.

Create an empty list and we name it new_list.

In [1]: new_list = []

We iterate a range of integers and assign it to this new_list.

In [2]: for items in range(1,6):
   ...:     new_list += [items]
   ...:

Show what is inside this list

In [3]: new_list
Out[3]: [1, 2, 3, 4, 5]

We iterate another range of integers where there are duplicates into the same new_list

In [4]: for new_items in range(7):
   ...:     new_list += [new_items]
   ...:

This show the new_list has duplicate entries

In [5]: new_list
Out[5]: [1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]

Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
Then, convert the dictionary back into a list.

In [6]: new_list = list(dict.fromkeys(new_list))

In [7]: new_list
Out[7]: [1, 2, 3, 4, 5, 0, 6]

In [8]:

Sunday, April 25, 2021

Python 3 - Nested Control Statement

Learning nested control statement in Python 3.
Taking notes on what I missed during the learning process.

1.  Remember to add comma when displaying str and variable together.
     Example: print ('Passed: ',(pass_counter))
2.  Learn to use nested control such as if...else within the for loop.
3.  Use for statement and the range function is appropriate when we know in advance that there are 10 exam results.

# fig03_03.py
"""Using nested control statements to analyze examination results."""

# initialize variables
pass_counter = 0 # number of passes
fail_counter = 0 # number of failures

# process 10 students
# exam_grades = int(input('Enter 1 for pass or 2 for fail: '))
for student in range(10):
    # get one exam result
    result = int(input('Enter result (1=pass, 2=fail): '))
    
    if result == 1:
        pass_counter += 1
    else:
        fail_counter += 1

# termination phase
print('Passed: ',(pass_counter))
print('Failed: ',(fail_counter))
    
if pass_counter > 8:
    print ('Bonus to instructor')

Saturday, December 19, 2020

From GRUB 2 to Login Process

Here is the basic overview of the boot process after the GRUB 2 bootloader finds the kernel.  The messages associated with the kernel provide a step-by-step view of the process.

The loading of Linux depends on a temporary filesystem, known as the initial RAM disk.
Once the boot process is complete, control is given to systemd, known as the first process.

In here we will describe the contents of systemd in detail, through the configuration of units and targets.

Note:
Most of Linux distros have replaced Upstart and SysVinit with the new systemd service manager.

Kernels and the Initial RAM Disk

After you select a kernel from the GRUB 2 configuration menu, Linux hands over boot responsibilities to the kernel with the help of the initial RAM disk, also known by its filename in the /boot directory, initramfs.
During the boot process, Linux loads that initramfs into your RAM.  Linux then loads hardware drivers and starts the first process, systemd.
Next, systemd activates all the system units for the initrd.target and mounts the root filesystem under /sysroot
Finally systemd restarts itself in the new root directory and activates all units for the default target.

To learn more, after logging in, you can review these messages in the /var/log/dmesg file or by running the dmesg command.


The First Process, Targets, and Units
Kernel continues the boot process by calling the 1st process, systemd.  In RHEL 7, the legacy init process is configured with a symbolic link to systemd.
Units are the basic building blocks of systemd.  The most common are service units, which have a .service extension and activate a system service.
The following command will show a list of all service units:
    # systemctl list-units --type=service --all

The example command below shows sshd services:
    # systemctl list-units --type=service --all | egrep -i sshd






Wednesday, December 9, 2020

CentOS 8 - Recover the Root Password

 This exercise shows the steps required to reset a lost password for the root user.  For this exercise, we use the following command to change the root password to a random string.
# pwmake 128 | passwd --stdin root



The next thing is to reboot the server.  When you see the GRUB menu press E to edit the current menu entry.  Scroll down until the line starting with linux.  Press CTRL-E or END to move to the end of the line, and then add the string rd.break.

Press CTRL-X to boot the system.


The rd.break directive interrupts the boot sequence before the root filesystem is properly mounted.  Confirm this by running ls /sysroot.  The output should look something below.

Remount the root /sysroot filesystem as read-write and change the root directory to /sysroot:
# mount -o remount, rw /sysroot
# chroot /sysroot

Follow by the passwd command to change the root password:
# passwd

Because SELinux is not running, the passwd command does not preserve  the context of the /etc/passwd file.  To ensure that the /etc/passwd file is labeled with the correct SELinux context, instruct Linux to relabel all files at the next boot with the following command:
# touch / .autorelabel

Type exit to close the chroot jail, and then type exit again to reboot the system.


Saturday, December 5, 2020

SSH in RHEL 8

 Configuring SSH
- Hardening the SSH server
- Using other useful sshd options
- Configuring Key-Based authentication with passphrases

Hardening the SSH Server
Dictionary attacks are common against an SSH server. 
The default SSH settings on Linux server uses port 22 and the Linux box has a root account. 

Fortunately, you can take some measures to protect SSH servers against these kinds of attacks:
- Disable root login
- Disable password login
- Configure a nondefault port for SSH to listen on
- Allow specific users only to log in on SSH

Limiting Root Access
The Linux servers by default have root login enabled. 
Disabling root login is easy.
- Modify the PermitRootLogin parameter in /etc/ssh/sshd_config
- Reload
- Restart the service by running systemctl reload servicename command
- Some services pick up changes only after a systemctl restart servicename command

To log in to a remote server using ssh, use one of these commands:
ssh user@servername
ssh -l user servername

Configuring Alternative Ports
Linux server attacker can use port scan to scan all the 65,535 ports and most of the port scans focus on known ports only, and SSH port 22 is always among these ports.
To protect against port scans, you can configure SSH server to listen on another port.