How to interact with 'Windows service' synchronously in python - python

How about using pywin32 module ?
Or is there any way to achieve this through subprocess module ?

I can't imagine how this is possible.
Windows services do not expose generic messaging API; each service (should it choose to) exposes its own specific API via its own choice of IPC channel (eg. WCF).
Regardless though, nothing would allow you to do this synchronously; any kind of IPC will be an async call to the service endpoint.
You kind of need to be more specific in your question.
The available generic APIs for interacting with a windows service are basically limited to; stop, start, install, uninstall. Have a look here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms685942(v=vs.85).aspx
(If you are writing a new windows service, in python, ZeroMQ would be a very reasonable choice to interact with it from a command line python script; there are any number of alternative IPC channels for python which would be equally good)
--
To just start a service, try:
import win32service
import win32serviceutil
import time
win32serviceutil.StartService(serviceName)
status = win32serviceutil.QueryServiceStatus(serviceName)
while status == win32service.SERVICE_START_PENDING:
time.sleep(1)
status = win32serviceutil.QueryServiceStatus(serviceName)
Nb. You'll get an access denied error unless you spawn the python instance as administrator.

Related

Python - Windows Network Security Authentication

I'm currently writing a script where I need to gain access to another computer on my LAN while using administrative credentials that differ from the account I am logged in as. I attempted to use the requests module.
Here is my code so far:
import requests
with requests.Session() as c:
location = ('file://computer/c$/')
USERNAME = 'notrealusername'
PASSWORD = 'notrealpassword'
c.get(location)
logindata = dict(username=USERNAME, password=PASSWORD, next='/')
c.post(location, data=logindata, headers{"Referer":"file://computer/c$/"})
Can someone tell me how I can edit my code to make it work properly according to the criteria specified above?
Impacket
This 3rd party library is pretty useful for Windows related networking tasks. In this situation i would use their wmiexec.py script:
wmiexec.py
A semi-interactive shell, used through Windows Management Instrumentation. It does not require to install any service/agent at the target server. Runs as Administrator. Highly stealthy.
If your not wanting any 3rd party dependencies, you could write your own solution. A wmi shell is mentioned in the BlackHat Python book.

Python oauth2client async

I am fighting with tornado and the official python oauth2client, gcloud... modules.
These modules accept an alternate http client passed with http=, as long as it has a method called request which can be called by any of these libraries, whenever an http request must be sent to google and/or to renew the access tokens using the refresh tokens.
I have created a simple class which has a self.client = AsyncHttpClient()
Then in its request method, returns self.client.fetch(...)
My goal is to be able to yield any of these libraries calls, so that tornado will execute them in asynchronously.
The thing is that they are highly dependant on what the default client - set to httplib2.Http() returns: (response, content)
I am really stuck and cannot find a clean way of making this async
If anyone already found a way, please help.
Thank you in advance
These libraries do not support asynchronous. The porting process is not always easy.
oauth2client
Depending on what you want to do maybe Tornado's GoogleOAuth2Mixin or tornado-alf will be enough.
gcloud
Since I am not aware of any Tornado/asyncio implementation of gcloud-python, so you could:
you may write it yourself. Again it's not simple transport change of Connection.http or request, all the stuff around must be able to use/yield future/coroutines.
wrap it in ThreadPoolExecutor (as #Apero mentioned). This is high level API, so any nested api calls within that yield will be executed in same thread (not using the pool). It could work well.
external app (with ProcessPoolExecutor or Popen).
When I had similar problem with AWS couple years ago, I've ended up with executing, asynchronously, CLI (Tornado + subprocess.Popen + some cli (awscli, or boto based)) and simple cases (like S3, basic EC2 operations) with plain AsyncHTTPClient.

Python - Receive from Azure Service Bus Topic is very slow

I am toying around with home automation, and I am planning to use Azure Service Bus as my "core" for message handling. With the .NET SDKs everything works perfectly and is fast enough (milliseconds for send + receive). However, I am now using the "azure.servicebus" module with Python (Debian on a Raspberry Pi), and the receive_subscription_message call is far from fast. It varies between near instant to lagging a minute behind.
My code is as follows:
from azure.servicebus import ServiceBusService, Message, Queue
bus_service = ServiceBusService(
service_namespace='mynamespace',
shared_access_key_name='Listener1',
shared_access_key_value='...')
msg = bus_service.receive_subscription_message('messages', 'ListenerTest.py', peek_lock=True)
msg.delete()
I have toyed around with peek_lock True and False, but the behaviour is the same.
Has anyone else been able to get this stable / near instant?
Please make sure there has indeed messages in the subscription, also please be aware that .NET SDK by default uses a Service Bus specific protocol instead of http, but the Python SDK uses http polling (basically check if there're messages in the subscription once in a while). We can find the brief info at https://github.com/Azure/azure-sdk-for-python/blob/master/doc/servicebus.rst:
ServiceBus Queues are an alternative to Storage Queues that might be useful in scenarios where more advanced messaging features are needed (larger message sizes, message ordering, single-operaiton destructive reads, scheduled delivery) using push-style delivery (using long polling).
Per my understanding this might explain why you see the message received either instantly or up to a minute. Based on behavior that you described, you might want to use AMQP, which is based on bi-directional TCP, and thus does not require polling. To use AMQP, you may want to leverage the standard Proton-Python library, I'd like to suggest you to check https://msdn.microsoft.com/en-us/library/azure/jj841070.aspx for a sample. But please note the tips from that article:
Note that at the time of this writing, the SSL support in Proton-C is
only available for Linux operating systems. Because Microsoft Azure
Service Bus requires the use of SSL, Proton-C (and the language
bindings) can only be used to access Microsoft Azure Service Bus from
Linux at this time. Work to enable Proton-C with SSL on Windows is
underway so check back frequently for updates.

How to disable a windows service with python

I know how to use win32serviceutil to start, stop, and restart services, but how can I disable them, or set them on manual start? I'm fine with using any module compatible with Python 3.4.
Disable is one of windows service startup types. And it's different from normal windows service operations, such as start, stop, restart and so on.
You need to use --startup disabled as parameters for win32serviceutil. Here is detail description. Check Usage() function.
After setting startup type, you need to stop the service. And after that, that service will be disabled unless you change the startup type again.
Here is detail for windows service, if you find all detail about windows service startup type.
If this is the answer, please confirm it. Thanks!
I ended up using os.system and Windows' Sc.exe to do it. Like so:
import os
os.system("sc config " + servicename + " start=disabled")
I think we can use WMI(Windows Management Instrumentation) to disable the windows service with python module 'wmi'.
import wmi
c = wmi.WMI()
windows_update_services_list = [
"wuauserv",
"TrustedInstaller"
]
for service_name in windows_update_services_list:
service = c.Win32_Service(Name=service_name)[0]
service.ChangeStartMode(StartMode="Disabled")
other useful links:
win32-service
change service start mode
powershell commands:
Set-Service -Name <service name> -StartupType Disabled

How to add authentication to a (Python) twisted xmlrpc server

I am trying to add authentication to a xmlrpc server (which will be running on nodes of a P2P network) without using user:password#host as this will reveal the password to all attackers. The authentication is so to basically create a private network, preventing unauthorised users from accessing it.
My solution to this was to create a challenge response system very similar to this but I have no clue how to add this to the xmlrpc server code.
I found a similar question (Where custom authentication was needed) here.
So I tried creating a module that would be called whenever a client connected to the server. This would connect to a challenge-response server running on the client and if the client responded correctly would return True. The only problem was that I could only call the module once and then I got a reactor cannot be restarted error. So is there some way of having a class that whenever the "check()" function is called it will connect and do this?
Would the simplest thing to do be to connect using SSL? Would that protect the password? Although this solution would not be optimal as I am trying to avoid having to generate SSL certificates for all the nodes.
Don't invent your own authentication scheme. There are plenty of great schemes already, and you don't want to become responsible for doing the security research into what vulnerabilities exist in your invention.
There are two very widely supported authentication mechanisms for HTTP (over which XML-RPC runs, therefore they apply to XML-RPC). One is "Basic" and the other is "Digest". "Basic" is fine if you decide to run over SSL. Digest is more appropriate if you really can't use SSL.
Both are supported by Twisted Web via twisted.web.guard.HTTPAuthSessionWrapper, with copious documentation.
Based on your problem description, it sounds like the Secure Remote Password Protocol might be what you're looking for. It's a password-based mechanism that provides strong, mutual authentication without the complexity of SSL certificate management. It may not be quite as flexible as SSL certificates but it's easy to use and understand (the full protocol description fits on a single page). I've often found it a useful tool for situations where a trusted third party (aka Kerberos/CA authorities) isn't appropriate.
For anyone that was looking for a full example below is mine (thanks to Rakis for pointing me in the right direction). In this the user and password is stored in a file called 'passwd' (see the first useful link for more details and how to change it).
Server:
#!/usr/bin/env python
import bjsonrpc
from SRPSocket import SRPSocket
import SocketServer
from bjsonrpc.handlers import BaseHandler
import time
class handler(BaseHandler):
def time(self):
return time.time()
class SecureServer(SRPSocket.SRPHost):
def auth_socket(self, socket):
server = bjsonrpc.server.Server(socket, handler_factory=handler)
server.serve()
s = SocketServer.ForkingTCPServer(('', 1337), SecureServer)
s.serve_forever()
Client:
#! /usr/bin/env python
import bjsonrpc
from bjsonrpc.handlers import BaseHandler
from SRPSocket import SRPSocket
import time
class handler(BaseHandler):
def time(self):
return time.time()
socket, key = SRPSocket.SRPSocket('localhost', 1337, 'dht', 'testpass')
connection = bjsonrpc.connection.Connection(socket, handler_factory=handler)
test = connection.call.time()
print test
time.sleep(1)
Some useful links:
http://members.tripod.com/professor_tom/archives/srpsocket.html
http://packages.python.org/bjsonrpc/tutorial1/index.html

Categories