pythonproxyparamikoportforwardingpysocks

Python port forwarding with dynamic SOCKs


I has been trying to create a port forwarding session including a dynamic socks with paramiko and pysocks, I already do it with plink using this:

plink -ssh -D 10100 -L 25000:PrivateServerIP:1494 user@RemoteServerIP

I am trying this but isn't working:

import paramiko
from getpass import getpass
import socks

USERNAME= 'username'
SERVER_IP = '138.x.x.x'
PRIVATE_IP = '10.x.x.x'
OTP = getpass()

def main():
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=SERVER_IP, username=signum, password=OTP)

    trans = client.get_transport()
    trans.open_channel("forwarded-tcpip", dest_addr = (PRIVATE_IP, 1494), src_addr = ('', 25000))
    
    s = socks.socksocket() 
    s.set_proxy(socks.SOCKS5, "",10100)

Solution

  • I run plink command in background using subprocess and QNetworkProxy for my app:

    import sys
    from PyQt5.QtWidgets import QMainWindow
    from PyQt5 import QtNetwork                                                                                                                                       
    from subprocess import Popen
    
    user = 'user'
    ip = 'x.x.x.x'
    passwd = 'passwd'
    dynamicPort = 10100
    sshPort = 22
    proxyHostName = 'localhost'
    
    cmnd = f'plink -batch -ssh -D {dynamicPort} -P {sshPort} {user}@{ip} -pw "{passwd}" "while [ True ]; do sleep 300;echo Keeping alive; done"'
    Popen(cmnd,shell=True)     
            
    
    class magic(QMainWindow):
        def __init__(self, *args, **kwargs):
            super(magic, self).__init__(*args, **kwargs) # Call the inherited classes __init__ method
            loadUi('file.ui', self) # Load the .ui file
                    
    
    def main(args):
        proxy = QtNetwork.QNetworkProxy()
        proxy.setType(QtNetwork.QNetworkProxy.Socks5Proxy)
        proxy.setHostName(proxyHostName)
        proxy.setPort(dynamicPort)
        QtNetwork.QNetworkProxy.setApplicationProxy(proxy)
        app = QApplication(args)
        a = magic()
        a.show()
        sys.exit(app.exec_())