Directory tree:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
├─ config │ ├── .ssh │ │ └── id_rsa │ ├── config.json │ └── settings.json ├── fcntlwin.py ├── forward.py ├── forwarding-helper.py ├── functions.py ├── i18n.py ├── languages │ └── helper-ja_JP.json ├── rconfig │ ├── .ssh │ │ └── id_rsa │ ├── config.json │ └── settings.json ├── rforward.py └── rforwarding-helper.py |
forward.py (paramiko):
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
#!/usr/bin/env python # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. """ Sample script showing how to do local port forwarding over paramiko. This script connects to the requested SSH server and sets up local port forwarding (the openssh -L option) from a local port through a tunneled connection to a destination reachable from the SSH server machine. """ import getpass import os import socket import select try: import SocketServer except ImportError: import socketserver as SocketServer import sys from optparse import OptionParser import paramiko SSH_PORT = 22 DEFAULT_PORT = 4000 g_verbose = False theServer = None # serve_forever, shutdown, serve_close SendStatusFunction = None SelectLoopFlag = True Transport = None class ForwardServer(SocketServer.ThreadingTCPServer): daemon_threads = True allow_reuse_address = True class Handler(SocketServer.BaseRequestHandler): def handle(self): try: chan = self.ssh_transport.open_channel( "direct-tcpip", (self.chain_host, self.chain_port), self.request.getpeername(), ) except Exception as e: verbose( "Incoming request to %s:%d failed: %s" % (self.chain_host, self.chain_port, repr(e)) ) return if chan is None: verbose( "Incoming request to %s:%d was rejected by the SSH server." % (self.chain_host, self.chain_port) ) return verbose( "Connected! Tunnel open %r -> %r -> %r" % ( self.request.getpeername(), chan.getpeername(), (self.chain_host, self.chain_port), ) ) while SelectLoopFlag: print("# select loop") r, w, x = select.select([self.request, chan], [], []) if self.request in r: data = self.request.recv(1024) if len(data) == 0: break chan.send(data) if chan in r: data = chan.recv(1024) if len(data) == 0: break self.request.send(data) peername = self.request.getpeername() chan.close() self.request.close() verbose("Tunnel closed from %r" % (peername,)) def forward_tunnel(local_port, remote_host, remote_port, transport): global theServer, Transport Transport = transport # this is a little convoluted, but lets me configure things for the Handler # object. (SocketServer doesn't give Handlers any way to access the outer # server normally.) class SubHander(Handler): chain_host = remote_host chain_port = remote_port ssh_transport = transport try: theServer = ForwardServer(("", local_port), SubHander) # .serve_forever() theServer.serve_forever() except Exception as e: raise def shutdown(): # https://docs.python.org/2/library/socketserver.html verbose("Called server shutdown") global theServer, SelectLoopFlag, Transport verbose("Server is going shutdown") SelectLoopFlag = False if Transport: Transport.close() if theServer: theServer.shutdown() # Tell the serve_forever() loop to stop and wait until it does. theServer.server_close() # Clean up the server. May be overridden. else: verbose("theServer is None") theServer = None Transport = None verbose("Shutdown") def isShutdown(): global Transport if Transport: return False else: return True def verbose(s): global g_verbose if g_verbose: print(s) sendStatus(s) def sendStatus(status): global SendStatusFunction if not SendStatusFunction: return SendStatusFunction(status) HELP = """\ Set up a forward tunnel across an SSH server, using paramiko. A local port (given with -p) is forwarded across an SSH session to an address:port from the SSH server. This is similar to the openssh -L option. """ def get_host_port(spec, default_port): "parse 'hostname:22' into a host and port, with the port optional" args = (spec.split(":", 1) + [default_port])[:2] args[1] = int(args[1]) return args[0], args[1] def parse_options(): global g_verbose, SSH_PORT, SSH_PORT parser = OptionParser( usage="usage: %prog [options] <ssh-server>[:<server-port>]", version="%prog 1.0", description=HELP, ) parser.add_option( "-q", "--quiet", action="store_false", dest="verbose", default=True, help="squelch all informational output", ) parser.add_option( "-p", "--local-port", action="store", type="int", dest="port", default=DEFAULT_PORT, help="local port to forward (default: %d)" % DEFAULT_PORT, ) parser.add_option( "-u", "--user", action="store", type="string", dest="user", default=getpass.getuser(), help="username for SSH authentication (default: %s)" % getpass.getuser(), ) parser.add_option( "-K", "--key", action="store", type="string", dest="keyfile", default=None, help="private key file to use for SSH authentication", ) parser.add_option( "", "--no-key", action="store_false", dest="look_for_keys", default=True, help="don't look for or use a private key file", ) parser.add_option( "-P", "--password", action="store_true", dest="readpass", default=False, help="read password (for key or password auth) from stdin", ) parser.add_option( "-r", "--remote", action="store", type="string", dest="remote", default=None, metavar="host:port", help="remote host and port to forward to", ) options, args = parser.parse_args() if len(args) != 1: parser.error("Incorrect number of arguments.") if options.remote is None: parser.error("Remote address required (-r).") g_verbose = options.verbose server_host, server_port = get_host_port(args[0], SSH_PORT) remote_host, remote_port = get_host_port(options.remote, SSH_PORT) return options, (server_host, server_port), (remote_host, remote_port) """ { 'options': { 'verbose': True, 'port': 8000, 'readpass': True, 'look_for_keys': True, 'user': '', 'keyfile': None, # '/home/user/.ssh/id_rsa' 'password': '', # optional }, 'server': { 'address': '192.168.11.102', 'port': 22, }, 'remote': { 'address': 'localhost', 'port': 8080, }, } """ def main(opt, sendStatusFunction = None): # options, server, remote = parse_options() # print(options) # print(server) # print(remote) global SelectLoopFlag, SendStatusFunction if sendStatusFunction: SendStatusFunction = sendStatusFunction SelectLoopFlag = True password = None if opt['options']['readpass']: password = getpass.getpass("Enter SSH password: ") elif 'password' in opt['options']: password = opt['options']['password'] client = paramiko.SSHClient() client.load_system_host_keys() # client.set_missing_host_key_policy(paramiko.WarningPolicy()) # client.set_missing_host_key_policy(paramiko.RejectPolicy()) client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) verbose("Connecting to ssh host %s:%d ..." % (opt['server']['address'], opt['server']['port'])) try: client.connect( opt['server']['address'], opt['server']['port'], username=opt['options']['user'], key_filename=opt['options']['keyfile'], look_for_keys=opt['options']['look_for_keys'], password=password, ) except Exception as e: message = "*** Failed to connect to %s:%d: %r" % (opt['server']['address'], opt['server']['port'], e) verbose(message) # sys.exit(1) return 1 verbose( "Now forwarding port %d to %s:%d ..." % (opt['options']['port'], opt['remote']['address'], opt['remote']['port']) ) try: forward_tunnel( opt['options']['port'], opt['remote']['address'], opt['remote']['port'], client.get_transport() ) except KeyboardInterrupt: message = "C-c: Port forwarding stopped." print(message) verbose(message) # sys.exit(0) return 2 except Exception as e: if len(e.args) > 1: verbose(e.args[1]) else: verbose(str(e)) # print('Exception:') # print(' type : ' + str(type(e))) # print(' args : ' + str(e.args)) # print(' message: ' + e.message) # print(' e : ' + str(e)) # sys.exit(1) return 3 return 0 # shutdown if __name__ == "__main__": options, server, remote = parse_options() opt = { 'options': options.__dict__, 'server': { 'address': server[0], 'port': server[1], }, 'remote': { 'address': remote[0], 'port': remote[1], }, } print(opt) main(opt) |
rforward.py (paramiko):
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
#!/usr/bin/env python # Copyright (C) 2008 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. """ Sample script showing how to do remote port forwarding over paramiko. This script connects to the requested SSH server and sets up remote port forwarding (the openssh -R option) from a remote port through a tunneled connection to a destination reachable from the local machine. """ import getpass import os import socket import select import sys import threading from optparse import OptionParser import paramiko SSH_PORT = 22 DEFAULT_PORT = 4000 g_verbose = False Transport = None SendStatusFunction = None handlerStopEvent = threading.Event() # 停止フラグ reverseForwardTunnelStopEvent = threading.Event() # 停止フラグ def handler(chan, host, port): global handlerStopEvent handlerStopEvent.clear() sock = socket.socket() try: sock.connect((host, port)) except Exception as e: verbose("Forwarding request to %s:%d failed: %r" % (host, port, e)) return verbose( "Connected! Tunnel open %r -> %r -> %r" % (chan.origin_addr, chan.getpeername(), (host, port)) ) while not handlerStopEvent.is_set(): print("# 1 ####") r, w, x = select.select([sock, chan], [], []) if sock in r: data = sock.recv(1024) if len(data) == 0: break chan.send(data) if chan in r: data = chan.recv(1024) if len(data) == 0: break sock.send(data) chan.close() sock.close() verbose("Tunnel closed from %r" % (chan.origin_addr,)) def reverse_forward_tunnel(server_port, remote_host, remote_port, transport): global reverseForwardTunnelStopEvent reverseForwardTunnelStopEvent.clear() transport.request_port_forward("", server_port) while not reverseForwardTunnelStopEvent.is_set(): print("# 2 ####") sendStatus("# 2 ####") # chan = transport.accept(1000) chan = transport.accept(timeout=1) # timeout=sec if chan is None: continue thr = threading.Thread( target=handler, args=(chan, remote_host, remote_port) ) thr.setDaemon(True) thr.start() # thr.join() # Don't .join print("exit reverse_forward_tunnel") def shutdown(): global handlerStopEvent, reverseForwardTunnelStopEvent, Transport # https://docs.python.org/2/library/socketserver.html verbose("Called server shutdown") if not Transport: verbose("Shutdown canceled") return verbose("Server is going shutdown") handlerStopEvent.set() reverseForwardTunnelStopEvent.set() Transport.close() Transport = None verbose("Shutdown") def isShutdown(): if Transport: return False else: return True def verbose(s): global g_verbose if g_verbose: print(s) sendStatus(s) def sendStatus(status): global SendStatusFunction if not SendStatusFunction: return SendStatusFunction(status) HELP = """\ Set up a reverse forwarding tunnel across an SSH server, using paramiko. A port on the SSH server (given with -p) is forwarded across an SSH session back to the local machine, and out to a remote site reachable from this network. This is similar to the openssh -R option. """ def get_host_port(spec, default_port): "parse 'hostname:22' into a host and port, with the port optional" args = (spec.split(":", 1) + [default_port])[:2] args[1] = int(args[1]) return args[0], args[1] def parse_options(): global g_verbose parser = OptionParser( usage="usage: %prog [options] <ssh-server>[:<server-port>]", version="%prog 1.0", description=HELP, ) parser.add_option( "-q", "--quiet", action="store_false", dest="verbose", default=True, help="squelch all informational output", ) parser.add_option( "-p", "--remote-port", action="store", type="int", dest="port", default=DEFAULT_PORT, help="port on server to forward (default: %d)" % DEFAULT_PORT, ) parser.add_option( "-u", "--user", action="store", type="string", dest="user", default=getpass.getuser(), help="username for SSH authentication (default: %s)" % getpass.getuser(), ) parser.add_option( "-K", "--key", action="store", type="string", dest="keyfile", default=None, help="private key file to use for SSH authentication", ) parser.add_option( "", "--no-key", action="store_false", dest="look_for_keys", default=True, help="don't look for or use a private key file", ) parser.add_option( "-P", "--password", action="store_true", dest="readpass", default=False, help="read password (for key or password auth) from stdin", ) parser.add_option( "-r", "--remote", action="store", type="string", dest="remote", default=None, metavar="host:port", help="remote host and port to forward to", ) options, args = parser.parse_args() if len(args) != 1: parser.error("Incorrect number of arguments.") if options.remote is None: parser.error("Remote address required (-r).") g_verbose = options.verbose server_host, server_port = get_host_port(args[0], SSH_PORT) remote_host, remote_port = get_host_port(options.remote, SSH_PORT) return options, (server_host, server_port), (remote_host, remote_port) """ { 'options': { 'verbose': True, 'port': 8080, 'look_for_keys': True, 'keyfile': None, # '/home/user/.ssh/id_rsa' 'user': 'USER', 'password': '', # optional 'readpass': True, }, 'server': { 'address': '192.168.11.102', 'port': 22, }, 'remote': { 'address': 'localhost', 'port': 80, }, } """ def main(opt, sendStatusFunction = None): # options, server, remote = parse_options() # print(options) # print(server) # print(remote) global SendStatusFunction, Transport if sendStatusFunction: SendStatusFunction = sendStatusFunction password = None if opt['options']['readpass']: password = getpass.getpass("Enter SSH password: ") elif 'password' in opt['options']: password = opt['options']['password'] client = paramiko.SSHClient() client.load_system_host_keys() # client.set_missing_host_key_policy(paramiko.WarningPolicy()) # client.set_missing_host_key_policy(paramiko.RejectPolicy()) client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) verbose("Connecting to ssh host %s:%d ..." % (opt['server']['address'], opt['server']['port'])) try: client.connect( opt['server']['address'], opt['server']['port'], username=opt['options']['user'], key_filename=opt['options']['keyfile'], look_for_keys=opt['options']['look_for_keys'], password=password, ) except Exception as e: print("*** Failed to connect to %s:%d: %r" % (opt['server']['address'], opt['server']['port'], e)) # sys.exit(1) return 1 verbose( "Now forwarding remote port %d to %s:%d ..." % (opt['options']['port'], opt['remote']['address'], opt['remote']['port']) ) try: Transport = client.get_transport() reverse_forward_tunnel( opt['options']['port'], opt['remote']['address'], opt['remote']['port'], Transport ) # reverse_forward_tunnel( # opt['options']['port'], opt['remote']['address'], opt['remote']['port'], client.get_transport() # ) except KeyboardInterrupt: message = "C-c: Port forwarding stopped." print(message) verbose(message) # sys.exit(0) return 2 except Exception as e: if len(e.args) > 1: verbose(e.args[1]) else: verbose(str(e)) # print('Exception:') # print(' type : ' + str(type(e))) # print(' args : ' + str(e.args)) # print(' message: ' + e.message) # print(' e : ' + str(e)) # sys.exit(1) return 3 print("exit main") return 0 # shutdown if __name__ == "__main__": options, server, remote = parse_options() opt = { 'options': options.__dict__, 'server': { 'address': server[0], 'port': server[1], }, 'remote': { 'address': remote[0], 'port': remote[1], }, } print(opt) main(opt) |
forwarding-helper.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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ Name : rforwarding helper Overview : ssh tunnel GUI wrapper, connect local PC to Relay Server Date : 2018-09-14 """ """ See: https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop Run tkinter code in another thread https://qiita.com/xeno1991/items/b207d55a413664513e5f """ import os, sys, threading, time, platform import tkinter as tk import tkinter.font as font # https://github.com/python/cpython/blob/3.7/Lib/tkinter/ttk.py if platform.system().lower() == "linux": import tkinter.ttk as ttk else: import tkinter as ttk import functions import forward # Internationalization import i18n i18n = i18n.i18n("helper-") def t(s): return i18n.t(s) # class App(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.platform = platform.system().lower() print("platform: %s, os.name: %s" % (self.platform, os.name)) self.scriptPath = os.path.dirname(os.path.abspath(__file__)) self.configDir = "%s/config" % self.scriptPath self.configPath = "%s/config.json" % self.configDir self.settingsPath = "%s/settings.json" % self.configDir self.loadConfigs() self.start() def loadConfigs(self): try: self.config = functions.json_loads(self.configPath) self.config["options"]["keyfile"] = self.config["options"]["keyfile"].replace("${config_directory}", self.configDir) self.settings = functions.json_loads(self.settingsPath) except Exception as e: s = str(e) print(s) self.putStatus(s) def quit(self): s = t("Finishing...") print(s) self.putStatus(s) self.threadTimer1Stop() self.threadTunnelStop() self.root.quit() for thread in threading.enumerate(): if thread.isAlive(): print(thread) self.root.destroy() # Tcl_AsyncDelete: async handler deleted by the wrong thread break sys.exit() def run(self): self.root = tk.Tk() self.root.protocol("WM_DELETE_WINDOW", self.quit) self.root.title(t("Forwarding -L")) w = 640 h = 480 self.root.geometry("%dx%d" % (w, h)) self.root.minsize(w, h) self.root.maxsize(w * 3, h * 3) # Font Family fontSize = 11 try: fontFamily = self.settings[self.platform]["font-family"] except Exception as e: print(str(e)) fontFamily = "System" defaultFont = font.Font(self.root, family=fontFamily, size=fontSize, weight="normal") self.root.option_add("*Font", defaultFont) # Toolbar frameToobar = ttk.Frame(self.root) frameToobar.pack(fill="x") self.buttonQuit = ttk.Button(frameToobar, text=t("Quit")) self.buttonQuit["command"] = self.quit self.buttonQuit.grid() self.buttonConnect = ttk.Button(frameToobar, text=t("Connect")) self.buttonConnect["command"] = self.clickButtonConnect self.buttonConnect.grid(row=0, column=1) # Status frameStatus=ttk.Frame(self.root) frameStatus.pack(fill="both", expand="yes") label = ttk.Label(frameStatus, text=t("Status") + " / " + t("Information")) label.pack(side="top", anchor="w") self.textStatus = tk.Text(frameStatus, height=4, width=4) self.textStatus.pack(side="left", fill="both", expand="yes") # status textbox scrollbar scrollbar = ttk.Scrollbar(frameStatus, orient=tk.VERTICAL, command=self.textStatus.yview) self.textStatus["yscrollcommand"] = scrollbar.set scrollbar.pack(side="left", fill="y", anchor="w", pady=1) # Statusbar frameBottom=ttk.Frame(self.root) frameBottom.pack(fill="x") self.textStatusbar = ttk.Label(frameBottom, text="Hello") self.textStatusbar.pack(side="left", padx=4, pady=2) self.labelDateTime = ttk.Label(frameBottom, text="**-**-** **:**:**") self.labelDateTime.pack(side="right", padx=4, pady=2) # Start --------------- self.threadTunnel = None self.threadTimer1 = None self.threadTimer1StopEvent = threading.Event() # 停止フラグ self.threadTimer1Start() self.root.mainloop() print("mainloop stopped") # sys.exit() # if need? # statusbar -------------------- def putStatusbar(self, status): try: self.textStatusbar.configure(text=status) self.textStatusbar.update() except Exception as e: s = str(e) print(s) # status ------------------------------------ def clearStatus(self): self.textStatus.delete("1.0", tk.END) # 先頭から最後まで def putStatus(self, status): # print(status) try: self.textStatus.insert(tk.END, "%s\n" % status) # 最後の位置に挿入 self.textStatus.see(tk.END) # スクロールして最後へ self.textStatus.update() # UI force update except Exception as e: s = str(e) print(s) # thread timer 1 ---------------------------- def threadTimer1Stop(self): self.threadTimer1StopEvent.set() print("Wait while stop threadTimer1") self.threadTimer1.join(timeout=10) print("threadTimer1 stopped") self.threadTimer1 = None def threadTimer1Start(self): if self.threadTimer1: return self.threadTimer1StopEvent.clear() self.threadTimer1 = threading.Thread(target=self.threadTimer1Function) self.threadTimer1.start() def threadTimer1Function(self): while not self.threadTimer1StopEvent.is_set(): # ft = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ft = time.strftime("%Y-%m-%d %H:%M", time.localtime()) self.labelDateTime.configure(text="%s" % ft) # print(forward.isShutdown()) if forward.isShutdown(): self.putStatusbar(t("Disconnect")) self.buttonConnect.config(text=t("Connect")) else: self.putStatusbar(t("Connecting")) self.buttonConnect.config(text=t("Disconnect")) time.sleep(1) # loop interval # thread tunnel ------------------- def clickButtonConnect(self): if self.threadTunnel: self.threadTunnelStop() else: self.threadTunnelStart() def threadTunnelStop(self): timeout = 30 # sec forward.shutdown() print("Wait while shutting down the server.", end="") for i in range(timeout): print(".", end="") if forward.isShutdown(): break time.sleep(1) if self.threadTunnel: print("Wait while stop threadTunnel") self.threadTunnel.join(timeout=10) del(self.threadTunnel) print("threadTunnel stopped") self.threadTunnel = None def threadTunnelStart(self): if self.threadTunnel: return self.threadTunnel = threading.Thread(target=self.threadTunnelFunction) self.threadTunnel.start() self.buttonConnect.config(text=t("Disconnect")) def threadTunnelFunction(self): returncode = forward.main(self.config, self.putStatus) self.putStatus("Exit forward tunnel: returncode: %d" % returncode) if returncode != 0: self.threadTunnelStop() self.threadTunnel = None self.buttonConnect.config(text=t("Connect")) app = App() print("Now we can continue running code while mainloop runs!") |
rforwarding-helper.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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ Name : rforwarding helper Overview: ssh tunnel GUI wrapper, connect local PC to Relay Server Date : 2018-09-14 """ """ See: https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop Run tkinter code in another thread https://qiita.com/xeno1991/items/b207d55a413664513e5f """ import os, sys, threading, time, platform import tkinter as tk import tkinter.font as font # https://github.com/python/cpython/blob/3.7/Lib/tkinter/ttk.py if platform.system().lower() == "linux": import tkinter.ttk as ttk else: import tkinter as ttk import functions import rforward # Internationalization import i18n i18n = i18n.i18n("helper-") def t(s): return i18n.t(s) # class App(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.platform = platform.system().lower() print("platform: %s, os.name: %s" % (self.platform, os.name)) self.scriptPath = os.path.dirname(os.path.abspath(__file__)) self.configDir = "%s/rconfig" % self.scriptPath self.configPath = "%s/config.json" % self.configDir self.settingsPath = "%s/settings.json" % self.configDir self.loadConfigs() self.start() def quit(self): s = t("Finishing...") print(s) self.putStatus(s) self.putStatusbar(s) self.threadTimer1Stop() self.threadTunnelStop() self.root.quit() for thread in threading.enumerate(): if thread.isAlive(): print(thread) self.root.destroy() # Tcl_AsyncDelete: async handler deleted by the wrong thread break sys.exit() def run(self): self.root = tk.Tk() self.root.protocol("WM_DELETE_WINDOW", self.quit) self.root.title(t("Forwarding -R")) w = 640 h = 480 self.root.geometry("%dx%d" % (w, h)) self.root.minsize(w, h) self.root.maxsize(w * 3, h * 3) # Font Family fontSize = 11 try: fontFamily = self.settings[self.platform]["font-family"] except Exception as e: print(str(e)) fontFamily = "System" defaultFont = font.Font(self.root, family=fontFamily, size=fontSize, weight="normal") self.root.option_add("*Font", defaultFont) # Toolbar frameToobar = ttk.Frame(self.root) frameToobar.pack(fill="x") self.buttonQuit = ttk.Button(frameToobar, text=t("Quit")) self.buttonQuit["command"] = self.quit self.buttonQuit.grid() self.buttonConnect = ttk.Button(frameToobar, text=t("Connect")) self.buttonConnect["command"] = self.clickButtonConnect self.buttonConnect.grid(row=0, column=1) # Status frameStatus=ttk.Frame(self.root) frameStatus.pack(fill="both", expand="yes") label = ttk.Label(frameStatus, text=t("Status") + " / " + t("Information")) label.pack(side="top", anchor="w") self.textStatus = tk.Text(frameStatus, height=4, width=4) self.textStatus.pack(side="left", fill="both", expand="yes") # status textbox scrollbar scrollbar = ttk.Scrollbar(frameStatus, orient=tk.VERTICAL, command=self.textStatus.yview) self.textStatus["yscrollcommand"] = scrollbar.set scrollbar.pack(side="left", fill="y", anchor="w", pady=1) # Statusbar frameBottom=ttk.Frame(self.root) frameBottom.pack(fill="x") self.textStatusbar = ttk.Label(frameBottom, text="Hello") self.textStatusbar.pack(side="left", padx=4, pady=2) self.labelDateTime = ttk.Label(frameBottom, text="**-**-** **:**:**") self.labelDateTime.pack(side="right", padx=4, pady=2) # start --------------- self.threadTunnel = None self.threadTimer1 = None self.threadTimer1StopEvent = threading.Event() # 停止フラグ self.threadTimer1Start() self.root.mainloop() print("mainloop stopped") # sys.exit() # if need? # statusbar -------------------- def putStatusbar(self, status): try: self.textStatusbar.configure(text=status) self.textStatusbar.update() except Exception as e: print(str(e)) self.putStatus(str(e)) # status ------------------------------------ def clearStatus(self): self.textStatus.delete("1.0", tk.END) # 先頭から最後まで def putStatus(self, status): # print(status) try: self.textStatus.insert(tk.END, "%s\n" % status) # 最後の位置に挿入 self.textStatus.see(tk.END) # スクロールして最後へ self.textStatus.update() # UI force update except Exception as e: s = str(e) print(s) # thread timer 1 ---------------------------- def threadTimer1Stop(self): self.threadTimer1StopEvent.set() print("Wait while stop threadTimer1") self.threadTimer1.join(timeout=10) print("threadTimer1 stopped") self.threadTimer1 = None def threadTimer1Start(self): if self.threadTimer1: return self.threadTimer1StopEvent.clear() self.threadTimer1 = threading.Thread(target=self.threadTimer1Function) self.threadTimer1.start() def threadTimer1Function(self): while not self.threadTimer1StopEvent.is_set(): # ft = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ft = time.strftime("%Y-%m-%d %H:%M", time.localtime()) self.labelDateTime.configure(text="%s" % ft) if rforward.isShutdown(): self.putStatusbar(t("Disconnect")) else: self.putStatusbar(t("Connecting")) time.sleep(1) # loop interval # thread tunnel ------------------- def clickButtonConnect(self): if self.threadTunnel: self.putStatusbar(t("Stop connecting...")) self.threadTunnelStop() else: self.putStatusbar(t("Start connection...")) self.threadTunnelStart() def connectButtonText(self, s, color): try: self.buttonConnect.configure(text=s) except Exception as e: print(str(e)) self.putStatus(str(e)) def loadConfigs(self): try: self.config = functions.json_loads(self.configPath) self.config["options"]["keyfile"] = self.config["options"]["keyfile"].replace("${config_directory}", self.configDir) self.settings = functions.json_loads(self.settingsPath) except Exception as e: s = str(e) print(s) self.putStatus(s) def threadTunnelStop(self): timeout = 30 # sec rforward.shutdown() print("Wait while shutting down the server.", end="") for i in range(timeout): print(".", end="") if rforward.isShutdown(): break time.sleep(1) if self.threadTunnel: print("Wait while stop threadTunnel") del(self.threadTunnel) # self.threadTunnel.join(timeout=10) print("threadTunnel stopped") self.threadTunnel = None self.connectButtonText(t("Connect"), "#eeffee") def threadTunnelStart(self): if self.threadTunnel: return self.threadTunnel = threading.Thread(target=self.threadTunnelFunction) self.threadTunnel.start() self.connectButtonText(t("Disconnect"), "#ffeeee") def threadTunnelFunction(self): returncode = rforward.main(self.config, self.putStatus) self.putStatus("Exit rforward tunnel: returncode: %d" % returncode) if returncode != 0: self.threadTunnelStop() self.threadTunnel = None self.connectButtonText(t("Connect"), "#eeffee") app = App() print("Now we can continue running code while mainloop runs!") |
functions.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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- import os, time, platform, subprocess, json if platform.system().lower() == "windows": import fcntlwin as fcntl else: import fcntl # Internationalization import i18n i18n = i18n.i18n("helper-") def t(s): return i18n.t(s) # functions # CharacterEncoding = "utf-8_sig" # UTF-8 with BOM CharacterEncoding = "utf-8" # See: https://qiita.com/MuriNishimori/items/a89fe986e28909208e30 def withBOM(path): global CharacterEncoding """ UTF_16_LE_BOM = "\xFF\xFE" UTF_8_BOM = "\xEF\xBB\xBF" UTF_32_BE_BOM = "\x00\x00\xFE\xFF" UTF_32_LE_BOM = "\xFF\xFE\x00\x00" """ UTF_16_BE_BOM = "\uFEFF" if not os.path.exists(path): raise Exception(t("File not found: %s") % path) try: line_first = open(path, encoding="utf-8").readline() withBOM = line_first[0] == UTF_16_BE_BOM if withBOM: CharacterEncoding = "utf-8_sig" # UTF-8 with BOM else: CharacterEncoding = "utf-8" # print("with BOM: %s: %s" % (CharacterEncoding, path)) return withBOM except Exception as e: raise def json_loads(path): global CharacterEncoding if not os.path.exists(path): raise Exception(t("File not found: %s") % path) try: withBOM(path) with open(path, "r", encoding=CharacterEncoding) as file: fcntl.flock(file.fileno(), fcntl.LOCK_EX) # Wait until can lock by ownself. s = file.read() j = json.loads(s) # pprint.pprint(json, width=80) return j except Exception as e: raise def json_save(path, dict): global CharacterEncoding # pprint.pprint(dict, width=80) try: s = json.dumps(dict, sort_keys=False, indent=4) with open(path, "w", encoding=CharacterEncoding) as file: fcntl.flock(file.fileno(), fcntl.LOCK_EX) # Wait until can lock by ownself. file.write(s) return except Exception as e: raise def readTextFile(path): global CharacterEncoding if not os.path.exists(path): raise Exception(t("File not found: %s") % path) try: withBOM(path) with open(path, "r", encoding=CharacterEncoding) as file: fcntl.flock(file.fileno(), fcntl.LOCK_EX) # Wait until can lock by ownself. s = file.read() return s except Exception as e: raise def putLog(filePath, s): global CharacterEncoding try: with open(filePath, "a", encoding=CharacterEncoding) as file: fcntl.flock(file.fileno(), fcntl.LOCK_EX) # Wait until can lock by ownself. file.write(time.strftime("\n# %Y-%m-%d %H:%M:%S", time.localtime()) + "\n\n") file.write(s + "\n") return True except Exception as e: print(str(e)) return False def executeAssoc(filePath): if not os.path.exists(filePath): raise Exception("File not found") pf = platform.system().lower() # print(pf) if pf == 'windows': os.startfile(filePath) elif pf == 'darwin': subprocess.call(["open", filePath]) elif pf == 'linux': subprocess.call(["xdg-open", filePath]) else: raise Exception("Unknown OS") |
i18n.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 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ usage: import i18n i18n = i18n.i18n("helper-") def t(s): return i18n.t(s) """ import os import json import locale # from collections import OrderedDict # import pprint class i18n: def __init__(self, prefix, langCode = "auto"): self.prefix = prefix self.scriptPath = os.path.dirname(os.path.abspath(__file__)) self.langCode = "en_US" self.i18nResources = {} if langCode == "auto": locale.setlocale(locale.LC_ALL, "") l = locale.getlocale() print("self.langCode: %s, Charset: %s" % l) self.langCode = l[0] if os.name == "nt": # Windows self.langCode = self.langCode.lower().replace("japanese_japan", "ja_JP") else: self.langCode = langCode self.resource() def t(self, s): if s in self.i18nResources: return self.i18nResources[s] return s def resource(self): try: self.resourceDirectory = "%s/languages" % (self.scriptPath) resourcePath = "%s/%s%s.json" % (self.resourceDirectory, self.prefix, self.langCode) if not os.path.exists(resourcePath): print("Language resource not found: %s" % resourcePath) return False with open(resourcePath, "r", encoding="utf-8_sig") as file: s = file.read() self.i18nResources = json.loads(s) # pprint.pprint(self.i18nResources, width=80) return True except Exception as e: print(str(e)) return False |
config/config.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
{ "options": { "# Local PC port": "", "port": 6001, "# Connect to Relay Server": "", "user": "USER", "password": "PASSWORD", "keyfile": "${config_directory}/.ssh/id_rsa", "look_for_keys": true, "readpass": false, "verbose": true }, "server": { "# SSH Relay Server": "", "address": "vps-server.example.com", "port": 22 }, "remote": { "# Forward Port of Relay Server": "", "address": "localhost", "port": 6000 } } |
config/settings.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "windows": { "#1 font-family": "System", "#2 font-family": "Meiryo", "font-family": "BIZ UDゴシック" }, "darwin": { "font-family": "System" }, "linux": { "font-family": "VL Gothic" } } |
rconfig/config.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
{ "options": { "# Forward Port of Relay Server": "", "port": 6000, "# Connect to Relay Server": "", "user": "USER", "password": "PASSWORD", "keyfile": "${config_directory}/.ssh/id_rsa", "look_for_keys": false, "readpass": false, "verbose": true }, "server": { "# SSH Relay Server": "", "address": "vps-server.example.com", "port": 22 }, "remote": { "# Local PC": "", "address": "localhost", "port": 80 } } |
rconfig/settings.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "windows": { "#1 font-family": "System", "#2 font-family": "Meiryo", "font-family": "BIZ UDゴシック" }, "darwin": { "font-family": "System" }, "linux": { "font-family": "VL Gothic" } } |
languages/helper-ja_JP.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
{ "Connect": "接続", "Connecting": "接続中", "Disconnect": "切断", "Quit": "終了", "Start connection...": "接続を開始しています...", "Stop connecting...": "接続を停止します...", "Status": "状態", "Information": "情報", "Finishing...": "終了中...", "File not found: %s": "ファイルが見つかりません: %s", "Unknown OS, Cannot execute file: %s": "不明な OS、ファイルを実行できません: %s", "Connect to Relay-server": "リレーサーバーへ接続" } |
fcntlwin.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 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ This module should be used only on Windows. instead of fcntl module on Windows. See: https://code.i-harness.com/ja-jp/q/15b420 Last Modified: 2019-02-14 Usage: if platform.system().lower() == "windows": import fcntlwin as fcntl else: import fcntl """ LOCK_EX = 2 def fcntl(fd, op, arg=0): return 0 def ioctl(fd, op, arg=0, mutable_flag=True): if mutable_flag: return 0 else: return "" def flock(fd, op): return def lockf(fd, operation, length=0, start=0, whence=0): return |
—