Change Unix File Permissions Using C

March 26, 2011 Leave a comment

This is a small program written in C used to change permissions of files in Unix.

You may ask why would someone want to use a C snippet instead of a quick “chmod” shell script?

Well, a simple “chown” script works just fine for cases where you don’t have a ridiculously large amount of files. Things get painfully slow when besides having millions of files you also have millions of directories. In those rare cases there is nothing faster than C.

If you have a 64 bit operating system you can compile this code with “-m64″ flag for better performance.

#include
#include
#include
#include

#define PATH "/export/home/egloo"
#define UID 501
#define GID 501
#define NOTIFICATION_INTERVAL 10000

int file_count = 0;
char cmd[128];

static int callback(const char *fpath, const struct stat *sb, int typeflag) {
// Check if it's a file or a directory
if (typeflag == FTW_D || typeflag == FTW_F) {

// Apply new permissions
chown(fpath, UID, GID);

// Send progress notification
file_count++;
if ( 0 == ( file_count % NOTIFICATION_INTERVAL ) ){
fprintf( stderr, "%ld\n", file_count );
sprintf(cmd,"/bin/echo \"%i files processed\" | /bin/mail -s \"CHOWN PROGRESS\" user@domain.com", file_count);
system(cmd);
}
}

// Continue FTW
return 0;
}

int main(int argc, char **argv) {
ftw(PATH, callback, 256);
}

Make GNOME use Xscreensaver instead of Gnome Screensaver

January 22, 2009 2 comments

xscreensaverAs you may know, Gnome comes preinstalled with a few catalog of basic screensavers: Gnome Screensaver which is the default screen saver and locker in a Gnome desktop. It is designed with simplicity and security in mind.

For this reason many useres prefer to use xscreensaver wich is a better, more secure and universally accepted screensaver program for Unix-like operating systems.

In fact xscreensaver can be found installed by default on some Linux distributions like Ubuntu and latest versions of SUSE, but there are still Red Hat based systems that do not install this packages.

To install xscreensaver you can use the standard repositories from your specific OS.

Red Hat based:
su -c "yum install xscreensaver"

Debian based:
sudo apt-get install xscreensaver

Now xscreensaver is installed, we launch the configuration screen by typing xsreensaver-demo on a console or by clicking on System > Preferences > Look and Feel > Screensaver. This will pop a message asking you to deactivate the gnome-screensaver daemon which should be fine.

xscreensaver

Select the screensaver design of your choice, hit the Preview button and close the dialog box when you’re done.

At this point, the screensaver should lock automatically after the defined inactive time, BUT it wont work if you want to activate it manally by pressing Ctrl+Alt+L or System > Lock Screen. This is because even when you defined xscreensaver as the default application, gnome is still looking for the old daemon in order to activate the screensaver.

To solve this problem open a terminal as root and issue the following command:

ln -sf /usr/bin/xscreensaver-command \
/usr/bin/gnome-screensaver-command

Now you can lock your screen and start xscreensaver with the standard gnome commands. :)

Categories: Gnome, Xserver Tags: ,

Connect Through SSH Without a Password

December 10, 2008 Leave a comment

lockpickOne day, you will find yourself trying to execute  a command on a remote UNIX box without the need of typing the password. The basis of using this technique relies on public keys which are a kind of digital signatures.

Let’s supose we have a server named “Mailserver” and another server called “Monitor” and you want Monitor to connect every 30 minutes to Mailserver and verify the health of some services.

Anyway, here is the quick-guide:

First of all connect to Monitor with the user of you choice.

Then,  type:

ssh-keygen -t rsa
This command will create the RSA public key of the current user. You will be asked to type a passphrase but it’s not necesary at all; You can just ignore it.

When the command finishes execution, a message will appear telling you the location of the new files. In most cases it is placed in the .ssh/ directory inside your home/ path.

Next, you’ll have to copy the public they to the authorized_keys2 file on the remote server (in this case Mailserver). To make it simple, here is the command (Remember to substitute user and hostname with your own):

scp ~/.ssh/id_rsa.pub user@hostname:~/.ssh/authorized_keys2
This will the last time you’ll prompted to type the password. When the transfer finishes, you should be able to ssh from Monitor to Mailserver without being prompted for a pass. :)

NOTE: On some UNIX like Solaris the default location of the public-keys can vary from system to system.

NOTE 2: You must have RSAAuthentication yes in your /etc/ssh/sshd_config file. On many Linux installations this setting is commented out in a default install.

Categories: networking, ssh Tags: ,

How to Read MySQL Binary Logs

November 19, 2008 4 comments

mysqllogoMySQL database server utilizes a transaction log to track all of the modifications performed within the databases. This log ensures both that the database is able to recover when abruptly interrupted (such as a loss of power) and that users are able to undo (or “rollback” in database language) the results of a database transaction. Except for the cases where the administrator has disabled or commented out the log-bin parameter in my.cfg file, this log is generated by default. As the name implies, binary log (transaction log) files are written in binary format, but sometimes you may need to examine the content of the transaction logs in text format, where the mysqlbinlog utility will come in handy.

A binlog file normally is named hostname-bin.xxxxx and stored in /var/lib/mysql directory. It cannot be opened and read straight away as it’s a binary file so we can make use of mysqlbinlog command.

For example, to display the contents of the binary log file named localhost-bin.000004, use this command:

mysqlbinlog localhost-bin.000004

The output includes all events contained in localhost-bin.000004. Event information includes the statement executed, the time the statement took, the thread ID of the client that issued it, the timestamp when it was executed, and so forth.

The binlogs are likely to be very huge thus making it almost impossible to read anything on screen. However, you can pipe the output into a file which can be open up for later browsing in text editor:

mysqlbinlog localhost-bin.000004 > filename.txt

To reduce the amount of data retrieved from binary logs, there are several options that can be used to limit the data that is been returned. Among the useful ones are listed below:

–start-datetime=[DATETIME]

–stop-datetime=[DATETIME]

The datetime value is relative to the local time zone on the machine where you run mysqlbinlog. The value should be in a format accepted for the DATETIME or TIMESTAMP data types. For example:

mysqlbinlog --start-datetime="2008-05-22 00:00:00" --stop-datetime="2008-05-29 00:00:00" localhost-bin.000004

For more information, you can take a look at the official mysqlbinlog documentation.

Categories: Databases Tags: ,

Share Keyboard and Mouse with Synergy

November 12, 2008 1 comment

synergy_logoIt’s very usual for a Linux user to work with multiple monitors and machines; It gives a lot of flexibility and a big boost to our performance. But switching between the different keyboards and mice can be a bit tedious.

 

For this purpose there is a hardware device that allows you to control multiple computers from a single keyboard, video monitor and mouse: a KVM switch. KVM switches are today difficult to find and not very cheap.

 

Fortunately there is a software approach to KVM switches: Synergy.

 

Synergy is used in situations where several PCs are used together, with a monitor connected to each, but are to be controlled by one user. You need only one keyboard and mouse on the desk.

 

Synergy runs on Windows, Linux and MacOS X in command line mode. There are also some cool GUIs like SynergyKM for MacOS X, QuickSynergy for Linux and MacOS X, and the self Synergy GUI for Windows.

 

The configuration can be done from the command line but trust me, having such great and minimalistic GUIs out there you don’t want to do that.

 

syn_example1

 

Okay, okay the main reason why this blog entry does not cover the internal commands is because there is already an excellent documentation that explains step by step the commands you can use with Synergy… You know, why reinventing the wheel.

Categories: KVM Tags: ,

Linux Cached Memory

October 29, 2008 11 comments

In Linux, reading from a disk is very slow compared to accessing real memory. In addition, it is common to read the same part of a disk several times during relatively short periods of time. For example, one might first read an e-mail message, then read the letter into an editor when replying to it, then make the mail program read it again when copying it to a folder. Or, consider how often the command ls might be run on a system with many users. By reading the information from disk only once and then keeping it in memory until no longer needed, one can speed up all but the first read. This is called disk buffering, and the memory used for the purpose is called the buffer cache.

Unlike Windows other operating systems, Linux administers memory the smartest way it can.

Since unused memory is next to worthless, the filesystem takes whatever memory is left and caches it in order to speed up disk access. When the cache fills up, the data that has been unused for the longest time is discarded and the memory thus freed is used for the new data.

Whenever an application needs memory, the kernel makes the cache smaller; You do not need to do anything to make use of the cache, it happens completely automatically.

Freeing memory buffer does not make your programs faster… Actually it makes disk access slower.

BUT if for some reason (kernel debugging for example) you want to force the buffer to be freed, you need to set the drop_caches value to 1:

$ echo 1 > /proc/sys/vm/drop_caches

Issuing this command will release all the cached memory and also will stop collecting I/O buffer blocks. Let’s see an example of the effect:

Under normal situations, most of the memory is already cached by the system. But if we force the system to free the memory, you can see in the graph how the memory is suddenly dropped.

The technical details of how this works are explained on the Linux API

Categories: Memory Tags: ,

FTP Error Codes

October 25, 2008 2 comments

In case you are a die-hard FTP user, you should find helpful the error code reference. Normally, these codes appear in the system log files, or directly into your terminal.

120 Service ready in nnn minutes.
125 Data connection already open; transfer starting.
150 File status okay; about to open data connection.
200 Command okay.
202 Command not implemented, superfluous at this site.
211 System status, or system help reply.
212 Directory status.
213 File status.
214 Help message.On how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user.
120 Service ready in nnn minutes.
125 Data connection already open; transfer starting.
150 File status okay; about to open data connection.
200 Command okay.
202 Command not implemented, superfluous at this site.
211 System status, or system help reply.
212 Directory status.
213 File status.
214 Help message.On how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user.
215 NAME system type. Where NAME is an official system name from the list in the Assigned Numbers document.
220 Service ready for new user.
221 Service closing control connection.
225 Data connection open; no transfer in progress.
226 Closing data connection. Requested file action successful (for example, file transfer or file abort).
227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
230 User logged in, proceed. Logged out if appropriate.
250 Requested file action okay, completed.
257 “PATHNAME” created.
331 User name okay, need password.
332 Need account for login.
350 Requested file action pending further information
421 Service not available, closing control connection.This may be a reply to any command if the service knows it must shut down.
425 Can’t open data connection.
426 Connection closed; transfer aborted.
450 Requested file action not taken.
451 Requested action aborted. Local error in processing.
452 Requested action not taken. Insufficient storage space in system.File unavailable (e.g., file busy).
500 Syntax error, command unrecognized. This may include errors such as command line too long.
501 Syntax error in parameters or arguments.
502 Command not implemented.
503 Bad sequence of commands.
504 Command not implemented for that parameter.
530 Not logged in.
532 Need account for storing files.
550 Requested action not taken. File unavailable (e.g., file not found, no access).
551 Requested action aborted. Page type unknown.
552 Requested file action aborted. Exceeded storage allocation (for current directory or dataset).
553 Requested action not taken. File name not allowed.NAME system type. Where NAME is an official system name from the list in the Assigned Numbers document.
220 Service ready for new user.
221 Service closing control connection.
225 Data connection open; no transfer in progress.
226 Closing data connection. Requested file action successful (for example, file transfer or file abort).
227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
230 User logged in, proceed. Logged out if appropriate.
250 Requested file action okay, completed.
257 “PATHNAME” created.
331 User name okay, need password.
332 Need account for login.
350 Requested file action pending further information
421 Service not available, closing control connection.This may be a reply to any command if the service knows it must shut down.
425 Can’t open data connection.
426 Connection closed; transfer aborted.
450 Requested file action not taken.
451 Requested action aborted. Local error in processing.
452 Requested action not taken. Insufficient storage space in system.File unavailable (e.g., file busy).
500 Syntax error, command unrecognized. This may include errors such as command line too long.
501 Syntax error in parameters or arguments.
502 Command not implemented.
503 Bad sequence of commands.
504 Command not implemented for that parameter.
530 Not logged in.
532 Need account for storing files.
550 Requested action not taken. File unavailable (e.g., file not found, no access).
551 Requested action aborted. Page type unknown.
552 Requested file action aborted. Exceeded storage allocation (for current directory or dataset).
553 Requested action not taken. File name not allowed.

Categories: FTP Tags: ,
Follow

Get every new post delivered to your Inbox.