#!/usr/bin/python -O # # Copyright 2005 Sven Wegener # Distributed under the terms of the GNU General Public License v2 # # $Id: ssh-master 283 2005-09-06 13:56:20Z sven $ # from string import strip from os import getenv, wait, fork, spawnlp, P_NOWAIT from os import open, close, dup2, O_RDWR from sys import exit from time import time, sleep from signal import alarm, signal, SIGALRM from copy import copy if fork(): exit(0) # re-open stdin, stdout and stderr to /dev/null devnull = open('/dev/null', O_RDWR) dup2(devnull, 0) dup2(devnull, 1) dup2(devnull, 2) close(devnull) hostdict = {} waithostdict = {} hosts = file(getenv('HOME') + '/.ssh/master_hosts').readlines() hosts = map(strip, hosts) hosts = filter(lambda (line): line and not line.startswith('#'), hosts) def spawnmaster(host): pid = spawnlp(P_NOWAIT, 'ssh', 'ssh', '-nNM', host) hostdict[pid] = host for host in hosts: spawnmaster(host) def signal_alarm(sig, stack): myhostdict = copy(waithostdict) for x, y in myhostdict.iteritems(): if y < time(): spawnmaster(x) del waithostdict[x] alarm(10) signal(SIGALRM, signal_alarm) alarm(30) while True: try: pid, status = wait() except OSError, e: sleep(5) continue except: raise host = hostdict[pid] del hostdict[pid] waithostdict[host] = time() + 15