Commit f74923bc7f72516f7e371da6605e2d6c419f1332

Authored by Ian Foster
1 parent b35fe03348
Exists in master

added pinhole scrip

Showing 1 changed file with 94 additions and 0 deletions Inline Diff

scripts/pinhole.py View file @ f74923b
File was created 1 #! /usr/bin/env python
2 """
3 usage 'pinhole port host [newport]'
4
5 Pinhole forwards the port to the host specified.
6 The optional newport parameter may be used to
7 redirect to a different port.
8
9 eg. pinhole 80 webserver
10 Forward all incoming WWW sessions to webserver.
11
12 pinhole 23 localhost 2323
13 Forward all telnet sessions to port 2323 on localhost.
14
15 """
16
17 import sys
18 from socket import *
19 from threading import Thread
20 import time
21 import signal
22 import os
23
24 running = True
25
26 def log( s ):
27 print '%s:%s' % ( time.ctime(), s )
28 sys.stdout.flush()
29
30 class PipeThread( Thread ):
31 pipes = []
32 def __init__( self, source, sink ):
33 Thread.__init__( self )
34 self.source = source
35 self.sink = sink
36
37 log( 'Creating new pipe thread %s ( %s -> %s )' % \
38 ( self, source.getpeername(), sink.getpeername() ))
39 PipeThread.pipes.append( self )
40 log( '%s pipes active' % len( PipeThread.pipes ))
41
42 def run( self ):
43 while running:
44 try:
45 data = self.source.recv( 1024 )
46 if not data: break
47 self.sink.send( data )
48 except:
49 break
50
51 log( '%s terminating' % self )
52 PipeThread.pipes.remove( self )
53 log( '%s pipes active' % len( PipeThread.pipes ))
54
55 class Pinhole( Thread ):
56 def __init__( self, port, newhost, newport ):
57 Thread.__init__( self )
58 log( 'Redirecting: localhost:%s -> %s:%s' % ( port, newhost, newport ))
59 self.newhost = newhost
60 self.newport = newport
61 self.sock = socket( AF_INET, SOCK_STREAM )
62 self.sock.bind(( '', port ))
63 self.sock.listen(5)
64
65 def run( self ):
66 while running:
67 newsock, address = self.sock.accept()
68 log( 'Creating new session for %s %s ' % address )
69 fwd = socket( AF_INET, SOCK_STREAM )
70 fwd.connect(( self.newhost, self.newport ))
71 PipeThread( newsock, fwd ).start()
72 PipeThread( fwd, newsock ).start()
73
74 if __name__ == '__main__':
75
76 print 'Starting Pinhole'