Friday, November 29, 2013

What Is Systemd and How It Works (Part 1)



systemd is a system and service manager and recent Fedora is using systemd (Fedora 18 and above, I think). System startup is managed by systemd now and all original System V (init system for starting individual services) and Upstart service has been deprecated and phased out.

The old System V was using different scripts(daemons) sequentially in different runlevels. For example, System V starts ssh service in runlevel 5 after firewall and network service because ssh service depends on network service. This sequentially running of services make a slow startup and that’s why System V has been phased out.

The new Systemd starts daemons at same time and this parallel running of daemons means a very fast startup. How come? Well, systemd uses sockets for all services. It sets up sockets for daemons and coordinates between them as they start up. So, when a daemon requires support from another daemon, systemd coordinate the data from their sockets . For example, daemon A starts and it needs a support from daemon B, however, daemon B has not started yet . Therefore, systemd writes daemon A’s request to daemon B’s socket(buffering) and it continues. So daemon A doesn’t need to wait for daemon B. As soon as daemon B starts, it will read its socket. This means parallel processing and system boots very fast. The socket activation was designed by Apple’s OS X system.

systemd is compatible with System V and actually systemd uses System V’s configurations and scripts as additional information files. If there is no any configuration file for systemd already, systemd will use System V scripts and configuration files to generate a corresponding configuration files. However, systemd configuration files always take precedence. For example, systemd uses /etc/fstab to generate corresponding systemd configuration file system or looks at /etc/rc.d directory to finds start and stop files and determines dependencies.

Configuration for systemd tasks are defined in unit files. Therefore, systemd defines different units files for different tasks and each unit file has its own configuration file. Unit files are divided to the following categories:

service 
target 
socket 
device 
mount 
automount 
path 
snapshot 
swap 
timer

So, those unit files that are related to “service” have “.service” extension or unit files related to “mount” have “.mount” extension and so forth. An good example can be boot.mount or smb.service.

Now, inside each unit file, there are directives and configuration options. Some of these directives and options are common to all units and you can find it in systemd.unit man page.

man systemd.unit

According to man page, this man page(systemd.unit) lists the common configuration options of all the unit types. These options need to be configured in the [Unit] or [Install] sections of the unit files.

In addition, you can find a list of configuration options shared by services, sockets, mount and swap unit types in systemd.exec man page:

man systemd.exec

The execution specific configuration options are configured in the [Service], [Socket], [Mount], or [Swap] sections in the unit files, depending on the unit type.

Unit file syntax


Well, a very comprehensive explanation exist in man page (man systemd.unit) for your reference. Here is a short, still very useful, explanation of [Unit] section in each unit files. Remember this part is common to all of them. Some common options under [Unit] section are:

[Unit]
Description= A descriptive information along with the unit name 
Documentation= A list of man pages referencing for this unit or its configuration 
Requires= According to man page, this configures requirement dependencies on other units. If this unit gets activated, the units listed here will be activated as well. If one of the other units gets deactivated or its activation fails, this unit will be deactivated. Note that requirement dependencies do not influence the order in which services are started or stopped. This has to be configured independently with the After= or Before= options. 
Wants= A weaker version of Requires=. A unit listed in this option will be started if the configuring unit is. However, if the listed unit fails to start up or cannot be added to the transaction this has no impact on the validity of the transaction as a whole. 
Conflicts= Configures negative requirement dependencies. If a unit has a Conflicts= setting on another unit, starting the former will stop the latter and vice versa.  
Before= Configures ordering dependencies between units. If a unit foo.service contains a setting “Before=bar.service” and both units are being started, bar.service's start-up is delayed until foo.service is started up.  
After= It is the inverse of “Before=”  
AllowIsolate= If true this unit may be used with the “systemctl isolate” command. Otherwise this will be refused.  
ConditionPathExists= a file existence condition is checked before a unit is started. If the specified absolute path name does not exist the condition will fail  
ConditionPathIsDirectory= is similar to ConditionPathExists= but verifies whether a certain path exists and is a directory

 
Some common options under [Install] section are:

 
[Install]  
Alias=Additional names this unit shall be installed under. The names listed here must have the same suffix (i.e. type) as the unit file name.  
Also= Additional units to install/deinstall when this unit is installed/deinstalled  
WantedBy=, RequiredBy=  This option creates a symbolic link to the unit in a “.wants” subdirectory for the WantedBy unit. For example, assume the you enabled the rsyslog service. “WantedBy=multi-user.target” directive in syslog.service unit file creates a symbolic link in /etc/systemd/system/multi-user.target.wants/rsyslog.service to the actual rsyslog.service. Then, this unit file (rsyslog.service) is wanted/needed by multi-user.target unit file. In other words, all units that multi-user.target wants it would be in multi-user.target.wants directory. As you can see here, all WantsBy symbolic links are setup in the /etc/systemd/system directory. These symbolic links can be changed as you enable/disable a service. if you disable a service, it will remove the link.RequiredBy is a much stronger dependency.

                                                                            Figure 1

Also, as I mentioned above, there are some configuration options shared by these four units as well: services, sockets, mount and swap (man systemd.exec). The execution specific configuration options are configured in the [Service], [Socket], [Mount], or [Swap] sections, depending on the unit type. Let’s take a look:

WorkingDirectory= Takes an absolute directory path. Sets the working directory for executed processes.  
RootDirectory= Takes an absolute directory path. Sets the root directory for executed processes, with the chroot system call.  
User=, Group= Sets the Unix user or group that the processes are executed as, respectively.  
Nice= Sets the default nice level (scheduling priority) for executed processes. CPUSchedulingPriority= Sets the CPU scheduling priority for executed processes.  
UMask= Controls the file mode creation mask. Default is 022.  
Environment= Sets environment variables for executed processes. Takes a space-separated list of variable assignments.  
EnvironmentFile= Similar to Environment= but reads the environment variables from a text file. The text file should contain new-line separated variable assignments. Empty lines and lines starting with ; or # will be ignored, which may be used for commenting. The argument passed should be an absolute file name or wildcard expression, optionally prefixed with "-", which indicates that if the file does not exist it won't be read and no error or warning message is logged.  
StandardOutput= Set output to a log, console, or null.  
SyslogFacility= Sets the syslog facility to use when logging to syslog. One of kern, user, mail, daemon, auth, syslog, lpr, news, uucp, cron, authpriv, ftp, local0, local1, local2, local3, local4, local5, local6 or local7.  
SyslogLevel= Default syslog level to use when logging to syslog or the kernel log buffer. One of emerg, alert, crit, err, warning, notice, info, debug.  
MemoryLimit= Limit the overall memory usage of the executed processes to a certain size. DeviceAllow=, DeviceDeny= Control access to specific device nodes by the executed processes. 

Now, let’s take a look at some examples.

                                                                           Figure 2

Don’t worry about [service] section on this example now. I will explain specific configuration options in the [Service], [Socket], [Mount], and [Swap] sections in part 2.

Another example:

                                                                              Figure 3

and

                                                                             Figure 4

and pretty much that’s it. I will explain the rest options and commands in part 2. Don’t forget to follow it. Hope you enjoyed. 

Khosro Taraghi

Monday, October 28, 2013

What Is FirewallD and How It Works (firewall-cmd)

Hello everyone,
Today, I would like to talk about new implemented firewall in Fedora (18 and above, I guess) which is called FirewallD or Dynamic Firewall. FirewallD is more powerful and flexible compared to old static firewall. In static firewall, you list a set of rules and then firewall reads them by restarting your firewall, however, in new FirewallD you apply modified rules without restarting firewall. In fact, FirewallD does not use netfilter rules in the traditional sense. In other words, you cannot use the iptables command to add firewall rules for the Firewalld daemon. They conflict with each other. And, of course you can use the old iptables firewall, however, you have to first disable FirewallD which is not a good idea in my opinion.

You can use either firewall-config tool (GUI version) or firewall-cmd command (command line version) to set up your firewall. Systemd manages FirewallD by using firewalld.service unit file. If you don't know what are systemd and unit files, take a look at these links:  http://linuxconfau.blip.tv/file/4696791/  and http://fedoraproject.org/wiki/Systemd
Let's take a look at inside firewalld.service Figure 1. I tried to put all explanations inside Figure 1.


                                                                               Figure 1

By the way, D-Bus is a free and open-source inter-process communication system, allowing multiple, concurrently-running computer programs (processes) to communicate with one another.

FirewallD uses zones. A network zone defines the level of trust for network connections. Most zones are mutable, but there are also immutable zones. Immutable zones are not customizable and there is no way to overload them. These are the different zones:

Zone                                    Description
-----------------------------------------------------
drop (immutable)                 Deny all incoming connections, outgoing ones are accepted.
block (immutable)                Deny all incoming connections, with ICMP host prohibited messages issued.
trusted (immutable)              Allow all network connections
public                                  Public areas, do not trust other computers
external                               For computers with masquerading enabled, protecting a local network
dmz                                     For computers publicly accessible with restricted access. 
work                                    For trusted work areas
home                                   For trusted home network connections
internal                                For internal network, restrict incoming connections

Default zone is defined in /etc/firewalld/firewalld.conf. Figure 2.
Location of default and fallback zone files (in xml format) are in /usr/lib/firewalld/zones Figure 2.
Zone configurations are located in /etc/firewalld/zones.

                                                                              Figure 2

firewall-cmd

firewall-cmd is a command line to set your firewall with so many options. There are two options to save your changes. One is Permanent and the other one is runtime. Runtime changes are deleted after reload or restart. Permanent option will be there even after reload/restart/reboot.

Now, let's try few examples (Figure 3):

firewall-cmd --get-zones --> List your zones
firewall-cmd --get-services --> List all supported zones under the current zone
firewall-cmd --get-icmptype --> List icmp types
firewall-cmd --get-default-zone --> List default zone
firewall-cmd --set-default-zone=zone --> To set your default zone
firewall-cmd --get-active-zones --> Print currently active zones
firewall-cmd --get-zone-of-interface=interface --> Print the name of the zone the interface is bound to or no zone.
firewall-cmd --list-all-zones --> List everything added for or enabled in all zones.



                                                                              Figure 3

firewall-cmd --zone=public --list-all  --> List everything added for or enabled in public zone
firewall-cmd --zone=public --query-interface=ens33
firewall-cmd --zone=dmz --query-interface=ens33
firewall-cmd [--permanent] --add-service postgresql  --> To add services to the zone
firewall-cmd --query-service=postgresql --> To check if the service is enabled for a zone
or
cat /etc/services | grep postgresql
iptables-save | grep 5432


                                                                          Figure 4

firewall-cmd --remove-service postgresql --> To remove services from the zone
firewall-cmd --zone=dmz --add-port=22/tcp --> To add ssh port 22
firewall-cmd --zone=dmz --query-port=22/tcp --> To query the added port 22
firewall-cmd --zone=dmz --remove-port=22/tcp --> To remove port 22 in dmz zone
firewall-cmd --zone=dmz --add-masquerade --timeout=30 --> Enable IPv4 masquerade for zone. If zone is omitted, default zone will be used. If a timeout is supplied, masquerading will be active for the amount of seconds.


                                                                          Figure 5

If you want to use custom rules, you can use --direct option. The direct options give a more direct access to the firewall.

Note:
Direct options should be used only as a last resort when it's not possible to use for example --add-service=service.

firewall-cmd --direct --get-chains ipv4 filter -->  Get all chains added to table filter, in this case, as a space separated list. This option concerns only chains previously added with --direct 

firewall-cmd --direct --get-rules ipv4 filter INPUT  --> Get all rules added to chain INPUT in table filter as a newline separated list of the priority and arguments.

firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 22 -j ACCEPT   --> Add a rule with the arguments args to chain INPUT in table filter with priority 0. The priority is used to order rules. Priority 0 means add rule on top of the chain, with a higher priority the rule will be added further down. Rules with the same priority are on the same level and the order of these rules is not fixed and may change. If you want to make sure that a rule will be added after another one, use a low priority for the first and a higher for the following.

firewall-cmd --direct --get-rules ipv4 filter INPUT
firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 -p tcp --dport 22 -j ACCEPT --> to remove rule
firewall-cmd --direct --get-rules ipv4 filter INPUT

                                                                           Figure 6

If you want a comprehensive list of options, please refer to man page. I read Ferdora 19's man page and it's much nicer than before in terms of explanation. And that's all. Hope you enjoyed.
Khosro Taraghi

Wednesday, September 25, 2013

Database Maintenance For PostgreSQL & VACUUM Command

Hello everyone,
Today, I would like to talk about database maintenance for PostgreSQL. In my previous blog, I explained that how we can install PostgreSQL. The best tool to use for physical maintenance which is related to disk usage, and analytical maintenance which is related to increasing performance, is VACUUM SQL command or its equivalent command-line vacuumdb. This command removes all temporary data that other processes may leave and any leftover data from rollbacks. That's why it's a good tool for disk usage. Also, it analyses data and activities in database to improve performance, especially when you want to update/add/delete a large number of data in database.That's why it's a good tool for increasing performance too.

NOTE:
Be aware that vacuum command will pause any query on the table that vacuum command is running until it completes its job on that table. Therefore, it's a good idea to run this tool at midnight when there is no or less database activities or during maintenance window when there is no any connection to database.

VACUUM SQL Syntax:


vacuum [Full] [verbose] [analyze] [table [(column,...)]];

vacuum command without any keywords will be run on all tables in connected database. If you want to run vacuum on a specific table or even on a specific column, you can use table/column keywords.

"analyze" keyword is used for query optimizer and it examines the allocation of data on each table/s and column/s.
Let's see an example. Figure 1 and 2 show the usage of vacuum sql statement with different keywords. I connect to "library" database and going to work with either all tables or only "books" table:

                                                                           Figure 1

                                                                             Figure 2

 

VACUUMDB Command Line Syntax:


We can do the same thing in command line with more options and flexibilities. Figure 3 shows all options and syntax with this command:

                                                                              Figure 3

It's pretty much self-explanatory. So, let's try some examples: (Figure 4)

                                                                              Figure 4

With PostgreSQL command-line, we can write a script and schedule it to run at midnight with cron command. It runs at 3 AM every night. Figure 5 and 6:


                                                                               Figure 5

                                                                              Figure 6

and here is the output (Figure 7):

                                                                            Figure 7

Hope you enjoyed.
Khosro Taraghi

Tuesday, August 27, 2013

Installing PostgreSQL Database Server/Client on RedHat Linux Families (RedHat,Fedora,CentOS,SELinux)

Hello everyone,

Today, I would like to talk about a very very good open source Database Server called PostgreSQL. Recently, I've started to work with Postgresql and really love it. I would say it has all features of commercial databases such as DB2 and Oracle and even more. Some of core features are:

  1.  Object-Relational DBMS
  2.  Capable of handling complex routines and rules
  3.  Declarative SQL queries
  4.  Multi version concurrency control
  5.  Multi user support
  6.  Transactions
  7.  Query optimization
  8.  Inheritance
  9.  Arrays
  10.  Highly extensible
  11. Comprehensive SQL support (support SQL99, SQL92)
  12. Referential integrity (insure the validity of database's data)
  13. Flexible API (so many vendors such as Object Pascal, Python, Perl, PHP, ODBC, Java/JDBC, Ruby, TCL, C/C++, and Pike have deployment support for PostgreSQL RDBMS
  14. Procedural Languages (it supports internal procedural native language called PL/pgSQL, which comparable to the Oracle procedural language PL/SQL, and also it has ability to use Perl, Python, and/or TCL as an embedded procedural language)
  15. MVCC (Multi-version Concurrency Control is the technology that Posrgresql uses to avoid unnecessary locking)
  16. Server/Client
  17. Write Ahead Logging (WAL), ability to write the changes to log file before writing to database.(In case of unlikely crash, there will be a record of transaction to restore)

Installing PostgreSQL


The following shows how to install PostgreSQL from source code. Although you could install PostgreSQL server and client easily with yum command (yum install postgresql-server postgresql-client), I would recommend to install from source code because it is so flexible to adding/removing features and to customize it even after compiling source code. For example, you can add more features to Postgresql by reconfiguring and compiling the source code again without losing your data and databases.

1. Installing the required/optional packages:

yum install gcc make kernel-devel perl-ExtUtils-MakeMaker perl-ExtUtils-Embed readline-devel zlib-devel openssl-devel pam-devel libxml2-devel openldap-devel tcl-devel python-devel flex bison

2. Download the source code from command line: (PostgreSQL-9.2.4 is the current stable version at the time of writing this)

wget http://ftp.postgresql.org/pub/source/v9.2.4/postgresql-9.2.4.tar.gz

3. Creating the "postgres" user:
It is always a good idea to create a PostgreSQL superuser to own and manage the PostgreSQL database files rather than using "root" account as the PostgreSQL superuser because of security purposes. This user can be named anything and I named it "posrgres":

su -     --> switch to root account 
useradd postgres  --> create user
passwd postgres   --> set password

                                                                     Figure 1

4. Move and unpack the Postgresql source package:

cp postgresql-9.2.4.tar.gz /usr/local/src/
cd /usr/local/src/
tar -xzvf postgresql-9.2.4.tar.gz


5. Grant the ownership of the Postgresql source directory to "postgres" user. It enables you to compile PostgreSQL as the "postgres" user.

chown -R postgres.postgres postgresql-9.2.4

6. Configuring the source.Now, switch to postgresql-9.2.4 directory:

cd postgresql-9.2.4
and run
./configure --help
to see all available options to customize your PostgreSQL


                                                                             Figure 2


It's pretty self explanatory. For our purpose, I am going to use the options below and leave other options as default:

./configure --mandir=/usr/local/pgsql/man --with-tcl --with-perl --with-python --with-pam --with-ldap --with-openssl --with-libxml

which
--mandir=DIR     is       man documentation [DATAROOTDIR/man]
--with-tcl             is       build Tcl modules (PL/Tcl); if you plan to use pl/Tcl procedural language
--with-perl           is       build Perl modules (PL/Perl); if you plan to use pl/Perl procedural language
--with-python      is       build Python modules (PL/Python); if you plan to use pl/Python procedural language
--with-pam          is       build with PAM support
--with-ldap          is       build with LDAP support
--with-openssl     is       build with OpenSSL support
--with-libxml      is       build with XML support

7. Now, run the "make" command after switching to "postgres" user:

su postgres
make


After compiling source, you should see the following message:
"All of PostgreSQL successfully made. Ready to install."


                                                                               Figure 3


8. We need to do regression test. This is optional but really recommended it.

make check


                                                                              Figure 4


                                                                              Figure 5


8. Now, you need to install compiled programs and libraries and "su -" command save your time to log in as root user for command's execution:

su -c "make install"


                                                                              Figure 6


Don't forget to change the owner of PostgreSQL installation directory, in this case /usr/local/pgsql, to "postgres" user:

su -c "chown -R postgres.postgres /usr/local/pgsql"

9. Then, install documentation:

su -c "make install-docs"


                                                                             Figure 7


10. Next, we need to set environment variables. I am going to set environment variables for man page and bin directory. In order to do that, add the following lines to the end of /etc/profile

echo 'PATH=$PATH:/usr/local/pgsql/bin' >> /etc/profile
echo 'MANPATH=$MANPATH:/usr/local/pgsql/bin' >> /etc/profile
echo 'export PATH MANPATH' >> /etc/profile


Don't forget to log out and log in again to take effect the new variables.
Now try "man psql"


                                                                               Figure 8


11. Now, we need to initialize and start PostgreSQL. Make sure you logged in as postgres user. Then run the following command:

/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data

The path after the -D option is up to you. You can put any path BUT make sure on that path the user "postgres" has write access on it.


                                                                            Figure 9


12. To start the database server in the background, run the following command:

/usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l /tmp/logfile-pgsql.log start


to make sure that server is running, use the following commands:

cat /tmp/logfile-pgsql.log
netstat -antp



                                                                           Figure 10


13. Next, we need to configure PostgreSQL in SysV Script so that we can gracefully control PostgreSQL database though the use of SysV runlevel system. In order to do that, we need to copy a script called "linux" to init.d directory. I also renamed it to "postgresql" to be more meaningful. Run the following commands:

su -c "cp /usr/local/src/postgresql-9.2.4/contrib/start-scripts/linux /etc/rc.d/init.d/postgresql"
su -c "chmod a+x /etc/rc.d/init.d/postgresql"   
--> make the script executable

If you wish for the script to startup PostgreSQL automatically when the machine boots up, run the following command:

su -c "chkconfig --add postgresql"


                                                                            Figure 11


Now, to start and stop PostgreSQL, run the following commands:

service postgresql stop
service postgresql start


                                                                            Figure 12


14. Let's create a test database, we need it when we want to try to connect from client side(another machine) to database server:

createdb testdb
psql testdb



                                                                             Figure 13


15. In order to connect to database server through network from client side, we need to do the followings:

  1.   Insatll PostgreSQL Client with yum command in the client machine(it's different than server machine):
           yum install postgresql-client 
  2. Go back to server, and open pg_hba.conf in vi:
           vi /usr/local/pgsql/data/pg_hba.conf
         then, change this line:
           host    all             all             127.0.0.1/32            trust
         to whatever your client's ip address is. Or you can say the whole subnet. In this case:
           host    all             all             192.168.0.2/24          trust
  3. Next, open postgresql.conf in vi:
           vi /usr/local/pgsql/data/postgresql.conf
         and uncomment this line:
          #listen_addresses = 'localhost'
         and change 'localhost' to the ip address of server, in this case:
          listen_addresses = '192.168.0.1'
  4. Open the PostgreSQL server port, run the below command:
          su -c "iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 5432 -j ACCEPT"
  5.  Restart postgresql service:
          service postgresql stop
          service postgresql start
  6. Finally, try to connect to server by the following command in clinet machine:
          psql -h 192.168.0.1 -U postgres -d testdb
           which
           -h means host
           -U means user
           -d means database name


                                                                      Figure 14


And that's all. I am going to post more blog about PostgreSQL since I've been liked it so far. Hope you enjoyed.

Khosro Taraghi

Monday, July 29, 2013

Moving User's Home Directory and Its Common Errors

Hello everybody,
Today, I would like to talk about a very common error in users' home directories. Have you ever seen these errors?

Could not update ICEauthority file (Figure 1):

                                                                          Figure 1

or "There is a problem with the configuration server. (/usr/libexec/gconf-sanity-check-2 exited with status 256)" (Figure 2)

                                                                            Figure 2

or "Nautilus could not create the following required folders" (Figure 3)

                                                                               Figure 3

They are very common errors in Linux world when you move user's home directory and some users/admins, especially new users/admin in Linux, simply can't fixed it and they reinstall Linux again. However, it has a very simple solution and some users are not aware of this simple solution.


Let's start with an example:
First, login as a root and create a user:

useradd test-user

create some dummy files there by switching to this user (Figure 4):

su - test-user
touch abc ab ac abcd
pwd
exit


                                                                                Figure 4

Take a look inside the test-user's home directory (Figure 5):

ls -al /home/test-user

                                                                                 Figure 5

Now, let's move user's home directory to new location (Figure 6):

mkdir -p /new-home
tar czf - /home/test-user | (cd /new-home ; tar -xvzf -)


the above command will compress user's home directory and decompress it into new location. "-" force tar command to send its output to stdout then receive its input from stdin. 

                                                                                 Figure 6

Use ls command to make sure your files are there:

ls -al /new-home/home/test-user

Complete ownership of all files and directories (Figure 7):

chown -R test-user.test-user /new-home/home/test-user

                                                                              Figure 7

Now, let's delete test-user's old directory (Figure 8):

rm -rf /home/test-user

Now, login with test-user (Figure 8):

su - test-user

And yes, you would see the error that I was talking about:

                                                                                  
                                                                              Figure 8

 and if you try to login with GUI, you would see those errors as I showed you above.

The problem is that you moved user's home directory but you didn't update /etc/passwd file and that's why the su command complained or you saw those odd errors in GUI. You can fix it easily with usermod command. Just type the following command (Figure 9):

usermod -d /new-home/home/test-user test-user

                                                                                 Figure 9

You should be fine now.Try to login again:

su - test-user

and here you go (Figure 9). To see your present work directory, type pwd.
And that's all.
Hope you enjoyed.
Khosro Taraghi

Wednesday, June 26, 2013

What is rdist? How rdist works in Linux?

Hello all,
Today, I would like to talk about “rdist” command. “rdist” is a remote file distribution program. It is a program to maintain identical copies of files over multiple hosts. It preserves the owner,  group, mode and mtime(modification time) of files and can update programs that are executing.

To install rdist, run the following command on server and all clients that you want to be in sync with server:

yum install rdist

Also, in order to communicate and distribute the files from server to clients, you need to install/start sshd service on clients and setup ssh in such a way that does not require a password but authenticate the client with cryptographic key pair. Therefore, run the following commands on server (Figure 1):

su -
ssh- keygen –t rsa –b 1024 
(Just hit Enter for the key and both passphrases)
ssh-copy-id root@client 
(copy key to clients. Note: replace the “client” with actual hostname of your clients. For example, MyTestMachine.localdomain).  And of course, you have to have a DNS to convert the hostname to IP address or simply define it in /etc/hosts.
Repeat this step for each client.

On clients, run the following commands:
service sshd start
chkconfig sshd on



                                                                    Figure 1

Now, let’s look at how it actually works. rdist looks for a control file called “Distfile" or “distfile” in current directory. If it’s not in current directory, you can explicitly specifies the control file’s name by –f flag, something like this:  rdist –f distfile

Inside “distfile” file, first you need to define the list of files that you want to distribute them on clients. For example,
SYSTEM_FILES = (/etc/group /root/test.txt)           --> separate files with one space
Then, list the clients (their host name):
HOSTS = (machine1.localdomain machine2.localdomain machine3.localdomain)

Now, define statements. The form of statement looks like this:
Label: pathnames -> destinations commands

So, the Label can be any name. The point of using Label is that you can run “rdist label” command to  distribute only the files described in a particular statement.

The pathnames and destinations are lists of files to be copied and hosts to copy them to, respectively. For instance,
All_clients: ${SYSTEM_FILES} -> ${HOSTS}
means copy /etc/group and /root/test.txt to machine1, machine2, and machine3
and of course you can use regular expression in pathnames, something like /usr/lib/*

By default, rdist copies the files and directories listed in pathnames to the equivalent paths on each destination machine. You can modify this behavior by supplying a sequence of commands and terminating each with a semicolon.

The commands are:
notify namelist;
except pathlist;
except_pat patternlist;
special [pathlist] string;
cmdspecial [pathlist] string;


The “notify” command takes a list of email addresses as its argument. So, when a file is updated, it sends an email to the defined list of emails. If you don’t add a complete email address, like someone@someone.com, it will add the name of destination host as suffix. So, if you just enter Khosro, for example, it will add Khosro@machine1.localdomain to it.

The “except” and “except_pat” commands are used to except pathnames from the list of files to be copied. You can define pattern or regular expression in “except_pat” command as well. Therefore,
“except /root/test.txt ;” command don’t copy test.txt file to clients.

The “special” command executes a shell command on each remote host. If there is a pathlist, the rdist executes the command once after copying each of specified files. For example,
special /root/test.txt “echo 1 > test2.txt” ;
does nothing when it copies the /etc/group, but it runs “echo 1 > test2.txt command when it copies /root/test.txt
If you don’t specify a pathlist, rdist executes the command after copying every file. For instance,
special  “echo 1 > test2.txt” ;
copies /etc/group, then runs “echo 1 > test2.txt”. and again, copies /root/test.txt and then runs “echo 1 > test2.txt” 

“cmdspecial” is the same as “special”, however, it executes the shell command once after all copying is complete. So, in our example, it copies the /root/test.txt and /etc/group first, and then runs “echo 1 > test2.txt” command.

The following shows how to run rdist command through ssh tunnel:
rdist -P /usr/bin/ssh -f distfile

Now, let's see some examples:  

Scenario 1:
If you want to run a shell command after copying the second file, you need a distfile like Figure 2:
 
                                                                   Figure 2

Figure 3 shows the notification email. It has been sent to user Khosro:

                                                                    Figure 3

And Figure 4 shows the copied files in destination:

                                                                     Figure 4 

Scenario 2:
If you want to execute a shell command after copying every file, you just need to remove the pathlist in "special" command (Figure 5)

                                                                      Figure 5

Scenario 3:
If you want to run a shell command once after all copying is complete, you need to use "cmdspecial" command (Figure 6)

                                                                   Figure 6

Scenario 4:
If you want to except a file, you need to use "except" command in distfile (Figure 7)


                                                                  Figure 7


And That's all. Hope you enjoyed.
Khosro Taraghi