Archive

Posts Tagged ‘Linux’

Reading logs with a Named Pipe

November 22, 2012 Leave a comment

Recently I had to write a piece of code that constantly would read a log file and if something wrong had happened a specific action should be taken.
For this reason I wrote this piece of code in Lua using Named Pipes.
If you are not familiar with Named Pipes check them out (from Wikepedia: A named pipe is system-persistent and exists beyond the life of the process and must be deleted once it is no longer being used.).

LOG_FILE = "/path/to/the/log/file"
LOG_PIPE = "/path/to/the/log_pipe"
LOG_STR  = "A word/phrase that we are searching for on the logs"

--- Create the logs pipe
function create_log_pipe()
    print("Creating the Logs' pipe...")

    local cmd_status = os.execute("rm -f " .. LOG_PIPE .. ";" ..
        "mkfifo " .. LOG_PIPE .. ";" ..
        "tail -n1 -f " .. LOG_FILE .." > " ..LOG_PIPE .. "&")

    if cmd_status == nil then
        print("[Error] Couldn't create the Logs' Pipe")
        exit
    else
        print("Logs' pipe was created")
    end
end

--- Open the logs' pipe
-- @return the logs' pipe descriptor
function open_log_pipe()
    print("Opening the Logs' pipe...")

    local logfd, _, _ = io.open(LOG_PIPE, "r")

    if not logfd then
        print("[Error] Couldn't open the Logs' pipe.")
        exit
    else
        print("Logs' pipe has opened successfully.")
    end

    return logfd
end

create_log_pipe()
log_pipe = open_log_pipe()

for line in log_pipe:lines() do
    repeat
        if string.find(line, LOG_STR) ~= nil then
            -- do something
        end
    until true
end

Credits on this thread.

Categories: Lua, Programming Tags: ,

How to install Debian – my way

August 1, 2010 12 comments

In this post I am not going to analyse the positive or negative (there is nothing negative :P) aspects of Debian.
I suppose that you know why Debian is such a good distro (number of packages, stability, rolling distro) and you want to install Debian but you are scared of the process. Actually it isn’t as difficult as it may sound. There is the easy way that you just install everything that the installation CD tells you or you can do something like the followings. My way of installing the Debian may be a little more ( 😯 ) complex but after understanding it, the whole process will be quite automated and quick.

Read more…

Categories: Debian, Linux Tags: ,

Pexpect module for Python 2.5

May 23, 2010 Leave a comment

Today I was searching for a way to run a bash command, that needed superuser’s permissions, from a python program that I had made… The problem was that I had to find a way to interact with the bash and when I would be asked for the password, the python program would answer with it.

So after some googling I found that awesome module called Pexpect , tested in Python 2.5, that allows to your python program to control and automate other programs.

As mentioned in its official site, Pexpect is basically a pattern matching system. It runs programs and watches output. When output matches a given pattern Pexpect can respond as if a human were typing responses. So it is very useful to automate some procedures, and others like testing and screen scraping. Also Pexpect is pure Python so it works on any platform that supports the standard Python pty module.

But enough with that!
Here is the code that I was talking about:

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author         : Aravanis Konstantinos
# Author's url   : http://AravanisKostas.com
# Author's email : kos.arav@gmail.com
#
# Tested in Python 2.5.5!

import pexpect
import getpass

class suError(Exception):
    """ A new exception. It is used from the su function, if there is a
        problem.
    """
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

def su(command, password = None, prompt = "Enter SuperUser Password: ",\
        attempts = None):
    """ Function that ran a command with superuser's permissions.

        @command  : the command that must be ran with superuser's permissions
        @password : the superuser's password.
        @prompt   : the message that will be printed to inform that will ask
                    for the password, if it wasn't set.
        @attempts : the number of attempts. If it is not set then the program
                    will attempt for ever to gain the superuser's permissions.
                    If the attempts were set to zero, the program will still
                    run for a time.
    """
    # decrease the number of the remaining attempts
    if attempts:
        attempts = attempts - 1

    # if the password hadn't been given then ask for it (from the
    # command line)
    if not password:
        password = getpass.getpass(prompt)

    # the command must be ran with superuser's permissions
    child = pexpect.spawn('su -c "' + command + '"')

    # when the password is asked, send it
    choice = child.expect(['Password:'])
    child.sendline(password)

    # check to see if there was an Authentication failure or else that
    # there was no problem
    choice = child.expect(['su: Authentication failure' ,pexpect.EOF])

    # if there was an Authentication failure, ask again for the password
    if choice == 0:
        # if the max number of attempts was reached
        if attempts < 1:
            raise suError("Too Many Attempts!")

        su(command, attempts = attempts)

    # return success
    return True

And if you want to test it:

############
# test it! #
############
try:
    su("echo su_test_text > su_test_file", attempts = 3)
except suError:
    print "No other attempts left!"

Install LAMP (Linux Apache Mysql PHP) – phpmyadmin

May 30, 2009 1 comment

This mini-tutorial was written mainly for personal use. The following steps are an example of the installation with the use of apt-get package manager of Ubuntu and Debian. I think that the packages are the same with any other package manager.

  1. Update your repositories:
    • #apt-get update
  2. Install Apache and PHP:
    • #apt-get install apache2 php5 libapache2-mod-php5
  3. Install Mysql:
    • #apt-get install mysql-server mysql-client php5-mysql
  4. If you need to re-set the root password of the mysql server:
    • #mysql -u root
    • mysql> USE mysql;
    • mysql> UPDATE user SET Password=PASSWORD(‘new-password’) WHERE user=’root’;
    • mysql> FLUSH PRIVILEGES;
  5. Install phpmyadmin:
    • #apt-get install phpmyadmin
    • echo “Include /etc/phpmyadmin/apache.conf” >> /etc/apache2/apache2.conf

Now you are ready to start your webserver and build your sites etc etc

ps: Don’t forget the port forwarding: set all the ports to 80 and under TCP/UDP protocol.

Categories: Linux, Tutorials Tags: , , , , ,

Configure your Dynamic DNS (DDNS) [for linux]

May 29, 2009 1 comment

In this tutorial I will show you the steps to make your own free dynamic dns for your web server…

  1. Take a domain for your site. Free domains you can find at dyndns. You have just to create an account and then to make your own domain!
  2. Install ddclient that updates the dns with the current IP (for the linux distribution with the apt-get package manager like ubuntu and debian run the command: #apt-get install ddclient) and then make the configuration of this.
  3. For a future reconfiguration of ddclient run the command: #dpkg-reconfigure ddclient
  4. If you have a router and you don’t know how to take the current IP make a script with the name take_ip.sh that will contain the text of the bullet and  put it under $HOME directory (don’t forget to change the mod to executable: #chmod +x take_ip.sh)
  5. Now change the line use=… of the /etc/ddclient.conf file with that of the bullet in order to be found the current IP by the daemon (ddclient)
    • use=cmd, cmd=$HOME/take_ip.sh

After those steps you will have your own dynamic DNS that will be updated with your current IP every time the daemon runs (this time was set during the configuration of the ddclient).

Categories: Linux, Tutorials Tags: ,