Count logons and logoffs on computer Windows 7 - java

I want to count the number of logons and logoffs on users of their computers. I take the information for logons/logoffs from the Windows event logs (from Win32_NTLogEvent WMI class). For example with following query:
select * from Win32_NtLogEvent
where EventCode = 4648 and TimeGenerated > '20120224000000.000000-***'
But when the computer has been restarted or started it counts 3 logons, when the user has clicked logoff or lock (from start menu) and then logon it counts 1 logon. The user authenticates via Windows Active Directory. Does it influence on the number of logons? Can I count only the number of logons using explicit credentials on users?
I found EventCode: 4608 and 4609 for starting up and shutting down of Windows but I need also the number of logons when the user has logoffed or locked the computer.

I found this solution here:
strComputer = "."
Set objWMIService = GetObject("winmgmts:{(Security)}\\" & _
strComputer & "\root\cimv2")
Set colEvents = objWMIService.ExecQuery _
("SELECT * FROM Win32_NTLogEvent WHERE LogFile = 'Security' AND " & _
"EventCode = 528 AND User = 'fabrikam\\kmyer'")
Wscript.Echo colEvents.Count
Simply replace the values with the ones you want.
Now this isn't a Java but VB code... However it apparently uses the WMI interface that you could use from your Java program. Or you could do something ugly and invoke a batch script from Java (or scheduled task) and read its output, or use a binding.
This is of course assuming that you want to check this on the user's computer, as your question hinted. If you want to count logons at a more global level and from different machines, then you need to query the Active Directory (or other mechanism the networked infrastructure is using); the linked thread offers solutions for this as well.
Update:
You can have a look at Eric Fitzgerald's blog post on Tracking User Logon Activity Using Logon Events, where you have the corresponding codes (as well as complete formulas for accurate time tracking).
Apparently you want event codes 4624 (LOGON) and 4634 (LOGOFF), plus other ones listed there if you plan on using Fitzgerald's formulas to calculate the exact activity time.

A better approach would be to use a system service.
The HandlerEx callback function, defined by RegisterServiceCtrlHandlerEx, can be configured to receive session change notifications including logon, logoff, lock and unlock events.
I'm not entirely certain whether the logoff events received by HandlerEx are reliable or if they exhibit the same problems as the event log. As a backup, SetConsoleCtrlHandler allows you to define a callback function to receive logoff notifications. These notifications are reliable.
The remote desktop services API functions, such as WTSEnumerateSessions, may also be useful, allowing you to list the currently logged-on users at any given time, or get additional information about a given session. Only a subset of these functions are available on workstations, but they're the ones you need.

Related

Change SIM country programmatically?

How can I programmatically change the country & network of an Android phone's SIM without root access? I'm using this code to retrieve information:
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
System.out.println(tm.getSimCountryIso()); // prints 'us', but I want it to be 'fr'
System.out.println(tm.getNetworkCountryIso()); // prints 'us, but I want it to be 'fr'
As my SIM card is from the USA, both of the outputs are us. How can I programmatically make the output be fr (France) for example?
Basically, I want to trick my smartphone into thinking its SIM's country & network is France, for example.
Something like this would be perfect but it doesn't exist:
tm.setSimCountryIso('fr')
tm.setNetworkCountryIso('fr')
What you are asking for is not possible without root.
As already stated in the comments, it is not physically possible to change the ICCID of the SIM unless it is a special writable SIM.
As for the call to getSimCountryIso and getNetworkCountryIso() those are system API's.
Without root, there is no way to interfere with their operation.
Android is built with several layers of security including restricting app access based on user privileges, enforcing SELinux on by default, verity checks as part of verified boot and more.
If you do have root on device, you can create an Xposed framework module that can hook these functions and overwrite their return value.
If you are curious, the table used to translate ICCID info into a two letter country name is hardcoded here.
In case that link does not open right - it starts on line 316.
So changing that would require recompiling one of the core JARs of the OS.
Also note, that depending on your real purpose, altering the result of these two functions may not work at all.
For example, if you want to create a Google account from the phone for a different country, changing the SIM will not help, since Google will still look at your IP address, regardless of how you are connected to the internet.

Retrieving password expiry warning from Active Directory

I have a system that uses Active Directory to authenticate users. Now I must use the security settings from AD to warn a user that his password will expire in a few days. The period before a password will be expired when the notification is presented to users is defined as described in this article.
I want to read the value set in "Interactive logon: Prompt user to change password before expiration"
from AD using javax.naming.directory.InitialDirContext. I hope this value is remembered in AD but I have no idea how to find it. I was looking in a set of AD attributes but noone seems to match this information. Is it possible to retrieve this value from AD?
This is more complicated as this setting is not directly held in Active Directory. This is a part of Group Policy (considering it's configured in a policy and not on a local computer), which is held on a network share and linked in Active Directory.
For a simple example, you can get into it like this:
Read your intended OU and check for gPLink attribute. The value is something like a list of Group Policy objects linked to the selected OU in a priority descending order. Each of the values is something like: [LDAP://CN={31B2F340-016D-11D2-945F-00C04FB984F9},CN=Policies,CN=System,DC=internal,DC=local;0]. The first part is a GP location, the last part seems to be a flag (2 meaning that the policy is enforced).
Read the policy object(s) and check for gPCFileSysPath attribute. This is the location where the policy settings are stored. It would be something like \\internal.local\sysvol\internal.local\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}.
Inspect the file store from point 2. and look for MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf file. It's a regular inf/ini file, investigate [Registry Values] section to find a line that reads: MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning=4,14. This 14 is a policy setting (to prompt for password change 14 days before expiry).
Now, the things get complicated to get the actual resultant set of policies. Policies get inherited from parents, meaning that in point 1. you should be checking the intended OU and all its parent OUs together with a domain node itself, evaluate all the gPLinks in appropriate order, possibly also taking into consideration their WMI filter, whether they do apply or not, in order to find out what value is in effect.
If your application happens to run on Windows that can be put under the same group policy it might be easier to just read the information from registry, as this will be already applied by the system.
In any case, I would consider to just use some default expiration warning period, given the amount of complexity to get the value from AD (provided that it is defined in group policy at all and not just defaults on computers locally).

[Twitter Streaming API]Is it possible to track keyword from the user's timeline? [duplicate]

I installed and tried out tweepy, I am using the following function right now:
from API Reference
API.public_timeline()
Returns the 20 most recent statuses from
non-protected users who have set a custom user icon. The public
timeline is cached for 60 seconds so requesting it more often than
that is a waste of resources.
However, I want to do extract all tweets that match a certain regular expression from the complete live stream. I could put public_timeline() inside a while True loop but that would probably run into problems with rate limiting. Either way, I don't really think it can cover all current tweets.
How could that be done? If not all tweets, then I want to extract as many tweets that match a certain keyword.
The streaming API is what you want. I use a library called tweetstream. Here's my basic listening function:
def retrieve_tweets(numtweets=10, *args):
"""
This function optionally takes one or more arguments as keywords to filter tweets.
It iterates through tweets from the stream that meet the given criteria and sends them
to the database population function on a per-instance basis, so as to avoid disaster
if the stream is disconnected.
Both SampleStream and FilterStream methods access Twitter's stream of status elements.
For status element documentation, (including proper arguments for tweet['arg'] as seen
below) see https://dev.twitter.com/docs/api/1/get/statuses/show/%3Aid.
"""
filters = []
for key in args:
filters.append(str(key))
if len(filters) == 0:
stream = tweetstream.SampleStream(username, password)
else:
stream = tweetstream.FilterStream(username, password, track=filters)
try:
count = 0
while count < numtweets:
for tweet in stream:
# a check is needed on text as some "tweets" are actually just API operations
# the language selection doesn't really work but it's better than nothing(?)
if tweet.get('text') and tweet['user']['lang'] == 'en':
if tweet['retweet_count'] == 0:
# bundle up the features I want and send them to the db population function
bundle = (tweet['id'], tweet['user']['screen_name'], tweet['retweet_count'], tweet['text'])
db_initpop(bundle)
break
else:
# a RT has a different structure. This bundles the original tweet. Getting the
# retweets comes later, after the stream is de-accessed.
bundle = (tweet['retweeted_status']['id'], tweet['retweeted_status']['user']['screen_name'], \
tweet['retweet_count'], tweet['retweeted_status']['text'])
db_initpop(bundle)
break
count += 1
except tweetstream.ConnectionError, e:
print 'Disconnected from Twitter at '+time.strftime("%d %b %Y %H:%M:%S", time.localtime()) \
+'. Reason: ', e.reason
I haven't looked in a while, but I'm pretty sure that this library is just accessing the sample stream (as opposed to the firehose). HTH.
Edit to add: you say you want the "complete live stream", aka the firehose. That's fiscally and technically expensive and only very large companies are allowed to have it. Look at the docs and you'll see that the sample is basically representative.
Take a look at the streaming API. You can even subscribe to a list of words that you define, and only tweets that match those words are returned.
The streaming API rate limiting works differently: you get 1 connection per IP, and a maximum number of events per second. If more events occur than that, then you only get the maximum anyways, with a notification regarding how many events you missed because of rate limiting.
My understanding is that the streaming API is most suitable for servers that will redistribute the content to your users as needed, instead of being accessed directly by your users - the standing connections are expensive and Twitter starts blacklisting IPs after too many failed connections and re-connections, and possibly your API key afterwards.

How to handle multiple video streams in Red5?

I am writing a Red5 application that provides 1-on-1 video chat to a Flash client over RTMP.
Unfortunately most tutorials I was able to find were sketchy at best and the documentation of Red5 itself tends to be vague when it comes to API concepts and intended usage.
In short, I am a bit stuck and looking for hints on Red5 ApplicationAdapter implementation. Gnarly details are as follows:
First of all, the connections come in two flavors: visitors and consultants. A visitor should be able to indicate which consultant it wishes to communicate with. A consultant simply gets connected to the requesting visitor as long as the consultant is not busy servicing another.
Obviously, every RTMP connection has two-way traffic: both sending and receiving video. From the standpoint of the server, connections bring in a bunch of video streams that get their receiving endpoints assigned by request.
Since several video conversations can be in progress simultaneously, the main task of the application is to handle the mapping of visitor streams to consultants and provide a list indicating each consultant's state (busy/available) via AMF.
So, all in all, I have a pretty good idea what I am aiming for but how to achieve it with Red5 is still a bit of a mystery.
Hopefully someone can enlighten me in any or all of the following:
What is the easiest way to establish the connection type (visitor/consultant)?
Which API classes should be used to implement a persistent, globally accessible list of active connections for reporting the state of each consultant?
How to switch receving endpoints dynamically when the goal is to connect a specific visitor to the selected consultant?
Saul ,
1.What is the easiest way to establish
the connection type
(visitor/consultant)?
assuming that both(visitor/consultant) are using flex client via which they start publishing their live video stream ,here you need to make sure that each published video stream name is unique (HOWTO is already mentioned in demo apps)
2.Which API classes should be used to
implement a persistent, globally
accessible list of active connections
for reporting the state of each
consultant?
and for providing the list of active connections you simply need to store(preferably in your db) each user's id with the stream name (which is also available as a tutorial demo app) to connect to.
I believe all the code is available for the red5 demos Do try oflaDemo , simpleSubscriber , fitcDemo demo apps.
I hope I am closer to your solution.
Since Oflademo or red5 is capable of 1v1 chats, then replicate this code to make around 50 chats. You can maintain a table with the following columns :
chat room number (1 to 50)
user1
user2
status(0 or 1 - unoccupied or occupied)
If let say a visitor V22 wants to get consulted from consultor C33, then a program can detect the first unoccupied room from 1 to 50, if the 7th room is unoccupied then, redirect V22 and C33 to room 7 and change status to 1(occupied). After the video call, the status can be reset to 0, and the table at roomno:7 , user1 of roomno:7, user2 of roomno:7, can be set to NULL. Its like maintaining tables in a restaurant in a computer.
You can basically develop multiple chatting using 1to1 using a database and php queries, no need to edit any swf code or maintain a complicated server etc.

Activation codes

I am not sure what shall i put as Title for this Question, But I am here looking for help.
I work in a company which makes desktop based application on CORE JAVA Platform.
We provide an ACTIVATION CODE to activate our software.
The concept of activation is -
User enters the Activation code --> software hits our server and download all the required files --> activation completed.
Once in a day, our software hits our server to check if the activation code has been expired.
Problem-
We have a new client which doesn't have a regular internet connection. Somehow they agreed to provide internet connection for one time-
User enters the Activation code --> software hits our server and download all the required files --> activation completed.
but after that no internet connection. I can stop the software to check with server about expiry Date of activation code.
But the problem with me is-
1) How do I check whether the Activation code has actually expired? ( Activation code is valid for 1 year only)
2) If after expiry If user enters a new Activation code, how do I check this is a valid activation code with 1 year validity?
1) you can store the registration date and compare it against the system date. of course then users can temper with the date. I used to have some software that always stored the last date it had seen, and if one moved the date to the past, it complained and insta-expired. you could do something like this but of course it's never as safe as talking to a server.
2) create a format for your activation key that contains a new key as well as the previous key. so the first key is, say, A, which is good for talking to a server and checking if A is okay. A new key might look like AB meaning "I replace A, add another year of activation, and am called B, so in a year, we'll need a key like BC". You'll have to think a bit about how to encode this securely, but I'm pretty confident it can work (for example, you can encrypt B with A, then B can only be used on a machine with activation code A).

Categories