If you mount a Windows 7 share using Samba/CIFS you may run into “mount error(12): Cannot allocate memory” if you are using very large files on the Windows machine. Looks like in certain situations Windows needs to be told to run as a file server and to expect large files. You can read more details at Large Files are locking up Windows 7 32 bit and 64 bit, but the solution is to make two registry edits and then restart a service:

Set “HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\LargeSystemCache” to “1″.
Set “HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\Size” to “3″.
Restart the “server” service.
Once you have done that you should be able to mount the share using a command like “sudo mount -a” or just reboot the Linux machine.

ref: http://jlcoady.net/windows/how-to-resolve-mount-error12-cannot-allocate-memory-windows-share

 

Many times when i setup multiple nic’s on the same machine using LAN (eth0) and WAN (eth1) ip’s. The reason is likely due to a Gateway not being setup correctly in your nic settings. In this case my WAN nic is bound to eth0 and would not ping.

[root@cn2 ~]# ping nike.com
PING nike.com (66.54.56.30) 56(84) bytes of data.
From cn2 (192.168.1.2) icmp_seq=2 Destination Host Unreachable
From cn2 (192.168.1.2) icmp_seq=3 Destination Host Unreachable
From cn2 (192.168.1.2) icmp_seq=4 Destination Host Unreachable
From cn2 (192.168.1.2) icmp_seq=5 Destination Host Unreachable

See current routes…

[root@cn2 ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.1.0 * 255.255.255.0 U 0 0 0 eth0
link-local * 255.255.0.0 U 1002 0 0 eth0
link-local * 255.255.0.0 U 1003 0 0 eth1
10.200.0.0 * 255.255.0.0 U 0 0 0 eth1
default 10.200.1.2 0.0.0.0 UG 0 0 0 eth0

Add new route on correct device.

[root@cn2 ~]# route add default gw 10.200.1.2 netmask 0.0.0.0 dev eth1
[root@cn2 ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.1.0 * 255.255.255.0 U 0 0 0 eth0
link-local * 255.255.0.0 U 1002 0 0 eth0
link-local * 255.255.0.0 U 1003 0 0 eth1
10.200.0.0 * 255.255.0.0 U 0 0 0 eth1
default 10.200.1.2 0.0.0.0 UG 0 0 0 eth1
default 10.200.1.2 0.0.0.0 UG 0 0 0 eth0

Delete old route.

[root@cn2 ~]# route del default dev eth0
[root@cn2 ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.1.0 * 255.255.255.0 U 0 0 0 eth0
link-local * 255.255.0.0 U 1002 0 0 eth0
link-local * 255.255.0.0 U 1003 0 0 eth1
10.200.0.0 * 255.255.0.0 U 0 0 0 eth1
default 10.200.1.2 0.0.0.0 UG 0 0 0 eth1

Done!

 

1. enable nagios.cmd access.

[root@james conf]# chmod -R 777 /usr/local/nagios/var/rw/
[root@james conf]# ls -la /usr/local/nagios/var/rw/
total 8
drwxrwxrwx 2 nagios nagios 4096 Dec 29 12:51 .
drwxrwxr-x 7 nagios nagios 4096 Dec 29 12:54 ..
prwxrwxrwx 1 nagios nagios 0 Dec 29 12:54 nagios.cmd
prwxrwxrwx 1 nagios nagios 0 Dec 27 16:02 nagios.cmd-old

2. add auth user to access cgi’s in cgi.cfg

use_authenticaiontion=1

add authenticated user (name of user logged in via .htaccess file) or * for all for following.

authorized_for_system_information=*
authorized_for_configuration_information=*
authorized_for_system_commands=*
authorized_for_all_services=*
authorized_for_all_hosts=*
authorized_for_all_service_commands=*
authorized_for_all_host_commands=*

3. nagios.cfg enable check_external_commands=1

4. restart nagios.

 

INSTALL on RHEL6

1.Archive to use for RHEL6.

OMSA 6.5 – wget http://ftp.us.dell.com/sysman/OM-SrvAdmin-Dell-Web-LX-6.5.0-2247.RHEL5.x86_64_A01.4.tar.gz

2.Required libraries are in yum repo.

yum install sblim-sfcb yum install sblim-sfcc yum install opensman-server yum install opensman-client

3.Run ./srvadmin-install.sh –express

INSTALL on RHEL 5

[root@lange ~]# wget -q -O – http://linux.dell.com/repo/hardware/latest/bootstrap.cgi | bash
Downloading GPG key: http://linux.dell.com/repo/hardware/latest/RPM-GPG-KEY-dell
Importing key into RPM.
Downloading GPG key: http://linux.dell.com/repo/hardware/latest/RPM-GPG-KEY-libs mbios
Importing key into RPM.
Write repository configuration
Downloading repository RPM
Installing repository rpm: http://linux.dell.com/repo/hardware/latest/platform_i ndependent/rh50_64/prereq/dell-omsa-repository-2-5.noarch.rpm
Installing yum plugins for system id
Loaded plugins: rhnplugin, security
dell-omsa-indep | 1.9 kB 00:00
dell-omsa-indep/primary | 97 kB 00:00
dell-omsa-indep 723/723
dell-omsa-specific | 1.9 kB 00:00
dell-omsa-specific/primary | 97 kB 00:00
dell-omsa-specific 723/723
Setting up Install Process
Resolving Dependencies
–> Running transaction check
—> Package yum-dellsysid.x86_64 0:2.2.26-6.2.el5 set to be updated
–> Processing Dependency: smbios-utils-python >= 2.2.0 for package: yum-dellsysid
–> Running transaction check
—> Package smbios-utils-python.x86_64 0:2.2.26-6.2.el5 set to be updated
–> Processing Dependency: python-smbios = 2.2.26-6.2.el5 for package: smbios-utils-python
–> Running transaction check
—> Package python-smbios.x86_64 0:2.2.26-6.2.el5 set to be updated
–> Processing Dependency: libsmbios = 2.2.26-6.2.el5 for package: python-smbios
–> Processing Dependency: python-ctypes for package: python-smbios
–> Running transaction check
—> Package libsmbios.x86_64 0:2.2.26-6.2.el5 set to be updated
—> Package python-ctypes.x86_64 0:1.0.2-1.1.el5 set to be updated
–> Finished Dependency Resolution

Dependencies Resolved

=================================================================================================================================================================================
Package Arch Version Repository Size
=================================================================================================================================================================================
Installing:
yum-dellsysid x86_64 2.2.26-6.2.el5 dell-omsa-indep 16 k
Installing for dependencies:
python-ctypes x86_64 1.0.2-1.1.el5 dell-omsa-specific 215 k
python-smbios x86_64 2.2.26-6.2.el5 dell-omsa-specific 71 k
smbios-utils-python x86_64 2.2.26-6.2.el5 dell-omsa-specific 63 k
Updating for dependencies:
libsmbios x86_64 2.2.26-6.2.el5 dell-omsa-indep 1.5 M

Transaction Summary
=================================================================================================================================================================================
Install 4 Package(s)
Upgrade 1 Package(s)

Total download size: 1.9 M
Downloading Packages:
(1/5): yum-dellsysid-2.2.26-6.2.el5.x86_64.rpm | 16 kB 00:00
(2/5): smbios-utils-python-2.2.26-6.2.el5.x86_64.rpm | 63 kB 00:00
(3/5): python-smbios-2.2.26-6.2.el5.x86_64.rpm | 71 kB 00:00
(4/5): python-ctypes-1.0.2-1.1.el5.x86_64.rpm | 215 kB 00:00
(5/5): libsmbios-2.2.26-6.2.el5.x86_64.rpm | 1.5 MB 00:01
———————————————————————————————————————————————————————————
Total 657 kB/s | 1.9 MB 00:02
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Updating : libsmbios 1/6
Installing : python-ctypes 2/6
Installing : python-smbios 3/6
Installing : smbios-utils-python 4/6
Installing : yum-dellsysid 5/6
Cleanup : libsmbios 6/6

Installed:
yum-dellsysid.x86_64 0:2.2.26-6.2.el5

Dependency Installed:
python-ctypes.x86_64 0:1.0.2-1.1.el5 python-smbios.x86_64 0:2.2.26-6.2.el5 smbios-utils-python.x86_64 0:2.2.26-6.2.el5

Dependency Updated:
libsmbios.x86_64 0:2.2.26-6.2.el5

Complete!
Loaded plugins: dellsysid, security
Cleaning up Everything
Done!

[root@lange ~]# yum install srvadmin-all
Loaded plugins: dellsysid, rhnplugin, security
dell-omsa-indep | 1.9 kB 00:00
dell-omsa-indep/primary | 97 kB 00:00
dell-omsa-indep 723/723
dell-omsa-specific | 1.9 kB 00:00
dell-omsa-specific/primary | 2.8 kB 00:00
dell-omsa-specific 7/7
Setting up Install Process
Resolving Dependencies
–> Running transaction check
—> Package srvadmin-all.x86_64 0:6.5.0-1.1.1.el5 set to be updated
–> Processing Dependency: srvadmin-base = 6.5.0 for package: srvadmin-all
–> Processing Dependency: srvadmin-webserver = 6.5.0 for package: srvadmin-all
–> Processing Dependency: srvadmin-rac4 = 6.5.0 for package: srvadmin-all
–> Processing Dependency: srvadmin-rac5 = 6.5.0 for package: srvadmin-all
–> Processing Dependency: srvadmin-storageservices = 6.5.0 for package: srvadmin-all
–> Processing Dependency: srvadmin-standardAgent = 6.5.0 for package: srvadmin-all
–> Processing Dependency: srvadmin-idrac = 6.5.0 for package: srvadmin-all
–> Running transaction check
—> Package srvadmin-base.x86_64 0:6.5.0-1.1.1.el5 set to be updated
–> Processing Dependency: srvadmin-omacore = 6.5.0 for package: srvadmin-base
–> Processing Dependency: srvadmin-smcommon = 6.5.0 for package: srvadmin-base
—> Package srvadmin-idrac.x86_64 0:6.5.0-1.228.2.el5 set to be updated
–> Processing Dependency: srvadmin-racadm4 = 6.5.0 for package: srvadmin-idrac
–> Processing Dependency: srvadmin-deng for package: srvadmin-idrac
–> Processing Dependency: srvadmin-rac-components for package: srvadmin-idrac
–> Processing Dependency: srvadmin-idrac-vmcli for package: srvadmin-idrac
–> Processing Dependency: srvadmin-idracadm for package: srvadmin-idrac
–> Processing Dependency: srvadmin-omilcore for package: srvadmin-idrac
–> Processing Dependency: srvadmin-racdrsc for package: srvadmin-idrac
–> Processing Dependency: srvadmin-omilcore for package: srvadmin-idrac
–> Processing Dependency: srvadmin-idrac-ivmcli for package: srvadmin-idrac
–> Processing Dependency: srvadmin-isvc for package: srvadmin-idrac
–> Processing Dependency: srvadmin-omcommon for package: srvadmin-idrac
–> Processing Dependency: srvadmin-argtable2 for package: srvadmin-idrac
—> Package srvadmin-rac4.x86_64 0:6.5.0-1.154.2.el5 set to be updated
–> Processing Dependency: srvadmin-racsvc = 6.5.0 for package: srvadmin-rac4
–> Processing Dependency: srvadmin-rac4-populator for package: srvadmin-rac4
—> Package srvadmin-rac5.x86_64 0:6.5.0-1.149.1.el5 set to be updated
–> Processing Dependency: srvadmin-racadm5 = 6.5.0 for package: srvadmin-rac5
—> Package srvadmin-standardAgent.x86_64 0:6.5.0-1.1.1.el5 set to be updated
–> Processing Dependency: srvadmin-itunnelprovider = 6.5.0 for package: srvadmin-standardAgent
—> Package srvadmin-storageservices.x86_64 0:6.5.0-1.1.1.el5 set to be updated
–> Processing Dependency: srvadmin-storage = 6.5.0 for package: srvadmin-storageservices
–> Processing Dependency: srvadmin-sysfsutils = 6.5.0 for package: srvadmin-storageservices
–> Processing Dependency: srvadmin-storelib = 6.5.0 for package: srvadmin-storageservices
—> Package srvadmin-webserver.x86_64 0:6.5.0-1.1.1.el5 set to be updated
–> Processing Dependency: srvadmin-iws = 6.5.0 for package: srvadmin-webserver
–> Processing Dependency: srvadmin-smweb = 6.5.0 for package: srvadmin-webserver
–> Running transaction check
—> Package srvadmin-argtable2.x86_64 0:6.5.0-3.1.el5 set to be updated
—> Package srvadmin-deng.x86_64 0:6.5.0-1.31.1.el5 set to be updated
—> Package srvadmin-idrac-ivmcli.x86_64 0:6.5.0-1.239.1.el5 set to be updated
–> Processing Dependency: libdchipm.so.5()(64bit) for package: srvadmin-idrac-ivmcli
—> Package srvadmin-idrac-vmcli.x86_64 0:6.5.0-1.254.1.el5 set to be updated
—> Package srvadmin-idracadm.x86_64 0:6.5.0-1.228.2.el5 set to be updated
—> Package srvadmin-isvc.x86_64 0:6.5.0-1.52.2.el5 set to be updated
—> Package srvadmin-itunnelprovider.x86_64 0:6.5.0-1.151.1.el5 set to be updated
–> Processing Dependency: openwsman-server >= 2.2.3 for package: srvadmin-itunnelprovider
–> Processing Dependency: sblim-sfcb >= 1.3.7 for package: srvadmin-itunnelprovider
–> Processing Dependency: libcmpiCppImpl.so.0()(64bit) for package: srvadmin-itunnelprovider
—> Package srvadmin-iws.x86_64 0:6.5.0-1.143.3.el5 set to be updated
–> Processing Dependency: srvadmin-jre for package: srvadmin-iws
–> Processing Dependency: libwsman_curl_client_transport.so.1()(64bit) for package: srvadmin-iws
–> Processing Dependency: libwsman.so.1()(64bit) for package: srvadmin-iws
–> Processing Dependency: libwsman_client.so.1()(64bit) for package: srvadmin-iws
—> Package srvadmin-omacore.x86_64 0:6.5.0-1.143.3.el5 set to be updated
–> Processing Dependency: libxmlsup.so.2()(64bit) for package: srvadmin-omacore
—> Package srvadmin-omcommon.x86_64 0:6.5.0-1.142.2.el5 set to be updated
—> Package srvadmin-omilcore.x86_64 0:6.5.0-1.452.1.el5 set to be updated
—> Package srvadmin-rac-components.x86_64 0:6.5.0-1.228.2.el5 set to be updated
—> Package srvadmin-rac4-populator.x86_64 0:6.5.0-1.154.2.el5 set to be updated
—> Package srvadmin-racadm4.x86_64 0:6.5.0-1.154.2.el5 set to be updated
—> Package srvadmin-racadm5.x86_64 0:6.5.0-1.149.1.el5 set to be updated
—> Package srvadmin-racdrsc.x86_64 0:6.5.0-1.228.2.el5 set to be updated
—> Package srvadmin-racsvc.x86_64 0:6.5.0-1.154.2.el5 set to be updated
—> Package srvadmin-smcommon.x86_64 0:6.5.0-1.201.2.el5 set to be updated
—> Package srvadmin-smweb.x86_64 0:6.5.0-1.201.2.el5 set to be updated
—> Package srvadmin-storage.x86_64 0:6.5.0-1.201.2.el5 set to be updated
—> Package srvadmin-storelib.x86_64 0:6.5.0-1.326.1.el5 set to be updated
–> Processing Dependency: srvadmin-storelib-sysfs-x86_64 for package: srvadmin-storelib
–> Processing Dependency: srvadmin-storelib-sysfs for package: srvadmin-storelib
—> Package srvadmin-sysfsutils.x86_64 0:6.5.0-1.1.el5 set to be updated
–> Running transaction check
—> Package libcmpiCppImpl0.x86_64 0:2.0.0Dell-3.1.el5 set to be updated
–> Processing Dependency: libwsman.so.1 for package: openwsman-client
—> Package libwsman1.x86_64 0:2.2.3.9-1.7.2.el5 set to be updated
—> Package openwsman-server.x86_64 0:2.2.3.9-1.7.2.el5 set to be updated
—> Package sblim-sfcb.x86_64 0:1.3.7-1.6.4.el5 set to be updated
—> Package srvadmin-hapi.x86_64 0:6.5.0-1.33.2.el5 set to be updated
—> Package srvadmin-jre.x86_64 0:6.5.0-1.145.1.el5 set to be updated
—> Package srvadmin-storelib-sysfs.x86_64 0:6.5.0-1.1.1.el5 set to be updated
—> Package srvadmin-xmlsup.x86_64 0:6.5.0-1.141.2.el5 set to be updated
–> Running transaction check
—> Package openwsman-client.x86_64 0:2.2.3.9-1.7.2.el5 set to be updated
–> Finished Dependency Resolution

Dependencies Resolved

=================================================================================================================================================================================
Package Arch Version Repository Size
=================================================================================================================================================================================
Installing:
srvadmin-all x86_64 6.5.0-1.1.1.el5 dell-omsa-indep 2.5 k
Installing for dependencies:
srvadmin-argtable2 x86_64 6.5.0-3.1.el5 dell-omsa-indep 58 k
srvadmin-base x86_64 6.5.0-1.1.1.el5 dell-omsa-indep 2.4 k
srvadmin-deng x86_64 6.5.0-1.31.1.el5 dell-omsa-indep 695 k
srvadmin-hapi x86_64 6.5.0-1.33.2.el5 dell-omsa-indep 887 k
srvadmin-idrac x86_64 6.5.0-1.228.2.el5 dell-omsa-indep 2.8 k
srvadmin-idrac-ivmcli x86_64 6.5.0-1.239.1.el5 dell-omsa-indep 202 k
srvadmin-idrac-vmcli x86_64 6.5.0-1.254.1.el5 dell-omsa-indep 106 k
srvadmin-idracadm x86_64 6.5.0-1.228.2.el5 dell-omsa-indep 1.0 M
srvadmin-isvc x86_64 6.5.0-1.52.2.el5 dell-omsa-indep 7.0 M
srvadmin-itunnelprovider x86_64 6.5.0-1.151.1.el5 dell-omsa-indep 2.0 M
srvadmin-iws x86_64 6.5.0-1.143.3.el5 dell-omsa-indep 13 M
srvadmin-jre x86_64 6.5.0-1.145.1.el5 dell-omsa-indep 35 M
srvadmin-omacore x86_64 6.5.0-1.143.3.el5 dell-omsa-indep 1.9 M
srvadmin-omcommon x86_64 6.5.0-1.142.2.el5 dell-omsa-indep 4.2 M
srvadmin-omilcore x86_64 6.5.0-1.452.1.el5 dell-omsa-indep 30 k
srvadmin-rac-components x86_64 6.5.0-1.228.2.el5 dell-omsa-indep 99 k
srvadmin-rac4 x86_64 6.5.0-1.154.2.el5 dell-omsa-indep 2.7 k
srvadmin-rac4-populator x86_64 6.5.0-1.154.2.el5 dell-omsa-indep 32 k
srvadmin-rac5 x86_64 6.5.0-1.149.1.el5 dell-omsa-indep 2.8 k
srvadmin-racadm4 x86_64 6.5.0-1.154.2.el5 dell-omsa-indep 314 k
srvadmin-racadm5 x86_64 6.5.0-1.149.1.el5 dell-omsa-indep 971 k
srvadmin-racdrsc x86_64 6.5.0-1.228.2.el5 dell-omsa-indep 34 k
srvadmin-racsvc x86_64 6.5.0-1.154.2.el5 dell-omsa-indep 39 k
srvadmin-smcommon x86_64 6.5.0-1.201.2.el5 dell-omsa-indep 726 k
srvadmin-smweb x86_64 6.5.0-1.201.2.el5 dell-omsa-indep 18 M
srvadmin-standardAgent x86_64 6.5.0-1.1.1.el5 dell-omsa-indep 2.4 k
srvadmin-storage x86_64 6.5.0-1.201.2.el5 dell-omsa-indep 2.8 M
srvadmin-storageservices x86_64 6.5.0-1.1.1.el5 dell-omsa-indep 2.5 k
srvadmin-storelib x86_64 6.5.0-1.326.1.el5 dell-omsa-indep 303 k
srvadmin-storelib-sysfs x86_64 6.5.0-1.1.1.el5 dell-omsa-indep 44 k
srvadmin-sysfsutils x86_64 6.5.0-1.1.el5 dell-omsa-indep 51 k
srvadmin-webserver x86_64 6.5.0-1.1.1.el5 dell-omsa-indep 2.4 k
srvadmin-xmlsup x86_64 6.5.0-1.141.2.el5 dell-omsa-indep 52 k
Updating for dependencies:
libcmpiCppImpl0 x86_64 2.0.0Dell-3.1.el5 dell-omsa-indep 95 k
libwsman1 x86_64 2.2.3.9-1.7.2.el5 dell-omsa-indep 324 k
openwsman-client x86_64 2.2.3.9-1.7.2.el5 dell-omsa-indep 61 k
openwsman-server x86_64 2.2.3.9-1.7.2.el5 dell-omsa-indep 174 k
sblim-sfcb x86_64 1.3.7-1.6.4.el5 dell-omsa-indep 1.4 M

Transaction Summary
=================================================================================================================================================================================
Install 34 Package(s)
Upgrade 5 Package(s)

Total download size: 91 M
Is this ok [y/N]:

[root@lange srvadmin]# bash /opt/dell/srvadmin/sbin/srvadmin-services.sh start
Starting Systems Management Device Drivers:
Starting dell_rbu: [ OK ]
Starting ipmi driver: Already started [ OK ]
Starting Systems Management Data Engine:
Starting dsm_sa_datamgrd: [ OK ]
Starting dsm_sa_eventmgrd: [ OK ]
Starting dsm_sa_snmpd: [ OK ]
Starting DSM SA Shared Services: [ OK ]

Starting DSM SA Connection Service: [ OK ]

 

root@donkey:~# grep -ir “smtp.comcast.net” /etc/
Binary file /etc/postfix/sasl_passwd.db matches
/etc/postfix/main.cf:relayhost = [smtp.comcast.net]:587
/etc/postfix/sasl_passwd:smtp.comcast.net < username >:< password >

Restart postfix.

Sent mail…

 

I have a bash script where i need to determine if the system is Dell or Non-Dell for add-on software. I looked around on ‘the google’ and found that you can determine the system manufacturer by running the below command.

[root@stone ~]# dmidecode | grep Dell
Vendor: Dell Inc.
Manufacturer: Dell Inc.
Manufacturer: Dell Inc.
Manufacturer: Dell Inc.
String 1: Dell System

[root@stone ~]# dmidecode -s system-product-name
PowerEdge 2950

[root@stone ~]# dmidecode -s bios-version
2.7.0

[root@stone ~]# dmidecode -s system-serial-number
6GV2KH1

Here are all the available options…

[root@stone ~]# dmidecode -s
dmidecode: option requires an argument — s
String keyword expected
Valid string keywords are:
bios-vendor
bios-version
bios-release-date
system-manufacturer
system-product-name
system-version
system-serial-number
system-uuid
baseboard-manufacturer
baseboard-product-name
baseboard-version
baseboard-serial-number
baseboard-asset-tag
chassis-manufacturer
chassis-type
chassis-version
chassis-serial-number
chassis-asset-tag
processor-family
processor-manufacturer
processor-version
processor-frequency

 

GROUP BY DATE

mysql> SELECT host, SUM(tx_diff) as tx_diff, adapter, ip, SUM(rx_diff) as rx_diff, date_format(date,’%b %D’) as dow FROM log where ip=’10.200.1.11′ group by date(date) order by date desc limit 10;
+—————————+————–+———+————-+————–+———-+
| host | tx_diff | adapter | ip | rx_diff | dow |
+—————————+————–+———+————-+————–+———-+
| monk.micro.washington.edu | 565109044386 | eth1 | 10.200.1.11 | 616332195564 | Sep 22nd |
| monk.micro.washington.edu | 215287966 | eth1 | 10.200.1.11 | 27642389383 | Sep 21st |
| monk.micro.washington.edu | 210201744 | eth1 | 10.200.1.11 | 303483939 | Sep 20th |
| monk.micro.washington.edu | 168338833 | eth1 | 10.200.1.11 | 239533210 | Sep 19th |
| monk.micro.washington.edu | 283795426 | eth1 | 10.200.1.11 | 226393293 | Sep 18th |
| monk.micro.washington.edu | 167879344 | eth1 | 10.200.1.11 | 221869928 | Sep 17th |
| monk.micro.washington.edu | 343850040 | eth1 | 10.200.1.11 | 276676860 | Sep 16th |
| monk.micro.washington.edu | 208617927 | eth1 | 10.200.1.11 | 173938951 | Sep 15th |
| monk.micro.washington.edu | 317222382 | eth1 | 10.200.1.11 | 162031338 | Sep 14th |
| monk.micro.washington.edu | 209365672 | eth1 | 10.200.1.11 | 228773179 | Sep 13th |
+—————————+————–+———+————-+————–+———-+
10 rows in set (1.12 sec)

GROUP BY MONTH

mysql> SELECT host, SUM(tx_diff) as tx_diff, adapter, ip, SUM(rx_diff) as rx_diff, date_format(date,’%M’) as month_year, date(date) as date FROM log where ip=’10.200.1.11′ group by date_format(date,’%Y-%c’) order by date desc limit 10;
+—————————+————–+———+————-+————–+————+————+
| host | tx_diff | adapter | ip | rx_diff | month_year | date |
+—————————+————–+———+————-+————–+————+————+
| monk.micro.washington.edu | 565582903163 | eth1 | 10.200.1.11 | 644158532495 | September | 2011-09-01 |
+—————————+————–+———+————-+————–+————+————+
1 row in set (1.15 sec)

GROUP BY WEEK

mysql> SELECT host, SUM(tx_diff) as tx_diff, adapter, ip, SUM(rx_diff) as rx_diff, date_format(date,’%W’) as dow FROM log where ip=’10.200.1.11′ group by date_format(date,’%W’) order by date desc limit 10;
+—————————+————–+———+————-+————–+———–+
| host | tx_diff | adapter | ip | rx_diff | dow |
+—————————+————–+———+————-+————–+———–+
| monk.micro.washington.edu | 1001045977 | eth1 | 10.200.1.11 | 28207975939 | Wednesday |
| monk.micro.washington.edu | 692902253 | eth1 | 10.200.1.11 | 707541136 | Tuesday |
| monk.micro.washington.edu | 521261648 | eth1 | 10.200.1.11 | 708563349 | Monday |
| monk.micro.washington.edu | 926105476 | eth1 | 10.200.1.11 | 700926063 | Sunday |
| monk.micro.washington.edu | 537660737 | eth1 | 10.200.1.11 | 677285321 | Saturday |
| monk.micro.washington.edu | 655542750 | eth1 | 10.200.1.11 | 705438965 | Friday |
| monk.micro.washington.edu | 572138807078 | eth1 | 10.200.1.11 | 623308403828 | Thursday |
+—————————+————–+———+————-+————–+———–+
7 rows in set (1.38 sec)

RECORDS FOR PAST 24 HOURS

mysql> SELECT host, SUM(tx_diff) as tx_diff, adapter, SUM(rx_diff) as rx_diff, date_format(date,’%b %D %h %p’) as dow FROM log where ip=’10.200.1.11′ and date between date_sub(now(),interval 24 hour) and now() group by date_format(date,’%H’) order by date desc; +—————————+————–+———+————–+—————-+
| host | tx_diff | adapter | rx_diff | dow |
+—————————+————–+———+————–+—————-+
| monk.micro.washington.edu | 130414938191 | eth1 | 129831708238 | Sep 22nd 03 PM |
| monk.micro.washington.edu | 130057896533 | eth1 | 129215613916 | Sep 22nd 02 PM |
| monk.micro.washington.edu | 129629346428 | eth1 | 128502661829 | Sep 22nd 01 PM |
| monk.micro.washington.edu | 129221533429 | eth1 | 127824340545 | Sep 22nd 12 PM |
| monk.micro.washington.edu | 10885315048 | eth1 | 16021185857 | Sep 22nd 11 AM |
| monk.micro.washington.edu | 7358250 | eth1 | 5630652540 | Sep 22nd 10 AM |
| monk.micro.washington.edu | 7218214 | eth1 | 5387548561 | Sep 22nd 09 AM |
| monk.micro.washington.edu | 5275165 | eth1 | 5158565423 | Sep 22nd 08 AM |
| monk.micro.washington.edu | 5325261 | eth1 | 4938127636 | Sep 22nd 07 AM |
| monk.micro.washington.edu | 5290874 | eth1 | 4730943343 | Sep 22nd 06 AM |
| monk.micro.washington.edu | 5285302 | eth1 | 4527051636 | Sep 22nd 05 AM |
| monk.micro.washington.edu | 6807211 | eth1 | 4326804360 | Sep 22nd 04 AM |
| monk.micro.washington.edu | 5281350 | eth1 | 4197910141 | Sep 22nd 03 AM |
| monk.micro.washington.edu | 5290722 | eth1 | 3983501232 | Sep 22nd 02 AM |
| monk.micro.washington.edu | 5285438 | eth1 | 3771119213 | Sep 22nd 01 AM |
| monk.micro.washington.edu | 5284276 | eth1 | 3562302274 | Sep 22nd 12 AM |
| monk.micro.washington.edu | 11227607 | eth1 | 3392253923 | Sep 21st 11 PM |
| monk.micro.washington.edu | 2600173 | eth1 | 3429676699 | Sep 21st 10 PM |
| monk.micro.washington.edu | 2556612 | eth1 | 3196016672 | Sep 21st 09 PM |
| monk.micro.washington.edu | 2559485 | eth1 | 2967940563 | Sep 21st 08 PM |
| monk.micro.washington.edu | 2674418 | eth1 | 2630574039 | Sep 21st 07 PM |
| monk.micro.washington.edu | 2556207 | eth1 | 2238077434 | Sep 21st 06 PM |
| monk.micro.washington.edu | 2552245 | eth1 | 2002786733 | Sep 21st 05 PM |
| monk.micro.washington.edu | 45729464710 | eth1 | 46747892032 | Sep 21st 04 PM |
+—————————+————–+———+————–+—————-+
24 rows in set (0.02 sec)

 

root@donkey:~# apt-get install cpufrequtils

root@donkey:~# cpufreq-info
cpufrequtils 006: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
driver: powernow-k8
CPUs which run at the same hardware frequency: 0
CPUs which need to have their frequency coordinated by software: 0
maximum transition latency: 8.0 us.
hardware limits: 800 MHz – 2.70 GHz
available frequency steps: 2.70 GHz, 1.90 GHz, 1.50 GHz, 800 MHz
available cpufreq governors: conservative, ondemand, userspace, powersave, performance
current policy: frequency should be within 800 MHz and 2.70 GHz.
The governor “ondemand” may decide which speed to use
within this range.
current CPU frequency is 800 MHz (asserted by call to hardware).
cpufreq stats: 2.70 GHz:0.09%, 1.90 GHz:0.00%, 1.50 GHz:0.00%, 800 MHz:99.91% (19590)

root@donkey:~# cpufreq-set -g powersave
root@donkey:~# cpufreq-info
cpufrequtils 006: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
driver: powernow-k8
CPUs which run at the same hardware frequency: 0
CPUs which need to have their frequency coordinated by software: 0
maximum transition latency: 8.0 us.
hardware limits: 800 MHz – 2.70 GHz
available frequency steps: 2.70 GHz, 1.90 GHz, 1.50 GHz, 800 MHz
available cpufreq governors: conservative, ondemand, userspace, powersave, performance
current policy: frequency should be within 800 MHz and 2.70 GHz.
The governor “powersave” may decide which speed to use
within this range.
current CPU frequency is 800 MHz (asserted by call to hardware).
cpufreq stats: 2.70 GHz:0.09%, 1.90 GHz:0.00%, 1.50 GHz:0.00%, 800 MHz:99.91% (19592)

for dual cpu, set per processor.

root@backupsrv:~# cpufreq-set -g powersave -c 0
root@backupsrv:~# cpufreq-set -g powersave -c 1

cpufrequtils 006: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
driver: powernow-k8
CPUs which run at the same hardware frequency: 0
CPUs which need to have their frequency coordinated by software: 0
maximum transition latency: 8.0 us.
hardware limits: 800 MHz – 2.90 GHz
available frequency steps: 2.90 GHz, 2.20 GHz, 1.70 GHz, 800 MHz
available cpufreq governors: conservative, ondemand, userspace, powersave, performance
current policy: frequency should be within 800 MHz and 2.90 GHz.
The governor “powersave” may decide which speed to use
within this range.
current CPU frequency is 800 MHz (asserted by call to hardware).
cpufreq stats: 2.90 GHz:0.10%, 2.20 GHz:0.00%, 1.70 GHz:0.11%, 800 MHz:99.78% (110341)
analyzing CPU 1:
driver: powernow-k8
CPUs which run at the same hardware frequency: 1
CPUs which need to have their frequency coordinated by software: 1
maximum transition latency: 8.0 us.
hardware limits: 800 MHz – 2.90 GHz
available frequency steps: 2.90 GHz, 2.20 GHz, 1.70 GHz, 800 MHz
available cpufreq governors: conservative, ondemand, userspace, powersave, performance
current policy: frequency should be within 800 MHz and 2.90 GHz.
The governor “powersave” may decide which speed to use
within this range.
current CPU frequency is 800 MHz (asserted by call to hardware).
cpufreq stats: 2.90 GHz:0.01%, 2.20 GHz:0.00%, 1.70 GHz:0.00%, 800 MHz:99.98% (6750)

root@backupsrv:~# apt-get install powertop

Disable Windows Manager

apt-get install rcconf
-disable unneeded services

*disabling x11 saves me 100 watts!

 

REDIRECT STDOUT TO NEW FILE

python /etc/cron.d/check_perms.py 1> logfile #create new file or overwrite existing
python /etc/cron.d/check_perms.py 1>> logfile #append to existing

REDIRECT STDOUT TO NEW FILE

python /etc/cron.d/check_perms.py 2> logfile #create new file or overwrite existing
python /etc/cron.d/check_perms.py 2>> logfile #append to existing

CRONTAB REDIRECTION

* * * * * root python somefile.py 1> /dev/null, discards stdout, email stderr if set.
* * * * * root python somefile.py 2> /dev/null, discards stderr, email stdout if set.
* * * * * root python somefile.py 2>&1 , emails both stderr and stdout and combines into one stream.
* * * * * root python somefile.py > /dev/null #sends all output to trash

EMAIL SCRIPT OUPUT FROM CMD LINE

All output…

python ./check_perms.py 2>&1 | mail -s ‘files perms’ jjest@uw.edu

To get output from stderr or stdout you must redirect to file first then to mail address…
*This is the onloy way i can get thish to work!!!

SENDS STDOUT TO EMAIL

$ python stderr.py 2>&1 /var/log/test 2> /dev/null | mail -s ‘yo’ jjest@uw.edu

SENDS STDERR TO EMAIL

$ python stderr.py 2>&1 /var/log/test 1> /dev/null | mail -s ‘yo’ jjest@uw.edu

 
SMTP dialog:

This is a sample of the dialog an e-mail client makes when connecting to an SMTP server for sending mail:

   telnet server-name 25     - SMTP communicates on port 25. See: /etc/services
   HELO your-domain          - This identifies the source of the mail.
   HELP                      - List the SMTP commands that are supported. (Included FYI and not part of a typical dialog)
   MAIL FROM: <your-email-address>
   RCPT TO: <recipient-email-address>
   DATA                      - End of DATA section is punctuated with a single dot on it's own line.
   Subject: E-mail-Subject
   Text of e-mail goes here
   .                         - The single dot
   QUIT
 

It is a good idea in Ubuntu to mount a disk by UUID instead of the device since devices (/dev/sd*) are known to change.  Here is how…

root@drvault:~# ls -la /dev/disk/by-uuid/ | grep data
lrwxrwxrwx 1 root root  24 2011-02-22 09:46 4596e922-5863-409e-ba9a-ddefcc7bc604 -> ../../mapper/data-backup

Add line to /etc/fstab

UUID=4596e922-5863-409e-ba9a-ddefcc7bc604 /data         ext4    defaults 0 0

Test mount…

mount -av

Done!

 

 Exclude multiple files and directories at the same time

When you want to exclude multiple files and directories, you can always specify multiple rsync exclude options in the command line as shown below.

$ rsync -avz --exclude file1.txt --exclude dir3/file4.txt source/ destination/

Wait. What if I had tons of files that I want to exclude from rsync?

I can’t keep adding them in the command line using multiple –exclude, which is hard to read, and hard to re-use the rsync command for later.

So, the better way is to use rsync –exclude-from option as shown below, where you can list all the files (and directories) you want to exclude in a file.

First, create a text file with a list of all the files and directories you don’t want to backup. This is the list of files and directories you want to exclude from the rsync.

$ vim exclude-list.txt
file1.txt
dir3/file4.txt

Next, execute the rsync using –exclude-from option with the exclude-list.txt as shown below.

$ rm -rf destination

$ rsync -avz --exclude-from 'exclude-list.txt' source/ destination/
building file list ... done
created directory destination
./
file2.txt
dir1/
dir1/dir2/
dir1/dir2/file3.txt
dir3/

Verify the desitination directory to make sure the files and directories listed in the exclude-list.txt file is not backed-up.

$ find destination
destination
destination/file2.txt
destination/dir1
destination/dir1/dir2
destination/dir1/dir2/file3.txt
destination/dir3
Ref: http://www.thegeekstuff.com/2011/01/rsync-exclude-files-and-folders/?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+TheGeekStuff+%28The+Geek+Stuff%29
 

You should have atleast half the amount of space for your swap file as you do for physical memory.

root@drvault:/data# sudo dd if=/dev/zero of=/1gb.swap bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 9.46563 s, 113 MB/s

root@drvault:/data# mkswap /1gb.swap
mkswap: /1gb.swap: warning: don’t erase bootbits sectors
        on whole disk. Use -f to force.
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=387ac3e8-64c7-4010-9f20-4e38b443762d

sudo swapon /1gb.swap

/1gb.swap  none  swap  sw  0 0

reboot
root@drvault:~# cat /proc/meminfo | grep Swap*
SwapCached:            0 kB
SwapTotal:       1048568 kB
SwapFree:        1048568 kB

 Add to top of /etc/rc.local script.

#swap file
mkswap /1gb.swap
swapon /1gb.swap

Now verify your memory. Reboot and test.

root@drvault:~# free
             total       used       free     shared    buffers     cached
Mem:       6194152     146112    6048040          0      15596      46528
-/+ buffers/cache:      83988    6110164
Swap:      5242872          0    5242872

You can also add to /etc/fstab

/1gb.swap       none    swap sw 0 0

 

#!/bin/bash

PREV_TOTAL=0
PREV_IDLE=0

###
#added by jj
###

#If less then cpu threshold than will
#perform backup, else loop until true.
CPU_THRESHOLD=5

#current date
DATE=$(/bin/date +%d-%m-%y)

####

while true; do
  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}                        # Get the idle CPU time.

  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  #echo -en "\rCPU: $DIFF_USAGE%  \b\b"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

  # Wait before checking again.
  sleep 1

  #added by jj
  if [ "$DIFF_USAGE" -lt "$CPU_THRESHOLD" ]
        then
                echo "CPU usage below $CPU_THRESHOLD%. Backing up now.."
                sleep 2

                #Perform backup.
                tar -czvf /vol03/backups/stone-archive-$DATE.tar.gz /vol03 /homes /etc

                #quit script.
                echo "Backup is complete."

                #delete old archives if approximately a month old
                REMOVE=$(find /vol03/backups/ -name *.tar.gz -atime +28 -exec rm {} \;)

                exit
  fi
done
 

Once you have nagios configured you can setup a failover setup where if the nagios master is offline then a standby slave will enable notifications and checking. Here are the setup notes and as custome script i wrote in pythong to achieve this.

the following command checks if nagios is running locally

[root@scrappy nagios]# /usr/local/nagios/libexec/check_nagios -F /usr/local/nagios/var/status.dat -e 1 -C ‘/usr/local/nagios/bin/nagios -d /usr/local/nagios/etc/nagios.cfg’

NAGIOS OK: 1 process, status log updated 5 seconds ago

now, set in nrpe config as following on remote slave/master to verify is running. must restart nrpe on machine installed on to reread nrpe.cfg

command[check_nagios_failover]=/usr/local/nagios/libexec/check_nagios -F /usr/local/nagios/var/status.dat -e 1 -C ‘/usr/local/nagios/bin/nagios -d /usr/local/nagios/etc/nagios.cfg’

test nrpe remote command.

[root@scrappy nagios]# /usr/local/nagios/libexec/check_nrpe -H james -c check_nagios_failover

NAGIOS OK: 15 processes, status log updated 0 seconds ago

modify nagios.cfg on nagios slave. restart nagios.

execute_service_checks=0

enable_notifications=0

check_external_commands=1

now set crontab on slave to check for master failure.

[root@scrappy etc]# crontab -l

* * * * * nagios /usr/local/nagios/set_slave_status.py > /dev/null

Create script and modify master ip.

#!/usr/bin/python

import os

import commands

import sys

master='james'

slave='scrappy'

tmp_file='/tmp/nagios-failover-state.txt'

commandfile='/usr/local/nagios/var/rw/nagios.cmd'

now=commands.getoutput('date +%s')

email='email@domain.com'

out=commands.getoutput('/usr/local/nagios/libexec/check_nrpe -H '+master+' -c check_nagios_failover')

#if not 0, then master is down.

master_return_val=out.find('OK')

#store state information

def failover_save_state(x):

fh=open(tmp_file,'w')

fh.write(x)

fh.close()

def sync_nagios_files():

os.system('rsync -av '+master+':/usr/local/nagios/etc/objects/* /usr/local/nagios/etc/objects/')

os.system('/etc/init.d/nagios reload')

print "Master conf files synced with Slave."

#read current state information

fh=open(tmp_file,'r')

current_state=fh.readlines()

fh.close()

current_state=current_state[0]

#enable or disable checks for hosts

#print current_state

if master_return_val <= 0 and current_state is not 'enabled':

if current_state=='enabled':

print "Nagios slave ("+slave+") is active. Nagios master ("+master+") is down. No state change"

else:

os.system('/usr/bin/printf "[%lu] ENABLE_NOTIFICATIONS\n" '+now+' > '+commandfile)

os.system('/usr/bin/printf "[%lu] START_EXECUTING_HOST_CHECKS\n" '+now+' > '+commandfile)

os.system('/usr/bin/printf "[%lu] START_EXECUTING_SVC_CHECKS\n" '+now+' > '+commandfile)

os.system('echo elvis has left the building | mail -s "[Nagios] Master Down! Slave Enabled." '+email)

print "Nagios Failover enabled"

failover_save_state('enabled')

sync_nagios_files()

elif current_state is not 'disabled':

if current_state=='disabled':

print "Nagios master ("+master+") is enabled. No state change."

else:

os.system('/usr/bin/printf "[%lu] DISABLE_NOTIFICATIONS\n" '+now+' > '+commandfile)

os.system('/usr/bin/printf "[%lu] STOP_EXECUTING_HOST_CHECKS\n" '+now+' > '+commandfile)

os.system('/usr/bin/printf "[%lu] STOP_EXECUTING_SVC_CHECKS\n" '+now+' > '+commandfile)

os.system('echo We are all out of donuts. | mail -s "[Nagios] Master Restored. Slave Disabled." '+email)

print "Nagios master restored"

failover_save_state('disabled')

sync_nagios_files()
make executable

 

[root@scrappy nagios]# chown nagios.nagios /usr/local/nagios/etc/set_slave_status.py

[root@scrappy etc]# chmod o=rwx set_slave_status.py

 

What is faster cp or rsync? Each test is done twice to verify consistency. Let’s find out…

Rsync over NFS

#donkey:~# time rsync -av /mnt/backupserv/10gb /data/10gb
sending incremental file list
10gb

sent 10738729030 bytes  received 31 bytes  41223528.07 bytes/sec
total size is 10737418240  speedup is 1.00

real    4m19.773s
user    1m31.566s
sys     2m23.025s
#donkey:~# time rsync /mnt/backupserv/10gb /data/10gb

real    4m15.026s
user    1m26.453s
sys     2m24.837s

RSYNC direct

#donkey:~# time rsync -av backupserv:/mnt/data/10gb /data/
receiving incremental file list
10gb

sent 30 bytes  received 10738729035 bytes  33401956.66 bytes/sec
total size is 10737418240  speedup is 1.00

real    5m21.004s
user    3m6.644s
sys     2m1.376s

#donkey:~# time rsync -av backupserv:/mnt/data/10gb /data/
receiving incremental file list
10gb

sent 30 bytes  received 10738729035 bytes  32790012.41 bytes/sec
total size is 10737418240  speedup is 1.00

real    5m26.857s
user    3m5.924s
sys     2m8.372s

CP over NFS

#donkey:~# time cp /mnt/backupserv/10gb /data/

real    2m17.176s
user    0m0.024s
sys     0m57.276s

#donkey:~# time cp /mnt/backupserv/10gb /data/

real    2m16.983s
user    0m0.020s
sys     0m57.920s

 

Need to move sample-query.sql into /etc/bacula.

*query
Automatically selected Catalog: MyCatalog
Using Catalog “MyCatalog”
Available queries:
1: List up to 20 places where a File is saved regardless of the directory
2: List where the most recent copies of a file are saved
3: List last 20 Full Backups for a Client
4: List all backups for a Client after a specified time
5: List all backups for a Client
6: List Volume Attributes for a selected Volume
7: List Volumes used by selected JobId
8: List Volumes to Restore All Files
9: List Pool Attributes for a selected Pool
10: List total files/bytes by Job
11: List total files/bytes by Volume
12: List Files for a selected JobId
13: List Jobs stored on a selected MediaId
14: List Jobs stored for a given Volume name
15: List Volumes Bacula thinks are in changer
16: List Volumes likely to need replacement from age or errors
17: List Volumes Bacula thinks are eligible for the changer
18: List Volumes by Volume:
19: List Volumes by Jobs:
20: List Volumes for a jobname:

 

Update file that already exists in tar archive
[root@james ~]# tar -uvf ./test.tar updatefile
Append file that doesnt not exist to archive.
[root@james ~]# tar -rvf ./test.tar newfilesfile
Extract one file from archive.
[root@james ~]# tar -xvf ./test.tar somefile

 

 

Search for a package

apt-cache search <phrase>

Install a package

apt-get install <package>

Upgrade kernel

apt-get dist-upgrade

 

Create a new file using touch and modify its access time.

Set the date to Feb 1st, 2009 @ 730am.

[root@stone backups]# touch testfile2 -t 200902010730 testfile2

Verify settings..
[root@stone backups]# ls -la | grep testfile2
-rw-r–r–  1 root katze          0 Feb  1  2009 testfile2
 

Add rule

root@firefly:/data/music# ufw allow from 10.200.80.132 to any port 3689

Delete rule by line number.

root@firefly:/data/music# ufw delete 1
Deleting:
allow 3689
Proceed with operation (y|n)? y
Rule deleted


View current rules

root@firefly:/data/music# ufw status
Status: active

To                         Action      From
–                         ——      —-
22                         ALLOW       Anywhere
21                         ALLOW       Anywhere
3689                       ALLOW       10.200.80.132

 

#!/usr/bin/python

def main():
salary1 = input("Enter Salary #1: ")
salary2 = input("Enter Salary #2: ")

# SET GLOBAL TO SHARE VARS
global x
global y

if(salary1 < salary2):
x=salary1
y=salary2
else:
y=salary1
x=salary2

def make_percent():
global total

total = 100-(float(x)/float(y)*100)
total=int(round(total,0))
print "Total Difference:",total,"%"

main()
make_percent()
root@donkey:~/tech/core# python calc_number_diff.py
Enter Salary #1: 75
Enter Salary #2: 76
Total Difference: 1 %

 

Install packages

apt-get install lvm2 dmsetup mdadm reiserfsprogs xfsprogs

Create partitions

fdisk /dev/sda

-create new partition (‘n’)
-change system partition type to lvm (‘t’)
-enter ’8e’ for hex partition type
-write partition table to disk (‘w’)

Create physical volume

root@backupserv:~# pvcreate /dev/sdb1 /dev/sda2 /dev/sdc1
Can’t open /dev/sdb1 exclusively.  Mounted filesystem?
Wiping software RAID md superblock on /dev/sda2
Physical volume “/dev/sda2″ successfully created
Wiping software RAID md superblock on /dev/sdc1
Physical volume “/dev/sdc1″ successfully created

root@backupserv:~# pvdisplay
“/dev/sda2″ is a new physical volume of “903.57 GB”
— NEW Physical volume —
PV Name               /dev/sda2
VG Name
PV Size               903.57 GB
Allocatable           NO
PE Size (KByte)       0
Total PE              0
Free PE               0
Allocated PE          0
PV UUID               zsP1EO-SlwB-nryo-gEP7-fInc-hJc4-ytVpLX

“/dev/sdc1″ is a new physical volume of “931.51 GB”
— NEW Physical volume —
PV Name               /dev/sdc1
VG Name
PV Size               931.51 GB
Allocatable           NO
PE Size (KByte)       0
Total PE              0
Free PE               0
Allocated PE          0
PV UUID               V3RZ2b-FBsM-HoI6-aQED-ouu9-LpR1-m02VLO

Create a Volume Group
root@backupserv:~# vgcreate data /dev/sdc1 /dev/sda2
Volume group “data” successfully created

root@backupserv:~# vgdisplay
— Volume group —
VG Name               data
System ID
Format                lvm2
Metadata Areas        2
Metadata Sequence No  1
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                0
Open LV               0
Max PV                0
Cur PV                2
Act PV                2
VG Size               1.79 TB
PE Size               4.00 MB
Total PE              469780
Alloc PE / Size       0 / 0
Free  PE / Size       469780 / 1.79 TB
VG UUID               XJVXrA-m5xO-GARp-6WT0-JFlX-7ARj-jxJChV

root@backupserv:~# vgscan
Reading all physical volumes.  This may take a while…
Found volume group “data” using metadata type lvm2fdisk /dev/sda

Create Logical Volume

root@backupserv:~# lvcreate –name share1 –size 100G data
Logical volume “share1″ created
root@backupserv:~# lvcreate –name share2 –size 500G data
Logical volume “share2″ created

*run lvscan for new logical volume scan.

Format partition

root@backupserv:~# mkfs.ext3 /dev/data/share1
mke2fs 1.41.9 (22-Aug-2009)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
6553600 inodes, 26214400 blocks
1310720 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=0
800 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000, 7962624, 11239424, 20480000, 23887872

Writing inode tables: 192/800

Mount device

root@backupserv:~# mkdir /mnt/share2
root@backupserv:~# mount /dev/data/share2 /mnt/share2
/dev/mapper/data-share2
516061624    202652 489644572   1% /mnt/share2

Deleting an Volume Group

root@backupserv:~# vgremove data
Do you really want to remove volume group “data” containing 2 logical volumes? [y/n]: yes
Can’t remove open logical volume “share1″
root@backupserv:~# umount /mnt/share*
root@backupserv:~# vgremove data
Do you really want to remove volume group “data” containing 2 logical volumes? [y/n]: yes
Do you really want to remove active logical volume “share1″? [y/n]: yes
Logical volume “share1″ successfully removed
Do you really want to remove active logical volume “share2″? [y/n]: yes
Logical volume “share2″ successfully removed
Volume group “data” successfully removed

Delete Physical Volume

root@backupserv:~# pvremove /dev/sdc1 /dev/sdb1
Labels on physical volume “/dev/sdc1″ successfully wiped
Physical Volume /dev/sdb1 not found

ref: http://www.howtoforge.com/linux_lvm_p2

Adding Additional Disk to LVM

create fdisk LVM partition first….

root@backupserv:~# pvcreate /dev/sdb1
Physical volume “/dev/sdb1″ successfully created

root@backupserv:~# vgextend vol1 /dev/sdb1
Volume group “vol1″ successfully extended
root@backupserv:~# vgdisplay vol1
— Volume group —
VG Name               vol1
System ID
Format                lvm2
Metadata Areas        3
Metadata Sequence No  5
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                1
Open LV               1
Max PV                0
Cur PV                3
Act PV                3
VG Size               2.70 TB
PE Size               4.00 MB
Total PE              708246
Alloc PE / Size       469238 / 1.79 TB
Free  PE / Size       239008 / 933.62 GB
VG UUID               RS2K3i-SOJ8-a230-fcQL-8PX0-Bpuj-qSUYKz

root@backupserv:~# lvextend -L +930G /dev/vol1/data1 /dev/sdb1
Extending logical volume data1 to 2.70 TB
Logical volume data1 successfully resized

root@backupserv:~# resize2fs /dev/vol1/data1
resize2fs 1.41.9 (22-Aug-2009)
Filesystem at /dev/vol1/data1 is mounted on /mnt/data; on-line resizing required
old desc_blocks = 115, new_desc_blocks = 173
….

*watch more space become available with ‘watch df -h’

 

‘-exec’ using trailing ‘\’

[root@monk ~]# tar -cvf test.tar install.log
install.log
[root@monk ~]# time find /tmp/conf-2-xp -name *.xad -exec tar –append –file=/root/test.tar {} +;
find: /tmp/conf-2-xp/9a2f6257887d6e51f58ce2/amd64: Permission denied
find: /tmp/conf-2-xp/9a2f6257887d6e51f58ce2/i386: Permission denied
find: /tmp/conf-2-xp/System Volume Information: Permission denied
tar: Removing leading `/’ from member names

real    0m15.239s
user    0m0.464s
sys     0m2.628s
[root@monk ~]# du -h test.tar
310M    test.tar
[root@monk ~]# rm -f test.tar

*delete fiel and recreate since we are appending and comparing file size after each run.

‘-exec’ using trailing ‘+’

[root@monk ~]# tar -cvf test.tar install.log
install.log
[root@monk ~]# time find /tmp/conf-2-xp -name *.xad -exec tar –append –file=/root/test.tar {} \;
find: /tmp/conf-2-xp/9a2f6257887d6e51f58ce2/amd64: Permission denied
find: /tmp/conf-2-xp/9a2f6257887d6e51f58ce2/i386: Permission denied

real    0m39.015s
user    0m2.739s
sys     0m21.893s
[root@monk ~]# du -h test.tar
310M    test.tar

Using xargs.

*use -print0 option to prevent whitespace issue. ‘xargs -0′ passes first argument.

[root@monk ~]# rm test.tar
rm: remove regular file `test.tar’? yes
[root@monk ~]# tar -cvf test.tar install.log
install.log
[root@monk ~]# time find /tmp/conf-2-xp -name ‘*.xad’ -print0 | xargs -0 tar –append –file=/root/test.tar;
find: /tmp/conf-2-xp/9a2f6257887d6e51f58ce2/amd64: Permission denied
find: /tmp/conf-2-xp/9a2f6257887d6e51f58ce2/i386: Permission denied
find: /tmp/conf-2-xp/System Volume Information: Permission denied
tar: Removing leading `/’ from member names

real    0m15.073s
user    0m0.446s
sys     0m2.774s
[root@monk ~]# du -h test.tar
310M    test.tar

Result: Using ‘+’ is two times faster than using ‘\’. -exec and xargs are about the same speed, when using ‘+’ for -exec.

 

Enabling Caching

*verify caching is on. if need to update, then restart.

jesterj@jesterj-laptop:/etc/mysql$ grep "query" /etc/mysql/my.cnf
query_cache-type = 1 #cache everything
query_cache_limit = 1M
query_cache_size = 16M

*Note that variables in the my.cnf file are reflecteed in the below variables.

mysql> SHOW VARIABLES LIKE '%query_cache%';
+------------------------------+----------+
| Variable_name | Value |
+------------------------------+----------+
| have_query_cache | YES |
| query_cache_limit | 1048576 |
| query_cache_min_res_unit | 4096 |
| query_cache_size | 16777216 |
| query_cache_type | ON |
| query_cache_wlock_invalidate | OFF |
+------------------------------+----------+
6 rows in set (0.00 sec)

View the query cache

mysql> SHOW STATUS LIKE '%qcache%';
+-------------------------+----------+
| Variable_name | Value |
+-------------------------+----------+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 16612448 |
| Qcache_hits | 1 |
| Qcache_inserts | 2 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 110 |
| Qcache_queries_in_cache | 2 |
| Qcache_total_blocks | 6 |
+-------------------------+----------+
8 rows in set (0.00 sec)

Now run test queries for a database so we can test query cache..

mysql> select * from test.data order by name ASC
mysql> select * from test.data order by name DESC

Notice as you run more and more queries the available free memory descreases and the queries in cache number increases

mysql> SHOW STATUS LIKE '%qcache%';
+-------------------------+----------+
| Variable_name | Value |
+-------------------------+----------+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 16534728 |
| Qcache_hits | 5 |
| Qcache_inserts | 3 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 110 |
| Qcache_queries_in_cache | 3 |
| Qcache_total_blocks | 8 |
+-------------------------+----------+
8 rows in set (0.00 sec)

Demand Query Caching

You can also specify query cache on demand so only queries that you specify
are cached.

Change query cache type to 2.

[mysql]
....
query-cache-type = 2
....

Restart mysql.

sudo /etc/init.d/mysql restart

Now log back into mysql and verify that DEMAND caching is set

mysql> SHOW VARIABLES LIKE '%query_cache%';
+------------------------------+----------+
| Variable_name | Value |
+------------------------------+----------+
| have_query_cache | YES |
| query_cache_limit | 1048576 |
| query_cache_min_res_unit | 4096 |
| query_cache_size | 16777216 |
| query_cache_type | DEMAND |
| query_cache_wlock_invalidate | OFF |
+------------------------------+----------+
6 rows in set (0.00 sec)

Now specify SQL_CACHE when you run a statemnt.

mysql> select SQL_CACHE * from test.data order by name ASC

Note that you can also use SQL_NO_CACHE when query-cache-type=1 to turn off caching for a particular sql stmt.

 

Create the procedure.

mysql> CREATE PROCEDURE donkey() SELECT * FROM data WHERE name LIKE '%64%';
Query OK, 0 rows affected (0.00 sec)

Execute the procedure.


mysql> CALL donkey();
+-----+------------+
| id | name |
+-----+------------+
| 31 | 1265397164 |
| 99 | 1265402640 |
| 100 | 1265402641 |
| 101 | 1265402642 |
| 102 | 1265402643 |
| 103 | 1265402644 |
| 104 | 1265402645 |
| 105 | 1265402646 |
| 106 | 1265402647 |
| 107 | 1265402648 |
| 108 | 1265402649 |
| 122 | 1265402664 |
| 219 | 1265402764 |
| 316 | 1265402864 |
| 479 | 1265404564 |
| 553 | 1265404640 |
| 554 | 1265404641 |
| 555 | 1265404642 |
| 556 | 1265404643 |
+-----+------------+
19 rows in set (0.00 sec)

Display the query.

mysql> SHOW CREATE PROCEDURE donkey2\G;
*************************** 1. row ***************************
Procedure: donkey2
sql_mode:
Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `donkey2`()
SELECT * FROM data WHERE name LIKE '%3%'
character_set_client: latin1
collation_connection: latin1_swedish_ci
Database Collation: latin1_swedish_ci
1 row in set (0.00 sec)
ERROR:
No query specified

Delete the procedure.

mysql> DROP PROCEDURE donkey;
Query OK, 0 rows affected (0.00 sec)

 

The following is an overview of how to edit standard files, the directory structure and how to enable site features in apache2. Let’s first dig into the folders that comprise apache2.

Files

$tree -d /etc/apache2 #only show dirs
/etc/apache2/
|– conf.d
|– mods-available
|– mods-enabled
|– sites-available
`– sites-enabled

Let’s define the functions of each.

conf.d – configuration files for modules, etc.
mods-available – list of available modules for apache
mods-enabled – list of modules that are loaded into apache config
site-available – configuration files for virtual hosts
sites-enabled – ?

Files also listed in /etc/apache2…

|– apache2.conf
|– envvars
|– httpd.conf
|– magic
`– ports.conf

Enabling and Disabling Modules

First, check the available modules on your system.

/etc/apache2/mods-available/
|– actions.conf
|– actions.load
|– alias.conf
|– alias.load
|– asis.load
|– auth_basic.load
|– auth_digest.load
|– authn_alias.load
|– authn_anon.load
|– authn_dbd.load
…..

To view all mods enabled view the mods-enabled dir. Note that these are sym linked to the mods-avialable directory.

/etc/apache2/mods-enabled
|– alias.conf -> ../mods-available/alias.conf
|– alias.load -> ../mods-available/alias.load
|– auth_basic.load -> ../mods-available/auth_basic.load
|– authn_file.load -> ../mods-available/authn_file.load
|– authz_default.load -> ../mods-available/authz_default.load
|– authz_groupfile.load -> ../mods-available/authz_groupfile.load

Let’s say we want to enable ‘mod-security’. The best way to do this on ubuntu/debian is to use ‘a2enmod’ utility, which stands for apache2 enable module.

jesterj@jesterj-laptop:/etc/apache2$ sudo a2enmod ssl
Enabling module ssl.
See /usr/share/doc/apache2.2-common/README.Debian.gz on how to configure SSL and create self-signed certificates.
Run '/etc/init.d/apache2 restart' to activate new configuration!

Note: You can also just type ‘a2enmod’ to list all available modules.

Now restart apache.

jesterj@jesterj-laptop:/etc/apache2$ sudo /etc/init.d/apache2 restart
* Restarting web server apache2 ... waiting [ OK ]

Now, verify the module is available.

jesterj@jesterj-laptop:/etc/apache2$ ls -la /etc/apache2/mods-enabled/ | grep ssl
lrwxrwxrwx 1 root root 26 2010-02-08 19:20 ssl.conf -> ../mods-available/ssl.conf
lrwxrwxrwx 1 root root 26 2010-02-08 19:20 ssl.load -> ../mods-available/ssl.load

To disable a module, do the same thing but use ‘a2dismod’.

Configuring Sites

 

For some reason after setting up replication the root password on both master and slave were cleared. This has happened more than once. Note that i can access mysql via…

$mysql -u root -p
mysql>

Of course this is not desirable. Simply reset the password on the master and the table propegates to the slave and fixes the problem.

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;

 

1. Create a new copy of the /etc/mysql/my.cnf file called my2.cnf. The new file should have the following configurations.

[client]
port = 3307
socket = /var/run/mysqld2/mysqld.sock

[mysqld_safe]
socket = /var/run/mysqld2/mysqld.sock
nice = 0

[mysqld]
user = mysql
pid-file = /var/run/mysqld2/mysqld.pid
socket = /var/run/mysqld2/mysqld.sock
port = 3307
basedir = /usr
datadir = /var/lib/mysql2
tmpdir = /tmp>

2. Create copy of /var/lib/mysql to /var/lib/mysql2 (data dir)

mkdir mysql2; cp -a mysql/* mysql2

3. create /var/run/mysqld2 dir. should be owned by mysql. (where pid and sock files are)

chown mysql:mysql /var/run/mysqld2

4. Then call mysqlmanager with the defaults file. Best to just modify the /etc/init.d/mysql2 file as a shell script and call directly!

mysqlmanager --defaults-file=/etc/mysql/my2.cnf --log=/var/log/mysqlmanager.log --pid-file=/var/run/mysqld2/mysqld.pid --angel-pid-file=/var/run/mysqld2/mysqlmanager.angel.pid --run-as-service --user=mysql

*create the mysqlmanager.log file.

sudo touch /var/log/mysqlmanager.log
sudo chown mysql:mysql mysqlmanager.log

5. Login to your new instance. Must specify new port and sock file.


root@slave:# mysql -P 3307 --socket=/var/run/mysqld2/mysqld.sock -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 61
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)

6. Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

mysql>

Now connect to the new host from 'mytop' to monitor your instance.

mytop -d mysql -P 3307 -S /var/run/mysqld2/mysqld.sock -u root -pPASSHERE

Rinse and repeat for additional mysql instances!

souce: http://www.ducea.com/2009/01/19/running-multiple-instances-of-mysql-on-the-same-machine/

 

-Create a text file with a secret phrase..

jesterj@jesterj-laptop:~$ cat > secret
donkey

-Encrypt file with password:

jesterj@jesterj-laptop:~$ gpg -c secret

-Verify file is encrypted:

jesterj@jesterj-laptop:~$ more secret.gpg
���(�U    �`�#.���ؖ-�$U

-Send to a different system, and test the file.

jesterj@jesterj-laptop:~$ scp secret.gpg jesterj@remotesystem:~
secret.gpg                                    100%   52     0.1KB/s   00:00

-Decrypt the file and enter passphrase.

jesterj@donkey:~$ gpg secret.gpg
gpg: CAST5 encrypted data
Enter passphrase:

-File is decrompressed:

jesterj@donkey:~$ more secret
donkey

Done!

soure: http://www.cyberciti.biz/tips/linux-how-to-encrypt-and-decrypt-files-with-a-password.html

 

To check a files checksum simply run the following command:

jesterj@jesterj-laptop:~$ md5sum file1
f5fa31b4e964cc2a86140bc2a2e11a13  file1

This does a check of the contents of the file and compares to the 128 bit key located in the header of the file.

To check a group of files then you can do the following.

jesterj@jesterj-laptop:~$ md5sum password* > md5checksums.txt
jesterj@jesterj-laptop:~$ md5sum password*
f5fa31b4e964cc2a86140bc2a2e11a13  password
67c2a19b0fb22552a5aa7cdc6ede2634  password.gpg
f5fa31b4e964cc2a86140bc2a2e11a13  password.orig
11b4f8cd65095066a644139500309bad  passwords
3295d069764198d327edeba43f2b301c  passwords.gpg
jesterj@jesterj-laptop:~$ md5sum -c md5checksums.txt
password: OK
password.gpg: OK
password.orig: OK
passwords: OK
passwords.gpg: OK

source:

http://linux.byexamples.com/archives/198/md5-checksum-how-to/

 

jesterj@jesterj-laptop:~$ tar zcvf – donkey* | ssh jesterj@donkey.dnsdojo.com “cat > ~/testarchive3.tar”By far the easiest way to tar a file and send it to a remote location is to simply have two commands on one line. The first to create the tar file, the other to scp the command. In this example, I am not prompted for a passphrase since i have my ssh key saved on the remote server for this user.

Easy:

jesterj@jesterj-laptop:~$ tar -cvf testarchive.tar donkey*; scp testarchive.tar jesterj@remoteserver:~
donkey
donkey1.zip
donkey2.txt
donkey2.zip
donkey.tar
donkey.txt
testarchive.tar                               100%   20KB  20.0KB/s   00:00
jesterj@jesterj-laptop:~$

Pipe the file…More complicated:

jesterj@jesterj-laptop:~$ tar zcvf - donkey* | ssh jesterj@donkey.dnsdojo.com "cat > ~/testarchive3.tar"

source: http://www.cyberciti.biz/faq/howto-use-tar-command-through-network-over-ssh-session/

 

Need to install debian-helper-scripts.

root@pse07:/var/lib# service apparmor off
The program 'service' can be found in the following packages:
* debian-helper-scripts
* sysvconfig
Try: apt-get install <selected package>
bash: service: command not found
root@pse07:/var/lib# sudo apt-get install debian-helper-script
root@pse07:/var/lib# service apparmor stop
Unloading AppArmor profiles : done.

 

In ubuntu there is program called apparmor that verifies certain programs are configured appropriately, mysql included. Just recently the partition that holds all the data (/var/lib/mysql) filed up. Since I was at 100% and this is a production box I needed to fix this quickly. My options were as follows:

1. Setup a sym link from /var/lib/mysql to /home/mysql, move data here OR
2. Simply create a new dir call /home/mysql, move data here

To do this edit /etc/mysql/my.cnf
...
datadir =/home/mysql
#datadir = /var/lib/mysql
...

Save the file and restart mysql and you will get the following error:

root@slave:/etc/mysql# /etc/init.d/mysql2 start
* Starting MySQL database server mysqld [fail]

The problem here is that apparmor is dissallowing mysql from running in any other location than /var/lib/mysql. You will need to edit the apparmor file for mysql.

root@slave:/etc/apparmor.d# grep "/var/lib/mysql" usr.sbin.mysqld
/var/lib/mysql/ r,
/var/lib/mysql/** rwk,

To correct this problem replace all instances of /var/lib/mysql with /home/mysql. Open the file with file and do a search and replace. See that I am escaping the slashes!

:%s /\/var\/lib\/mysql/\/home\/mysql/

Reload appamor and mysql should start up with the new config in your my.cnf file!

root@slave:/etc/apparmor.d# /etc/init.d/apparmor restart
Reloading AppArmor profiles : done.
root@slave:/etc/apparmor.d# /etc/init.d/mysql2 start
* Starting MySQL database server mysqld

 

Who’s connected to my server?

root@donkey:~# netstat -ntla | grep "80"
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
tcp        0      0 192.168.1.5:80          206.169.197.253:20277   ESTABLISHED

Grep port for host.

root@donkey:~# lsof -i tcp:80 | grep "20277"
apache2 20114 www-data    9u  IPv4 9576072       TCP donkey.local:www->206-169-197-253.static.twtelecom.net:20277 (ESTABLISHED)

Kill Connection

kill -9 20114

 

Let’s talk about managing processes. If you want to run a script or scripts and then continue with other tasks while they run w/o using cron then you can use the ‘jobs’ command.

First, let create a script that will run indefinitely so we have time to work with our examples.

#!/usr/bin/python
x=0
while x == 1:
z=1

The above script will loop indefinitely since ‘x’ will never equal 1.

Next, run the script from the command line. Adding a & to the end of the script will send this jobs to the background.

jesterj@jesterj-laptop:~$ python loop.py &
[1] 4221

This sends loop.py to the background  with process id ’4221′. You can view the process id stats by doing the following:

jesterj@jesterj-laptop:~$ ps -ef | grep ’4221′
jesterj   4221  3083 99 16:37 pts/1    00:02:40 python loop.py

To view all jobs running in the background type ‘jobs’.

jesterj@jesterj-laptop:~$ jobs
[1]+  Running                 python loop.py &

To add another instance of the script to the background, repeat.

jesterj@jesterj-laptop:~$ python loop.py &
[2] 4333
jesterj@jesterj-laptop:~$ jobs
[1]-  Running                 python loop.py &
[2]+  Running                 python loop.py &

To quit the process use kill and the job number.

jesterj@jesterj-laptop:~$ kill %1
jesterj@jesterj-laptop:~$ jobs
[1]-  Terminated              python loop.py
[2]+  Running                 python loop.py &

To bring a process out of jobs to the foreground use, fg:

jesterj@jesterj-laptop:~$ fg %2
python loop.py

 

Basic Commands

:w  – write file

:wq – write and quit

:q! – exit, ignore changes

:set number – show line numbers

:set nonumber – turn off line numbers.


Text Mode

dd – Delete lines

2dd – delete 2 lines

p  – paste buffer lines

w – skip to mext word

a – append after cursor

i – insert at cursor

o – open new line after current line

r – replace character.

yy – yank current line

Searching

/string – search forward for string

?string – search back for string.

/tel[a-z] – search for ‘tel’ with last letter a-z

Find and Replace – ‘g’ stand for global, all lines in document.

:s/OLDWORD/NEWWORD/g

Search and replace,escaping slashes.

To replace the phrase /var/lib/mysql with /home/mysql you need to escape each ‘/’ with a ‘\’. For example…

:%s/\/var\/lib\/mysql/\/home\/mysql/

Regular Expressions

/Hello/ – search for word ‘Hello’ in line.

/^Hello$/ – search and matches if Hello is only word on line.

Recording Macros

qv – start record mode for macro ‘a’. second letter should be lower case character.

q – stop record

@v – to paste recorded text

9 @v – repeat v macro 9 times.
Save Settings

You can save persistent changes for vi by editing ~/.exrc

set number
….

 

>>>import os,tarfile

>>> tarfile=tarfile.open(‘/data/archive-1-1-1.tgz’,'r’)
>>> for x in tarfile:
…     print x

<TarInfo ‘./tmp/’ at 0xb7d9588c>
<TarInfo ‘./tmp/biteoff/’ at 0xb7d9558c>
<TarInfo ‘./tmp/biteoff/bite_offload.tgz’ at 0xb7d959cc>
<TarInfo ‘./tmp/biteoff/aesid.log’ at 0xb7d95a2c>
<TarInfo ‘./tmp/biteoff/lruid.xml’ at 0xb7d95a8c>
<TarInfo ‘./tmp/biteoff/BITEdump.sql’ at 0xb7d95aec>
<TarInfo ‘./tmp/biteoff/offload.cfg’ at 0xb7d95b4c>

ZIP

>>> import os, zipfile
>>> zipfile=zipfile.ZipFile(‘/home/jesterj/foo.zip’,'r’)
>>> for x in zipfile.namelist():
…     print x

index.php

 

If you connect to vncserver and get a blank grey screen with a consol window then this means that the ~/.vnc/xstartup script is not initializing the windows manager correctly.

For ubuntu, edit the script (comment out lines) to the following…

#!/bin/sh
# Uncomment the following two lines for normal desktop:
# unset SESSION_MANAGER
# exec /etc/X11/xinit/xinitrc
[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
#xsetroot -solid grey
#vncconfig -iconic &
#xterm -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
export XKL_XMODMAP_DISABLE=1 #require for proper keyboard mapping
gnome-session
#twm &
\
Then, run ‘vncserver’ to create a new session based on the above script!

 

The below command will show all files, recrusively for the phrases “phrase1″ and “phrase2″ in the / filesystem.

$ sudo grep -rl “phrase1\|phrase2″ /

 

Setup Squid for Linux

Internet Browser Client Setup

Firefox > preferences > settings > Manual Proxy Configuration

IP: (ip for squid server) PORT: 3128 (defautol squid port)

Squid Server Setup

apt-get install squid3
pico /etc/squid3/squid.conf

Add the following…

acl client1 src 10.10.10.2/255.255.255.0
http_access allow client1

Restart squid.

Install SARG reporting tool

sudo apt-get install sarg
edit /etc/squid/sarg.conf
modify squid log file location to:
/var/log/squid3/access.log

run ‘sarg’

look in /var/www/squid-reports for html files of acces logs!

Works!

 

If you have a script that you want to setup at varying time intervals, including but not limited to certain days of the week or specific hours in a day then those commands should go in /etc/crontab.

However, if you want to simply run your script on an hourly or daily basis you can simply put a sym link in /etc/cron.daily or hourly.

Best way to do this is put your actual script in /usr/bin and create a sym link in the appropriate cron directory.

/etc/cron.daily$ sudo ln -s /usr/bin/memcache_save_data.py ./memcache_save_data

Bingo! No more to do. /etc/crontab runs all files in this folders automatically

Note: Cron does not allow you to have file extensions on files in /etc/cron dirs. Also, if you need to pass parameters to the script then you need to run this in /etc/crontab as there is no way to specify these with the above option.

 

If you are unable to get the proper permissions/access on your system because of a shared hosting environment then you may just want to dump your local database and send it to a remote server. This is a simple way to setup a daily copy.

1. Create user called ‘remote’ on the slave (destination for backup) that you can access from the master (the data that needs to be backed up)

mysql> GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* to remote@'MASTERIPADDRESS' IDENTIFIED BY 'PASSHERE';
Query OK, 0 rows affected (0.07 sec)

mysql> flush privileges;

Note:
*REPLICATION CLIENT Gives the right to the user to ask where the slaves/masters are.
*REPLICATION SLAVE Needed for the replication slaves (to read binlogs from master).

IMPORTANT! – Make sure /etc/mysql/my.cnf bind-address is not 127.0.0.1 – if so comment. If change, you will need to restart mysql.

2. Verify you can connect from the master to the slave.

# mysql -h ipaddresstoslave -u remote -p

3. Create a script to run the commands.

#!/usr/bin/python
import os
import datetime
file='mysql-dump-all-%s.sql' % (datetime.date.today())
print "Creating backup file..."
os.system('mysqldump --all-databases -u jester_root -pREMOTEPASS > ~/'+file)
print "Dumping to titan..."
os.system('mysql -h IPTOSLAVE -u remote -pREMOTEPASS < ~/'+file)
print "Deleting local sql file..."
os.system('rm ~/'+file)

4. Add file to cron

Done!

 

What is replication and what should it is and what it isnt…

Master-Master – synchronous replication where each server updates one another.

Pros: Used for hot standby situation. Write to one master only to avoid primary key collisions.
Cons: Network intensive.

Master-Slave – Primary used to share the load. Writes go to master from client,reads go to slave.

Pros: Asyncronous updates (one way) Simple, inexpensive. Hot cache from slave.
Cons: Not good for heavy write loads.

source: http://www.mysqlperformanceblog.com/2009/11/13/finding-your-mysql-high-availability-solution-%E2%80%93-replication/

http://dev.mysql.com/doc/refman/5.1/en/replication.html

How to setup mysql replication

Create new replication user on master.

mysql> GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* to slave@'SLAVEIPADDRESS' IDENTIFIED BY 'PASSHERE';
Query OK, 0 rows affected (0.07 sec)

IMPORTANT!!! – make sure /etc/mysql/my.cnf 127.0.0.1 for bind-address is commented out or cannot connect from the slave!


#bind-address = 127.0.0.1

Now verify can connect from slave:


root@slave:/var/log# mysql -h MASTERIP -P 3306 -u slave -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 60
Server version: 5.1.37-1ubuntu5-log (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

Configure master.

edit /etc/my.cnf

Add the following.

[mysqld]
...
log-bin=mysql-bin
server-id=1 #master id
...

Make backup of Master.


root@donkey [~]# mysqldump --all-databases -u root -p > mysql-dump-master.sql
Enter password:

Write down the position of the master status for later…

mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 106 | | |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

Shudown mysql


root@donkey [~]# sudo /etc/init.d/mysql stop Shutting down MySQL.

Transfter file to Slave.

scp mysql-dump-all-10-15-09.sql root@slave:~

Import Data

root@titan:~# mysql -u root -p < ~/mysql-dump-all-10-15-09.sql
Enter password

Slave /etc/mysql/my.cnf

[mysqld]
server-id = 2
log_bin = mysql-bin.log

Now set master from slave.

mysql> CHANGE MASTER TO MASTER_HOST='205.234.235.89',MASTER_USER='replication_user', MASTER_PASSWORD='PASSHERE',MASTER_LOG_POS=106,MASTER_LOG_FILE='mysql-bin.000001';
Query OK, 0 rows affected (0.00 sec)

*log file and position should be the output from master ‘show master status’; command.
*in need to reset the above then do ‘stop slave’, ‘reset slave’ and issue the CHANGE MASTER TO cmd again.

mysql> start slave
-> ;
Query OK, 0 rows affected (0.00 sec)

Verify Master/Slave are replicating. ‘Slave IO Running’ and ‘Slave SQL Running’ should both be set to “YES”

mysql> show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 10.139.68.174
Master_User: slave
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000002
Read_Master_Log_Pos: 43981
Relay_Log_File: mysqld-relay-bin.000005
Relay_Log_Pos: 33858
Relay_Master_Log_File: mysql-bin.000002
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 43981
Relay_Log_Space: 33858
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: 0
1 row in set (0.00 sec)

Check master to see if positon of slave ans master are in sync!

Done!

 

#Grant options: ALL, SELECT, UPDATE, INSERT
mysql> GRANT SELECT ON *.* to 'someuser'@'IPCONNECTINGFROM or %' IDENTIFIED BY 'passwordhere';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

Verify setup…

mysql> select host, password, user from user;

 

Install module

sudo apt-get install libapache2-mod-python

Add python directives to /etc/apache2/sites-enabled/000-default

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonDebug On
</Directory>

Restart apache.

sudo /etc/init.d/apache2 restart

Create test page:

def index(req):
return "donkey";

Bingo!

 

Need to convert RPM to DEB

apt-get install alien.

jesterj@1029384756:~$ sudo alien -k ./Desktop/VMware-Player-2.5.3-185404.i386.rpm
Warning: Skipping conversion of scripts in package VMware-Player: postinst prerm
Warning: Use the –scripts parameter to include the scripts.
vmware-player_2.5.3-185404_i386.deb generated
jesterj@1029384756:~$ sudo dpkg -i vmware-player_2.5.3-185404_i386.deb
Selecting previously deselected package vmware-player.
(Reading database … 194000 files and directories currently installed.)
Unpacking vmware-player (from vmware-player_2.5.3-185404_i386.deb) …
Setting up vmware-player (2.5.3-185404) …
jesterj@1029384756:~$

 
< ? PHP
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename='temp.txt'");
readfile("./temp.txt");
?>
 

>>> import time
>>> timestamp=float(’1251157271.796′)
>>> print time.gmtime(timestamp)
time.struct_time(tm_year=2009, tm_mon=8, tm_mday=24, tm_hour=23, tm_min=41, tm_sec=11, tm_wday=0, tm_yday=236, tm_isdst=0)
>>> start_time=time.gmtime(timestamp)
>>> for x in start_time:
…     print x

2009
8
24
23
41
11
0
236
0

 

memcache class  not found in php page.

problem: i’ve install memcache for php, restarted apache but get the follwoing
error…
“Fatal error: Class ‘Memcache’ not found in /var/www/loadscript/index.php on line 2″

resolution: Add this line to php.ini and restart apache

extension=memcache.so

 

$ apt-get install memcached python-memcache

jesterj@jesterj-laptop:~$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>import memcache
>>>memcache = memcache.Client(['10.10.10.45:11211'])
>>>datavar="some data here"
>>>memcache.set('1234',datavar,60)
>>>memcache.get('1234')

‘some data here’

Ref: http://dev.mysql.com/doc/refman/5.1/en/ha-memcached-interfaces-python.html

Do the same above to connect from remote machine…

 

Error uninstalling/installing Ubuntu package.

If you have a problem with a certain package run this…

sudo dpkg -r <packagename>

Then reinstall with apt!

 


Tuple are immutable. Lists are mutable.

a=(1,2,3) #tuples have ()
a[0]=100

Error! Tuple values cannot be changed!

a=[1,2,3] #list have brackets
a[0]=100

success!

Note: dicts have curly braces ie: a={}

 

Unmount the array, i don’t know if this is necessary, but doing so means less stuff to go wrong.
sudo umount /dev/md0

Then you need to go and prepare the disk(s) to be added. (The prepare section of the guide)

Then tell mdadm that it can play with it:
sudo mdadm --add /dev/md0 /dev/sda2

Then tell mdadm to stop playing and use it to expand/grow your raid5 array(make sure that the number of raid devices is correct, it should be the number of disks/partitions the grown/expanded array will have):
sudo mdadm --grow /dev/md0 --raid-devices=4

View and wait for the new array to reshape:
cat /proc/mdstat

Check the filesystem (required to resize it):
sudo e2fsck -f /dev/md0

Resize the filesystem on the new array so that you can use it for something useful.
sudo resize2fs /dev/md0

Mount the expanded/grown array with it’s resized filesystem(remember to change the mount point):
sudo mount -t ext3 /dev/md0 /home/tore/raid

Go check your files:
cd /home/tore/raid
cksfv -r -q

REF: http://ubuntuforums.org/archive/index.php/t-517282.html

 

Install mdadm
apt-get install mdadm

Create the fisrt striped set:

sudo mdadm –create –force /dev/md0 –level=stripe –chunk=4096 –raid-devices=2 /dev/sdc /dev/sdd

Create the second striped set:
sudo mdadm –create –force /dev/md1 –level=stripe –chunk=4096 –raid-devices=2 /dev/sde /dev/sdf

You now have two 2tb striped arrays. We now want to take those and tell mdadm to mirror them w/ Raid 1, hence the
name Raid0+1.

Raid 1 both of your stripe sets

sudo mdadm –create –force /dev/md2 –level=mirror –chunk=4096 –raid-devices=2 /dev/md0 /dev/md1

Partition the drive w/ fdisk

fdisk /dev/md2
-Create a new partition.
-Write to disk

Next, format the new drive

mkfs.ext3 /dev/md2

Finally, mount the drive and use!

mount -t ext3 /dev/md2 /mnt/raid1

View the details of the array…

mdadm -D /dev/md2

$ cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4] [raid0] [raid1]
md2 : active raid1 md1[1] md0[0]
1953521600 blocks [2/2] [UU]
[===========>.........] resync = 59.3% (1160324480/1953521600) finish=973.8min speed=13574K/sec

md1 : active raid0 sdf[1] sde[0]
1953521664 blocks 4096k chunks

md0 : active raid0 sdd[1] sdc[0]
1953521664 blocks 4096k chunks

unused devices:

 

I wrote up this quick little banking script to illustrate how to do simple object oriented programming in php5 using classes. Functions within a class are known as methods.

-JJ

class account_transact
{
    var $balance;
    var $account_type;
    var $amount;

    function get_bal($account_type)
    {
        if($account_type=='checking')
        {
            #query for sql to look up account
            $balance=100;
        }
        elseif($account_type=='savings')
        {
            #query for sql to look up account
            $balance=25;
        }
        return $balance;
    }
    function verify_account($account_type)
    {
        if($account_type=="checking" || $account_type=="savings")
        {
            #account verified
            return $account_type;
        }
        else
        {
            echo $account_type." is not a valid account";
            exit();
        }
    }
    function deposit($account_type, $amount)
    {
        $cur_bal=$this->get_bal($account_type);
        $new_bal=$cur_bal+$amount;
        print "Balance for ".$account_type." is $".$new_bal."
"; } } //create new class instance $transaction=new account_transact(); //checking deposit $account=$transaction->verify_account("checking"); $transaction->deposit($account,"5"); //savings $account=$transaction->verify_account("savings"); $transaction->deposit($account,"-10"); ?>

More: http://www.php-editors.com/articles/simple_php_classes.php

 

Today i found a better way to kill processes in linux. Use pkill. Now instead of killing items w/ the process id, you can kill items matching a certain pattern, plus lots of extras…

For example, lets say i have a bunch of stagnate processes all spawned from the same script.

root 27623 27622 0 Jun25 ? 00:00:00 /bin/sh -c python /etc/nagios2/scripts/notify_failover.py
root 27625 27623 0 Jun25 ? 00:00:00 python /etc/nagios2/scripts/notify_failover.py
root 27920 27919 0 Jun25 ? 00:00:00 /bin/sh -c python /etc/nagios2/scripts/notify_failover.py
root 27922 27920 0 Jun25 ? 00:00:00 python /etc/nagios2/scripts/notify_failover.py
root 28206 28205 0 Jun25 ? 00:00:00 /bin/sh -c python /etc/nagios2/scripts/notify_failover.py
root 28208 28206 0 Jun25 ? 00:00:00 python /etc/nagios2/scripts/notify_failover.py
root 28730 28729 0 Jun25 ? 00:00:00 /bin/sh -c python /etc/nagios2/scripts/notify_failover.py
root 28732 28730 0 Jun25 ? 00:00:00 python /etc/nagios2/scripts/notify_failover.py
root 29061 29060 0 Jun25 ? 00:00:00 /bin/sh -c python /etc/nagios2/scripts/notify_failover.py

Now, I could kill them by doing this....

kill 27623 27625, etc, etc...

However, the more efficient way to do this would be to do the following...

pkill -f "python /etc/nagios2/scripts/notify_failover.py"

Whamo! All process gone!

 

sudo tcpdump -n -i eth0 -s 0 -w output.txt src or dst port 80

 

-Firefox > Preferences > Manual Proxy configuration > Socks Host: localhost Port: 9999, socksv5.

LINUX:

Next open linux terminal and setup up tunneling.

$ssh -CND 9999 user@remoterserver.com

WINDOWS:

Follow these screen shots…

*Leave terminal window open.

To verify web traffic is coming from the host go to www.whatismyip.com and the server ip should be listed from where data is being tunnelled through!

 
a=set(['apple','apple','orange','apple','pear','berry'])
b=set(['pear','coconut','strawberry'])
a | b

set(['strawberry', 'coconut', 'apple', 'orange', 'pear', 'berry'])

a.union(b)

set(['strawberry', 'coconut', 'apple', 'orange', 'pear', 'berry'])

 

Need to install ‘antiword’ debian package then read output from CLI.

import commands
output=commands.getoutput('antiword /home/jesterj/Desktop/test.doc')
print output

Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.

Write to word…

Pretty easy here. Just write to a file and append with .doc.

f=open("newfile.doc","wr")
f.write(output)
f.close()

Badow!

 

install ‘xlrd’ for reading…
Download: http://www.lexicon.net/sjmachin/xlrd.htm

root@donkey:~# sudo apt-cache search xlrd
python-xlrd – extract data from MS Excel spreadsheet files

import xlrd
wb=xlrd.open_workbook('/home/jesterj/Desktop/JJ-MonthlyNumbersNew-6.18.09.xls')
wb.sheet_names()

[u'Sheet1', u'Sheet2', u'Sheet3']
sh=wb.sheet_by_index(0)
for rownum in range(sh.nrows):
    print sh.row_values(rownum)

Ref: http://scienceoss.com/read-excel-files-from-python/

Install 'xlwt' for writing excel files...
Download: http://pypi.python.org/pypi/xlwt


import xlwt
from datetime import datetime

font0 = xlwt.Font()
font0.name = 'Times New Roman'
font0.colour_index = 2
font0.bold = True

style0 = xlwt.XFStyle()
style0.font = font0

style1 = xlwt.XFStyle()
style1.num_format_str = 'D-MMM-YY'

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')

ws.write(0, 0, 'Test', style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))

wb.save('example.xls')
 

Symmetrical difference calculates the difference of not whats in the just one list. It calculates the items that are not common in both lists!

list1=['donkey','balls']
list2=['donkey','scrotom']
set1=set(list1)
set2=set(list2)
print set1

set(['donkey', 'balls'])

print set2

set(['donkey', 'scrotom'])

symdiff = set1 ^ set2
symdiff

set(['balls', 'scrotom'])

 

There is no way to do a function diff on a list. However you can do a loop.

list1 = [1, 2, 3, 5, 7,  11]
list2 = [1, 2, 4, 8, 16, 32]
diff_list = []
for item in list1:
    if item not in list2:
        diff_list.append(item)

print diff_list
[3, 5, 7, 11]

Or use sets….

from sets import Set
set1=Set(['a','b','c'])
set2=Set(['d','b','c'])
diff=set1-set2
print diff
 

Set(['a'])

for x in diff:
    print x

a

Or conver list to a set…

list1=['a','b']
list2=['b','c']

set1=set(list1)
set2=set(list2)

diff=set1-set2
 
def main():
cases=['auth','transact','dns','network','ssl']
print sys.argv
try:
if sys.argv[1]=='-t':
if sys.argv[2] not in cases or len(sys.argv[2])==0:
print "*Must specify a valid case: %s " % cases
exit()
else:
case=sys.argv[2]

if case=='auth':
test_authentication()
if case=='transact':
test_transaction_problem(transact_url)
if case=='dns':
test_dns(hosts)
if case=='network':
test_network(hosts)
if case=='ssl':
test_ssl(hosts)
else:
print "You must specify a valid test %s" % cases
except:
print "You must specify option -t followed by test option %s" % cases

 

dd if=/dev/zero of=file_to-create bs=1k count=4000000

*the above will create a 4gb file called ‘file_to-create”

 

Using urllib…

#!/usr/bin/python
import urllib
c=urllib.urlopen('http://nike.com')
print c.getcode()

200

or try with httplib…

#!/usr/bin/python
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status

200

 
#!/usr/bin/python

items=['klm','klm','pia','nwa','klm','al','al','al','ri','pia','klm']

#get unique items from list
get_unique=[]
for a in items:
if a not in get_unique:
get_unique.append(a)

#dict for storage of key,occurence
dict={}

for x in items:
for y in get_unique:
if x in y:
if x in dict:
val=dict[x]
val+=1
dict[x]=val
else:
dict[x]=1

print dict

</code>

 

*NOTE: def() method/function must be defined before it is called. If the def is below where it is called will get a ‘NameError: name ‘donkey’ is not defined’

def donkey():

print “hello”

a=donkey()

 
#!/usr/bin/python
def mylist(a):
fruit=[]
fruit.append(a)
return fruit

b=mylist("donkey")
print b

 
import zipfile

a=zipfile.ZipFile('/path/to/zipfile.ZIP')
for x in a.namelist():
...     if x.endswith('.zip'):
...             info=a.getinfo(x)
...             print "%s %s" % (info.filename, info.file_size)
...

123.zip 4563
254.zip  5435
donkey.zip 8979

 

letterDict = {}
all_letters_list =
['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r'
,'s','t','u','v','w','x','y','z']
test_string = “in mississippimississippimississippimississippi pigs can
fly like the wind”

# saving the dict
for letter in test_string:
letterDict[letter] = letterDict.get(letter, 0) + 1

print letterDict

=========

print ‘-’ * 60
print ‘Examine the line below to see how it worked ‘
print ‘ 1 – inserting:  letterDict[letter] = letterDict.get(letter, 0) +
1  – self initiates with value of 0 and increments +1′
print ‘ 2 -  reading :  letterDict.get(testLetter, 0)  – when reading -
insert a default count of 0 for those letters not found.’
print ‘-’ * 60
print ‘test_string = ‘, test_string
print
print ‘letterDict = ‘, letterDict
print
print ‘Histogram (count) of letters in test string’

# reading the dict, but inserting default 0 for letters not found.
for testLetter in all_letters_list:
print ‘%s – %2s’ % (testLetter, letterDict.get(testLetter, 0))

 
import difflib
a=difflib.get_close_matches
a("Phil Collins", ["Phil Colins","PhilCollins","Phil Collins","Phil Collins - Genesis"])

['Phil Collins', 'PhilCollins', 'Phil Colins']

 

find -depth -type d -empty -exec rmdir {} \;

 

# umount /dev/sdb1
umount: /dev/sdb1: device is busy
umount: /dev/sdb1: device is busy
# fuser -m /dev/sdb1
/dev/sdb1: 3322

(3322 is id of the process that uses the device. if you like to know what it is, you may try this:

# ps aux | grep 3322)

# kill -9 3322
# umount /dev/sdb1
#

 
Type "help", "copyright", "credits" or "license" for more information.
import Cfg #class you just created
c = Cfg.Cfg()
c.test()
donkey

from Cfg import Cfg
c = Cfg()
c.test
bound method Cfg.test of <Cfg.Cfg instance at 0xb7ce35ec>>
c.test()
donkey

 

import codecs
someFile=”donkeys.txt”
fileObj = codecs.open(someFile, “r”, “utf-8″ )
u = fileObj.read()
print u

 

>>> path=’/donkey/file.cfg’
>>> var=path.split(‘/’)
>>> print var
['', 'donkey', 'file.cfg']
>>> var[-1]
‘file.cfg’

or can do

>>>varv.pop()
‘file.cfg’

#note you must assign path.split(‘/’) to a string or path.string will
just print out the last letter of the 3rd element which is ‘g’

 

Many times when you parse a file using split() or the csv module you return strings that have garbage characters in the line. Take the below string for example…

>>> badstring=’\xef\xbb\xbf#Some information’
>>> print badstring
#Some information
>>> if badstring.startswith(‘#’):
…     print “Hello”

>>>

The above doesn’t print ‘Hello’ becuase of the garbage data. So we need to create a method to remove the junk chars.

Here is what we do….

def remove_garbage():

 
items=['a','b','c']
size=len(items)

print size

# 3

 

apt-get install python-mutagen

#!/usr/bin/python
from mutagen.mp3 import MP3
import os

for root, dirs, files in os.walk('/mnt/music'):
for name in files:
joined=os.path.join(root, name)
audio=MP3(joined)
if audio.info.bitrate < 128000:
print joined
print audio.info.bitrate

		
 

$ telnet titan.zipcon.net 22
Trying 63.249.22.50…
Connected to titan.zipcon.net.
Escape character is ‘^]’.
SSH-2.0-OpenSSH_5.1p1 Debian-3ubuntu1

 

w
14:16:50 up 2 days, 23:54,  4 users,  load average: 0.24, 0.16, 0.07
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
jesterj  tty7     :0               Fri14    3days 24:30m  0.30s x-session-manag
jesterj  pts/0    :0.0             14:13    0.00s  0.10s 19.94s gnome-terminal
jesterj  pts/2    :0.0             11:52    2:23   0.20s  0.10s ssh jesterj@pse
jesterj  pts/1    :0.0             11:23    2:34   0.16s  0.06s ssh jesterj@pse

 

$ netstat -nta
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:6024            0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN
tcp        0      0 10.139.68.153:42651     10.139.68.39:22         ESTABLISHED
tcp        0      0 10.139.68.153:51346     64.4.34.126:1863        ESTABLISHED
tcp        0      0 10.139.68.153:44434     206.255.61.214:4228     ESTABLISHED
tcp        0      0 10.139.68.153:38705     205.234.235.90:80       ESTABLISHED
tcp        0      0 10.139.68.153:38707     205.234.235.90:80       ESTABLISHED
tcp        0      0 10.139.68.153:40101     64.4.37.39:1863         TIME_WAIT
tcp        0      0 10.139.68.153:38708     205.234.235.90:80       ESTABLISHED
tcp        0      0 10.139.68.153:52217     10.139.10.45:22         ESTABLISHED
tcp        0      0 10.139.68.153:38702     205.234.235.90:80       ESTABLISHED
tcp        0      0 10.139.68.153:38709     205.234.235.90:80       ESTABLISHED
tcp        0      0 10.139.68.153:38710     205.234.235.90:80       ESTABLISHED
tcp6       0      0 :::80                   :::*                    LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN

 

ubuntu@ubuntu:/mnt$ sudo mount -t ext3 /dev/md0 /mnt/md0

mount: wrong fs type, bad option, bad superblock on /dev/md0,
missing codepage or other error
(could this be the IDE device where you in fact use
ide-scsi so that sr0 or sda or so is needed?)
In some cases useful info is found in syslog – try
dmesg | tail  or so


$ sudo mdadm –assemble /dev/md0 /dev/sdd /dev/sdb /dev/sdc
mdadm: /dev/md0 has been started with 3 drives.

$sudo mount /dev/md0 /data/

OR….

Simply run this command.

mdadm --detail --scan >> /etc/mdadm/mdadm.conf

Mount again and all should work!

 
import MySQLdb
data="jeremiah's new laptop"
data=MySQLdb.escape_string(data)
cursor.execut("INSERT INTO table1 name VALUES (data);")

 
import sys, socket

hostname = socket.gethostname()
print "Host name:", hostname

 

I DID NOT WRITE THIS TUTORIAL. REFERENCE URL IS LISTED BELOW…
====

We need to install several packages to execute the examples in this tutorial.

If you don’t already have MySQL installed, we must install it.

$ sudo apt-get install mysql-server

This command installs the MySQL server and various other packages. While installing the package, we are prompted to enter a password for the MySQL root account.

$ apt-cache search MySQLdb
python-mysqldb – A Python interface to MySQL
python-mysqldb-dbg – A Python interface to MySQL (debug extension)
bibus – bibliographic database
eikazo – graphical frontend for SANE designed for mass-scanning

We don’t know the package name for the MySQLdb module. We use the apt-cache command to figure it out.

$ sudo apt-get install python-mysqldb

Here we install the Python interface to the MySQL database. Both _mysql and MySQL modules.

Next, we are going to create a new database user and a new database. We use the mysql client.

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 30
Server version: 5.0.67-0ubuntu6 (Ubuntu)

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

mysql> SHOW DATABASES;
+——————–+
| Database |
+——————–+
| information_schema |
| mysql |
+——————–+
2 rows in set (0.00 sec)

We connect to the database using the root account. We show all available databases with the SHOW DATABASES statement.

mysql> CREATE DATABASE testdb;
Query OK, 1 row affected (0.02 sec)

We create a new testdb database. We will use this database throughout the tutorial.

mysql> CREATE USER ‘testuser’@'localhost’ IDENTIFIED BY ‘test623′;
Query OK, 0 rows affected (0.00 sec)

mysql> USE testdb;
Database changed

mysql> GRANT ALL ON testdb.* TO ‘testuser’@'localhost’;
Query OK, 0 rows affected (0.00 sec)

mysql> quit;
Bye

We create a new database user. We grant all privileges to this user for all tables of the testdb database.
_mysql module

The _mysql module implements the MySQL C API directly. It is not compatible with the Python DB API interface. Generally, the programmers prefer the object oriented MySQLdb module. We will concern ourself with the latter module. Here we present only one small example with the _mysql module.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import _mysql
import sys

try:
conn = _mysql.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

conn.query(“SELECT VERSION()”)
result = conn.use_result()

print “MySQL version: %s” % \
result.fetch_row()[0]

conn.close()

except _mysql.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

The example will get and print the version of the MySQL database. For this, we use the SELECT VERSION() SQL statement.
MySQLdb module

MySQLdb is a thin Python wrapper around _mysql. It is compatible with the Python DB API, which makes the code more portable. Using this model is the preferred way of working with the MySQL.
First example

In the first example, we will get the version of the MySQL database.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()
cursor.execute(“SELECT VERSION()”)

data = cursor.fetchone()

cursor.close()
conn.close()

except mdb.Error, e:
print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

print “Database version : %s ” % data

In this script, we connect to the testdb database and execute the SELECT VERSION() statement. This will return the current version of the MySQL database. We print it to the console.

import MySQLdb as mdb

We import the MySQLdb module.

conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

We connect to the database. The connect() method has four parameters. The first parameter is the host, where the MySQL database is located. In our case it is a localhost, e.g. our computer. The second parameter is the database user name. It is followed by the user’s account password. The final parameter is the database name.

cursor = conn.cursor()
cursor.execute(“SELECT VERSION()”)

From the connection, we get the cursor object. The cursor is used to traverse the records from the result set. We call the execute() method of the cursor and execute the SQL statement.

data = cursor.fetchone()

We fetch the data. Since we retrieve only one record, we call the fetchone() method.

cursor.close()
conn.close()

Releasing of resources.

except mdb.Error, e:
print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

We check for errors. This is important, since working with databases is error prone.

print “Database version : %s ” % data

We print the data that we have retrieved to the console.

$ ./version.py
Database version : 5.1.41-3ubuntu12.6

The output might look like the above.
Creating and populating a table

We create a table and populate it with some data.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’, ‘test623′, ‘testdb’);

cursor = conn.cursor()
cursor.execute(“CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))”)
cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Jack London’)”)
cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Honore de Balzac’)”)
cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Lion Feuchtwanger’)”)
cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Emile Zola’)”)
cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Truman Capote’)”)

conn.commit()

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

We create a Writers table and add five authors to it.

cursor.execute(“CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))”)

This SQL statement creates a new database table called Writers. It has two columns. Id and Name.

cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Jack London’)”)
cursor.execute(“INSERT INTO Writers(Name) VALUES(‘Honore de Balzac’)”)

We use the INSERT statement to insert authors to the table. Here we add two rows.

mysql> SELECT * FROM Writers;
+—-+——————-+
| Id | Name |
+—-+——————-+
| 1 | Jack London |
| 2 | Honore de Balzac |
| 3 | Lion Feuchtwanger |
| 4 | Emile Zola |
| 5 | Truman Capote |
+—-+——————-+
5 rows in set (0.00 sec)

After executing the script, we use the mysql client tool to select all data from the Writers table.
Retrieving data

Now, that we have inserted some data into the database, we want to get it back.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()
cursor.execute(“SELECT * FROM Writers”)

rows = cursor.fetchall()

for row in rows:
print row

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

In this example, we retrieve all data from the Writers table.

cursor.execute(“SELECT * FROM Writers”)

This SQL statement selects all data from the Writers table.

rows = cursor.fetchall()

The fetchall() method gets all records. It returns a result set. Technically, it is a tuple of tuples. Each of the inner tuples represent a row in the table.

for row in rows:
print row

We print the data to the console, row by row.

$ ./retrieve.py
(1L, ‘Jack London’)
(2L, ‘Honore de Balzac’)
(3L, ‘Lion Feuchtwanger’)
(4L, ‘Emile Zola’)
(5L, ‘Truman Capote’)

This is the output of the example.

Returning all data at a time may not be feasible. We can fetch rows one by one.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()
cursor.execute(“SELECT * FROM Writers”)

numrows = int(cursor.rowcount)

for i in range(numrows):
row = cursor.fetchone()
print row[0], row[1]

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

We again print the data from the Writers table to the console. This time, we fetch the rows one by one.

numrows = int(cursor.rowcount)

Here we determine the number of rows returned by the SQL statement.

for i in range(numrows):
row = cursor.fetchone()
print row[0], row[1]

We fetch the rows one by one using the fetchone() method.

$ ./retrieve2.py
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote

Output of the example.
The dictionary cursor

There are multiple cursor types in the MySQLdb module. The default cursor returns the data in a tuple of tuples. When we use a dictionary cursor, the data is sent in a form of Python dictionaries. This way we can refer to the data by their column names.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor(mdb.cursors.DictCursor)
cursor.execute(“SELECT * FROM Writers”)

rows = cursor.fetchall()

for row in rows:
print “%s %s” % (row["Id"], row["Name"])

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

In this example, we print the contents of the Writers table using the dictionary cursor.

cursor = conn.cursor(mdb.cursors.DictCursor)

We use the DictCursor dictionary cursor.

rows = cursor.fetchall()

We fetch all data.

for row in rows:
print “%s %s” % (row["Id"], row["Name"])

We refer to the data by column names of the Writers table.
Column headers

Next we will show, how to print column headers with the data from the database table.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()
cursor.execute(“SELECT * FROM Writers”)

rows = cursor.fetchall()

desc = cursor.description

print “%s %3s” % (desc[0][0], desc[1][0])

for row in rows:
print “%2s %3s” % row

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

Again, we print the contents of the Writers table to the console. Now, we include the names of the columns too. The column names are considered to be the ‘meta data’. It is obtained from the cursor object.

desc = cursor.description

A Cursor Object’s description attribute returns information about each of the result columns of a query.

print “%s %3s” % (desc[0][0], desc[1][0])

Here we print and format the table column names.

for row in rows:
print “%2s %3s” % row

And here, we traverse and print the data.

$ ./columnheaders.py
Id Name
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote

Ouput of the script.
Prepared statements

Now we will concern ourselves with prepared statements. When we write prepared statements, we use placeholders instead of directly writing the values into the statements. Prepared statements increase security and performance. The Python DB API specification suggests 5 different ways how to build prepared statements. MySQLdb module supports one of them, the ANSI printf format codes.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()

cursor.execute(“UPDATE Writers SET Name = %s WHERE Id = %s”,
(“Guy de Maupasant”, “4″))

print “Number of rows updated: %d” % cursor.rowcount

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

We change the name of an author on the fourth row.

cursor.execute(“UPDATE Writers SET Name = %s WHERE Id = %s”,
(“Guy de Maupasant”, “4″))

This is the way to do it. We use the two %s placeholders. Before the SQL statement is executed, the values are bound to their placeholders.

mysql> SELECT Name FROM Writers WHERE Id=4;
+——————+
| Name |
+——————+
| Guy de Maupasant |
+——————+
1 row in set (0.00 sec)

The author on the fourth row was successfully changed.
Writing images

Some people prefer to put their images into the database, some prefer to keep them on the file system for their applications. Technical difficulties arise when we work with millions of images. Images are binary data. MySQL database has a special data type to store binary data called BLOB (Binary Large Object).

mysql> CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
Query OK, 0 rows affected (0.06 sec)

For this example, we create a new table called Images.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
fin = open(“chrome.png”)
img = fin.read()
fin.close()

except IOError, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

try:
conn = mdb.connect(host=’localhost’,user=’testuser’,
passwd=’test623′, db=’testdb’)
cursor = conn.cursor()
cursor.execute(“INSERT INTO Images SET Data=’%s’” % \
mdb.escape_string(img))

conn.commit()

cursor.close()
conn.close()

except mdb.Error, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

In the above script, we read a png image and insert it into the Images table.

fin = open(“chrome.png”)
img = fin.read()

We open and read an image. The read() function returns the data as string.

cursor.execute(“INSERT INTO Images SET Data=’%s’” % \
mdb.escape_string(img))

This string data is inserted into the table. Before doing so, it is processed by the escape_string() method. It escapes a string for use as a query parameter. This is common practice to avoid malicious sql injection attacks.
Reading images

In the previous example, we have inserted an image into the database table. Now we are going to read the image back from the table.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(host=’localhost’,user=’testuser’,
passwd=’test623′, db=’testdb’)

cursor = conn.cursor()

cursor.execute(“SELECT Data FROM Images LIMIT 1″)

fout = open(‘image.png’,'wb’)
fout.write(cursor.fetchone()[0])
fout.close()

cursor.close()
conn.close()

except IOError, e:

print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

We read one image from the Images table.

cursor.execute(“SELECT Data FROM Images LIMIT 1″)

We select one record from the table.

fout = open(‘image.png’,'wb’)

We open a writable binary file.

fout.write(cursor.fetchone()[0])

We fetch the data from the previous SQL statement and write it to the file.

Now we should have an image called image.png in our current directory. We can check if it is the same image, that we have inserted into the table.
Transaction support

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.

For databases that support transactions, the Python interface silently starts a transaction when the cursor is created. The commit() method commits the updates made using that cursor, and the rollback() method discards them. Each method starts a new transaction.

The MySQL database has different types of storage engines. The most common are the MyISAM and the InnoDB engines. The MyISAM is the default one. There is a trade-off between data security and database speed. The MyISAM tables are faster to process and they do not support transactions. The commit() and rollback() methods are not implemented. They do nothing. On the other hand, the InnoDB tables are more safe against the data loss. They support transactions. They are slower to process.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()

cursor.execute(“UPDATE Writers SET Name = %s WHERE Id = %s”,
(“Leo Tolstoy”, “1″))
cursor.execute(“UPDATE Writers SET Name = %s WHERE Id = %s”,
(“Boris Pasternak”, “2″))
cursor.execute(“UPDATE Writer SET Name = %s WHERE Id = %s”,
(“Leonid Leonov”, “3″))

conn.commit()

cursor.close()
conn.close()

except mdb.Error, e:

conn.rollback()
print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

In this script, we try to update three rows. The storage engine of the table is MyISAM.

cursor.execute(“UPDATE Writers SET Name = %s WHERE Id = %s”,
(“Leo Tolstoy”, “1″))
cursor.execute(“UPDATE Writers SET Name = %s WHERE Id = %s”,
(“Boris Pasternak”, “2″))

Here we want to change names of authors for rows 1 and 2.

cursor.execute(“UPDATE Writer SET Name = %s WHERE Id = %s”,
(“Leonid Leonov”, “3″))

There is an error in the SQL statement. There is no Writer table.

conn.rollback()

We can call the rollback() method, but it does nothing.

$ ./isam.py
Error 1146: Table ‘testdb.Writer’ doesn’t exist

mysql> SELECT * FROM Writers;
+—-+——————-+
| Id | Name |
+—-+——————-+
| 1 | Leo Tolstoy |
| 2 | Boris Pasternak |
| 3 | Lion Feuchtwanger |
| 4 | Guy de Maupasant |
| 5 | Truman Capote |
+—-+——————-+
5 rows in set (0.00 sec)

Running the script gives an error. But as we see, the first two rows already were changed.

In the last example of this tutorial, we are going to recreate the Writers table. This time, the table will be of InnoDB type. InnoDB MySQL database tables support transactions.

DROP TABLE Writers;

CREATE TABLE IF NOT EXISTS Writers(Id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(25)) ENGINE=INNODB;

INSERT INTO Writers(Name) VALUES(‘Jack London’);
INSERT INTO Writers(Name) VALUES(‘Honore de Balzac’);
INSERT INTO Writers(Name) VALUES(‘Lion Feuchtwanger’);
INSERT INTO Writers(Name) VALUES(‘Emile Zola’);
INSERT INTO Writers(Name) VALUES(‘Truman Capote’);

This is writers.sql file. It is used to recreate the Writers table.

mysql> source writers.sql
Query OK, 0 rows affected (0.03 sec)

Query OK, 0 rows affected (0.10 sec)

Query OK, 1 row affected (0.02 sec)

Query OK, 1 row affected (0.03 sec)

Query OK, 1 row affected (0.02 sec)

Query OK, 1 row affected (0.02 sec)

Query OK, 1 row affected (0.02 sec)

We can use the source commnad to load and execute the sql script.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
conn = mdb.connect(‘localhost’, ‘testuser’,
‘test623′, ‘testdb’);

cursor = conn.cursor()

cursor.execute(“DELETE FROM Writers WHERE Id = 5″)
cursor.execute(“DELETE FROM Writers WHERE Id = 4″)
cursor.execute(“DELETE FROM Writer WHERE Id = 3″)

conn.commmit()

except mdb.Error, e:

conn.rollback()
print “Error %d: %s” % (e.args[0],e.args[1])
sys.exit(1)

cursor.close()
conn.close()

Now, we are going to execute the above script. We want to delete three rows from the table. The third SQL statement has an error.

$ ./innodb.py
Error 1146: Table ‘testdb.Writer’ doesn’t exist

mysql> SELECT * FROM Writers;
+—-+——————-+
| Id | Name |
+—-+——————-+
| 1 | Jack London |
| 2 | Honore de Balzac |
| 3 | Lion Feuchtwanger |
| 4 | Emile Zola |
| 5 | Truman Capote |
+—-+——————-+
5 rows in set (0.00 sec)

The error occured before we have committed the changes to the database. The rollback() method was called and no deletions took place.

REF: http://zetcode.com/databases/mysqlpythontutorial/

 
#!/usr/bin/python
import csv
import MySQLdb

spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|')
for row in spamReader:
print ' '.join(row)
 

To create an image (link to a more verbose explanation) use dd on an unmounted CD/DVD drive:
dd if=/dev/cd of=cd.iso

 

add command to the bottom of the .bashrc file

alias cvsu='cvs -q update -P -d'

$source ~/.bashrc

now run the new command
$ cvsu

 

When displaying numbers on a web page make sure that you right justify the data for use of decimals.

For example, if left justifying data your table will look like this…

100.50
324.34
.25
5.34

When right justified it looks better and your decimals line up.

100.00
.25
5.67

 

Standard php conditional:

  1. if (date("G") < 12) {
  2. echo 'Good morning';
  3. } else {
  4. echo 'Good afternoon';
  5. }

Shorthand…

  1. $greeting = (date("G") < 12) ? 'Good morning' : 'Good afternoon';
  2. echo $greeting;

(http://www.addedbytes.com/php/ternary-conditionals/)

 

Say for example, you have a web page you want to access some data on but the database is located on a different server. To do this you will need to add another user to the mysql.users table and specify the remote location where you are accesing from.

$ mysql -u root -p

mysql>  GRANT ALL PRIVILEGES ON database_name.* TO myUser@host_name IDENTIFIED BY 'pass' WITH GRANT OPTION;

*user ‘%’ for hostname if wanting to accept connections from all hosts.

mysql> Flush priviledges

Next, edit your /etc/mysql/my.cnf file:

Comment the bind-address

#bind-address: 127.0.0.1  //if enabled with disallow connections from a remote host.

Restart mysql:

# /etc/init.d/mysql restart

 
 

Problem: When executing a python script you get the following error:

SyntaxError: Non-ASCII character ‘\xe2′ in file /usr/share/onboard/utils.py on line 17, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

The Fix:

Add

# -*- coding: utf-8 -*-

to the top of your document

Jan 302009
 

check ‘dmesg’ for new drive
create partition table with fdisk
format disk. 'mkfs -t ext3 /dev/hdc1
mount the drive 'mount -t ext3 /dev/sdc1 /mount/dir'

 

Usage: python ./scriptname.py oldword newword sourcfile.txt newfile.txt

#!/usr/local/bin/python
import os, sys
usage = "usage: %s search_text replace_text [infile [outfile]]" %         os.path.basename(sys.argv[0])

if len(sys.argv) < 3:
     print usage
else:
stext = sys.argv[1]
rtext = sys.argv[2]
input = sys.stdin
output = sys.stdout
if len(sys.argv) > 3:
input = open(sys.argv[3])
if len(sys.argv) > 4:
output = open(sys.argv[4], 'w')
for s in input.xreadlines():
output.write(s.replace(stext, rtext))
Jan 302009
 

Shell script to send email notification if hdd status reaches certain threshold.

#!/bin/sh
Drives=`df | perl -e 'while(<>) { if((/9[5-9]%/ or /100%/) and not /\/dev\/sdb1/) { print$_; }}'` email="email@email.com"

if [ "$Drives" ]; then
mail -s "[disk status] $HOSTNAME full" $email << EOM
$HOSTNAME is critically low on space. View df message below.
$Drives
EOM

fi
 

Install iperf

apt-get install iperf

Listen on machine #1

$ iperf -s -P 2 -i 5 -p 5999 -f M

Send packets on machine #2

iperf -c backupserv -P 1 -i 5 -p 5999 -f M -t 60 -T 1

Results:
————————————————————
Client connecting to backupserv, TCP port 5999
TCP window size: 0.02 MByte (default)
————————————————————
[  3] local 192.168.1.5 port 49711 connected with 192.168.1.3 port 5999
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0- 5.0 sec    562 MBytes    112 MBytes/sec
[  3]  5.0-10.0 sec    562 MBytes    112 MBytes/sec
[  3] 10.0-15.0 sec    561 MBytes    112 MBytes/sec
[  3] 15.0-20.0 sec    561 MBytes    112 MBytes/sec
[  3] 20.0-25.0 sec    562 MBytes    112 MBytes/sec
[  3] 25.0-30.0 sec    561 MBytes    112 MBytes/sec
[  3] 30.0-35.0 sec    561 MBytes    112 MBytes/sec
[  3] 35.0-40.0 sec    561 MBytes    112 MBytes/sec
[  3] 40.0-45.0 sec    561 MBytes    112 MBytes/sec
[  3] 45.0-50.0 sec    561 MBytes    112 MBytes/sec
^C[  3]  0.0-50.8 sec  5707 MBytes    112 MBytes/sec

© 2011 OSS Robot Suffusion theme by Sayontan Sinha