Mobil Mewah

Salah satu sumber Inspirasi.

Mobil Sport terbaik

Anda pasti bisa memilikinya.

Bermain dengan pesawat

Salah satu ide yang gila, Balapan di udara.

Bermain di angkasa

Apakah ini salah satu Goals dalam hidup anda? anda pasti bisa mencapainya

Saturday, 29 August 2015

Django Choice form filtered base on logged username


With Django we have form which have many feature to faster development. I usually use Django Model Form, which get the meta data from a model and spit out a form ready to use and rendered to client in HTML form.

Django Select Form
Now i need to get a choice field in django , but the choice field get from a foreign key, and need to filter it base on the username logged in to system.

So the purpose is to get a list of choice which only available for the specific user, let say the user belong to VIP user group. So user only see the choice only available to VIP user group defined before by admin.


So lets get the how to do it. Here are the model code :
  class Usergroup(models.Model):
    """Models for User Group"""
    group_name = models.CharField(max_length=64, null = False, default = '')
    owner = models.CharField(max_length=64, null = False, default = ''  )
    update_by = models.CharField(max_length=250,null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
            db_table = 'Usergroup'
            ordering = ['-created_at']
            verbose_name_plural = 'usergroup'
            permissions = (
                ("view_usergroup", "Can see detail of the User Group"),
                ("list_usergroup", "Can list all the User Group"),
            )

    def __unicode__(self):
        return self.group_name

    @models.permalink
    def get_absolute_url(self):
        return ('user_group', (),{'group_name':self.group_name})




here are the form code :
   class AdminVIPUsersModelForm(forms.ModelForm):
     """For new and edit model"""
     def __init__(self, *args, **kwargs):
        super(AdminVIPUsersModelForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if field.widget.__class__ == forms.widgets.TextInput:
                if field.widget.attrs.has_key('class'):
                    field.widget.attrs['class'] += ' form-control input-medium'
                else:
                    field.widget.attrs.update({'class':'form-control input-medium'})

     class Meta:
         model = VIPuser
         fields = ('user_name','passwd','user_group','access_type','owner')
     user_name = forms.CharField(widget=forms.TextInput(attrs={ \
                    'class':'form-control input-medium'}),label='User Name' \
                    ,help_text="Used for login on Wifi")
     passwd = forms.CharField(widget=forms.PasswordInput(attrs={ \
                    'class':'form-control input-medium'}),label='Password' \
                    ,help_text="Passoword for user login from HotSpot")
     user_group = forms.ModelChoiceField(widget=forms.Select(attrs={ \
                    'class':'form-control input-medium'}),label='Group' \
                    ,help_text="Group the user belong", \
                    queryset = Groupchoices.objects.all())
     access_type = forms.CharField(widget=forms.TextInput(attrs={ \
                    'class':'form-control input-medium'}),label='Access Type' \
                    ,help_text="User access type description")
     owner = forms.CharField(widget=forms.TextInput(attrs={ \
                    'class':'form-control input-small'}),label='Owner' \
                    ,help_text="The creator of the group and will used only \
                    by the creator")

And in the views.py :
        form = AdminVIPUsersModelForm()
        form.fields["user_group"].queryset = Usergroup.objects.filter(owner=request.user.username)


This usecase will be used when there is foreign key relation on each table.

Hope this help someone as i documented for my future reference in this blog.

Tuesday, 18 August 2015

Check windows process with Nagios Monitoring

I need to check a process running on windows machine from a monitoring server. The monitoring using Nagios. I want to get alert when the process is not running on the windows machine.

This can be achieved by using Nagios NRPE client++ .

Assume NRPE client++ already installed.
To test on nagios machine do this :

./check_nt -H 10.10.10.10 -p 12489 -v PROCSTATE -d SHOWALL -l w3wp.exe

If running, it will return :

w3wp.exe: Running

if not running, it will return :

w3wp: not running

this so simple is it?


Tuesday, 11 August 2015

Monitoring DNS with a vbscript

DNS on windows usually come with Active directory service. But also can used to query external Domain name as long as the server have internet connection.


Hostname entries in DNS also rarely changed and some use local cache with TTL from server. Somehow, we need to monitor a change in DNS query result with alert when these changes happend.

Let say it is other Domain name which not in our control, we want to know immidiately when the Address changed in DNS. And also alert with email that the query result changed with the query info inside the email.

Within windows 7 as client, we can do this using a VBScript and a task scheduler, and access to SMTP mail server to sent out the alert.

Below are the script to be used. The script will query the domain to be monitor, and check if the result as expected. then it will sent email with the query result, and change subject if host name is changed for the monitored domain.

strEmailTo="anyong@superbadmin.com"
strEmailFrom="dnsmonitor@superbadmin.com"
strDomain="superdomain.com"
strDNSServer="192.168.1.111"
strSMTPServer="192.168.1.232"
iSMTPPort=25
strLogs = "c:\scripts\dnsmon\logs\"
Const ForAppending = 8 'for loggin
Dim strLogFile, objFSO, strDate, objLogFile

arrRecords = Array( _
 "Name:    " & strDomain ,_
 "Address:  " &  "172.10.120.121" _
)

Set objShell = CreateObject("WScript.Shell")
'Set objNSLookup = objShell.Exec("nslookup -q=MX " & strDomain & " " & strDNSServer)
Set objNSLookup = objShell.Exec("nslookup " & strDomain & " " & strDNSServer)
Set objStdOut = objNSLookup.StdOut
strOutput = objStdOut.ReadAll

strMsg = "NSLookup Output: " & VbCrLf & VbCrLf & strOutput & VbCrLf & "Test Results:" & vbCrLf

bChanged = False
For Each strRecord In arrRecords
 bRecordChanged = False
 If InStr(strOutput, strRecord) = 0 Then
  bRecordChanged = True
  bChanged = True
 End If
 strMsg = strMsg & VbCrLf & "Changed: " & bRecordChanged & " - " & strRecord
Next

strMsg = strMsg & VbCrLf & VbCrLf & "Overall result of change: " & bChanged & VbCrLf & "############################"

'Logging Part
strLogFile = strLogs & "superdomain.com-check-logs-" & Year(strDate) & "-" & Month(strDate) & "-" & Day(strDate) & ".log" 'for log file
set objFSO = CreateObject("Scripting.FileSystemObject")
set objLogFile = objFSO.OpenTextFile(strLogFile, ForAppending, True)
objLogfile.WriteLine Now & " ## " &strMsg 
objLogFile.Close
set objLogFile = Nothing
set objFSO = Nothing
'//////////
'end logging

'WScript.Echo strMsg

'Context.LogMessage strMsg
'bChanged = True
'If bChanged = True then
If True then
 Set objEmail = CreateObject("CDO.Message")
 objEmail.From = strEmailFrom
 objEmail.To = strEmailTo
 if bChanged = True then
  objEmail.Subject = "[Mon] superweb.com DNS Changed"
 else
  objEmail.Subject = "[Mon] superweb.com DNS Change"
 End If
 objEmail.Textbody = "Checked : " & Now & VbCrLf & strOutput
 objEmail.Configuration.Fields.Item _
     ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
 objEmail.Configuration.Fields.Item _
     ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPServer
 objEmail.Configuration.Fields.Item _
     ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = iSMTPPort
 objEmail.Configuration.Fields.Update
 objEmail.Send
 'Context.SetResult = 1
Else
 'Context.SetResult = 0
End If

This simple vbscript can be executed on windows and need have access to smtp server to sent out emails.


Twitter Delicious Facebook Digg Stumbleupon Favorites More