Search code examples
pythonwindowsssh

SSH command times out the 6th time it calls after working correctly 5 times


I have Python code in a script like this -

def run_ssh_cmd(host, cmd):
    global i
    i += 1
    ql(f"Running cmd {i}: {cmd}", "info", host)

    cmds = ["ssh", "-t", "-p", "22", host, cmd]
    process = Popen(cmds, stdout=PIPE, stderr=PIPE, stdin=PIPE)
    stdout, stderr = process.communicate()

    # Check if the command was successful
    if process.returncode != 0:
        ql(f"Error occurred on cmd {cmd}: {stderr}", "error", host)
        raise CalledProcessError(process.returncode, cmds, stderr)

This code giving a timeout error on the 6th command, every time, when I run it from my PC. The error states "ssh: connect to host sub1.domain.io port 22: Connection timed out"

  • I can ssh into the domain without any issue and the first 5 times it runs fine
  • My colleague can run this script without any issues
  • I can even run this command on other servers on a different domain without any issue. It's only when I try to hit one of the subdomains of "domain.io" that this happens
  • It always works 5 times then times out on the 6th regardless of the command
  • I checked the ssh logs on the server and there's nothing strange or different there
  • I don't have any .ssh\config file

Why would my computer consistently get a connection timeout after 5 successful commands?


Solution

  • The issue was that UFW was installed on our server and it blocks the 6th SSH connection attempt within 30 seconds. Disabling it allows the commands to work. Looking into configuration options or an alternative firewall, but this at least solves the mystery.