2009-07-27 09:04:44

Kill shell session using pkill

Every once in a while, you need to include the ability for a shell script to commit seppuku, and to kill the shell that spawned it. This is sometimes needed if you're running a program which is known to hang the shell, for instance.

Another common usage, if you're a BOFH, is to replace a common executable file with a shell script that terminates the user's shell that executed the script. I'm making no judgments! :o)

/usr/bin/pkill -9 -s 0 -o

The command breaks down as:

  • pkill: base command
  • -9: kill signal for "terminate & exit immediately"
  • -s 0: session 0, which is pkill's own ID
  • -o: oldest process, which will be the shell

Tags:   linux     |    Perm Link:   Kill shell session using pkill



2009-06-20 01:00:21

One line command to setup SSH keypairs

Setting up SSH keypairs isn't a terribly complex task, but it can be tedious if you have a lot of users who aren't Linux or SSH savvy. Simplifying a task to a simple command is always a nice goal when operating in such an environment.

So, keeping that in mind, here's a simple "one liner" alias that can be placed into auto executing profiles (such as /etc/profile, /etc/bashrc, etc). When a user runs the command, it will generate a custom RSA keypair, of 2048bit strength, with a null password. It copies the pub key first into the authorized_keys file on the local server, and then SSH's into the remote server to place it there, as well. Make sure to change "servername" to the name of your actual server!

Once this is done, the user is able to SSH from the local server to the remote without being prompted for a password. This is obviously useful for things like batched and automated processes.

Naturally, this type of passwordless authentication is a security concern, so use it sparingly and wisely.

export auto-keypairs='cd ~ ; mkdir ~/.ssh; ssh-keygen -t rsa -b 2048 -N "" -C "Auto Keypairs" -f ~/.ssh/rsa_auto ; cat ~/.ssh/rsa_auto.pub >> ~/.ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys ; ssh servername "mkdir ~/.ssh ; echo `cat .ssh/rsa_auto.pub` >> .ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys"'

Tags:   linux     |    Perm Link:   One line command to setup SSH keypairs



2008-05-22 08:22:04

Chroot SFTP using OpenSSH

The open source community has been in rather desperate need of a good, clean method of chrooting SFTP sessions, but at the same time, denying shell access. In the past, people have gotten around this lack by hacking the SSH or SFTP binaries, or creating a restricted shell by various means. The basic problem with these methods is a lack of standardization and integration. Fortunately, the OpenSSH team (which is part of the OpenBSD Project), have included the ability to do just that in the recent versions of OpenSSH. And what's more, it can do it without all the /dev, /etc and shell requirements typically required for a chroot environment.

This guide will go through the entire process of setting up a chroot (aka jailed) SFTP environment for Fedora, from beginning to end.

The major benefits of utilizing this method of chrooting SFTP:

  • Denies shell access
  • Simplified installation/setup/maintenance
  • Forces users to use an encrypted session for file transfers
  • Can be installed as a separate sshd binary, leaving your current SSH configuration intact

While this method of chrooting is better than what was previously available, it isn't perfect:

  • Utilizes local (or potentially LDAP) accounts, instead of an account file, ala many FTP servers
  • The SFTP binary is tied to the SSH binary, and can't be upgraded independently
  • Doesn't allow SCP (SCP requires shell access, which this method blocks)

Notes about this guide:

  • This guide is for Fedora Core, but can be used for other distros, such as Debian or Unbuntu. Just change the software installers as required.
  • The current version of OpenSSH at this point in time is 5.0p1 (the "p" denotes that it is compatible with Operating Systems other than OpenBSD, such as Linux or Solaris), and was released on April 3rd, 2008. This is the version that will be used for this guide.

Configure binaries:

Configure the binaries so that it will not install over the existing SSH installation:
wget ftp://ftp.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-5.0p1.tar.gz
tar zxpvf openssh-5.0p1.tar.gz
cd openssh-5.0p1
./configure --with-tcp-wrappers --prefix=/opt/sftponly --sysconfdir=/etc/sftponly
If the configuration fails due to lack of tcp wrappers, run the following command
yum install -y tcp_wrappers\*

Compile the binaries:

Perform the build and then install it:
make
make install

Configure the /etc/sftponly/sshd_config file.

Modify the following variables:
Port 2222
ServerKeyBits 2048
AllowTcpForwarding no
TCPKeepAlive no
PidFile /var/run/sftponly.pid
Remove the following lines at the end of the config file:
Subsystem sftp /opt/sftponly/libexec/sftp-server
Add the following lines:
Subsystem sftp internal-sftp
Match Group sftponly
        ChrootDirectory %h
        ForceCommand internal-sftp
        AllowTcpForwarding no

Daemon setup (to prevent the normal ssdh from getting squashed)

Rename the new sshd binary to sftponly:
mv /opt/sftponly/sbin/sshd /opt/sftponly/sbin/sftponly
Create the sftponly init.d file:
cp -pr /etc/init.d/sshd /etc/init.d/sftponly
Edit /etc/init.d/sftponly and replace the following variables:
prog="sftponly"
KEYGEN=/opt/sftponly/bin/ssh-keygen
SSHD=/opt/sftponly/sbin/sftponly
RSA1_KEY=/etc/sftponly/ssh_host_key
RSA_KEY=/etc/sftponly/ssh_host_rsa_key
DSA_KEY=/etc/sftponly/ssh_host_dsa_key
PID_FILE=/var/run/sftponly.pid
Fix all of the subsys references:
sed -i -e 's/\/var\/lock\/subsys\/sshd/\/var\/lock\/subsys\/sftponly/g' /etc/init.d/sftponly
Cleanup the status message:
sed -i -e 's/openssh-daemon/sftponly/g' /etc/init.d/sftponly
Now generate the link files for the rc#.d directories:
ln -s /etc/init.d/sftponly /etc/rc0.d/K25sftponly
ln -s /etc/init.d/sftponly /etc/rc1.d/K25sftponly
ln -s /etc/init.d/sftponly /etc/rc2.d/S55sftponly
ln -s /etc/init.d/sftponly /etc/rc3.d/S55sftponly
ln -s /etc/init.d/sftponly /etc/rc4.d/S55sftponly
ln -s /etc/init.d/sftponly /etc/rc5.d/S55sftponly
ln -s /etc/init.d/sftponly /etc/rc6.d/K25sftponly

Group setup

Install the sftponly group with a specific GID:
groupadd -g 999 sftponly

Chroot filesystem setup

Make the chroot filesystem, and modify ownership and permissions:
mkdir /chroot
chown root:root /chroot
chmod 755 /chroot

User setup

Create the user, temporarily allowing shell access:
useradd -m -r -N -d /chroot/twinkles -s /bin/bash -g 999 -c "Chroot_User twinkles" twinkles
passwd twinkles
su - twinkles
As the user "twinkles", not root, perform the following commands:
/opt/sftponly/bin/ssh-keygen -b 2048 -t rsa
/opt/sftponly/bin/ssh-keygen -b 1024 -t dsa
touch ~/.ssh/authorized_keys
mkdir -p ~/incoming
mkdir -p ~/outgoing
exit
As root, change the shell to /sbin/nologin, and clean up permissions:
usermod -s /sbin/nologin twinkles
chown root:root /chroot/twinkles
chmod 755 /chroot/twinkles

SSH key authentication

If you want to test the account without having to use passwords:
cat ~/.ssh/id_rsa.pub >> ~twinkles/.ssh/authorized_keys

Ladies and Gentlemen, start your daemons!

Start the daemon:
[root@navi ~]# service sftponly status
sftponly is stopped

[root@navi ~]# service sftponly start
Starting sftponly:        [ OK ]
Verify the daemon is running and attached to the correct TCP port:
[root@navi ~]# service sftponly status
sftponly (pid 11729) is running...

[root@navi ~]# ps -ef | grep sftponly
root        11729        1 0 08:57 ?        00:00:00 /opt/sftponly/sbin/sftponly

[root@navi ~]# netstat -pan | grep 2222
tcp        0        0 0.0.0.0:2222        0.0.0.0:*        LISTEN        11729/sftponly

Testing

With the configuration complete and the daemon started, you obviously would want to test it. Here are examples of what you should see:

[root@navi openssh-5.0p1]# sftp -oPort=2222 twinkles@localhost Connecting to localhost...
sftp>

sftp> pwd
Remote working directory: /

sftp> ls -l
drwxr-xr-x        2 490        999        4096 May 22 02:32 incoming
drwxr-xr-x        2 490        999        4096 May 22 02:32 outgoing

sftp> put sshd.c
Uploading sshd.c to /sshd.c
Couldn't get handle: Permission denied

sftp> cd incoming

sftp> pwd
Remote working directory: /incoming

sftp> put sshd.c
Uploading sshd.c to /incoming/sshd.c
sshd.c                100% 57KB 56.7KB/s 00:00

sftp> exit

[root@navi openssh-5.0p1]# scp --port=2222 sshd.c twinkles@localhost:/
This account is currently not available.

[root@navi openssh-5.0p1]# cd ~twinkles/incoming/

[root@navi incoming]# ls -AFlh
total 64K
-rw-r--r-- 1 twinkles sftponly 57K 2008-05-22 08:44 sshd.c

A couple of important things to note in this example:

  • Make sure to SFTP to port 2222, since that's the TCP port your sftponly binary is configured to, in /etc/sftponly/sshd_config!
  • The user cannot modify the "root" directory. This is because the directory is actually owned by the user root. The user can, however, modify the sub-directories (incoming, outgoing) because he does own those.
  • The scp program won't work, because the user's shell is set to /sbin/nologin.
  • When inside the sftp shell, notice that an ls -l shows UIDs and GIDs, instead of names. This is due to the chroot not having access to the /etc filesystem.

And there you go ... a nicely chrooted SFTP environment.

Tags:   linux     |    Perm Link:   Chroot SFTP using OpenSSH



2008-04-26 09:16:25

Create a bootable Fedora Live image on a USB stick

Every once in a while, I need to haul out a rescue disk for RedHat to fix an issue (usually something like trying to access failed disk systems). Inevitably, I can't find my rescue disk when I actually need it, so I end up having to wait for a new download to finish.

One of the nice features in the recent versions of Fedora is the inclusion of a small script called livecd-iso-to-disk. Just like it says, it creates a Live image on a disk (a USB stick/key/drive/whatever is a removable disk). Joy! Unlike most other image to disk procedures, this is non-destructive to pre-existing data on the disk. In other words, you don't have to dedicate a USB key just for a Live image.

# yum install livecd-tools -y
livna 100% |=========================| 2.1 kB 00:00
fedora 100% |=========================| 2.1 kB 00:00
updates 100% |=========================| 2.3 kB 00:00
Setting up Install Process
Parsing package install arguments
Resolving Dependencies
--> Running transaction check
---> Package livecd-tools.i386 0:013-1.fc8 set to be updated
--> Processing Dependency: syslinux for package: livecd-tools
--> Processing Dependency: isomd5sum for package: livecd-tools
--> Running transaction check
---> Package isomd5sum.i386 0:11.3.0.50-2 set to be updated
---> Package syslinux.i386 0:3.36-7.fc8 set to be updated
--> Finished Dependency Resolution

Dependencies Resolved

=================================================================
Package Arch Version Repository Size
=================================================================
Installing:
livecd-tools i386 013-1.fc8 fedora 48 k
Installing for dependencies:
isomd5sum i386 11.3.0.50-2 fedora 149 k
syslinux i386 3.36-7.fc8 fedora 678 k

Transaction Summary
=================================================================
Install 3 Package(s)
Update 0 Package(s)
Remove 0 Package(s)

Downloading Packages:
(1/3): livecd-tools-013-1 100% |=========================| 48 kB 00:00
(2/3): syslinux-3.36-7.fc 100% |=========================| 678 kB 00:01
(3/3): isomd5sum-11.3.0.5 100% |=========================| 149 kB 00:01
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Installing: isomd5sum ######################### [1/3]
Installing: syslinux ######################### [2/3]
Installing: livecd-tools ######################### [3/3]

Installed: livecd-tools.i386 0:013-1.fc8
Dependency Installed: isomd5sum.i386 0:11.3.0.50-2 syslinux.i386 0:3.36-7.fc8
Complete!

Next, check to make sure that the USB stick is bootable.

# parted /dev/sdb print
Model: Imation Flash Drive (scsi)
Disk /dev/sdb: 1062MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number Start End Size Type File system Flags
1 32.3kB 1062MB 1062MB primary fat16

Information: Don't forget to update /etc/fstab, if necessary.

Okay, so our USB stick isn't bootable; easy enough to fix!

# parted /dev/sdb
GNU Parted 1.8.6
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print
Model: Imation Flash Drive (scsi)
Disk /dev/sdb: 1062MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number Start End Size Type File system Flags
1 32.3kB 1062MB 1062MB primary fat16

(parted) toggle 1 boot
(parted) print
Model: Imation Flash Drive (scsi)
Disk /dev/sdb: 1062MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number Start End Size Type File system Flags
1 32.3kB 1062MB 1062MB primary fat16 boot

(parted) quit
Information: Don't forget to update /etc/fstab, if necessary.

Now we're ready to actually copy the image to the disk.

# livecd-iso-to-disk Fedora-8-Live-i686.iso /dev/sdb1
Copying live image to USB stick
Updating boot config file
Installing boot loader
USB stick set up as live image!

Now you have a bootable drive, without destroying the other data on the USB device. Yay!

Tags:   linux     |    Perm Link:   Create a bootable Fedora Live image on a USB stick



2007-10-10 07:38:15

vi and bash commands

Here are some quick cheat sheets for vi and bash commands (aka keybindings) that are quite useful.

bash commands

vi commands

Tags:   linux     |    Perm Link:   vi and bash commands



2007-09-06 16:57:03

Create hard links in Python

#!/usr/bin/env python
#################################################################
# Who: James Conner
# When: Sep 05, 2007
# What: hard_link_sync
# Version: 0.0.2
# Why: Hard links are needed for contractors to access deep
#      hierarchy files.
#################################################################
# Updates:
# Ver:Who:When:Why
# 0.0.1:James Conner:Sep 05 2007:Initial creation
# 0.0.2:James Conner:Sep 06 2007:Check using os.samefile
#################################################################
import os,sys
from optparse import OptionParser

#################################################################
# Global Variables
#################################################################
#----------------------------------------------------------------
# The CONTRACTOR_DIR gets created under the mount point.  This is
# where all hard links will be created.
#----------------------------------------------------------------
CONTRACTOR_DIR="/contractor"
sys.path.append('/usr/local/bin')

#################################################################
# Option Parser
#################################################################
parser = OptionParser(version = "0.0.2")

parser.add_option('-d','--directory',
  dest='dir_info',
  default='',
  metavar='DIRNAME',
  help=('Perform the action on a directory and its recursive path'))

parser.add_option('-o','--output',
  dest='stdout_info',
  default='',
  metavar='FILENAME',
  help=('Output to a file instead of stdout'))
(opts, arg) = parser.parse_args()

#################################################################
# Functions
#################################################################
#----------------------------------------------------------------
# The find_mount function takes a path as a parameter.  It looks
# at the path to find the highest mount point by splitting the
# path by the "/" character into a list, and then performing the
# "ismount" function from os.path.  Each iteration of the while
# loop looks at 1 fewer items in the path list.  If the counter
# reaches 0, that means the filesystem is "/" and thus sets the
# path to "/".
#----------------------------------------------------------------
def find_mount(path):
  while not os.path.ismount(path):
    splitpath=path.split("/")
    count=len(splitpath)-1
    path="/".join(splitpath[0:count])
    if count == 0:
      path = "/"
      break
  return path

#----------------------------------------------------------------
# The hardlink function takes 3 variables to make it happen. The
# absolute path to the file to be linked to, the highest mount
# point of the filesystem, and the filename (not absolute).
#----------------------------------------------------------------
def hardlink(absolute,mounted_fs,filename):
  if os.path.exists(mounted_fs+CONTRACTOR_DIR):
    splitpath_abs=absolute.split("/")
    if mounted_fs != "/":
      splitpath_mnt=mounted_fs.split("/")
    else:
      splitpath_mnt=mounted_fs
    splitpath_file=filename.split("/")
    abs_len=len(splitpath_abs)
    mnt_len=len(splitpath_mnt)
    path_without_mounted="/".join(splitpath_abs[mnt_len:-1])
    file_to_link=mounted_fs+CONTRACTOR_DIR+"/"+path_without_mounted+"/"+splitpath_file[-1]
    path_to_make=mounted_fs+CONTRACTOR_DIR+"/"+path_without_mounted
    if not os.path.exists(path_to_make):
      os.makedirs(path_to_make, 0775)
      print path_to_make, "created!"
    if not os.path.isfile(file_to_link):
      os.link(absolute,file_to_link)
      print file_to_link,"created!"
    else:
      if os.path.samefile(absolute, file_to_link):
        print file_to_link, "already exists!"
      else:
        print "ERROR:",absolute,"is not the same file as",file_to_link+"!"
        os.remove(file_to_link)
        print file_to_link,"has been removed!"
        os.link(absolute,file_to_link)
        print file_to_link, "successfully relinked!"
  else:
    if os.path.isfile(mounted_fs+CONTRACTOR_DIR):
      print mounted_fs+CONTRACTOR_DIR,"is a file, not a directory!"
      sys.exit(12)
    else:
      os.makedirs(mounted_fs+CONTRACTOR_DIR, 0775)
      print mounted_fs+CONTRACTOR_DIR,"created!"
      hardlink(absolute,mounted_fs,filename)

#----------------------------------------------------------------
# The traverse_dir function takes a target directory, and the
# highest mounted path.  It lists the contents of a directory,
# and passes off files to the hardlink function, while other dirs
# are called recursively until all sub-trees are exhausted.
#----------------------------------------------------------------
def traverse_dir(parent_dir,mount_path):
  if os.path.isdir(parent_dir):
    for i in os.listdir(parent_dir):
      listed_target=os.path.abspath(parent_dir)+"/"+i
      if os.path.isfile(listed_target):
        just_the_filename=listed_target.split("/")[-1]
        hardlink(listed_target,mount_path,just_the_filename)
      if os.path.isdir(listed_target):
        traverse_dir(listed_target,mount_path)

#################################################################
# Program Execution
#################################################################
#----------------------------------------------------------------
# Here's where the fun starts.
# if the -o or --output option has been declared, then we
# redirect stdout to a file, taking care to preserve the old
# stdout, just in case we really need it.
#----------------------------------------------------------------
if opts.stdout_info:
  old_stdout = sys.stdout
  out_file = open(opts.stdout_info, 'w')
  sys.stdout = out_file

#----------------------------------------------------------------
# Happy Happy Joy Joy
#----------------------------------------------------------------
if len(sys.argv) < 2:
  print "No arguments supplied."
  print "Please type",sys.argv[0],"-h to see the options for this program."
elif opts.dir_info:
  if os.path.isdir(opts.dir_info):
    mount_path=find_mount(os.path.abspath(opts.dir_info))
    traverse_dir(os.path.abspath(opts.dir_info),mount_path)
  else:
    print "Not a directory!"
    sys.exit(10)
elif arg:
  for i in arg:
    if os.path.isfile(i):
      mount_path=find_mount(os.path.abspath(i))
      hardlink(os.path.abspath(i),mount_path,i)
    else:
      print "Not a file!"
      sys.exit(11)
else:
  sys.exit(99)

Tags:   python, linux     |    Perm Link:   Create hard links in Python



2007-08-31 15:11:42

View target WWIDS by fibre adapter with bash

#!/bin/bash
#################################################################
# Who: James Conner
# When: Aug 17, 2007
# What: wwids.sh
# Version: 0.0.1
# Why: View WWIDS by adapter
#################################################################
# Updates:
# Ver  -  Who  -  When  -  Why
# 0.0.1 - James Conner - Aug 17 - Initial creation
#################################################################
# To Do List:
#################################################################
ADAPTERS=`/bin/ls -1 /proc/scsi/qla2xxx`
WWIDS=( 50019DC 5001A90 5002A31 50087CD 500CA35 )

for a in ${ADAPTERS[@]}
do
echo "Adapter ${a}:"

for i in ${WWIDS[@]}
do
if [ "$i" = "50019DC" ]
  then
    echo "EVA1"
elif [ "$i" = "5001A90" ]
  then
    echo "EVA2"
elif [ "$i" = "5002A31" ]
  then
    echo "EVA3"
elif [ "$i" = "50087CD" ]
  then
    echo "EVA4"
elif [ "$i" = "500CA35" ]
  then
    echo "EVA5"
fi
cat /proc/scsi/qla2xxx/${a} | grep -i $i | grep -i "target"
done
echo ""
echo ""
done

Tags:   linux, bash     |    Perm Link:   View target WWIDS by fibre adapter with bash



2007-08-31 14:15:32

PGP auto decryption with bash

#!/bin/bash
#################################################################
# Who: James Conner
# When: Aug 29, 2007
# What: pgp_decrypter.sh
# Version: 0.1.1
# Why: Decrypt PGP files sent by external customers
#################################################################
# Updates:
# Ver  -  Who  -  When  -  Why
# 0.0.1 - James Conner - Aug 17 - Initial creation
# 0.0.2 - James Conner - Aug 20 - Added SCP retrieval
# 0.0.3 - James Conner - Aug 21 - Added SFTP deletion by batch
# 0.0.4 - James Conner - Aug 23 - Added PGP backups
# 0.0.5 - James Conner - Aug 24 - Added QA (PGP & ASCII)
# 0.1.0 - James Conner - Aug 27 - Code clean up & func comments
# 0.1.1 - James Conner - Aug 29 - Added verbose/debug option
#################################################################
# To Do List:
#################################################################


#################################################################
# Options
#################################################################
if [ $# -ne 0 ];then
while getopts "dv" OPTIONS
do
  case $OPTIONS in
  d|debug|v|verbose   ) set -x ;;
  *           ) printf "Bob's yer uncle\n"
              exit 90 ;;
  esac
done
fi

#################################################################
# Variables
#################################################################
LS=`/usr/bin/which ls`
RM=`/usr/bin/which rm`
REV=`/usr/bin/which rev`
CUT=`/usr/bin/which cut`
CAT=`/usr/bin/which cat`
SFTP=`/usr/bin/which sftp`
SCP=`/usr/bin/which scp`
DATE=`/usr/bin/which date`
CHOWN=`/usr/bin/which chown`
CHMOD=`/usr/bin/which chmod`
BASENAME=`/usr/bin/which basename`
CORPUSER="corpprod"
DONEARC="/usr/local/bin/done_arc -f"
DATE_OPTIONS="+%Y_%m_%d"
SFTP_TEMPLATE_FILE="/usr/local/corpbin/corp_download_template.txt"
SFTP_BATCH_FILE="/usr/local/corpbin/corp_download/corp_download_`${DATE} ${DATE_OPTIONS}`.txt"
SFTP_SERVER="ustransfer"
SFTP_OPTIONS="-b ${SFTP_BATCH_FILE}"
SCP_OPTIONS="-pr"
SFTP_USER="corp_transfer"
GREP="`/usr/bin/which grep` -q"
FILE=`/usr/bin/which file`
PGP=`/usr/bin/which pgp`
PGP_ENCRYPTED_EXTENSION=PGP
PGP_DECRYPTED_EXTENSION=decrypted
PGP_PASSPHRASE=internal-passwd
PGP_ENCRYPT_DIR=/corp/transfer
PGP_DECRYPT_DIR=/corp/transfer
LOG_DIR=/corp/transfer/logs
LOG_FILE="${LOG_DIR}/`${DATE} ${DATE_OPTIONS}`.txt"
declare -a PGP_FILE_ARRAY # Executed in func_run
declare -a FILES_TO_DELETE_ARRAY # Executed in func_create_sftp_batch_file
OMNI_JOB_NAME=CORP_Inbound
OMNI=/usr/omni/bin/omnib
OMNI_OPTIONS="-mode full"

#################################################################
# Functions
#################################################################
#----------------------------------------------------------------
# Performs a PGP decryption on a single file that is passed to
# the function as an argument
#----------------------------------------------------------------
func_pgp_decrypt () {
# Verify file doesn't already exist
if [ -f ${PGP_DECRYPT_DIR}/${1}.${PGP_DECRYPTED_EXTENSION} ];then
  # Return an error code to exit out of the loop for this file
  printf "${PGP_DECRYPT_DIR}/${1}.${PGP_DECRYPTED_EXTENSION} decrypted file already exists \n"
  pgpd=10
else
  # Perform decryption and set the error code variable
  ${PGP} --decrypt --passphrase ${PGP_PASSPHRASE} ${PGP_ENCRYPT_DIR}/${1} --output "${PGP_DECRYPT_DIR}/${1}.${PGP_DECRYPTED_EXTENSION}" 2> /dev/null
  pgpd=$?
fi
return $pgpd
}


#----------------------------------------------------------------
# Performs a qa check by verifying the file, whose name is passed
# to the function as an argument, is a PGP encrypted file
#----------------------------------------------------------------
func_check_pgp_file () {
# Looking for "PGP armored data message"
${FILE} ${PGP_ENCRYPT_DIR}/${1} | ${GREP} "PGP armored" 2> /dev/null
chkpgp=$?
return $chkpgp
}


#----------------------------------------------------------------
# Performs a qa check by verifying the file, whose name is passed
# to the function as an argument, has been decrypted to a plain
# ascii text file
#----------------------------------------------------------------
func_check_ascii_file () {
# Looking for "ASCII text, with CRLF line terminators"
${FILE} ${PGP_DECRYPT_DIR}/${1}.${PGP_DECRYPTED_EXTENSION} | ${GREP} "ASCII text" 2> /dev/null
chkascii=$?
return $chkascii
}


#----------------------------------------------------------------
# After the batch file containing the filenames to delete has
# been created, perform the sftp connection to the FTP server
# and remove the old data
#----------------------------------------------------------------
func_sftp_delete () {
# Delete the PGP files from the FTP server
${SFTP} ${SFTP_OPTIONS} ${SFTP_USER}@${SFTP_SERVER}
}


#----------------------------------------------------------------
# Since the keypairs have been exchanged, this scp function does
# not require a password to pull down the contents of the FTP to
# the local incoming directory
#----------------------------------------------------------------
func_scp () {
# Get the PGP files from the FTP server
${SCP} ${SCP_OPTIONS} ${SFTP_USER}@${SFTP_SERVER}:* ${PGP_ENCRYPT_DIR}
}


#----------------------------------------------------------------
# Create the SFTP batch file which contains the list of PGP files
# to be deleted off the FTP server.
#----------------------------------------------------------------
func_create_sftp_batch_file () {
[ -f ${SFTP_BATCH_FILE} ] && ${RM} ${SFTP_BATCH_FILE}

${CAT} << END_WRITE >> ${SFTP_BATCH_FILE}
lcd ${PGP_ENCRYPT_DIR}
END_WRITE
createBatch=$?
return $createBatch
}
#----------------------------------------------------------------
# Get a list of files which have been decrypted, and chop off the
# decrypted extension
#----------------------------------------------------------------
func_write_sftp_batch_file () {
for f in $1
do
# Basename the file since the default dir on the SFTP is the
# correct directory
f=`${BASENAME} ${f}`
${CAT} << END_WRITE >> ${SFTP_BATCH_FILE}
rm ${f}
END_WRITE
done
writeBatch=$?
return $writeBatch
}


#----------------------------------------------------------------
# The general control function.  It initiates the PGP and ASCII
# qa checks, as well as the decrypt function
#----------------------------------------------------------------
func_run () {
# Begin decryption process by loading the file array
PGP_FILE_ARRAY=( `${LS} ${PGP_ENCRYPT_DIR}/*.${PGP_ENCRYPTED_EXTENSION}` )
for i in ${PGP_FILE_ARRAY[@]}
do
  # Basename the file
  i=`${BASENAME} ${i}`
  # Verify the file is PGP armor encrypted
  func_check_pgp_file ${i}
  if [ $? = "0" ];then
  # Perform the decryption process
  func_pgp_decrypt ${i}
  if [ $? = "0" ];then
    # QA the decrypted file to make sure it's ascii and done_arc the PGP file
    ${CHMOD} 660 ${i}*
    ${CHOWN} ${CORPUSER} ${i}*
    echo `${LS} -AFlh ${i}` >> $LOG_FILE
    func_write_sftp_batch_file ${i}
    ${DONEARC} ${i}
    func_check_ascii_file ${i}
    if [ $? = "0" ];then
      printf "${i} successfully processed \n"
      ${RM} -rf ${PGP_ENCRYPT_DIR}/${i}
    else
      printf "##############################################################\n"
      printf "# ERROR: ${i} is not an ASCII file \n"
      printf "##############################################################\n"
    fi
  else
    printf "##############################################################\n"
    printf "# ERROR: ${i} failed to decrypt \n"
    printf "##############################################################\n"
  fi
  else
  printf "##############################################################\n"
  printf "# ERROR: Check ${i}, it is not reporting as an PGP File \n"
  printf "##############################################################\n"
  fi
done
}


#----------------------------------------------------------------
# Prior to any work being performed on the PGP encrypted files
# which are downloaded via the func_scp function, they must be
# backed up to ensure data integrity in case of corruption
#----------------------------------------------------------------
func_omni_backup () {
${OMNI} -datalist ${OMNI_JOB_NAME} ${OMNI_OPTIONS}
dp=$?
return $dp
}

#################################################################
# Program Execution
#################################################################
# Download the files to work with
func_scp
echo "Starting backup"
if [ $? = 0 ];then
  # Create the batch file to delete the files off the FTP svr
  func_create_sftp_batch_file
  # Once the files are sucessfully downloaded, start a DP session
  func_omni_backup
  if [ $? = 0 ];then
  # Start the decryption process
  func_run
  if [ $? = 0 ];then
    echo "Completed"
    # Perform the deletion of PGP files from the FTP svr via
    # the sftp batch script that was successfully written
    func_sftp_delete
  else
    exit 97
  fi
  else
  exit 98
  fi
else
  exit 99
fi

Tags:   linux, bash     |    Perm Link:   PGP auto decryption with bash



2007-08-30 21:28:49

View target WWIDS by fibre adapter with Python

#!/usr/bin/env python
import os,sys

driverDir="/proc/scsi/qla2xxx"
EVA_WWIDS={"50019DC":"EVA1", "5001A90":"EVA2", "5002A31":"EVA3", "50087CD":"EVA4", "500CA35":"EVA5"}

def ExamineAdapter(adapter):
 print "Adapter: ",adapter
 f = open(adapter,'r')
 for lines in f.xreadlines():
  if "adapter-port" in lines:
   print lines.strip()
  elif "-target-" in lines:
   for EVA in EVA_WWIDS.keys():
    if EVA in lines.upper():
     print EVA_WWIDS.get(EVA),":",lines.strip()
 print ""
 f.close()

def ListDriverDir():
 driverDirContents=os.listdir(driverDir)
 adapter_port = {}
 for port in driverDirContents:
  adapter_port[port]=(os.path.join(driverDir, port))
 return adapter_port.values()

try:
 portResults=ListDriverDir()
except:
 print "Oops, no drivers!"
 sys.exit(1)
else:
 map(ExamineAdapter, portResults)

Tags:   python, linux     |    Perm Link:   View target WWIDS by fibre adapter with Python



2007-08-06 23:09:16

Create an SSL Cert (self signed) for Apache

genkey --makeca --days 3560 jamesconner.us
genkey --days 3560 jamesconner.us

vi /etc/httpd/conf.d/ssl.conf and change the following parameters:
SSLCertificateFile /etc/pki/tls/certs/{sitename}.cert
SSLCertificateKeyFile /etc/pki/tls/private/{sitename}.key

Restart the httpd service and SSL will be enabled.

Tags:   linux, web     |    Perm Link:   Create an SSL Cert (self signed) for Apache



2007-08-06 23:09:16

Redirect HTTP to HTTPS via ModRewrite

Place the following code in the body of httpd.conf and restart the httpd service:

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [L,R]

Tags:   linux, web     |    Perm Link:   Redirect HTTP to HTTPS via ModRewrite



2007-08-02 20:18:37

MX518 Linux Config in /etc/X11/xorg.conf

Section "InputDevice"
    Identifier "Mouse0"
    Driver "mouse"
    Option "Device" "/dev/input/mice"
    Option "Buttons" "10"
    Option "ZAxisMapping" "4 5"
    Option "Emulate3Buttons" "false"
    Option "ButtonMapping" "1 2 3 6 7 8 9 10 4 5"
EndSection

Tags:   linux     |    Perm Link:   MX518 Linux Config in /etc/X11/xorg.conf



James Conner