Monday, March 10, 2014

Installing Pure-FTPd on Centos and creating virtual users

FTP virtual user is a user that can upload file on behalf of system user. For example you have a OS user “pradono” and the home directory is /home/pradono, a virtual user “test1″ that is setup on behalf of “pradono”, can upload file to /home/pradono/test1 and the file uploaded will have the ownership as “pradono”.

1. Installing Pure-FTPd using yum

Let’s start by adding an additional CentOS repo
[root@prod1 ~]# cd /etc/yum.repos.d/
[root@prod1 /etc/yum.repos.d]# wget http://centos.karan.org/kbsingh-CentOS-Extras.repo
And enable kbs-CentOS-Testing by editing /etc/yum.repos.d/kbsingh-CentOS-Extras.repo
[root@prod1 /etc/yum.repos.d]# nano -w kbsingh-CentOS-Extras.repo
Change enabled=0 to enabled=1
[...]
[kbs-CentOS-Testing]
name=CentOS.Karan.Org-EL$releasever - Testing
gpgcheck=0
enabled=1
baseurl=http://centos.karan.org/el$releasever/extras/testing/$basearch/RPMS/
Import the repo key
[root@prod1 /etc/yum.repos.d]# rpm --import http://centos.karan.org/RPM-GPG-KEY-karan.org.txt
Install pure-ftpd.
[root@prod1 /etc/yum.repos.d]# yum -y install pure-ftpd

2. Edit the Pure-FTPd config file

[root@prod1 /etc/yum.repos.d]# cd /etc/pure-ftpd/
[root@prod1 /etc/pure-ftpd]# nano -w pure-ftpd.conf
Make sure you have these options enabled
[...]
# If you want simple Unix (/etc/passwd) authentication, uncomment this
UnixAuthentication yes
# If you want to log all client commands, set this to "yes".
# This directive can be duplicated to also log server responses.
VerboseLog yes
# PureDB user database (see README.Virtual-Users)
PureDB /etc/pure-ftpd/pureftpd.pdb
# Automatically create home directories if they are missing
CreateHomeDir yes
The CreateHomeDir option makes adding virtual users more easy by creating a user’s home directory upon login (if it doesn’t already exist).

3. Import OS users to Pure-FTPd FTP Users (Optional)

We can either import users with system-level accounts (defined in /etc/passwd) at once or create new users manually using pure-pw useradd. To import users that already exist on your system into the virtual user database, enter these commands:
The name has to be pureftpd.passwd. This creates pureftpd.passwd file.
pure-pw mkdb imports pureftpd.passwd to the puredb file, in this example /etc/pure-ftpd/pureftpd.pdb.
[root@prod1 /etc/pure-ftpd]# pure-pwconvert >> pureftpd.passwd
[root@prod1 /etc/pure-ftpd]# pure-pw mkdb
Update: Just use UnixAuthentication yes in your pure-ftpd.conf file and you don’t need step 3 above.

4. Add a virtual user.

This adds a virtual user “test” to pureftpd.pass file
[root@prod1 /etc/pure-ftpd]# pure-pw useradd test -u doniking -g doniking -d /home/doniking/test
Password:
Again, this imports the updated pureftpd.passwd file into a puredb file.
[root@prod1 /etc/pure-ftpd]# pure-pw mkdb

5. Testing.

We haven’t restarted pure-ftpd service yet until now. Let’s restart it.
[root@prod1 /etc/pure-ftpd]# service pure-ftpd restart
Stopping pure-ftpd: [ OK ]
Starting pure-ftpd: [ OK ]
Test the user
[root@prod1 /etc/pure-ftpd]# ftp localhost
Connected to doniking.lan.
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 2 of 50 allowed.
220-Local time is now 00:47. Server port: 21.
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.
500 This security scheme is not implemented
500 This security scheme is not implemented
KERBEROS_V4 rejected as an authentication type
Name (localhost:root): test
331 User test OK. Password required
Password:
230-User test has group access to: 500
230 OK. Current directory is /
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

6. Notes.

- Every time you add a virtual user, run
[root@prod1 /etc/pure-ftpd]# pure-pw mkdb
to import pureftpd.passwd to pureftpd.pdb.
- If you want to enable the OS users to ftp, you don’t need to use pure-pwconvert command as others suggest. Simply enable
UnixAuthentication yes
in your /etc/pure-ftpd/pure-ftpd.conf config file.

Thursday, March 6, 2014

How to add Two Gateway on same Linux machine

Q:I have one test server that has Two Interfaces. To one interface i have assigned ip 172.16.122.1 and GW 172.16.xxx.xxx
Now i connected cable to second interface and gave it ip 10.2.2.98.
Now they both on different subnets.
So how do I add the second gateway in /etc/sysconfig/network file. And when i will try to ping then through which interface will it ping the remote system.

A:Technically you can have multiple default gateways but that is the realm of core internet servers, network load balancers, and so on for the most part.

Much more common is a requirement for multiple routes, each with its own router.
Example: You have a computer sitting between two networks, like this: 192.168.1.5/24 and 192.168.2.5/24
You use 192.168.1.1 as Default Gateway - that is the default route for anything not locally attached. Locally attached is explicitly defined as anything which is in any of the subnets on which you have an interface in the UP/RUNNING state and for which there is no explicit static route defined.
In this configuration you already have three routes: A route for everything locally on 192.16.8.1.0/24, with the gateway being your own IP address on that subnet. You have a similar route for the systems on 192.168.2.0/24... And finally you have a default route, that being for "0.0.0.0" pointing to the default gateway. (There are also some other "psuedo" routes on some operating systems, eg for accessing the loopback device, or for broadcast traffic)
Now say there is a router at 192.168.2.2 which provides access to a number of networks. Usually these are "internal" networks. You can now add "static routes" to these networks. Example for a network with subnet 192.168.5.0/24
Linux Example:

route add -net 192.168.5.0 netmask 255.255.255.0 gw 192.168.2.2
 
You can add multiple "static" routes through one router, or routes can use as many routers/gateways as needed.
You can view the table of known routes with the command

netstat -rn
 
The Linux specific command will show the same information in a slightly different format.

ip route show
 
The router(s) specified must "know" how to reach the target network, otherwise it will go to its own default gateway and forward your packets that way.
To make this configuration changes persistent you need to add it to the system configuration files. Static routes are relevant to one specific interface so they do not go into /etc/sysconfig/network. In stead these go into files located in /etc/sysconfig/network-scripts/

For example: /etc/sysconfig/network-scripts/route-eth0
You add "via" entries into this file for routes. These lines read like "Access network X via gateway Y on Network interface device Z.
Example

default 192.168.1.1 dev eth0
192.168.5.0/24 via 192.168.2.2 dev eth0
192.168.6.0/24 via 192.168.2.2 dev eth0
 
And so on.

Monday, March 3, 2014

How To Backup ESXi Configuration – The Missing Piece

“How do I Backup my ESXi USB Key?” Other than ripping the USB key out of a production machine… how was the user to do this? Well, vMA and the vCLI provide a method for this:

Backing up your ESXi Configuration:

To backup your ESXi configuration you’ll be using the vicfg-cfgbackup.pl command as follows:
  • Download either the vMA or vCLI
  • Launch vicfg-cfgbackup.pl:
    C:\Program Files\VMware\VMware vSphere CLI\bin>vicfg-cfgbackup.pl –save –server 192.168.15.253 –username root –password password backup.bak
  • Note: The backup will be stored relative to your user “AppData” path:
    C:\Users\Username\AppData\Local\VirtualStore\

Restoring your ESXi Configuration:

Restoring your ESXi config can be done after you have the host up and responding over the network again by using the following:
C:\Program Files\VMware\VMware vSphere CLI\bin>vicfg-cfgbackup.pl –load –server 192.168.15.253 –username root –password password backup.bak
Note: You will be asked to reboot the host on restore.
Backing  up multiple hosts! – There is a script to backup multiple ESXi hosts on the VMware communities site here. Also in PowerCLI here!

Tuesday, January 21, 2014

3PAR StoreServ Zoning Best Practice Guide

Original text: http://vmfocus.com/2013/08/22/3par-storeserv-zoning-best-practice-guide/

This is an excellent guide which has been written by Gareth Hogarth who has recently implemented a 3PAR StoreServ and was concerned about the lack of information from HP in relation to zoning.  Being a ‘stand up guy’ Gareth decided to perform a lot of research and has put together the ’3PAR StoreServ Zoning Best Practice Guide’ below.
This article focuses on zoning best practices for the StoreServ 7400 (4 node array), but can also be applied to all StoreServ models including the StoreServ 10800 8-node monster.
3PAR StoreServ Zoning Best Practice Guide
Having worked on a few of these, I found that a single document on StoreServ zoning BP doesn’t really exist. There also appears to be conflicting arguments on whether to use Single Initiator – Multiple Target zoning or Single Initiator – Single Target zoning. The information herein can be used as a guideline for all 3PAR supported host presentation types (VMware, Windows, HPUX, Oracle Linux, Solaris etc…).
Disclaimer:  Please note that this is based on my investigation, engaging with HP Storage Architects and Implementation Engineers. Several support cases were opened in order to gain a better understanding of what is & isn’t supported. HP recommendations change all the time, therefore it’s always best to speak with HP or your fabric vendor to ensure you are following latest guidelines or if you need further clarification.
Right, let’s start off with Fabric Connectivity
In terms of host connectivity options the StoreServ 7000 (specifically the 7400) provides us with the following:
  • 4x built-in 8 Gb/s Fibre Channel ports per node pair.
  • Optional 8 Gb/s Quad Port Fibre Channel HBA (Host Bus Adapter) per node (we will be focusing on this configuration option).
  • Optional 10 Gb/s Dual Port FCOE (Fibre Channel over Ethernet) converged network adapter per node.
StoreServ target ports are identified in the following manner Node:Slot:Port.
StoreServ target ports located on the on-board HBA’s will always assume the slot identity of 1, respectively StoreServ targets ports located on the optional expansion slot will always assume the identity of slot 2.
StoreServ nodes are grouped in pairs, it’s important to pay particular attention to this when zoning host initiators (server HBA ports) to the StoreServ Target ports.
StoreServ7000-HostPorts
Recommendations
  • Each HP 3PAR StoreServ node should be connected to two fabric switches.
  • Ports of the same pair of nodes with the same ID (value) should be connected to the same fabric.
  • General rule – odd ports should be connect to fabric 1 and even ports should be connected to fabric 2.
Figure 1a below identifies physical cabling techniques, mitigating against single points of failure using a minimum of two fabric switches, which are separated from each other.
The example below illustrates StoreServ nodes with supplementary quad port HBA’s:
figure 1a_StoreServ_nPcabling
Moving on to Port Persistence
As already covered by Craig in this blog post, a host port would be connected and zoned on the fabric switch via one initiator (host HBA port) to one HP 3PAR StoreServ target port (one-to-one zoning). The pre-designated HP 3PAR StoreServ backup port must be connected to the same fabric as its partner node port.
It is best practice that a given host port sees a single I/O path to HP 3PAR StoreServ. As an option, a backup port can be zoned to the same host port as the primary port, which would result in the host port seeing two I/O paths to the HP 3PAR StoreServ system. This would also result in the configuration where a HP 3PAR StoreServ port can serve as the primary port for a given host port(s) and backup port for host port(s) connected to its partner node port.
Persistent ports leverage SAN fabric NPIV functionality (N_Port ID Virtualization) for transparent migration of a host’s connection, to a predefined partner port on the HP 3PAR StoreServ array during software upgrades or node failure.
One of the ways this is accomplished is by having a predefined host facing port on the 3PAR StoreServ array, so that in the event of upgrade (node shutdown) or node down status the partner port will assume the identity of its partner port. The whole process is transparent to the host. When the node returns to normal I/O is failed back to the original target port.
Although unconfirmed I have heard that in in future releases of Inform OS we will get this level of protection at the port level.
Essentially for this to work Port Persistence requires that corresponding ‘native’ and ‘guest’ StoreServ ports on a node pair, be connected to the same fibre channel fabric.
Requirements for 3PAR Port Persistence:
  • The same host ports on the host facing HBA’s in the nodes in a node pair must be connected to the same fabric switch.
  • The host facing ports must be set to target mode.
  • The host facing ports must be configured for point-to-point connections.
  • The Fibre Channel fabric must support NPIV and have NPIV enabled on the switch ports.
Checking and enabling NPIV
Brocade Fabric OS (ensure you have the appropriate license which enables NPIV)
admin> portcfgshow ‘port#’
If the NPIV capability is enabled, the results of the portcfgshow command will identify this, i.e NPIV capability ON.
If the NPIV capability is not enabled, you can turn it on with the following command:
admin> portCfgNPIVPort ‘port#’ 1   (1 = on, 0 = off)
 Cisco MDS Series Switches
fabSwitch # conf t
fabSwitch(config) # feature npiv (Enables NPIV for all VSANs on the switch)
QLogic SANbox 3800, 5000 and 9000 Switches
Don’t require a license, it’s enabled by default (just ensure you are using firmware version 6.8.0.0.3 or above).
Now let’s cover Switch Zoning (Fibre Channel)
SAN zoning is used to logically group hosts and storage devices together in a physical SAN, so that authorised devices can only communicate with each other if they are in the same SAN zone.
The function of zoning is to:
  • Restrict access so that hosts can only see the data they are authorised to see.
  • Prevent RSCN (Registered State Change Notification) broadcasts.
What are ‘RSCNs’ ? RSCNs are a feature of fabric switches.  It’s a service of the fabric that notifies devices of changes on the state of other attached devices. For example if a device is reset, removed or otherwise undergoes a significant change in status.
These broadcasts are made to all members in the configured SAN zone. As hosts and storage targets can be grouped in a zone its best practice to reduce the impact of these types of broadcasts (Note: an argument against RSCN’s causing issues in zoning tables is that newer HBA’s do a good job limiting the impact of these types of broadcasts).  Nevertheless, I prefer limiting the number of initiators and targets in a fabric zone to a minimum.
Zoning Types
  • Domain, Port zoning uses switch domain id’s and port numbers to define zones.
  • Port World Wide Name or pWWN zoning uses port World Wide Names to define zones. Every port on a HBA has a unique pWWN. (A host HBA comprises of a – nWWN & a pWWN, the nWWN refers to the whole device whereas the pWWN refers to the individual port.
The preferred zoning unit for the 3PAR StoreServ is pWWN. If you are currently using Domain, Port migrating to pWWN is very easy. Simply create new zones based on the pWWN of the host and the pWWN of the storage target, add these new zones to your fabric switches, zoning-out the references to Domain, Port for that respective HBA port. Some fabric vendor’s support mixing both Domain, Port and pWWN in the same zone. I prefer using one or the other explicitly.
The following command outputs the StoreServ ports and partner ports, which can be used to identify the node pWWN’s for zoning.
3PAR01 cli% showport 
HP 3PAR StoreServ supports the following zoning configurations:
  • Single initiator – Single Target per zone (recommended)
  • Single initiator – Multiple Targets per zone
Use Single Initiator – Single Target per zone over Single Initiator Multiple Targets per zone to reduce RSCN’s as previously discussed.
At the time of writing, HP 3PAR OS implementation documentation references Single Initiator Multiple Targets as the recommended zoning type. However, when I queried this I was directed to use Single Initiator – Single Target Zoning.  HP support pointed me in the direction of this document which identifies Single Initiator – Single Target zoning as best practice: http://www8.hp.com/h20195/v2/GetDocument.aspx?docname=4AA4-4545ENW
HP will support Single Initiator – Multiple Target, but you should not have a single host initiator attached to more than two StoreServ target ports!
Host port WWN’s should be zoned in partner pairs. For example if a host is zoned to node port 0:2:1, then it should be zoned to node port 1:2:1 (I’m speculating here, but I guess this is because controller nodes mirror cache I/O, so that in the event of node failure write operations in cache are not lost – hence we zone in node pairs and not across nodes from different pairs).
After you have zoned the host pWWN to the StoreServ node pWWN, you can use the 3PAR CLI showhost command to ensure that each host initiator is zoned to the correct StoreServ target ports (ensuring initiators go to different targets over different fabrics).
Figure 1b represents a staggered approach where you would have odd numbered VMware hosts connecting to nodes 0 & 1, and even numbered hosts connecting to nodes 2 & 3 (Note: currently the StoreServ is designed to tolerate a single node failure only, this includes the 8-node StoreServ 10800 array).
The example depicts Single Initiator – Single Target zoning, so a host with two HBA ports connecting over two fabrics will have a total of four zones (two per fabric). In case you were wondering the maximum allowed is eight (also known as fan-in limitation which is four per fabric).
figure 1b_host_zoning
Here are some additional points to be aware of
 Fan-in/Fan-out ratios:
  • Fan-in refers to a host server port connected to several HP 3PAR storage ports via Fibre Channel switch.
  • Fan-out refers to the HP 3PAR StoreServ storage port that is connected to more than one host HBA port via Fibre Channel switch.
Note: Fan-in over subscription represents the flow of data in terms of client initiator to StoreServ target ports. HP/3PAR documentation states that a maximum of four HP 3PAR storage system ports can fan-in to a single host server port (if you are thinking great, I’ll connect my VMware host to 8 ports [four per fabric] think again.  Using this approach when you have hundreds of hosts can quickly reach the maximum StoreServ port connection limitation which is 64!) it’s just not necessary.
StoreServ Target Port Maximums (As per 3PAR InForm OS 3.1.1 please observe the following):
  • Maximum of 16 hosts initiators per 2Gb HP 3PAR StoreServ Storage Port
  • Maximum of 32 hosts initiators per 4Gb HP 3PAR StoreServ Storage Port
  • Maximum of 32 hosts initiators per 8Gb HP 3PAR StoreServ Storage Port
  • Maximum total of 1,024 host initiators per HP 3PAR StoreServ Storage System
HP documentation states that these recommendations are guidelines, adding more than the recommended hosts should only be attempted, when the total expected workload is calculated and shown not to overrun either the queue depth or throughput of the StoreServ node port.
Note: StoreServ storage ports irrespective of speed, will negotiate at the lowest speed of the supporting fabric switch (keep this in mind when calculating the number of host connections).
The following focuses on changing the target port queue depth on a VMware ESX environment.
The default setting for target port queue depth on the ESX host can be modified to ensure that the total workload of all servers will not overrun the total queue depth of the target HP StoreServ system port. The method endorsed by HP is to limit the queue depth on a per-target basis. This recommendation comes from limiting the number of outstanding commands on a target (HP 3PAR StoreServ system port), per ESX host.
The following values can be set on the HBA running VMware vSphere. These values limit the total number of outstanding commands the operating system routes to one target port:
  • For Emulex HBA target throttle = tgt_queue_depth
  • For Qlogic HBA target throttle = ql2xmaxqdepth
  • For Brocade HBA target throttle = bfa_lun_queue_depth
(Note: for instructions on how to change these values follow VMware KB1267‎, these values are also adjustable on Linux Redhat & Solaris).
The Formula used to calculate these values is as follows:
(3PAR port queue depth [see below]) / (total number of ESX severs attached) = recommended value
The I/O queue depth for each HP 3PAR StoreServ storage system HBA mode is shown below:
Note: The I/O queues are shared among the connected host server HBA ports on a first come first serve basis.
HP 3PAR StoreServ Storage HBA I/O queue depth values
Qlogic 2Gb 497
LSI 2Gb 510
Emulex 4Gb 959
HP 3PAR HBA 4Gb 1638
HP 3PAR HBA 8Gb 3276
Well, hopefully you found the above information useful. Here is a high level summary of what we have discussed:
  • Identify and enable NPIV on your fabric switches (Fibre Channel only feature – NPIV-Port Persistence is not present in iSCSI environments)
  • Use Single Initiator -> Single Target zoning (HP will support Single Initiator – Multiple Target, but you should not have a single host initiator attached to more than two StoreServ target ports).
  • A maximum of four HP 3PAR Storage System ports can fan-in to a single host server port.
  • Zoning should be done using pWWN. You should not use switch port/Domain ID or nWWN.
  • A host (non-hypervisors) should be zoned with a minimum of two ports from the two nodes of the same pair. In addition, the ports from a host zoning should be mirrored across nodes.
  • Hosts need to be zoned to node pairs. For example, zoned to nodes 0 and 1 or to nodes 2 and 3. Hosts should NOT be zoned to non-mirrored nodes such as 0 and 3.
  • When using hypervisors, avoid connecting more than 16 initiators per 4 Gb/s port or more than 32 initiators per 8 Gb/s port.
  • Each HP 3PAR StoreServ system has a maximum number of initiators supported, that depends on the model and configuration.
  • A single HBA zoned with two FC ports will be counted as two initiators. A host with two HBA’s, each zoned with two ports, will count as four initiators.
  • In order to keep the number of initiators below the maximum supported value, use the following recommendations:
    • Hypervisors: four paths maximum.
    • Other hosts (non-hypervisors): two paths to two different nodes of the same port pairs.
  • Hypervisors can be zoned to four different nodes but the hypervisor HBAs must be zoned to the same Host Port on HBAs in the nodes for each Node Pair.
Reference Documents
HP SAN Design Reference Zoning Recommendations
HP 3PAR InForm® OS 3.1.1 Concepts Guide
The HP 3PAR Architecture
HP UX 3PAR Implementation Guide
HP 3PAR Red Hat Enterprise Linux and Oracle Linux Implementation Guide
HP 3PAR VMware ESX Implementation Guide
HP 3PAR StoreServ Storage and VMware vSphere 5 best practices
HP 3PAR Windows Server 2012, Server 2008 Implementation Guide
HP Brocade Secure Zoning Best Practises
HP 3PAR Peer Persistence Whitepaper
An introduction to HP 3PAR StoreServ for the EVA Administrator
Building SANs with Brocade Fabric Switches by Syngress

Monday, January 6, 2014

Handy Tip: How to split large Outlook PST files to make Outlook run faster (for free)


I get a lot of email. My work one is split into a working PST file and an couple of archive PST files. I’ve started to find that the archive files are just far to big. It means that my machine struggles to defragment the archive file, and today I came across a nice Microsoft support tip, that means you can split PST files up into smaller, moremanageable file sizes. If you want to read how to do it, see this Microsoft support article (KB932086). Now I can have Archives by year (e.g. WorkArchive2005, WorkArchive2006, etc). Nice! Once you have migrated all of your email out of the existing PST file, create a new one and set that to be your new default mail file. Outlook does not reduce the size of the existing PST when you move or delete items.

Thursday, December 19, 2013

Fedora 19 upgrade to Fedora 20 with FedUp

Common problem that I have encouter in my usage of Linux in last 15 year was upgrade from one to another version of release. For quite time best solution was been provided by Debian, but for other non-deb distributions was quite interesting to do upgrade. It was paint-full and time consuming process.

But after release of Fedora fedup util, situation is quite better. On the begging I have little sceptic when my friend Primoz have told me that there is easy was to do upgrade on Fedora with only one command. Till then, for me only safe was was to make backup of /home folder and to do complete install from scratch. If worked on any distro that I have worked till now (Fedora, CentOS, Ubuntu, LinuxMint ...).

What is FedUp?

FedUp (FEDora UPgrader) is the name of a new system for upgrading Fedora installs in Fedora 18 and later. It replaces all of the previously recommended upgrade methods (PreUpgrade and DVD) that were been used in previous Fedora releases. Anaconda, the Fedora installer, has no built-in upgrade functionality in Fedora 18 or later. It has been completely delegated to FedUp.
Currently, FedUp is capable of handling upgrades between all still-supported Fedora releases using a network repository or a DVD image as the package source. Upgrades from EOL Fedora releases may work, but are not supported.

Today I have tested this new upgrade tool.

Here are some considerations to be acknowledged, and here are steps to perform upgrade:

0. make backup of /home directory (just to be on the safe side)
1. do full upgrade of Fedora 19 with "yum update" command
2. check if FedUp is version 0.8, as 0.7 makes problems, check this link for more info: https://fedoraproject.org/wiki/Common_F20_bugs
3. check FedUp page for complete procedure (here is only short version): https://fedoraproject.org/wiki/FedUp
4. execute command "fedup --network 20" (keep in mind that this is network based upgrade, for ISO based upgrade, check fedup page).

What it download cca 1500 packages (this includes also some aditional repos like RPMFusion, Virtualbox ... etc). It needs about 20 min on HP Folio 9740m i5 1.8 with 4GB ram and 320GB HDD.


5. Reboot PC, and whait for that process to be finished, cca 30 min.
6. You have new Fedora 20 on system :) Enjoy :)


Tuesday, November 26, 2013

[Linux, OpenSSL, expect] Doing SFTP file transfers from a shell script

[Linux, OpenSSL, expect] Doing SFTP file transfers from a shell script


PRODUCT:   OpenSSH_5.4p1, OpenSSL 1.0.0a-fips 1 Jun 2010 
           expect version 5.43.0


OP/SYS:    Linux Fedora 13


COMPONENT:  SFTP, SCP 


SOURCE:     Philippe Vouters
            Fontainebleau/France


LOW-COST HIGH-TECH:  http://techno-star.fr


SYMPTOM(S) or PROBLEM(S):

The SFTP -b or the SCP -B options enables batch mode. However, under OpenSSH
version 5.4p1, these options require an empty passphrase and do not allow for
password prompting. What to do when the remote system only has port 22 opened
and only accepts OpenSSH logging using a login/password pair ? This is where
expect enables to workaround this OpenSSH restriction where you do not have the
target account RSA key with an empty passphrase. If you own the target account
RSA key with an empty passphrase then you may use the simpler

        sftp -b script user@host

or scp equivalent shell command.


SOLUTION or RESPONSE:

Use expect to synchronize with each SFTP/SCP output and to simulate their
inputs. Expect acts on terminal screens much the same way as the non-interactive
telnet tool found elsewhere in this knowledge database.


WORKAROUND or ALTERNATIVE:

In your shell script, use SFTP/SCP in interactive mode and synchronize their
output and input using expect commands.


EXPECT INFORMATION:

expect is an optional software. Under Fedora 13 and a root account, use yum to
install expect.

        # yum install expect


KSH SHELL SCRIPT NOTES:

This ksh script expects that the SFTP software is BSD based and accepts the
[-P port] option. Such an SFTP client is available under Linux Fedora 13. 
Carefully check your "man 1 sftp" before blindly using this ksh script. For 
example this sftp man at http://linux.die.net/man/1/sftp which claims BSD
compatibility is not suited for the below ksh script. The following man at
http://linuxreviews.org/man/sftp/ is fully suited and corresponds to the
author's Linux Fedora 13 computer sftp man which he based this ksh script upon.

If running a Linux SFTP client software whose man is identical to what is
described at http://linux.die.net/man/1/sftp, you would modify all occurences
of -P ${port} in the ksh script below to -oPort=${port} such as given as an
example in the http://linux.die.net/man/1/sftp Web browser displayable man.


KSH SHELL FULL SCRIPT:

#!/bin/ksh
#
#        Copyright (C) 2010 by Philippe.Vouters@laposte.net
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by the
#    Free Software Foundation, either version 3 of the License, or
#    any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>;.
#
# Software Description:
# This software transfers the latest 3PAR (a SAN equipment) weekly*.tbz2 and
# optionally the InSplore*.tbz2 files to /tmp local directory. The InSplore
# file is transfered provided it has been produced the same day than the run of 
# this script.
#
# This script makes uses of optional expect freeware and an smtp client whose
# source code is downloadable from http://vouters.dyndns.org/zip/.
# Under Fedora 12 and a root account:
#     # yum install expect
# For smtp:
#     # unzip -aa smtp.zip
#     # export bin=/usr/local/bin
#     # cd smtp
#     # make -f Makefile_smtp
#
# Enter the IP address or the DNS name with the IP port separated with a colon
# of each Service Processor while incrementing the index.
#
SP_hostname[0]="127.0.0.1:10001" # corresponds to 10.10.31.41:22
SP_hostname[1]="127.0.0.1:10002" # corresponds to 10.10.52.25:22
#
# Indicate your email account characteristics as well as a list of remote 
# recipients with a space as the delimiter in the smtp_destinees variable.
#
smtp_server="smtp.sfr.fr"
smtp_login="Philippe.Vouters@laposte.net"
smtp_password="password"
smtp_destinees="Philippe.Vouters@laposte.fr"

# These are the 3PAR Service Processor (SP) Username and Password. They ought
# to be constant whichever the 3PAR SP.
SP_username="spvar"
SP_password="3parvar"

#
# This function prepares a notification of file transfers from the SP.
#
function send_mail_notification
{
       if [[ $1 != "" && $2 != "" ]]; then
           echo "$1 and $2 available in directory /tmp" >> /tmp/smtp_body.txt
       fi
       if [[ $1 != "" && $2 == "" ]]; then
           echo "$1 available in directory /tmp" >> /tmp/smtp_body.txt
       fi
       if [[ $1 == "" && $2 != "" ]]; then
           echo "$2 available in directory /tmp" >> /tmp/smtp_body.txt
       fi
}

#
# Function get_last_weekly
#
# This function is in charge of copying the last dated weekly report to /tmp
# The last dated weekly report has been produced on the preceeding Sunday.
# Input :
#      - Index toward the DNS or IP address stored into SP_hostname
# Output:
#      - /tmp/
#
function get_last_weekly
{
# Step 1:
# get SP's all files in weekly/ directory using sftp and 
# maintenance SSH account.
#
port=`echo ${SP_hostname[$1]} | sed 's/\([\/A-Za-z0-9\.]*\):\([0-9]*\)/\2/g'`
hostname=`echo ${SP_hostname[$1]} | sed 's/\([\/A-Za-z0-9\.]*\):\([0-9]*\)/\1/g'`
echo "spawn sftp -P ${port} ${SP_username}@${hostname}" > /tmp/except
echo "expect -nobrace \" password: \"" >> /tmp/except
echo "send \"${SP_password}\n\"" >> /tmp/except
echo "expect -nobrace \"\nsftp> \"" >> /tmp/except
echo "send \"ls weekly/\n\"" >> /tmp/except
echo "expect -nobrace \"\nsftp> \"" >> /tmp/except
echo "send \"bye\n\"" >> /tmp/except
echo "wait" >> /tmp/except
echo "exit" >> /tmp/except
Weekly_files=`expect /tmp/except | gawk '{if (/weekly\//) {print $0;}}' | sed 's/\r//g' | sed 's/weekly\///g'`
for Weekly in ${Weekly_files}; do
     lastSunday=`date --date="last Sunday" +%y%m%d`
     echo ${Weekly} | sed 's/${lastSunday}//' > /dev/null
     if [[ $? == 0 ]]; then
         Weekly_file=${Weekly}
     fi
done
# Step 2:
# get SP's last dated weekly*.tbz2 in weekly/ directory using sftp and 
# maintenance SSH account.
echo "spawn sftp -P ${port} ${SP_username}@${hostname}" > /tmp/except
echo "expect -nobrace \" password: \"" >> /tmp/except
echo "send \"${SP_password}\n\"" >> /tmp/except
echo "expect -nobrace \"\nsftp> \"" >> /tmp/except
echo "send \"cd weekly\n\"" >> /tmp/except
echo "expect \"\nsftp> \"" >> /tmp/except
echo "send \"lcd /tmp\n\"" >> /tmp/except
echo "expect -nobrace \"sftp> \"" >> /tmp/except
echo "send \"get ${Weekly}\n\"" >> /tmp/except
echo "expect -nobrace \"\nsftp> \"" >> /tmp/except
echo "send \"bye\n\"" >> /tmp/except
echo "wait" >> /tmp/except
echo "exit" >> /tmp/except
expect /tmp/except
Weekly_file=/tmp/${Weekly_file}
rm -f /tmp/except
}
#
# Function get_last_InSplore
# This function downloads to /tmp the today's Insplore file.
#
# Input :
#    - full path of SP's Insplore file
#    - Index toward the SP's IP address or DNS name.
# Output :
#    - the Insplore filename prefixed with /tmp/
#
function get_last_InSplore
{
# Step 1:
# check SP for today's InSplore file using sftp and 
# maintenance SSH account.
#
port=`echo ${SP_hostname[$2]} | sed 's/\([\/A-Za-z0-9\.]*\):\([0-9]*\)/\2/g'`
hostname=`echo ${SP_hostname[$2]} | sed 's/\([\/A-Za-z0-9\.]*\):\([0-9]*\)/\1/g'`
echo "spawn sftp -P ${port} ${SP_username}@${hostname}" > /tmp/except
echo "expect -nobrace \" password: \"" >> /tmp/except
echo "send \"${SP_password}\n\"" >> /tmp/except
echo "expect -nobrace \"\nsftp> \"" >> /tmp/except
echo "send \"ls $1\n\"" >> /tmp/except
echo "expect -nobrace \"\nsftp> \"" >> /tmp/except
echo "send \"bye\n\"" >> /tmp/except
echo "wait" >> /tmp/except
echo "exit" >> /tmp/except
InSplore_file=`expect /tmp/except | gawk '{if (/$$1/) {print $0;}}'`
#
# Step 2:
# get SP's today's InSplore file if it exists and using the 
# maintenance SSH account.
#
echo ${InSplore_file} | sed 's/not found//'
if [[ $? != 0 ]]; then
   echo "spawn sftp -P ${port} ${SP_username}@${hostname}" > /tmp/except
   echo "expect -nobrace \" password: \"" >> /tmp/except
   echo "send \"${SP_password}\n\"" >> /tmp/except
   echo "expect -nobrace \"sftp> \"" >> /tmp/except
   echo "send \"lcd /tmp\n\"" >> /tmp/except
   echo "expect -nobrace \"sftp> \"" >> /tmp/except
   echo "send \"get $1\n\"" >> /tmp/except
   echo "expect -nobrace \"sftp> \"" >> /tmp/except
   echo "send \"bye\n\"" >> /tmp/except
   echo "wait" >> /tmp/except
   echo "exit" >> /tmp/except
   expect /tmp/except
   InSploreFile=/tmp/$(basename ${InSploreFile})
else
   InSploreFile=""
fi
rm -f /tmp/except
}
#
# Start of main script body.
#
touch /tmp/smtp_body.txt
i=0
until [ $i == ${#SP_hostname[@]} ]; do
  if [[ $SP_hostname[$i] != "" ]]; then
      #
      # First step : get last weekly
      #
      get_last_weekly $i
      #
      # Second step: Isolate the SP identification number from the weekly file.
      #
      LastSunday=`date --date="last Sunday" +%y%m%d`
      Today=`date +%Y%m%d`
      SP_num=`echo ${Weekly_file} | sed 's/\([\/A-Za-z0-9]*\)_weekly_\([0-9]*\)_'"${LastSunday}"'\.tbz2/\2/g'`
      InSploreFile=${SP_num}/insplore/InSplore.*-${SP_num}.${Today}.*.tbz2
      #
      # Third step: download if any today's InSplore file
      #
      get_last_InSplore ${InSploreFile} $i
      #
      # Fourth step: prepare notification email
      #
      if [[ ${InSploreFile} != "" ]]; then
            InSploreFile=$(basename ${InSploreFile})
      fi
      #
      # Prepare mail notification
      #
      send_mail_notification ${InSploreFile} $(basename ${Weekly_file})
  fi
  let i+=1
done
#
# send mail to recipients
#
smtp -o ${smtp_login} -server ${smtp_server} -s "Weekly and Insplore transfers over" -f /tmp/smtp_body.txt ${smtp_destinees}
# do cleanup
rm -f /tmp/smtp_body.txt
exit 0


MORE ABOUT EXPECT:

expect has been written in some compiled code (very likely C language according 
to ldd command below) to produce an executable which is linked with the Tcl
binary library. Here is the proof on Linux Fedora 13 (i686 version):

[philippe@victor ~]$ file /usr/bin/expect
/usr/bin/expect: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped

So from above a 32 bits executable

[philippe@victor ~]$ ldd /usr/bin/expect
        linux-gate.so.1 =>  (0x00737000)
        libexpect5.43.so => /usr/lib/libexpect5.43.so (0x00a03000)
        libtcl8.5.so => /usr/lib/libtcl8.5.so (0x00110000)
        libdl.so.2 => /lib/libdl.so.2 (0x009fc000)
        libm.so.6 => /lib/libm.so.6 (0x009d0000)
        libutil.so.1 => /lib/libutil.so.1 (0x06547000)
        libc.so.6 => /lib/libc.so.6 (0x00858000)
        /lib/ld-linux.so.2 (0x00836000)

So from above linked with libtcl library.


HP-UX and EXPECT:

For HP-UX, you may download expect from :
http://hpux.connect.org.uk/hppd/hpux/Tcl/expect-5.45/


REFERENCE(S):

As SFTP -b option does not prompt for any passphrase/password, this solution
is unuseable. The ksh script excerp above is based on one guest input at:
http://www.linux-bsd-central.com/index.php/content/view/26/

How to use DiskSpd to simulate Veeam Backup & Replication disk actions

This HOW-TO contains information on how to use Microsoft© DiskSpd to simulate Veeam Backup & Replication disk actions to measure disk pe...