Showing posts with label Linux System Administrator. Show all posts
Showing posts with label Linux System Administrator. Show all posts

Tuesday, June 19, 2012

Basic Linux Command-line Tips and Tricks

1.  Everything in Linux is a file including the hardware and even the directories.
2. # : Denotes the super(root) user
3.  : Denotes the normal user
4.  /root: Denotes the super user’s directory
/home: Denotes the normal user’s directory.
5.  Switching between Terminals
§  Ctrl + Alt + F1-F6: Console login
§  Ctrl + Alt + F7: GUI login
6.  The Magic Tab: Instead of typing the whole filename if the unique pattern for a particular file is given then the remaining characters need not be typed and can be obtained automatically using the Tab button.
7.   ~(Tilde): Denotes the current user’s home directory
8.   Ctrl + Z: To stop a command that is working interactively without terminating it.
9.  Ctrl + C: To stop a command that is not responding. (Cancellation).
10.  Ctrl + D: To send the EOF( End of File) signal to a command normally when you see ‘>’.
11.  Ctrl + W: To erase the text you have entered a word at a time.
12.  Up arrow key: To redisplay the last executed command. The Down arrow key can be used to print the next command used after using the Up arrow key previously.
13.  The history command can be cleared using a simple option –c (clear).
14.  cd :   The cd command can be used trickily in the following ways:
cd : To switch to the home user
cd * : To change directory to the first file in the directory (only if the first file is a directory)
cd .. : To move back a folder
cd - : To return to the last directory you were in
15.  Files starting with a dot (.) are a hidden file.
16.   To view hidden files: ls -a
17.   ls: The ls command can be use trickily in the following ways:
ls -lR : To view a long list of all the files (which includes directories) and their subdirectories recursively .
ls *.* : To view a list of all the files with extensions only.
18.   ls -ll: Gives a long list in the following format
drwxr-xr-x 2 root root 4096 2010-04-29 05:17 bin where
drwxr-xr-x : permission where d stands for directory, rwx stands for owner privilege, r-x stands for the group privilege and r-x stands for others permission respectively.
Here r stands for read, w for write and x for executable.
2=> link count
root=>owner
root=>group
4096=> directory size
2010-04-29=>date of creation
05:17=> time of creation
bin=>directory file(in blue)

The color code of the files is as follows:
Blue: Directory file
White: Normal file
Green: Executable file
Yellow: Device file
Magenta: Picture file
Cyan: link file
Red: Compressed file
File Symbol
-(Hyphen) : Normal file
d=directory
l=link file
b=Block device file
c=character device file
19.  Using the rm command: When used without any option the rm command deletes the file or directory ( option -rf) without any warning. A simple mistake like rm / somedir instead of rm /somedir can cause major chaos and delete the entire content of the /(root) directory. Hence it is always advisable to use rm command with the -i(which prompts before removal) option. Also there is no undelete option in Linux.
20.  Copying hidden files: cp .* (copies hidden files only to a new destination)
21. dpkg -l : To get a list of all the installed packages.
23. Use of ‘ > ‘ and ‘ >> ‘ : The ‘ > ‘ symbol ( input redirector sign) can be used to add content to a file when used with the cat command. Whereas ‘ >> ‘ can be used to append to a file. If the ‘ >> ‘ symbol is not used and content is added to a file using only the ‘>’ symbol the previous content of the file is deleted and replaced with the new content.
e.g: $ touch text (creates an empty file)
$ cat >text
This is text’s text. ( Save the changes to the file using Ctrl +D)
$cat >> text
This is a new text. (Ctrl + D)
Output of the file:
This is text’s text.
This is a new text.

23.  To count the number of users logged in : who |wc –l

24.  cat:  The cat command can be used to trickly in the following way:
- To count no. of lines from a file : cat |wc -l
- To count no. of words from a file : cat |wc -w
To count no. of characters from a file : cat |wc –c

25.  To search a term that returns a pattern: cat |grep [pattern]

26.  The ‘tr’ command: Used to translate the characters of a file.
tr ‘a-z’ ‘A-Z’ <text >text1 : The command for example is used to translate all the characters from lower case to upper case of the ‘text’ file and save the changes to a new file ‘text1′.
27.  File permission using chmod: ‘chmod’ can be used directly to change the file permission of files in a simple way by giving the permission for root, user and others in a numeric form where the numeric value are as follows:
r(read-only)=>4
w(write)=>2
x(executable)=>1
e.g. chmod 754 text will change the ownership of owner to read, write and executable, that of group to read and executable and that of others to read only of the text file.
28.  more: It is a filter for paging through text one screenful at a time.
Use it with any of the commands after the pipe symbol to increase readability.
e.g. ls -ll |more
29.  cron : Daemon to execute scheduled commands. Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates.
1 * * * * echo “hi” >/dev/tty1 displays the text “hi” after every 1 minute in tty1
.—————- minute (0 – 59)
| .————- hour (0 – 23)
| | .———- day of month (1 – 31)
| | | .——- month (1 – 12) OR jan,feb,mar,apr …
| | | | .—– day of week (0 – 7) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
* * * * * command to be executed
Source of example: Wikipedia
30.  fsck: Used for file system checking. On a non-journaling file system the fsck command can take a very long time to complete. Using it with the option -c displays a progress bar which doesn’t increase the speed but lets you know how long you still have to wait for the process to complete.
e.g. fsck -C
31.  To find the path of the commandwhich command
e.g. which clear
32. Setting up alias: Enables a replacement of a word with another string. It is mainly used for abbreviating a system command, or for adding default arguments to a regularly used command
e.g. alias cls=’clear’ => For buffer alias of clear
33.  The du (disk usage) command can be used with the option -h to print the space occupied in human readable form. More specifically it can be used with the summation option (-s).
e.g. du -sh /home summarizes the total disk usage by the home directory in human readable form.
34.  Two or more commands can be combined with the && operator. However the succeeding command is executed if and only if the previous one is true.
e.g. ls && date lists the contents of the directory first and then gives the system date.
35.  Surfing the net in text only mode from the terminal: elinks [URL]
e.g: elinks www.google.com
Note that the elinks package has to be installed in the system.
36.  The ps command displays a great more deal of information than the kill command does.
37.  To extract a no. of lines from a file:
e.g head -n 4 abc.c is used to extract the first 4 lines of the file abc.c
e.g tail -n 4 abc.c is used to extract the last 4 lines of the file abc.c
38.  Any changes to a file might cause loss of important data unknowingly. Hence    Linux creates a file with the same name followed by ~ (Tilde) sign without the recent changes. This comes in really handy when playing with the configuration files as some sort of a backup is created.
39.   A variable can be defined with an ‘=’ operator. Now a long block of text can be assigned to the variable and brought into use repeatedly by just typing the variable name preceded by a $ sign instead of writing the whole chunk of text again and again.
e.g ldir=/home/my/Desktop/abc
cp abcd $ldir copies the file abcd to /home/my/Desktop/abc.
40. To find all the files in your home directory modified or created today:
e.g. find ~ -type f -mtime 0

Tuesday, January 10, 2012

Managing Services on Linux with systemd

 You've read all about systemd, the new Linux init daemon. You know what it does, and why. Now it's time to dig in and learn how to make it sit up and beg — or at least start, stop, and get information on services.

Starting and Stopping Services

My earlier piece, "Here We Go Again, Another Linux Init: Intro to systemd" discusses the concepts behind systemd and what it is supposed to do. Now it's time to learn how to use it to control services on our systems. systemd is backwards-compatible with sysvinit and Upstart, so you can try it out by installing it on any Linux that uses sysvinit or Upstart without a lot of extra work. Arch Linux, Debian, and OpenSUSE all include systemd in their software repositories.
A conspicuous omission from distros that support systemd is Ubuntu. There are various reasons given for this, and I don't care because I'm tired of geekfights and just want to get on with things. Another way is to fetch yourself a copy of Fedora 15 or 16, which runs systemd by default.

systemadm is a nice graphical systemd manager (figure 1). It's still a baby so it might crash or something, but you can try it by installing the systemd-gtk package on Fedora, the systemd package on Arch, or the systemd-gui for Debian. No, of course distros cannot use consistent package naming, because that is against the rules.
As pretty as systemadm is, let us adjourn to the command line for the rest of this article. Watch the prompts in the examples to see which ones require root privileges. You can see the status of everything systemd controls by running systemctl with no options:
$ systemctl
UNIT                                              LOAD   ACTIVE SUB       JOB DESCRIPTION
proc-sys-fs-binfmt_misc.automount                 loaded active waiting       Arbitrary Executable File Formats File System Aut
sys-devices-pci0...000:00:1b.0-sound-card0.device loaded active plugged       82801I (ICH9 Family) HD Audio Controller
sys-devices-pci0...-0000:05:00.0-net-wlan0.device loaded active plugged       Centrino Wireless-N 1000
How do you see only available services, running or not?
$ systemctl list-units -t service --all
UNIT              LOAD   ACTIVE   SUB   JOB   DESCRIPTION
ceph.service      loaded inactive dead        LSB: Start Ceph distributed filesystem daemons at boot time
chronyd.service   loaded active   running     NTP client/server
cman.service      error  inactive dead        cman.service
These will spit out a whole lot of output, probably a hundred lines or more. Want to see only active services?
$ systemctl list-units -t service
You can check the status of any individual service, such as the cman.service, which has an error flag in the previous example:
$ systemctl status cman.service
cman.service
   Loaded: error (Reason: No such file or directory)
   Active: inactive (dead)

How nice, it tells us what the problem is. Here is what a normal running service looks like, with complete information on the service:
$ systemctl status sshd.service
sshd.service - OpenSSH server daemon
   Loaded: loaded (/lib/systemd/system/sshd.service; enabled)
   Active: active (running) since Thu, 15 Dec 2011 12:11:05 -0800; 2h 26min ago
 Main PID: 2091 (sshd)
   CGroup: name=systemd:/system/sshd.service
      \   2091 /usr/sbin/sshd -D

On Fedora you can still use the old service and chkconfig commands. But why not start learning the new systemd commands? This is how to start a service:
# systemctl start sshd.service
Or use restart to restart a running service. This stops a service:
# systemctl stop sshd.service
Those are in effect only for the current session, so if you want a service to start at boot do this:
# systemctl enable sshd.service
And that's all. No hassling with startup scripts. This disables it from starting at boot:
# systemctl disable sshd.service
You can check to see if a service is already running; 0 means it is currently running and 1 means it is not:
$ systemctl is-enabled sshd.service; echo $? 
enabled
0
You can use systemctl halt, poweroff, or reboot to shutdown or reboot the system. All three send a wall message to users warning that the system is going down.

Processes, cgroups, and Killing

systemd organizes processes with cgroups, and you can see this with the ps command, which has been updated to show cgroups. Run this command to see which service owns which processes:
$ ps xawf -eo pid,user,cgroup,args 
  PID USER     CGROUP                      COMMAND
 1338 root     name=systemd:/user/carla/2       \_ gdm-session-worker [pam/gdm-password]
 1358 carla    name=systemd:/user/carla/2           \_ /bin/sh /etc/xdg/xfce4/xinitrc
 1487 carla    name=systemd:/user/carla/2               \_ /usr/bin/ssh-agent /bin/sh -c exec -l /bin/bash -c "startxfce4"
 1515 carla    name=systemd:/user/carla/2               \_ xscreensaver -no-splash
 1517 carla    name=systemd:/user/carla/2               \_ xfce4-session

cgroups were introduced into the Linux kernel a few years ago, and they are an interesting mechanism for allocating and limiting kernel resources. In systemd, cgroups are used to corral and manage processes. When new processes are spawned they become members of the parent's cgroup. The cgroup is named for the service it belongs to, and services cannot escape from their cgroups so you always know what service they belong to. When you need to kill a service you can kill the cgroup, and snag all of its processes in one swoop instead of playing find-the-fork-or-renamed-process. Another way to view the process hierarchy is with the system-cgls command, as shown in Figure 2.
Figure 2: Partial output from system-cgls showing process cgroups.
Figure 2: Partial output from system-cgls showing process cgroups.

There is my old friend Avahi daemon. So instead of hunting down and killing the two Avahi processes the old-fashioned way, systemd lets me do it in one command:
# systemctl kill avahi-daemon.service
Lennart Poettering, the main author of systemd, has written a series of articles for sysadmins. They're not indexed, so here are links for your convenience. These cover customizing startup services, runlevels, gettys, and everything you need to know to control systemd