Batch download files from a website

I needed a quick bash script that will batch download all files from a public web server.
The files had the names like 1.gif, 2.gif, etc and were accessible via a CDN subdomain like http://images.mydomain.com.

So here it is:

for i in {1..18000}; do wget images.mydomain.com/$i.gif; sleep 5;done

Replace mydomain.com with your site and that’s it.
Alternatively you can get rid of “sleep 5″ and put the whole script in a file and execute it with:


[root@nix]# nohup ./script.sh &

This will keep your script running even if you disconnect from the shell console.

Restore mysql database from sql file

If you want to restore a mysql database from a sql file you have to issue this command:

[root@enix ~]#mysql -uroot -pxxx my-database < my-database-backup.sql

– where: my-database is your databse where you want to restore data;
– my-database-backup.sql is your sql backup file
– change root to your mysql user
– change xxx with your mysql password

And that’s it.

When dumping the database with mysqldump, use the option –no-create-db.
This will suspress the CREATE DATABASE statement in your dump file.
Then restore the database with

mysql -h <host> -u <user> -p <databasename> < dump.sql

In this way you can restore your data in whatever database you like (But that database has to exist!).

Substitution operators

Substitution operators are used for expanding parameters and variable values.

Examples:

${variablename:-some word}

-If varname exists and isn’t null, return its value; otherwise return word.

Purpose: Returning a default value if the variable is undefined.

[root@euve59329 ~]# echo ${PWDx:-non existent variable}
non existent variable

${varname:=word}
– If varname exists and isn’t null, return its value; otherwise set it to
word and then return its value. Positional and special parameters

[root@euve59329 ~]# echo ${ID:=0}
0

– ID variable does not exist. In this case, the value is set to 0.

Purpose:Setting a variable to a default value if it is undefined.


${varname:?message} 

If varname exists and isn’t null, return its value; otherwise print
varname: followed by message, and abort the current command or
script (non-interactive shells only). Omitting message produces the
default message parameter null or not set.

 

[root@euve59329 ~]# echo ${thevariable:?does not exist}
bash: thevariable: does not exist
[root@euve59329 ~]#

– Purpose: Catching errors that result from variables being undefined.


${varname:+word}

[root@euve59329 ~]# echo ${count:+1}
1
[root@euve59329 ~]# echo ${countX:+1}

Purpose: Testing for the existence of a variable.
Example: ${count:+1} returns 1 (which could mean “true”) if count is
defined.


 

${varname:offset:length}

 

Performs substring expansion.[5] It returns the substring of $varname
starting at offset and up to length characters. The first character in
$varname is position 0. If length is omitted, the substring starts at
offset and continues to the end of $varname. If offset is less than 0 then
the position is taken from the end of $varname. If varname is @, the
length is the number of positional parameters starting at parameter
offset.
Purpose: Returning parts of a string (substrings or slices).
Example:

 

[root@euve59329 ~]# count=MyCoolText
[root@euve59329 ~]# echo ${count:4}
olText
[root@euve59329 ~]# echo ${count:4:4}
olTe
[root@euve59329 ~]#

Inspired from Learning the bash Shell: Unix Shell Programming (In a Nutshell (O’Reilly))

String Manipulation and Expanding Variables

String Manipulation and Expanding Variables

For your ready references here are all your handy bash parameter substitution operators. Try them all; enhance your scripting skills like a pro:

${parameter:-defaultValue} Get default shell variables value
${parameter:=defaultValue} Set default shell variables value
${parameter:?”Error Message”} Display an error message if parameter is not set
${#var} Find the length of the string
${var%pattern} Remove from shortest rear (end) pattern
${var%%pattern} Remove from longest rear (end) pattern
${var:num1:num2} Substring
${var#pattern} Remove from shortest front pattern
${var##pattern} Remove from longest front pattern
${var/pattern/string} Find and replace (only replace first occurrence)
${var//pattern/string} Find and replace all occurrences
REFERENCES:

via http://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

How to empty large log files

If you want to empty large log files (aka lots of GB) without deleting the file, here’s how you can do that:

 

 

nix# > mylargelog.log

or

nix# echo " " > mylargelog.log

Tadaa!!

Search in archives

When using the linux shell daily we encounter situations when we need to search specific strings in one or more archives. If you are wondering how to search in archives for different patterns or strings, this tutorial will show you how.

You might have an archived log file and you want to search for the word “error”, here’s how you can do it.

Presenting zcat:

zcat is a linux console utility that takes as input compressed data files and send to stdout the results. Used with advanced utilities like cut, grep or awk, zcat becomes a very powerful application that helps the linux system administrator to search through archived files.

Here’s an example.

[root@nyx /]# zcat httpd-log_20140821.gz | awk -F ";" '($6~"error")

[Wed Aug 27 11:08:27 2014] [error] [client 91.196.46.169] PHP Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings.

The explaining:

zcat parses httpd-log_20140821.gz, outputs the lines that have the word “error” in the 6th column of the log file.

Another example:

zcat logs_2014082* | awk -F ";" '($1=="Transaction timed out") | sort -u

Alert: a Transaction timed out error was received at 2014-08-20 1:33

Alert: a Transaction timed out error was received at 2014-08-21 10:03

The explanation:

zcat parses the archived files hat start with ” logs_2014082″, searches if the 1st column contains “Transaction timed out” then sorts the output and removes duplicate lines.

Introducing zgrep.
Like the similar grep command, zgrep is a linux utility that was developed for the sole purpose of matching patters or strings inside an archived file.

Example:

zgrep error httpd.log.gz

[Sat Aug 23 06:12:20 2014] [error] [client 141.8.147.29] File does not exist: /www/html/nixware.net/httpdocs/index
[Sat Aug 23 06:12:21 2014] [error] [client 37.58.100.76] File does not exist: /www/html/nixware.net/httpdocs/forum

 

The explanation: zgrep searches the httpd.log.gz file for the “error” word and sends the output to stdout.

zmore:

– allows you to filter archived or plain text files one screen a a time. As it’s name says it does basically the same thing as more but it can search.

How to run linux scripts

Scripts can be defined as a sequence of commands that are stored inside a file and are usually executed in order to automate certain tasks. In the following minutes I’m gonna show you how to run linux scripts from the shell.

In the BASH environment you can find many types of scripts. Depending on the user needs you can find BASH, Python, Perl or other type of scripts.

In some cases they might have an extension like .sh, .bsh, or .py, however this is not a rule. In Linux, files don’t need to have an extension, but they are required to have an shebang.

The shebang is the first line in a script which tells the shell what program to interpret the script with, when executed.

Here’s an example:

~ # more /root/blockip.sh
#!/bin/bash

As you can see, the first line in the script tells us that this is a BASH script.

So, how can we run a script ?

First you need to check the permissions of the script:

~ # ls -l /root/blockip.sh
-r--r--r   1 root     root          156 Jun  1 20:12 /root/blockip.sh
root@nyxware#

In order to execute a script, the user under which the script needs to be executed has to have execution permissions, and the above one doesn’t have that permissions and this is how you can fix it:

chmod + x ./blockip.sh

No check the permissions again:

~ # ls -l /root/blockip.sh
-rwxrwxrwx   1 root     root          156 Jun  1 20:12 /root/blockip.sh
root@nyxware

The permissions are ok now.

Now you can run the script by typing:

root@nyxware
~ # ./blockip.sh
OK
root@nyxware

Alternatively, you can run the same script with it’s absolute path:

root@nyxware
~ # /root/blockip.sh
OK
root@nyxware

A python script can be run like this:

~ # python test.py
Usage: test.py server [options]

Test for SSL heartbeat vulnerability (CVE-2014-0160)

Options:
  -h, --help            show this help message and exit
  -p PORT, --port=PORT  TCP port to test (default: 443)
root@nyxware

~ #

run linux script

 

 

 

 

 

 

In Perl:

root@nyxware#hello-world.pl
Hello world!

How to save iptables rules

iptables is a Linux application built for the purpose to allow a system administrator to configure and maintain specific tables/rules provided by the Linux kernel firewall module.
There are currently 3 different kernel modules build for the IPv4, IPv6 and ARP stack protocols (iptables is used for IPv4, ip6tables refferes to IPv6, arptables to Addres Resolution Protocol).

The most used and the one used in this tutorial is iptables. In order to execute iptables related commands you need root privileges or to be in the sudoers file in Debian/Ubuntu OSes.

 

The syntax used to check the iptables service status is:

service iptables status  ##CentOS, Redhat
sudo iptables -L -n -v   ##Debian, Ubuntu

 

To start iptables:

service iptables start ##CentOS, Redhat
sudo ufw enable ##Ubuntu

 

To list iptables rules:

iptables -L

 

Save iptables rules:

iptables-save  #Debian
sudo iptables-save  #Ubuntu
service iptables save #CentOS

On CentOS, for example, you would see an output like this:

iptables save

 

 

 

 

To restore iptables rules:

~ # iptables-restore &lt; /etc/sysconfig/iptables
root@nyxware
~ #

Autostart services in Linux

chkconfig is a simple command-line tool that helps a Linux administrator configure,  maintain,  autostart and manage the configuration of the symlinks located in /etc/rc[0-6].d path.

First of all let me show you which are the most used services in a Linux distributuion.

You can find out what services can be started in your server by typing:

chkconfig --list

The output should look something like this:

~ # chkconfig --list
acpid           0:off   1:off   2:on    3:on    4:on    5:on    6:off
cgconfig        0:off   1:off   2:off   3:off   4:off   5:off   6:off
cgred           0:off   1:off   2:off   3:off   4:off   5:off   6:off
cmdavd          0:off   1:off   2:off   3:off   4:off   5:off   6:off
cmdmgd          0:off   1:off   2:off   3:off   4:off   5:off   6:off
crond           0:off   1:off   2:on    3:on    4:on    5:on    6:off
htcacheclean    0:off   1:off   2:off   3:off   4:off   5:off   6:off
httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off
ip6tables       0:off   1:off   2:on    3:on    4:on    5:on    6:off
iptables        0:off   1:off   2:on    3:on    4:on    5:on    6:off
mailman         0:off   1:off   2:on    3:on    4:on    5:on    6:off
mdmonitor       0:off   1:off   2:on    3:on    4:on    5:on    6:off
mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off
named           0:off   1:off   2:on    3:on    4:on    5:on    6:off
netconsole      0:off   1:off   2:off   3:off   4:off   5:off   6:off
netfs           0:off   1:off   2:off   3:on    4:on    5:on    6:off
network         0:off   1:off   2:on    3:on    4:on    5:on    6:off
ntpd            0:off   1:off   2:off   3:off   4:off   5:off   6:off
ntpdate         0:off   1:off   2:off   3:off   4:off   5:off   6:off
portreserve     0:off   1:off   2:on    3:on    4:on    5:on    6:off
psa             0:off   1:off   2:on    3:on    4:on    5:on    6:off
qmail           0:off   1:off   2:on    3:on    4:on    5:on    6:off
rdisc           0:off   1:off   2:off   3:off   4:off   5:off   6:off
restorecond     0:off   1:off   2:off   3:off   4:off   5:off   6:off
rsyslog         0:off   1:off   2:on    3:on    4:on    5:on    6:off
saslauthd       0:off   1:off   2:off   3:off   4:off   5:off   6:off
spamassassin    0:off   1:off   2:on    3:on    4:on    5:on    6:off
squid           0:off   1:off   2:off   3:off   4:off   5:off   6:off
sshd            0:off   1:off   2:on    3:on    4:on    5:on    6:off
xinetd          0:off   1:off   2:on    3:on    4:on    5:on    6:off

xinetd based services:
        chargen-dgram:  off
        chargen-stream: off
        daytime-dgram:  off
        daytime-stream: off
        discard-dgram:  off
        discard-stream: off
        echo-dgram:     off
        echo-stream:    off
        ftp_psa:        on
        poppassd_psa:   on
        rsync:          off
        smtp_psa:       on
        smtps_psa:      on
        submission_psa: on
        tcpmux-server:  off
        time-dgram:     off
        time-stream:    off

The left column contains the name of the process, to the right you have 7 columns, each one represents a Linux runlevel. Usually you will use runlevels 3,4,5. Runlevel 0 and 6 are related to shutdown (0) and reboot (6), so you should never use these.

The “on” and “off” reffer to the fact that a specific service will autostart (on) or will not autostart (off) after a reboot of the server.

The manual of chkconfig can be accesed via the command:

~ # chkconfig --help
chkconfig version 1.3.49.3 - Copyright (C) 1997-2000 Red Hat, Inc.
This may be freely redistributed under the terms of the GNU Public License.usage:   chkconfig [--list] [--type ] [name]
         chkconfig --add 
         chkconfig --del 
         chkconfig --override 
         chkconfig [--level ] [--type ]  &lt;on|off|reset|resetpriorities&gt;
root@nyxware~ #

To autostart a service after each reboot you would use a command like this:

chkconfig --level 345 httpd on

or just

chkconfig httpd on

To stop a process from starting after each reboot enter the command:

chkconfig httpd off

or stop it from running at a specific runlevel:

# chkconfig --level 3 httpd off
root@nyxware#

Use grep to see the status of a specific service:

~ # chkconfig --list | grep ssh
sshd            0:off   1:off   2:on    3:on    4:on    5:on    6:off
root@nyxware
~ #

  * replace httpd with your desired service name.

Show only specific columns in Linux log files

To troubleshoot specific application errors, a sysadmin needs to check his logs for warning, errors or other useful information.
However, most server logs are quite unreadable or contain too much information. This kind of situation is unacceptable and you need to extract only specific columns from that log.
Let’s say you are checking the Apache error log and you want to extract only a specific column. I’m trying to search the log for the word error, the display the IP’s that are getting that error and count how many times the error occurs per IP.
Here’s how you can do it.

First you need to find out where the Apache log file is. In my case it is /etc/httpd/logs/error_log (Redhat, CenOS). If you use Debian or Ubuntu the location will be /var/log/apache2/error.log.

Now that you know the log location, put the path in the command below:

cat /etc/httpd/logs/error_log | grep error | cut -d" " -f8 | uniq -c | sort

You should see something like this:

[root@nyx ~]# cat /etc/httpd/logs/error_log | grep error | cut -d" " -f8 | uniq -c | sort
      1 109.166.141.29]
      1 111.162.148.116]
      1 118.113.227.137]
      1 166.78.10.25]
      1 187.33.2.88]
      1 207.46.13.77]
      1 66.249.78.221]
      1 66.249.78.3]
      6 61.19.246.190]
      6 95.111.68.120]

So, the command syntax is pretty simple: I concatenate the log file, match the “error” word, then print the 8th column, remove duplicates, count the occurrence per IP and sort the list. Voila!

Now you know which IPs are receiving errors when they are visiting your site. You might want to do some checks and see what the problem is. Maybe those IPs are just running bots that are searching for vulnerabilities and it might be a good idea to block them in your firewall.