Unable to access PACS using pynetdicom3 - python

I'm trying to connect to a PACS server using Python (specifically pynetdicom3), however I'm unable to do so using the method specified in the documentation. I am able to access this server using dcm4che. E.g. running findscu -c AETitle#serverIP:port on the command line works (when run from the dcm4che folder).
However, when I try to connect to the server with pynetdicom3 using the code from the docs (slightly modified of course), I get an error regarding the "called AE title". This is the code:
from pynetdicom3 import AE, VerificationSOPClass
ae = AE(ae_title='AETitle',
port=port,
scu_sop_class=[VerificationSOPClass])
assoc = ae.associate(serverIP, port)
if assoc.is_established:
print('Connection established')
Where AETitle, port, and serverIP are the same as the ones I use to access the server in dcm4che, provided by the administrator.
This is the error:
E: Association Rejected:
E: Result: Rejected Permanent, Source: Service User
E: Reason: Called AE title not recognised
The output from running the dcm4che command specifies that the "called AE title" is the same as the one I've used in the command and code. Is this the correct way to specify AE title in pynetdicom3, and if not, what is?

You are currently defining the local Application Entity, i.e. your own python code with the AE title "AETitle".
In basic terms your application at the moment is saying "I am AETitle", not "I want to talk to AETitle" as it should, because the server is not recognising the called AE title.
You have to add the called AE title as a third argument on your association method call.
assoc = ae.associate(serverIP, port, "AEtitle")
Otherwise pynetdicom3 will use some kind of internal default or empty value for the called AE title.

Related

Access Azure EventHub with WebSocket and proxy

I'm trying to access Azure EvenHub but my network makes me use proxy and allows connection only over https (port 443)
Based on https://learn.microsoft.com/en-us/python/api/azure-eventhub/azure.eventhub.aio.eventhubproducerclient?view=azure-python
I added proxy configuration and TransportType.AmqpOverWebsocket parametr and my Producer looks like this:
async def run():
producer = EventHubProducerClient.from_connection_string(
"Endpoint=sb://my_eh.servicebus.windows.net/;SharedAccessKeyName=eh-sender;SharedAccessKey=MFGf5MX6Mdummykey=",
eventhub_name="my_eh",
auth_timeout=180,
http_proxy=HTTP_PROXY,
transport_type=TransportType.AmqpOverWebsocket,
)
and I get an error:
File "/usr/local/lib64/python3.9/site-packages/uamqp/authentication/cbs_auth_async.py", line 74, in create_authenticator_async
raise errors.AMQPConnectionError(
uamqp.errors.AMQPConnectionError: Unable to open authentication session on connection b'EHProducer-a1cc5f12-96a1-4c29-ae54-70aafacd3097'.
Please confirm target hostname exists: b'my_eh.servicebus.windows.net'
I don't know what might be the issue.
Might it be related to this one ? https://github.com/Azure/azure-event-hubs-c/issues/50#issuecomment-501437753
you should be able to set up a proxy that the SDK uses to access EventHub. Here is a sample that shows you how to set the HTTP_PROXY dictionary with the proxy information. Behind the scenes when proxy is passed in, it automatically goes over websockets.
As #BrunoLucasAzure suggested checking the ports on the proxy itself will be good to check, because based on the error message it looks like it made it past the proxy and cant resolve the endpoint.

Can not connect via AsyncSSH, error Host key is not trusted

When I run this script I receive SSH connection failed: Host key is not trusted error, but even connect to this host to take the key, keep to receive this error.
import asyncio, asyncssh, sys
async def run_client():
async with asyncssh.connect('172.18.17.9', username="user", password="admin", port=9321) as conn:
result = await conn.run('display version', check=True)
print(result.stdout, end='')
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SSH connection failed: ' + str(exc))
Try adding the known_hosts=None parameter to the connect method.
asyncssh.connect('172.18.17.9', username="user", password="admin", port=9321, known_hosts=None)
From asyncssh documentation here:
https://asyncssh.readthedocs.io/en/latest/api.html#asyncssh.SSHClientConnectionOptions
known_hosts (see Specifying known hosts) – (optional) The list of keys
which will be used to validate the server host key presented during
the SSH handshake. If this is not specified, the keys will be looked
up in the file .ssh/known_hosts. If this is explicitly set to None,
server host key validation will be disabled.
With me, it runs smoothly after inserting known_hosts=None
Here's my example when trying the coding sample in Ortega book:
I tried with hostname=ip/username/password of localCentOS, command test is ifconfig
import asyncssh
import asyncio
import getpass
async def execute_command(hostname, command, username, password):
async with asyncssh.connect(hostname, username = username,password=password,known_hosts=None) as connection:
result = await connection.run(command)
return result.stdout
You should always validate the server's public key.
Depending on your use case you can:
Get the servers host keys, bundle them with your app and explicitly pass them to asyncssh (e.g., as string with a path to your known_hosts file).
Manually connect to the server on the command line. SSH will then ask you if you want to trust the server. The keys are then added to ~/.ssh/known_hosts and AsyncSSH will use them.
This is related but maybe not totally your salvation:
https://github.com/ronf/asyncssh/issues/132
The real question you should be asking yourself as you ask this question (help us help you) is where is it all failing? Known-hosts via analogy is like env vars that don't show up when you need them to.
EDIT: Questions that immediately fire. Host key is found but not trusted? Hmm?
EDIT2: Not trying to be harsh towards you but I think it's a helpful corrective. You've got a software library that can find the key but is not known. You're going to come across a lot of scenarios with SSH / shell / env var stuff where things you take for granted aren't known. Think clearly to help yourself and to ask the question better.

ServerSelectionTimeoutError errno 11001 getaddrinfo failed python

mongodb_uri = "mongodb://[username:password#]XX.XX.XX.XX"
client = MongoClient(mongodb_uri)
db = client['database']
print(db)
collection_taxonomy = db['collection']
doc = collection_taxonomy.find()
pprint.pprint(doc)
for each_doc in doc:
pprint.pprint(each_doc)
I am getting time out error as I try to print each document of the collection. However, I do not get time out error when I try to connect to localhost.
Tried connecting with connect=False
client = MongoClient(mongodb_uri,connect=False)
Still I get time out error while i print each document.
What could be wrong? Appreciate if someone can help me .
I am using Python 3.5 and Pymongo 3.5.1
Thanks,
-Roopa
is "mongodb://[username:password#]XX.XX.XX.XX" the actual value of mongodb_uri or have you substituted that for the value in your actual application?
The "getaddrinfo failed" message indicates that the hostname you put in mongodb_uri is invalid.
Removed square brackets([]) after substituting values in actual application.
"mongodb://username:password#XX.XX.XX.XX"
Works like a charm.!
Thanks a ton.
Roopa
I got the same error when i had a restricted rights on the user account which was trying to connect, so please try changing the user access rights or use a different account with higher privileges
user with the below rights failed
readWrite#dbname.colname
user with the below rights worked (note this is the user created for Atlas application)
atlasAdmin#admin
The URI should be like "mongodb://username:password#host", where the host is the hostname or IP.
This happened to me when I was connecting with the name, but the host name changed, so I changed the URI to connect via the machine's IP.

What is "principal" argument of kerbros-sspi?

I was trying to connect to remote machine via WinRM in Python (pywinrm) using domain account, following the instruction in
How to connect to remote machine via WinRM in Python (pywinrm) using domain account?
using
session = winrm.Session(server, auth=('user#DOMAIN', 'doesNotMatterBecauseYouAreUsingAKerbTicket'), transport='kerberos')
but I got this:
NotImplementedError("Can't use 'principal' argument with kerberos-sspi.")
I googled "principal argument" and I got its meaning in mathematics,which is in complex_analysis (https://en.m.wikipedia.org/wiki/Argument_(complex_analysis)) and definitely not the right meaning. I'm not a native English speaker and I got stuck here.
The original code is here:
https://github.com/requests/requests-kerberos/blob/master/requests_kerberos/kerberos_.py
def generate_request_header(self, response, host, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
        # Flags used by kerberos module.
        gssflags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
        if self.delegate:
            gssflags |= kerberos.GSS_C_DELEG_FLAG
        try:
            kerb_stage = "authGSSClientInit()"
            # contexts still need to be stored by host, but hostname_override
            # allows use of an arbitrary hostname for the kerberos exchange
            # (eg, in cases of aliased hosts, internal vs external, CNAMEs
            # w/ name-based HTTP hosting)
            kerb_host = self.hostname_override if self.hostname_override is not None else host
            kerb_spn = "{0}#{1}".format(self.service, kerb_host)
            
            kwargs = {}
            # kerberos-sspi: Never pass principal. Raise if user tries to specify one.
            if not self._using_kerberos_sspi:
                kwargs['principal'] = self.principal
            elif self.principal:
                raise NotImplementedError("Can't use 'principal' argument with kerberos-sspi.")
Any help will be greatly appreciated.

How to get the list of windows administrators from a remote machine using WMI client for Python?

I am writing a Python script to retrieve the list of administrators users from a remote Windows box using the WMI client (https://pypi.python.org/pypi/WMI/1.4.9). This is the code I am using:
import wmi
wql = r'SELECT * FROM Win32_GroupUser WHERE GroupComponent="Win32_Group.Domain=\"MY_MACHINE\",Name=\"Administrators\""'
host = '10.253.6.38'
domain = 'My_Domain'
user = 'My_User'
auth_user = '{0}\{1}'.format(domain, user)
password = 'Secret
wmic = wmi.WMI(host, user=auth_user, password=password)
admins_list = wmic.query(wql)
But when I try running the query I get an exception with this error:
com_error: (-2147217385, 'OLE error 0x80041017', None, None)
I cannot find anywhere what that error means. If I run the exact same script but I use another query like for example SELECT PartComponent FROM Win32_SystemUsers, it works fine. To make it more strange, if I run the same query that is giving me problems directly in the remote machine using the "WMI Tester" it works perfectly. I have spent more than 2 days trying to make this work with no luck, I've run out of ideas. If anyone knows what is going on I could use some help here. thanks.

Categories