Listening on socket and executing commands

Last edited on

Introduction

Sometimes it is desirable for an external process to be able to send commands to Squish for Squish to execute.

Here is a basic example of a Squish test script that can receive commands from a socket and execute them.

⚠️ Be aware that using Python's _exec()_ command is intrinsically insecure (since it will try to execute any Python code it is given), so this script should only be used behind a firewall.

import socket
import sys

def main():
    host = ""
    port = 50000
    backlog = 5
    size = 1024
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen(backlog)
    while True:
        client, address = sock.accept()
        test.log("Client connected.")
        while True:
            data = client.recv(size).rstrip()
            if not data:
                continue
            test.log("Received command: %s" % data)
            if data == "disconnect":
                test.log("Client disconnected.")
                client.send(data)
                client.close()
                break
            if data == "exit":
                test.log("Client asked server to quit")
                client.send(data)
                client.close()
                return

            test.log("Executing command: %s" % data)
            try:
                exec(data)
            except Exception, err:
                test.log("Error occured while executing command: %s" % (
                        data), str(err))