Process Monitoring using Python in Windows

You have created a process in windows which needs to be run continuously without any halt when your windows is up and running.You want to check the status of the process, whether the process is running or got killed or in a not responding state, and restart the process if it is in any of the states mentioned.For doing this we can create a small python program and can use the TaskList functionality in windows.TaskList displays all running applications and services with their Process ID (PID) This can be run on either a local or a remote computer.

So here I’m taking putty as an example process.Putty is an SSH and telnet client.This scenario can be used with any process, just adjust the variables for the process you want to monitor in the code accordingly.This code will check the putty.exe process is running or not every 60 seconds

__author__ = 'mahi'
import os
import time
import subprocess

process_command = ['C:\Program Files\PuTTY\putty.exe', '-load', 'MyPutty']
process_name = 'putty.exe'
sleep_time = 60

while True:
	#Listing Processes which are not responding
    process_list = os.popen('tasklist /FI "STATUS eq Not Responding"').read().strip().split('\n')
    for process in process_list:
        if process.startswith(process_name):
            pn = process.split(' ')
            nr = pn.pop(0)
            while not nr:
                nr = d.pop(0)
			#Kill the process which is not responding
            kill_list = os.popen('taskkill /F /T /PID %s' % nr).read()
		#Checking the process is running or not
        process_list = os.popen('tasklist /FI "STATUS eq Running"').read().strip().split('\n')
        found = False
        for process in process_list:
            if process.startswith(process_name):
                found = True
		#If process is not running start it
        if not found:
            with open(os.devnull, 'wb') as devnull:
                subprocess.Popen(process_command, stdout=devnull, stderr=subprocess.STDOUT)

        time.sleep(sleep_time)

Enabling Kibana Authentication with Apache Server

Kibana doesn’t support authentication or restricting access to dashboards by default.We can restrict access to Kibana 4 using apache server as a proxy in front of Kibana.
This procedure will work and tested on RPM based flavours[eg :- Redhat,CentOS].In this setup Kibana is running on default port 5601 and apache server is running on port 80

Install apache server:


sudo yum install httpd

Create a password file for basic authentication of http users, this is to enable the password protected access to kibana portal. Replace “admin” with your own user name

sudo htpasswd -c /etc/httpd/conf/kibana.htpasswd admin
Configure Apache:

 

By default apache will run on port 80.If you want to change it from port 80 to some other port, say 8080, change the value for Listen in /etc/httpd/conf/httpd.conf

 

Listen 8080

 

Here we are keeping the port as 80 itself.
Add the following entries to the end of httpd.conf  file to enable authentication for Kibana,
sudo vi /etc/httpd/conf/httpd.conf

 

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName example.com
        DocumentRoot /var/www
        <Proxy *>
            AuthType Basic
            AuthName “Authentication Required”
            AuthUserFile “/etc/httpd/conf/kibana.htpasswd”
            Require valid-user
        </Proxy>
        ProxyPass / http://192.168.1.5:5601/
        ProxyPassReverse / http://192.168.1.5:5601/
</VirtualHost>

Start Apache:
sudo service apache start

Enabling Kibana Authentication with Nginx

Kibana doesn’t support authentication or restricting access to dashboards by default.We can restrict access to Kibana 4 using nginx as a proxy in front of Kibana.
This procedure will work and tested on RPM based flavours[eg :- Redhat,CentOS].In this setup Kibana is running on default port 5601 and nginx server is running on port 8080.
Install nginx server:

To install Nginx using yum we need to include the Nginx repository, install the Nginx repository using,

rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

Install Nginx and httpd-tools by issuing the following command,

yum -y install nginx httpd-tools

Create a password file for basic authentication of http users, this is to enable the password protected access to kibana portal. Replace “admin” with your own user name

htpasswd -c /etc/nginx/conf.d/kibana.htpasswd admin

Configure Nginx:

Create a confiiguration file with the name kibana.conf in /etc/nginx/conf.d directory

vi /etc/nginx/conf.d/kibana.conf

Place the following content to the kibana.conf file, assuming that both kibana and Nginx are installed on same server


server {
listen *:8080;
server_name 192.168.1.5;
access_log /var/log/nginx/kibana-access.log;
error_log /var/log/nginx/kibana-error.log;

location / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/conf.d/kibana.htpasswd;
proxy_pass http://192.168.1.5:5601;
#proxy_connect_timeout 150;
#proxy_send_timeout 100;
#proxy_read_timeout 100;
}
}

Restart nginx server:

sudo service nginx restart

Go to the URL : http://192.168.1.5:8080, we should get a authentication screen as below on successful setup,
6

If nothing is showing up check the logs and see whether you have encountered an error as below,

2015/08/11 22:31:13 [crit] 80274#0: *3 connect() to 192.168.1.5:5601 failed (13: Permission denied) while connecting to upstream, client: 10.200.100.29, server: 10.242.126.73, request: "GET / HTTP/1.1", upstream: "http://192.168.1.5:5601/", host: "192.168.1.5:8080"

Error Resolution:
This is happening because we have selinux enabled on our machine.

Disable the selinux by running the command

sudo setsebool -P httpd_can_network_connect 1

Restart nginx:

sudo service nginx restart

Python Email Sender

Here is a python program which allows us to send a simple email using the python smtplib module.
This code is tested on a linux machine(Redhat) where it uses the sendmail functionality defaulted to linux which acts as the smtp server.

 __author__ = 'mahi'  
 import smtplib  
 sender = 'test@example.com'  
 receivers = ['abc@test.com','cde@test.com']  
 subject = 'Test Email'  
 text = 'This is a sendmail test.'  
 message = """From: %s  
 To: %s  
 Subject: %s  
 %s  
 """%(sender,", ".join(receivers), subject, text)  
 try:  
   smtpObj = smtplib.SMTP('localhost')  
   smtpObj.sendmail(sender, receivers, message)  
   print "Successfully sent email"  
 except smtplib.SMTPException:  
   print "Error: unable to send email"  

Python Package Installer

Here is a small python function which helps in installing python packages from a python program itself.This installs python pip first and using pip it install other python modules.

 def install_python_packages():  
   try:  
     #Install pip first  
     subprocess.call(['sudo', 'yum','install', '-y', 'python-pip'])   
     #Packages to install  
     packages = ['boto','impyla','mysql-python','python-logstash']  
     for i in range(0,len(packages)):  
       subprocess.call(['sudo', 'pip', 'install', packages[i]])  
   except:  
     print "Error :"+str(traceback.format_exc())  

Impala Query Executor Using Python Impyla

Impala is an open source massively parallel processing (MPP) SQL query engine that runs on top of Hadoop. We can execute queries on impala from python programs.Below is a small python script which uses impyla (python client for impala) to execute a simple query on impala and return back the results. We can install impyla python module using pip install as below,

pip install impyla

    Code
 __author__ = 'mahi'  
 import traceback  
 from impala.dbapi import connect  
 def impala_query_executor():  
   query = "SELECT count(emp_id) FROM employee_details"  
   dns_name = <impala_system_ip_address>  
   try:  
    connection = connect(host=dns_name, port= 21050)  
    cur = connection.cursor()  
    cur.execute(query)  
    print "query executed"  
    for result in cur.fetchall():  
      print "Execution Result : " +str(result)  
    connection.close()  
   except:  
    print "Error :"+str(traceback.format_exc())   

Simple Shellshock Vulnerability Tester Code

Shellshock, also known as Bashdoor, is a security bug in the widely used Unix Bash shell which was disclosed on 24 September 2014.Many Internet daemons, such as web servers, use Bash to process certain commands, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system.
The below python code allows us to test a remote machine for shellshock vulnerability if we have the ip, username and password of the remote machine.For testing this code we need to install a simple utility in ubuntu called sshpass.sshpass is a utility designed for running ssh using the mode referred to as “keyboard-interactive” password authentication, but in non-interactive mode.Just type,

 import sys  
 from subprocess import Popen,PIPE  
 ip = raw_input("Enter SSH IP or Domain \n")  
 username = raw_input("Enter SSH Username \n")  
 password = raw_input("Enter SSH Password \n")  
 p = Popen(["sshpass", "-p", password+'\r', "ssh", "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", username+'@'+ip, "env x='() { :;};echo -n vulnerable' bash -c echo -n ''"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate()  
 status = p[0].strip()  
 if status.find("vulnerable") == -1:  
     print ip + " is not vulnerable"  
 else:  
     print ip + " is vulnerable"