问题
I have some windows services written in C#. When somebody stops or starts the service, I would like to be able to determine who it was and log that information.
I tried logging Environment.UserName
but that evaluates to SYSTEM even on my local machine.
Also, for the time being these services are running on Windows 2000 server.
回答1:
Within the Event Viewer (Control Panel | Administrative Tools | Event Viewer) on the System tab the Service Control Manager logs who started and stop each event. I've just tested this myself and viewed the results. This leads me to two things:
- You may be able to query or hook those events from the Service Control Manager as they happen, or
- You can definitely just query the Event Viewer's "System" log to look for those events for your Service.
Hope that leads you to your solution.
回答2:
You can enable auditing according to this article
http://windowsitpro.com/systems-management/access-denied-auditing-users-who-might-be-starting-and-stopping-services
Additionally, it may be a good idea to alert email to yourself in OnStop() method.
回答3:
- You can filter the System EventLog by Service Control Manager
Event ID 7040 - covers Service start type change (eg disabled, manual, automatic)
Event ID 7036 - covers Service start/stop
For others that have PowerShell, you can use this:
get-eventlog -source "Service Control manager" -LogName System | select message, timegenerated, username | Out-GridView
回答4:
There probably isn't a way. Any of the normal .NET ways that you get at the environment's user are going to return the user whose credentials the service runs with (which will typically be SYSTEM, LOCAL SERVICE, NETWORK SERVICE, etc).
How I'd probably do it is poll the system to see if a user is logged in, and assume that user did it. Of course, this discounts services that are shut down by the system for some reason (presumably your service would not be), and can only help you narrow it down if more than one user is logged in at one time (but then, you could always log both of them).
回答5:
- Just open Event Viewer (Start menu -> Search "Event" Event Viewer will come, open it)
- Expand 'Windows Log' on Event viewer left menu.
- Click on Application. (It will show your application error with description in 'general' tab.
- Again try to start your service and from event viewer see what is exact cause for stopping briefly in 'general' tab.
来源:https://stackoverflow.com/questions/496632/is-it-possible-to-log-who-started-or-stopped-a-windows-service