Exam Notes Section 4

Sockets in Python

  • Resolve IP to hostname
>>> import socket
>>> print(socket.gethostbyaddr("8.8.8.8"))
('google-public-dns-a.google.com', ['8.8.8.8.in-addr.arpa'], ['8.8.8.8'])
  • Resole hostname to IP
>>> import socket
>>> print(socket.gethostbyname("www.colorado.edu"))
128.138.129.98
  • Get protocol name with port number
>>> import socket
>>> print(socket.getservbyport(53))
domain
  • Get port number with protocol name
>>> import socket
>>> print(socket.getservbyname("https"))
443
  • UDP socket send data

socket.sendto(data,(ip_address,port_number))

  • UDP receive data

socket.recvfrom(size_buffer)

Hashing in Python

haslib provides various hashing mechanisms.

Example.

import hashlib
hash = hashlib.sha265() // specify the hashing algorithm
hash.update("some text or data to be hashed")
print(hash.hexdigest())  // returns the hash value in hex

Intro to Flask

  • Initialize Flask class

app = Flask(__name__)

  • URL –> Function
@app.route('/')
def index():
    do something

Handling Variables

  • URL –> Function (accept INT variable in url)
@app.route('/accept/<int:n>')
def accept(n):
    do something with n
  • URL –> Function (accept STRING variable in url)
@app.route('/accept/<string:n>')
def accept(n):
    do something with n
  • URL –> Function (accept MESSAGE variable in url)
@app.route('/accept/<msg:n>')
def accept(n):
    do something with n
  • URL –> Function (Accept GET,POST)
@app.route('/accept/,methods=['GET','POST'])
def accept():
    if request.method == 'POST':
        value=request.form['somevar']
        do something
@app.route('/accept/,methods=['GET','POST'])
def accept():
    username=request.args.get('username')  // returns username variable in GET

Logging in python

logging module provides capabilities for logging messages in application

logging.baseconfig(filename="/var/log/someprogram.log",level=logging.DEBUG)
logging.debug("App has started")

Ploting graphs in python

matplotlib module is used to plot line, bar and pie graphs in python

  • Plot a line graph
import matplotlib.pyplot as plt

x=[1,2,10,6,7,9]
plt.plot(x)
plt.xlabel("Other numbers")
plt.ylabel("Numbers")

plt.title("My number graphs")

plt.show()
  • Plot multiple line in a graph
import matplotlib.pyplot as plt

x=[1,2,10,6,7,9]
plt.plot(x)

x2=[10,4,5,3,2]
plt.plot(x2)

plt.xlabel("Other numbers")
plt.ylabel("Numbers")

plt.title("My number graphs")

plt.margins(0.0.25)  // specify margin at the begining on graph

plt.legend(["graph1","graph2"], loc="upper left")  // print a legent at upper left of graph

plt.savefig('test.jpg') // saves the graph as image, should be before show !

plt.show()

  • Plot a bar graph
import matplotlib.pyplot as plt
import numpy as np

y=[4,9,2,7,1]
groups=len(y)
index=np.arange(groups)

barwidth=0.5  // width of each bar

plt.bar(index,y,barwidth,color='r')

plt.xlabel("X label")
plt.ylabel("Y label")
plt.title("My first bar graph")
plt.xticks(index+barwidth,("A","B","C","D","E"))   // bar names

plt.show()   // show the graph

Reading a CSV File

csv module is used to create and write csv files in python

  • Reading a csv file
import csv

with open('test.csv') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        if row:
            do something
            // row[0] gives the first column data

Pretty tables in python

prettytable module is used to print tables in terminal.

from prettytable import PrettyTable

table = PrettyTable(["column1","column2"])  // define the header of the table

table.add_row([1,2])

print(table) // print the table to terminal

Run system commands from python

subprocess module is used to run system commands and get output to python program.

import subprocess

output = subprocess.check_output(["ping","-c","10","{}".format("8.8.8.8")])   // every argument should be a new list element

BeautifulSoup – easy web page scrapping

bs4 module is used to easily scrape a web page.
requests module is used to get, send data to/from a web page.

  • Get title from a page
from bs4 import BeautifulSoup
import requests

url="http://20.163.169.28"

r = requests.get(url)

soup=BeautifullSoup(r.text,"html.parser")

print(soup.title)
print(soup.title.string)
  • Get all links from a web page
from bs4 import BeautifulSoup

url="http://20.163.169.28"

r = requests.get(url)

soup=BeautifullSoup(r.text,"html.parser")

for a in soup.find_all('a',href=True):
    print(a)

Send a mail from python

smtplib module is used to send email from python script

import smtplib
from email.mime.text import MIMEText

msg=MIMEText("Some message")
msg['Subject'] = "This is the subject"
msg['From'] = mailfrom
msg['To'] = mailto

s = smtplib(mailserver,timeout=25)
s.sendmail(mailfrom,mailto,msg.as_string())

Exam Notes Section 3

Hashes in python

hases in python are called dictionaries.
Dictionary are key,value pairs where key should be unique.

  • Initialize Dict:
    test = {}
    test = dict()

  • Add values to Dict:
    test[‘one’] = 1

  • Remove values from Dict:
    del test[‘one’]

  • Sorting a dict on keys:
    sorted – function is used to sort dictionaries
    By default it will sort on keys
    Example:
    sorted(test)

SQLite in python

import sqlite3 module provides CURD capabilities using sql lite databases

  • Open a database
db = sqlite3.connect("test.sql3")
  • Initialize a cursor
db.row_factory = sqlite3.Row
cursor = db.cursor()
  • Create and execute query to database
query = "select * from testtable"
cursor.execute(query)
  • Grab result into a list
rows = cursor.fetchall()
  • Prepared statements
    ? tells SQLite to substiute a passed in value.
quert = "select * from testtable where name=?"
t=(petname,)
cursor.execute(query,t)
  • Creating Databases
    To create a new database run:
sqlite3 newDatabaseName.sql
sqlite3> .schema
sqlite3> CREATE TABLE states (id varchar(1),
abbreviation varchar(2), name varchar(20));

Exam Notes Section 3

shbang

shbang tells the interpretor how to execute this file.
Invoking python3 before the file is not needed with shbang.
i.e python3 test.py // not needed

Example:

#!/usr/bin/env python3

python code

Command Line Arguments

SYS module

sys module can be used to accept command line arguments to a program.
sys.argv returns a list of arguments passed to the program
– sys.argv[0] – always returns program name
– sys.argv[1] – gives 1st argument

Note: if you pass 2 arguments to the program then len(sys.argv) will be 3 as 0 element is always the program name.

Argparse module

argparse module was introduced in pyhton3 and is a enhanced version of sys module.
argparse makes a help menu with the added arguments, it can also accept True/False for options.

Actions:
store – stores the value in argument variable
store_true – stores true values
store_false – store false values
append – appends the arguments to a list
count – counts the number of arguments (-vvv)
version – can be used to retuen the version of the program

Type:
int – accept only integers
str – accept only strings
open – use to return a filedescription to open file

import argparse
parser = argparse.ArgumentParser()  // initialize parser
parser.add_argument("echo")  // add positional argument (default data type is string, action is store)
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")  // add a optional argument
args = parser.parse_args() // parses arguments and returns a dict like object
if args.verbose:
    print("verbosity turned on")
print(args.echo)

Files

Check if file exists

os modue can used to handle files on the system.
os.path.isfile : Checks if file exists on the given location, Also follows symbolic links
os.path.exists : Check if file or folder exists on the given location, Also returns False for broken symbolic link

Example:

import os
if os.path.isfile('test.txt'):
    file exists and do something

Open files for reading and writing

open function can be used read and write data to/from files
– return a file handle
– can be looped over to get data
!!! if not using with then need to close the file handle by fh.close() !!

Example:

with open('test.txt') as fh:
    do something

Lists

lists are array like objects in python. items can be added and removed from the list.
– list.append(x) : appends x to the list
– list.remove(x) : removes x from the list
– list.sort() : sorts the list in ascending order
– list.reverse(): sorts a sorted list in reverse order

Python Exam Notes

Section 1

Accepting Input

input command can be used to accept input from user.
It always returns a string so if you need to accept int then you need to typecast str to int.

data=input("Enter Number")

Generate random integers

random function can be used to generate random interegers, float or get random chars from a string

Generate random intergers between x & y

random.randint(x,y)

Generate float between 0 & 1

`random.random()

Get random char from a string

random.choice('string')

Conditional statements

if condition:
    do something
elif condition:
    do something
else:
    do something

Looping in python

while loop

while x < 10:
    do something

for loop

for i in range(0,3):
    do something

range(0,3) – will create list of 0-3 numbers

Formatting output

format function can be used to print str,int,float and binary
We do not need to specify the data type to print, format can figure out what the data type is

Example:

print("Printing String {}".format("Hello"))
print("Printing Integer {}".format(10))

Section 2

Scrape a webpage (download html source code a website)

urllib.request module can be used to scrape a webpage

Example:

import urllib.request
url = "www.amarchaudhari.me"
page=urllib.request.urlopen(url) // returns a file like object
pagetext=page.read().decode('utf-8')  // read data from the object and decode bytes to text

Searching for text/numbers in a html source

re module can be used to easily search text/numbers that match a regex
if text matching the regex is found then re.search will return a match group object.
– group(0) – the entire match
– group(1) – first matched sub-group
– None – if there is no match

Example:

price=re.search(r'[\d+]',pagetext)
if hasattr(price,'group'):
    do something
else:
    text not present and do something

OR
price=re.search(r'[\d+]',pagetext)
if price:
    do something

Time

import time
from time import strftime

time module can be used to get current system time.
strftime can give formatted output of current time.

Formatting Options:

Example:

from time import strftime
current_date=strftime("%Y-%m-%d")

Output:
2016-12-04

IPTables Essentials: Installation and Common Rules

Introduction

Iptables is a software firewall that is included with most modern unix operation systems by default. Iptables can be used to restrict/limit traffic incoming, outgoing and forwarded traffic on a linux box.

Installation

CentOS 7

$ yum install epel-release
$ yum install iptables-services

To use iptables on centos 7 you will need to disable firewalld
$ systemctl stop firewalld
$ systemctl disable firewalld 

Saving Rules

service iptables save

IPtables rules

Machine A

Accept from loopback

Loopback is an interface used by the machine to make network connections to itself. There could be some applications running on the loopback, such has a database server to which a webserver is connection on loopback.

iptables -A INPUT -i lo -j ACCEPT

Accept Established and Related Incoming Connections

established : connection setup ( 3-way handshake ) has been completed
related : packets related to established and which want to start new connections

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Accept ICMP icmp-type echo-request, echo-reply (ping), time-exceeded (traceroute), or destination-unreachable

ICMP packets are used to check connectivity to the server, usually ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT

Allow SSH from trusted IP ranges

iptables -A INPUT -p tcp -s 100.64.0.0/16,10.21.32.0/24,198.18.0.0/16 --dport 22 -m state --state NEW -j ACCEPT

Set default policies for INPUT, OUTPUT, FORWARD

DROP INPUT traffic that is not listed in rules

iptables -P INPUT DROP

ACCEPT FORWARD traffic that is not listed in rules

iptables -P FORWARD ACCEPT

ACCEPT OUTPUT Traffic

iptables -P OUTPUT ACCEPT

Drop outgoing traffic to facebook

Simplest way us to block the IP address returned by the DNS. Obviously if you want to be more specific then block all IP ranges of AS32934

iptables -A FORWARD -d 157.240.2.35 -j DROP
iptables -A FORWARD -d 31.13.74.36 -j DROP
iptables -A FORWARD -s 157.240.2.35 -j DROP
iptables -A FORWARD -s 31.13.74.36 -j DROP

Drop outgoing traffic to *.cheezburger.com

iptables -A FORWARD -d 216.176.177.72 -j DROP
iptables -A FORWARD -s 216.176.177.72 -j DROP

Allow forwarded traffic to other servers

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -p icmp -m icmp --icmp-type 8 -j ACCEPT
iptables -A FORWARD -p icmp -m icmp --icmp-type 0 -j ACCEPT
iptables -A FORWARD -p icmp -m icmp --icmp-type 11 -j ACCEPT
iptables -A FORWARD -p icmp -m icmp --icmp-type 3 -j ACCEPT
iptables -A FORWARD -p tcp -s 100.64.0.0/16,10.21.32.0/24,198.18.0.0/16 --dport 22 -m state --state NEW -j ACCEPT
iptables -A FORWARD -d 100.64.69.2,100.64.69.5 -p tcp --dport 80 -m state --state NEW -j ACCEPT
iptables -A FORWARD -d 100.64.69.2,100.64.69.5 -p tcp --dport 443 -m state --state NEW -j ACCEPT
iptables -A FORWARD -s 100.64.0.0/16 -d 100.64.69.3 -j ACCEPT
iptables -A FORWARD -s 100.64.0.0/16,172.20.74.4 -d 100.64.69.3 -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -s 100.64.0.0/16,172.20.74.4 -d 100.64.69.3 -p tcp --dport 20 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -d 100.64.69.4 -p tcp --dport 53 -j ACCEPT
iptables -A FORWARD -d 100.64.69.4 -p udp --dport 53 -j ACCEPT

Machine B & Machine F

Accept from loopback

Loopback is an interface used by the machine to make network connections to itself. There could be some applications running on the loopback, such has a database server to which a webserver is connection on loopback.

iptables -A INPUT -i lo -j ACCEPT

Accept Established and Related Incoming Connections

established : connection setup ( 3-way handshake ) has been completed
related : packets related to established and which want to start new connections

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Accept ICMP icmp-type echo-request, echo-reply (ping), time-exceeded (traceroute), or destination-unreachable

ICMP packets are used to check connectivity to the server, usually ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT

Allow SSH from trusted IP ranges

iptables -A INPUT -p tcp -s 100.64.0.0/16,10.21.32.0/24,198.18.0.0/16 --dport 22 -m state --state NEW -j ACCEPT

Accept NEW http, https traffic from any source

iptables -A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT

Set default policies for INPUT, OUTPUT, FORWARD

DROP INPUT traffic that is not listed in rules

iptables -P INPUT DROP

DROP FORWARD traffic that is not listed in rules

iptables -P FORWARD DROP

ACCEPT OUTPUT Traffic

iptables -P OUTPUT ACCEPT

Machine C

Accept from loopback

Loopback is an interface used by the machine to make network connections to itself. There could be some applications running on the loopback, such has a database server to which a webserver is connection on loopback.

iptables -A INPUT -i lo -j ACCEPT

Accept Established and Related Incoming Connections

established : connection setup ( 3-way handshake ) has been completed
related : packets related to established and which want to start new connections

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Accept ICMP icmp-type echo-request, echo-reply (ping), time-exceeded (traceroute), or destination-unreachable

ICMP packets are used to check connectivity to the server, usually ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT

Allow SSH from trusted IP ranges

iptables -A INPUT -p tcp -s 100.64.0.0/16,10.21.32.0/24,198.18.0.0/16 --dport 22 -j ACCEPT

Accept all INPUT traffic from 100.64.0.0/16

iptables -A INPUT -s 100.64.0.0/16 -j ACCEPT

Accept NEW FTP traffic from 100.64.0.0/16, 100.64.0.27 and 172.20.74.4

iptables -A INPUT -s 100.64.0.0/16,100.64.0.27,172.20.74.4 -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -s 100.64.0.0/16,100.64.0.27,172.20.74.4 -p tcp --dport 20 -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -s 100.64.0.0/16,100.64.0.27,172.20.74.4 -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED -j ACCEPT

Allow OUTPUT DNS to 100.64.69.4

iptables -A OUTPUT -d 100.64.69.4 -p tcp --dport 53 -j ACCEPT
iptables -A OUTPUT -d 100.64.69.4 -p udp --dport 53 -j ACCEPT

Allow OUTPUT ftp, http, https and ssh traffic to any source

iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 21 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 20 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 1024:65535 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

Allow OUTPUT ICMP traffic

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type destination-unreachable -j ACCEPT

Allow OUTPUT ESTABLISHED traffic

iptables -A OUTPUT -m state --state ESTABLISHED -j ACCEPT

Default policy for INPUT, OUTPUT is DROP

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

Machine D

Accept from loopback

Loopback is an interface used by the machine to make network connections to itself. There could be some applications running on the loopback, such has a database server to which a webserver is connection on loopback.

iptables -A INPUT -i lo -j ACCEPT

Accept Established and Related Incoming Connections

established : connection setup ( 3-way handshake ) has been completed
related : packets related to established and which want to start new connections

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Accept ICMP icmp-type echo-request, echo-reply (ping), time-exceeded (traceroute), or destination-unreachable

ICMP packets are used to check connectivity to the server, usually ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT

Allow SSH from trusted IP ranges

iptables -A INPUT -p tcp -s 100.64.0.0/16,10.21.32.0/24,198.18.0.0/16 --dport 22 -j ACCEPT

Allow INPUT DNS from any source

iptables -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p udp --dport 53 -j ACCEPT

Set default policies for INPUT, OUTPUT, FORWARD

DROP INPUT traffic that is not listed in rules

iptables -P INPUT DROP

ACCEPT FORWARD traffic that is not listed in rules

iptables -P FORWARD DROP

ACCEPT OUTPUT Traffic

iptables -P OUTPUT ACCEPT

Machine E

Accept from loopback

Loopback is an interface used by the machine to make network connections to itself. There could be some applications running on the loopback, such has a database server to which a webserver is connection on loopback.

iptables -A INPUT -i lo -j ACCEPT

Accept Established and Related Incoming Connections

established : connection setup ( 3-way handshake ) has been completed
related : packets related to established and which want to start new connections

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Accept ICMP icmp-type echo-request, echo-reply (ping), time-exceeded (traceroute), or destination-unreachable

ICMP packets are used to check connectivity to the server, usually ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT

Allow SSH from trusted IP ranges

iptables -A INPUT -p tcp -s 10.21.32.0/24 --dport 22 -m state --state NEW -j ACCEPT

Allow INPUT traffic to CIFS and SMB

iptables -A INPUT -s 10.21.32.0/24 -p tcp --dport 135 -j ACCEPT
iptables -A INPUT -s 10.21.32.0/24 -p udp --dport 137:139 -j ACCEPT
iptables -A INPUT -s 10.21.32.0/24 -p tcp --dport 445 -j ACCEPT

Set default policies for INPUT, OUTPUT, FORWARD

DROP INPUT traffic that is not listed in rules

iptables -P INPUT DROP

ACCEPT FORWARD traffic that is not listed in rules

iptables -P FORWARD DROP

ACCEPT OUTPUT Traffic

iptables -P OUTPUT ACCEPT

CISCO port-security configuration

Port security can be used to restrict devices communicating through the interface by limiting the MAC address on the interface. When you assign a SECURE MAC address to the port, the device does not forward/process frames that fall outside the group of secure mac addresses, resulting in dedicated bandwidth for the devices which are allowed to communicate through the port.

Port security guidelines and restrictions

  • Port security supports private vlans (PVLAN)
  • Port security supports dot1q tunnels
  • Port security does not support EtherChannel
  • Port security does not support port analyzer (SPAN)
  • Port security supports trunk ports only with following configuration –
    switchport trunk encapsulation
    switchport mode trunk
    switchport nonegotiate

Secure MAC address can be configured in the following ways :

  • Configure all MAC address using the switchport port-security mac-address mac_address command.
  • Allow the port to dynamically learn the MAC address of the connected devices.
  • Configure few specific MAC addresses and allow the port to dynamically learn rest
  • Configure sticky MAC address which are stored in the address-table, and added to the configuration file. If the switches needs to be restarted, the interface does not need to re-learn the MAC addresses as they are already in the configuration file.

Security Violation :
A security violation occurs when a device who is not part of secure mac address tries to communicate through the secure port.

  • If violation is occurs, switch sends a snmp trap
  • Violation mode action configured is executed

Violation Actions :

  • Shutdown – (default) Switch will shutdown the interface (err-disabled) and no frames are forwarded thereafter.
  • Protect – Switch allows only secure frames and blocks violating frames
  • Restrict – Switch restricts the data, sends a snmp trap and increases the SecurityViolation counter

To enable port security on a trunk, perform this task:

 
 

Command

Purpose

Step 1

Router(config)# interface type1  slot/port

Selects the LAN port to configure.

Step 2

Router(config-if)# switchport

Configures the port as a Layer 2 port.

Step 3

Router(config-if)# switchport trunk encapsulation {isl | dot1q}

Configures the encapsulation, which configures the Layer 2 switching port as either an ISL or 802.1Q trunk.

Step 4

Router(config-if)# switchport mode trunk

Configures the port to trunk unconditionally.

Step 5

Router(config-if)# switchport nonegotiate

Configures the trunk not to use DTP.

Step 6

Router(config-if)# switchport port-security

Enables port security on the trunk.

Step 7

Router(config-if)# do show port-securityinterface type1 slot/port | include Port Security

Verifies the configuration.

 

Reference : Cisco-port-security-docs

apxs binary missing for apache ( CentOS 6)

‘missing Apache httpd server packages.’ % APXS)

RuntimeError: The ‘apxs’ command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages.

To solve the above error , you need to install http-devel package :
# yum install httpd-devel

mod_wsgi for python3.4 and django >=1.7

if you are going to use python3.4 , The default version of mod_wsgi in apache is not going to work and you may get errors as following :

TEST_SETTING_RENAMES_REVERSE = {v: k for k, v in TEST_SETTING_RENAMES.items()}

This error is occuring because python3.4 does not support default version of mod_wsgi , So the fix is to re-compile/install compatible version.

Fixing the error :

Requirments –
– Python 3.4 installed with proper paths
– Apache devel install ( yum install httpd-devel )
>> if this is not installed , you will get error like : apxs binary missing

Installing new version on mod_wsgi –

# pip3.4 install mod_wsgi

Loading new mod_wsgi in apache :

# mod_wsgi-express install-module
>> This command will give you required statements you need to put in vhost config and restart your apache.
>> Please make sure you unload/de-active mod_python and mod_wsgi (old)