Posts Tagged ‘shell script’

Linux: How to change recursively directory permissions to executable (+x) flag

Monday, September 2nd, 2013

change recursively permissions of directories and subdirectories Linux and Unix with find command
I had to copy large directory from one Linux server to windows host via SFTP proto (with WinSCP). However some of directories to be copied lacked executable flag, thus WinSCP failed to list and copy them.

Therefore I needed way to set recursively, all sub-directories under directory /mirror (located on Linux server) to +x executable flag.

There are two ways to do that one is directly through find cmd, second by using find with xargs
Here is how to do it with find:

# find /mirror -type d -exec chmod 755 {} + Same done with find + xargs:

# find /path/to/base/dir -type d -print0 | xargs -0 chmod 755
To change permissions only to all files under /mirror server directory with find

# find /path/to/base/dir -type f -exec chmod 644 {} +

Same done with find + xargs:
# find /path/to/base/dir -type f -print0 | xargs -0 chmod 644

Also, tiny shell script that recursively changes directories permissions (autochmod_directories.sh) is here

Generating Static Source Code Auditing reports with Spike PHP Security Audit Tool

Saturday, April 24th, 2010

I’m conducting a PHP Audit on a server in relation to that one of the audit criterias I follow is a
Static PHP Source Code Auditing of the php files source code located physically on the Linux server.
Auditing a tons of source code manually is a kind of impossible task, therefore I needed a quick way to at least
partly automate or fully automate the PHP applications source code.
A quick search in Google pointed me to a php application tool – Spike Security Audit .
This small application PHP written app is quite handy. It is able to either check a certain php source code file for WARNINGS or ERRORS or do a complete security source code analysis of a bunch of PHP files in a directory including all the other php source files in subdirectories.

After executed the PHP Security Audit Tool generates a nice source code analysis report in html that can easily be later observed with some Browser.

The use of the tool is pretty straight forward, all you have to do is download it from Spikeforge – the project’s official webpage and unzip it e.g.


debian-server:~# wget http://developer.spikesource.com/frs/download.php/136/spike_phpSecAudit_0.27.zip
debian-server:~# unzip spike_phpSecAudit_0.27.zip

Then you have to invoke the run.php with the php cli, that you need to have installed first.
If you don’t have the php cli yet please install it with the command:


debian-server:~# apt-get install php5-cli

Now you have to execute the run.php script bundled with the spike php security audit program source code.


debian-server:~# php run.php

Please specify a source directory/file using –src option.

Usage run.php options

Options:
–src Root of the source directory tree or a file.
–exclude [Optional] A directory or file that needs to be excluded.
–format [Optional] Output format (html/text). Defaults to ‘html’.
–outdir [Optional] Report Directory. Defaults to ‘./style-report’.
–help Display this usage information.

As you can see the spike php security audit has only few command line options and they’re quite easily understandable.
However in my case I had to audit a couple of directories which contained source code.
I also wanted the generated reports to be cyclic, on let’s say per daily basis cause I wanted to have the PHP applicaiton analysis generated on a daily basis.
In that reason I decided to write a small shell script that would aid the usage of php spike audit, I’ve called the script code-analysis.sh

The usage of the Automation source code analysis script for PHP Spike Audit can be downloaded here
The script has a few configuration options that you might need to modify before you can put it to execute on a crontab.

This are:


# Specify your domain name on which php spike audit reports will be accessed
domain_name='yourdomainname.com';
# put here the location where phpspike run.php execute is located
spike_phpsec=/usr/local/spike_phpSecAudit_0.27/run.php;
# specify here which will be the directory where the php source code analysis reports will be stored by php spike
log_dir=/root/code-analysis/;
# in that part you have to specify the physical location of the php cli it's located by default in /usr/bin/php on Debian GNU Linux.
php_bin=/usr/bin/php;
# the directory below should be set to a directory where the reports that will be visible from the webserver will be stored
www_dir=/var/www/code-analysis;

# in the variables

directory[1]=’/home/source-code1/’; ..
directory[2]=”; ..

# you should configure the directories containing php source code to be audited by the php spike audit tool.

After you have prepared the code-analysis.sh script with your custom likings, you can now put it to be executed periodically
using crontab or some other unix system scheduler of choice.

To do that edit your root crontab.

crontab -u root -e

and put in it.

# code analysis results
05 3 * * * /usr/local/bin/code-analysis.sh >/dev/null 2>&1

Now hopefully you can edit your /etc/apache2/apache2.conf or your httpd.conf depending on your linux or unix architecture and make a Alias like:


Alias /code-analysis "/var/www/code-analysis"

Now your php source code analysis from the php spike audit tool will be generated daily.
You will be able to access them via web using http://yourdomain.com/code-analysis/

That way, you can review your php source code written or changed in your php applications on daily basis and you can a way easily track your coding mistakes, as well as track for possible security issues in your code.

For the sake of security I’ve also decided to protect the /code-analysis Apache directory with a password using the following .htaccess file:


AuthUserFile /var/www/code-analysis/.htpasswd
AuthGroupFile /dev/null
AuthName "Login to access PHP Source Code Analysis"
AuthType Basic

< Limit GET >
require valid-user
< /Limit >

If you decide to protect yours as well you have to also generate the .htpasswd file using the following command:


debian-server:~# htpasswd -c /var/www/code-analysis/.htpasswd admin

You will be asked for a password. The code-analysis.sh script will also take care to generate an html file for you including links to reports to all the php source code audited directories reports.

Now accessing http://yourdomain.com/code-analysis/ will give you shiny look to the php source applications generated reports .

Run 2 and more Skypes simultaneously on Mac OS X – Run multiple Skype acccounts on same Mac

Saturday, June 21st, 2014

run-2-and-more-skypes-simultaneously-on-mac-os-x-multiple-skype-account-login-on-mac
For people running Mac OS X, the question of 
how is it possible to use 2 skype accounts in parallel on Mac probably makes good sense?

I don't own a Mac notebook and thefore I'm a Mac newbie, however, I'm into situation where I and my wife Svetlana went (for 3 days) to my hometown Dobrich and we have with us only her Mac OS X powered Mac Book air.

 

One user is already logged in Skype, (my wife) is expecting some relatives and friends to contact us and  same time I had to login to check few servers via ssh and discuss some server downtime issues from yesterday in Skype .
Thus we
need 2 skype instances to run separately on her Macbook air powered PC with Mac OS X Leopard
 

Earlier I've blogged how to make 2 and more Skype accounts work simultaneously on one Windows PC because I had to set it up for a company, in this short article I will explain how is possible to run many skype clients on Mac OS X.

 

1. Open Mac Terminal from Finder

finder-terminal-screenshot-mac-os-x-leopard-run-many-skypes-mac-os

2. In Terminal run the first Skype Instance

Type in Terminal:

open /Applications/Skype.app/Contents/MacOS/Skype

3. Run Second Skype instance

In older Skype Mac OS versions, I read the

/secondary

Skype command option was there and could be used to run a second parallel skype instance on Mac, however in newer releases this option was removed and if you try to invoke it warning window pops up saying an instance is already running.

mac-os-x-you-have-another-copy-of-skype-running-screenshot

To get around the issue and run the second Skype, quickest way is to run another Skype client under privileged user through sudo command (this is unsecure – but anyways as Mac OS is proprietary and we don't have access to code and probably there are tons of spy and report software integrated into the OS, it doesn't really matter.)

mac-os-x-skype-run-screenshot-pic

To get around the issue and run the second Skype, quickest way is to run another Skype client under privileged user through sudo command (this is unsecure – but anyways as Mac OS is proprietary and we don't have access to code and probably there are tons of spy and report software integrated into the OS, it doesn't really matter.)

4. Script it into 2nd_skype.sh for later use

To run and use two parallel skypes regularly it might be useful to make shell script out of it and place it somewhere, 2nd_skype.sh script should be something like:


#!/bin/bash
open /Applications/Skype.app/Contents/MacOS/Skype
sudo /Applications/Skype.app/Contents/MacOS/Skype

Then make the script executable with:

chmod a+x 2nd_skype.sh

5. Run more than 2 Skypes (Run multiple Skypes on same Mac PC hack)

There is another "hack" method with deleting the Skype.pid (Process ID). Skype recognize where it is running by checking its Skype.pid on start up.

Deleting the pid after each next Skype client launch,  allow the user to run as many Skypes as you want on Mac OS X but it is not clear for how long it time it will work.

rm -f ~/Library/Application Support/Skype/Skype.pid

Then launch again Skype in background from Mac Terminal

open -nW '/Application/Skype.app' &

In case if you wonder why the open command is used, since above line could be run also directly and Skype will pop-up, by using open command you instruct the program to detach itself from Terminal from which it run, so later if Terminal is closed Skype app. will not terminate.

Another approach is to create, a many users lets say 5 users and use the Skype sudo run method each client with a separate user.

sudo user1 /Applications/Skype.app/Contents/MacOS/Skype
sudo user2 /Applications/Skype.app/Contents/MacOS/Skype
sudo user3 /Applications/Skype.app/Contents/MacOS/Skype
sudo user4 /Applications/Skype.app/Contents/MacOS/Skype

sudo user5 /Applications/Skype.app/Contents/MacOS/Skype

I enclose the script with the custom icon (Skype) ready to be launched and Voila, on script launch Skype multiple login prompts pops up.

For the lazy ones who don't want to tamper with writting scripts or doing hacks to run Skype multiple times on Mac there is even a Multi Skype Launcher app for Mac.

 


 

How to set a crontab to execute commands on a seconds time interval on GNU / Linux and FreeBSD

Sunday, October 30th, 2011

crontab-execute-cron-jobs-every-second-on-linux-cron-logo
Have you ever been in need to execute some commands scheduled via a crontab, every let’s say 5 seconds?, naturally this is not possible with crontab, however adding a small shell script to loop and execute a command or commands every 5 seconds and setting it up to execute once in a minute through crontab makes this possible.
Here is an example shell script that does execute commands every 5 seconds:

#!/bin/bash
command1_to_exec='/bin/ls';
command2_to_exec='/bin/pwd';
for i in $(echo 1 2 3 4 5 6 7 8 9 10 11); do
sleep 5;
$command1_to_exec; $command2_to_exec;
done

This script will issue a sleep every 5 seconds and execute the two commands defined as $command1_to_exec and $command2_to_exec

Copy paste the script to a file or fetch exec_every_5_secs_cmds.sh from here

The script can easily be modified to execute on any seconds interval delay, the record to put on cron to use with this script should look something like:

# echo '* * * * * /path/to/exec_every_5_secs_cmds.sh' | crontab -

Where of course /path/to/exec_every_5_secs_cmds.sh needs to be modified to a proper script name and path location.

Another way to do the on a number of seconds program / command schedule without using cron at all is setting up an endless loop to run/refresh via /etc/inittab with a number of predefined commands inside. An example endless loop script to run via inittab would look something like:

while [ 1 ]; do
/bin/ls
sleep 5;
done

To run the above sample never ending script using inittab, one needs to add to the end of inittab, some line like:

mine:234:respawn:/path/to/script_name.sh

A quick way to add the line from consone would be with echo:

echo 'mine:234:respawn:/path/to/script' >> /etc/inittab

Of course the proper paths, should be put in:

Then to load up the newly added inittab line, inittab needs to be reloaded with cmd:

# init q

I've also red, some other methods suggested to run programs on a periodic seconds basis using just cron, what I found in stackoverflow.com's  as a thread proposed as a solution is:

* * * * * /foo/bar/your_script
* * * * * sleep 15; /foo/bar/your_script
* * * * * sleep 30; /foo/bar/your_script
* * * * * sleep 45; /foo/bar/your_script

One guy, even suggested a shorted way with cron:

0/15 * * * * * /path/to/my/script

Make daily Linux MySQL database backups with shell script

Thursday, May 23rd, 2013

Creating database backup with MySQL with mysqlbackupper and mysqlback shell scripts easy create mysql backups

Some time ago, I've written a tiny shell script which does dumps of Complete (SQL Script) MySQL databases. There are plenty of ways to backup MySQL database and plenty of scripts on the net but I like doing it my own way. I have few backup scripts. I prefer script database over keeping binary logs, or using some un-traditional backup methods like backing all binary data in /var/lib/mysql.

One was intended to backup with mysqldump whole database and later upload to a central server running tsh (shell). Using tsh maybe not the best method to upload, but the script can easily be modified to use ssh passwordless authentication as a method to upload.

I'm not a pro shell scripter, but MySQLBackupper script can be used as useful for learning some simple bash  shell scripting.

To use the script as intended you will have to build tsh from source. Tsh is in very early development stage (ver 0.2) but as far as I tested it before some years it does great what it is intended for. You can  MySQLBackupper.sh script from here.
Earlier, I used MysqlBackupper.sh to upload all SQL dumps to /backups directory on central backup storage server, thus I had written secondary script to classify uploaded backups based on backup archive name. Script used is mysqldumps-classify.sh and can be viewed here. Though this way of making backups, needs a bit of custom work for managing backups up to 10 / 20 servers it worked well.

I have written also another mysqlbackup script which is much more simplistic and only dumps with mysqldump and stores copies on hard disk in tar.gz archive. You can download my other simple mysqkbackup.sh here.

Only inconvenient thing about above scripts is they dump all SQL databases. Hence whether necessary to get content for single database from (complete) All database SQL (script backup), I use SED (stream editor) one liner script.

It is interesting to hear how others prepare their MySQL db backups.

screen -d Fix “Must run suid root for multiuser support.” su user detach error

Thursday, March 28th, 2013

I had to run a shell script to run automatically in detached screen during Linux system boot up via /etc/rc.local. This is needed because the server uses the tiny shell script to fetch data from remote host database and fill information into local MySQL server.

My idea was to su from root to www-data (Apache) user – the script has requirements to run with Apache user, then it has to run detached using GNU screen (multi terminal emulator. The tiny one line script I imagined would do the trick is like so:

# tty=$(tty); su www-data -c 'cd /home/user/www/enetpulse; screen -d /home/user/www/enetpulse/while_true.sh'; chmod 0720 $tty

I run this as root user to test whether it will work or not before I put it in /etc/rc.local but for my surprise got an error:
 

Must run suid root for multiuser support.

After a quick investigation on what is causing it I came across the solution which is to include screen arguments (-m -S shared). The working variant that gets around the error – i.e. successfully changes user privileges to Debian Apache user (www-data) and then detach with screen is:

# tty=$(tty); chmod a+rw $tty; su www-data -c 'cd /home/user/www/enetpulse; screen -d -m -S shared /home/user/www/enetpulse/while_true.sh'; chmod 0720 $tty;

That's all now script works out as planned on next server reboot

Convert WAV to MP3 in command line with LAME on Linux

Friday, April 8th, 2011

I needed to convert a bunch of files from WAV to MP3 format on my Linux desktop.

I’ve placed all my wav files to the directory /home/hipo/wav

And then I issued the small one liner script to convert the .wav files to .mp3 using the niftly lame linux mp3 convertor.

Here is how I did it:

linux-desktop:~$ cd wav
linux-desktop:/home/hipo/wav$ for i in *.wav; do
new_name=$(echo $i |sed -e 's#wav#mp3#g');
lame -V0 -h -b 160 --vbr-new "$i" "$new_name";
done

After executing the little script you might go and have a coffee, if you have thousands of files, each file convertion takes about 10-15 seconds of time (speed depends on your CPU).

Here is some output from a lame convertion to mp3 taking place:

Encoding as 8 kHz single-ch MPEG-2.5 Layer III VBR(q=0)
Frame | CPU time/estim | REAL time/estim | play/CPU | ETA
27237/27237 (100%)| 0:12/ 0:12| 0:12/ 0:12| 155.89x| 0:00
64 [27237] ***************************************************************
----------------------------------------------
kbps mono % long switch short %
64.0 100.0 84.1 8.9 7.0
If you want to save my convertion quickly for a later, download my Convert WAV to mp3 from a directory with lame shell script here

Actually there are plenty of other ways to convert wav to mp3 on Linux through mplayer, ffmpeg even with mpg123.

There are also some GUI programs that could do the convertion like winff , however for some weird reason after installing WinFF on my debian it was not able to complete convertion to mp3?!
But it doesn’t matter, the good news is I did what I wanted to via the simple lame program and the above script, hope it helps somebody out there.

Script to Automatically change current MySQL server in wp-config.php to another MySQL host to minimize WordPress and Joomla downtimes

Friday, July 20th, 2012

I'm running a two servers for a couple of home hosted websites. One of the servers is serving as Apache host1 and has configured MySQL running on it and the second is used just for database host2 – (has another MySQL configured on it).
The MySQL servers are not configured to run as a MySQL MASTER and MySQL SLAVE (no mysql replication), however periodically (daily), I have a tiny shell script that is actualizing the data from the active SQL host2 server to host1.

Sometimes due to electricity problems or CPU overheats the active MySQL host at host2 gets stoned and stops working causing the 2 WordPress based websites and One joomla site inaccessible.
Until I manually get to the machine and restart host2 the 3 sites are down from the net and as you can imagine this has a very negative impact on the existing website indexing (PageRank) in Google.

When I'm at home, this is not a problem as I have physical access to the servers and if somethings gets messy I fix it quickly. The problem comes, whether I'm travelling or in another city far from home and there is no-one at home to give the hanged host hard reboot ….

Lately the problems with hang-ups of host2 happaned 3 times or so for 2 weeks, as a result the websites were inaccessible for hours and since there is nobody to reboot the server for hours; the websites keep hanging until the DB host is restarted ;;;;

To work-around this I came with the idea to write a tiny shell script to check if host2 is ping-able in order to assure the Database host is not down and then if script determines host2 (mysql) host is down it changes wp-config.php (set to use host2) to a wp-config.php (which I have beforehand configured to use) host1.

Using the script is a temporary solution, since I have to actually find the real hang-up causing troubles, but at least it saves me long downtimes. Here is a download link to the script I called change_blog_db.sh .
I've configured the script to be run on the Apache node (host1) via a crontab calling the script every 10 minutes, here is the crontab:
 

*/10 * * * * /usr/sbin/change_blog_db.sh > /dev/null 2>&1

The script is written in a way so if it determins host2 is reachable a copy of wp-config.php and Joomla's configuration.php tuned to use host2 is copied over the file config originals. In order to use the script one has to configured the head variables script section, e.g.:

host_to_ping='192.168.0.2';
blog_dir='/var/www/blog';
blog_dir2='/var/www/blog1';blog_dir3='/var/www/joomla';
notify_mail='hipo@www.pc-freak.net';
wp_config_orig='wp-config.php';
wp_config_localhost='wp-config-localhost.php';
wp_config_other_host='wp-config-192.168.0.2.php';
joomla_config_orig='configuration.php';
joomla_config_other_host='configuration-192.168.0.2.php';

You will have to manually prepare;;;

wp-config-localhost.php, wp-config-192.168.0.2.php ,configuration-192.168.0.2.php, wp-config-localhost.php to be existing files configured to with proper host1 and host2 IP addresses.
Hope the script will be useful to others, experiencing database downtimes with WordPress or Joomla installs.
 

Check and Restart Apache if it is malfunctioning (not returning HTML content) shell script

Monday, March 19th, 2012

Check and Restart Apache Webserver on Malfunction, Apache feather logo

One of the company Debian Lenny 5.0 Webservers, where I'm working as sys admin sometimes stops to properly server HTTP requests.
Whenever this oddity happens, the Apache server seems to be running okay but it is not failing to return requested content

I can see the webserver listens on port 80 and establishing connections to remote hosts – the apache processes show normally as I can see in netstat …:

apache:~# netstat -enp 80
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
tcp 0 0 xxx.xxx.xxx.xx:80 46.253.9.36:5665 SYN_RECV 0 0 -
tcp 0 0 xxx.xxx.xxx.xx:80 78.157.26.24:5933 SYN_RECV 0 0 -
...

Also the apache forked child processes show normally in process list:

apache:~# ps axuwwf|grep -i apache
root 46748 0.0 0.0 112300 872 pts/1 S+ 18:07 0:00 \_ grep -i apache
root 42530 0.0 0.1 217392 6636 ? Ss Mar14 0:39 /usr/sbin/apache2 -k start
www-data 42535 0.0 0.0 147876 1488 ? S Mar14 0:01 \_ /usr/sbin/apache2 -k start
root 28747 0.0 0.1 218180 4792 ? Sl Mar14 0:00 \_ /usr/sbin/apache2 -k start
www-data 31787 0.0 0.1 219156 5832 ? S Mar14 0:00 | \_ /usr/sbin/apache2 -k start

In spite of that, in any client browser to any of the Apache (Virtual hosts) websites, there is no HTML content returned…
This weird problem continues until the Apache webserver is retarted.
Once webserver is restarted everything is back to normal.
I use Apache Check Apache shell script set on few remote hosts to regularly check with nmap if port 80 (www) of my server is open and responding, anyways this script just checks if the open and reachable and thus using it was unable to detect Apache wasn't able to return back HTML content.
To work around the malfunctions I wrote tiny script – retart_apache_if_empty_content_is_returned.sh

The scripts idea is very simple;
A request is made a remote defined host with lynx text browser, then the output of lines is counted, if the output returned by lynx -dump http://someurl.com is less than the number returned whether normally invoked, then the script triggers an apache init script restart.

I've set the script to periodically run in a cron job, every 5 minutes each hour.
# check if apache returns empty content with lynx and if yes restart and log it
*/5 * * * * /usr/sbin/restart_apache_if_empty_content.sh >/dev/null 2>&1

This is not perfect as sometimes still, there will be few minutes downtime, but at least the downside will not be few hours until I am informed ssh to the server and restart Apache manually

A quick way to download and set from cron execution my script every 5 minutes use:

apache:~# cd /usr/sbin
apache:/usr/sbin# wget -q https://www.pc-freak.net/bscscr/restart_apache_if_empty_content.sh
apache:/usr/sbin# chmod +x restart_apache_if_empty_content.sh
apache:/usr/sbin# crontab -l > /tmp/file; echo '*/5 * * * *' /usr/sbin/restart_apache_if_empty_content.sh 2>&1 >/dev/null