How to check connection between windows and anywhere usb with nagios

The easiest way to monitor the connection between your Digi Anywhere USB device and a server is to monitor the USB device connected it. I use Nagios to monitor several indicators in each server, and the following script can be used to monitor if USB devices are connected:

strComputer = "."
 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colDevices = objWMIService.ExecQuery ("Select * From Win32_USBControllerDevice")
 
For Each objDevice in colDevices
    strDeviceName = objDevice.Dependent
    strQuotes = Chr(34)
    strDeviceName = Replace(strDeviceName, strQuotes, "")
    arrDeviceNames = Split(strDeviceName, "=")
    strDeviceName = arrDeviceNames(1)
    Set colUSBDevices = objWMIService.ExecQuery ("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
    For Each objUSBDevice in colUSBDevices
        'Wscript.Echo objUSBDevice.Description
        If objUSBDevice.Description="SCR3311 USB Smart Card Reader" Then
           WScript.Echo "OK - Card reader detected"
           WScript.Quit 0
        End If
    Next
Next
 
WScript.Echo "WARNING - No card reader detected"
WScript.Quit 1

In my case, I monitor a card reader that identifies as "SCR3311 USB Smart Card Reader". You should type the exact name of the device you're monitoring at that spot. If you don't know the exact name of the device, uncomment the line
'Wscript.Echo objUSBDevice.Description
and then execute
cscript //nologo //t:10 "check_cardreader.vbs"

Put above file in c:\program files (x86)\nrpe\check_cardreader.vbs and update nrpe.cfg to contain:
command[check_cardreader]=cscript //nologo //t:10 "c:\program files (x86)\nrpe\check_cardreader.vbs"

After restarting the NRPE service, you're ready to monitor the USB device.

© GeekLabInfo How to check connection between windows and anywhere usb with nagios is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

iptables and dynamic DNS – part 3

This is an updated post for this updated article.

I just found back an old note about using iptables in combination with dyndns to open up access from a remote location. For instance, if you have a laptop that you take everywhere and you want to connect to your home or office. The script the other site suggested was broken, so let's write a new one.

Step 1: Create a new chain in the firewall

Create a new chain in the firewall where we can plug in the dynamic rules. On my Fedora machine, the firewall is located in /etc/sysconfig/iptables. I added the bold lines to this example.


*nat
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
<b>:DYNAMICPARENT - [0:0]
-A INPUT -j DYNAMICPARENT</b>
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

Step 2: Write a script

#!/bin/bash
 
HOSTNAME=myname.dyndns.org
CHECK_INTERVAL=60 #once a minute
 
IP="" #initialize $IP
while [ true ]; do
        OIP=$IP
        IP=$(dig +short $HOSTNAME | grep -iE "^[0-9]+.[0-9]+.[0-9]+.[0-9]+$"|head -n 1)
        if [ "$OIP" != "$IP" -a "$IP" != "" ]; then
                echo "Changing ip to $IP"
                /sbin/iptables -N DYNAMICNEW                    # create new rule
                /sbin/iptables -I DYNAMICNEW -s $IP -j ACCEPT   # allow new ip
                /sbin/iptables -I DYNAMICPARENT -j DYNAMICNEW   # attach new rule to its parent
 
                while [ true ]; do  # unlink old rule - if multiple exist, remove all
                        /sbin/iptables -D DYNAMICPARENT -j DYNAMICCHILD 2>/dev/null || break
                done
                /sbin/iptables -F DYNAMICCHILD #flush all old rules
                /sbin/iptables -X DYNAMICCHILD #flush all old rules
 
                /sbin/iptables -E DYNAMICNEW DYNAMICCHILD #rename new to "current"
        fi
        sleep $CHECK_INTERVAL
done

In this case, the firewall accepts all traffic from $IP, but of course you could restrict it to 1 port. Also, I focussed on IPv4, but you could easily rewrite this script to IPv6 using ip6tables. I saved the file to /usr/local/bin/dynfirewall.sh

Step 3: Run the script

I'd prefer running the script from inittab, but since Fedora doesn't work like this anymore, I put the following line in /etc/rc.d/rc.local:

/usr/local/bin/dynfirewall.sh >>/var/log/dynfirewall 2>>/var/log/dynfirewall &

Please don't forget the ampersand at the end to fork the script!!

Why is this script better than previous version?

- This script can handle cnames
- The old script used to delete old rules, before creating new ones. This one does not. Therefore, it will never leave a second where you cannot connect.

© GeekLabInfo iptables and dynamic DNS - part 3 is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading...Loading...

iptables and dynamic DNS – part 2

In 2011, I wrote this post on Dynamic DNS: http://www.geeklab.info/2011/02/iptables-and-dynamic-dns. While this is still useful, I found a newer, cooler way to do Dynamic DNS in combination with iptables. It's called libnetfilter_queue.

iptables is used to change the inner netfilter tables of the kernel. And because the kernel has no internal resolver, it is impossible for the kernel to do on-the-fly dns lookups. But by offloading this decision to userspace, it is possible. The libnetfilter_queue lib offers that functionality.

libnetfilter_queue is a userspace library providing an API to packets that have been queued by the kernel packet filter. It has bindings for Python and several other languages.

Requirements for my setup

python-NetfilterQueue - https://github.com/kti/python-netfilterqueue

libnfnetlink

libnetfilter_queue

libmnl

You may need to build the first dependency yourself. The other 3 are available in Fedora 20 by default. If you're running RHEL/CentOS, the Fedora packages can be recompiled for your setup.

iptables rule

First, you need to get iptables to enqueue specific packets to your queue.

iptables -I INPUT -p tcp --dport 631 -m state --state NEW -j NFQUEUE --queue-num 6789 -m comment --comment "Remote CUPS printer"

Queue handler

Then we write a script that handles the queue. A quick-and-dirty implementation:

#!/usr/bin/python
 
import socket
from netfilterqueue import NetfilterQueue
 
def getIP(d):
    """
    This method returns the first IP address string
    that responds as the given domain name
    """
    try:
        data = socket.gethostbyname(d)
        #ip = repr(data)
        return data
    except Exception:
        # fail gracefully!
        return False
 
def dnsfilter(pkt):
        if pkt.get_payload_len() < 0x10:
                "Don't know how to handle this too small packet"
                pkt.drop()
                return False
 
        payload=pkt.get_payload()
        srcip=".".join("{:d}".format(ord(c)) for c in payload[0x0c:0x10])
        allowedip=getIP('localhost')
        print "Debug: SRC="+srcip+" ALLOWED="+allowedip+" RESULT=",
        if srcip==allowedip:
                print "Accept"
                pkt.accept()
        else:
                print "Drop"
                pkt.drop()
 
nfqueue = NetfilterQueue()
nfqueue.bind(6789, dnsfilter)
try:
        nfqueue.run()
except KeyboardInterrupt:
        print

This is a quick-and-dirty implementation that misses basic features such as caching the result of gethostbyname. This may introduce terrible delays if used wrong.

Ubuntu/Debian

I'm running RedHat-based software on all of my machines. Above information may be useful for Ubuntu/Debian users, but it's not tested and I'm not supporting it.

Servers: RedHat Enterprise Linux/CentOS is more suitable for servers, as there's a lot of professional level support available. I think that's important, because if I say, get a car accident, I want the servers to be managable by another professional.

Desktops/Laptops: RPM packages are pretty exchangable between RedHat-based platforms. That's a good reason to run Fedora on the desktop.
© GeekLabInfo iptables and dynamic DNS - part 2 is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

How to monitor a Konica-Minolta printer’s settings using Nagios

For some reason, some users seem not to be able to keep their hands off the settings of my KonicaMinolta Bizhub 283. They keep changing the paper format for tray 2 to PlainPaper, causing all kinds of problems. Since there is no way to lock the settings, I started to monitor them and report them.

This is my Nagios script:

#!/usr/bin/python
 
import os
import pycurl
import cStringIO
import re
import random
import time
import tempfile
import sys
 
from lxml import etree
 
newcookiefile = tempfile.NamedTemporaryFile()
 
if len(sys.argv)!=2:
        print "Usage: "+sys.argv[0]+" [printer ip or hostname]"
        sys.exit(1)
 
buf = cStringIO.StringIO()
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://"+sys.argv[1]+"/wcd/index.html")
c.setopt(pycurl.COOKIEFILE, newcookiefile.name)
c.setopt(pycurl.COOKIEJAR, newcookiefile.name)
c.setopt(pycurl.WRITEFUNCTION, buf.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.ENCODING, "")
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
c.setopt(pycurl.USERAGENT, "Something")
c.perform()
curlData = buf.getvalue()
buf.close()
 
buf = cStringIO.StringIO()
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://"+sys.argv[1]+"/wcd/system.xml")
c.setopt(pycurl.COOKIEFILE, newcookiefile.name)
c.setopt(pycurl.COOKIEJAR, newcookiefile.name)
c.setopt(pycurl.WRITEFUNCTION, buf.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.ENCODING, "")
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
c.setopt(pycurl.USERAGENT, "Something")
c.perform()
curlData = buf.getvalue()
buf.close()
 
#print curlData
 
tree = etree.fromstring(curlData)
root = etree.Element("root")
paperformat=tree.xpath('/MFP/DeviceInfo/Input/TrayList/Tray/TrayID[text()="Tray2"]/../CurrentPaper/MediaType')[0].text
 
if "PlainPaper" == paperformat:
        print "Someone touched the settings - again!"
        sys.exit(2)
 
print "OK"
sys.exit(0)
© GeekLabInfo How to monitor a Konica-Minolta printer's settings using Nagios is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

How to monitor your Dymo printserver

About twice a week, I get a call that a Dymo LabelWriter 450 no longer works. In most cases, the reason was that the user pulled the USB cable.

My Dymo LabelWriters are connected to a Dymo printserver. While the printservers can be monitored using ping, this does not allow you to see if the printer it still connected to the printserver. Luckily the Dymo printserver has SNMP support with the option to see what device is connected.

I did a SNMPWalk against the printserver, first with the LabelWriter connected, then disconnected. Aside from some counters, three values were different:

Connected Disconnected
HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: DYMO LabelWriter 400 HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: [nothing here]
HOST-RESOURCES-MIB::hrDeviceStatus.2 = INTEGER: running(2) HOST-RESOURCES-MIB::hrDeviceStatus.2 = INTEGER: unknown(1)
HOST-RESOURCES-MIB::hrPrinterStatus.1 = INTEGER: idle(3) HOST-RESOURCES-MIB::hrPrinterStatus.1 = INTEGER: unknown(2)

I also found that HOST-RESOURCES-MIB::hrDeviceDescr.2 sometimes shows the correct printer string one time, but doesn't show it the second time:

$ snmpget -v 1 -c public dymo2  HOST-RESOURCES-MIB::hrDeviceDescr.2
HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: DYMO LabelWriter 450
$ snmpget -v 1 -c public dymo2  HOST-RESOURCES-MIB::hrDeviceDescr.2
HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: 
$ snmpget -v 1 -c public dymo2  HOST-RESOURCES-MIB::hrDeviceDescr.2
HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: DYMO LabelWriter 450
$ snmpget -v 1 -c public dymo2  HOST-RESOURCES-MIB::hrDeviceDescr.2
HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: 
$ snmpget -v 1 -c public dymo2  HOST-RESOURCES-MIB::hrDeviceDescr.2
HOST-RESOURCES-MIB::hrDeviceDescr.2 = STRING: DYMO LabelWriter 450

Therefore, I use a script that tries 10 times in a row. If it finds a valid string at least once, that's good enough:

#!/bin/bash
 
[ "$1" == "" ] && { echo "Syntax: $0 [hostname]" ; exit 1; }
 
i=0
while [ $i -lt 10 ]; do
        response=$(/usr/lib64/nagios/plugins/check_snmp -H $1 -o HOST-RESOURCES-MIB::hrDeviceDescr.2 -R dymo)
        retval=$?
        if [ $retval -eq 0 ]; then
                echo $response
                exit $retval
        fi
        i=$((i+1))
done
 
echo "Printer disconnected from printserver"
exit 2

This script can be used with Nagios to monitor the LabelWriter.

© GeekLabInfo How to monitor your Dymo printserver is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Several ways to mount a harddisk/usb disk image

I've got an image of a USB disk that was created with the command dd. How can we mount it and access files? The file is named smosimg

Method 1: fdisk and bash

# fdisk -l smosimg
 
Disk smosimg: 1993 MB, 1993342976 bytes, 3893248 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000336e0
 
  Device Boot      Start         End      Blocks   Id  System
smosimg1   *        2048     1230847      614400   83  Linux
smosimg2         1230848     3893247     1331200   83  Linux

I want to mount the second partition that starts at block 1230848. The block size is 512 bytes, so we multiply 1230848 by 512:

mkdir target
mount -o loop,offset=$((1230848*512)) smosimg target

Method 2: kpartx

mkdir target
kpartx -a smosimg
mount /dev/mapper/loop0p2 target -o loop
kpartx -d smosimg

Method 3: losetup

mkdir target
losetup --partscan --find --show disk.img
mount /dev/loop0p2 target
losetup -d /dev/loop0

I've personally tested all three methods, and on my Fedora 18 machine, they all work.

© GeekLabInfo Several ways to mount a harddisk/usb disk image is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Windows Photo Viewer terminating with “COM Surrogate” error

One of the computers I manage had a problemen with Windows Photo Viewer, which crashed with the message "COM Surrogate has stopped working".

Especially when clicking "Next" in the viewer, the application crashed.

It's a 64 bit Dell computer running Windows 7 with all updates applied. It has a Trend Micro virusscanner and a TightVNC 2.x server for remote management.

What is COM Surrogate?

Often, COM objects are defined in DLLSs, a piece of code that is executable, but just not by itself. It is started by another program when needed. But sometimes, you just want to run code from a DLL without writing a complete wrapper program around it. That's where Microsoft has provided a program that can execute parts of a COM DLL without developing a complete program to load the DLL.

This program is called dllhost.exe and has user friendly name "COM Surrogate

What can I do against a crashing COM Surrogate?

I read several solutions, most of which were useless to me, but they may help you.

Replace video card

In my case, the issue was that the drivers of the onboard video card crashed. The computer is an Optiplex 9010 with an Intel® Q77 Express Chipset (Intel® BD82Q77 PCH) chipset that has Integrated Graphics.

I inserted an ATI Radio HD34xx card, which was automatically installed by Windows 7. After a reboot, the problem seems to be completely gone.

Commands

There are a few dlls that can be "re-registered" with Windows. Click on start, type cmd and right-click to choose "Run as Administrator". On the command line, type:

regsvr32 vbscript.dll
regsvr32 jscript.dll

Check Disk for Errors

Bad sectors on the hard drive could be the cause of COM Surrogate crashing. You can check your disk with the chkdsk command.

Disable DEP for dllhost.exe

Another fix that is suggested by numerous websites, is adding dllhost.exe to the exception list of DEP (Data Execution Prevention).

On 32-bit systems, you could whitelist:

C:\Windows\System32\dllhost.exe

And on 64-bit systems, that would be:
C:\Windows\SysWOW64\dllhost.exe

Although this MAY be a fix, I really suggest you don't use this method. The dllhost.exe is an executable that runs a crapload of DLLs, both Microsoft-DLLs and Third-party DLLs. It's like telling your virusscanner to exclude *.exe from scanning.

If it were your financial software, I would not advice against it, but dllhost.exe is used by so many programs, that I don't consider it safe to exclude.

© GeekLabInfo Windows Photo Viewer terminating with "COM Surrogate" error is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

How to prevent https://r.twimg.com/jot from opening

Recently, I noticed that I had a tab opening in Firefox with the URL https://r.twimg.com/jot in a new tab. Apparently, when visiting RSS feeds in Thunderbird, this tracker is opened in another tab, which is quite annoying.

I've read a lot of solutions to this issue, most of them being changes in the settings of either Thunderbird or Firefox. Probably the best solution was to deny ||r.twimg.com/jot through ad block plus.

My solution was a quick hack: I fixed it by adding a patch to /usr/bin/firefox
if [ "`echo $@|grep r.twimg.com/jot`" != "" ]; then
echo jot stopped | logger
exit 0
fi
if [ "`echo $@|grep twitter.com/i/jot`" != "" ]; then
echo jot stopped | logger
exit 0
fi

© GeekLabInfo How to prevent https://r.twimg.com/jot from opening is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

IPv6 neighbour proxy

When experimenting with IPv6 this weekend, I thought it would be cool to give my IPv4-only devices such as my webcam an IPv6 address.

Using Tayga to do NAT64, I could route an IPv6 range to a virtual network interface where Tayga translates incoming packets to IPv4. As Tayga's documentation states: "You will need to select an unused /96 from your site's IPv6 address range which will be used as the NAT64 prefix." Unfortunately, I  only have one single /64 available, a range that should not be split.

What I did, was the following:

Diagram1

This is not really best practice, as hosts in the range 2001:400:1234:567:ffff:0:0:0 - 2001:400:1234:567:ffff:ffff:ffff:ffff  could be located on both the LAN and the Tayga virtual router, it's the only working method for the time being.

The Linux router sends packets for 2001:400:1234:567:ffff::/96 to Tayga instead of direcly to the lan. This works for outside hosts, but hosts on the LAN don't know that packets for this range should be sent to the Linux router.  They try to find my webcam on the LAN, but obviously can't find it.

Neighbour discovery

This looking for the webcam on the LAN is called neighbour discovery. The Neighbour Discovery Protocol performs functions similar to IPv4 ARP for finding other nodes on the same LAN. With above setup, the host at 2001:400:1234:567:ffff::1 is actually off the LAN. The Linux router must tell my laptop to send packets for this IP to the router.

proxy_ndp

You can do this using proxy_ndp, the IPv6 variant of proxy_arp. First enable proxy_ndp by running:

sysctl -w net.ipv6.conf.all.proxy_ndp=1

You can enable this permanently by adding the following line to /etc/sysctl.conf:

net.ipv6.conf.all.proxy_ndp = 1

Then run:

ip -6 neigh add proxy 2001:400:1234:567:ffff::1 dev eth0

This means for the Linux router to generate Neighbour Advertisement messages in response to Neighbour Sollicitation messages for 2001:400:1234:567:ffff::1 that enter through eth0. Note that 2001:400:1234:567:ffff::1 itself is not found on eth0, but on another virtual interface.

ndppd - NDP Proxy Daemon

While proxy_arp could be used to proxy a whole subnet, this appears not to be the case with proxy_ndp. To protect the memory of upstream routers, you can only proxy defined addresses. There is a daemon that can proxy a whole subnet, ndppd. It's available at
http://priv.nu/projects/ndppd/.

Links

Another interesting page on this subject is found at:
http://linux-attitude.fr/post/proxy-ndp-ipv6
(French, use google translate) - multiple /64's in a /56

http://wiki.stocksy.co.uk/wiki/IPv6%2BXen_on_a_Hetzner_server_with_routing_to_dummy0_and_proxy_ndp - exactly what I'm doing, but for other purposes. Just found this page after typing my own.

© GeekLabInfo IPv6 neighbour proxy is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Bash: download and execute shell scripts

Sometimes, when running 1 bash script repeatedly on several different machines, I found that being able to download and immediately execute a script is very handy.

The following command will download a script and immediately execute it:

bash <(curl -s http://geeklab.info/my-script.sh)

This command uses Bash's Process Substitution to do it's job. command2 <(command) means for bash to put the output of command in a pipe and then run command2 [tempfile]. So above statement does the same as:

TMPFILE=$(mktemp /tmp/my.XXXXX)
curl -s http://geeklab.info/my-script.sh > $TMPFILE
bash $TMPFILE
rm $TMPFILE

Process substitution is also very useful when you want to know the difference between the output of two commands:

diff <( command1 ) <( command2 )

Furthermore, it's possible to pipe the contents of the temporary file into command2. For instance:
bash < <(curl http://geeklab.info/my-script.sh) would do the same as:

TMPFILE=$(mktemp /tmp/my.XXXXX)
curl -s http://geeklab.info/my-script.sh > $TMPFILE
bash < $TMPFILE
rm $TMPFILE

With bash, this difference is small, but with other commands, it may not be.

© GeekLabInfo Bash: download and execute shell scripts is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...