Thursday, June 2, 2011

Keeping your idle ssh connection alive (the wrong way)

Need to keep an ssh connection alive? Maybe you're doing it wrong - use nohup. Can't? Got some weird corner case that needs a living ssh connection with some process doing something in the foreground? You could always use expect/pexpect. But that's too much trouble! This python script is a quick and dirty way of doing it wrong:
import time
import sys

def infinite():
    i = 0
    while 1:
        print "been asleep for ", i ,"hours"
        time.sleep(60 * 60)
        i += 1

def sleeper(minutes):
    print time.strftime("%a, %d %b %Y %I:%M:%S +0000", time.localtime())
    time.sleep(minutes * 60)
    print 'awaking'
    print time.strftime("%a, %d %b %Y %I:%M:%S +0000", time.localtime())

def main():
    if len(sys.argv) != 2:
        print "fail!"
        return
    if sys.argv[1] == "infinite":
        infinite()
    else:
        sleeper(int(sys.argv[1]))

if __name__ =="__main__":
    main()

Usage:
python keepawake.py 60 
Sleeps for 60 minutes
python keepawake.py infinite 
sleeps until you Ctrl+C

If you're using this often (why?! You're doing it wrong!) then of course just throw in an alias within your .bashrc:
alias keepawake='python ~/path/to/keepawake.py'

And now you can call:
keepawake 60
keepawake infinite
whenever your heart desires.

No comments:

Post a Comment