Linux tips and tricks

Från Wikipedia, den fria encyklopedin.

Innehåll

File System watchers

incrontab is neat utility to set up commands to run when something is altered in the file system. Example of content in the configuration file which is edited by writing incrontab -e:

/home/svenne/folderToWatch IN_CLOSE_WRITE /home/svenne/Program/myProgram.sh

This will run the program myProgram.sh everytime a file or folder is written and closed in the folder folderToWatch.

NOTE: incrontab is disallowed by default, so make sure you type:

echo <username> > /etc/incron.allow

before configuring anything.

Hints:

  • Don't use IN_MODIFY if the program you will be running on the event is going to use the file in the surveilled directory, as it might not be closed yet. In that case it is better to ise IN_CLOSE_WRITE (which is triggered when the file is closed.

More info:

Remove sound notifications

System Settings > Notifications > System Notifications > Player Settings > No audio output

Remove The Update manager Pop-up

http://maketecheasier.com/remove-the-annoying-update-manager-pop-up-in-ubuntu-jaunty/2009/06/18

Convert FLAC to Mp3

Start out by installing package zenity, then follow this guide: http://www.ubuntuhowtos.com/howtos/convert_flac_to_mp3


Static IP

A good reason for having a static IP address is that it improves boot time.

  1. Remove the network manager. Type the following into your terminal:
    sudo aptitude purge network-manager
  2. Edit /etc/network/interfaces:
    sudo vim /etc/network/interfaces
  3. Change content to be the following:
    auto lo
    iface lo inet loopback
    
    iface eth0 inet static
    address 192.168.1.100
    netmask 255.255.255.0
    gateway 192.168.1.1
    
    auto eth0
    

    Where:

    • "192.168.1.100 " my static ip
    • "255.255.255.0" my subnet mask
    • "192.168.1.1" my routers/gateway ip
    • "eth0" my current ethernet interface
  4. Edit /etc/resolv.conf: I recommend using the OpenDNS name servers for faster browsing.
    nameserver 208.67.222.222
    nameserver 208.67.220.220
    
  5. Restart your networking:
    sudo /etc/init.d/networking restart

Avoid entering password everytime the laptop needs to connect to WLAN

  • Start up Seahorse - ALT+F2 -> seahorse -> Enter
  • Select Edit/Preferences
  • Select first key and select change unlock password
  • after entering your old password, for new password just hit line return twice

there will be a warning message that security is low, but this will allow you to connect to Wifi without problem at boot (without being asked!).

Just dont save your other passwords on this keyring if you dont want anyone to access eg your emails!

Thanks to: http://ubuntuforums.org/showthread.php?t=192281&page=12

Downgrading from KDE4 to KDE3

Finally I gave up on KDE4, I realized that it is still far to incomplete and unstable for me. Especially when it comes to my server that I feel must be stable. I recently installed Kubuntu 8.04.1 with KDE4, so now I had to downgrade the desktop environment. All I had to do was:

  1. Log out of the KDE4 session
  2. Open terminal (ctrl+alt+F2)
  3. run sudo aptitude install kubuntu-desktop
  4. Restart x-server (ctrl+alt+backspace)
  5. Login to a KDE3 session
  6. Run Adept Manager
  7. Search for everything having the name kde4 in it and uninstall it

Done!

Hopefully one day I will be using KDE4 again, in a couple of minors maybe.

Backup before upgrade

When upgrading to a new version (i.e. from Kubuntu 8.04 to 8.10) it might be a good idea to make a backup of the entire system in case something goes wrong. Here are some tutorials that might come handy:

Change default file manager

In 'Kubuntu 7.10 Gutsy Gibbon' the default file manager changed to Dolphin (from Konqueror in previous versions). To change back to Konqueror:

  1. In Konqueror configuration or control panel, choose 'File Associations' module
  2. Select inode/directory
  3. Choose Dolphin and press 'Move down', so that Konqueror is at the top. Press 'Apply'

Restricted extras

To quickly install media codecs etc that are restricted by copyright etc install the following packages:

sudo aptitude install ubuntu-restricted-extras kubuntu-restricted-extras

Rotate video

mencoder -vf rotate=1 -ovc lavc -oac copy src.avi -o dest.avi
  • 0 Rotate by 90 degrees clockwise and flip (default).
  • 1 Rotate by 90 degrees clockwise.
  • 2 Rotate by 90 degrees counterclockwise.
  • 3 Rotate by 90 degrees counterclockwise and flip.

More info here.

Allow scripts to talk to graphical apps

The magic trick is to add DISPLAY=:0 before your command (if your app is running on display 0).

The common case is when you want to schedule some command to initiate something on a running graphical application, see for instance Applications_for_Linux#Scheduling.

VNC - Remotely share your desktop

There is a built-in feature in (K)ubuntu to share the desktop, Krfb. However, this function is not very resource efficient. Below follow some better alternatives:

x11vnc

Will show the same desktop as the local monitor.

Try this: http://kubuntuguide.org/Karmic#X11VNC_Server

- OR -

Follow the guide here: http://ubuntuforums.org/showthread.php?t=363236

I changed the serverargs row to:

server_args = -inetd -o /var/log/x11vnc.log -display :0 -auth /home/cewan/.Xauthority -many -bg
vnc4server

Follow the guide here to make it work. I also had to add:

-extension XFIXES

to server_args in the /etc/xinetd/Xvnc file, as mentioned on the fifth page of the before mentioned thread.

The main advantages of vnc4server that I see are:

  • Better performance
  • You get your own login, instead of resuming what is showing at your local monitor at home
  • You can set ANY resolution you like, by simply editing the /etc/xinetd/Xvnc file

Reminder:

  • If you want to see if VNC is running, by typing ps -ef | grep vnc, remember that it will only be started once you've done a remote login over VNC.
Even better performance - TightVNC

"The difference between the tightvncserver and the normal vncserver is the data encoding, optimized for low bandwidth connections." - Ubuntu package declaration

To setup TightVNC:

  • Follow the before mentioned tutorial, but skip the steps about vnc4server, xinetd and the Xvnc script.
  • Install TightVNC: sudo aptitude install tightvncserver
  • Follow first part of this guide to enable KDE for TightVNC.
  • Now run the server by typing tightvncserver or tightvncserver -depth 16 -geometry 1200x700 if you want a custom resolution and depth.

Web server statistics with Awstats

  • Install awstats package
  • Edit a file called /etc/awstats/awstats.hostname.conf where hostname is the hostname (find it under /etc/hostname). Put something like this in it:
LogFile="/var/log/apache2/access.log"
LogFormat=1
DNSLookup=1
DirData="/var/lib/awstats"
DirCgi="/cgi-bin"
DirIcons="/icon"
SiteDomain="hostname"
AllowToUpdateStatsFromBrowser=1
AllowFullYearView=3
SkipHosts="localhost 127.0.0.1 REGEX[^192\.168\.] REGEX[^10\.] <your-ip-from-isp>"
  • Make sure that directory /var/lib/awstats is editable by www-data (or whatever the www user is called)
  • Copy icons to web directory:
cp -r /usr/share/awstats/icon /var/www/icon
  • Run this to update databases:
/usr/lib/cgi-bin/awstats.pl -config=hostname -update
  • In your web browser, go to the url:
http://hostname/cgi-bin/awstats.pl?config=hostname
  • Study the stats in quiet awe
  • Edit crontab to update stats automatically every night:
crontab -e
0 1 * * * /usr/lib/cgi-bin/awstats.pl -config=hostname -update

Thanks to Peter and GoodWebHosting!

Remove annoying bouncing cursor and taskbar notification

Whenever an application is started an icon of that program is bouncing next to the mouse cursor for 30 seconds. Also, a flashing item appears in the taskbar.

bouncing.png
taskbar.png

Bouncing cursor

Taskbar indicator

If you find both of these annoying, remove them under 'System Settings' -> 'Desktop' -> 'Launch Feedback'.

Browse music files with MythTV

By default music is sorted by artist name in MythTV. Perform the following to be able to browse the file structure instead:

  • (From main) Utilities
  • Setup
  • Media Settings
  • Music Settings
  • Tree Sorting - Type directory here
  • Don't know if it's needed, but I have ARTIST - TRACK_TITLE under Filename Format.

All Done!

Stay logged in with ssh

Remove ssh session timeout by adding the following line to /etc/ssh/sshd_config

ClientAliveInterval 300

The reason the ssh session times out is usually that some router in the middle cuts the connection due to inactivity. This addition makes the server send empty packages every fifth minute, which will work unless the router is set to timeout before that (usually the timout is 10 minutes).

Don't forget to restart the ssh server (sudo /etc/init.d/ssh restart), and then relogin.

Adding authorization to web server

Add the following content to /etc/apache2/sites-available/default:

<Directory /var/www/restrictedDir>
    AllowOverride AuthConfig
    AuthUserFile /home/myUser/.htpasswd
    AuthName "My Site - restricted area"
    AuthType Basic
    require user userName
</Directory>

replace:

  • restrictedDir with your directory under the webroot
  • myUser with your username
  • userName with the login username you desire for the webpage

Now run the following:

htpasswd -c ~/.htpasswd userName

and enter your desired password.

All done! Restart webserver to see the changes.

Exporting display

Both my stationary and laptop are now running Linux. Sometimes I want to run programs on the stationary but display the actual window on my laptop, sort of like a remote control. With Linux this is an easy task, and does not require any third party programs.

  1. client: ssh user@server_ip -X
  2. now logged in at server: start your favorite program, e.g. amarok &

Almost too easy to mention, eh?

Make sure that X11 forwarding is enabled on the server, usually it is by default. Check the file /etc/ssh/sshd_config for X11Forwarding yes.

Creating a keyboard shortcut for Konqueror File Manager

If using Windows you are probably used to pressing Win+E to open the file manager (Windows Explorer). This could be achieved quite easily in KDE as well:

  • Open K-Menu
  • Right click on any item and click edit item.
  • KDE Menu Editor appears. Right click on the group where you want to add the item. Choose New item.
  • Name it for instance Konqueror - Home
  • Set Command to konqueror -profile filemanagement
  • Click the empty icon (upper right corner) and select the desired icon, for instance Konqueror or Home.
  • Click the button next to Current shortcut key which says None
  • Press Win+E
  • Save by pressing Ctrl+S

All done, test it by pressing Win+E!

Walk through windows on all screens

This tip is for people using more than one screen at the same time.

When pressing Alt+Tab only the programs on the current screen shows in the list, and not the programs on other screens.

To make all programs show in the list, open Control Center, then Desktop -> Window Behavior, and make sure that 'Separate screen focus' is checked. That's it!

KDE printer dialog in OpenOffice

To use the KDE printer dialog (which gives you a lot more options when printing) in OpenOffice, run the OOo printer administration tool (for me it was found here /usr/lib/openoffice/program/spadmin). Set the command to be kprinter.

Thanks to Maf. King!

Browse remote file systems over ssh

Konqueror has a built in ssh client which enables you to access remote file systems. Simply start the address line with fish:// to use it!

Example:

fish://user@host

Automatically login (KDE)

  1. K-Menu -> System settings -> Advanced -> Login Manager
  2. Press Administrator Mode and type in root password.
  3. Convenience -> Enable auto login -> Apply

Done!

Using KDE dialogs in non-KDE applications

This example demonstrates how to enable it for Firefox.

  1. Install package kgtk
  2. Restart KDE (Ctrl-Alt-Backspace) MAKE SURE YOU DON'T HAVE ANY UNSAVED DATA (for Kubuntu, was not needed with Gentoo)
  3. Open K-Menu -> Internet, right click 'Firefox Web Browser' and select 'Edit item'
  4. Edit the 'Command' field, by adding the following to the beginning:
     /usr/local/kde/bin/kgtk-wrapper (Kubuntu)
     /usr//bin/kgtk-wrapper (Gentoo)
    

    The command field would typically then look like:

     /usr/local/kde/bin/kgtk-wrapper firefox %u
    

Printing in Firefox (KDE)

To be able to use KDE printer dialog (which has a lot more settings) in Firefox follow the tutorial on UbuntuForums.org: How To: Make Firefox / Thunderbird print to kprinter automatically in KDE / Kubuntu

CD/DVD Images

Mounting

On Windows you would typically use Daemon Tools to mount an image. With Linux you don't even have to install anything, just mount it using:

mount -t iso9660 image.iso mount.point -o loop

This works for *.iso and *.img; for the bin/cue format, the file must first be converted to iso (using bchunk for instance):

bchunk image.bin image.cue new_file_name

This is a fast operation, takes typically 15 seconds for a CD-sized image.

Another option is to use CDemu.

Handling daa images (PowerISO)

.daa images cannot be mounted directly as the only program that handles them are PowerISO. This is a Windows only program, but fortunately the company released a free converter which converts daa to iso (or whatever). The converter can be found at PowerISO's website under the download section: http://poweriso.com/download.htm

Reinstall Desktop

If you accidentally uninstall some important core files for KDE/GNOME this is easilly solved by:

sudo apt-get install kubuntu-desktop

...for KDE, and

sudo apt-get install ubuntu-desktop

...for GNOME!


Removing PC Speaker sound

Sound coming from the internal pc speaker is usually just annoying. Remove it right away by writing:

modprobe -r pcspkr

To make sure that it's always turned off, even when you've rebooted the computer, add that line to the file:

/etc/rc.local

before the last line (exit 0).

Making sure numlock is turned on after startup

Most people use the numeric keypad to type numbers, not to navigate with the arrows. Still, for some strange reason, the default is that numlock is turned off. To make sure it is turned on by default:

File sharing

SSHFS - Mount files over ssh

Here we have another excellent solution for Linux that you won't find on Windows. If you have a computer with an SSH server, you can now mount the files on that server on your Linux box. What is that good for you might say? Let's say you want to play mp3s from your server on your local computer. This could be solved by:

  • Copying the files to the local computer with FTP or SCP
  • Install a music server that streams the songs
  • Mount using NFS or SAMBA
  • Mount your music collection using SSHFS, then browse and play the files as if they were on your local computer

The first two options are not very convenient. NFS and SAMBA is okey for local networks, but SSH has encryption and if you already have it installed no need to add any more users and firewall settings and so on.

Okey then, you are convinced! Let's get started:

  1. Install package sshfs
     sudo aptitude install sshfs
    
  2. Add fuse to /etc/modules
     sudo vim /etc/modules
    
  3. Set permissions
     sudo chmod +x /usr/bin/fusermount (or /bin/fusermount)
     cd /dev
     sudo chgrp fuse fuse
     sudo addgroup <username> fuse
    
  4. logout and login again
  5. Create a mount point
     mkdir <mntpoint>
    
  6. Perform the mount
     sshfs remote-system-name:/remote-folder <mntpoint>
    

Enjoy!

To unmount run:

fusermount -u <mntpoint>

OR

sudo umount <mntpoint>

Thanks to:

Automounting

To automatically mount at startup, try this guide!

NFS - Between Linux boxes

Server

Install necessary packages:

sudo aptitude -P install nfs-kernel-server nfs-common portmap

Add share:

sudo vi /etc/exports

Example of line to add:

/home/czar/tmp 192.168.1.1/24(rw,no_root_squash,async)

Shares the specified folder to 192.168.1.*

To reload the changes:

sudo /etc/init.d/nfs-kernel-server restart

Client

Install necessary packages:

sudo aptitude -P install nfs-common portmap

Manually mount share:

mkdir mounts/czar-tmp
sudo mount 192.168.1.2:/home/czar/tmp mounts/czar-tmp

Automatically mount (add the line to /etc/fstab):

192.168.1.2:/home/czar/tmp /home/localuser/mounts/czar-tmp nfs user

The last option (user) lets all users mount the share.

Tips

You might want/need to add hosts to hosts.allow and hosts.deny, see links below if that is the case.

For more info check:

Windows network

Automatically mount when booting up

Make sure you always have access to remote folders, such as folders on Windows boxes in the network by adding a some stuff to the fstab file. //remotemachine/remoteshare /home/localuser/mnt/ smbfs dmask=777,fmask=777,user,password=notneeded 0 0 This will let all users mount this share. Also it assumes that no password is needed to access the windows share. For more info follow this tutorial on ubuntuguide.org!

Sharing a folder on a Windows network

GUI

  1. Make sure that samba is installed
  2. Right click a folder in File Browser and choose share folder
command line

Open config file:

sudo vim /etc/samba/smb.conf

Add to the end of the file:

[name_of_share]
path = /path/to/share/
guest ok = yes

Restart samba server

sudo /etc/init.d/samba restart

Setting permissions on your shares

There are basically two options. Allow anonymous access or setup a user that can access the share.

Anonymous access

  1. sudo vim /etc/samba/smb.conf
    
  2. Make sure the following line exists and is not commented out:
    security = share
  3. Save and quit vim
  4. Restart samba
    sudo /etc/init.d/samba restart
    

Writable access for anonymous

  1. Edit the config file:
    sudo vim /etc/samba/smb.conf
    
  2. Path entry should look like this:
    [PATH]
    path = ...
    guest ok = yes
    read only = no
    writable = yes
    
  3. Set up the guest account. In the global section:
    [global]
            #...
            guest account = nobody
            map to guest = bad user
    
  4. Save and quit vim
  5. The following will create the user with no password:
    # smbpasswd -an nobody
    
  6. Restart samba
    sudo /etc/init.d/samba restart
    

Thanks to: http://micheljansen.org/blog/entry/182

Setup specific user access

  1. Add a username and password to samba by typing
    sudo smbpasswd -a <username>
    

    Note that the user you add to samba must exist as a regular user, however the password does not have to be the same. To add a regular user in Linux:

    sudo useradd <username>
    sudo passwd <username>
    
  2. Now access the folder from a Windows box and type in the username and password that was added to samba.

Sharing a printer on a Windows network

https://help.ubuntu.com/community/NetworkPrintingFromWinXP

After following the guide you can find the exact url to your printer at:

http://<hostname>:631/printers/

smb4k (KDE)

To access files over a windows network, install the samba package: smb4k

If mounting fails, and you get the message:

smbmnt must be installed suid root for direct user

Enter the following two in a terminal:

sudo chmod u+s `which smbmnt`
sudo chmod u+s `which smbumount`

And try the mount again!

Cudos to debuntu.org!

Accessing shares

Directly in Konqueror

Type the following in location field:

smb://computer_name
Mounting to a local directory

Mount shares with the manual command:

mount -t smbfs -o username=domain\\username //computer_name/folder /local_folder_to_mount_on

OR

mount -t cifs -o username=domain\\username //computer_name/folder /local_folder_to_mount_on

I have bumped into problems with the smbfs version, so I use cifs instead. If one doesn't work for you, try the other.

The package to install is smbfs, as this provides support for both smbfs and cifs.

If you have problems with special characters add the following option:

iocharset=utf8

Which would make it:

... -o username=domain\\username,iocharset=utf8 ...

Setting up an ssh server

SSH (Secure Shell) is a secure version of telnet, which is a way of connecting to another computer and performing command line operations.

To be able to connect to your computer remotely using ssh, install the following package:

ssh

You're done! If you are behind a router don't forget to forward the ssh port 22 to your computer. Now to connect to your ssh server:

ssh <username>@<hostname>

If you experience a delay when logging in to the ssh server, add the following line to /etc/ssh/sshd_config

UseDNS no

Performing backups

rsync -avP --stats --delete <source_folder> <destination_folder> 1> ~/BackupLogs/out.log 2> BackupLogs/err.log

This command will:

  • backup <source_folder> to <destination_folder>
  • the name of the source folder will be added to destination folder
  • --delete - files not existing in source but in destination will be deleted
  • a = archive - folders and subfolders will be included and attributes preserved
  • v = verbose - print what files have been processed
  • P = progress - transfer speed, percentages etc
  • 1> = send output to the following file
  • 2> = send errors to the following file

If you are getting the following error message:

rsync error: some files could not be transferred (code 23) at main.c(892) [sender=2.6.8]

It means you don't have the proper permissions on those files, you probably need to be root (run the command as sudo).

Scheduling

Use crontab to schedule your backup. To make sure that there will be no permission issues schedule under user root:

sudo crontab -u root -e

The following line will run the given command at 23:45 every day:

45 23 * * * sh /home/<username>/backup-jobs.sh

the shell script in this case will contain an rsync operation.

GUI

Instead of using the terminal, you might want to use KCron (package kcron), which is a nice GUI for crontab!

Excluding folders

use the --exclude option to exclude stuff when synching. Example:

rsync -avP --stats /home/aUser --exclude "/home/aUser/temp" --delete /backups

Will exclude the temp folder when synching /home/aUser to /backups.

Backing up remotely

Simply use ssh! Example:

rsync -avP --stats --delete <local source folder> <username>@<hostname>:<destination folder on server>
Software