-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathport_forward.py
78 lines (69 loc) · 2.23 KB
/
port_forward.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#! /usr/bin/env python2
# Author: Mario Scondo (www.Linux-Support.com)
# Date: 2010-01-08
# Script template by Stephen Chappell
#
# This script forwards a number of configured local ports
# to local or remote socket servers.
#
# Configuration:
# Add to the config file port-forward.config lines with
# contents as follows:
# <local incoming port> <dest hostname> <dest port>
#
# Start the application at command line with 'python port-forward.py'
# and stop the application by keying in <ctrl-c>.
#
# Error messages are stored in file 'error.log'.
#
from __future__ import print_function
try:
import socket
import sys
import threading as thread
import time
except ImportError as e:
print("Something went wrong:\n{}".format(e))
def main(setup, error):
file = open(error, 'a')
# open file for error messages
sys.stderr = file.write(error)
# read settings for port forwarding
for settings in parse(setup):
thread.start_new_thread(server, settings)
# wait for <ctrl-c>
while True:
time.sleep(60)
def parse(setup):
settings = list()
for line in setup:
# skip comment line
if line.startswith('#'):
continue
parts = line.split()
settings.append((int(parts[0]), parts[1], int(parts[2])))
return settings
def server(*settings):
try:
dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dock_socket.bind(('', settings[0]))
dock_socket.listen(5)
while True:
client_socket = dock_socket.accept()[0]
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((settings[1], settings[2]))
thread.start_new_thread(forward, (client_socket, server_socket))
thread.start_new_thread(forward, (server_socket, client_socket))
finally:
thread.start_new_thread(server, settings)
def forward(source, destination):
string = ' '
while string:
string = source.recv(1024)
if string:
destination.sendall(string)
else:
source.shutdown(socket.SHUT_RD)
destination.shutdown(socket.SHUT_WR)
if __name__ == '__main__':
main('./port-forward.config', './error.log')