Jennifer Lin’s Weblog

August 3, 2009

Change your hostname without rebooting in RHEL

Filed under: UNIX/LINUX — jennyca @ 1:17 pm

Never reboot if you don’t have to and keep your uptime intact.

Logged in as root

vi /etc/sysconfig/network

HOSTNAME=harley.rxtest.com

save your change and exit vi.

vi /etc/hosts

192.168.1.x     harley.rxtest.com     harley

save your change and exit vi.

The changes to /etc/hosts and /etc/sysconfig/network are necessary to make your changes persistent.

# hostname harley.rxtest.com

changed the hostname that is currently set

# hostname

check if the hostname changed

Restart the network and apply the changes made to /etc/hosts and /etc/sysconfig/network

service network restart

To verify the hostname has been fully changed, logout of your system and you should see your new hostname being used at the login prompt and after you’ve logged back in.

http://www.xenocafe.com/tutorials/linux/redhat/change_hostname_without_reboot/index.php

December 10, 2008

Linux Background Job

Filed under: UNIX/LINUX — jennyca @ 2:10 am

A task can usually be started and run as a background task by putting a ‘&’ at the end of the command line.

If a task was started and is running in the foreground, it is still possible to move it to the background without cancelling it. To move a task from the foreground to the background perform the following steps:

  1. CTRL-Z (That is, while holding the CTRL key down, tap the ‘z’ key) This will suspend the current foreground job (task).
  2. Enter the job control command ‘bg’
  3. Tap the ‘Enter’ key

The job is now running in the background.

Useful commands to see which jobs are still running is the ‘jobs’ or the ‘ps ua’ commands. If the ‘jobs’ command is used, a background jobs can be brought to the foreground with the command fg n where n is the job (not the PID) number.

%	job number

&	execute the command background

^z	interrupt a job and stop it (suspended)

jobs	list the jobs being run in background

bg	place the job from suspend to background 

kill 	kill the specified job number

nohup	此程式可以讓使用者 logout 出去後,仍能繼續執行所指定的程式 

ps	顯示系統正在執行中的行程資訊
       【選項】
	-l  (list):顯示較多的資訊
	-t  termlist  (terminal):列出所指定termlist終端機所產生的處理程序
	-u  uidlist  (user ID):只列出在uidlist中所指定使用者識別碼或使用者名稱所產生的程序
	-g  grplist  (group ID):只列出在grplist中所指定群識別碼所產生的處理程序

October 30, 2008

Set Time and Date on Red Hat Enterprise Linux OS with CLI

Filed under: UNIX/LINUX — jennyca @ 3:44 pm

First lets look at the date. Issue:date at the CLI.

You should get a response like:
Fri Feb 15 11:36:02 CST 2008

If the time zone is off, type timeconfig and set it.

If the clock is off type: date -s 11:36:00
the -s means set then replace 11:36:00 with the respective time.

If the date is off, issue: date -s "02/15/2008" replacing the 02/15/2008 with the respective date.

Once you’ve changed everything to the way it needs to be, issue the command date again and verify.

http://blog.kameronkenny.com/?p=71

October 29, 2008

Red Hat Enterprise Linux version and Kernel version

Filed under: UNIX/LINUX — jennyca @ 7:23 pm

$  more /etc/redhat-release

Red Hat Enterprise Linux ES release 4 (Nahant)

Different releases:

workstation (WS), enterprise server (ES) and advanced server (AS)

CentOS, the free version derived from RHEL

As of 2005[update] Red Hat distributed four variants of Red Hat Enterprise Linux:

  • Red Hat Enterprise Linux AS for mission-critical/enterprise computer systems.
  • Red Hat Enterprise Linux ES for supported network servers
  • Red Hat Enterprise Linux WS for technical power-user desktops or high-performance computing
  • Red Hat Desktop – for multiple deployments of single-user desktops

In Red Hat Enterprise Linux 5 there are new editions that substitute former Red Hat Enterprise Linux AS/ES/WS/Desktop:

  • Red Hat Enterprise Linux Advanced Platform (former AS)
  • Red Hat Enterprise Linux (former ES) (limited up to 2 CPUs)
  • Red Hat Enterprise Linux Desktop with Workstation and Multi-OS option
  • Red Hat Enterprise Linux Desktop with Workstation option (former WS)
  • Red Hat Enterprise Linux Desktop with Multi-OS option
  • Red Hat Enterprise Linux Desktop (former Desktop)

Relationship to free or community distributions

  • Red Hat Linux 6.2 → Red Hat Linux 6.2E
  • Red Hat Linux 7.2 → Red Hat Enterprise Linux 2.1
  • Red Hat Linux 9 → Red Hat Enterprise Linux 3
  • Fedora Core 3 → Red Hat Enterprise Linux 4
  • Fedora Core 6 → Red Hat Enterprise Linux 5
  • Fedora 9 / Fedora 10 → Red Hat Enterprise Linux 6 (planned for release in the first quarter of 2010)

Version history

  • Red Hat Linux 6.2E (Zoot), 2000-03-27
  • Red Hat Enterprise Linux 2.1 AS (Pensacola), 26 March 2002
  • Red Hat Enterprise Linux 2.1 ES (Panama), May 2003
  • Red Hat Enterprise Linux 3 (Taroon), 2003-10-22, kernel 2.4.21-4
    • Update 1, 16 January 2004 (Release Notes) kernel 2.4.21-9
    • Update 2, 18 May 2004
    • Update 3, 3 September 2004
    • Update 4, 21 December 2004
    • Update 5, 20 May 2005, kernel 2.4.21-32
    • Update 6, 28 September 2005, kernel 2.4.21-35 (Release Notes)
    • Update 7, 15 March 2006
    • Update 8, 20 July 2006, kernel 2.4.21-47
    • Update 9, 15 June 2007, kernel 2.4.21-50
  • Red Hat Enterprise Linux 4 (Nahant), 2005-02-15, kernel 2.6.9-5
    • 4.1, also known as Update 1, 9 June 2005[8], kernel 2.6.9-11
    • 4.2, also known as Update 2, 5 October 2005 (Release Notes), kernel 2.6.9-22
    • 4.3, also known as Update 3, 7 March 2006 (Release Notes), kernel 2.6.9-34
    • 4.4, also known as Update 4, 11 August 2006 (Release Notes) kernel 2.6.9-42
    • 4.5, also known as Update 5, 1 May 2007 (Release Notes) kernel 2.6.9-55
    • 4.6, also known as Update 6, 15 November 2007 (Release Notes) kernel 2.6.9-67
    • 4.7, also known as Update 7, 24 July 2008 (Release Notes) kernel 2.6.9-78
  • Red Hat Enterprise Linux 5 (Tikanga), (Release notes) 2007-03-14, kernel 2.6.18-8

    http://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux

September 7, 2008

Why do init scripts require lock files?

Filed under: UNIX/LINUX — jennyca @ 3:41 am

When a service is started through an init script, a file is touched in the /var/lock/subsys/ directory with the same name as the init script. When the service is stopped, this file is removed. The contents of this file are unimportant for the scope of this article, as long as the filename is the same as the init script.

This file represents that a service’s subsystem is locked, which means the service should be running. Since a service may consist of multiple executables with different names, finding the process ID (PID) of a single executable may not be sufficient to determine the status of the entire service itself. For this reason, the command:

service <initscript> status

checks both the PID of the executable and the file in the /var/lock/subsys/ directory. If the PID is not found but the subsystem is locked, you will receive a message similar to this:

<service> dead but subsys locked

Managing a service’s subsystem has two purposes. First, if the service does not lock the subsystem, it can still be started and stopped through the service interface. However, when switching runlevels, the rc scripts check for the existence of the file in /var/lock/subsys/. If this file is not found, the service will not correctly start or stop between runlevels, even if there are start and kill symbolic links in the /etc/rc#.d/ directories.

Second, the /var/lock/subsys/ directory is checked during reboots and shutdowns. The order of a shutdown is as follows:

  1. Run service <initscript> stop for all known services
  2. Run kill -SIGTERM to terminate all processes
  3. Pause for five seconds
  4. Run kill -SIGKILL to kill all remaining processes

This method of shutting down is ordered such that processes are killed as gracefully as possible. During a shutdown, the script /etc/rc.d/init.d/killall checks the /var/lock/subsys/ directory to see if any subsystems are still locked. If a service’s subsystem is locked after all other services have been stopped (i.e. step 1 above has completed), the killall script uses the subsystem filename to call service <initscript> stop. This attempts to stop the service gracefully before handing off to steps 2 through 4, which forcefully terminate the process itself.

http://www.redhat.com/magazine/008jun05/departments/tips_tricks/

August 21, 2008

Getting Yesterdays or Tomorrows day with shell date command

Filed under: Utilities — jennyca @ 12:09 am

When invoked without arguments, the date command displays the current date and time. Depending on the options specified, date will set the date and time or print it in a user defined way. I’ve seen many people writing a perl script for calculating yesterday or tomorrow. Computer loves numbers but we love relative terms like 2 days ago. Luckily GNU date command is designed to handle relative date calculation.

Why use relative date formats?

[a] Ease of use
[b] To write your own scripts
[c] Automate task using cron (example run a job on last day of the month or Nth day of the month or 3rd Friday and so on)

First print today’s date:
$ date
Sun Jun 17 12:17:24 CDT 2007

Now display Yesterday’s date:
$ date --date="1 days ago"
OR try:
$ date --date="yesterday"
Sat Jun 16 12:17:20 CDT 2007

Now display Tomorrow’s date:
$ date --date="-1 days ago"
Or better try:
$ date --date="next day"
Sat Jun 16 12:17:20 CDT 2007

Getting date in the future

To get tomorrow and day after tomorrow (tomorrow+N) use day word to get date in the future:

Getting date in the past

To get yesterday and earlier day in the past use string day ago:

Moving by whole years or months

You can add year and months keywords to get more accurate date:
$ date --date='2 year ago' # past
$ date --date='3 years' # go into future
$ date --date='2 days' # future
$ date --date='1 month ago' # past
$ date --date='2 months' # future

Moving date using more precise units

  • You can use fortnight for 14 day
  • Week for 7 days
  • hour for 60 minutes
  • minute for 60 seconds
  • second for one second
  • You can also use this / now / today keywords to stress the meaning

To print the date of this Friday:
$ date --date='this Friday'
To print the date of the day six months and 15 day
$ date --date='6 months 15 day'
To print the date of the day two months and 5 days ago:
$ date --date='2 months 5 day ago'

You can also use relative format to setup date and time. For example to set the system clock forward by 30 minutes, enter:
# date --set='+30 minutes'

To display date in epoch time:
$ date --date='1970-01-01 00:00:01 UTC +5 hours' +%s

http://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html

Linux date 命令使用技巧

date命令
date命令的功能是显示和设置系统日期和时间。
该命令的一般格式为: date [选项] 显示时间格式(以+开头,后面接格式)
date 设置时间格式
命令中各选项的含义分别为:
-d datestr, –date datestr 显示由datestr描述的日期
-s datestr, –set datestr 设置datestr 描述的日期
-u, –universal 显示或设置通用时间
时间域
% H 小时(00..23)
% I 小时(01..12)
% k 小时(0..23)
% l 小时(1..12)
% M 分(00..59)
% p 显示出AM或PM
% r 时间(hh:mm:ss AM或PM),12小时
% s 从1970年1月1日00:00:00到目前经历的秒数
% S 秒(00..59)
% T 时间(24小时制)(hh:mm:ss)
% X 显示时间的格式(%H:%M:%S)
% Z 时区 日期域
% a 星期几的简称( Sun..Sat)
% A 星期几的全称( Sunday..Saturday)
% b 月的简称(Jan..Dec)
% B 月的全称(January..December)
% c 日期和时间( Mon Nov 8 14:12:46 CST 1999)
% d 一个月的第几天(01..31)
% D 日期(mm/dd/yy)
% h 和%b选项相同
% j 一年的第几天(001..366)
% m 月(01..12)
% w 一个星期的第几天(0代表星期天)
% W 一年的第几个星期(00..53,星期一为第一天)
% x 显示日期的格式(mm/dd/yy)
% y 年的最后两个数字( 1999则是99)
% Y 年(例如:1970,1996等)
需要特别说明的是,只有超级用户才能用date命令设置时间,一般用户只能用date命令显示时间。
例1:用指定的格式显示时间。
$ date ‘+This date now is =>%x ,time is now =>%X ,thank you !’
This date now is =>11/12/99 ,time is now =>17:53:01 ,thank you !
例2:用预定的格式显示当前的时间。
# date
Fri Nov 26 15:20:18 CST 1999
例3:设置时间为下午14点36分。
# date -s 14:36:00
Fri Nov 26 14:15:00 CST 1999
例4:设置时间为1999年11月28号。
# date -s 991128
Sun Nov 28 00:00:00 CST 1999
例5:设置一天前
date –date “1 days ago” +”%Y-%m-%d”

Date 命令参数小技巧
LastUpdated:2006-03-27
By:Gman!

-for beginner:wink:此参数可以用于日志处理和时间统计;

由于Linux对man date -d 参数说的比较模糊,故举例如下:
# -d, –date=STRING  display time described by STRING, not `now’

For Linux
[root@Gman root]# date -d next-day +%Y%m%d
20060328
[root@Gman root]# date -d last-day +%Y%m%d
20060326
[root@Gman root]# date -d yesterday +%Y%m%d
20060326
[root@Gman root]# date -d tomorrow +%Y%m%d
20060328
[root@Gman root]# date -d last-month +%Y%m
200602
[root@Gman root]# date -d next-month +%Y%m
200604
[root@Gman root]# date -d next-year +%Y
2007
——————————————————————————
而FreeBSD则不同;举例如下:
For FreeBSD
bash-2.05b# date -v -1d +%Y%m%d
20060326
bash-2.05b#  date -v -1m +%Y%m%d
20060227
bash-2.05b#  date -v -1y +%Y%m%d
20050327

http://www.zks.cn/article.asp?id=41

August 15, 2008

netrc

Filed under: UNIX/LINUX — jennyca @ 3:03 am

netrc, .netrc – user configuration for ftp

Description

This file contains configuration and autologin information for the File Transfer Protocol client ftp(1).

The .netrc file contains login and initialization information used by the auto-login process. It resides in the user’s home directory. The following tokens are recognized; they may be separated by spaces, tabs, or new-lines:

       machine name
Identify a remote machine name. The auto-login process searches the .netrc file for a machine token that matches the remote machine specified on the ftp command line or as an open command argument. Once a match is made, the subsequent .netrc tokens are processed, stopping when the end of file is reached or another machine or a default token is encountered.default
This is the same as machine name except that default matches any name. There can be only one default token, and it must be after all machine tokens. This is normally used as:

default login anonymous password user@site

thereby giving the user automatic anonymous ftp login to machines not specified in .netrc. This can be overridden by using the -n flag to disable auto-login.

login name
Identify a user on the remote machine. If this token is present, the auto-login process will initiate a login using the specified name.

password string
Supply a password. If this token is present, the auto-login process will supply the specified string if the remote server requires a password as part of the login process. Note that if this token is present in the .netrc file for any user other than anonymous, ftp will abort the auto-login process if the .netrc is readable by anyone besides the user.

account string
Supply an additional account password. If this token is present, the auto-login process will supply the specified string if the remote server requires an additional account password, or the auto-login process will initiate an ACCT command if it does not.

macdef name
Define a macro. This token functions like the ftp macdef command functions. A macro is defined with the specified name; its contents begin with the next .netrc line and continue until a null line (consecutive new-line characters) is encountered. If a macro named init is defined, it is automatically executed as the last step in the auto-login process.

UNIX 下 SCO TCP/IP ftp 命令表

Filed under: UNIX/LINUX — jennyca @ 2:58 am

UNIX 下 SCO TCP/IP ftp 命令表
序号 命 令 功 能
1 ! 执行本地 shell 命令
2 $ 执行宏功能
3 account 发送帐号口令到远程服务器
4 append 附加到文件中
5 ascii 设置 ASCII 码传输类型
6 bell 命令完成时响铃
7 binaey 设置二进制码传输类型
8 bye 结束并退出 ftp
9 case 触发远程文件名大小写变化功能
10 cd 改变远程工作目录
11 cdup 把远程工作目录改为其父目录
12 close 结束 ftp
13 cr 触发回车换行功能
14 delete 删除远程文件
15 debug 触发调试方式
16 dir 列远程目录
17 disconnect 结束 ftp
18 form 设置文件传输格式
19 get 取文件
20 glob 触发本地文件名元字母扩展功能
21 hash 为每个传输缓区触发#号打印功能
22 help 显示求助信息
23 lcd 改变本地工作目录
24 ls 列远程工作目录内容
25 macdef 定义宏功能
26 mdelete 删除远程主机上的多个文件
27 mdir 列多个远程目录的内容
28 mget 取多个文件
29 mkdir 在远程主机上建新目录
30 mls 列多个远程目录的内容
31 mode 设置文件传输方式
32 mput 发送多个文件
33 nmap 设置或取消文件名映射机制
34 ntrans 设置或取消文件名字符变换机制
35 open 连接远程主机
36 prompt 触发交互提示功能
37 proxy 在辅助控制连接上执行一条 ftp 命令
38 put 发送一个文件
39 pwd 显示远程机器上的工作目录
40 quit 结束并退出 ftp
41 quote 发送任意 ftp 命令
42 recv 取文件
43 remotehelp 取远程主机的求助信息
44 rename 重新命名远程文件
45 reset 清除应答队列
46 rmdir 删除远程主机的一个目录
47 runique 触发用本地唯一文件名存储功能
48 send 发送一个文件
49 sendport 为每个数据连接触发使用 PORT
50 status 显示当前状态
51 struct 设置文件传输结构
52 sunique 触发远程唯一主机文件存储功能
53 tenex 设置 tenex 文件传输类型
54 trace 触发分组跟踪功能
55 type 设置文件传输类型
56 user 发送新的用户信息
57 verbose 触发 verbose 方式
58 xmkdir 生成远程主机目录
59 xpwd 显示远程主机工作目录
60 xrmdir 删除远程主机目录
61 ? 显示本地 ftp 求助信息
不同的系统,上述命令可能有所差异,可用“?”获得帮助!

http://www.mypcera.com/softxue/txt1/ftpcmd.htm


August 13, 2008

UNIX: Flag an e-mail message as high priority

Filed under: UNIX/LINUX — jennyca @ 12:46 am

Question:  How can I flag an e-mail message as “high priority” in sendmail?

Answer:  E-mail was not originally designed to allow priority rankings. However, there are tags that can be added to the message header to simulate priority.

There are two tags that are commonly used by Microsoft to express priority in Outlook e-mail systems. These are:

X-Priority: 1 (Highest)
X-MSMail-Priority: High

To flag an e-mail as high priority using sendmail, you need to do the following:

First create a file called message.txt. An example of the file contents is shown below:

To: someone@yahoo.com
Subject: Test
Content-Type: text/plain
X-Priority: 1 (Highest)
X-MSMail-Priority: High

Hi there. How are you?

Somebody

Then enter the following command:

/usr/sbin/sendmail -t < message.txt

This will send an e-mail to someone@yahoo.com. If the recipient is using MS Outlook/Outlook Express, the message will appear as high priority. Please note that other e-mail packages may not acknowledge these tags at all or may interpret them differently than Outlook/Outlook Express.

http://www.techonthenet.com/unix/high_priority.php

July 27, 2008

Unix/Linux find command

Filed under: UNIX/LINUX — jennyca @ 9:14 pm

Locating Files:

The find command is used to locate files on a Unix or Linux system.  find will search any set of directories you specify for files that match the supplied search criteria.  You can search for files by name, owner, group, type, permissions, date, and other criteria.  The search is recursive in that it will search all subdirectories too.  The syntax looks like this:

find where-to-look criteria what-to-do

All arguments to find are optional, and there are defaults for all parts.  (This may depend on which version of find is used.  Here we discuss the freely available GNU version of find, which is the version available on YborStudent.)  For example where-to-look defaults to . (that is, the current working directory), criteria defaults to none (that is, show all files), and what-to-do (known as the find action) defaults to -print (that is, display found files to standard output).

For example:

find

will display all files in the current directory and all subdirectories.  The commands

find . -print
find .

do the exact same thing.  Here’s an example find command using a search criteria and the default action:

find / -name foo

will search the whole system for any files named foo and display them.  Here we are using the criteria -name with the argument foo to tell find to perform a name search for the filename foo. The output might look like this:

/home/wpollock/foo
/home/ua02/foo
/tmp/foo

If find doesn’t locate any matching files, it produces no output.

The above example said to search the whole system, by specifying the root directory (/) to search.  If you don’t run this command as root, find will display a error message for each directory on which you don’t have read permission.  This can be a lot of messages, and the matching files that are found may scroll right off your screen.  A good way to deal with this problem is to redirect the error messages so you don’t have to see them at all:

find / -name foo 2>/dev/null

Other Features And Applications:

The -print action lists the files separated by a space when the output is piped to another command.  This can lead to a problem if any found files contain spaces in their names, as the output doesn’t use any quoting.  In such cases, when the output of find contains a file name such as foo bar and is piped into another command, that command sees two file names, not one file name containing a space.

In such cases you can specify the action -print0 instead, which lists the found files separated not with a space, but with a null character (which is not a legal character in Unix or Linux file names).  Of course the command that reads the output of find must be able to handle such a list of file names.  Many commands commonly used with find (such as tar or cpio) have special options to read in file names separated with nulls instead of spaces.

You can use shell-style wildcards in the -name search argument:

find . -name foo\*bar

This will search from the current directory down for foo*bar (that is, any filename that begins with foo and ends with bar).  Note that wildcards in the name argument must be quoted so the shell doesn’t expand them before passing them to find.  Also, unlike regular shell wildcards, these will match leading periods in filenames.  (For example find -name \*.txt.)

You can search for other criteria beside the name.  Also you can list multiple search criteria.  When you have multiple criteria any found files must match all listed criteria.  That is, there is an implied Boolean AND operator between the listed search criteria.  find also allows OR and NOT Boolean operators, as well as grouping, to combine search criteria in powerful ways (not shown here.)

Here’s an example using two search criteria:

find / -type f -mtime -7 | xargs tar -rf weekly_incremental.tar
gzip weekly_incremental.tar

will find any regular files (i.e., not directories or other special files) with the criteria -type f, and only those modified seven or fewer days ago (-mtime -7).  Note the use of xargs, a handy utility that coverts a stream of input (in this case the output of find) into command line arguments for the supplied command (in this case tar, used to create a backup archive). 1

Another use of xargs is illustrated below.  This command will efficiently remove all files named core from your system (provided you run the command as root of course):

find / -name core | xargs /bin/rm -f
find / -name core -exec /bin/rm -f '{}' \; # same thing
find / -name core -delete                  # same if using Gnu find

(The last two forms run the rm command once per file, and are not as efficient as the first form.)

One of my favorite find criteria is to locate files modified less than 10 minutes ago.  I use this right after using some system administration tool, to learn which files got changed by that tool:

find / -mmin -10

(This search is also useful when I’ve downloaded some file but can’t locate it.)

Another common use is to locate all files owned by a given user (-user username).  This is useful when deleting user accounts.

You can also find files with various permissions set.  -perm /permissions means to find files with any of the specified permissions on, -perm -permissions means to find files with all of the specified permissions on, and -perm permissions means to find files with exactly permissionsPermisisons can be specified either symbolically (preferred) or with an octal number.  The following will locate files that are writeable by others:

find . -perm +o=w

(Using -perm is more complex than this example shows.  You should check both the POSIX documentation for find (which explains how the symbolic modes work) and the Gnu find man page (which describes the Gnu extensions).

When using find to locate files for backups, it often pays to use the -depth option, which forces the output to be depth-first—that is, files first and then the directories containing them.  This helps when the directories have restrictive permissions, and restoring the directory first could prevent the files from restoring at all (and would change the time stamp on the directory in any case).  Normally, find returns the directory first, before any of the files in that directory.  This is useful when using the -prune action to prevent find from examining any files you want to ignore:

find / -name /dev -prune | xargs tar ...

When specifying time with find options such as -mmin (minutes) or -mtime (24 hour periods, starting from now), you can specify a number n to mean exactly n, -n to mean less than n, and +n to mean more than n. 2 For example:

find . -mtime 0   # find files modified within the past 24 hours
find . -mtime -1  # find files modified within the past 24 hours
find . -mtime 1   # find files modified between 24 and 48 hours ago
find . -mtime +1  # find files modified more than 48 hours ago
find . -mmin +5 -mmin -10 # find files modifed between 6 and 9 minutes ago

The following displays non-hidden (no leading dot) files in the current directory only (no subdirectories), with an arbitrary output format (see the man page for the dozens of possibilities with the -printf action):

find . -maxdepth 1 -name '[!.]*' -printf 'Name: %16f Size: %6s\n'

As a system administrator you can use find to locate suspicious files (e.g., world writable files, files with no valid owner and/or group, SetUID files, files with unusual permissions, sizes, names, or dates).  Here’s a final more complex example (which I save as a shell script):

find / -noleaf -wholename '/proc' -prune \
     -o -wholename '/sys' -prune \
     -o -wholename '/dev' -prune \
     -o -wholename '/windows-C-Drive' -prune \
     -o -perm -2 ! -type l  ! -type s \
     ! \( -type d -perm -1000 \) -print

This says to seach the whole system, skipping the directories /proc, /sys, /dev, and /windows-C-Drive (presumably a Windows partition on a dual-booted computer).  The -noleaf option tells find to not assume all remaining mounted filesystems are Unix file systems (you might have a mounted CD for instance).  The -o is the Boolean OR operator, and ! is the Boolean NOT operator (applies to the following criteria).  So this criteria says to locate files that are world writable (-perm -2) and NOT symlinks (! -type l) and NOT sockets (! -type s) and NOT directories with the sticky (or text) bit set (! \( -type d -perm -1000 \)).  (Symlinks, sockets and directories with the sticky bit set are often world-writable and generally not suspicious.)

A common request is a way to find all the hard links to some file.  Using ls -li file will tell you how many hard links the file has, and the inode number.  You can locate all pathnames to this file with:

  find mount-point -xdev -inum inode-number

Since hard links are restricted to a single filesystem, you need to search that whole filesystem so you start the search at the filesystem’s mount point.  (This is likely to be either /home or / for files in your home directory.)  The -xdev options tells find to not search any other filesystems.

(While most Unix and all Linux systems have a find command that supports the -inum criteria, this isn’t POSIX standard.  Older Unix systems provided the ncheck command instead that could be used for this.)

Using -exec Efficiently

The -exec option to find is great, but since it runs the command listed for every found file, it isn’t very efficient.  On a large system this makes a difference!  One solution is to combine find with xargs as discussed above:

  find whatever... | xargs command

However this approach has two limitations.  Firstly not all commands accept the list of files at the end of the command.  A good example is cp:

find . -name \*.txt | xargs cp /tmp  # This won't work!

(Note the Gnu version of cp has a non-POSIX option -t for this.)

Secondly filenames may contain spaces or newlines, which would confuse the command used with xargs.  (Again Gnu tools have options for that, find ... -print0 |xargs -0 ....)

There are POSIX (but non-obvious) solutions to both problems.  An alternate form of -exec ends with a plus-sign, not a semi-colon.  This form collects the filenames into groups or sets, and runs the command once per set.  (This is exactly what xargs does, to prevent argument lists from becoming too long for the system to handle.)  In this form the {} argument expands to the set of filenames.  For example:

find / -name core -exec /bin/rm -f '{}' +

This form of -exec can be combined with a shell feature to solve the other problem.  The POSIX shell allows us to use:

sh -c 'command-line' [ command-name [ args... ] ]

(We don’t usually care about the command-name, so X, dummy, or inline cmd is used.)  Here’s an example of efficiently copying found files, in a POSIX-compliant way 3:

find . -name '*.txt' -exec sh -c 'cp "$@" /tmp' dummy {} +

Or even better:

find . -name '*.txt' -type f \
  -exec sh -c 'exec cp -f "$@" /tmp' find-copy {} +

The find command can be amazingly useful.  See the man page to learn all the criteria and options you can use.

http://content.hccfl.edu/pollock/Unix/FindCmd.htm

Next Page »

Blog at WordPress.com.