Useful Linux commands. Some miscellaneous commands that you might find useful.

  1. Mandriva security tip.
  2. Updating the packages list in Debian.
  3. Linux Tips and Useful Files.
  4. Make your computer talk!
  5. Window Screenshots.
  6. Listing the contents of a directory.
  7. Echoing output in a script.
  8. Setting the system time.
  9. Installing Firefox extensions.
  10. Using Midnight Commander as your favorite text editor.
  11. More nmap tricks.
  12. Setting up Console Mode Linux display.
  13. Transparent rxvt files.
  14. Vim Tips.
  15. Using Flash Disks.
  16. My /etc/fstab file.
  17. Various Cool Linux Commands.
  18. VIM & other useful stuff.
  19. Changing the Metacity themes.

Mandriva security tip.

To make Mandriva Linux 2010 more secure after installation, switch to a root account with su, then type:

passwd -l xguest

This will disable the xguest account for the system, Mandriva came with this account enabled and it had no password!

Updating the packages list in Debian.

To do this, you need to open a terminal and type:

sudo apt-get update

This will update the list of packages that are available to the apt system.
Then type:

sudo apt-get upgrade

And this will download and install all packages that are available to be updated. I do this frequently to keep my system up to date.

Linux Tips and Useful Files.

The following is a command to rip a DVD with mencoder and save it in a DivX file in MPEG4 format.

mencoder dvd://1 -oac mp3lame -vf scale=360:288 -ovc lavc \
-lavcopts vcodec=mpeg4:vbitrate=1200:autoaspect -o movie.avi

When you have typed something like man gcc and you want to search the man page, just press the / key and type your search string. You can recall it with the / key again and press the up-arrow key to go back through the search history for the session. This works the same as in the Firefox web browser. And also works in the vim editor. Just use it in the command mode and it will position the cursor at the first instance of the search word. Very useful indeed.

Make your computer talk!

To do this, you need the festival program installed. Once you have done that, just type: echo "$(fortune -o)" | festival --tts. You will hear a random fortune come out your speakers. This is cool if you put it on your .login file and it will play every time you login.

Window Screenshots.

To take a screenshot of a window on the desktop, use sleep 4; import -frame window.png this will wait 4 seconds before taking the shot. Just click on the window frame with the cross-hairs when they appear and you are done. Better than screwing around with MS paint. (SHUDDER). GIMP is way better. And it has a wealth of plugins to extend the functionality. And Helix Banshee is a very good media player and well integrated into the Gnome desktop. I just insert an audio CD and it will load up and start playing automatically. Very nice. Hotplugging is handled by HAL and works flawlessly.

Listing the contents of a directory.

Type this command for another way to print the directory contents. Not very useful however without the extended file information.

for file in *; do echo -ne "$file\n"; done;

Echoing output in a script.

To output some information in a script, type echo "$(date)" for example and it will be output easily.

Setting the system time.

I wanted to use the date(1) command to print out the current date and time and so I typed date -s “” as root and pasted the date value back into the commas and edited it to be the current date value and hit ENTER and it was done instantly. Windows would probably need a re-boot… for example date -s "Wed Jan 17 04:58:22 EST 2007". Once you do this it will be setup automatically.

I was listening to the radio last night and I heard a person ask what the Square root of 65536 was. So I wrote this program and got the answer…

#include 
#include 
#define num1 65536
int main() {
        int num2;
        num2 = sqrt(num1);
        fprintf(stdout, "The Square root of %i is %i.\n\n", num1, num2);
        return 0;
}

Installing Firefox extensions.

if you have copied a bunch of Firefox extensions into a directory on your hard drive and you are wondering how to install them in Firefox then read on. First you need to open a command prompt window and navigate to the directory containing the files. Then just type the following command.

/usr/bin/tree -R -H ./ > firefox.htm

Then just open the firefox.htm in firefox and install the files. This command generates valid XHTML code and is the best way to generate a HTML listing of files in a directory.

Using Midnight Commander as your favorite text editor.

Are you using the Midnight Commander’s text editor, and want to insert a copy of a file at the cursor position? Then just press F11 and select `Insert a out of command to cursor` and type cat FILE where FILE is the file you want to insert.

cat $HOME/files/myfile.txt

Then the file will be inserted at the cursor position. Very useful trick indeed. To insert a DOS line ending character just type:

perl -e 'printf("\cM");'

Simple.

More nmap tricks.

Below is the result of running nmap with the -O option. This shows the information about the OS the target machine is running. Since I have a firewall running on my system, you cannot see all of the 1674 or so ports on my system. Only the ones that need to be available for general network usage. I have the httpd port open for using Apache 2.0 for testing new webpage designs. This output does not say too much about the target system, which in this case is localhost.

$ sudo nmap -sR elrond
Starting Nmap 3.95 ( http://www.insecure.org/nmap/ ) at 2007-02-05 11:41 EST
Interesting ports on Elrond.Elflord (127.0.0.2):
(The 1666 ports scanned but not shown below are in state: filtered)
PORT    STATE SERVICE              VERSION
22/tcp  open  ssh
80/tcp  open  http
111/tcp open  rpcbind (rpcbind V2)  2 (rpc #100000)
631/tcp open  ipp
Nmap finished: 1 IP address (1 host up) scanned in 21.916 seconds

Setting up Console Mode Linux display.

I am running Knoppix 3.6 HD install on my Packard Bell laptop, and I had a problem where the console mode font was pretty small and would not fit on the screen. It would scroll off the bottom of the screen. I set the vga value in /etc/lilo.conf to vga=EXTENDED. Fixed the problem. You could also use vga=ask to get the kernel to prompt you for a list of vga modes. For more information, see /usr/src/linux/Documentation/fb/vesafb.txt.

I have also installed a new version of rxvt from source and I set the menufile to /etc/X11/rxvt.menu and I got an automatically updated menu of my applications in the rxvt menu. When I make installed it it was installed to /usr/local/bin so I still have the existing rxvt in the /usr/bin directory, but that was a symlink. I changed that to point to the new rxvt binary as the copy of the binary in the /usr/local/bin was not being used by default. Now I have a lovely new terminal that is much more attractive than the default rxvt program. GNU/Emacs uses the same command line options as rxvt so I am wondering if I could write a shell script to run either application and have them looking
the same.?

Something like this.

#!/bin/sh
$1 -bg "#003333" \
-fg "#FFFFFF" \
-cr "#FFFF33"

once you have this, you can run “options.sh emacs-21.3” to run Emacs with a traditional color scheme. Very nice. If you use this to run the rxvt program assuming it is compiled with the right options, it will have the same color scheme as GNU/Emacs. Nice if you like consistency. Put the script into $HOME/bin and name it rxvt-color or something like that, and you will have a nice looking rxvt. And a little program to write a name to a text file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define log "log.txt"
 
int main(int argc, char **argv)
{
        char *myarg;
        myarg = argv[0];
        if (!argv[1]) {
 
                fprintf(stdout, "\x28 Usage %s [Options]. \x29\n", myarg);
        } else {
                fprintf(stdout, "\x28 Command Line: %s\nYour Name: %s \x29\n", myarg, argv[1]);
                FILE *f;
                f = fopen(log, "a+");
                if(!f) {
                    printf("Sorry, cannot store your data in %s.\n", log);
                    exit(1);
                        } else {
                                fputs("\015\n", f);
                                fputs("Command Line:\015\n", f);
                                fputs(myarg, f);
                                fputs("Your name:\015\n", f);
                                fputs(argv[1], f);
                                fputs("\015\n", f);
                                fputs("\015\n", f);
                        }
                fclose(f);
                }
        return 0;
}
</string.h></stdlib.h></stdio.h>

Transparent rxvt files.

#!/bin/bash
# This is a shell script that provides a more attractive rxvt terminal.
# The default rxvt is pretty ugly compared to Eterm &amp; Aterm, so I have
# brightened it up a bit.
# Uses a pretty long command line, so I have broken it up into 3 lines for easier
# reading on a text console.
 
urxvt -fn "fixed" +sr +st -fg "#FFFFFF" -bg "#000033" -bd "#302c64" \
-ip +sb -title "*-Home-${HOME}-Shell-${SHELL}-Display-${DISPLAY}*" \
-tint DarkSlateGrey -fade 50 -fadecolor red

The above script gives you a more attractive transparent rxvt program. Very useful indeed. There is quite a demand for cool transparent Terminals, so here you go you lovely people. You get one right here. Updated for Fedora Core 5. Now with translucent rather than transparent background. Like aterm.

#!/bin/sh --
# an example of having different menus (even different pixmaps)
# show up depending on the machine you are rlogin/telnet connecting to
# Customised by Bejiitas Wrath 2005. I am adding many more useful commands
# for GNU/Linux. Having a menubar makes the archaic rxvt program much more
# useful indeed.
# I cannot understand why the script is setup for telnet when every self
# respecting person uses ssh...
# If this could work with Aterm it would be even better still.
menu="$0"       # or any convenient database
exe="/usr/X11R6/bin/rxvt"       # default program to execute
if test $# -gt 0; then
    # if first argument contains "rxvt" use that instead
    case $1 in *rxvt*) exe="$1" shift;; esac
fi
while [ $# -gt 0 ]
do
    case $1 in
        -h)             # give usage
        echo "
Usage:  `basename $0` [rxvt-prgm] [options]
        start rxvt
        and load a menu corresponding to \"machine\" if the option
            -e {rlogin|telnet|tn3270} Machine.Domain ...
        was used"
        exit
        ;;      # don't bother if we've already set it
        -menu) break;;  # don't bother if we've already set it
        -e)
        if test $# -ge 3;
        then
            case $2 in
                # try to find menu for these cases
                *rlogin | *telnet | *tn3270)
                # strip domain &amp; convert case
                mach=`echo $3 | sed -e 's/\..*$//' | tr [A-Z] [a-z]`
                if test ! -z "$mach";
                then
                    found=`egrep "^\[menu:$mach\]" $menu`
                    if test ! -z "$found";
                    then
                        mach="$menu;$mach"
                        exe="$exe -menu $mach"
                    fi
                fi
                ;;
            esac
        fi
        break
        ;;
        *)
        exe="$exe $1"
        ;;
    esac
    shift
done
# echo "$exe $@"
$exe $@ &amp;
exit    # stop shell here!
#-------------------------------------------------------------------------
[menu:weber]
#[menu:machine1]
[clear]
# [pixmap:machine1.xpm]
/Programs/*
{VIM}           vim\r
{Mail}          Mail\r
{Emacs}         emacs\r
{-}
{Exit}          exit\r
/Jobs/*
{Top}           top\r
{Ps u}          ps aux|egrep ^$USER\r
{Ps aux}        ps aux|egrep -v "(root|ps)"\r
# who's REALLY logged on (even with utmp logging turned off)
{Who}           ps aux|egrep "\-bash"|egrep -v "grep"\r
{-}
{Background}    ^Z bg\r
{Kill}          ^C\r
/Misc/*
{Finger}        finger -lmps\r
{Commander}     mc\r
{Clock}         xclock -update 1 -digital -strftime '%H:%M:%S - %A %d %b %Y' &amp;\r
[read:terminal]
[show]
#[done:machine1]
[done:weber]
#-------------------------------------------------------------------------
[menu:conn]
#[menu:machine2]
[clear]
# [pixmap:machine2.xpm]
/Programs/*
{VIM}           vim\r
{Checkmail}     mc\r
{Dir}           ls -hula|${PAGER:-more}\r
{Dir-Time}      ls -lat|${PAGER:-more}\r
{Space Left}    df -hla\r
{Emacs}         emacs\r
{-}
{Exit}          exit\r
/Jobs/*
{Background}    ^Z bg\r
{Kill}          ^C\r
{Pstree}        pstree\r
/Networking/*
{Web}           lynx\r
{Eth0}          ifconfig eth0\r
{Netstat}       netstat -eai\r
{Elinks}        elinks\r
/Misc/*
{Finger}        finger -lmps\r
{Commander}     mc\r
{Clock}         xclock -update 1 -digital -strftime '%H:%M:%S - %A %d %b %Y' &amp;\r
[read:terminal]
[show]
#[done:machine2]
[done:conn]
#--------------------------------------------------------------------- eof

The above file goes into your home directory and gives rxvt a menu. Used in conjunction with the shell script above it, you can have quite a useful rxvt program. Name it rxvt.menu and it will work with the above script.

Vim Tips.

When you are using VIM and you have typed up the perfect text file, but you want to insert text into the middle of the file, what do you do? Well read on.

To manage this, position the cursor where you want the text file to be inserted and press ESC to get into the VIM command mode and type :r
/home/foo/foo.txt
and press ENTER. The text file will be inserted into your main textfile at the cursor position. Now how useful will this technique be? Quite useful indeed I would think. Even better than logging into your machine remotely over the Internet using SSH. Although once you have logged into your machine you could then run vi and do your editing then. Sure Telnet is easy, but hardly secure. OpenSSH is quite easy and fun to use, so why not use anything else?

Using Flash Disks.

We all love using those USB Flash disks but what if you cannot mount it on your system? Well I have a Transcend 128MB drive and I want to mount it on my GNU/Linux machine, so I can use it right away, so I use this command in my /ect/fstab file that will allow me to mount the USB Drive which is /dev/sda by mounting it to the /mnt/sda directory. Then assuming the device is the same device name every time then you can just mount it by typing mount /mnt/sda then it will be accessible to the normal user, instead of having to switch to the root user to access the files on the device. This is for OpenSuSE 10.2. It might be slightly different on something like Fedora Core 5. But the basic principle is the same.

My /etc/fstab file.

/dev/hda2       /mnt/hda2       reiserfs        defaults 0 0
/dev/hda4       /       ext3    acl,user_xattr 1 1
/dev/hda3       swap    swap    defaults 0 0
proc    /proc   proc    defaults 0 0
sysfs   /sys    sysfs   noauto 0 0
debugfs /sys/kernel/debug       debugfs noauto 0 0
usbfs   /proc/bus/usb   usbfs   noauto 0 0
devpts  /dev/pts        devpts  mode=0620,gid=5 0 0
/dev/hdc        /mnt/cd iso9660 noauto,user,noexec 0 0
/dev/sda        /mnt/sda        vfat    noauto,user,noexec 0 0
/dev/sda1       /mnt/sda1       vfat    noauto,user,noexec 0 0
/dev/sdb        /mnt/sdb        vfat    noauto,user,noexec 00

Various Cool Linux Commands.

There are many cool commands that us GNU/Linux users can use to manage our system.

[2.6.15-1.2054_FC5  ]
[ Mythrandyr@mythrandyr.gondor ]
[ Jobs 0. PWD: ~. bash 3.1.7. ]
4-:\&gt; w
 03:38:24 up 1 day,  5:57,  3 users,  load average: 0.94, 0.68, 0.58
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
Mythrand tty1     -                Thu21   12:02m  1.11s  0.03s /bin/sh /usr/bin/startx
Mythrand pts/0    -                Fri15   12:01m  0.00s 21.78s kded [kdeinit]
Mythrand pts/1    -                03:37    0.00s  0.42s  0.04s w

The above command shows information about the current user. You can see that the user has been up for 1 hour and 6 Minutes. You can also see how many other users are on the system, ie 2 users. The login time is shown in the middle and it shows that I logged in at 20:01 using xdm and I logged into Xorg at that time on Display :0.

[2.6.15-1.2054_FC5  ]
[ Mythrandyr@mythrandyr.gondor ]
[ Jobs 0. PWD: ~. bash 3.1.7. ]
2-:\&gt; finger -lmps
Login: Mythrandyr                       Name: hsimpson
Directory: /home/Mythrandyr             Shell: /bin/bash
On since Thu Jun  1 21:42 (EST) on tty1    12 hours 1 minute idle
On since Fri Jun  2 15:36 (EST) on pts/0   12 hours idle
On since Sat Jun  3 03:37 (EST) on pts/1 (messages off)
No mail.

Now I am using the finger command. It shows even more information about my user than the last command. You can see tons of information about all of the users logged into your GNU/Linux system and when they last logged in.

[2.6.15-1.2054_FC5  ]
[ Mythrandyr@mythrandyr.gondor ]
[ Jobs 0. PWD: ~. bash 3.1.7. ]
7-:\&gt; locate alchemist
/etc/alchemist
/etc/alchemist/namespace
/etc/alchemist/switchboard
/etc/alchemist/namespace/printconf
/etc/alchemist/namespace/printconf/local.adl
/etc/alchemist/namespace/printconf/rpm.adl
/etc/alchemist/switchboard/printconf.swb.adl
/usr/lib/alchemist
/usr/lib/libalchemist.so.0
/usr/lib/libalchemist.so.0.0.0
/usr/lib/alchemist/blackbox
/usr/lib/alchemist/blackbox/libforgeblackbox.so.0
/usr/lib/alchemist/blackbox/libforgeblackbox.so.0.0.0
/usr/lib/python2.4/site-packages/_alchemistmodule.so
/usr/lib/python2.4/site-packages/pyalchemist.so
/usr/lib/python2.4/site-packages/pyalchemist_python.py
/usr/lib/python2.4/site-packages/pyalchemist_python.pyc
/usr/lib/python2.4/site-packages/pyalchemist_python.pyo
/usr/share/doc/alchemist-1.0.36
/usr/share/doc/alchemist-1.0.36/README
/var/cache/alchemist
/var/cache/alchemist/printconf.local
/var/cache/alchemist/printconf.rpm
/var/cache/alchemist/printconf.local/1
/var/cache/alchemist/printconf.local/wm
/var/cache/alchemist/printconf.rpm/1
/var/cache/alchemist/printconf.rpm/wm

The above output is from the locate command which is used to find various files on your filesystem. The crond program should have a script it runs to update the database of files so you can type for example locate xmms and it will find all of the files with xmms in their name. As you can see it finds any files named ‘alchemist’ whatever and wherever they may be. For Fedora Core 5 it has the afforementioned cron job setup so this will work out of the box.

linux@linux:~$ /sbin/ifconfig wlan0
wlan0     Link encap:Ethernet  HWaddr 00:17:3F:FC:15:CC
          inet addr:192.168.2.3  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: fe80::217:3fff:fefc:15cc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1492  Metric:1
          RX packets:45426 errors:0 dropped:0 overruns:0 frame:0
          TX packets:28076 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:42529839 (40.5 Mb)  TX bytes:3622781 (3.4 Mb)

The above command shows information about the Networking Adapter connected to your machine. This is how you can debug any problems with your adapter.

VIM & other useful stuff.

This is my .vimrc file, this will give you a very useful VIM configuration.

:set nu
:set wrap
:set encoding=utf-8
au BufReadPost * if line("'\"") &gt; 0 &amp;&amp; line("'\"") &lt;= line("$") |
                        \ exe "normal g'\"" | endif
:highlight Normal ctermbg=black ctermfg=white guibg=white guifg=white
:colors koehler
:syntax on
set nocompatible
set bs=2
set tw=72
set cindent
set mouse=a
set nowrapscan
set showmatch
set showmode
set uc=0
set mousehide
set hlsearch
let c_comment_strings=1
" Color for xiterm, rxvt, nxterm, color-xterm :
if has("terminfo")
set t_Co=8
set t_Sf=\e[3%p1%dm
set t_Sb=\e[4%p1%dm
else
set t_Co=8
set t_Sf=\e[3%dm
set t_Sb=\e[4%dm
endif

The above is my .vimrc file. This will give you white text and a blue background just like the old DOS Edit program. Nifty Huh? For more information go to /usr/share/doc/vim/FAQ.gz. This file will answer just about all your questions about the excellent VIM editor. With this .vimrc you can set the colors the way you want, and if you are using GVIM you do not get the glaring white background. It will also remember the last cursor position, so if you are editing a large configure script or source file you do not need to page down to line 4567 any longer. Doing this over and over again would drive you mad. And the computer should be the one doing part of the work. You should not need to do everything. Having :set wrap! turns off line wrapping which I use when I am coding. use :set wrap in command mode to turn it back on.

Using :set nu turns on line numbering, which is indispensable when coding, especially when you have 6000 lines of code and gcc reports an error on line 3478. Imagine counting down the lines in Notepad… See VIM is better than notepad! Or you can type vim myfile.cpp +3478 to go to the line number directly. Instead of pressing Page down over and over again…

Here is a small Perl script that will list the contents of a directory branching off of the current directory. A very useful script. The output is sorted to make the output easier to read and to find what you are looking for. I wanted to use getc() but I decided using chomp() was easier.

#!/usr/bin/perl -W
use strict;
use warnings;
printf("Please enter a directory to view.\n");
chomp( my $dir = );
if (!$dir)
{
        printf("You did not enter a directory!\n");
        exit;
} else {
        my $path = $ENV{"PWD"};
        printf("\n%s\/%s\n", $path, $dir);
        opendir(DNAME, "$dir") || die "I cannot open that dir!\n $!";
        {
        my @dir = readdir(DNAME);
        @dir = sort(@dir);
        foreach my $x (@dir) {
        print "$x\n";
                }
        }
}
linspirelive:~/My Computer/ USB DISK Pro/Init# wget http://members.tripod.com/bejiitas_wrath/maps/emacs.txt
--12:06:06--  http://members.tripod.com/bejiitas_wrath/maps/emacs.txt
           =&gt; `emacs.txt'
Resolving members.tripod.com... 209.202.226.100
Connecting to members.tripod.com[209.202.226.100]:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3,400 [text/plain]
100%[================================================================================&gt;] 3,400         11.78K/s
12:06:14 (11.76 KB/s) - `emacs.txt' saved [3400/3400]

Above, you can see the output of the wget command, which can fetch files from the Internet. I am using it here to download a textfile from my website http://members.tripod.com to my USB thumb drive using Linspire. A very useful command to use if you want to fetch a file from the Internet or your network.

Changing the Metacity themes.

This is the command to set the GTK Theme.

gconftool-2 --type=string --set /apps/metacity/general/theme Clearlooks

This will change to the Clearlooks Metacity theme. You only need to use this command once. Use it again to change the theme to another.

An example of printf(). This is the simplest possible script that will print the current time.

#!/usr/bin/perl
print scalar localtime(time());

I have been playing around with xclock and I have discovered a very good command line for it.

xclock -update 1 -digital -strftime "%H:%M:%S-%A-%d-%b" &amp;

This command line gives you the perfect time/date display and updates every tick of the second. And it does not take up much space on the desktop.

date +%H:%M:%S-%A-%d-%b

The above command will print the same date output to the console. This could be useful if you wanted, you could put this in your .bashrc or just use it to find the right format, although typing ‘man strftime’ will help also. You cannot have spaces in the command or else it will be confused and output an error.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.