Configure SOCK5 proxy in Libtorrent session (Using Python) - python

I have been trying to configure proxy for a libtorent session; went through the documentation yet could not figure out a solution.
I tried the approach mentioned here. Did not work for me. This is the error I got-
r = lt.proxy_settings()
AttributeError: module 'libtorrent' has no attribute 'proxy_settings'. Did you mean: 'pe_settings'?
I tried to look for pe_settings() is the documentation but could not find anything like that. Being hopeful, I decided to do as the error message suggests, hoping it would lead me to some other error(from where i can pick up). Hence, I changed lt.proxy_settings() to lt.pe_settings(). The error that I get now is-
ses.set_dht_proxy(r)
Boost.Python.ArgumentError: Python argument types in
session.set_dht_proxy(session, pe_settings)
did not match C++ signature:
set_dht_proxy(libtorrent::session {lvalue}, libtorrent::aux::proxy_settings)
Mismatch in argument while trying to call the setters.
I also tried to use settings_pack. That did not work as well.
Here is what the session configuration looks like-
ses = lt.session()
ses.listen_on(6881, 6891)
r = lt.pe_settings()
r.proxy_hostnames = True
r.proxy_peer_connections = True
r.hostname = self.proxy_ip
r.username = ""
r.password = ""
r.port = self.proxy_port
r.type = lt.proxy_type_t().socks5_pw
#print lt.proxy_type().socks5_pw
#ses.set_dht_proxy(r)
#ses.set_peer_proxy(r)
#ses.set_tracker_proxy(r)
#ses.set_web_seed_proxy(r)
ses.set_proxy(r)
t = ses.settings()
t.force_proxy = True
t.proxy_hostnames = True
t.proxy_peer_connections = True
#t.proxy_tracker_connections = True
t.anonymous_mode = True
ses.set_settings(t)
print (ses.get_settings())
#ses.dht_proxy()
ses.peer_proxy()
#ses.tracker_proxy()
ses.web_seed_proxy()
ses.proxy()
ses.set_settings(t)
Any suggestions/ comments/ insights will be highly appreciated! Thanks!
Versions and platforms-
1. python 3.9
2. libtorrent 2.0.7 (installed it using vcpkg dependency manager)
3. mac os- Monterey
Vcpkg dependency manager installation steps
settings_pack documentation

you configure the proxy via the same settings_pack all other session-wide settings are configured via. Specifically you want to set:
proxy_hostname
proxy_port
proxy_type
Maybe proxy_username and proxy_password (docs)

Related

ssl.PROTOCOL_TLSv1_2 is deprecated, So what should I do?

I'm trying to get an image.
Here is my code.
import io
import ssl
from urllib import request
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
item_image = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/180px-Cat03.jpg"
f = io.BytesIO(request.urlopen(item_image,context=context).read())
When I try this code, warning appiers
C:\Users\xxx\AppData\Local\Temp\ipykernel_7868\2896668910.py:4: DeprecationWarning: ssl.PROTOCOL_TLSv1_2 is deprecated
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
I referred to this answer.
Python3 "DeprecationWarning: ssl.PROTOCOL_TLSv1_2 is deprecated sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)" error
So I tried to replace "ssl.PROTOCOL_TLSv1_2" to "ssl.PROTOCOL_TLS_CLIENT" or "ssl.PROTOCOL_TLS_SERVER"
but both does not work.
I've read document but I can not understand.https://docs.python.org/3/library/ssl.html
What shoud I do to clear this worning?
I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you
Mostly it is a matter of python configuration semantics (TLSv1.2 is still current, and supported by wikipedea), it's just the configuration approach has changed. Try:
context = ssl.SSLContext( ssl.PROTOCOL_TLS_CLIENT )
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.maximum_version = ssl.TLSVersion.TLSv1_3

Blocking DBus call from python API

I am programming a BLE device and therefore need to get some information from the org.freedesktop.DBus.Properties interface, but can't get it to work from dbus python API. From the console this is no problem. For example, from dbus-send I can invoke following method call successfully (with correct mac address of course):
$ dbus-send --system --dest=org.bluez --print-reply "/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX" org.freedesktop.DBus.Properties.Get string:'org.bluez.Device1' string:'Paired'
>> method return time=1645780543.222377 sender=:1.7 -> destination=:1.329 serial=1113 reply_serial=2
variant boolean true
Now, what I'm trying to do is actually something like this:
import dbus
bus = dbus.SystemBus()
connected = bus.call_blocking(
'org.bluez', #bus_name
'/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX', #object_path
'org.freedesktop.DBus.Properties', #dbus_interface
'Get', #method
signature='(ss)', #signature
args=['org.bluez.Device1', 'Connected'], #args
)
print(connected)
which gives me the error: ERROR:dbus.connection:Unable to set arguments ['org.bluez.Device1', 'Paired'] according to signature '(ss)': <class 'TypeError'>: Fewer items found in struct's D-Bus signature than in Python arguments
I tried also with no signature with no success. And I also found a similar question here, but for C-API. So I tried to adapt it to the python dbus API, but still can't get it to work. Moreover, the official documentation isn't very helpful as well, as there is no clear statement on how the argument mechanism works here or a reference to such an explanation. This is pretty annoying, since I can invoke a blocking call for instance on the GetManagedObjects method from org.freedesktop.DBus.ObjectManager interface that way, but that one takes no arguments of course...
Any help appreciated.
There are more Pythonic libraries for D-Bus such as pydbus
device_path = "/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX"
bus = pydbus.SystemBus()
device = bus.get('org.bluez', device_path)
print(device.Connected)
If you did want to do it with the deprecated python-dbus library then I have always done it this way:
BLUEZ_SERVICE_NAME = 'org.bluez'
DEVICE_INTERFACE = 'org.bluez.Device1'
remote_device_path = device_path
remote_device_obj = self.bus.get_object(BLUEZ_SERVICE_NAME,
remote_device_path)
remote_device_props = dbus.Interface(remote_device_obj,
dbus.PROPERTIES_IFACE)
print(remote_device_props.Get(DEVICE_INTERFACE, 'Connected'))
If you want to do it with PyGObject library then an example of that is:
from gi.repository import Gio, GLib
bus_type = Gio.BusType.SYSTEM
bus_name = 'org.bluez'
object_path = '/org/bluez/hci0'
prop_iface = 'org.freedesktop.DBus.Properties'
adapter_iface = 'org.bluez.Adapter1'
adapter_props_proxy = Gio.DBusProxy.new_for_bus_sync(
bus_type=bus_type,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name=bus_name,
object_path=object_path,
interface_name=prop_iface,
cancellable=None)
all_props = adapter_props_proxy.GetAll('(s)', adapter_iface)
print(all_props)
powered = adapter_props_proxy.Get('(ss)', adapter_iface, 'Powered')
print(powered)
Just for completeness and if someone stumble upon this:
You can get the deprecated API call to work if you change the signature to just ss instead of (ss) for some reason. This seems not to be consistent with other dbus APIs, which must have the signature as tuple.
connected = bus.call_blocking(
'org.bluez', #bus_name
'/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX', #object_path
'org.freedesktop.DBus.Properties', #dbus_interface
'Get', #method
signature='ss', #signature
args=['org.bluez.Device1', 'Connected'], #args
)

Python Pyramid(cornice) with Elasticsearch DSL

Using python pyramid and ElastiSearch. I looked at pythonelasticsearch-dsl which offers a nice ORM but I'm not sure how to integrate it with pyramid.
So far I made a "global connection" as per pythonelasticsearch-dsl and expose the connection via an attribute into pyramid's request.
Do you see anything wrong with this code ?!
from elasticsearch_dsl import connections
def _create_es_connection(config):
registry = config.registry
settings = registry.settings
es_servers = settings.get('elasticsearch.' + 'servers', ['localhost:9200'])
es_timeout = settings.get('elasticsearch.' + 'timeout', 20)
registry.es_connection = connections.create_connection(
hosts=es_servers,
timeout=es_timeout)
def get_es_connection(request):
return getattr(request.registry, 'es_connection',
connections.get_connection())
# main
def main(global_config, **settings):
...
config = Configurator(settings=settings)
config.add_request_method(
get_es_connection,
'es',
reify=True)
I use the connection as
#view
request.es ...
If there are any other ways I would appreciate any pointers - thank you.
A few things look weird, but I guess it comes from the copy/paste from your project (missing type cast in settings, connections undefined, etc.)
What you are trying to do is very similar to what you'd do with SQLAlchemy:
https://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/database/sqlalchemy.html
But according the docs of pythonelasticsearch-dsl you don't even have to bother with all that, since the lib allows you define a global default connection:
https://elasticsearch-dsl.readthedocs.io/en/latest/configuration.html#default-connection

pysimplesoap - RuntimeError: No scheme given for url

My first attempt at using pysimplesoap (and my first attempt at soap) code
from pysimplesoap.client import SoapClient
j_location = 'http://api.jasperwireless.com/ws/schema'
j_xsd = 'http://api.jasperwireless.com/ws/schema/JasperAPI.xsd'
j_echo_wsdl = 'http://api.jasperwireless.com/ws/schema/Echo.wsdl'
j_billing_wsdl = 'http://api.jasperwireless.com/ws/schema/Billing.wsdl'
print 'Creating client'
myclient = SoapClient(wsdl=j_echo_wsdl)
print 'Target Namespace', myclient.namespace
The error
RuntimeError: No scheme given for url: JasperAPI.xsd
I'm not sure how I am supposed to resolve this error.
I guess the problem is because "JasperAPI.xsd" is referenced as a local file in the WSDL:
<xs:import namespace="http://api.jasperwireless.com/ws/schema" schemaLocation="JasperAPI.xsd"/>
I'm not entirely sure how schemaLocation is supposed to work. At least some software automatically transforms
schemaLocation="JasperAPI.xsd"
into
schemaLocation="http://api.jasperwireless.com/ws/schema/JasperAPI.xsd"
but at least libxml2 - which is used by most (all?) Python SOAP implementations - does not do this.
As a one-time quick fix you could try putting JasperAPI.xsd in your local working directory.

Configuring eulexistdb with python bringing errors in django setting module

I have following code written in python in order to communicate with ExistDB using eulexistdb module.
from eulexistdb import db
class TryExist:
def __init__(self):
self.db = db.ExistDB(server_url="http://localhost:8899/exist")
def get_data(self, query):
result = list()
qresult = self.db.executeQuery(query)
hits = self.db.getHits(qresult)
for i in range(hits):
result.append(str(self.db.retrieve(qresult, i)))
return result
query = '''
let $x:= doc("/db/sample/books.xml")
return $x/bookstore/book/author/text()
'''
a = TryExist()
response = a.get_data(query)
print response
I am amazed that this code runs fine in Aptana Studio 3 giving me the output I want, but when running from other IDE or using command "python.exe myfile.py" brings following error:
django.core.exceptions.ImproperlyConfigured: Requested setting EXISTDB_TIMEOUT, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I used my own localsetting.py to solve the problem using following code:
import os
# must be set before importing anything from django
os.environ['DJANGO_SETTINGS_MODULE'] = 'localsettings'
... writing link for existdb here...
Then I get error as:
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
How do I configure the setting in Django to suit for ExistDB? Help me here please..
Never Mind. I found the answer with little research from this site. What I did was created a localsetting.py file with following configurations.
EXISTDB_SERVER_USER = 'user'
EXISTDB_SERVER_PASSWORD = 'admin'
EXISTDB_SERVER_URL = "http://localhost:8899/exist"
EXISTDB_ROOT_COLLECTION = "/db"
and in my main file myfile.py I used :
from localsettings import EXISTDB_SERVER_URL
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'localsettings.py'
and In the class TryExist I changed in __ init __() as:
def __init__(self):
self.db = db.ExistDB(server_url=EXISTDB_SERVER_URL)
PS: Using only os.environ['DJANGO_SETTINGS_MODULE'] = 'localsettings' brings the django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty..
The reason your code works in an IDE but not at the command line is probably that you have a difference in what Python environments are used to run your code.
I've done a couple of tests:
Virtualenv with eulexistdb installed but not Django. eulexistdb tries to load django.conf but fails and so does not try to get its configuration from a Django configuration. Ultimately, your code runs without error.
Virtualenv with 'eulexistdb*and* Django:eulexistdbtries to loaddjango.conf` and succeed. I then tries to get is configuration from the Django configuration but fails. I get the same error you describe in your question.
To prevent the error in the presence of a Django installation, the problem can be fixed by adding a Django configuration like you did in your accepted self-answer. But if the code you are writing does not otherwise use Django, that's a bit of a roundabout way to get your code to run. The most direct way to fix the problem is to simply add a timeout parameter to the code that creates the ExistDB instance:
self.db = db.ExistDB(
server_url="http://localhost:8080/exist", timeout=None)
If you do this, then there won't be any error. Setting the timeout to None leaves the default behavior in place but prevents eulexistdb from looking for a Django configuration.

Categories