Friday, 19 February 2021

DYMO Label Framework JavaScript Library Async Example: Print a label

 Recently did some work to add label printing to an app I have written for Canoe Slalom.

I found it hard to find any examples, particularly async examples.

So here is my code for you to use/abuse as you wish.

My code displays a spinner at the start, which is removed when the label has finished printing. it also enables a submit button. 

My label description is in a hidden form field called label and the address to print is in a field called address.

 <script src="http://labelwriter.com/software/dls/sdk/js/DYMO.Label.Framework.latest.js" type="text/javascript" charset="UTF-8">  

<script type="text/javascript" charset="UTF-8">

function loader() {

// dymo.label.framework.trace = 1; 

dymo.label.framework.init();

}

function printLabel() {

    $('#spinner').show();

var address = document.getElementById('address').value;

  var textArea = document.createElement('textarea');

  textArea.innerHTML = document.getElementById('label').innerHTML;

  var labelXml = textArea.value;


var label = dymo.label.framework.openLabelXml(labelXml);

label.setObjectText("Text", address);

dymo.label.framework.getPrintersAsync().then(function(printers) {

var printerName = '';

if (printers.length > 0) {

for (var i = 0; i < printers.length; ++i)

{

    var printer = printers[i];

    if (printer.printerType == "LabelWriterPrinter" && printer.isConnected == true)

    {

        printerName = printer.name;

        break;

    }

}

}

if (printerName!='') {

label.printAsync(printerName).then(function() {

  $('#spinner').hide();

    enableButton('submit');

});

}

else {

  $('#spinner').hide();

    alert("Could not find Label Writer printer");

    enableButton('submit');

}

});

}

</script>

Label contains the following


<?xml version="1.0" encoding="utf-8"?><DieCutLabel Version="8.0" Units="twips"><PaperOrientation>Landscape</PaperOrientation><Id>LargeAddress</Id><IsOutlined>false</IsOutlined><PaperName>30321 Large Address</PaperName><DrawCommands><RoundRectangle X="0" Y="0" Width="2025" Height="5020" Rx="270" Ry="270" /></DrawCommands><ObjectInfo><AddressObject><Name>Text</Name><ForeColor Alpha="255" Red="0" Green="0" Blue="0" /><BackColor Alpha="0" Red="255" Green="255" Blue="255" /><LinkedObjectName /><Rotation>Rotation0</Rotation><IsMirrored>False</IsMirrored><IsVariable>True</IsVariable><GroupID>-1</GroupID><IsOutlined>False</IsOutlined><HorizontalAlignment>Left</HorizontalAlignment><VerticalAlignment>Middle</VerticalAlignment><TextFitMode>ShrinkToFit</TextFitMode><UseFullFontHeight>True</UseFullFontHeight><Verticalized>False</Verticalized><StyledText><Element><String xml:space="preserve"></String><Attributes><Font Family="Arial" Size="12" Bold="False" Italic="False" Underline="False" Strikeout="False" /><ForeColor Alpha="255" Red="0" Green="0" Blue="0" HueScale="100" /></Attributes></Element></StyledText><ShowBarcodeFor9DigitZipOnly>True</ShowBarcodeFor9DigitZipOnly><BarcodePosition>Suppress</BarcodePosition><LineFonts><Font Family="Arial" Size="12" Bold="False" Italic="False" Underline="False" Strikeout="False" /></LineFonts></AddressObject><Bounds X="322" Y="57.9999999999999" Width="4613" Height="1882" /></ObjectInfo></DieCutLabel> 

Saturday, 29 August 2020

No network access after windows 10 upgrade

 Recently windows 10 upgraded itself, after the numerous reboots when it was finally finished I was left with no network access.

My broadcom giganet ethernet card refused to work and no amount of dagnostics (which helpfully declare you need internet access) was going to fix it.

As a number of articles suggested I tried 'Netsh network reset catalog' and 'Netsh int ip reset' without any luck.

Disabling windows firewall didn't have any effect. I should have noticed at this point that AVG had vanished.

A ipconfig/renew resulted in the following message.

An error occurred while renewing interface internet

An attempt was made to access a socket in a way forbidden by its access permissions

I eventually noticed in my notifications that the windows upgrade had removed AVG as it was out of date.

If however I went into the firewall there was still an option to enable AVG firewall.

It now became clear that windows had ripped AVG out rather than correctly deinstalling it. You'd wonder why windows update could not simply inform you to update or remove AVG. I guess its part of Microsoft's upgrade at any cost strategy.

I downloaded avgclear from their site using another pc and then ran it to fully remove all traces of AVG.

A quick reboot later and my network card is functioning again.


Friday, 25 May 2018

Invalid certificate being returned for most sites in chrome and edge

As of this morning I could not access most secure web sites using Google Chrome or Microsoft Edge. Every site came up with a secure certificate warning. Chrome kept telling me my connection wasn't private and there was no way to continue.

A wasted morning removing windows updates and some software I'd just installed didn't resolve the issue.

Only by change I noticed AVG listed as the first in the chain when I inspected the certificate in the browser bar.

I then disabled AVG online shield and everything started working again.

As always although AVG was 'up to date' it wasn't. I was running V16 rather than V18. AVG never warns you when a new major version is available.

I duly updated to V18 and everything continues to work.

Monday, 12 February 2018

HP ilo 2 java issues - Solved

Recently tried to connect to one of my HP Servers as I have in the past and I could net get ilo to work even though I tried Edge, IE, Chrome, Opera and Firefox (which used to work) on Windows 10 and Linux Mint. It seems they have all dropped support for Java which means console access is no longer possible.

Fortunately I have as a worst case backup for such situations still have a Vmware VM running XP which I fired up and it worked flawlessly.

However this situation is less than ideal as I'd like to be able to access consoles from my standard desktop or even my laptop.

After many hours of searching and trying things I finally have a solution which works with ilo2 (versions 2.05 thru 2.30)

You need to install Firefox ESR which is the last version of firefox before java support was dropped. The extended support release is designed for administrators like you and me for this very purpose. Better news still is it can be installed alongside your existing firefox so you need only fire it up when needed. It is also available on all platforms.

Please ensure you only install the 32 bit version as the 64 bit version does not include Java support. I suggest you install it in a custom directory.

On Windows 10 you should find it then works fine although you need to remember to put the ip of the secure console in your Java trusted sites using the Java config manager.

You may get Java errors the first time you try and fire up the console window. If you do close the window and fire it up again.

You may also see a grey screen or diagonal grey stripes, if you do scroll to the middle of the console window and click on activate plugin or enable Java. Don't forget to scroll back to the top left of your window to see the console.

Finally you will get untold security messages but just ok them and pass on Java upgrades.

If the console doesn't connect, then again close and reopen and it normally connects the second time.

Successfully working on 32 bit and 64 bit versions of Windows 10 with Java 8 151 and 161 installed.

Firefox ESR also works on Linux Mint with IcedTea (Java equivalent) installed.

Footnote: You need Firefox ESR V52, later versions which it will auto update to will not work. I've also had recent issues with ilo2 2.05 not working so upgrade to ilo2 2.30 if you can.

Wednesday, 10 January 2018

IBM Softlayer cloud console access using Windows 10

Having struggled for hours trying to get vpn access working with softlayer and then even longer to get Softlayer's java console software to work I finally managed to get console access working with some help from support.

So firstly, ignore anything on their control panel, pptp does not work with windows 10 nor does their java console which requires IE (not edge) or firefox (but not the current version).

Save yourself a huge amount of pain and download Motion Pro client for Windows
https://speedtest.dal05.softlayer.com/array/MotionProSetup_win32.zip
https://speedtest.dal05.softlayer.com/array/MotionProSetup_win64.zip
Having installed that configure all the vpn connections you will need, the vpn servers can be found on this list.
https://www.softlayer.com/VPN-Access
Copy the link for the server you want and then edit it like so:-
https://vpn.mil01.softlayer.com/prx/000/http/localhost/login
becomes
vpn.mil01.softlayer.com
Use the profile add option in motion pro to create a vpn connection, set the host name to vpn.xxxx.softlayer.com, specify your vpn username and password. You should then be able to connect.
If you don't know your vpn username and password, go to https://control.softlayer.com/account/users/vpn in the control panel, your username should be displayed (if not add one), enable automatic SSL access and set a strong password.
Once you have a vpn connection you need to fire up a VNC viewer such as tight vnc.
You will need to find the VNC connection details, to do this go to your virtual server in the control panel, drill down to the device details by clicking on it and then use the action option on the right and select console access. 
Capture the connection and login details from the pop up window that appears and then close it.
Server Name: myserver.mydomain.com
Address: 10.X.XX.XX Port: YYYY
Username: root Password: 12345678
Now start your vnc viewer and enter the remote host and port as 10.X.XX.XX::YYYY, click on connect, when prompted for the password enter it and the console should appear (no need to enter a username).
You can save the details somewhere secure for each server so all you have to do next time is connect up the saved vpn connection, fire up your vnc viewer, select the correct connection and enter the associated password.

Wednesday, 18 October 2017

windows 10 chrome - The application has failed to start because its side-by-site configuration is incorrect.

So this is perhaps the most unusual error and indeed the most meaningless one I've come across for a while when trying to start chrome this morning.

"The application has failed to start because its side-by-site configuration is incorrect."

Rebooting made no difference

Windows update did install 2017-10 Cumulative update and chrome started logging errors at 3am. From event log I can see the following.

Activation context generation failed for "C:\Program Files\Google\Chrome\Application\chrome.exe". Dependent Assembly 61.0.3163.100,language="*",type="win32",version="61.0.3163.100" could not be found. Please use sxstrace.exe for detailed diagnosis.

Can not remove chrome as even its setup can't be found by windows and when run manually does nothing.

It appears its a visual c++ issue.

The simple solution in the end was to go to https://www.google.com/chrome/, click on download chrome and let it install.

Monday, 25 September 2017

If you want your own cloud storage/backup lima is not the answer

I purchased a lima (advertised as a personal cloud) when they first came out. Ever since then I have been cursing the decision. I should have known, it was advertised on facebook and on visiting the site you are greeted with the news that the 'waiting list' for the product is at 97% and almost full. I see many months on this is still the case, despite this your product will ship just as if it was in stock.

Your receive a little plastic block (blue and white) which has 3 connectors, usb, network and power.

So to the first issue one connector is on one end (USB) and the other 2 on the other (Network and Power) so it doesn't make for a tidy install when you set it up. You'll note the website never shows it plugged in. The power connector can easily fall out or be knocked out so make sure you route the cable carefully.

Secondly it only supports USB 2 drives/USB 2 mode so its not particularly fast.

There is not even an led to indicate it is powered up, connected to the network, logged on to your account, working, syncing or for that matter anything else. Normally I curse everything having an led but in this case it would have been useful.

When you need support you will find you need to see if its 'warm or cold' to determine whether it is powered up, you'll have to check your router to see whether it has an ip address and manually test whether it might be able to access the outside world.

First of all, check that your Ethernet and power cables are correctly plugged in.
Then, could you please answer the following questions?
1. Is the Lima device cold or warm?2. Does the wall socket work fine if you plug another equipment?3. Does your hard drive's led light up when hooking it up to the Lima device? Does it spin?4. Does your router's Ethernet port led light up when you plug the Lima device in? If No: Could you please try to plug your Lima to another router port? Could you also plug Lima with another ethernet cable?
From the router settings:
1. Does the Lima [MAC address](https://en.wikipedia.org/wiki/MAC_address) appear?2. Does the Lima get an IP address?3. Is there a firewall (on your computer and/or on your router)? Does it allow Lima and the Lima app?4. Test the following URLs on a computer connected to the same network as Lima: http://portquiz.net:25211 and http://test-connectivity.meetlima.com/
Please send me a screenshot of the results.

All of this could have been done with an LED which indicated its status and/or the issue. LED off, no power, all fine, on, various number of flashes - various error states.

Support is an laboriously slow process where you have to answer to scripted questions, many of which you may have already covered, be prepared to be patient, repeat yourself and to reboot your router. Once you've done that the information gets passed on to Technical Support who will take some time to answer. Bear in mind you've lost access to all your data whilst this happens.

Thank you for your message. We’re really sorry for the inconvenience. I forwarded your case to our Technical Support Team which will investigate further. I will get back to you as soon as I get an update from them. Their reply time could take some time, so we thank you in advance for your patience. In the meantime, let me know if I can be of any assistance.
In this case it tool a week for Technical support to respond and tell me my lima needed replacing for the second time.


Let me first apologize for getting back to you only now. We received hundreds of questions, and we take the time to answer them one by one. We try to answer personally every single question, so it takes a bit of time. Thank you for your patience. After investigation, your Lima seems to be damaged. We can then offer a full replacement of your Lima package. Before doing so, you will need to follow a few steps listed below. We strongly recommend you to backup any data you could have transferred to your Lima drive. Otherwise, they won’t be accessible anymore. See how to retrieve files from Lima's drive to your computer. The account you created when receiving your first Lima won’t be accessible anymore. Your previous account will be erased so that you can create a new one as a new Lima user. To be able to use the same email address, please contact us when receiving your new device. Have you changed your shipping address since you placed your order? please keep us informed so we will know where to ship your replacement (shipping address + phone number). You don't have to send us back the damaged device, so you can keep it. If you've received a gift with your Lima (earphones), you can keep it as well, as we won't be able to replace it. Your new device will be shipped very soon, you will be recontacted when it leaves our warehouse. Please expect some shipping delays though.

You'll find there is no way of identifying your Lima, no serial number or mac address is printed on it, so if you have 2 like me which are both called 'Blue Lima' by the software you will have to put a label on each one with its serial number/mac address and ip address.

You may find your lima works fine BUT when it does fail you are in for a shock, it has to be sent back and they send you a new one, now you'd think they'd just update your account with the new Lima's mac address, you'd plug it in and continue as before but you'd be wrong.

Bear in mind this is sold as a non techie home cloud. Here are the instructions to replace your failed Lima.

Since it is damaged and returned back, it is not possible to unpair it anymore. The only workaround would be resetting your account so that you can have a Lima and its backup only that are paired to your account.
Here are the preliminary steps:
First, please, eject your Lima Drive from Lima Menu > Preferences > Status as described [here](https://support.meetlima.com/en/articles/203938719-How-should-I-power-off-my-Lima-device). When the hard drive is confirmed as ejected, you will see a confirmation message. This may take a minute.Do not forget to [backup all the necessary data](https://support.meetlima.com/articles/207426143-How-to-retrieve-files-from-Limas-drive-to-my-computer) you copied in your Lima space before you uninstall.
1. Uninstall your Lima apps from all your devices. Need help to uninstall the apps? Check [this article](https://support.meetlima.com/hc/en-us/articles/204931205-How-to-uninstall-Lima-) in our Knowledge Base.2. Unplug the ethernet wire and wait for a minute.3. Unplug your HDD.4. Unplug the power supply.5. Replug the ethernet wire.6. Replug the power supply.7. Plug your HDD into your computer and format it (to NTFS for Windows or HFS+ for Mac). Keep it unplugged for the time being.
Please get back to me when all these steps have been performed so that I can delete your Lima account.

So to replace a faulty Lima you have to copy all the files off it, format the drive, they have to delete your account, then set up a new one, configure the limas and finally copy all the data back.

You will have also lost any files which were in the process of being loaded to the lima when it failed and are presumably in the cache on your computer, well at least they were until you remove the app as instructed above and deleted your account.

Suddenly you wonder wonder what happens if Lima Technolody Inc goes bust, your lima won't work without your account details stored on their server (so much for your own cloud) and all the data stored on the drive is encrypted, so from what I can see if they go bust you say bye bye to all your date stored on it. Presumably if they are for any reason offline you may not be able to use your Limas either?

I originally bought the product as I thought it would be a fit and forget storage and backup solution, as I bought 2 limas.

It took over six months to get an answer from support how to configure 2 Lima's in a configuration without using upnp, in fact I worked it out myself in the end and they eventually confirmed that it would work.

I had confirmation from our Team, to connect 2 Limas with port forwarding, please follow these steps: - Manually redirect port 25211 to one of your Lima, - Please use the port 25212 to the second one.You can use any ports between 25211 and 25215 for your Limas. The Limas will eventually figure it out by themselves (but may take 5-10 minutes) This is relevant to do it manually only if you plan to do a manual redirection. If you are using UPnP/IGD or NAT-PMP, it's automatic. Please do not hesitate to get back to me if you have any further question.
upnp is commonly disabled as software can create security holes in your router without you knowing. In addition its common to have a secure area and a non secure area on your home network. If you do have a separate secure area you'll need hairpinning/loopback on your router so devices behind the firewall can access the Limas. Unfortuately upnp does not support this.

If you are lucky you can define permanent dhcp addresses for the Limas on your router and the port mapping outlined above and everything will work 'eventually'.

It would have been nice to have a simple way to allocate a name, ip addresses and port to each Lima  permanently.

Similarly a simple piece of software could allow you to perhaps diagnose what is wrong with it. There is a diagnostic dump feature in the Lima app on windows which you send to support as I have done many times but without any response.

The windows software seems to take an age to determine the status of the Limas and then a few minutes on it might change its mind. More recent versions seem more accurate. That said there is little indication there is anything wrong with your lima, the task bar icon just changes colour so it could be weeks or months before you notice a fault, you might notice the pop up notification but as it disappears within a few seconds you might not.

The linux version has no gui so you've got to be happy with the command line.

The android version appears to need you to start it to perform the sync and used to eat the battery on my phone.

Forget using the Lima app on a HD pc like a surface pro, the font used is so small its pretty impossible to read anything.

You'll need fine finger control when trying to check the status of uploads too as you have to hover over the different coloured slices of a status bar to see what's what, the slices being proportional to the size of the drive, even then its very vague and there is no way to see what is actually waiting to go.

On a security note your devices might decide to talk to each other through a 'free' relay, on the face of it all the data is encrypted but the whole point of these devices was that the data did not leave your control, now the data is being routed via a relay server located god knows where and controlled by god knows who. There should be an option to disable this feature.

Suffice to say I've had my Limas for 18 months or so now, I've had 2 fail and I've not trusted them with any of my data yet as they are simply too unreliable.

All in all it was a clever idea but it should have stayed on the designers bench until it was fit for purpose. With some sort of status indicator, better software, some form of proper diagnostics, proper support for non pnp environments/secure environments and some thought to easily replacing a faulty unit this could have been a really good product particular when run as a pair.

Mine are most likely just going to be dumped in the parts bin and await recycling.

Friday, 8 September 2017

Windows 10 Language pack install fails - Solved

I noticed today my £ key isn't working. Tried installing the language pack but it just downloads it and gives up. Checking on google it seems a common problem but with no real solutions other than perhaps a clean boot which is a long and complicated task.

After a few hours of trying stuff I found the language pack in a sub folder of C:\Windows\SoftwareDistribution\Download.

I tried installing it myself by running Lpksetup, it started installing but just gave up with installation failed.

A sudden thought, safe mode, hmm how on windows 10, hold down shift whilst clicking on restart.

Sure enough it installed in safe mode and I could select my new language pack as default, it advised me it would be available on next login.

Rebooted and hurrah I have my £'s back.

Monday, 9 May 2016

hp-health (hpasm) fails after centos update

Did a routine yum update to a centos 6  server today and as part of that update it installed hp-health-10.40-1777.17.rhel6.i686. As part of the upgrade it obviously stops and starts hpasmxld.

As soon as that was done errors started being logged in syslog.

hpasmxld[2143]: OsKcsExecCmd:  IPMI NetFN  0x6   CMD: 0x31 has timed out!
hpasmxld[2143]: OsKcsExecCmd:  IPMI NetFN  0x6   CMD: 0x1 has timed out!
hpasmxld[2143]: hpIoctl(): IOCTL Timeout -- Waiting on IPMI

Trying to fire up hpasmcli meant a wait of a couple of minutes.

Stopping hpasmxld caused an error

# service hp-health stop
  Using Proliant High Performance
        IPMI based System Health Monitor
  Using standard Linux IPMI device driver
/etc/init.d/hp-health: line 760: dmidecode: command not found
  Shutting down Proliant High Performance
  IPMI based System Health Monitor (hpasmxld):   ESCALATE: kill -9 hpasmxld
                                                           [  OK  ]

It appears a pre-requisit is not correctly identified and was not installed as part of the yum update.

After installing dmidecode (yum install dmidecode) and restarting hp-asrd and hp-healthd all appears fine. hpasmcli performance is back to normal, no more errors in syslog and hpasmxld can be stopped and started correctly.

Thursday, 30 July 2015

Centos 6 patching bind for bind bug CVE-2015-5477

In order to patch centos 6 for bind bug CVE-2015-5477 it is necessary to use the CR (continuous release) repository as it is not available for 6.6 and will be released in 6.7 and thus must be installed as a hot fix.

To do this simple enable the CR repository

# yum install centos-release-cr

Then update bind

# yum update bind

For good measure restart bind

# service named restart

And then I suggest you remvoe the CR repository

# yum erase centos-release-cr

You can check which repositories are in use

# yum repolist

 

Friday, 24 July 2015

redirecting tcp traffic

Sometimes I see a transit issue on the internet which I can't fix as I don't have a contract with the particular company in question. Whilst I am waiting for it to be resolved I sometimes route traffic round the issue by bouncing it off another server in another part of the world.

So for instance if I wanted to send tcp traffic to a particular port from a server in say the UK to a server in Singapore when there is a traffic issue between them then I could bounce the traffic off a server I have in Japan using iptables.

SERVERIP="x.x.x.x"
DESTIP="y.y.y.y"
ORIGIP="z.z.z.z"
PORT="nnn"

iptables -F -t nat
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp -s $ORIGIP -d $SERVERIP --dport $PORT -j DNAT --to-destination $DESTIP
iptables -A POSTROUTING -t nat -o eth0 -s $ORIGIP -d $DESTIP -j MASQUERADE
iptables -A POSTROUTING -t nat -o eth0 -s $DESTIP -d $ORIGIP -j MASQUERADE

Simply run the commands above on the server in Japan setting SERVERIP to the address of the server in Japan, DESTIP to the address of the server in Singapore and ORIGIP to the address of the server in the UK.

Once that's done send the traffic to SERVIP rather than DESTIP and it will be redirsted to DESTIP and appear to be from ORIGIP.

Bear in mind you won't be able to send traffic to SERVERIP on the port specified so it's probably not a good idea to redirect port 22!


Wednesday, 13 May 2015

resize an lvm partition on a vm guest

So you've order an upgrade to your virtual disk from your cloud provider and the virtual disk has been extended but df show it is still the same size.

# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_test-lv_root
                       28G  1.4G   26G   6% /
tmpfs                 504M     0  504M   0% /dev/shm
/dev/sda1             477M   48M  404M  11% /boot

e2fsck won't work because it's mounted.

# e2fsck -f /dev/mapper/vg_test-lv_root
e2fsck 1.41.12 (17-May-2010)
/dev/mapper/vg_test-lv_root is mounted.
e2fsck: Cannot continue, aborting.

resize2fs says there is nothing to do!

# resize2fs /dev/mapper/vg_test-lv_root
resize2fs 1.41.12 (17-May-2010)
The filesystem is already 7473152 blocks long.  Nothing to do!

You need to extend the partition with lvextend....

# lvextend -l +100%FREE /dev/mapper/vg_test-lv_root
  Size of logical volume vg_test/lv_root changed from 28.51 GiB (7298 extents) to 78.51 GiB (20098 extents).
  Logical volume lv_root successfully resized

and then resize the file system....

# resize2fs -p /dev/mapper/vg_test-lv_root
resize2fs 1.41.12 (17-May-2010)
Filesystem at /dev/mapper/vg_test-lv_root is mounted on /; on-line resizing required
old desc_blocks = 2, new_desc_blocks = 5
Performing an on-line resize of /dev/mapper/vg_test-lv_root to 20580352 (4k) blocks.
The filesystem on /dev/mapper/vg_test-lv_root is now 20580352 blocks long.

now you can see the space you have ordered!

# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_test-lv_root
                       78G  1.4G   72G   2% /
tmpfs                 504M     0  504M   0% /dev/shm
/dev/sda1             477M   48M  404M  11% /boot

As always such operations carry a risk so take a backup or better still a snapshot and carry out at your own risk.



Friday, 30 January 2015

centos resolv.conf keeps getting overwritten

So if ever resolv.conf keeps getting overwritten when you boot linux you can tear your hair out trying to
work out why various web sites will tell you its NetworkManager (as does the file) or dhcpd or netctl.

Having ruled out all those, checked all sorts of boot scripts and even tried to use audit to find out what is changing the file check for /etc/resolv.conf.save. If it exists it will get copied to /etc/resolv.conf when the server boots.

remove /etc/resolv.conf.save and all should be well.

Tuesday, 3 June 2014

Using fail2ban with dated log files

I recently set up a new web server and took advantage of apache's ability to log directly to date stamped log files. This means there is no need to restart apache each day or rotate the logs.

Unfortunately I could not find a way to get fail2ban to recognise the new log file names for example error_20140603.log rather than error.log Even when I managed to add and remove log files using fail2ban-client I found issues as sendmail-whois-lines still searched the original files rather than the latest.

My final solution was to simply write a script to start fail2ban when the server is booted which also runs each day at midnight and takes account of the dated log files.

One problem I faced is fail2ban won't start if it can't find the log file so you have to ensure it exists.

Below is the code which is called by /etc/rc.d/rc.local to ensure fail2ban is started when the server is booted and by cron at midnight.

# define variables
pidfile="/var/run/fail2ban/fail2ban.pid"
nlogfile="/var/log/apache2/error."
nlogfile+=`date +%Y.%m.%d`
nlogfile+=".log"
# check if fail2ban is running
dostart=1
if [ -f $pidfile ];
then
  pid=`cat $pidfile`
  if ps -p $pid > /dev/null
  then
    echo fail2ban is running
    dostart=0
  fi
fi
# create config file
cat < /etc/fail2ban/jail.local
[apache]
enabled  = true
filter   = apache
action   = iptables-multiport[name=APACHE, port="http,https"]
        sendmail-whois-lines[name=APACHE, dest=root, sender=fail2ban@mydomain.com, sendername="fail2ban", logpath=${nlogfile}]
logpath  = ${nlogfile}
maxretry = 0
bantime  = 86400
EOF
# ensure real log file is created
wget http://127.0.0.1/fail2ban.php

sleep 1
# reload/start as required
if [ $dostart == 1 ];
then
  fail2ban-client start
else
  fail2ban-client reload
fi


As you can hopefully see the code creates a new jail.local with the correct logfile name in it.

It also does a wget of a non existant file to cause an error to be logged by the web server. This ensures the dated log file is created by apache and has the correct permissions.

Just remember to ensure apache is started before fail2ban!

Thursday, 1 August 2013

Symantec System Recovery Desktop Edition

So I have a failed PC and a spare PC, best way to move from one to another is Symantec System Recovery Desktop Edition as the hardware is different and simply moving the drive from one to the other won't work.

I buy Symantec System Recovery Desktop Edition 2013 from Symantec online but then have to wait 2-3 days before I get my licence key so can't do anything.

Finally the key arrives and I can get cracking.

Or perhaps not the 2013 version won't work on my system as I get the error message "Error 0x0000005D: Your PC needs to restart. Please hold down the power button" 

After chatting to support it appears my machine is not PAE capable so won't work with the 2013 edition as per tech note http://www.symantec.com/business/support/index?page=content&id=TECH203411

So I request and get a download of the 2011 edition which boots fine and I can now do a cold backup using the boot iso.

I then attempt to restore the backup on my spare pc which I know supports Windows 7 as it has run it in the past.

All goes well until it reboots and windows starts configuring itself when I get the following message.



"Windows could not parse or process the unattend answer file for pass [specialize]. The settings specified in the answer file can not be applied. The error was detected while processing settings for the component [Microsoft-Windows-Shell-Script]"

When I click OK the PC then reboots and when it restarts windows I get another message.



"The computer restarted unexpectedly or encountered a problem or an unexpected error. Windows installation cannot proceed. To install windows click "OK" to restart the computer and restart the installation".
 
There is a method to get round this message which I tried but I did not end up with a useable system afterwards. Even after much googling I ended up with a pc which appeared to work but had issues with DNS resolution, entries appeared in the dns cache correctly but for some reason the program requesting the lookup did not get the address meaning I could ping an ip address but not a name such as www.google.co.uk.

Next day after some sleep I decided to do a restore but to prevent Symantec System Recovery creating an answer file, this can be done as follows:-

During the restore wizard process, hold down the 'Ctrl' key when clicking the 'Use Rrestore Anywhere' option. Disable 'Run Windows Mini Setup' and put a check in 'Delete existing drivers'. 

The restore then worked without error and windows booted correctly except although windows correctly saw my network card I had no network access.

Having learnt from my earlier restore when I had the same issue I removed and reinstalled my firewall software (AVG it turns out but this will probably apply to most virus software) and hey presto my network appeared.

Symantec support were helpful but in the end I worked it out myself.

Hope this helps some other poor unfortunate sole if they have the same issue.

Thursday, 7 February 2013

mysql commands out of sync after repair table

Recently I was trying to automate some table repairs when a server crash is detected. My code attempted to repair a number of tables but after repairing the first table subsequent repairs failed with "Commands out of sync; you can't run this command now".

On investigation I realised I actually needed to read the response from the database much as if I had queried a table.

It appears four columns are returned from the repair statement reflecting the status of the repair.

Example code:-

    sprintf(sql_statement,"repair table %s",tablename);
    reportlog(sql_statement);
    if (mysql_query (local, sql_statement) != 0) {
        sprintf(message,"mysql select failed:\nError %u %s\n",mysql_errno(local), mysql_error(local));
        reportlog(message);
    }

    res_set = mysql_store_result(local);
    if (res_set != NULL) {
        row = mysql_fetch_row (res_set);
        if (row != NULL) {
            sprintf(message,"%s %s %s %s",row[0],row[1],row[2],row[3]);
            reportlog(message);
        }
    }   
    mysql_free_result(res_set);

Running the code results in :-

database.tablename repair status OK