Posted on Leave a comment

LaTeX typesetting part 2 (tables)

LaTeX offers a number of tools to create and customise tables, in this series we will be using the tabular and tabularx environment to create and customise tables.

Basic table

To create a table you simply specify the environment \begin{tabular}{columns}

\begin{tabular}{c|c} Release &;\;Codename \\ \hline Fedora Core 1 &;Yarrow \\ Fedora Core 2 &;Tettnang \\ Fedora Core 3 &;Heidelberg \\ Fedora Core 4 &;Stentz \\ \end{tabular}

In the above example “{c|c}” in the curly bracket refers to the position of the text in the column. The below table summarises the positional argument together with the description.

Position Argument
c Position text in the centre
l Position text left-justified
r Position text right-justified
p{width} Align the text at the top of the cell
m{width} Align the text in the middle of the cell
b{width} Align the text at the bottom of the cell

Both m{width} and b{width} requires the array package to be specified in the preamble.

Using the example above, let us breakdown the important points used and describe a few more options that you will see in this series

Option Description
&; Defines each cell, the ampersand is only used from the second column
\ This terminates the row and start a new row
| Specifies the vertical line in the table (optional)
\hline Specifies the horizontal line (optional)
*{num}{form} This is handy when you have many columns and is an efficient way of limiting the repetition
|| Specifies the double vertical line

Customizing a table

Now that some of the options available are known, let us create a table using the options described in the previous section.

\begin{tabular}{*{3}{|l|}}
\hline \textbf{Version} &;\textbf{Code name} &;\textbf{Year released} \\
\hline Fedora 6 &;Zod &;2006 \\ \hline Fedora 7 &;Moonshine &;2007 \\ \hline Fedora 8 &;Werewolf &;2007 \\
\hline
\end{tabular}

Managing long text

With LaTeX, if there are many texts in a column it will not be formatted well and does not look presentable.

The below example shows how long text is formatted, we will use “blindtext” in the preamble so that we can produce sample text.

\begin{tabular}{|l|l|}\hline Summary &;Description \\ \hline Test &;\blindtext \\
\end{tabular}

As you can see the text exceeds the page width; however, there are a couple of options to overcome this challenge.

  • Specify the column width, for example, m{5cm}
  • Utilise the tabularx environment, this requires tabularx package in the preamble.

Managing long text with column width

By specifying the column width the text will be wrapped into the width as shown in the example below.

\begin{tabular}{|l|m{14cm}|} \hline Summary &;Description \\ \hline Test &;\blindtext \\ \hline
\end{tabular}\vspace{3mm}

Managing long text with tabularx

Before we can leverage tabularx we need to add it in the preamble. Tabularx takes the following example

**\begin{tabularx}{width}{columns}** \begin{tabularx}{\textwidth}{|l|X|} \hline
Summary &; Tabularx Description\\ \hline
Text &;\blindtext \\ \hline
\end{tabularx}

Notice that the column that we want the long text to be wrapped has a capital “X” specified.

Multi-row and multi-column

There are times when you will need to merge rows and/or column. This section describes how it is accomplished. To use multi-row and multi-column add multi-row to the preamble.

Multirow

Multirow takes the following argument \multirow{number_of_rows}{width}{text}, let us look at the below example.

\begin{tabular}{|l|l|}\hline Release &;Codename \\ \hline Fedora Core 4 &Stentz \\ \hline \multirow{2}{*}{MultiRow} &;Fedora 8 \\ &;Werewolf \\ \hline
\end{tabular}

In the above example, two rows were specified, the ‘*’ tells LaTeX to automatically manage the size of the cell.

Multicolumn

Multicolumn argument is \multicolumn{number_of_columns}{cell_position}{text}, below example demonstrates multicolumn.

\begin{tabular}{|l|l|l|}\hline Release &;Codename &;Date \\ \hline Fedora Core 4 &;Stentz &;2005 \\ \hline \multicolumn{3}{|c|}{Mulit-Column} \\ \hline
\end{tabular}

Working with colours

Colours can be assigned to the text, an individual cell or the entire row. Additionally, we can configure alternating colours for each row.

Before we can add colour to our tables we need to include \usepackage[table]{xcolor} into the preamble. We can also define colours using the following colour reference LaTeX Colour or by adding an exclamation after the colour prefixed by the shade from 0 to 100. For example, gray!30

\definecolor{darkblue}{rgb}{0.0, 0.0, 0.55}
\definecolor{darkgray}{rgb}{0.66, 0.66, 0.66}

Below example demonstrate this a table with alternate colours, \rowcolors take the following options \rowcolors{row_start_colour}{even_row_colour}{odd_row_colour}.

\rowcolors{2}{darkgray}{gray!20}
\begin{tabular}{c|c} Release &;Codename \\ \hline Fedora Core 1 &;Yarrow \\ Fedora Core 2 &;Tettnang \\ Fedora Core 3 &;Heidelberg \\ Fedora Core 4 &;Stentz \\
\end{tabular}

In addition to the above example, \rowcolor can be used to specify the colour of each row, this method works best when there are multi-rows. The following examples show the impact of using the \rowcolours with multi-row and how to work around it.

As you can see the multi-row is visible in the first row, to fix this we have to do the following.

\begin{tabular}{|l|l|}\hline \rowcolor{darkblue}\textsc{\color{white}Release} &;\textsc{\color{white}Codename} \\ \hline \rowcolor{gray!10}Fedora Core 4 &;Stentz \\ \hline \rowcolor{gray!40}&;Fedora 8 \\ \rowcolor{gray!40}\multirow{-2}{*}{Multi-Row} &;Werewolf \\ \hline
\end{tabular}

Let us discuss the changes that were implemented to resolve the multi-row with the alternate colour issue.

  • The first row started above the multi-row
  • The number of rows was changed from 2 to -2, which means to read from the line above
  • \rowcolor was specified for each row, more importantly, the multi-rows must have the same colour so that you can have the desired results.

One last note on colour, to change the colour of a column you need to create a new column type and define the colour. The example below illustrates how to define the new column colour.

\newcolumntype{g}{>{\columncolor{darkblue}}l} 

Let’s break it down:

  • \newcolumntype{g}: defines the letter g as the new column
  • {>{\columncolor{darkblue}}l}: here we select our desired colour, and l tells the column to be left-justified, this can be subsitued with c or r
\begin{tabular}{g|l} \textsc{Release} &;\textsc{Codename} \\ \hline Fedora Core 4 &;Stentz \\ &Fedora 8 \\ \multirow{-2}{*}{Multi-Row} &;Werewolf \\ \end{tabular}\

Landscape table

There may be times when your table has many columns and will not fit elegantly in portrait. With the rotating package in preamble you will be able to create a sideways table. The below example demonstrates this.

For the landscape table, we will use the sidewaystable environment and add the tabular environment within it, we also specified additional options.

  • \centering to position the table in the centre of the page
  • \caption{} to give our table a name
  • \label{} this enables us to reference the table in our document
\begin{sidewaystable}
\centering
\caption{Sideways Table}
\label{sidetable}
\begin{tabular}{ll} \rowcolor{darkblue}\textsc{\color{white}Release} &;\textsc{\color{white}Codename} \\ \rowcolor{gray!10}Fedora Core 4 &;Stentz \\ \rowcolor{gray!40} &;Fedora 8 \\ \rowcolor{gray!40}\multirow{-2}{*}{Multi-Row} &;Werewolf \\ \end{tabular}\vspace{3mm}
\end{sidewaystable}

Lists in tables

To include a list into a table you can use tabularx and include the list in the column where the X is specified. Another option will be to use tabular but you must specify the column width.

List in tabularx

\begin{tabularx}{\textwidth}{|l|X|} \hline Fedora Version &;Editions \\ \hline Fedora 32 &;\begin{itemize}[noitemsep] \item CoreOS \item Silverblue \item IoT \end{itemize} \\ \hline
\end{tabularx}\vspace{3mm}

List in tabular

\begin{tabular}{|l|m{6cm}|}\hline Fedora Version &;Editions \\ \hline Fedora 32 &;\begin{itemize}[noitemsep] \item CoreOS \item Silverblue \item IoT \end{itemize} \\ \hline
\end{tabular}

Conclusion

LaTeX offers many ways to customise your table with tabular and tabularx, you can also add both tabular and tabularx within the table environment (\begin\table) to add the table name and to position the table.

The packages used in this series are:

\usepackage{fullpage}
\usepackage{blindtext} % add demo text
\usepackage{array} % used for column positions
\usepackage{tabularx} % adds tabularx which is used for text wrapping
\usepackage{multirow} % multi-row and multi-colour support
\usepackage[table]{xcolor} % add colour to the columns \usepackage{rotating} % for landscape/sideways tables

Additional Reading

This was an intermediate lesson on tables. For more advanced information about tables and LaTex in general, you can go to the LaTeX Wiki.

Posted on Leave a comment

Internet connection sharing with NetworkManager

NetworkManager is the network configuration daemon used on Fedora and many other distributions. It provides a consistent way to configure network interfaces and other network-related aspects on a Linux machine. Among many other features, it provides a Internet connection sharing functionality that can be very useful in different situations.

For example, suppose you are in a place without Wi-Fi and want to share your laptop’s mobile data connection with friends. Or maybe you have a laptop with broken Wi-Fi and want to connect it via Ethernet cable to another laptop; in this way the first laptop become able to reach the Internet and maybe download new Wi-Fi drivers.

In cases like these it is useful to share Internet connectivity with other devices. On smartphones this feature is called “Tethering” and allows sharing a cellular connection via Wi-Fi, Bluetooth or a USB cable.

This article shows how the connection sharing mode offered by NetworkManager can be set up easily; it addition, it explains how to configure some more advanced features for power users.

How connection sharing works

The basic idea behind connection sharing is that there is an upstream interface with Internet access and a downstream interface that needs connectivity. These interfaces can be of a different type—for example, Wi-Fi and Ethernet.

If the upstream interface is connected to a LAN, it is possible to configure our computer to act as a bridge; a bridge is the software version of an Ethernet switch. In this way, you “extend” the LAN to the downstream network. However this solution doesn’t always play well with all interface types; moreover, it works only if the upstream network uses private addresses.

A more general approach consists in assigning a private IPv4 subnet to the downstream network and turning on routing between the two interfaces. In this case, NAT (Network Address Translation) is also necessary. The purpose of NAT is to modify the source of packets coming from the downstream network so that they look as if they originate from your computer.

It would be inconvenient to configure manually all the devices in the downstream network. Therefore, you need a DHCP server to assign addresses automatically and configure hosts to route all traffic through your computer. In addition, in case the sharing happens through Wi-Fi, the wireless network adapter must be configured as an access point.

There are many tutorials out there explaining how to achieve this, with different degrees of difficulty. NetworkManager hides all this complexity and provides a shared mode that makes this configuration quick and convenient.

Configuring connection sharing

The configuration paradigm of NetworkManager is based on the concept of connection (or connection profile). A connection is a group of settings to apply on a network interface.

This article shows how to create and modify such connections using nmcli, the NetworkManager command line utility, and the GTK connection editor. If you prefer, other tools are available such as nmtui (a text-based user interface), GNOME control center or the KDE network applet.

A reasonable prerequisite to share Internet access is to have it available in the first place; this implies that there is already a NetworkManager connection active. If you are reading this, you probably already have a working Internet connection. If not, see this article for a more comprehensive introduction to NetworkManager.

The rest of this article assumes you already have a Wi-Fi connection profile configured and that connectivity must be shared over an Ethernet interface enp1s0.

To enable sharing, create a connection for interface enp1s0 and set the ipv4.method property to shared instead of the usual auto:

$ nmcli connection add type ethernet ifname enp1s0 ipv4.method shared con-name local

The shared IPv4 method does multiple things:

  • enables IP forwarding for the interface;
  • adds firewall rules and enables masquerading;
  • starts dnsmasq as a DHCP and DNS server.

NetworkManager connection profiles, unless configured otherwise, are activated automatically. The new connection you have added should be already active in the device status:

$ nmcli device
DEVICE         TYPE      STATE         CONNECTION
enp1s0         ethernet  connected     local
wlp4s0         wifi      connected     home-wifi

If that is not the case, activate the profile manually with nmcli connection up local.

Changing the shared IP range

Now look at how NetworkManager configured the downstream interface enp1s0:

$ ip -o addr show enp1s0
8: enp1s0 inet 10.42.0.1/24 brd 10.42.0.255 ...

10.42.0.1/24 is the default address set by NetworkManager for a device in shared mode. Addresses in this range are also distributed via DHCP to other computers. If the range conflicts with other private networks in your environment, change it by modifying the ipv4.addresses property:

$ nmcli connection modify local ipv4.addresses 192.168.42.1/24

Remember to activate again the connection profile after any change to apply the new values:

$ nmcli connection up local $ ip -o addr show enp1s0
8: enp1s0 inet 192.168.42.1/24 brd 192.168.42.255 ...

If you prefer using a graphical tool to edit connections, install the nm-connection-editor package. Launch the program and open the connection to edit; then select the Shared to other computers method in the IPv4 Settings tab. Finally, if you want to use a specific IP subnet, click Add and insert an address and a netmask.

Adding custom dnsmasq options

In case you want to further extend the dnsmasq configuration, you can add new configuration snippets in /etc/NetworkManager/dnsmasq-shared.d/. For example, the following configuration:

dhcp-option=option:ntp-server,192.168.42.1
dhcp-host=52:54:00:a4:65:c8,192.168.42.170

tells dnsmasq to advertise a NTP server via DHCP. In addition, it assigns a static IP to a client with a certain MAC.

There are many other useful options in the dnsmasq manual page. However, remember that some of them may conflict with the rest of the configuration; so please use custom options only if you know what you are doing.

Other useful tricks

If you want to set up sharing via Wi-Fi, you could create a connection in Access Point mode, manually configure the security, and then enable connection sharing. Actually, there is a quicker way, the hotspot mode:

$ nmcli device wifi hotspot [ifname $dev] [password $pw]

This does everything needed to create a functional access point with connection sharing. The interface and password options are optional; if they are not specified, nmcli chooses the first Wi-Fi device available and generates a random password. Use the ‘nmcli device wifi show-password‘ command to display information for the active hotspot; the output includes the password and a text-based QR code that you can scan with a phone:

What about IPv6?

Until now this article discussed sharing IPv4 connectivity. NetworkManager also supports sharing IPv6 connectivity through DHCP prefix delegation. Using prefix delegation, a computer can request additional IPv6 prefixes from the DHCP server. Those public routable addresses are assigned to local networks via Router Advertisements. Again, NetworkManager makes all this easier through the shared IPv6 mode:

$ nmcli connection modify local ipv6.method shared

Note that IPv6 sharing requires support from the Internet Service Provider, which should give out prefix delegations through DHCP. If the ISP doesn’t provides delegations, IPv6 sharing will not work; in such case NM will report in the journal that no prefixes are available:

policy: ipv6-pd: none of 0 prefixes of wlp1s0 can be shared on enp1s0

Also, note that the Wi-Fi hotspot command described above only enables IPv4 sharing; if you want to also use IPv6 sharing you must edit the connection manually.

Conclusion

Remember, the next time you need to share your Internet connection, NetworkManager will make it easy for you.

If you have suggestions on how to improve this feature or any other feedback, please reach out to the NM community using the mailing list, the issue tracker or joining the #nm IRC channel on freenode.

Posted on Leave a comment

LaTeX Typesetting – Part 1 (Lists)

This series builds on the previous articles: Typeset your docs with LaTex and TeXstudio on Fedora and LaTeX 101 for beginners. This first part of the series is about LaTeX lists.

Types of lists

LaTeX lists are enclosed environments, and each item in the list can take a line of text to a full paragraph. There are three types of lists available in LaTeX. They are:

  • Itemized: unordered or bullet
  • Enumerated: ordered
  • Description: descriptive

Creating lists

To create a list, prefix each list item with the \item command. Precede and follow the list of items with the \begin{<type>} and \end{<type>} commands respectively where <type> is substituted with the type of the list as illustrated in the following examples.

Itemized list

\begin{itemize} \item Fedora \item Fedora Spin \item Fedora Silverblue
\end{itemize}

Enumerated list

\begin{enumerate} \item Fedora CoreOS \item Fedora Silverblue \item Fedora Spin
\end{enumerate}

Descriptive list

\begin{description} \item[Fedora 6] Code name Zod \item[Fedora 8] Code name Werewolf
\end{description}

Spacing list items

The default spacing can be customized by adding \usepackage{enumitem} to the preamble. The enumitem package enables the noitemsep option and the \itemsep command which you can use on your lists as illustrated below.

Using the noitemsep option

Enclose the noitemsep option in square brackets and place it on the \begin command as shown below. This option removes the default spacing.

\begin{itemize}[noitemsep] \item Fedora \item Fedora Spin \item Fedora Silverblue
\end{itemize}

Using the \itemsep command

The \itemsep command must be suffixed with a number to indicate how much space there should be between the list items.

\begin{itemize} \itemsep0.75pt \item Fedora Silverblue \item Fedora CoreOS
\end{itemize}

Nesting lists

LaTeX supports nested lists up to four levels deep as illustrated below.

Nested itemized lists

\begin{itemize}[noitemsep] \item Fedora Versions \begin{itemize} \item Fedora 8 \item Fedora 9 \begin{itemize} \item Werewolf \item Sulphur \begin{itemize} \item 2007-05-31 \item 2008-05-13 \end{itemize} \end{itemize} \end{itemize} \item Fedora Spin \item Fedora Silverblue
\end{itemize}

Nested enumerated lists

\begin{enumerate}[noitemsep] \item Fedora Versions \begin{enumerate} \item Fedora 8 \item Fedora 9 \begin{enumerate} \item Werewolf \item Sulphur \begin{enumerate} \item 2007-05-31 \item 2008-05-13 \end{enumerate} \end{enumerate} \end{enumerate} \item Fedora Spin \item Fedora Silverblue
\end{enumerate}

List style names for each list type

Enumerated Itemized
\alph* $\bullet$
\Alph* $\cdot$
\arabic* $\diamond$
\roman* $\ast$
\Roman* $\circ$
$-$

Default style by list depth

Level Enumerated Itemized
1 Number Bullet
2 Lowercase alphabet Dash
3 Roman numerals Asterisk
4 Uppercase alphabet Period

Setting list styles

The below example illustrates each of the different itemiszed list styles.

% Itemize style
\begin{itemize} \item[$\ast$] Asterisk \item[$\diamond$] Diamond \item[$\circ$] Circle \item[$\cdot$] Period \item[$\bullet$] Bullet (default) \item[--] Dash \item[$-$] Another dash
\end{itemize}

There are three methods of setting list styles. They are illustrated below. These methods are listed by priority; highest priority first. A higher priority will override a lower priority if more than one is defined for a list item.

List styling method 1 – per item

Enclose the name of the desired style in square brackets and place it on the \item command as demonstrated below.

% First method
\begin{itemize} \item[$\ast$] Asterisk \item[$\diamond$] Diamond \item[$\circ$] Circle \item[$\cdot$] period \item[$\bullet$] Bullet (default) \item[--] Dash \item[$-$] Another dash
\end{itemize}

List styling method 2 – on the list

Prefix the name of the desired style with label=. Place the parameter, including the label= prefix, in square brackets on the \begin command as demonstrated below.

% Second method
\begin{enumerate}[label=\Alph*.] \item Fedora 32 \item Fedora 31 \item Fedora 30
\end{enumerate}

List styling method 3 – on the document

This method changes the default style for the entire document. Use the \renewcommand to set the values for the labelitems. There is a different labelitem for each of the four label depths as demonstrated below.

% Third method
\renewcommand{\labelitemi}{$\ast$}
\renewcommand{\labelitemii}{$\diamond$}
\renewcommand{\labelitemiii}{$\bullet$}
\renewcommand{\labelitemiv}{$-$}

Summary

LaTeX supports three types of lists. The style and spacing of each of the list types can be customized. More LaTeX elements will be explained in future posts.

Additional reading about LaTeX lists can be found here: LaTeX List Structures

Posted on Leave a comment

Fedora 32: Simple Local File-Sharing with Samba

Sharing files with Fedora 32 using Samba is cross-platform, convenient, reliable, and performant.

What is ‘Samba’?

Samba is a high-quality implementation of Server Message Block protocol (SMB). Originally developed by Microsoft for connecting windows computers together via local-area-networks, it is now extensively used for internal network communications.

Apple used to maintain it’s own independent file sharing called “Apple Filing Protocol (AFP)“, however in recent times, it also has also switched to SMB.

In this guide we provide the minimal instructions to enable:

  • Public Folder Sharing (Both Read Only and Read Write)
  • User Home Folder Access
Note about this guide: The convention '~]$' for a local user command prompt, and '~]#' for a super user prompt will be used.

Public Sharing Folder

Having a shared public place where authenticated users on an internal network can access files, or even modify and change files if they are given permission, can be very convenient. This part of the guide walks through the process of setting up a shared folder, ready for sharing with Samba.

Please Note: This guide assumes the public sharing folder is on a Modern Linux Filesystem; other filesystems such as NTFS or FAT32 will not work. Samba uses POSIX Access Control Lists (ACLs). For those who wish to learn more about Access Control Lists, please consider reading the documentation: "Red Hat Enterprise Linux 7: System Administrator's Guide: Chapter 5. Access Control Lists", as it likewise applies to Fedora 32. In General, this is only an issue for anyone who wishes to share a drive or filesystem that was created outside of the normal Fedora Installation process. (such as a external hard drive). It is possible for Samba to share filesystem paths that do not support POSIX ACLs, however this is out of the scope of this guide.

Create Folder

For this guide the /srv/public/ folder for sharing will be used.

The /srv/ directory contains site-specific data served by a Red Hat Enterprise Linux system. This directory gives users the location of data files for a particular service, such as FTP, WWW, or CVS. Data that only pertains to a specific user should go in the /home/ directory.

Red Hat Enterprise Linux 7, Storage Administration Guide: Chapter 2. File System Structure and Maintenance: 2.1.1.8. The /srv/ Directory

Make the Folder (will provide an error if the folder already exists).
~]# mkdir --verbose /srv/public Verify folder exists:
~]$ ls --directory /srv/public Expected Output:
/srv/public

Set Filesystem Security Context

To have read and write access to the public folder the public_content_rw_t security context will be used for this guide. Those wanting read only may use: public_content_t.

Label files and directories that have been created with the public_content_rw_t type to share them with read and write permissions through vsftpd. Other services, such as Apache HTTP Server, Samba, and NFS, also have access to files labeled with this type. Remember that booleans for each service must be enabled before they can write to files labeled with this type.

Red Hat Enterprise Linux 7, SELinux User’s and Administrator’s Guide: Chapter 16. File Transfer Protocol: 16.1. Types: public_content_rw_t

Add /srv/public as “public_content_rw_t” in the system’s local filesystem security context customization registry:

Add new security filesystem security context:
~]# semanage fcontext --add --type public_content_rw_t "/srv/public(/.*)?" Verifiy new security filesystem security context:
~]# semanage fcontext --locallist --list Expected Output: (should include)
/srv/public(/.*)? all files system_u:object_r:public_content_rw_t:s0

Now that the folder has been added to the local system’s filesystem security context registry; The restorecon command can be used to ‘restore’ the context to the folder:

Restore security context to the /srv/public folder:
$~]# restorecon -Rv /srv/public Verify security context was correctly applied:
~]$ ls --directory --context /srv/public/ Expected Output:
unconfined_u:object_r:public_content_rw_t:s0 /srv/public/

User Permissions

Creating the Sharing Groups

To allow a user to either have read only, or read and write accesses to the public share folder create two new groups that govern these privileges: public_readonly and public_readwrite.

User accounts can be granted access to read only, or read and write by adding their account to the respective group (and allow login via Samba creating a smb password). This process is demonstrated in the section: “Test Public Sharing (localhost)”.

Create the public_readonly and public_readwrite groups:
~]# groupadd public_readonly
~]# groupadd public_readwrite Verify successful creation of groups:
~]$ getent group public_readonly public_readwrite Expected Output: (Note: x:1...: number will probability differ on your System)
public_readonly:x:1009:
public_readwrite:x:1010:

Set Permissions

Now set the appropriate user permissions to the public shared folder:

Set User and Group Permissions for Folder:
~]# chmod --verbose 2700 /srv/public
~]# setfacl -m group:public_readonly:r-x /srv/public
~]# setfacl -m default:group:public_readonly:r-x /srv/public
~]# setfacl -m group:public_readwrite:rwx /srv/public
~]# setfacl -m default:group:public_readwrite:rwx /srv/public Verify user permissions have been correctly applied:
~]$ getfacl --absolute-names /srv/public Expected Output:
file: /srv/public
owner: root
group: root
flags: -s-
user::rwx
group::---
group:public_readonly:r-x
group:public_readwrite:rwx
mask::rwx
other::---
default:user::rwx
default:group::---
default:group:public_readonly:r-x
default:group:public_readwrite:rwx
default:mask::rwx
default:other::---

Samba

Installation

~]# dnf install samba

Hostname (systemwide)

Samba will use the name of the computer when sharing files; it is good to set a hostname so that the computer can be found easily on the local network.

View Your Current Hostname:
~]$ hostnamectl status

If you wish to change your hostname to something more descriptive, use the command:

Modify your system's hostname (example):
~]# hostnamectl set-hostname "simple-samba-server"
For a more complete overview of the hostnamectl command, please read the previous Fedora Magazine Article: "How to set the hostname on Fedora".

Firewall

Configuring your firewall is a complex and involved task. This guide will just have the most minimal manipulation of the firewall to enable Samba to pass through.

For those who are interested in learning more about configuring firewalls; please consider reading the documentation: "Red Hat Enterprise Linux 8: Securing networks: Chapter 5. Using and configuring firewall", as it generally applies to Fedora 32 as well.
Allow Samba access through the firewall:
~]# firewall-cmd --add-service=samba --permanent
~]# firewall-cmd --reload Verify Samba is included in your active firewall:
~]$ firewall-cmd --list-services Output (should include):
samba

Configuration

Remove Default Configuration

The stock configuration that is included with Fedora 32 is not required for this simple guide. In particular it includes support for sharing printers with Samba.

For this guide make a backup of the default configuration and create a new configuration file from scratch.

Create a backup copy of the existing Samba Configuration:
~]# cp --verbose --no-clobber /etc/samba/smb.conf /etc/samba/smb.conf.fedora0 Empty the configuration file:
~]# > /etc/samba/smb.conf

Samba Configuration

Please Note: This configuration file does not contain any global definitions; the defaults provided by Samba are good for purposes of this guide.
Edit the Samba Configuration File with Vim:
~]# vim /etc/samba/smb.conf

Add the following to /etc/samba/smb.conf file:

# smb.conf - Samba Configuration File # The name of the share is in square brackets [],
# this will be shared as //hostname/sharename # There are a three exceptions:
# the [global] section;
# the [homes] section, that is dynamically set to the username;
# the [printers] section, same as [homes], but for printers. # path: the physical filesystem path (or device)
# comment: a label on the share, seen on the network.
# read only: disable writing, defaults to true. # For a full list of configuration options,
# please read the manual: "man smb.conf". [global] [public]
path = /srv/public
comment = Public Folder
read only = No

Write Permission

By default Samba is not granted permission to modify any file of the system. Modify system’s security configuration to allow Samba to modify any filesystem path that has the security context of public_content_rw_t.

For convenience, Fedora has a built-in SELinux Boolean for this purpose called: smbd_anon_write, setting this to true will enable Samba to write in any filesystem path that has been set to the security context of public_content_rw_t.

For those who are wishing Samba only have a read-only access to their public sharing folder, they may choose skip this step and not set this boolean.

There are many more SELinux boolean that are available for Samba. For those who are interested, please read the documentation: "Red Hat Enterprise Linux 7: SELinux User's and Administrator's Guide: 15.3. Samba Booleans", it also apply to Fedora 32 without any adaptation.
Set SELinux Boolean allowing Samba to write to filesystem paths set with the security context public_content_rw_t:
~]# setsebool -P smbd_anon_write=1 Verify bool has been correctly set:
$ getsebool smbd_anon_write Expected Output:
smbd_anon_write --> on

Samba Services

The Samba service is divided into two parts that we need to start.

Samba ‘smb’ Service

The Samba “Server Message Block” (SMB) services is for sharing files and printers over the local network.

Manual: “smbd – server to provide SMB/CIFS services to clients

Enable and Start Services

For those who are interested in learning more about configuring, enabling, disabling, and managing services, please consider studying the documentation: "Red Hat Enterprise Linux 7: System Administrator's Guide: 10.2. Managing System Services".
Enable and start smb and nmb services:
~]# systemctl enable smb.service
~]# systemctl start smb.service Verify smb service:
~]# systemctl status smb.service

Test Public Sharing (localhost)

To demonstrate allowing and removing access to the public shared folder, create a new user called samba_test_user, this user will be granted permissions first to read the public folder, and then access to read and write the public folder.

The same process demonstrated here can be used to grant access to your public shared folder to other users of your computer.

The samba_test_user will be created as a locked user account, disallowing normal login to the computer.

Create 'samba_test_user', and lock the account.
~]# useradd samba_test_user
~]# passwd --lock samba_test_user Set a Samba Password for this Test User (such as 'test'):
~]# smbpasswd -a samba_test_user

Test Read Only access to the Public Share:

Add samba_test_user to the public_readonly group:
~]# gpasswd --add samba_test_user public_readonly Login to the local Samba Service (public folder):
~]$ smbclient --user=samba_test_user //localhost/public First, the ls command should succeed,
Second, the mkdir command should not work,
and finally, exit:
smb: \> ls
smb: \> mkdir error
smb: \> exit Remove samba_test_user from the public_readonly group:
gpasswd --delete samba_test_user public_readonly

Test Read and Write access to the Public Share:

Add samba_test_user to the public_readwrite group:
~]# gpasswd --add samba_test_user public_readwrite Login to the local Samba Service (public folder):
~]$ smbclient --user=samba_test_user //localhost/public First, the ls command should succeed,
Second, the mkdir command should work,
Third, the rmdir command should work,
and finally, exit:
smb: \> ls
smb: \> mkdir success
smb: \> rmdir success
smb: \> exit Remove samba_test_user from the public_readwrite group:
~]# gpasswd --delete samba_test_user public_readwrite

After testing is completed, for security, disable the samba_test_user‘s ability to login in via samba.

Disable samba_test_user login via samba:
~]# smbpasswd -d samba_test_user

Home Folder Sharing

In this last section of the guide; Samba will be configured to share a user home folder.

For example: If the user bob has been registered with smbpasswd, bob’s home directory /home/bob, would become the share //server-name/bob.

This share will only be available for bob, and no other users.

This is a very convenient way of accessing your own local files; however naturally it carries at a security risk.

Setup Home Folder Sharing

Give Samba Permission for Public Folder Sharing

Set SELinux Boolean allowing Samba to read and write to home folders:
~]# setsebool -P samba_enable_home_dirs=1 Verify bool has been correctly set:
$ getsebool samba_enable_home_dirs Expected Output:
samba_enable_home_dirs --> on

Add Home Sharing to the Samba Configuration

Append the following to the systems smb.conf file:

# The home folder dynamically links to the user home. # If 'bob' user uses Samba:
# The homes section is used as the template for a new virtual share: # [homes]
# ... (various options) # A virtual section for 'bob' is made:
# Share is modified: [homes] -> [bob]
# Path is added: path = /home/bob
# Any option within the [homes] section is appended. # [bob]
# path = /home/bob
# ... (copy of various options) # here is our share,
# same as is included in the Fedora default configuration. [homes] comment = Home Directories valid users = %S, %D%w%S browseable = No read only = No inherit acls = Yes

Reload Samba Configuration

Tell Samba to reload it's configuration:
~]# smbcontrol all reload-config

Test Home Directory Sharing

Switch to samba_test_user and create a folder in it's home directory:
~]# su samba_test_user
samba_test_user:~]$ cd ~
samba_test_user:~]$ mkdir --verbose test_folder
samba_test_user:~]$ exit Enable samba_test_user to login via Samba:
~]# smbpasswd -e samba_test_user Login to the local Samba Service (samba_test_user home folder):
$ smbclient --user=samba_test_user //localhost/samba_test_user Test (all commands should complete without error):
smb: \> ls
smb: \> ls test_folder
smb: \> rmdir test_folder
smb: \> mkdir home_success
smb: \> rmdir home_success
smb: \> exit Disable samba_test_user from login in via Samba:
~]# smbpasswd -d samba_test_user
Posted on Leave a comment

Using data from spreadsheets in Fedora with Python

Python is one of the most popular and powerful programming languages available. Because it’s free and open source, it’s available to everyone — and most Fedora systems come with the language already installed. Python is useful for a wide variety of tasks, but among them is processing comma-separated value (CSV) data. CSV files often start off life as tables or spreadsheets. This article shows how to get started working with CSV data in Python 3.

CSV data is precisely what it sounds like. A CSV file includes one row of data at a time, with data values separated by commas. Each row is defined by the same fields. Short CSV files are often easily read and understood. But longer data files, or those with more fields, may be harder to parse with the naked eye, so computers work better in those cases.

Here’s a simple example where the fields are Name, Email, and Country. In this example, the CSV data includes a field definition as the first row, although that is not always the case.

Name,Email,Country
John Q. Smith,[email protected],USA
Petr Novak,[email protected],CZ
Bernard Jones,[email protected],UK

Reading CSV from spreadsheets

Python helpfully includes a csv module that has functions for reading and writing CSV data. Most spreadsheet applications, both native like Excel or Numbers, and web-based such as Google Sheets, can export CSV data. In fact, many other services that can publish tabular reports will also export as CSV (PayPal for instance).

The Python csv module has a built in reader method called DictReader that can deal with each data row as an ordered dictionary (OrderedDict). It expects a file object to access the CSV data. So if our file above is called example.csv in the current directory, this code snippet is one way to get at this data:

f = open('example.csv', 'r')
from csv import DictReader
d = DictReader(f)
data = []
for row in d: data.append(row)

Now the data object in memory is a list of OrderedDict objects :

[OrderedDict([('Name', 'John Q. Smith'), ('Email', '[email protected]'), ('Country', 'USA')]), OrderedDict([('Name', 'Petr Novak'), ('Email', '[email protected]'), ('Country', 'CZ')]), OrderedDict([('Name', 'Bernard Jones'), ('Email', '[email protected]'), ('Country', 'UK')])]

Referencing each of these objects is easy:

>>> print(data[0]['Country'])
USA
>>> print(data[2]['Email'])
[email protected]

By the way, if you have to deal with a CSV file with no header row of field names, the DictReader class lets you define them. In the example above, add the fieldnames argument and pass a sequence of the names:

d = DictReader(f, fieldnames=['Name', 'Email', 'Country'])

A real world example

I recently wanted to pick a random winner from a long list of individuals. The CSV data I pulled from spreadsheets was a simple list of names and email addresses.

Fortunately, Python also has a helpful random module good for generating random values. The randrange function in the Random class from that module was just what I needed. You can give it a regular range of numbers — like integers — and a step value between them. The function then generates a random result, meaning I could get a random integer (or row number!) back within the total number of rows in my data.

So this small program worked well:

from csv import DictReader
from random import Random d = DictReader(open('mydata.csv'))
data = []
for row in d: data.append(row) r = Random()
winner = data[r.randrange(0, len(data), 1)]
print('The winner is:', winner['Name'])
print('Email address:', winner['Email'])

Obviously this example is extremely simple. Spreadsheets themselves include sophisticated ways to analyze data. However, if you want to do something outside the realm of your spreadsheet app, Python may be just the trick!


Photo by Isaac Smith on Unsplash.

Posted on Leave a comment

Control the firewall at the command line

A network firewall is more or less what it sounds like: a protective barrier that prevents unwanted network transmissions. They are most frequently used to prevent outsiders from contacting or using network services on a system. For instance, if you’re running a laptop at school or in a coffee shop, you probably don’t want strangers poking around on it.

Every Fedora system has a firewall built in. It’s part of the network functions in the Linux kernel inside. This article shows you how to change its settings using firewall-cmd.

Network basics

This article can’t teach you everything about computer networks. But a few basics suffice to get you started.

Any computer on a network has an IP address. Think of this just like a mailing address that allows correct routing of data. Each computer also has a set of ports, numbered 0-65535. These are not physical ports; instead, you can think of them as a set of connection points at the address.

In many cases, the port is a standard number or range depending on the application expected to answer. For instance, a web server typically reserves port 80 for non-secure HTTP communications, and/or 443 for secure HTTPS. The port numbers under 1024 are reserved for system and well-known purposes, ports 1024-49151 are registered, and ports 49152 and above are usually ephemeral (used only for a short time).

Each of the two most common protocols for Internet data transfer, TCP and UDP, have this set of ports. TCP is used when it’s important that all data be received and, if it arrives out of order, reassembled in the right order. UDP is used for more time-sensitive services that can withstand losing some data.

An application running on the system, such as a web server, reserves one or more ports (as seen above, 80 and 443 for example). Then during network communication, a host establishes a connection between a source address and port, and the destination address and port.

A network firewall can block or permit transmissions of network data based on rules like address, port, or other criteria. The firewall-cmd utility lets you interact with the rule set to view or change how the firewall works.

Firewall zones

To verify the firewall is running, use this command with sudo. (In fairness, you can run firewall-cmd without the sudo command in environments where PolicyKit is running.)

$ sudo firewall-cmd --state
running

The firewalld service supports any number of zones. Each zone can have its own settings and rules for protection. In addition, each network interface can be placed in any zone individually The default zone for an external facing interface (like the wifi or wired network card) on a Fedora Workstation is the FedoraWorkstation zone.

To see what zones are active, use the –get-active-zones flag. On this system, there are two network interfaces, a wired Ethernet card wlp2s0 and a virtualization (libvirt) bridge interface virbr0:

$ sudo firewall-cmd --get-active-zones
FedoraWorkstation interfaces: wlp2s0
libvirt interfaces: virbr0

To see the default zone, or all the defined zones:

$ sudo firewall-cmd --get-default-zone
FedoraWorkstation
$ sudo firewall-cmd --get-zones
FedoraServer FedoraWorkstation block dmz drop external home internal libvirt public trusted work

To see the services the firewall is allowing other systems to access in the default zone, use the –list-services flag. Here is an example from a customized system; you may see something different.

$ sudo firewall-cmd --list-services
dhcpv6-client mdns samba-client ssh

This system has four services exposed. Each of these has a well-known port number. The firewall recognizes them by name. For instance, the ssh service is associated with port 22.

To see other port settings for the firewall in the current zone, use the –list-ports flag. By the way, you can always declare the zone you want to check:

$ sudo firewall-cmd --list-ports --zone=FedoraWorkstation
1025-65535/udp 1025-65535/tcp

This shows that ports 1025 and above (both UDP and TCP) are open by default.

Changing zones, ports, and services

The above setting is a design decision.* It ensures novice users can use network facing applications they install. If you know what you’re doing and want a more protective default, you can move the interface to the FedoraServer zone, which prohibits any ports not explicitly allowed. (Warning: if you’re using the host via the network, you may break your connection — meaning you’ll have to go to that box physically to make further changes!)

$ sudo firewall-cmd --change-interface=<ifname> --zone=FedoraServer
success

* This article is not the place to discuss that decision, which went through many rounds of review and debate in the Fedora community. You are welcome to change settings as needed.

If you want to open a well-known port that belongs to a service, you can add that service to the default zone (or use –zone to adjust a different zone). You can add more than one at once. This example opens up the well-known ports for your web server for both HTTP and HTTPS traffic, on ports 80 and 443:

$ sudo firewall-cmd --add-service=http --add-service=https
success

Not all services are defined, but many are. To see the whole list, use the –get-services flag.

If you want to add specific ports, you can do that by number and protocol as well. (You can also combine –add-service and –add-port flags, as many as necessary.) This example opens up the UDP service for a network boot service:

$ sudo firewall-cmd --add-port=67/udp
success

Important: If you want your changes to be effective after you reboot your system or restart the firewalld service, you must add the –permanent flag to your commands. The examples here only change the firewall until one of those events next happens.

These are just some of the many functions of the firewall-cmd utility and the firewalld service. There is much more information on firewalld at the project’s home page that’s worth reading and trying out.


Photo by Jakob Braun on Unsplash.

Posted on Leave a comment

Connect your Google Drive to Fedora Workstation

There are plenty of cloud services available where you can store important documents. Google Drive is undoubtedly one of the most popular. It offers a matching set of applications like Docs, Sheets, and Slides to create content. But you can also store arbitrary content in your Google Drive. This article shows you how to connect it to your Fedora Workstation.

Adding an account

Fedora Workstation lets you add an account either after installation during first startup, or at any time afterward. To add your account during first startup, follow the prompts. Among them is a choice of accounts you can add:

Online account listing

Select Google and a login prompt appears for you to login, so use your Google account information.

Online account login dialog

Be aware this information is only transmitted to Google, not to the GNOME project. The next screen asks you to grant access, which is required so your system’s desktop can interact with Google. Scroll down to review the access requests, and choose Allow to proceed.

You can expect to receive notifications on mobile devices and Gmail that a new device — your system — accessed your Google account. This is normal and expected.

Online account access request dialog

If you didn’t do this at first startup, or you need to re-add your account, open the Settings tool, and select Online Accounts to add the account. The Settings tool is available through the dropdown at right side of the Top Bar (the “gear” icon), or by opening the Overview and typing settings. Then proceed as described above.

Using the Files app with Google Drive

Open the Files app (formerly known as nautilus). Locations the Files app can access appear on the left side. Locate your Google account in the list.

When you select this account, the Files app shows the contents of your Google drive. Some files can be opened using your Fedora Workstation local apps, such as sound files or LibreOffice-compatible files (including Microsoft Office docs). Other files, such as Google app files like Docs, Sheets, and Slides, open using your web browser and the corresponding app.

Remember that if the file is large, it will take some time to receive over the network so you can open it.

You can also copy and paste files in your Google Drive storage from or to other storage connected to your Fedora Workstation. You can also use the built in functions to rename files, create folders, and organize them.

Be aware that the Files app does not refresh contents in real time. If you add or remove files from other Google connected devices like your mobile phone or tablet, you may need to hit Ctrl+R to refresh the Files app view.


Photo by Beatriz Pérez Moya on Unsplash.

Posted on Leave a comment

Manage tasks and projects on Fedora with Taskwarrior

There are a multitude of applications to manage your todo list. One of these apps is Taskwarrior, it allows you to manage your task in the terminal without a GUI. This article will show you how to get started using it.

What is Taskwarrior?

Taskwarrior is CLI task manager and organizer. It is flexible, fast, and unobtrusive. It does its job then gets out of your way.

Taskwarrior uses $HOME/.taskrc and $HOME/.task to store your settings and tasks respectively.

Getting started with Taskwarrior

It’s easy to use the Taskwarrior to add your daily missions. These are some simple commands. To add tasks:

$ task add buy milk Created task 1. $ task add buy eggs Created task 2. $ task add bake cake Created task 3.

To list your tasks, you can use the task command on its own for the simplest listing:

$ task ID Age Description Urg 1 17s buy milk 0 2 14s buy eggs 0 3 11s bake cake 0 3 tasks.

To mark a task as complete, use the done keyword:

$ task 1 done Completed task 1 'buy milk'. Completed 1 task.
$ task 2 done Completed task 2 'buy eggs'. Completed 1 task.
$ task [task next] ID Age Description Urg 1 57s bake cake 0 1 task

Diving deeper into Taskwarrior

Priority management

Taskwarrior (task) is designed to help prioritize your tasks. To do this, task has multiple implicit and explicit variables it can use to determine an “Urgency” value.

Consider the following list.

$ task [task next] ID Age Description Urg 1 2min buy eggs 0 2 2min buy flour 0 3 2min bake cake 0 4 2min pay rent 0 5 3s install fedora 0 5 tasks

One could argue that paying your rent and installing Fedora have a higher priority than baking a cake. You can tell task about this by using the pri modifier.

$ task 4 mod pri:H Modifying task 4 'pay rent'. Modified 1 task.
$ task 5 mod pri:M Modifying task 5 'install fedora'. Modified 1 task.
$ task [task next] ID Age P Description Urg  4 4min H pay rent 6
 5 2min M install fedora 3.9 1 4min buy eggs 0 2 4min buy flour 0 3 4min bake cake 0 5 tasks

Rent is very important, it has a due date that we need to pay it by, such as within 3 days from the 1st of the month. You can tell task this by using the due modifier.

$ task 4 mod due:3rd Modifying task 4 'pay rent'. Modified 1 task.
$ task [task next] ID Age P Due Description Urg 4 12min H 2d pay rent 13.7 5 10min M install fedora 3.9 1 12min buy eggs 0 2 12min buy flour 0 3 12min bake cake 0 5 tasks
$ date Sat Feb 29 11:59:29 STD 2020

Because the 3rd of next month is nearby, the urgency value of rent has skyrocketed, and will continue to do so once we have reached and passed the due date.

However, not all tasks need to be done right away. Say for example you don’t want to worry about paying your rent until it is posted on the first of the month. You can tell taskwarrior about this using the wait modifier. (Hint: in the following example, som is short for “start of month,” one of the shortcuts taskwarrior understands.)

$ task 4 mod wait:som Modifying task 4 'pay rent'. Modified 1 task.
$ task [task next] ID Age P Description Urg 5 14min M install fedora 3.9 1 16min buy eggs 0 2 16min buy flour 0 3 16min bake cake 0 4 tasks

You will no longer be able to see the pay rent task until the start of the month. You can view waiting tasks by using task waiting:

$ task waiting ID Age P Wait Remaining Due Description 4 18min H 2020-03-01 11h 2020-03-03 pay rent 1 task

There are a few other modifiers you can define. Schedule and until will place a “start” date and remove a task after a date respectfully.

You may have tasks that require other tasks to be completed. To add a dependency for other tasks, use the dep modifier:

$ task [task next] ID Age P Description Urg 5 30min M install fedora 3.9 1 33min buy eggs 0 2 33min buy flour 0 3 33min bake cake 0 4 tasks
$ task 3 mod dep:1,2 Modifying task 3 'bake cake'. Modified 1 task. $ task [task next] ID Age Deps P Description Urg 1 33min buy eggs 8 2 33min buy flour 8 5 31min M install fedora 3.9 3 33min 1 2 bake cake -5 4 tasks

This will modify the priorities of any tasks that is blocking a task. Now buying eggs and flour is more urgent because it is preventing you from performing a task.

Annotations

You can add notes to a task using task <number> annotate:

$ task 3 anno No blueberries Annotating task 3 'bake cake'. Annotated 1 task. $ task [task next] ID Age Deps P Description Urg 1 1h buy eggs 8 2 1h buy flour 8 5 1h M install fedora 3.9 3 1h 1 2 bake cake -4.2 2020-02-29 No blueberries 4 tasks

Organizing tasks

Tasks can being assigned to projects and tags by using the project modifier and adding a tag using the + sign followed by the tag name, such as +problem.

Putting it all together

You can combine everything you learned to create a task in one line with all the required options.

$ task add Write Taskwarrior post \
pri:M due:1m wait:som until:due+2w sche:15th \
project:magazine +taskwarrior +community +linux Created task 6. The project 'magazine' has changed. Project 'magazine' is 0% complete (1 task remaining).
$ task 6 No command specified - assuming 'information'. Name Value ID 6 Description Write Taskwarrior post Status Waiting Project magazine Entered 2020-02-29 13:50:27 (6s) Waiting until 2020-03-01 00:00:00 Scheduled 2020-03-15 00:00:00 Due 2020-03-30 14:50:27 Until 2020-04-13 14:50:27 Last modified 2020-02-29 13:50:27 (6s) Tags taskwarrior community linux Virtual tags SCHEDULED TAGGED UDA UNBLOCKED UNTIL WAITING YEAR LATEST PROJECT PRIORITY UUID 27768737-f6a2-4515-af9d-4f58773c76a5 Urgency 5.3 Priority M

Installing Taskwarrior on Fedora

Taskwarrior is available in the default Fedora repository. To install it use this command with sudo:

$ sudo dnf install task

For rpm-ostree based distributions like Fedora Silverblue:

$ sudo rpm-ostree install task 

Tips and tricks

  • Taskwarrior has a hook system, meaning that there are many tools you can plug in, such as bugwarrior!
  • Taskwarrior can connect to a taskserver for server/client setups. (This is left as an exercise for the reader for now.)

Photo by Bogdan Kupriets on Unsplash.

Posted on Leave a comment

Make free encrypted backups to the cloud on Fedora

Most free cloud storage is limited to 5GB or less. Even Google Drive is limited to 15GB. While not heavily advertised, IBM offers free accounts with a whopping 25GB of cloud storage for free. This is not a limited time offer, and you don’t have to provide a credit card. It’s absolutely free! Better yet, since it’s S3 compatible, most of the S3 tools available for backups should work fine.

This article will show you how to use restic for encrypted backups onto this free storage. Please also refer to this previous Magazine article about installing and configuring restic. Let’s get started!

Creating your free IBM account and storage

Head over to the IBM cloud services site and follow the steps to sign up for a free account here: https://cloud.ibm.com/registration. You’ll need to verify your account from the email confirmation that IBM sends to you.

Then log in to your account to bring up your dashboard, at https://cloud.ibm.com/.

Click on the Create resource button.

Click on Storage and then Object Storage.

Next click on the Create Bucket button.

This brings up the Configure your resource section.

Next, click on the Create button to use the default settings.

Under Predefined buckets click on the Standard box:

A unique bucket name is automatically created, but it’s suggested that you change this.

In this example, the bucket name is changed to freecloudstorage.

Click on the Next button after choosing a bucket name:

Continue to click on the Next button until you get the the Summary page:

Scroll down to the Endpoints section.

The information in the Public section is the location of your bucket. This is what you need to specify in restic when you create your backups. In this example, the location is s3.us-south.cloud-object-storage.appdomain.cloud.

Making your credentials

The last thing that you need to do is create an access ID and secret key. To start, click on Service credentials.

Click on the New credential button.

Choose a name for your credential, make sure you check the Include HMAC Credential box and then click on the Add button. In this example I’m using the name resticbackup.

Click on View credentials.

The access_key_id and secret_access_key is what you are looking for. (For obvious reasons, the author’s details here are obscured.)

You will need to export these by calling them with the export alias in the shell, or putting them into a backup script.

Preparing a new repository

Restic refers to your backup as a repository, and can make backups to any bucket on your IBM cloud account. First, setup the following environment variables using your access_key_id and secret_access_key that you retrieved from your IBM cloud bucket. These can also be set in any backup script you may create.

$ export AWS_ACCESS_KEY_ID=<MY_ACCESS_KEY>
$ export AWS_SECRET_ACCESS_KEY=<MY_SECRET_ACCESS_KEY>

Even though you are using IBM Cloud and not AWS, as previously mentioned, IBM Cloud storage is S3 compatible, and restic uses its interal AWS commands for any S3 compatible storage. So these AWS keys really refer to the keys from your IBM bucket.

Create the repository by initializing it. A prompt appears for you to type a password for the repository. Do not lose this password because your data is irrecoverable without it!

restic -r s3:http://PUBLIC_ENDPOINT_LOCATION/BUCKET init

The PUBLIC_ENDPOINT_LOCATION was specified in the Endpoint section of your Bucket summary.

For example:

$ restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage init

Creating backups

Now it’s time to backup some data. Backups are called snapshots. Run the following command and enter the repository password when prompted.

restic -r s3:http://PUBLIC_ENDPOINT_LOCATION/BUCKET backup files_to_backup

For example:

$ restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage backup Documents/
Enter password for repository: repository 106a2eb4 opened successfully, password is correct Files: 51 new, 0 changed, 0 unmodified Dirs: 0 new, 0 changed, 0 unmodified Added to the repo: 11.451 MiB processed 51 files, 11.451 MiB in 0:06 snapshot 611e9577 saved

Restoring from backups

Now that you’ve backed up some files, it’s time to make sure you know how to restore them. To get a list of all of your backup snapshots, use this command:

restic -r s3:http://PUBLIC_ENDPOINT_LOCATION/BUCKET snapshots

For example:

$ restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage snapshots
Enter password for repository: ID Date Host Tags Directory ------------------------------------------------------------------- 106a2eb4 2020-01-15 15:20:42 client /home/curt/Documents

To restore an entire snapshot, run a command like this:

restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage restore snapshotID --target restoreDirectory

For example:

$ restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage restore 106a2eb4 --target ~
Enter password for repository: repository 106a2eb4 opened successfully, password is correct
restoring <Snapshot 106a2eb4 of [/home/curt/Documents]

If the directory still exists on your system, be sure to specify a different location for the restoreDirectory. For example:

restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage restore 106a2eb4 --target /tmp

To restore an individual file, run a command like this:

restic -r s3:http://PUBLIC_ENDPOINT_LOCATION/BUCKET restore snapshotID --target restoreDirectory --include filename

For example:

$ restic -r s3:http://s3.us-south.cloud-object-storage.appdomain.cloud/freecloudstorage restore 106a2eb4 --target /tmp --include file1.txt Enter password for repository: restoring <Snapshot 106a2eb4 of [/home/curt/Documents] at 2020-01-16 15:20:42.833131988 -0400 EDT by curt@client> to /tmp

Photo by Alex Machado on Unsplash.

[EDITORS NOTE: The Fedora Project is sponsored by Red Hat, which is owned by IBM.]

[EDITORS NOTE: Updated at 1647 UTC on 24 February 2020 to correct a broken link.]

Posted on Leave a comment

Playing Music on your Fedora Terminal with MPD and ncmpcpp

MPD, as the name implies, is a Music Playing Daemon. It can play music but, being a daemon, any piece of software can interface with it and play sounds, including some CLI clients.

One of them is called ncmpcpp, which is an improvement over the pre-existing ncmpc tool. The name change doesn’t have much to do with the language they’re written in: they’re both C++, but ncmpcpp is called that because it’s the NCurses Music Playing Client Plus Plus.

Installing MPD and ncmpcpp

The ncmpmpcc client can be installed from the official Fedora repositories with DNF directly with

$ sudo dnf install ncmpcpp

On the other hand, MPD has to be installed from the RPMFusion free repositories, which you can enable, as per the official installation instructions, by running

$ sudo dnf install https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm

and then you can install MPD by running

$ sudo dnf install mpd

Configuring and Starting MPD

The most painless way to set up MPD is to run it as a regular user. The default is to run it as the dedicated mpd user, but that causes all sorts of issues with permissions.

Before we can run it, we need to create a local config file that will allow it to run as a regular user.

To do that, create a subdirectory called mpd in ~/.config:

$ mkdir ~/.config/mpd

copy the default config file into this directory:

$ cp /etc/mpd.conf ~/.config/mpd

and then edit it with a text editor like vim, nano or gedit:

$ nano ~/.config/mpd/mpd.conf

I recommend you read through all of it to check if there’s anything you need to do, but for most setups you can delete everything and just leave the following:

db_file "~/.config/mpd/mpd.db" log_file "syslog"

At this point you should be able to just run

$ mpd

with no errors, which will start the MPD daemon in the background.

Using ncmpcpp

Simply run

$ ncmpcpp

and you’ll see a ncurses-powered graphical user interface in your terminal.

Press 4 and you should see your local music library, be able to change the selection using the arrow keys and press Enter to play a song.

Doing this multiple times will create a playlist, which allows you to move to the next track using the > button (not the right arrow, the > closing angle bracket character) and go back to the previous track with <. The + and – buttons increase and decrease volume. The Q button quits ncmpcpp but it doesn’t stop the music. You can play and pause with P.

You can see the current playlist by pressing the 1 button (this is the default view). From this view you can press i to look at the information (tags) about the current song. You can change the tags of the currently playing (or paused) song by pressing 6.

Pressing the \ button will add (or remove) an informative panel at the top of the view. In the top left, you should see something that looks like this:

[------]

Pressing the r, z, y, R, x buttons will respectively toggle the repeat, random, single, consume and crossfade playback modes and will replace one of the characters in that little indicator to the initial of the selected mode.

Pressing the F1 button will display some help text, which contains a list of keybindings, so there’s no need to write a complete list here. So now go on, be geeky, and play all your music from your terminal!