Wednesday, April 10, 2013

cool awk

Awk is quite neat


I recently used it to checkout a bunch of files I modified by mistake.

git checkout * 

did't work because some files we're not in the index and Git complained.

So I did

git st | awk '{if ($2=="modified:") {print $3} }' | xargs git co

which was quite cool...

More on AWK

among infinite features, I just used 'match' to see if a string was inside another...

in particular lines which have an M in the first column... (like to see file in the Megabytes range with du)

du -h  | awk '{ if (match($1, "M")) {print $2} }'

Here's a link which reminded me how to do the 'if's in awk... and other examples:


http://www.thegeekstuff.com/2010/02/awk-conditional-statements/


4 Awk If Statement Examples ( if, if else, if else if, :? )
by SASIKALA on FEBRUARY 17, 2010


This article is part of the on-going Awk Tutorial Examples series. In our earlier awk articles, we discussed about awk print, awk user-defined variables, awk built-in variables, and awk operators.

In this awk tutorial, let us review awk conditional if statements with practical examples.

Awk supports lot of conditional statements to control the flow of the program. Most of the Awk conditional statement syntax are looks like ‘C’ programming language.

Normally conditional statement checks the condition, before performing any action. If the condition is true action(s) are performed. Similarly action can be performed if the condition is false.

Conditional statement starts with the keyword called ‘if’. Awk supports two different kind of if statement.

Awk Simple If statement
Awk If-Else statement
Awk If-ElseIf-Ladder
Awk Simple If Statement

Single Action: Simple If statement is used to check the conditions, if the condition returns true, it performs its corresponding action(s).

Syntax:
if (conditional-expression)
action
if is a keyword
conditional-expression – expression to check conditions
action – any awk statement to perform action.
Multiple Action: If the conditional expression returns true, then action will be performed. If more than one action needs to be performed, the actions should be enclosed in curly braces, separating them into a new line or semicolon as shown below.



Syntax:
if (conditional-expression)
{
action1;
action2;
}
If the condition is true, all the actions enclosed in braces will be performed in the given order. After all the actions are performed it continues to execute the next statements.

Awk If Else Statement

In the above simple awk If statement, there is no set of actions in case if the condition is false. In the awk If Else statement you can give the list of action to perform if the condition is false. If the condition returns true action1 will be performed, if the condition is false action 2 will be performed.

Syntax:
if (conditional-expression)
action1
else
action2
Awk also has conditional operator i.e ternary operator ( ?: ) whose feature is similar to the awk If Else Statement. If the conditional-expression is true, action1 will be performed and if the conditional-expression is false action2 will be performed.

Syntax:

conditional-expression ? action1 : action2 ;
Awk If Else If ladder

if(conditional-expression1)
action1;
else if(conditional-expression2)
action2;
else if(conditional-expression3)
action3;
.
.
else
action n;
If the conditional-expression1 is true then action1 will be performed.
If the conditional-expression1 is false then conditional-expression2 will be checked, if its true, action2 will be performed and goes on like this. Last else part will be performed if none of the conditional-expression is true.
Now let us create the sample input file which has the student marks.

$cat student-marks
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122 38 37
Edwin 2537 87 97 95
Dayan 2415 30 47
1. Awk If Example: Check all the marks are exist

$ awk '{
if ($3 =="" || $4 == "" || $5 == "")
print "Some score for the student",$1,"is missing";'
}' student-marks
Some score for the student RinRao is missing
Some score for the student Dayan is missing
$3, $4 and $5 are test scores of the student. If test score is equal to empty, it throws the message. || operator is to check any one of marks is not exist, it should alert.

2. Awk If Else Example: Generate Pass/Fail Report based on Student marks in each subject

$ awk '{
if ($3 >=35 && $4 >= 35 && $5 >= 35)
print $0,"=>","Pass";
else
print $0,"=>","Fail";
}' student-marks
Jones 2143 78 84 77 => Pass
Gondrol 2321 56 58 45 => Pass
RinRao 2122 38 37 => Fail
Edwin 2537 87 97 95 => Pass
Dayan 2415 30 47 => Fail
The condition for Pass is all the test score mark should be greater than or equal to 35. So all the test scores are checked if greater than 35, then it prints the whole line and string “Pass”, else i.e even if any one of the test score doesn’t meet the condition, it prints the whole line and prints the string “Fail”.

3. Awk If Else If Example: Find the average and grade for every student

$ cat grade.awk
{
total=$3+$4+$5;
avg=total/3;
if ( avg >= 90 ) grade="A";
else if ( avg >= 80) grade ="B";
else if (avg >= 70) grade ="C";
else grade="D";

print $0,"=>",grade;
}
$ awk -f grade.awk student-marks
Jones 2143 78 84 77 => C
Gondrol 2321 56 58 45 => D
RinRao 2122 38 37 => D
Edwin 2537 87 97 95 => A
Dayan 2415 30 47 => D
In the above awk script, the variable called ‘avg’ has the average of the three test scores. If the average is greater than or equal to 90, then grade is A, or if the average is greater than or equal to 80 then grade is B, if the average is greater than or equal to 70, then the grade is C. Or else the grade is D.

4. Awk Ternary ( ?: ) Example: Concatenate every 3 lines of input with a comma.

$ awk 'ORS=NR%3?",":"\n"' student-marks
Jones 2143 78 84 77,Gondrol 2321 56 58 45,RinRao 2122 38 37
Edwin 2537 87 97 95,Dayan 2415 30 47,
We discussed about awk ORS built-in variable earlier. This variable gets appended after every line that gets output. In this example, it gets changed on every 3rd line from a comma to a newline. For lines 1, 2 it’s a comma, for line 3 it’s a newline, for lines 4, 5 it’s a comma, for line 6 a newline, etc.

Thursday, March 14, 2013

counting connections to my server and limit connections by IP

Today I was informed by Amazon that I was being hacked. : - o

I learned to count the connection that where being made to my server with a very pretty command:

sudo netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

There were some 'mean' Indonesians and Slovakians opening a lot of connection to my server, so the output of the command looked like:

sudo netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
...

     54 64.90.61.239
     62 77.55.119.209
     63 75.119.200.56
    134 112.78.2.183
    182 173.233.65.108


Having Apache allowing 300 connections (directive MaxClients in apache2.conf), and ServerLimit 500 (ServerLimit directive), this connections from weird countries I shouldn't have visitors from rapidly collapsed my site and it was down

iptables to the rescue:

I found this simple tutorial: http://www.cyberciti.biz/faq/iptables-connection-limits-howto/ to configure IPTABLES, and this other one to learn a bit more about the command: https://help.ubuntu.com/community/IptablesHowTo

In the end, it was enough to do

sudo iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 -j REJECT --reject-with tcp-rese

and then

sudo sh -c "iptables-save > /etc/iptables.rules"

to save the configuration into a file that is loaded at boot. Watch out dont overwrite the /etc/iptables.rules if you have any.

After this commands my site was up again, and I had learned a lot.

here is the tutorial I followed (iptables is pretty standard, so its not necessary to reproduce it here):

Iptables Limits Connections Per IP

by on February 7, 2010 · 29 comments· last updated at February 9, 2010
How do I restrict the number of connections used by a single IP address to my server for port 80 and 25 using iptables? You need to use the connlimit modules which allows you to restrict the number of parallel TCP connections to a server per client IP address (or address block).
This is useful to protect your server or vps box against flooding, spamming or content scraping.

Syntax

The syntax is as follows:
/sbin/iptables -A INPUT -p tcp --syn --dport $port -m connlimit --connlimit-above N -j REJECT --reject-with tcp-reset
# save the changes see iptables-save man page, the following is redhat and friends specific command
service iptables save

Example: Limit SSH Connections Per IP / Host

Only allow 3 ssg connections per client host:
/sbin/iptables  -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT
# save the changes see iptables-save man page, the following is redhat and friends specific command
service iptables save

Example: Limit HTTP Connections Per IP / Host

Only allow 20 http connections per IP (MaxClients is set to 60 in httpd.conf):
WARNING! Please note that large proxy servers may legitimately create a large number of connections to your server. You can skip those ips using ! syntax
/sbin/iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 -j REJECT --reject-with tcp-reset
# save the changes see iptables-save man page, the following is redhat and friends specific command
service iptables save
Skip proxy server IP 1.2.3.4 from this kind of limitations:
/sbin/iptables -A INPUT -p tcp --syn --dport 80 -d ! 1.2.3.4 -m connlimit --connlimit-above 20 -j REJECT --reject-with tcp-reset

Example: Class C Limitations

In this example, limit the parallel http requests to 20 per class C sized network (24 bit netmask)
/sbin/iptables  -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j REJECT --reject-with tcp-reset
# save the changes see iptables-save man page
service iptables save

Example: Limit Connections Per Second

The following example will drop incoming connections if IP make more than 10 connection attempts to port 80 within 100 seconds (add rules to your iptables shell script)
#!/bin/bash
IPT=/sbin/iptables
# Max connection in seconds
SECONDS=100
# Max connections per IP
BLOCKCOUNT=10
# ....
# ..
# default action can be DROP or REJECT
DACTION="DROP"
$IPT -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
$IPT -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds ${SECONDS} --hitcount ${BLOCKCOUNT} -j ${DACTION}
# ....
# ..

How Do I Test My Firewall Working?

Use the following shell script to connect to your web server hosted at 202.1.2.3:
#!/bin/bash
ip="202.1.2.3"
port="80"
for i in {1..100}
do
  # do nothing just connect and exit
  echo "exit" | nc ${ip} ${port};
done
 

References:

Wednesday, March 6, 2013

for loop inline bash style AND while ... loop

So simple, yet I always forget.

Here's how to do a for loop in inline bash:

for x in {1..30}; do foo1; foo2; done

Also how to do an inline while loop in bash:

while true; do foo; sleep 2; done

copy hidden files when using 'cp'

To copy hidden files when using 'cp' don't specify the files being copied..


Don't specify the files:
cp -r /etc/skel /home/user

http://superuser.com/questions/61611/how-to-copy-with-cp-to-include-hidden-files-and-hidden-directories-and-their-con

Sunday, March 3, 2013

cakephp 1.3 migration to 2.3.1

I decided to migrate one of my apps (one of the easiest) from cakephp 1.3 to 2.3.1

Although the cakaphp upgrade shell is magnificent upgrading my code, it doesn't to all (obviously).

Problems I encountered:


  • upgrading plugins
    • I was lucky I think all my plugins had a 2.x branch
  • One to manually upgrade webroot/index.php file
  • One has to manually merge Config/core.php file with your old one
  • Im 1.3 I used $this->view = 'MyView'  in app_controller to use my own view class. This changed to $this->viewClass
  • I also had to update my legacy code.
    • That is to change some things from 1.2 style to 1.3 style... which was already compatble with 2.3.1 !
      • that included basically changing
        • $this->Javascript->link to $this->Html->script
        • $this->Javascript->codeBlock to $this->Html->scriptBlock
        • $this->Javascript->object to $this->JsBaseEngine->object
        • this was easily done with find && sed:
find . -type f -exec sed -i -e "s/Javascript->link/Html->script/g" {} \;
find . -type f -exec sed -i -e "s/Javascript->codeBlock/Html->scriptBlock/g" {} \;
find . -type f -exec sed -i -e "s/Javascript->link/Html->script/g" {} \;

Tuesday, February 26, 2013

windows registry files

As I wrote in a previous post, I had to change computers.

One of the things is I had a lot of configuration in the registry file of the old computer (from which I only have the hard drive).

So I needed to extract this info...

The registry files are located in

Windows\System32\Config

So I copied those files to a folder in the new computer.

Now I needed a program to read those files, so I used: Windows Registry Recovery



Lastly this didn't work as expected. Apparently the actual registry isn't located (or accesible) in Windows\System32\Config. I say this because I inspected the files found in that dir with the tool afore mentioned, and I didn't find what I was looking (the entries for WinSCP's configuration). So I had to mount the HDD in the old computer, cross my fingers and use REGEDIT to export them.

I was lucky enough in that the computer worked for the time I needed : )


apache user

The linux user that uses Apache webserver can be seen under User directive in apache's configuration

Fedora: /etc/httpd/conf/httpd.conf
Ubuntu: /etc/apache2/apache2.conf


Who in the world started changing the paths of files depending on the flavor of the linux distrubution ?

Sunday, February 24, 2013

query for table definition on mysql

in the console, issue:


show create table my_tables_name;

and it will show the table definition...

for example:

mysql> show create table client_users;
+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table        | Create Table                                                                                                                                                                                   |
+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| client_users | CREATE TABLE `client_users` (
  `id` varchar(36) NOT NULL,
  `client_id` varchar(36) NOT NULL,
  `user_id` varchar(36) NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |


(for cakePHP guys: I wanted not to use a HABTM)


Apps I can't work without


I recently had to changed computer, and reinstall all the software... : s
So I guess it's a good time to write the (almost all freeware) apps I've been installing, without any particular order. Thanks you guys for that great development, I hope some day to contribute to you guys back.
And that gets me on working...

Friday, January 25, 2013

maintaining session after redirect from payment (credit card) post

I was facing this exact problem in CakePHP, the answer was to use Security.low in core.php !:

(http://cakephp.1045679.n5.nabble.com/After-auto-redirect-from-another-domain-site-the-session-was-lost-td1324708.html)

Hey Guys,
Let me write down the steps to reproduce my problem:
Reproduce steps:
1. Customer login my site(https://www.mysite.com);
2. Choose a product and redirect to Paypal sandbox site(https://developer.paypal.com/cgi-bin/devscr) to complete the payment;
3. After the payment, the customer will be auto redirected to my site;
4. And then the customer session was lost.

I find the solution in Paypal forums, said that :

You could pass your "session variable" Through PayPal variable "custom" than read it back in when the buyer is returned to your site after completing the PayPal payment or through the IPN POST.
 
You could also use an authentication cookie which would stick around while the customer made a payment on PayPal's website and when they returned to your site they would still be authorized.
I try to store the session in my post form and get it after the redirect from paypal site.
And then I use $this->Session->id($lastSessionID) to restore it. But fail as before.

Is there anybody has the idea how to implement it in Cake App?
Appreciate for any reply from you.

-- 
Thanks
Joshua


thanks indeed

Saturday, December 8, 2012

Working with Amazon's Elastic Beanstalk

I decided to start using Amazon cloud services.

There is a pretty instresting solution Amazon Beastalk, which you should consider.

There is a lot of documentation, but as normal, there are always pseudo dark steps not thoroughly documented.

For intance, when you arrive to "Develop, Test, and Deploy" section of the "AWS Elastic Beanstalk" documentation, there is a step, name #1 quite obscure:


1.- From your Git repository directory, type the following command.
git aws.config

Nowhere it is told that you must previously 'set up your gir repository' as described here.

I also encountered what I think is a bug regarding timezones on Amazon's service, which was easily fixed. Following the README of the "AWS Command line tools". I got this error:


 $ elastic-beanstalk-describe-applications
Service returned an error.
Type: Sender
Code: RequestExpired
Message: Request has expired. Timestamp date: 2012-06-02T14:44:13-04:30

Strangely, this happened because I had my ubuntu virtual box configured to show time as in my timezone (-04:30), while the EC2 instance (at least that's we're I checked) showed in UTC format.

So I decided to change my locale to UTC

doing
 $ sudo dpkg-reconfigure tzdata

I had to select "ETC", and then "UTC"...

Done that, the command "elastic-beanstalk-describe-applications" ran without problems. showing my applications.

Then I continued following the beanstalk documentation and did
git aws.config
git aws.push

The only problem I encountered after doing this is that I realized that Amazon Beanstalk doesn't support Git Submodules !! So I had to make a new directory, copy all my application there, do a new complete repository with all the code and push it to amazon. At first I was kind of reluctant to do this, but then I started to think that it was not that bad ... (I also didn't have other options : )

I realized that my app was configured to always redirect to https protocol (secure http) (this gave me a lot of headaches, because if Beanstalk is not configured to work with SSL then the Health Check URL didn't work at all because of the difference http/https... ). So I decided to buy a $13 SSL certificate from godaddy (they cost this if you click on their ad after a google search, not if you enter directy to godaddy).

I wanted to configure mydomain.com instead of www.mydomain.com, and also to use Amazon Route 53. This was not a problem with the current documentation at Amazon.









Friday, December 7, 2012

rsync over ssh with a private key

RSYNC is my favorite tool to sync two directories, either local or remotely.

Now I learned how to do it over ssh using a private key:

Thanks to Troy and this link: http://troy.jdmz.net/rsync/index.html

This is the command:

rsync -e "ssh -i /path/to/my/key.pem -l myuser" myremotehost:/remote/path/ localpath -iva

Easy peasy

Thursday, December 6, 2012

joomla white page in template after server migration/update // comparing packages

I changed servers mounted all the stuff and some of the Joomla sites I had opened correctly, others just showed a white page.

I didn't know why.

After many many failed attemps to fix it, god's hand enlightened me and I decided to compare the installed php packages between servers.

This can be done using
dpkg --get-selections | grep php

Comparing these packages between servers, it showed evidently I had missed installation of the package
php5-mcrypt

An apt-get install put my joomla sites running again.

Tuesday, December 4, 2012

install LAMP - postgres - change data dir - ssh without password... all donde minuted in AWS Amazon Web Services

I just wanted to comment on how good Amazon Web Services are.

I had my server hosted with another provider, whose name I'm not going to say...

I was with them a lot of time, maybe 10 years. Upgraded my server a couple of times and all. One day my server went nuts and they wanted to charge me $99 dollars AN HOUR just to take a look and help me, no warranties.

So I decided it was time to migrate to a better service: Amazon AWS.

I was getting used to it while setting up the a webapp on Elastic Beanstalk, which is also an excellent service you should try if you have a big webapp you want to deploy. It has and all integration with git, so its all really easy. Using it was that I started understading the relationship between the different services:
EC2: the app servers
RDS: database servers
Route52: domain record management
CloudFront: asset delivery
etc...

Well, as I was saying I was urged to migrate from my old server.

I could set up a running new server in minutes. Maybe the most complicated stuff would be opening a new account and passing through the telephone validation.

So I wrote all this because I wanted to documents the command I did to install the LAMP+Postgres environment I needed. Also to change the datadir of mysql:

I decided to use an instance running Ubuntu.

commands (with sudo or as root):
apt-get update
apt-get install apache2 libapache2-mod-php5 mysql-server libapache2-mod-auth-mysql php5-mysql postgresql-client php5-pgsql

that get all I needed installed.

I had a snapshot of a volume I wanted to mount in the new server. So in Amazon's interface I select attach volume to xxxx instance. After that I had to modify mount the drive that appeared in /dev/xvdf with the command

mount /dev/xvdf /mnt

To make the change permanent I edited the file

/etc/fstab

and added the line

/dev/xvdf /mnt ext4 defaults 0 0

where /mnt is the mount point... the other options are googlable.

I also needed to change MySql's data directory. This was kind of tricky the first time I had to do it.

One needs to change /etc/mysql/my.cnf file find datadir options and change it to what one needs.

The restart mysql with

service mysql restart

But that't not all, it is necessaty to update ubuntu's apparmor file with

vim /etc/apparmor.d/usr.sbin.mysqld

There you must find the old datadir path and change for the new one. Afterwards, reconfigure mysql with

dpkg-reconfigure mysql-server-5.5

And then restart again mysql (I did this, I don't know if its absolutely necessary).

I also needed to log in to the server using classic user/password combination, so its necessary to edit sshd_config with

vim /etc/ssh/sshd_config

There it is necessary to change the directive to

PasswordAuthentication yes

Finally I installed exim4 as an MTA

apt-get install exim4

and configured it with

dpkg-reconfigure exim4-config

I then chose a user to forward me root and postmaster mails. It is necessary to create a file in the user home

~/.forward

and the contents are the email address to which you wish to forward the emails.

that's it !

Monday, May 28, 2012

Database migration from PostgreSQL to MySql

Since I need to use Amazon RDS for my new application, I needed to migrate from my current PostgreSQL database to MySql.

Luckily I didn't realy in anything specific of postgresql, so migration  of schema and data was a breeze. I used a free downloadable online console tool pg2mysql

Well, in the schema generated my pg2mysql the TIMESTAMP fields in Postgres were converted to TIMESTAMP datatype in MySql (which has a DEFAULT CURRENT_TIMESTAMP by default), which is not what I wanted. So I manually edited my schema dump replacing "timestamp" to "datetime".

I also changed the default MyISAM to InnoDB...

In particular, in my code I had to be careful because certain syntax changes:

  • DISTINCT ON  (field1, field2)  field2 as f1, field2 as f2, field3 -> DISTINCT(CONCAT(field1, field2)), field3



Wednesday, May 16, 2012

error running shared postrotate script for mysql

I was receiving this emails on a daily basis:
/etc/cron.daily/logrotate:
error: error running shared postrotate script for /var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log
run-parts: /etc/cron.daily/logrotate exited with return code 1
I decided to do something about it. After checking this link I determined it was because of a password error in the user debian-sys-maint.


I had deleted this user without noticing it's importance.

So in this link I found how to recover the user, and also I read Ubuntu: Reset debian-sys-maint’s mysql password ...

I hope I don't receive the email tomorrow.

Just for documentation sake, I copy the relevant contents of the previous link I mentioned.

1)
Recently I upgraded Linux on my home server and every day I would get this email:
Subject: Anacron job 'cron.daily' on server.local
/etc/cron.daily/logrotate:
error: error running shared postrotate script for '/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log '
run-parts: /etc/cron.daily/logrotate exited with return code 1
I first examined the /etc/cron.daily/logrotate script.
There was only one executable line: /usr/sbin/logrotate /etc/logrotate.conf
I next examined /etc/logrotate.conf and found this: include /etc/logrotate.d
logrotate.d is a directory of scripts to run.
SInce my error message was for MySQL, I examined the /etc/logrorate.d/mysql-server script.
One line in this script is
MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
I examined /etc/mysql/debian.cnf and found the cause of the error message:
user = debian-sys-maint
password = oMhAfEiEiO
It was the PASSWORD! There was a mismatch between the password in debian.cnf and the password for thedebian-sys-maint user in MySQL.
Finally, I changed the password for debian-sys-maint in MySQL to the password listed in debian.cnf and the daily error message email stopped.

2)
Log into MySQL as the root user and run the following SQL query, substituting PASSWORD-HERE for the actual plain text password which is the same as the password in the /etc/mysql/debian.conf file:

INSERT INTO `user` (
 `Host`,
 `User`,
 `Password`,
 `Select_priv`,
 `Insert_priv`,
 `Update_priv`,
 `Delete_priv`,
 `Create_priv`,
 `Drop_priv`,
 `Reload_priv`,
 `Shutdown_priv`,
 `Process_priv`,
 `File_priv`,
 `Grant_priv`,
 `References_priv`,
 `Index_priv`,
 `Alter_priv`,
 `Show_db_priv`,
 `Super_priv`,
 `Create_tmp_table_priv`,
 `Lock_tables_priv`,
 `Execute_priv`,
 `Repl_slave_priv`,
 `Repl_client_priv`,
 `Create_view_priv`,
 `Show_view_priv`,
 `Create_routine_priv`,
 `Alter_routine_priv`,
 `Create_user_priv`,
 `ssl_type`,
 `ssl_cipher`,
 `x509_issuer`,
 `x509_subject`,
 `max_questions`,
 `max_updates`,
 `max_connections`,
 `max_user_connections`
)
VALUES (
 'localhost',
 'debian-sys-maint',
 password('PASSWORD-HERE'),
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'Y',
 'N',
 'N',
 'N',
 'N',
 'N',
 '',
 '',
 '',
 '',
 0,
 0,
 0,
 0
);
FLUSH PRIVILEGES;

3)
On Ubuntu systems there is a (system) mysql user debian-sys-maint that is used by the system’s init scripts to control the mysql database, e.g. to start or stop the mysql server. The password of this user is stored (in clear text) in /etc/mysql/debian.cnf. If this password does not match the the actual password in the mysql server the mysql init scripts will fail:
# /etc/init.d/mysql restart
 * Stopping MySQL database server mysqld     [fail]
 * Starting MySQL database server mysqld     [ OK ]
# /etc/init.d/mysql status
/usr/bin/mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'debian-sys-maint'@'localhost' (using password: YES)'
Moreover trying to update the mysql server will fail with an error like:
Fehler traten auf beim Bearbeiten von:
 /var/cache/apt/archives/mysql-server-5.1_5.1.37-1ubuntu5.1_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
To fix the problem you have to update the mysql password for the user debian-sys-maint:
  1. Get the password from /etc/mysql/debian.cnf. The clear text password is stored twice in the file (the lines starting with “password =”:
    # Automatically generated for Debian scripts. DO NOT TOUCH!
    [client]
    host = localhost
    user = debian-sys-maint
    password = your-secret-password
    socket = /var/run/mysqld/mysqld.sock
    [mysql_upgrade]
    host = localhost
    user = debian-sys-maint
    password = your-secret-password
    socket = /var/run/mysqld/mysqld.sock
    basedir = /usr
  2. Update the password in the mysql server (you need mysql root access):
    mysql --user root --password
    mysql> SET PASSWORD FOR 'debian-sys-maint'@'localhost' = PASSWORD('your-secret-password');
  3. If an previous mysql-server system upgrade failed, just restart the upgrade.
The (debian) documentation can be found in /usr/share/doc/mysql-server-5.1/README.Debian:
[...] You may never ever delete the special mysql user “debian-sys-maint”. This user together with the credentials in /etc/mysql/debian.cnf are used by the init scripts to stop the server as they would require knowledge of the mysql root users password else. So in most of the times you can fix the situation by making sure that the debian.cnf file contains the right password, e.g. by setting a new one (remember to do a “flush privileges” then). [...]

cancel script completely on ctrl-c

I found this question interesting: basically how to cancel completely a script and all child processes : You do this by creating a subro...