Sutff about my job and comments about personal activities. Take a look to the first idea.

Monday, April 16, 2018

Microsip - Precios con descuentos

En Microsip, el modulo de comercio exterior no coinciden los totales de la factura vs el total del módulo de comercio exterior, por lo q es necesario modificar los precios para q incluya el descuento.

Se creo un script en python q permite hacer este cambio.

#!/usr/bin/env python
# @author Beto Reyes
# @date 28/Marzo/2018
# http://kinterbasdb.sourceforge.net/dist_docs/usage.html#tutorial
# syntax on
# colorscheme darkblue
import kinterbasdb as k
import csv, datetime, os
import argparse, sys, glob
import logging, logging.handlers
from sets import Set
from datetime import timedelta

parser = argparse.ArgumentParser(description='Actualiza el precio de cada partida en base al descuento')
parser.add_argument('--database', dest='strAliasfdb', default='Prueba')
parser.add_argument('--force', dest='boolForce', default='0') # False
parser.add_argument('--commit', dest='commit', default='0') # False
parser.add_argument('--folio', dest='folio', default='0') # False
args = parser.parse_args()
globals().update(vars(args))
#print args

class doctosVentas:
       #strAliasfdb='Prueba'
       #strAliasfdb='IRSA'

       def __init__(self, strDBHost, strAliasfdb, strPassword):
               logger.info("Conectandose a DB %s:%s" % (strDBHost, strAliasfdb))
               self.con = k.connect(dsn='%s:%s.fdb' % (strDBHost, strAliasfdb), user='sysdba', password=strPassword,
                       timeout={'period': 60.0}) # time out after 60.0 seconds of inactivity
               self.cur = self.con.cursor()
               self.strAliasfdb = strAliasfdb

       #
       def convierteDescuento(self, folio):
               if folio == "0": return 1

               strSql = "select folio, tipo_docto, subtipo_docto, estatus, aplicado, cfdi_certificado, docto_ve_id \n\
                       from doctos_ve where folio like '%s%%%s'" % (folio[0], folio[1:])
               logger.debug("%s" % (strSql))
               cur = self.con.cursor()
               cur.execute(strSql)
               docto = cur.fetchone()
               folio = docto[0]
               tipo_docto = docto[1]
               subtipo_docto = docto[2]
               estatus = docto[3]
               aplicado = docto[4]
               cfdi_certificado = docto[5]
               docto_ve_id = docto[6]
               logger.info( "Folio:%s Tipo:%s Subtipo:%s Estatus:%s Aplicado:%s CFDI:%s" %
                       (folio, tipo_docto, subtipo_docto, estatus, aplicado, cfdi_certificado ))
               if not ((( tipo_docto == 'F' and  estatus == 'N' ) or ( tipo_docto == 'R' and  estatus == 'P' )) and
                       subtipo_docto == 'N' and aplicado == 'S' and cfdi_certificado == 'N'):
                       logger.info ("No es posible modificar la factura")
                       return 1
               strSql = "select precio_unitario, pctje_dscto, docto_ve_det_id from doctos_ve_det \n\
                       where docto_ve_id = %s" % (docto_ve_id)
               cur.execute(strSql)
               detalle = cur.fetchall()
               detalle2 = []
               for row in detalle:
                       precio_unitario = row[0]
                       pctje_dscto = row[1]
                       docto_ve_det_id = row[2]
                       if pctje_dscto > 0:
                               #detalle2.append( [round(row[0]*(100-row[1])/100,3), 0, row[2]])
                               detalle2.append( [format(row[0]*(100-row[1])/100,'.2f'), 0, row[2]])
                       else:
                               detalle2.append( [format(row[0],'.2f'), 0, row[2]])
                       logger.info("id:%s precio:%s dscto:%s" % (docto_ve_det_id, precio_unitario, pctje_dscto))
               cur.executemany("update doctos_ve_det set precio_unitario = ? , pctje_dscto = ? where docto_ve_det_id = ?", de
talle2)
               logger.info("Actualizando...")
               cur.execute(strSql)
               detalle = cur.fetchall()
               for row in detalle:
                       precio_unitario = row[0]
                       pctje_dscto = row[1]
                       docto_ve_det_id = row[2]
                       logger.info("id:%s precio:%s dscto:%s" % (docto_ve_det_id, precio_unitario, pctje_dscto))

# Add log to unix syslog
logger = logging.getLogger('corrigeFactura')
syslog = logging.handlers.SysLogHandler()
syslog.setFormatter(logging.Formatter('%(name)s: %(message)s'))
logger.addHandler(syslog)
logger.setLevel(logging.INFO)

# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Log everything and send it to stderr
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)

myFactura = doctosVentas('localhost', strAliasfdb, '437880')
#myFactura.convierteDescuento('C29877')
myFactura.convierteDescuento(folio)

if commit=='0':
       logger.info('Desconectando de DB: rollback')
       myFactura.con.rollback()
else:
       logger.info('Desconectando de DB: commit')
       myFactura.con.commit()
myFactura.con.close()

Thursday, June 01, 2017

NetworkManager

When using NetworkManager, it is posible to start a VPN connection after a successful wireless connection.
I have autofs configured on my home directory, so I need to start autofs after VPN connection:
/etc/NetworkManager/dispatcher.d/10autofs

#!/bin/bash
SERVER='172.16.1.1'
# Nothing to do if user does not have requisite binaries.
ping -c 1 $SERVER &>/dev/null
if [ $? -ne 0 ]; then
        # server is down so unmount
        /etc/init.d/autofs stop
else
        # server is up
        /etc/init.d/autofs start
fi
Whenever a VPN or wireless disconnection ocurrs, I've to stop autofs:
/etc/NetworkManager/dispatcher.d/pre-down.d/autofs
#!/bin/bash
interface=$1 
status=$2
if [ "$interface" == "wlan0" ] || [ "$CONNECTION_ID" == "reyesdf-tap" ]; then
        for dir in $(mount | grep "/mnt/auto" | awk '{print $3}' | tail -n +2)
        do
            umount $dir
        done
        sleep 5
        /etc/init.d/autofs stop
fi

References for understanding the scripts:
https://wiki.archlinux.org/index.php/NetworkManager
https://developer.gnome.org/NetworkManager/unstable/NetworkManager.html

Sunday, April 23, 2017

Running Asterisk with different web user

Freepbx 12 install configure "asterisk" user to run apache server... as explained here:
https://community.freepbx.org/t/running-asterisk-with-different-web-user/26812/1

But, as the same post explain, its better to use www-data user to run apache server...
The diagnostic is that everytime  "amportal chown" or "amportal start" is executed, the ownership of files are changed to "asterisk"...

The config files are needed to modify before running freepbx install
wget http://mirror.freepbx.org/modules/packages/freepbx/freepbx-12.0-latest.tgz
tar xvfz freepbx-12.0-latest.tgz
freepbx/amp_conf/bin/freepbx_engine:AMPASTERISKUSER=www-data
freepbx/install_amp:$runas_uid = "www-data";
freepbx/libfreepbx.install.php: $set['value'] = 'www-data';
freepbx/libfreepbx.install.php: $set['value'] = 'www-data';
cd freepbx
./install_amp --installdb

Wednesday, January 28, 2015

Android: How to Delete synced Contacts

If you wish to delete all contacts from your Android device, without deleting from gmail...

1. Disable syncing by going to Settings > Accounts & sync. Select your Google account and uncheck Contacts. If you sync contacts with other apps such as Facebook or Twitter, be sure to disable syncing for those apps as well.

2. Go to Settings > Applications > Manage applications > All > Contacts Storage and select Clear data.
Note: This will also clear other data like your recent calls and Favorites

Thanks to  Mitch Bartlett for his post of Android: How to Delete All Contacts

Tuesday, December 23, 2014

Dongle gsm

Asterisk huawei 3g dongle
https://code.google.com/p/asterisk-chan-dongle/

All the instrucctions specifically for asterisk 11 are here:
http://zaliasrobotas.blogspot.mx/2013/10/chandongle-do-not-compile-with-asterisk.html

Tuesday, October 21, 2014

fsck /home

To fsck /home, you need to change /etc/passwd to set user directory to /var/tmp

breyes:x:1000:1000:Beto Reyes,,,:/var/tmp:/bin/bash

After that, you do a list of open files related to /home directory with:
lsof +D /home

I recomend to stop samba service
/etc/init.d/samba stop

Stop dropbox service
dropbox stop

Do a full fsck with:
fsck.ext3 -f /dev/solar_vg/home_lv

after finishing, undo the previous steps

Saturday, September 13, 2014

Actualización Microsip

La actualización de Microsip requiere:

Respaldo de Bases de datos
tar cfz /var/partimage/microsip-YYYYMMDD.tgz \
    /var/lib/firebird/2.5/data/Empresa.fdb \
    /var/lib/firebird/2.5/data/System/Config.fdb \
    /var/lib/firebird/2.5/data/System/Metadatos.fdb
Actualización licencias de candado, en alguna maquina con Microsip instalado:
1. Módulo: Administración de Sistema
2. Menú: Herramientas
3. Opción: Licencias de Candado Microsip

Es posible bajar la actualización del sitio oficial:
http://soporte.microsip.com/VERSIONES.aspx

Para ls instalación se requiere el archivo Metadatos.fdb y extraer el contenido a /var/lib/firebird/2.5/data/System/
http://www.microsip.com/Actualizaciones/2018/MD_2018.zip

Convierta a formato Firebird 2.5 la base de datos de la configuración del sistema
1. Respalde la configuración del sistema por medio del menú Archivo de la carpeta de empresas.
2. Restaure el mismo respaldo por medio del menú Herramientas.

Convierta las bases de datos de todas sus empresas
En la misma carpeta de empresas, haga lo siguiente para cada una de las empresas:
1. Respalde la empresa.
2. Restaure el mismo respaldo.
3. Aplique la Conversión de versiones NG por medio del menú Herramientas.

Thursday, September 13, 2012

squid proxy gateway based downloaded object

#  TAG: tcp_outgoing_address
#       Allows you to map requests to different outgoing IP addresses
#       based on the username or sourceaddress of the user making
#       the request.
#
#       tcp_outgoing_address ipaddr [[!]aclname] ...
#
#       Example where requests from 10.0.0.0/24 will be forwareded
#       with source address 10.1.0.1, 10.0.2.0/24 forwarded with
#       source address 10.1.0.2 and the rest will be forwarded with
#       source address 10.1.0.3.
#
#       acl normal_service_net src 10.0.0.0/255.255.255.0
#       acl good_service_net src 10.0.1.0/255.255.255.0
#       tcp_outgoing_address 10.0.0.1 normal_service_net
#       tcp_outgoing_address 10.0.0.2 good_service_net
#       tcp_outgoing_address 10.0.0.3 
 
Reference here 

Tuesday, June 05, 2012

PDFs: imagemagick & poppler

I was looking for a way to extract images from pdfs to know the resolution of each embeded image.
poppler has a tool named "pdfimages" to extract images from the pdf, usage:

pdfimages -j file.pdf img

Then, use tools from imagemagick to read characteristics of the images, usage:
display img.jpg
identify -verbose img.jpg
imagemagick let create a pdf file from jpg images, usage:
convert imageA.jpg imageB.jpg file.pdf pdf

Saturday, April 14, 2012

wmic for Linux

Compiling WMIC for Linux (Without Installing Samba)

http://semafour.wordpress.com/2010/02/17/compiling-wmic-for-linux-without-installing-samba/

http://www.edcint.co.nz/checkwmiplus/

Tunning remote desktop

I just found a way to set default connection setting for clients...
Using Group Policies Editor, gpedit.msc

\Computer Configuration\Administrative Templates\Windows Components\Terminal Services\Printer Redirection
"Do not allow client printer redirection". Set it to Enable

PD. google "disable remote printers using group policies"

Monday, September 19, 2011

firebird setup of microsip in linux

First, you have to backup youcurrent databases in windows

gbak.exe -t -user SYSDBA -password xxxx "c:\Microsip datos\MyCompany.fdb" "c:\Microsip datos\Respaldos\MyCompany.fbk"
gbak.exe -t -user SYSDBA -password xxxx "c:\Microsip datos\System\Config.fdb" "c:\Microsip datos\Respaldos\Config.fbk"
gbak.exe -t -user SYSDBA -password xxxx "c:\Microsip datos\System\Metadatos.fdb" "c:\Microsip datos\Respaldos\Metadatos.fbk"

The security2.fdb should be copied when firebird is not running, so the firebird service should be stopped before copying from windows, and services must be stopped too before copying into linux.

Then, directories must be created in "data" directory of firebird
mkdir /var/lib/firebird/2.5/data/System
mkdir /var/lib/firebird/2.5/data/Respaldos
mkdir /var/lib/firebird/2.5/data/Exportación
Copy the backups into /tmp and restore them on these directories
/usr/bin/gbak -t -c -user SYSDBA -pass xxxx -rep /tmp/MyCompany.fbk /var/lib/firebird/2.5/data/MyCompany.fdb
/usr/bin/gbak -t -c -user SYSDBA -pass xxxx -rep /tmp/Config.fbk /var/lib/firebird/2.5/data/System/Config.fdb
/usr/bin/gbak -t -c -user SYSDBA -pass xxxx -rep /tmp/Metadatos.fbk /var/lib/firebird/2.5/data/System/Metadatos.fdb
All files should be "firebird" owner
chown -R firebird.firebird /var/lib/firebird/2.5/data/

Microsip config is:
"Conexion", "Abrir conexion"
Servidor: 172.16.1.1
Carpeta de datos: /var/lib/firebird/2.5/data/
To test access with isql, try
/usr/bin/isql-fb
> CONNECT localhost:/var/lib/firebird/2.5/data/MyCompany.fdb
> user 'SYSDBA' password 'xxxx';
> show tables;
> quit;

I read this link to understand how to do it and then write this tutorial.

Tuesday, August 16, 2011

Backup firebird databases

I'm was looking forward how to backup Firebird used by Microsip

gbak "remote-host:c:\Databases\Mytest.FDB" /dev/stdout -user SYSDBA -pass xxxx | gzip > $path/Mytest-$(date +%Y%m%d%H%M).fbk.gz


# Backup config database

gbak "remote-host:c:\Databases\System\CONFIG.FDB" /dev/stdout -user SYSDBA -pass xxxx | gzip > $path/Config-$(date +%Y%m%d%H%M).fbk.gz


# The only way to access the security database is via the Service Manager. As
# GBAK can also use the Service Manager (Option -se), you can run a backup
# using this option. However, the backup file will also be written to the
# server machine.

gbak -user sysdba -pass xxxx -service dbhost:service_mgr "C:\Archivos de programa\Firebird\Firebird_2_1\security2.fdb" "C:\Archivos de programa\Firebird\Firebird_2_1\security2-$(date +%Y%m%d%H%M).fbk"

Tuesday, November 03, 2009

openvpn routed

I used to have bridge openvpn server in windows.. cause there was the easy way to configure...
But in linux bridge interfaces are not optimal, its better to use route openvpn..
Configuring the server and clients are found almost everywhere.. and iptables is also needed
A pretty short tutorial is can be found here

VMware tunning

I just needed how to tune my vmware host... a easy guide here.. from alfi's blog

Sunday, November 01, 2009

VMware tunning

I just needed how to tune my vmware host... a easy guide here.. from alfi's blog

Friday, October 30, 2009

SPA8000 & asterisk

I just received my SPA 8000 and I needed to connect to an asterisk...
Just like a SIP extension... found in:
Configuring the Cisco SPA8800 IP Telephony Gateway in an Asterisk® Environment a link


SPA8000 & asterisk

I just received my SPA 8000 and I needed to connect to an asterisk...
Just like a SIP extension... found in:
Configuring the Cisco SPA8800 IP Telephony Gateway in an Asterisk® Environment a link


Tuesday, October 27, 2009

SSH attacks

2 years ago I set up a iptables rule to stop ssh attack... something like:
# Limit SSH connections
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name ATTACKER_SSH --rsource --update --seconds 600 --hitcount 6 -j DROP
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name ATTACKER_SSH --rsource --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT

but last month I read about fail2ban which is little easiear to configure and even more specific... and set it up in 5 minutes...
http://www.howtoforge.com/fail2ban_debian_etch

Thursday, October 15, 2009

USB HASP dongle

It was not so hard to set up usb dongle key to get access in linux... I use it for Microsip

Download
Device Drivers for USB HASP keys
http://www.aladdin.com/support/hasp/hasp4/linuxdrv.aspx
wget ftp://ftp.aladdin.com/pub/hasp/new_releases/linux/HDD_Linux_USB_daemon.tar.gz

NetHASP License Manager
http://www.aladdin.com/support/hasp/enduser.aspx
wget ftp://ftp.aladdin.com/pub/hasp/hl/linux/hasplm_linux_8.30.tgz

Untar de tarballs to /usr/sbin

Mount usbfs
mount -t usbfs none /proc/bus/usb

To connect to USB dongle run:
/usr/sbin/aksusbd
and it will create /tmp/.aksusb

To start service on UDP:475
/usr/sbin/hasplm

UPDATE: 24/Dic/2015
I've have issues regarding dongle disconnection

usb 1-3: usbfs: USBDEVFS_CONTROL failed cmd aksusbd rqt 192 rq 161 len 8 ret -71

I had to desconect the power of the usb port and then connect again with:

echo 0 > /sys/bus/usb/devices/1-3/authorized
echo 1 > /sys/bus/usb/devices/1-3/authorized

After that, retart the aksusb daemon with
/etc/init.d/aksusbd restart

There is a link on how to install microsip 2007 on linux using winehq
Unfortunatelly, laters version of microsip use HASP SRM Dongle, which is not yet suported according with Etersoft Support for HASP dongles in Wine

UPDATE: 7/March/2017
Driver update can be downloaded from Gemalto Downloads
License version 7.51 on release October/2016

Nagios monitoring configuration for hasplmd segfault:

define service{
use generic-service
host_name localhost
service_description hasp_proc
check_command check_hasp
# Minutes to wait before next "regular" check.
normal_check_interval 2
# Minutes to wait before re-checking a non-OK service.
# A value of 1 = 60 seg, a value of 0.50 min = 30 seg
#retry_check_interval 1
retry_check_interval .25
# Number of times to retry a service check when a non-OK state is returned.
max_check_attempts 3
event_handler restart-aksusbd
}
define command{
command_name check_hasp
command_line /usr/lib/nagios/plugins/check_procs -c 1: -C hasplmd
}
define command{
command_name restart-aksusbd
command_line /usr/local/bin/aksusbd_eventhandler.sh "$SERVICESTATE$" "$SERVICESTATETYPE$" "$SERVICEATTEMPT$"
}

Add path to /etc/init.d/aksusbd
PATH=/sbin:/usr/sbin:/bin:/usr/bin

visudo
nagios ALL=NOPASSWD: /etc/init.d/aksusbd start

/usr/local/bin/aksusbd_eventhandler.sh


!/bin/sh
#
# Event handler script for restarting the web server on the local machine
#
# Note: This script will only restart the web server if the service is
# retried 3 times (in a "soft" state) or if the web service somehow
# manages to fall into a "hard" error state.
#

# What state is the AKSUSB service in?

LOG=/tmp/eventhandler.log
echo $UID >> $LOG
echo $(date) $@ >> $LOG
# kill -ABRT $(pidof hasplmd)

case "$1" in
OK)
# The service just came back up, so don't do anything...
;;

WARNING)
# We don't really care about warning states, since the service is probably still running...
;;

UNKNOWN)
# We don't know what might be causing an unknown error, so don't do anything...
;;

CRITICAL)
# Aha! The AKSUSB service appears to have a problem - perhaps we should restart the server...
# Is this a "soft" or a "hard" state?
case "$2" in
# We're in a "soft" state, meaning that Nagios is in the middle of retrying the
# check before it turns into a "hard" state and contacts get notified...
SOFT)
# What check attempt are we on? We don't want to restart the service on the first
# check, because it may just be a fluke!
case "$3" in
# Wait until the check has been tried 2 times before restarting the web server.
# If the check fails on the 4th time (after we restart the web server), the state
# type will turn to "hard" and contacts will be notified of the problem.
# Hopefully this will restart the web server successfully, so the 4th check will
# result in a "soft" recovery. If that happens no one gets notified because we
# fixed the problem!
2)
echo -n "Restarting AKSUSB service (3rd soft critical state)..."
# Call the init script to restart the AKSUSB services
#chmod o+w /sys/bus/usb/devices/1-3/authorized
#echo 0 > /sys/bus/usb/devices/1-3/authorized
#echo 1 > /sys/bus/usb/devices/1-3/authorized
sudo /etc/init.d/aksusbd start
;;
esac
;;
# The AKSUSB service somehow managed to turn into a hard error without getting fixed.
# It should have been restarted by the code above, but for some reason it didn't.
# Let's give it one last try, shall we?

# Note: Contacts have already been notified of a problem with the service at this
# point (unless you disabled notifications for this service)
HARD)
echo -n "Restarting HTTP service..."
# Call the init script to restart the HTTPD server
#chmod o+w /sys/bus/usb/devices/1-3/authorized
#echo 0 > /sys/bus/usb/devices/1-3/authorized
#echo 1 > /sys/bus/usb/devices/1-3/authorized
sudo /etc/init.d/aksusbd start
;;
esac
;;
esac
exit 0