#!/usr/bin/python

# kclient.py: portknocking client
# This code is heavily based on the work of Marilen Corciovei
# Read the original at: http://len.is-a-geek.org/misc/portknock.html

import socket, os, sys
import select

# User-configurable
rem_ip = "192.168.0.100"                       # remote ip
open_portseq = [4005, 40034, 9001, 5674]       # open port sequence
close_portseq = [3421, 34321, 9783]            # close port sequence
timeout = 3                                    # timeout waiting for connection

def conn(sock, addr, dumbhack=None):
    sock.setblocking(0)
    try:
        sock.connect(addr)
    except socket.error:
        pass
    r,w,e = select.select([], [sock], [], timeout)
    if w:
        print 'Port already open?!', addr
    else:
        print 'Knock success', addr

def open_knock():
    for port in open_portseq:
        print "Knocking on port: %i" % port
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn(s, (rem_ip, port))
        s.close()

def close_knock():
    for port in close_portseq:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn(s, (rem_ip, port))
        s.close()

def main():
    if "-o" in sys.argv[1:]:
        open_knock()
    if "-c" in sys.argv[1:]:
        close_knock()

if __name__=='__main__':
    main()



syntax highlighted by Code2HTML, v. 0.9.1