Hello Everyone !
This is MyAnsibleQuest!!!
Sorry for the late post. In the previous post, we built a custom Ansible module in Python. This post is relatively more interesting because it deals with a different perspective for using Ansible.
We have seen a lot of programs which needs human intervention for specific result oriented tasks. This intervention is making automation of tasks very difficult. I said difficult but not impossible. If we know the steps going to be asked by a program, we can automatically arrange for the set of answers. Its like you know the questions, you know the answers, and you want everything automatically taking place. Here I am just giving a glimpse of such automation as a small project using Python and Ansible.
During my college days, I have used a python script for scanning ports of a Linux System providing the ip/hostname and number of ports to be scanned. In network programming, a communication end point is created which allows a server to listen for requests. Once a communication end point has been established, our listening server can now enter its infinite loop, waiting for clients to connect, and responding to requests. Sockets are the "communication end point".
My complete python code 'myfirstpexp.py' looks like this:
#!/usr/bin/python
import sys, time, subprocess, re, os
from socket import *
from datetime import datetime
from socket import *
from datetime import datetime
host=' '
max_port = 5000 # default max port either ways you must enter a value
min_port = 1 # default min port either ways you must enter a value
min_port = 1 # default min port either ways you must enter a value
def scan_host(host, port, returnval = 1):
''' This function is used for checking whether port is open or not. '''
try:
s = socket(AF_INET, SOCK_STREAM)
try:
s = socket(AF_INET, SOCK_STREAM)
code = s.connect_ex((host, port))
if code == 0:
returnval = code
s.close()
except Exception, e:
pass
return returnval
returnval = code
s.close()
except Exception, e:
pass
return returnval
def host_check(host):
''' This function is used to check whether the host is alive or not. '''
''' The output of the ping command is set to null, and displays whether up or not. '''
devnull = open(os.devnull, 'w')
res = subprocess.call(["ping", "-c", "1", host], stdout=devnull, stderr=devnull)
if res == 0:
print host, 'is up!'
else:
print host, 'is down!'
sys.exit(1)
devnull = open(os.devnull, 'w')
res = subprocess.call(["ping", "-c", "1", host], stdout=devnull, stderr=devnull)
if res == 0:
print host, 'is up!'
else:
print host, 'is down!'
sys.exit(1)
def main():
''' This is the main function which asks for three values viz. '''
''' host: IP address of the host '''
''' Maximum Port: the max value of port to be scanned '''
''' Minimum Port: the min value of port to start for the scanning'''
try:
host = raw_input("(*) Enter Host Address: ")
max_port = int(raw_input("(*) Enter Max Port: "))
min_port = int(raw_input("(*) Enter Min Port: "))
except KeyboardInterrupt:
print "\n\n(*) Interruption by User Occured."
print "(*) Shutting down the Application."
sys.exit(1)
try:
host = raw_input("(*) Enter Host Address: ")
max_port = int(raw_input("(*) Enter Max Port: "))
min_port = int(raw_input("(*) Enter Min Port: "))
except KeyboardInterrupt:
print "\n\n(*) Interruption by User Occured."
print "(*) Shutting down the Application."
sys.exit(1)
host_check(host)
hostip = gethostbyname(host)
print "\n(*) Host: %s IP: %s" % (host, hostip)
print "\n\n(*) Scanning started at %s...\n" %(time.strftime("%H:%M:%S"))
start_time = datetime.now()
for port in range(min_port, max_port):
try:
response = scan_host(host, port)
print "\n(*) Host: %s IP: %s" % (host, hostip)
print "\n\n(*) Scanning started at %s...\n" %(time.strftime("%H:%M:%S"))
start_time = datetime.now()
for port in range(min_port, max_port):
try:
response = scan_host(host, port)
if response == 0:
print("(*) Port %d: Open" % (port))
except Exception, e:
pass
stop_time = datetime.now()
duration = stop_time - start_time
print "\n(*) Scanning done at %s ..." % (time.strftime("%H:%M:%S"))
print "(*) Scanning Duration: %s ..." % (duration)
print "(*) Have a nice day !!! ... 4hathacker_Ansible_Case"
print("(*) Port %d: Open" % (port))
except Exception, e:
pass
stop_time = datetime.now()
duration = stop_time - start_time
print "\n(*) Scanning done at %s ..." % (time.strftime("%H:%M:%S"))
print "(*) Scanning Duration: %s ..." % (duration)
print "(*) Have a nice day !!! ... 4hathacker_Ansible_Case"
if __name__ == "__main__":
main()
main()
Its a very simple port scanning code which includes three functions viz. host_check(), scan_host() and main(). All functions are explained within the multiple line comments.
Lets see how it looks when you run the code.
Now the actual task for us is to automate the following script using Ansible. To achieve the same, I have used a python module - Pexpect. Its a pure Python module which matches a pattern after watching the output and then respond as if a human were typing responses. We can install Pexpect with pip and you can seek any help from this link.
To use Pexpect in Ansible, we have to strictly follow the Ansible documentation otherwise I have seen a lot of problems while dealing with it. There is an Expect module in Ansible to do things like this, and it uses Pexpect behind the scene. I have created a 'firstpexp.yml' playbook which will automate the above python script.
1. In this playbook, I have used three variables viz., nmap_ip, max_port_number, min_port_number as vars.
2. While using expect module, firstly I ran the command module to run the myfirstpexp.py script.
3. In the responses, I have provided the already known output patterns in .yml format with their respective options to be filled at runtime via the vars.
4. echo is optional just for the sake of checking whether the script is running fine or not. This I have even confirmed with debug module also.
Note: Pexpect works fine only if the pattern matches the response asked. We must escape special characters. In order to work for automatic server setups, like mysql_secure_installation, ambari_setup, etc. this works very effectively.
This is how you can make use of expect module in Ansible and interact with scripts in bash, python, php, etc.
Merry Christmas !!!
0 comments: