Excel – Set Default Date Format

In the Data Validation dialog box, click Settings tab, and then choose Custom from the Allow drop down list, then enter this formula: =AND(ISNUMBER(B2),LEFT(CELL(“format”,B2),1)=”D”)

Posted in Others | Leave a comment

Configuring SELinux Policies for Apache Web Servers


SELinux can be very troublesome when deploying web applications on Red Hat while not using the default Apache directories, for either content or logs. Your application may need to be installed in a separate directory or maybe, for other reasons, you want to place your content somewhere else. In these scenarios, SELinux will not allow Apache to access your content or log files.

Instead of disabling SELinux, which you should never do, though many do, you should instead create custom policies that apply the proper SELinux context types to your directories and files. Aside from allowing more freedom for placement of your application files, if something were to cause your context settings to disappear, you will be able to quickly remedy the problem by running a context restore to get your applications running again right away.

Application must reside outside of the default Apache directory (/var/www/html).
SELinux blocks Apache from loading content outside of default directories.
Some files require for the application read and write access. By default, they cannot.
Some directories require write access for uploading content. By default, they cannot.


This tutorial assumes that MySQL and Apache are already installed and configured. The scope is to show how to apply common Apache SELinux contexts to a web application’s directory structure, by creating and applying custom policies, allowing you to place your files outside of the default location (/var/www/html).
Application Directory Structure

Before designing an SELinux policy for our web application, we need to understand the directory structure our application will use. This structure is  an example only. Your structure will more than likely differ due to environmental requirements.

Our application has the following directory tree on the web server. I’m only showing a subset of directories and files, but it should be enough for the purposes of this tutorial.

|     |—/app1
|           |—/public_html
|                 |—/wp-content
|                 |—/uploads
|                 |—/index.php
|                 |—/wp-config.php
|     |—/app1

Apps     This directory contains the web application directories, which host the application files. Each application will be segregated into its own child app directory. All files should be read-only, unless explicit permissions allow otherwise.
Logs     This directory will contain the log files for our applications. Each application will have its own child log directory.
Cache     Contains the Apache cache directories for each application.
Creating SELinux Policies
Install Required Packages

Before we can create our own policies, we need to ensure SEMANAGE is installed. This application allows us to browse through the existing, default context policies, and create our own.

Open a console with root privileges
Install the policycoreutils-python package, which contains SEMANAGE.

yum install -y policycoreutils-python

For troubleshooting SELinux issues, download the setroubleshooting package. This step is actually optional, but you’ll be thankful for it when you are able quickly diagnose SELinux problems with it.

yum install -y setroubleshooting

Apache Context Types

Before we can start creating our own policies for applying Apache’s context types, we need to understand which are available to us out of the box. The following table shows the ones we are primarily interested in, however there are several others available.
httpd_sys_content_t     Read-only directories and files used by Apache
httpd_sys_rw_content_t     Readable and writable directories and files used by Apache. Assign this to directories where files can be created or modified by your application, or assign it to files directory to allow your application to modify them.
httpd_log_t     Used by Apache to generate and append to web application log files.
httpd_cache_t     Assign to a directory used by Apache for caching, if you are using mod_cache.

For a complete list of context types for Apache, open the man page for Apache and SELinux.

man httpd_selinux

If you’d like to see existing policies, to better understand why default contexts are applied to your direcotires and files, list them using the semanage command.

semanage fcontext -l

Create the Policies

Create a policy to assign the httpd_sys_content_t context to the /webapps directory, and all child directories and files.

semanage fcontext -a -t http_sys_content_t “/webapps(/.*)?”

Create a policy to assign the httpd_log_t context to the logging directories.

semanage fcontext -a -t httpd_log_t “/webapps/logs(/.*)?”

Create a policy to assign the httpd_cache_t context to our cache directories.

semanage fcontext -a -t httpd_cache_t “/webapps/cache(/.*)?”

Allowing ReadWrite Access

Apache now has permission to use our custom application directories. However, it does not have readwrite access to anything, which may be desired. If your application does have files or directories that need this type of access, like WordPress does, then we need to also apply the context which allows it, but only for those files or directories that require it.

The following will be assigned the Apache readwrite context, so that they can be written to or modified.
/uploads/     Directory     Allow WordPress to upload files for blog entries, such as images, videos, audio, etc.
/wp-config.php     File     This file is modifed by WordPress when permalinks are enabled or changed. It needs to be writable, otherwise, changes to the file will have to be done manually.

Create a policy to assign the httpd_sys_rw_content_t context to the upload directory, and all child files.

semanage fcontext -a httpd_sys_rw_content_t “/webapps/app1/public_html/uploads(/.*)?”

Create a policy to assign the httpd_sys_rw_content_t context to the WordPress configuration file, wp-config.php.

semanage fcontext -a httpd_sys_rw_content_t “/webapps/app1/public_html/wp-config.php”

Applying the SELinux Policy

Our policies are created and ready to be applied to our directory structure. We will use the restorecon command to apply them. This is the same command you will use to re-apply the contexts to the application directories, if for some reason they get removed or corrupted.

Apply the SELinux policies

restorecon -Rv /webapps

Our directory structure should now have the following SELinux contexts applied.

/webapps (httpd_sys_content_t)
|—/apps (httpd_sys_content_t)
|     |—/app1 (httpd_sys_content_t)
|           |—/public_html (httpd_sys_content_t)
|                 |—/wp-content (httpd_sys_content_t)
|                 |—/uploads (httpd_sys_rw_content_t)
|                 |—/index.php (httpd_sys_content_t)
|                 |—/wp-config.php (httpd_sys_rw_content_t)
|—/logs (httpd_log_t)
|     |—/app1 (httpd_log_t)
|—/cache (httpd_cache_t)
|—/app1 (httpd_cache_t)

You can verify your context types our being applied used the ls command with the -Z switch, on each of the directories. We’ll check the webapps root, as an example.

ls -lZ /webapps

The output will display the context type. Notice the highlighted context types.

drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 apps
drwxr-xr-x. root root unconfined_u:object_r:httpd_log_t:s0 logs
drwxr-xr-x. root root unconfined_u:object_r:httpd_cache_t:s0 cache


You now have a secure web application, with files the reside outside of the default locations. A lot of administrators disable SELinux thinking it prevents them from configuring the server based on their own requirements. Even a lot of vendors ask you to disable it, since it may be viewed as too difficult or time consuming to guide the adminitrators through it.

SELinux is a crucial layer in securing your server. And as mentioned in the beginning, it should never be disabled. It provides protections beyond what firewalls and other layers can provide. It’s better to learn how easy it is to utilize, than to open security wholes.

The goal of this tutorial was to show just how easy manipulating SELinux is to fit your environments requirements. I hope the example was helpful enough to show how easy it is.


Source: http://www.serverlab.ca/tutorials/linux/web-servers-linux/configuring-selinux-policies-for-apache-web-servers/

Posted in Linux | Tagged | Leave a comment

Exchange New-MailboxImportRequest – Import PST files

New-MailboxImportRequest -Name “Import1” -Mailbox “Test User” -FilePath \\ServerName\SharedFolder\Imported.pst -TargetRootFolder “Inbox/Imported”

The above command will create a subfolder under the Inbox called “Imported” and all PST data will be imported into that subfolder.

Get-MailboxImportRequest -Status Completed | Remove-MailboxImportRequest -Confirm:$all ( delete all completed import requests )

Posted in Exchange | Leave a comment

Grep through files and replace

Want to replace recursively http://example.co.uk with and also create backups of the files modified:

grep -rFl “http://www.example.co.uk” /path  | xargs sed -i.bak ‘s/http:\/\/www.example.co.uk/http:\/\/’

Posted in Linux | Tagged , , | Leave a comment

PS Codes

ps ax

       Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display to describe the state of a process:
       D    uninterruptible sleep (usually IO)
       R    running or runnable (on run queue)
       S    interruptible sleep (waiting for an event to complete)
       T    stopped, either by a job control signal or because it is being traced.
       W    paging (not valid since the 2.6.xx kernel)
       X    dead (should never be seen)
       Z    defunct ("zombie") process, terminated but not reaped by its parent.

       For BSD formats and when the stat keyword is used, additional characters may be displayed:
       <    high-priority (not nice to other users)
       N    low-priority (nice to other users)
       L    has pages locked into memory (for real-time and custom IO)
       s    is a session leader
       l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
       +    is in the foreground process group.
Posted in Linux | Leave a comment

Install OpenDKIM with Postfix on CentOS

Install opendkim    ( epel repoor other sources )

Either find/add those options to the original config file, or even better, make a copy of the original file and replace /etc/opendkim.conf with the following:

AutoRestart             Yes      # Need to investigate this option !!!
AutoRestartRate         10/1h
LogWhy                  Yes
Syslog                  Yes
SyslogSuccess           Yes
Mode                    sv
Canonicalization        relaxed/simple
ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts
InternalHosts           refile:/etc/opendkim/TrustedHosts
KeyTable                refile:/etc/opendkim/KeyTable
SigningTable            refile:/etc/opendkim/SigningTable
Selector                   mail
SignatureAlgorithm      rsa-sha256
Socket                  inet:8891@localhost
PidFile                 /var/run/opendkim/opendkim.pid
UMask                   022
UserID                  opendkim:opendkim
TemporaryDirectory      /var/tmp

Now we have to setup the public and private keys (replace yourdomain in the text with the apropriate domain name):

mkdir /etc/opendkim/keys/yourdomain
opendkim-genkey -D /etc/opendkim/keys/yourdomain/ -d yourdomain -s mail
chown -R opendkim: /etc/opendkim/keys/yourdomain
mv /etc/opendkim/keys/yourdomain/mail.private /etc/opendkim/keys/yourdomain/mail

Now we have to add it to the OpenDKIM keytable. Edit /etc/opendkim/KeyTable and add:

mail._domainkey.yourdomain yourdomain:mail:/etc/opendkim/keys/yourdomain/mail

Next step, adding the domain to the signing table. Edit /etc/opendkim/SigningTable, and insert:

*@mydomain.com mail._domainkey.mydomain.com

And the last move with DKIM, edit /etc/opendkim/TrustedHosts and add your LAN there.

Now we have to tell Postfix that we want to use OpenDKIM miltering. Edit /etc/postfix/main.cf and insert at the end of the file:

smtpd_milters = , inet:, inet:
non_smtpd_milters       = $smtpd_milters
milter_default_action   = accept
milter_protocol         = 6

The port 12768 is used by amavisd-new in this case !!!

Now we can try to start OpenDKIM and reload postfix:

service opendkim start
chkconfig opendkim on
service postfix reload

If everything worked well, You can send a test mail and see in the source and it contains a DKIM signature, tail /var/log/maillog -f and see the OpenDKIM entries like DKIM-Signature field added (s=mail, d=yourdomain)

Now you should add the dkim signature to your domain file (probably at your ISP). The exact signature as it should look was generated by the opendkim certificate generator, and it is located in /etc/opendkim/keys/yourdomain/mail.txt

TXT record – mail._domainkey

v=DKIM1; k=rsa; p=MIGfM………….

So, all you need is to insert it in the DNS zone file or send it to Your ISP if the DNS is hosted and after a while it will start to work. If you want to check if the DKIM signature is properly inserted in your DNS zone, you can do dig +short mail._domainkey.yourdomain TXT
and it should give You and answer with the hashed key.

After a working OpenDKIM and SPF, you might want to join it together with the new DMARC technology!


SOURCE: https://www.prosinger.net/opendkim-postfix/

Posted in Linux | Tagged | Leave a comment

Reduce KVM Windows qcow2 file size

  1. Clean up the virtual drive (remove temps files, etc)
  2. Defrag with the open source UltraDefrag software with “full optimisation”
  3. Run “sdelete -z c:
  4. Run “qemu-img convert -p -f qcow2 -O qcow2 Win7.qcow2  /newpath/Win7.qcow2

For Linux Guest:

dd if=/dev/zero of=/mytempfile
# that could take a some time
rm -f /mytempfile


qemu-img resize my-server.qcow2 +10GB to increase the size of a qcow2 file

Posted in Linux, Windows | Tagged | Leave a comment

Bash Assign Find Output To Array

To assign the output to an array, you need to use a command substitution inside of an array assignment.

arr=($(grep -n "search term" file.txt | sed 's/:.*//'))

The inner $() runs the command while the outer () causes the output to be an array. The problem with this is that it will not work with files containing spaces. To handle this, you can set IFS to \n.

arr=($(grep -n "search term" file.txt | sed 's/:.*//'))
unset IFS

You can also cut out the need for sed by performing an expansion on each element of the array:

arr=($(grep -n "search term" file.txt))
Posted in Linux | Tagged , | Leave a comment

Shrinking LVM logical volume with ext3/ext4 filesystem

… the required steps to reduce the size of an LVM logical volume formatted as an ext4 filesystem…

1) Unmount the logical volume (or boot into a live CD if the logical volume contains the root filesystem)
2) Check the filesystem for errors
3) Shrink the filesystem to the desired size
4) Reduce the size of the underlying logical volume
5) Check if the resulting logical volume and filesystem are ok
6) Re-mount the logical volume

To illustrate the procedure assume a volume group name vg_d620 which contains the lv_example logical group. The objective will be to shrink the lv_example logical group that is formatted with ext4 to 30G.

1) Unmount the logical volume

Change to the superuser and unmount the logical volume filesystem that is to be resized:

  1. $ su
  2. # umount /dev/mapper/vg_d620-lv_example

2) Check the filesystem for errors

e2fsck checks a Linux ext2/ext3/ext4 filesystem for errors, in this case the -f switch is used to force the check even if the filesystem appears to be clean:

  1. # e2fsck -f /dev/mapper/vg_d620-lv_example
  2. e2fsck 1.41.12 (17-May-2010)
    Pass 1: Checking inodes, blocks, and sizes
    Pass 2: Checking directory structure
    Pass 3: Checking directory connectivity
    Pass 4: Checking reference counts
    Pass 5: Checking group summary information/dev/mapper/vg_d620-lv_example: 11448/3678208 files (1.5% non-contiguous), 4768046/14704640 blocks

3) Shrink the filesystem to the desired size

resize2fs is used to shrink our unmounted filesystem located on vol_d620-lv_example. The -p switch is prints out percentage completion bars for the resize operation. Here the ext4 filesystem is reduced to the desired filesystem final size, in this case I want it to be of 30 gigabytes:

  1. # resize2fs -p /dev/mapper/vg_d620-lv_example 30G
  2. resize2fs 1.41.12 (17-May-2010)
    Resizing the filesystem on /dev/mapper/vg_d620-lv_example to 7864320 (4k) blocks.
    Begin pass 2 (max = 16894)
    Begin pass 3 (max = 449)
    Begin pass 4 (max = 1866)
    Updating inode references XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXThe filesystem on /dev/mapper/vg_d620-lv_example is now 7864320 blocks long.

4) Reduce the size of the underlying logical volume

Having shrunk the ext4 filesystem it is time to reduce the logical volume size accordingly. To achieve this the lvreduce tool is employed. The -L switch specifies final size of the logical volume which should match the size of the ext4 filesystem.

  1. # lvreduce -L 30G /dev/mapper/vg_d620-lv_example
  2. WARNING: Reducing active logical volume to 30.00 GiB
    THIS MAY DESTROY YOUR DATA (filesystem etc.)
    Do you really want to reduce lv_example? [y/n]: y
    Reducing logical volume lv_example to 30.00 GiBLogical volume lv_example successfully resized

5) Check if the resulting logical volume and filesystem are ok

Everything should have proceeded as planned however let’s verify things. e2fsck and resize2fs are used verify the new filesystem, respectively. Notice that this time the resize2fs doesn’t specify any size, the goal here is to have the filesystem match the size of the logical volume.

  1. # e2fsck -f /dev/mapper/vg_d620-lv_example
  2. e2fsck 1.41.12 (17-May-2010)
    Pass 1: Checking inodes, blocks, and sizes
    Pass 2: Checking directory structure
    Pass 3: Checking directory connectivity
    Pass 4: Checking reference counts
    Pass 5: Checking group summary information/dev/mapper/vg_d620-lv_example: 11448/1966080 files (1.5% non-contiguous), 4658570/7864320 blocks
  3. # resize2fs -p /dev/mapper/vg_d620-lv_example
  4. resize2fs 1.41.12 (17-May-2010)The filesystem is already 7864320 blocks long. Nothing to do!

6) Re-mount the logical volume

Finally, mount the updated logical volume:

  1. # mount /dev/mapper/vg_d620-lv_example /mnt/example

It should be noted that if in step 4 e2fsck fails because the partition is tool small lvextend can be used to extend the logical volume until e2fsck completes with success.

Further information on lvm, lvreduce, lvextend,e2fsck and resize2fs can be obtained in the associated man pages.


Shrinking a Logical Volume With LVM

Note: Before you do anything involving your partitions or volumes, make a complete backup.

Make sure to set up a test system with the same kernel and distribution to see how this stuff works. This article was written using our lab box. Read our terms of use. Note that this article was written using a Fedora RC 1 distribution and a generic 2.4.24 kernel.] As we do all of this, we have a text file on our logical volume called ruk.txt that we can use to somewhat test the integrity of our filesystem and volume:

[root@srv-1 root]# mount
/dev/sda1 on / type ext3 (rw)
none on /proc type proc (rw)
none on /dev/pts type devpts (rw,gid=5,mode=620)
/dev/sdb1 on /opt type ext3 (rw)
/dev/sdc1 on /usr/src type ext3 (rw)
/dev/sdd1 on /usr/local type ext3 (rw)
/dev/volgroup/logicalvol on /mnt type ext3 (rw)
[root@srv-1 root]# cat /mnt/ruk.txt
[root@srv-1 root]# umount /mnt

OK. We have data on our volume. Now, we want to shrink down the filesystem on our volume so we can remove one of the drives:

[root@srv-1 root]# lvmdiskscan
lvmdiskscan -- reading all disks / partitions (this may take a while...)
lvmdiskscan -- /dev/sda1  [       3.75 GB] Primary  LINUX native partition [0x83]
lvmdiskscan -- /dev/sda2  [     250.98 MB] Primary  LINUX swap partition [0x82]
lvmdiskscan -- /dev/sdb1  [          4 GB] Primary  LINUX native partition [0x83]
lvmdiskscan -- /dev/sdc1  [          4 GB] Primary  LINUX native partition [0x83]
lvmdiskscan -- /dev/sdd1  [          4 GB] Primary  LINUX native partition [0x83]
lvmdiskscan -- /dev/sde   [          4 GB] USED LVM whole disk
lvmdiskscan -- /dev/sdf   [          4 GB] USED LVM whole disk
lvmdiskscan -- /dev/sdg   [          4 GB] USED LVM whole disk
lvmdiskscan -- /dev/sdh   [          4 GB] free whole disk
lvmdiskscan -- 8 disks
lvmdiskscan -- 4 whole disks
lvmdiskscan -- 0 loop devices
lvmdiskscan -- 0 multiple devices
lvmdiskscan -- 0 network block devices
lvmdiskscan -- 5 partitions
lvmdiskscan -- 0 LVM physical volume partitions
[root@srv-1 root]# 
ot@srv-1 root]# e2fsck -f /dev/volgroup/logicalvol
e2fsck 1.34 (25-Jul-2003)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/volgroup/logicalvol: 12/1441792 files (0.0% non-contiguous), 53460/2883584 blocks
[root@srv-1 root]#
ot@srv-1 root]# resize2fs /dev/volgroup/logicalvol 40000
resize2fs 1.34 (25-Jul-2003)
Resizing the filesystem on /dev/volgroup/logicalvol to 40000 (4k) blocks.
The filesystem on /dev/volgroup/logicalvol is now 40000 blocks long.
[root@srv-1 root]# 

Check our test file:

[root@srv-1 root]# mount /dev/volgroup/logicalvol /mnt
[root@srv-1 root]# df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda1              3874108   1611852   2065460  44% /
none                   3874108   1611852   2065460  44% /dev/pts
/dev/sdb1              4127076    235028   3682404   6% /opt
/dev/sdc1              4127076    278956   3638476   8% /usr/src
/dev/sdd1              4127076     32828   3884604   1% /usr/local
155872     32832    116640  22% /mnt
[root@srv-1 root]#
[root@srv-1 root]# ls /mnt
lost+found  ruk.txt
[root@srv-1 root]# cat /mnt/ruk.txt
[root@srv-1 root]# 
[root@srv-1 root]# umount /mnt
umount: /mnt: not mounted

Our test file is still complete after resizing the filesystem. Note that the logical volume is still the same size. Let’s shrink it by 8 Gigs:

[root@srv-1 root]# lvreduce -L -8G /dev/volgroup/logicalvol
lvreduce -- WARNING: reducing active logical volume to 3 GB
lvreduce -- THIS MAY DESTROY YOUR DATA (filesystem etc.)
lvreduce -- do you really want to reduce "/dev/volgroup/logicalvol"? [y/n]: y
lvreduce -- doing automatic backup of volume group "volgroup"
lvreduce -- logical volume "/dev/volgroup/logicalvol" successfully reduced
[root@srv-1 root]# mount /dev/volgroup/logicalvol /mnt
[root@srv-1 root]# ls /mnt
lost+found  ruk.txt
[root@srv-1 root]# df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda1              3874108   1611996   2065316  44% /
none                   3874108   1611996   2065316  44% /dev/pts
/dev/sdb1              4127076    235028   3682404   6% /opt
/dev/sdc1              4127076    278956   3638476   8% /usr/src
/dev/sdd1              4127076     32828   3884604   1% /usr/local
155872     32832    116640  22% /mnt
[root@srv-1 root]# 
ot@srv-1 root]# cat /mnt/ruk.txt
[root@srv-1 root]# 

Our file is still there, and the logical volume is shrunk down. Let's remove /dev/sdg from the volume group:
[root@srv-1 root]# vgreduce volgroup /dev/sdg
vgreduce -- doing automatic backup of volume group "volgroup"
vgreduce -- volume group "volgroup" successfully reduced by physical volume:
vgreduce -- /dev/sdg
[root@srv-1 root]#

Let’s do a scan:

[root@srv-1 root]# pvscan
pvscan -- reading all physical volumes (this may take a while...)
pvscan -- ACTIVE   PV "/dev/sde" of VG "volgroup" [3.99 GB / 1016 MB free]
pvscan -- ACTIVE   PV "/dev/sdf" of VG "volgroup" [3.99 GB / 3.99 GB free]
pvscan -- inactive PV "/dev/sdg" is in no VG  [4 GB]
pvscan -- total: 3 [12 GB] / in use: 2 [8 GB] / in no VG: 1 [4 GB]
[root@srv-1 root]#

We are now ready to replace or reconfigure our logical volume.There are six articles in this series:
Setting Up Logical Volume Manager
Extending a Logical Volume
Shrinking a Logical Volume With LVM
Adding a RAID1 Device to a Volume With LVM
Upgrading LVM To Version 2 and Patching The Linux Kernel
Finish Conversion And Expansion to Two RAID1 Devices With LVM

Source : http://www.softpanorama.org/Commercial_linuxes/LVM/shrinking_a_logical_volume.shtml

Posted in Linux | Tagged , | Leave a comment

Only one Perl instance – lock script

Use File::NFSLock to get an exclusive lock on the script itself:

use Fcntl qw(LOCK_EX LOCK_NB);
use File::NFSLock;

# Try to get an exclusive lock on myself.
my $lock = File::NFSLock->new($0, LOCK_EX|LOCK_NB);
die "$0 is already running!\n" unless $lock;

Alternatively use Sys::RunAlone near the top of your code.
 use Sys::RunAlone;
 # code of which there may only be on instance running on system

 use Sys::RunAlone silent => 1;
 # be silent if other running instance detected

 use Sys::RunAlone retry => 50;
 # retry execution 50 times with wait time of 1 second in between

 use Sys::RunAlone retry => '55,60';
 # retry execution 55 times with wait time of 60 seconds in between

 use Sys::RunAlone 'silent';
 # obsolete form of silent => 1
Posted in Others | Tagged | Leave a comment