Python – PSQL postgresql Client check and installer.

The script performs a check to see if PSQL client is installed. If it is not installed then it will check if the postgres-contrib RPM package is installed and if not it will go ahead and install it. Then regardless it will continue with the installation of the PSQL package. Note: The script does not know how to handle SSH not being up on the remote server. It will quit if SSH is not running on a server.

The script can be run by issuing the following command

$ fab -f check_PSQL 
from fabric.api import *
from fabric.api import settings
from fabric.api import run, roles
import socket
env.roledefs = {
    'db': ['', ''],
    'web': ['web1', 'web2', 'web3'],
env.use_ssh_config = False
env.user = "root"
env.password = "ILoveCake!"
env.port = 22
hostname = socket.gethostname()
#Function that checks if PSQL is installed.
def check_PSQL():
    with settings(abort_exception = Exception):
        try: #Check if psql is installed. If it is exit function and execute post_install_check_PSQL function
            if run("which psql", warn_only = True).succeeded:
            else: #If it is not installed it will check to see if psql94 yum RPM package is installed
                if run("rpm -q postgresql94-contrib").succeeded:
                    run ("yum install -y postgresql94-contrib") #if it is installed then it will install the PSQL package
        except Exception: #if psql94 yum RPM package is NOT installed it will install it and then procceed with the install of PSQL
            run ("rpm -Uvh")
            run ("yum install -y postgresql94-contrib")
def post_install_check_PSQL(): #This function performs a post install check. It checks if PSQL is installed or not.
                               #If PSQL is not installed then it will append to a list the name fo the server and display the server name
                               #with the failure.
    with settings(abort_exception = Exception):
            run("which psql", warn_only = True).succeeded
            print "PSQL is installed"
        except Exception:
            print "Issue with PSQL instal on following server"
            print check_PSQL_hosts_error
Share Button

Python – Fabric: Connect to a remote server and execute few simple commands.

Fabric is a Python module used to connect to remote servers with SSH and execute various commands. The script below provides the IP for the server to connect to along with the username and password. Then a function is defined with the commands we wish to execute. We execute the script by typing the following command. It provides the name of the file and it also calls the function we defined.

fab -f uptime
from fabric.api import *

env.use_ssh_config = False
env.hosts = [""]
env.user = "root"
#env.key_filename = "/root/.ssh/id_rsa"
env.password = "Password!"
env.port = 22

def uptime():
        run ("ls -ltr")
Share Button