The opening of ports is an important part of providing or accessing functions that are performed on a remote system. It is often not always easy to detect whether a target system can even be reached from a calling system. This post shows a Python code that can be used to do this kind of check.
Check if Port is Open
Below are two forms of a Python source code to check if a port on a target system can be reached, which also means whether it is open in the firewall too. The first is a VMware Cloud Foundation (VCF) Automation Python action, to perform this test with the data center infrastructure automation platform. The second is a Red Hat Ansible playbook, to perform this test with the IT process automation platform. Both use the same Python code, but it is embedded in the different platform frames.
VCF Automation Python Action
The code of the action is very easy to understand. There are two input parameters, the host name and the port of the target system. A connection to the remote system is established via the Python socket module, a low-level networking interface. If the return value is 0 the operation was successful and a message is output to the log. If the connection was established successfully, there is no block in the firewall.
""" Checks if the given port of the given host is open in the firewall.
@author Stefan Schnell <mail@stefan-schnell.de>
@license MIT
@version 0.1.0
@param {string} in_host - Name or IPv4 address of the target host
@param {number} in_port - Port to connect
@outputType Properties
"""
import json
import socket
def handler(context: dict, inputs: dict) -> dict:
outputs: dict = {}
host: str = str(inputs["in_host"])
port: int = int(inputs["in_port"])
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result_connect: int = sock.connect_ex((host, port))
if result_connect == 0:
print(f"At {host} is port {port} open")
else:
print(f"At {host} is port {port} not open")
except Exception as err:
print("Error:", repr(err))
finally:
sock.close()
outputs = {
"status": "done"
}
return outputs
|
Ansible Playbook
The same Python code is used in the playbook, the only difference is in the parameter passing, which is platform-specific. To execute it, it must be passed to the Python compiler and that is done in the first task of the playbook. The second task shows the result of the execution.
---
# Executes a Python script which is embedded in YAML and
# checks if the given port of the given host is open in the firewall.
#
# To pass the parameters host and port define in the AAP surveys
# the host as type text and the port as type integer.
# Or execute it with
# ansible-playbook checkIfPortIsOpen.yml -e in_host=127.0.0.1 -e in_port=443
#
# @author Stefan Schnell <mail@stefan-schnell.de>
# @license MIT
# @version 0.3.0
- name: Executes Python script and check if port at host is open
hosts: localhost
gather_facts: false
vars:
in_host: "127.0.0.1"
in_port: 443
check_port_python_code: |
#!/usr/bin/python3
import socket
def main():
host: str = "{{ in_host }}"
port: int = {{ in_port }}
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result_connect: int = sock.connect_ex((host, port))
if result_connect == 0:
print(f"At {host} is port {port} open")
else:
print(f"At {host} is port {port} not open")
except Exception as err:
print("Error:", repr(err))
finally:
sock.close()
if __name__ == "__main__":
main()
tasks:
- name: Python script execution
block:
- name: Execute Python script
ansible.builtin.command:
cmd: "/usr/bin/python3 -c '{{ check_port_python_code }}'"
changed_when: result.rc != 0
register: result
- name: Print result of the Python script
ansible.builtin.debug:
msg: "{{ result.stdout_lines }}"
|
Conclusion
These examples show several advantages. The direct interchangeability of Python code between the different platforms. Without any major modifications in the source code it can be used on both platforms. The Python code in the Ansible playbook can even be saved and used directly as a file. The direct use of Python code in a playbook offers further interesting opportunities to automate complex process steps with Ansible without leaving the playbook layer. In addition to all these perspectives, the task of checking the accessibility of the port of a remote system is also fulfilled. This approach has often helped me in many projects for necessary activations in the firewall.