fictive-kin / wireguard

MIT License
29 stars 8 forks source link

Client Vpn #18

Open yury-miguel opened 3 days ago

yury-miguel commented 3 days ago

How could I use lib to set up a client and start it?

jnhmcknight commented 2 days ago

If you are not already familiar with setting up WireGuard, then I suggest you look through the official documentation first: https://www.wireguard.com/quickstart/

As the README shows in a very basic way, you can create a configuration for a client fairly quickly. In order to include the appropriate directives in the config file to connect to a remote peer, you will need certain information about the remote peer: it's public address (whether IP or domain name) and UDP port, it's internal IP and it's public (or private) key. And then add the new local peer to the remote peer's configuration in a similar way

It will end up looking something like this (warning: this code was not actually tested):


from wireguard import Server

# the private_key is not required if this is a completely new installation, but will
# be needed to add other clients to the setup without breaking any that have
# already been configured.
existing_peer = Server(
    'my-existing-peer',
    '192.168.24.1/24',
    private_key='some-private-key',
    endpoint='my-vpn.example.com',
    port=51820,
)

new_peer = existing_peer.peer('my-new-client')

# Output the new client's config for copying to the peer device
print(new_peer.config.local_config)

# For writing the config file and reloading the service, the user running this would
# need appropriate privileges on the system.

# Write out the existing peer's config to the default location: /etc/wireguard/wg0.conf
# including the newly created peer
existing_peer.config.write()

# Restart/reload the wireguard service on the existing peer
existing_peer.service.sync(existing_peer.config.full_path)

After saving the config that was outputted for the new_peer onto your new client, you would start up the wireguard service on the new client.

There are other options that are available to be used in the config files, which can be found by looking through the Peer and Server classes, but descriptions of what the options will do are in the wg documentation: https://git.zx2c4.com/wireguard-tools/about/src/man/wg.8

yury-miguel commented 1 day ago

OK Thanks for your feedback and I will check your sample code provided, I ended up doing the following code below to connect the client:


# CAMINHO DO WIREGUARD
WG_TUNNEL = "TesteAuto"
WG_EXECUTAVEL = r"wireguard.exe"
WG_CONF = r"cliente.conf"

# RETORNA SE O EXECUTÁVEL ESTÁ OU NÃO INSTALADO
def checha_instalacao():
    return os.path.exists(WG_EXECUTAVEL)

# INSTALA SE NECESSÁRIO O WIREGUARD
def instala_wireguard():
    instalador = r""
    subprocess.run(['msiexec', '/i', instalador, '/quiet'], check=True)
    print("WireGuard Instalado com sucesso!")

#COPIA O ARQUIVO DE CONFIGURAÇÃO PARA UM LOCAL RECONHECIDO
def cria_tunel():
    wg_tunnel_conf = fr"C:\Program Files\WireGuard\Data\Configurations\{WG_TUNNEL}.conf"
    os.makedirs(os.path.dirname(wg_tunnel_conf), exist_ok=True)
    os.replace(WG_CONF, wg_tunnel_conf)
    print(f"Túnel {WG_TUNNEL} criado com sucesso!")

# CONECTA NA VPN SERVER
def conecta_vpn():
    try:
        if not checha_instalacao():
            print("Wireguard não foi instalado, Instalando agora ....")
            instala_wireguard()

        print(f"Conectando a vpn {WG_CONF}")
        subprocess.run([WG_EXECUTAVEL, '/installtunnelservice', WG_CONF], check=True)
        print("Conectado com sucesso à VPN")

        time.sleep(5)

        resposta = subprocess.run(['ping', '10.10.0.1'], stdout=subprocess.PIPE)
        print(resposta.stdout)

    except subprocess.CalledProcessError as e:
        print("Erro ao conectar à Vpn:",e)

# DESCONECTA DA VPN SERVER
def desconecta_vpn():
    try:
        subprocess.run([WG_EXECUTAVEL, '/uninstalltunnelservice', WG_TUNNEL], check=True)
        print("Desconectado da VPN com sucesso!")

    except subprocess.CalledProcessError as e:
        print("Erro ao desconectar da Vpn",e)`