Python RESTful client with CAS authentication - python

I'm trying to build a python library for interacting with our RESTful API, but it uses CAS for client auth, and I haven't been able to find any good existing libraries for it. So far I've found the following links, but I'm not sure if they're intended to be used in clients or by a website that uses CAS itself. Does anyone have any advice for a good library to use and a good way to structure my code for interacting with it?
https://wiki.jasig.org/download/attachments/28213515/pycas.py.txt
https://sp.princeton.edu/oit/sdp/CAS/Wiki%20Pages/Python.aspx
http://github.com/benoitc/restkit/
http://morethanseven.net/2009/02/18/python-rest-client.html
I also just tried using caslib, but that fails to work:
>>> import caslib
>>> srv = caslib.CASServer('https://my.cas/auth')
>>> svc = caslib.CASService('https://my.service/foo')
>>> caslib.login_to_cas_service(srv.login(svc),'user#example.com','password')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "caslib/cas_dance.py", line 250, in login_to_cas_service
raise CASLoginError('Could not parse the document at %s: %s' % (login_fh.url, errors))
caslib.cas_dance.CASLoginError: Could not parse the document at https://my.cas/auth/login?service=https%3A%2F%2Fmy.service%2Ffoo: undefined entity ©: line 97, column 26
Hmm, the error above appears to be in our markup (or the validater that caslib uses.)
Edit again: The failure is removed after installing the lxml library for python. The fallback parser didn't work as well.

You might have to roll you own solution, either by modifying the python rest client to support CAS, or building something from scratch (I would recommend on top of httplib2.)

Eleven years later, there are at least two Python CAS libraries, with Flask examples available:
python-cas - seems more current
Flask-CAS -- Github repo gone
I don't personally have these working yet, so YMMV.

Maybe, the official python example in: https://wiki.jasig.org/display/casum/restful+api

Related

"AttributeError: 'module' object has no attribute" - Can someone explain the meaning of this error message?

I'm trying to get the ODB library working. In the documentation at https://python-obd.readthedocs.io/en/latest/ it lists the following code:
import obd
connection = obd.OBD("/dev/ttyUSB0") # connects to USB or RF port
cmd = obd.commands.SPEED # select an OBD command (sensor)
response = connection.query(cmd) # send the command, and parse the response
print(response.value) # returns unit-bearing values thanks to Pint
print(response.value.to("mph")) # user-friendly unit conversions
When I put this in a file called test.py and I run it:
python2 test.py
I get the following error message:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import obd
File "/home/ubuntu/obd.py", line 3, in <module>
AttributeError: 'module' object has no attribute 'OBD'
Stackoverflow comes up with several iterations of this error message, but none clearly explain the problem, only giving specific solutions to those libraries.
I guess it's obvious that I'm new to Python, and I'm having trouble interpreting this error message, even after several hours of writing several small Python programs. I am of course also interested in why the error message is so un-intuitive to a newcomer and where I can gain the common knowledge I might be missing, and I guess this is as good a case to discover that through as any.
So far I have figured out the following:
<module> refers to the name of my python script that I am trying to run.
The mistake I made at first, was to name my test.py file, initially obd.py. This conflicted with the import obd as it was trying to import the file itself - even after I deleted it! The reason was that when I tried to run it the first time, it created a file called obd.pyc - and even though obd.py was no longer there, import OBD found the initially created obd.pyc and tried to import that - which of course does not contain the OBD object from the library I was trying to use.
This is not the detailed answer I'm looking for, so please add a more detailed explanation - or a link to how Python compiling works, if you can.

How to connect to remote OpenVas scanner with python?

I am exploring OpenVas tool for a project requirement, openVas is currently managed by Greenbone. I am getting error when I try to use remote scanner using python api.
I did all initial configuration, setup the required gui account etc and was able to scan the required systems manually however when I try to do the same using Python Api its not working. There isn't any example available on internet nor in there manual to verify my code.
I have used [https://pypi.org/project/python-gvm/] api.
I wrote simple code but its not working..
from gvm.connections import SSHConnection
from gvm.protocols.latest import Gmp
from gvm.transforms import EtreeTransform
from gvm.xml import pretty_print
connection = SSHConnection(hostname='192.168.1.84',username='alex',password='alex#123')
gmp = Gmp(connection)
gmp.authenticate('admin', 'admin')
# Retrieve current GMP version
version = gmp.get_version()
# Prints the XML in beautiful form
pretty_print(version)
I am getting error-
/usr/bin/python3.7 /home/punshi/PycharmProjects/nessus_api/openvas-greenbone.py
/usr/local/lib/python3.7/dist-packages/paramiko/kex_ecdh_nist.py:39: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be removed in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.
m.add_string(self.Q_C.public_numbers().encode_point())
/usr/local/lib/python3.7/dist-packages/paramiko/kex_ecdh_nist.py:96: CryptographyDeprecationWarning: Support for unsafe construction of public numbers from encoded data will be removed in a future version. Please use EllipticCurvePublicKey.from_encoded_point
self.curve, Q_S_bytes
/usr/local/lib/python3.7/dist-packages/paramiko/kex_ecdh_nist.py:111: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be removed in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.
hm.add_string(self.Q_C.public_numbers().encode_point())
Traceback (most recent call last):
File "/home/punshi/PycharmProjects/nessus_api/openvas-greenbone.py", line 8, in <module>
gmp.authenticate('admin', 'admin')
File "/usr/local/lib/python3.7/dist-packages/gvm/protocols/gmpv7.py", line 211, in authenticate
response = self._read()
File "/usr/local/lib/python3.7/dist-packages/gvm/protocols/base.py", line 54, in _read
return self._connection.read()
File "/usr/local/lib/python3.7/dist-packages/gvm/connections.py", line 126, in read
raise GvmError('Remote closed the connection')
gvm.errors.GvmError: Remote closed the connection
Process finished with exit code 1
I have tested SSH connection manually so the problem is either with my code or some other.
Additional Detail-
Ubuntu 16,
Greenbone Security Assistant 7.0.3 (gui)
Open Vas - 9.0.3
I've exactly the same problem that I solved it with TLSConnection instead of SSHConnection. Here is your code:
import gvm
from gvm.protocols.latest import Gmp
from gvm.transforms import EtreeTransform
from gvm.xml import pretty_print
connection =gvm.connections.TLSConnection(hostname='192.168.1.84')
gmp = Gmp(connection)
gmp.authenticate('admin', 'admin')
# Retrieve current GMP version
version = gmp.get_version()
# Prints the XML in beautiful form
pretty_print(version)
I am exploring OpenVas tool for a project requirement, openVas is currently managed by Greenbone.
Just a side note. OpenVAS is developed by Greenbone since many years now. Therefore we did rename the project to Greenbone Vulnerability Management (GVM) with version 10. Only the actual scanner component will be still named after OpenVAS. See https://community.greenbone.net/t/is-openvas-manager-and-gvmd-the-same/1777/3 for more details.
Using the SSHConnection needs some additional setup at the remote server. Using TLSConnection might be easier but needs also changes in the settings of gvmd/openvasmd because it is only listening on a unix socket by default.

Control firewalld in CentOS via Python's dbus module?

My goal is to automate configuring firewalls on CentOS 7 machines using Python.
The OS comes with firewalld, so that's what I'm using. I looked into it and found that it uses dbus (I've never heard of or dealt with any of this - please correct me if anything I say is incorrect.)
I found this documentation for how to control dbus processes using Python:
http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.txt
I checked and the version of Python that comes with the OS includes the dbus module, so it seems like a promising start.
That document suggests that I needed to learn more about what firewalld exposes via the dbus interface. So I did some more research and found this:
https://www.mankier.com/5/firewalld.dbus
The first document says I need to start out with a "well-known name". Their example for such a thing was org.freedesktop.NetworkManager. The second document is titled firewalld.dbus, so I figured that was as good a name as any to try since the document doesn't explicitly give a name anywhere else.
The first document also says I need a name for an object path. Their example is /org/freedesktop/NetworkManager. The second document has an object path of /org/fedoraproject/FirewallD1.
I put those together and tried using the first method the first document suggested, SystemBus's get_object():
>>> from dbus import SystemBus
>>> bus = SystemBus()
>>> proxy = bus.get_object('firewalld.dbus', '/org/fedoraproject/FirewallD1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/dbus/bus.py", line 241, in get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib64/python2.7/site-packages/dbus/proxies.py", line 248, in __init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib64/python2.7/site-packages/dbus/bus.py", line 180, in activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib64/python2.7/site-packages/dbus/bus.py", line 278, in start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib64/python2.7/site-packages/dbus/connection.py", line 651, in call_blocking
message, timeout)
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.ServiceUnknown:
The name firewalld.dbus was not provided by any .service files
I also gave org.fedoraproject.FirewallD1 a try as the first parameter but ended up with a similar error message.
Why are these not working? Is there some way I can discover what the proper names are? It mentions ".service files" at the end of the error message... where would such a file be located?
Edit: Found several ".service files" by using find / -name *.service. One of them is at /usr/lib/systemd/system/firewalld.service... seems pretty promising so I'll check it out.
Edit 2: It's a rather short file... only about 10 lines. One of them says BusName=org.fedoraproject.FirewallD1. So I'm not sure why it said the name was not provided by any .service files... unless it's not using this file for some reason?
If the unit file says:
BusName=org.fedoraproject.FirewallD1
Then maybe you should try using that as your bus name:
>>> import dbus
>>> bus = dbus.SystemBus()
>>> p = bus.get_object('org.fedoraproject.FirewallD1', '/org/fedoraproject/FirewallD1')
>>> p.getDefaultZone()
dbus.String(u'FedoraWorkstation')
I figured this out based on the fact that this:
>>> help(bus.get_object)
Says that the get_object call looks like:
get_object(self, bus_name, object_path, introspect=True, follow_name_owner_changes=False, **kwargs)

Use python 2 shelf in python 3

I have data stored in a shelf file created with python 2.7
When I try to access the file from python 3.4, I get an error:
>>> import shelve
>>> population=shelve.open('shelved.shelf')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "C:\Python34\lib\shelve.py", line 223, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "C:\Python34\lib\dbm\__init__.py", line 88, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
I'm still able to access the shelf with no problem in python 2.7, so there seems to be a backward-compatibility issue. Is there any way to directly access the old format with the new python version?
As I understand now, here is the path that lead to my problem:
The original shelf was created with Python 2 in Windows
Python 2 Windows defaults to bsddb as the underlying database for shelving, since dbm is not available on the Windows platform
Python 3 does not ship with bsddb. The underlying database is dumbdbm in Python 3 for Windows.
I at first looked into installing a third party bsddb module for Python 3, but it quickly started to turn into a hassle. It then seemed that it would be a recurring hassle any time I need to use the same shelf file on a new machine. So I decided to convert the file from bsddb to dumbdbm, which both my python 2 and python 3 installations can read.
I ran the following in Python 2, which is the version that contains both bsddb and dumbdbm:
import shelve
import dumbdbm
def dumbdbm_shelve(filename,flag="c"):
return shelve.Shelf(dumbdbm.open(filename,flag))
out_shelf=dumbdbm_shelve("shelved.dumbdbm.shelf")
in_shelf=shelve.open("shelved.shelf")
key_list=in_shelf.keys()
for key in key_list:
out_shelf[key]=in_shelf[key]
out_shelf.close()
in_shelf.close()
So far it looks like the dumbdbm.shelf files came out ok, pending a double-check of the contents.
The shelve module uses Python's pickle, which may require a protocol version when being accessed between different versions of Python.
Try supplying protocol version 2:
population = shelve.open('shelved.shelf', protocol=2)
According to the documentation:
Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
This is most likely the protocol used in the original serialization (or pickling).
Edited: You may need to rename your database. Read on...
Seems like pickle is not the culprit here. shelve relies also in anydbm (Python 2.x) or dbm (Python 3) to create/open a database and store the pickled information.
I created (manually) a database file using the following:
# Python 2.7
import anydbm
anydbm.open('database2', flag='c')
and
# Python 3.4
import dbm
dbm.open('database3', flag='c')
In both cases, it creates the same kind of database (may be distribution dependent, this is on Debian 7):
$ file *
database2: Berkeley DB (Hash, version 9, native byte-order)
database3.db: Berkeley DB (Hash, version 9, native byte-order)
anydbm can open database3.db without problems, as expected:
>>> anydbm.open('database3')
<dbm.dbm object at 0x7fb1089900f0>
Notice the lack of .db when specifying the database name, though. But dbm chokes on database2, which is weird:
>>> dbm.open('database2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/dbm/__init__.py", line 88, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
unless I change the name of the name of the database to database2.db:
$ mv database2 database2.db
$ python3
>>> import dbm
>>> dbm.open('database2')
<_dbm.dbm object at 0x7fa7eaefcf50>
So, I suspect a regression on the dbm module, but I haven't checked the documentation. It may be intended :-?
NB: Notice that in my case, the extension is .db, but that depends on the database being used by dbm by default! Create an empty shelf using Python 3 to figure out which one are you using and what is it expecting.
I don't think it's possible to use a Python 2 shelf with Python 3's shelve module. The underlying files are completely different, at least in my tests.
In Python 2*, a shelf is represented as a single file with the filename you originally gave it.
In Python 3*, a shelf consists of three files: filename.bak, filename.dat, and filename.dir. Without any of these files present, the shelf cannot be opened by the Python 3 library (though it appears that just the .dat file is sufficient for opening, if not actual reading).
#Ricardo Cárdenes has given an overview of why this may be--it's likely an issue with the underlying database modules used in storing the shelved data. It's possible that the databases are backwards compatible, but I don't know and a quick search hasn't turned up any obvious answers.
I think it's likely that some of the possible databases implemented by dbm are backwards-compatible, whereas others are not: this could be the cause of the discrepancy between answers here, where some people, but not all, are able to open older databases directly by specifying a protocol.
*On every machine I've tested, using Python 2.7.6 vs Pythons 3.2.5, 3.3.4, and 3.4.1
The berkeleydb module includes a retro-compatible
implementation of the shelve object. (You will also need to install Oracle Berkeley DB)
You just need to:
import berkeleydb
from berkeleydb import dbshelve as shelve
population = shelve.open('shelved.shelf')

PyWin32 get network information/statistics

I am trying to get Network Statistics for my Windows 7 system using PyWin32.
The steps I followed:
1) Run COM MakePy utility and than select network list manager 1.0
type library under type library.
2) Above process generated this python file.
Now the problem I am facing is after the above two steps what should be my next step. I tried a couple of things like:
I copied the CLSID = IID('{DCB00000-570F-4A9B-8D69-199FDBA5723B}') line from the above generated python file and used it like
>>> import win32com
>>> obj = win32com.client.gencache.GetClassForCLSID("{DCB00000-570F-4A9B-8D69-199FDBA5723B}")
>>> obj.GetConnectivity()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: unbound method GetConnectivity() must be called with INetworkListManager instance as first argument (got nothing instead)
When I do obj.method() it show a list of all available method.
So, now I have no idea what to do or how to proceed and what is the general process of using Type library with pywin32.
The above task is just a part of learning process on how to use PyWin32,COM MakePy utility.
Is this even achievable using pywin32.?
You'll need to use win32com.client.Dispatch to actually create the object.
Also, the class you start with is the CoClass, in this case
class NetworkListManager(CoClassBaseClass): # A CoClass
is the one you want.
win32com.client.Dispatch('{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')
works here.
Many of these Dispatch classes have a human readable dotted name as an alias, although
this particular one doesn't seem to.

Categories

Resources