Showing posts with label FreeBSD. Show all posts
Showing posts with label FreeBSD. Show all posts

Sunday, June 3, 2007

Basics Of Securing FreeBSD

As the Internet becomes less and less of a friendly place, you don't want to be connected without being protected by some sort of firewall. Fortunately, FreeBSD supports two firewalls: ipfw and ipfilter. Here is some information to get you started:

man ipfw
FreeBSD Handbook: Chapter 10 -- Security -- Firewalls
man ipf
IPFilter and PF resources
For information on setting up IPfilter, refer to the Section6 Firewall Tutorial.
Good security is always "defense in layers," meaning that if one mechanism fails, there should be a backup mechanism. Even if your system is protected by a firewall, you should also disable all services except for those you absolutely need. On a desktop system, you need very few services.

To see which services are using ports on your system, use the following command:

sockstat -4
Your output will vary, depending upon what settings you selected during the final installation phase of FreeBSD and what ports and packages you have built since then.

[edit] Securing X11
It is very common to see X11 services port 6000 in the output. Unfortunately, there have been many X11 exploits over the years. Fortunately, you don't need to leave port 6000 open in order to use X11 on your system. Don't worry, you'll still have a Window Manager available if you close this port!

There are several ways to close this port; one of the easiest is edit /usr/X11R6/bin/startx, find the serverargs line and make the following change:

serverargs="-nolisten tcp"
Once you've saved your changes, start X as a regular user and rerun sockstat. Port 6000 should now be no longer open.

[edit] Securing Sendmail
If you'd like to read up on some of the security issues of leaving port 6000 open, refer to the Section6 X11 Security tutorial.

You now have one less service in your sockstat output. You probably still have two ports that deal with email: ports 25 (smtp) and 587 (submission). You don't need port 587 to send/receive email; to close it you can edit /etc/mail/sendmail.cf. Find this line:

O DaemonPortOptions=Port=587, Name=MSA, M=E
Comment it out, and then restart the service:

killall -HUP sendmail
The changes made to /etc/mail/sendmail.cf should now take effect. Repeat sockstat and port 587 should no longer show as open.

By default, FreeBSD runs with Sendmail enabled. If you do not wish to use the Sendmail as your MTA, simply make following change to /etc/rc.conf

sendmail_enable="NONE"
Afterwards, simply kill -9 sendmail and the service will no longer start when the system boots

[edit] Securing Services in /etc/rc.conf
Another common service on FreeBSD servers to look for is Portmap. Portmap, in conjuction with NFS is used to shared files between Unix computers. If you do not have a need for this service, then it is wise to disable it. When running sockstat, look for port 111 in the output and disable it by adding the following lines to /etc/rc.conf

nfs_server_enable="NO"
nfs_client_enable="NO"
portmap_enable="NO"
Syslog (port 514) will probably also show in your output. You most likely do not want to disable syslog completely, because you will not receive logging messages. However, you do not need to have this port open to do so. In your /etc/rc.conf file, make sure syslog is enabled and add a second line with some options:

syslogd_enable="YES"
syslogd_flags="-ss"
The -ss flag will disable logging from remote hosts and close that port, but still allow your localhost to keep its logging capabilities.

If you find any other questionable servcies in your sockstat output, man rc.conf to see if there is an option to disable it. If there isn't, it was most likely started with a startup script that was installed with a package or a port. If this is the case, then check the /usr/local/etc/rc.d directory

This will allow you to see which startup scripts have been added to your system. Most packages/ports will install a sample script with a "sample" extension. As long as it ends in "sample," that script will not run at startup. Other packages/ports install a working script that is read at bootup. These startup scripts usually end with an "sh" extension. The easiest way to disable the script is to rename it with a "sample" extension, and then kill the daemon so that its port number no longer shows up in the output of sockstat.

You might also want to consider adding the following options to /etc/rc.conf:

tcp_drop_synfin="YES"
This option prevents something known as OS fingerprinting, which is a scan technique used to determine the type of operating system running on a host. If you decide to enable this option, you will also have to rebuild your kernel with the following option included in your kernel configuration file:

options TCP_DROP_SYNFIN
Two related options are:

icmp_drop_redirect="YES"
icmp_log_redirect="YES"
ICMP redirects can be used to launch a DOS attack, as explained in the ICMP redirect portion of this ARP and ICMP redirection games article.

Be very careful if you decide to include the icmp_log_redirect option, as it will log every ICMP redirect, which has the potential of filling up your logging directory if you ever are the victim of this type of attack.

Another useful option in the /etc/rc.conf is

accounting_enable="YES"
This will enable system accounting. If you're new to system accounting, read the man pages for sa and lastcomm to decide whether this option would be useful to you or not.

Finally, this is a good option to include in /etc/rc.conf:

clear_tmp_enable="YES"
This will clear the /tmp directory at startup, which is always a good thing.

[edit] Converting passwd hashes to Blowfish
Changing the default algorithm used when encrypting a user's password can be very useful in securing accounts against local exploits. One renowned cipher that provides quick and secure encryption is called Blowfish. To implement Blowfish hashes, edit /etc/login.conf and change the following line:

:passwd_format=blf:\
Save the change, then rebuild the login database with the following command:

cap_mkdb /etc/login.conf
You'll then either have to change all of your users' passwords yourself, or instruct your users to change their passwords themselves so they will get a new Blowfish hash.

Once you're finished, double-check that it worked by checking the contents of the /etc/master.passwd file. All of the passwords for your users should begin with $2.

Finally, configure the adduser utility to use Blowfish whenever you create a new user by editing the /etc/auth.conf file. Make the following change:

crypt_default=blf
[edit] Changing the banner info
You've probably noticed when you log in to your FreeBSD system that your login prompt reminds you that you are running FreeBSD. And that after you log in, you receive the FreeBSD copyright information, which is followed by the version of FreeBSD and the name of your kernel, and finally, a useful (but rather boring) motd which again reminds you that you are running FreeBSD. You probably already know what version of FreeBSD you are running and might not want to share that information with the rest of the world. And the motd is a good place to remind the rest of the world that they shouldn't be messing with your system anyways.

You can edit the /etc/motd file to say whatever you wish to be displayed when one logs in to your system.

The next step is to remove the copyright info. Create an empty copyright file by running the following command:

touch /etc/COPYRIGHT
Then to change the text that appears at the login prompt, edit the /etc/gettytab. Find the line in the default:\ section that starts with the following:

:cb:ce:ck:lc
Carefully, change the text between \r\n\ \r\n\r\nr\n: to whatever text you wish to appear. Double-check that you have the right amount of \rs and \ns and save your change.

You can test your changes by logging out and checking the login prompt.

Finally, even though you've edited your motd to remove your version and kernel information, by default FreeBSD will still re-add it to /etc/motd every time you log in. To prevent this behavior, add the following line to /etc/rc.conf:

update_motd="NO"
This change requires a reboot, so make sure you've first tested your previous changes and have saved all of your work on any other terminals.

There are a few edits that will also restrict logins to your system in the first place. Since these changes modify the behavior of the login program, you'll want to carefully test your changes. Keep one terminal open and go to another terminal to log out and ensure that you can still log in. If for some reason you're unable to log in (this shouldn't happen, but you can't be too careful), you can return to the other terminal and look for errors in the file you just edited.

No one (including you) should log in to your system using the root account for general use. To prevent this from happening, edit /etc/ttys. Once you get past a page's worth of comments, you'll notice a section that goes from ttyv0 to ttyv8. Change the word secure on each of those lines to insecure. This is a file you don't want a typo in, so double-check your changes carefully. Test your change by trying to log in as root on one of your alternate terminals. You should receive a "Login incorrect" message.

[edit] Securing Login Locations
The last edit covered here allows you to restrict who can log in to your system and from where. This is done by editing /etc/login.access.

If you want to prevent all remote logins (meaning you can only log in if you are physically sitting at your system), remove the # from this line: #-:wheel:ALL EXCEPT LOCAL .win.tue.nl and remove the .win.tue.nl so that the line now looks like this:

-:wheel:ALL EXCEPT LOCAL
If you plan on accessing your system remotely, replace .win.tue.nl with the IP address(es) or hostname(s) of the system(s) you'll be logging in from. If there are multiple addresses, separate them with a single space. If you have only one or two user accounts that you wish to be able to log in to your system, you can prevent all other logins by making the following changes:

-:ALL EXCEPT user1 user2:ttyv0 ttyv1 ttyv2 ttyv3 ttyv4
Replace user1 user2 with the names of the user accounts to which you wish to give access. Put in as many ttys as you wish to restrict.

Alternatively, you can place the users in a group and give login access to that group. This example adds the users sam, bob, and dave to a group called mygroup and allows only the members of that group to login to the system. First, edit the /etc/group file and carefully add this line:

mygroup:*:100:sam,bob,dave
When you add your own group, make sure you use a GID (in my case, 100) that is not being used by any other lines in your /etc/group file.

Then, change /etc/login.access to:

-:ALL EXCEPT mygroup:ttyv0 ttyv1 ttyv2 ttyv3 ttyv4 ttyv5
It is very important you test this change. Leave one terminal logged in, just in case something goes wrong. Go to another terminal and try to log in as each of the users in your group. That should work. Then try to log in as another user; if need be, create a test account and try to log in as that test account. That login attempt should result in a "Permission denied" message.

FreeBSD Jail

Introduction
Jails are a great way to secure your processes to a virtual system. Though they have more overhead than chroot, (which basically just restricts the root of a process) a jail uses a virtual machine to house your process or processes. This means that far more restrictions can be placed on the jail, and there's no "breaking out" as can be done with chroot (see links in references).
A few notes first of all. It's very true what they say in the man page about it being easier to make a fat jail, and scale down to a thin one than vice versa. A few weeks of research (and many make worlds) have helped me discover that.
Also note that as of FreeBSD 5.4 (and likely 6.0) there is no IPv6 support for jails. This is unfortunate because jails tend to monopolize address space after making quite a few of them and address space is what IPv6 is all about. Sure there's NAT but everyone knows NAT is an ugly hack these days. I can only hope that IPv6 will be supported soon.
Jail Creation Techniques
From what I've seen there are three primary ways of creating jails.
MiniBSD
I've heard reports of people using [https://neon1.net/misc/minibsd.html MiniBSD] to do this, but I haven't had much luck with it, and I have yet to see a howto explaining how they made it work, it's a great idea of making an initial thin jail but there's a million things that can go wrong since it's very minimal and the service(s) you are trying to run may have dependancy issues.
Using /stand/sysinstall
Other howtos tell to use /stand/sysinstall to go out to the net, download the system binaries, and install specific distributions from the installer. I've had little luck with this as well since you run into the problem of not having an interface set up for the installer to use. There's probably a way to do this but none of the howtos I tried did a very good job of explaining how.
Using make world
This is the way I'll use here in this tutorial and the way explained in the manpage. You can customize the make file to scale down your distribution and set some optomization flags for your system. The primary drawback is the time it takes to build the world which can be hours depending on your system.
Getting services to not listen to *
First off, we should make sure we get the system so that we have nothing listening on *, to check what what we need to modify issue this command
sockstat|grep "\*:[0-9]"
This should give you a synopsys of all the processes and ports you need to trim down. Here are some hints with your ipv4 addr being 10.0.0.1 and your ipv6 addr being 2002::7ea9
sshd:
• edit /etc/ssh/sshd_config
• change ListenAddress derivative
ListenAddress 10.0.0.1
ListenAddress 2002::7ea9
httpd
• edit /usr/local/etc/apache/httpd.conf (and ssl.conf for https)
• change Listen derivative
Listen 10.0.0.1:80
Listen [2002::7ea9]:80
slapd
• edit /etc/rc.conf
• change slapd_flags
slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://10.0.0.1/ ldap://127.0.0.1/ ldap://[2002::7ea9]/"'
inetd
• edit /etc/rc.conf
• change inetd_flags=
inetd_flags="-wW -a yourhost.example.com"
mysql
• edit /etc/my.cnf
bind-address=10.0.0.1
postfix edit /usr/local/etc/postfix/main.cf
• change inet_interfaces
inet_interfaces = [2002::7ea9], 10.0.0.242
samba (this will get you most of the way there)
• edit /usr/local/etc/smb.conf
• change the following:
interfaces = 10.0.0.242/24 127.0.0.1
socket address = 10.0.0.242
bind interfaces only = yes
note: if you don't need wins lookups and netbios name translation
you can safely disable nmbd. There doesn't seem to be a way
for nmb to not listen to *:138 anyhow.
To disable nmb go to /etc/rc.conf and replace samba_enable="YES" with smbd_enable="YES"
openntpd (xntpd listens on all and cannot be changed)
*edit /usr/local/etc/ntpd.conf
listen on 10.0.0.1
listen on 2002::7ea9
syslogd
*edit /etc/rc.conf
syslogd_flags="-s -s" #For no listening
syslogd_flags="-a 10.0.0.1"
bind
• edit your named.conf (may be in /var/named/etc/named.conf)
• In the options section:
listen-on { 10.0.0.242; };
listen-on-v6 port 53 { 2002:d8fe:10f1:6:202:b3ff:fea9:7ea9; };
query-source address 10.0.0.242 port *;
query-source-v6 address 2002:d8fe:10f1:6:202:b3ff:fea9:7ea9 port *;
Unrealircd
• In the listen section:
listen[::ffff:10.0.0.1]:6667
listen[2002::7ea9]:6667
• In the "set { dns {" section
bind-ip 10.0.0.242;
Building your jail for the first time
Creating an appropriate make.conf
You'll need to run make world (or make installworld) to create your jail. If you don't want to install the whole kitchen sink you can use the make.conf below. You can put it in your jail for future use and it'll be used by future port builds inside your jail. One thing I've noticed is that make installworld doesn't seem to respect and MAKE_CONF or __MAKE_CONF variables passed to it so we'll just put it in /etc/make.conf for now.
Lets first back our current make.conf up:
cp /etc/make.conf /etc/make.conf.bak
And new one in there. Keep in mind, depending on what you want to use this jail for you may want to modify this make.conf. For me this has worked on building a variety of services from ports (inside the jail). I like to name the below file make.conf.jail and copy it to make.conf, then copy make.conf.bak back to make.conf when I'm done building the jail.
NO_ACPI= true # do not build acpiconf(8) and related programs
NO_BOOT= true # do not build boot blocks and loader
NO_BLUETOOTH= true # do not build Bluetooth related stuff
NO_FORTRAN= true # do not build g77 and related libraries
NO_GDB= true # do not build GDB
NO_GPIB= true # do not build GPIB support
NO_I4B= true # do not build isdn4bsd package
NO_IPFILTER= true # do not build IP Filter package
NO_PF= true # do not build PF firewall package
NO_AUTHPF= true # do not build and install authpf (setuid/gid)
NO_KERBEROS= true # do not build and install Kerberos 5 (KTH Heimdal)
NO_LPR= true # do not build lpr and related programs
NO_MAILWRAPPER=true # do not build the mailwrapper(8) MTA selector
NO_MODULES= true # do not build modules with the kernel
NO_NETCAT= true # do not build netcat
NO_NIS= true # do not build NIS support and related programs
NO_SENDMAIL= true # do not build sendmail and related programs
NO_SHAREDOCS= true # do not build the 4.4BSD legacy docs
NO_USB= true # do not build usbd(8) and related programs
NO_VINUM= true # do not build Vinum utilities
NO_ATM= true # do not build ATM related programs and libraries
NO_CRYPT= true # do not build any crypto code
NO_GAMES= true # do not build games (games/ subdir)
NO_INFO= true # do not make or install info files
NO_MAN= true # do not build manual pages
NO_PROFILE= true # Avoid compiling profiled libraries

# BIND OPTIONS
NO_BIND= true # Do not build any part of BIND
NO_BIND_DNSSEC= true # Do not build dnssec-keygen, dnssec-signzone
NO_BIND_ETC= true # Do not install files to /etc/namedb
NO_BIND_LIBS_LWRES= true # Do not install the lwres library
NO_BIND_MTREE= true # Do not run mtree to create chroot directories
NO_BIND_NAMED= true # Do not build named, rndc, lwresd, etc.
Building the Jail
Now for actually building your jail...
I'm defining JAILDIR here because I'm going to use it in a shellscript style example throughout the rest of this howto.
# Let's first make some directories
JAILDIR=/home/jail
mkdir -p $JAILDIR/dev
mkdir -p $JAILDIR/etc
mkdir -p $JAILDIR/usr/tmp
chmod 777 $JAILDIR/usr/tmp

cd /usr/src/

# You can replace the below with make installworld if you've built your
# world previously
make buildworld
make installworld DESTDIR=$JAILDIR
cd /usr/src/etc
cp /etc/resolv.conf $JAILDIR

make distribution DESTDIR=$JAILDIR NO_OPENSSH=YES NO_OPENSSL=YES
cd $JAILDIR

# At this point we'll mount devfs, and then hide the unneeded devs
mount_devfs devfs $JAILDIR/dev
devfs -m $JAILDIR/dev rule -s 4 applyset

# Create a null kernel
ln -s dev/null kernel

# Quell warnings about fstab
touch $JAILDIR/etc/fstab

# Use our existing resolv.conf
cp /etc/resolv.conf $JAILDIR/etc/resolv.conf

# Copy our settings for ssl
mkdir -p $JAILDIR/etc/ssl
mkdir -p $JAILDIR/usr/local/openssl
cp /etc/ssl/openssl.cnf $JAILDIR/etc/ssl
cd $JAILDIR/usr/local/openssl/
ln -s ../../../etc/ssl/openssl.cnf openssl.cnf

Make a decent rc.conf:
hostname="jail.example.com" # Set this!
ifconfig_em0="inet 10.0.0.20 netmask 255.255.255.255"
defaultrouter="10.0.0.1" # Set to default gateway (or NO).
clear_tmp_enable="YES" # Clear /tmp at startup.
# Once you set your jail up you may want to consider adding a good securelevel:
# Same as sysctl -w kern.securelevel=3
kern_securelevel_enable="YES" # kernel security level (see init(8)),
kern_securelevel="3"

You'll also want to make an alias on your interface for the ip above so we'll do something like:
ifconfig em0 10.0.0.20 netmask 255.255.255.255 alias
Now you'll want to have devfs inside your jail, so to get it working for the first time do this:
mount_devfs devfs $JAILDIR/devfs
And finally, copy your original make.conf back.
cp /etc/make.conf.bak /etc/make.conf
Starting the jail for the first time
OPTIONAL (but probably necessary): You'll want to mount /usr/ports and /usr/src so you can install ports inside your jail, unless you have another way you want to do this (such as downloading packages).
mount_nullfs /usr/ports $JAILDIR
mount_nullfs /usr/src $JAILDIR
Now we can start our jail
jail $JAILDIR jail.example.com 10.0.0.20 /bin/sh
Once inside the jail you'll want to start services:
/bin/sh /etc/rc
While you're here you'll want to edit your password file since if someone breaks into your jail, and starts cracking it you won't want them to have the same passwords as your root system has. Also remove all users you don't need in the jail:
vipw
passwd root
From here, assuming all went well you can do something like:
cd /usr/ports/security/openssh
make install clean
And build your port(s) inside your jail. Once you're finished be sure to unmount the directories so a compromised jail can't build more ports.

If you have trouble getting your programs to start inside your jail you can use the methods I outlined in [Chrooting_an_Eggdrop#Figuring_out_what_eggdrop_needs | my chroot tutorial]]. I've verifed that truss works correctly in a jail so between ldd and truss you should be set.
Also note that if you try to start your jail with just:
jail $JAILDIR jail.example.com 10.0.0.20 /bin/sh /etc/rc
but you have no services/daemons/programs set to run, the jail will simply start and then exit since there's nothing running inside.
Getting it to start automatically
You'll now need to put your settings in /etc/rc.conf First put the alias you jail has in there:
ifconfig_em0_alias0="inet 10.0.0.20 netmask 0xffffffff"
Editing the rc.conf
For those of you that are looking to make your own rc script, I don't recommend it. I've found issues getting devfs rules to be applied with the a script, and really this way is much easier. It's also the standard way and you can attach to jails later on quite easily without using screen (read below).
Here's the standard rc.conf way of getting your jail to run at startup:
jail_enable="YES" # Set to NO to disable starting of any jails
jail_list="cell" # Space separated list of names of jails
jail_set_hostname_allow="NO" # Allow root user in a jail to change its hostname
jail_socket_unixiproute_only="YES" # Route only TCP/IP within a jail

jail_cell_rootdir="/usr/home/prison/cell"
jail_cell_hostname="cell.example.com"
jail_cell_ip="10.0.0.20"
jail_cell_exec_start="/bin/sh /etc/rc"
jail_cell_devfs_enable="YES"
jail_cell_devfs_ruleset="devfsrules_jail"
Jail maintenance
Of course from time to time you may have to upgrade ports in your jail, or the world in the jail itself. This isn't a big deal either. Instead of using jail (which makes its own IP address and everything) we can use chroot instead which is similar since all we're using is a simple shell and then we'll be done with it.
First mount the dirs so they're accessable in the chroot:
mount_nullfs /usr/ports $JAILDIR
mount_nullfs /usr/src $JAILDIR
Connect to your jail: find the jail id of the jail you are running with jls:
#jls
JID IP Address Hostname Path
1 10.0.0.20 cell.example.com /usr/home/prison/cell
Now connect to it using the JID:
jexec 1 /bin/sh
To upgrade your world:
cd /usr/src
make buildworld
make installworld
NOTE: If you've just done make buildworld previously you can do make installworld and install all the newly compiled binaries again.
To build a port:
cd /usr/ports/sysutils/example
make install clean
NOTE: You may also want to install portupgrade to make port management easier.
When you're done just exit:
exit
Integrating Portaudit
You'll notice that portaudit security check only checks the root server, but none of the jails. There are many ways around this, but here's one:
Create a shell script in a place you keep custom shell scripts. We'll use /root/bin/metaportaudit.sh
#!/bin/sh

JAILDIR=/usr/home/prison/
JAILS="irc www mysql"
TMPDIR="/tmp"

# First lets audit the root server
/usr/local/sbin/portaudit -a

# Now Lets create temp files of ports in the jails,
# audit the root server all jails
# and delete the temp files
cd $TMPDIR
for jail in $JAILS; do
echo ""
echo "Checking for packages with security vulnerabilities in jail \"$jail\":"
echo ""
ls -1 $JAILDIR/$jail/var/db/pkg > $TMPDIR/$jail.paf
/usr/local/sbin/portaudit -f $TMPDIR/$jail.paf
rm $TMPDIR/$jail.paf
done
Now lets edit /usr/local/etc/periodic/security on about line 55
you'll want to change:
echo
echo /usr/local/sbin/portaudit -a |
su -fm "${daily_status_security_portaudit_user:-nobody}" || rc=$?
to
echo
echo /root/bin/metaportaudit.sh -a |
su -fm "${daily_status_security_portaudit_user:-nobody}" || rc=$?

Jails in Linux
Now you may think "well I have to use Linux, because xapplication only works on Linux!" Well there's hope. You can mess around with the bsdjail patch, or you can install vserver (which has packages in Debian). There's a great tutorial on vserver in Debian here:
Running_Vservers_on_Debian
References
• Creating a Jail Server
• http://chxo.com/gww/asparagus/notes/Creating_A_Jail_Server.html

• Jail Tools Cookbook
• http://www.the-labs.com/FreeBSD/JailTools/cookbook.html

Install Cacti in FreeBSD

安裝於 FreeBSD 需求的環境:

#/usr/ports/databases/mysql41-server
#make install
#/usr/ports/net-mgmt/net-snmp4
#make install
#/usr/ports/net/rrdtool
#make install
#/usr/ports/www/apache2
#make install
#/usr/ports/lang/php4 # 安裝這邊的 php4 已經包含( Apache Module and CLI )
#make install
#/usr/ports/lang/php4-extensions # 選擇你要的php 套件
#make install

開始安裝 cacti 套件:

#tar xzvf cacti-version.tar.gz # 解壓縮重 cacti 官網抓回的最新套件
#mysqladmin --user=root create cacti # 製做一個cacti 的資料庫
#mysql -p cacti < cacti.sql # 將 cacti 已經建好的資料表導入剛剛建好的 cacti 資料庫
#mysql -u root -pxxxxx # 使用 root 進入 mysql
mysql> GRANT ALL ON cacti.* TO cactiuser@localhost IDENTIFIED BY 'somepassword'; # 建立 cacti 資料庫的使用者帳號及密碼
Query OK, 0 rows affected (0.07 sec)
mysql> flush privileges; # 更新資料庫,使改變的部份生效
Query OK, 0 rows affected (0.05 sec)
mysql>exit # 跳出 mysql
Bye
#vi /usr/local/www/data-dist/cacti/include/config.php # 編輯 cacti 的 config 設定檔

$database_default = "cacti";
$database_hostname = "localhost";
$database_username = "cactiuser";
$database_password = "somepassword";

#pw adduser cactiuser # 建立 cactiuser 這個帳號
#passwd cactiuser
Changing local password for cactiuser
New Password: xxxx
Retype New Password: xxxx

#chown -R cactiuser rra/ log/ # 修改 rra 跟 log 兩個目錄權限讓 cactiuser 為擁有者
#crontab -e # 建立 crontab 每五分鐘跑一次 cacti 流量圖

*/5 * * * * /usr/local/bin/php /usr/local/www/data-dist/cacti/poller.php > /dev/null 2>&1

#php poller.php # 也可手動跑一次 cacti

最後設定 http://your-server/cacti/

開個瀏覽器開始瀏覽你的 cacti 目錄,並且進行第一次登入安裝設定,第一次進入的帳號密碼為 admin / admin ,登入前系統會要求你更改新的登入 admin 使用者密碼。

升級 CACTI - Upgrading CACTI :

#cd /usr/local/www/data-dist # 切換目錄到 www 的擺放目錄
#mysqldump -l --add-drop-table cacti > mysql.cacti # 將 mysql 的 cacti 資料庫備份出來
#mv cacti cacti_old # 改變舊的 cacti 目錄到 cacti_old 目錄
#tar -xzvf cacti-new-version.tar.gz # 抓到新版的 cacti 放置 /usr/local/www/data-dist 並解開壓縮
#mv cacti-new-version cacti # 更改新版的目錄名稱為 cacti
#vi include/config.php # 編輯新版的 config.php 檔

$database_default = "cacti";
$database_hostname = "localhost";
$database_username = "cactiuser";
$database_password = "xxxxx";

#cp cacti_old/rra/* cacti/rra/ # copy 舊資料到新版本資料夾
#cp cacti_old/scripts/* cacti/scripts/ # copy 舊的 scripts 到新資料夾
#chown -R cactiuser rra/ log/ # 改變 rra log 兩目錄擁有者權限

http://your-server/cacti/ # 開個瀏覽器進入 cacti 目錄就完成升級動作

補丁 CACTI - Patches CACTI

沒有任何一套軟體開發出來就是完美的,而且沒有那一家公司敢說它們自家的軟體完全無漏洞及 Bug ,軟體並不是完全無漏洞才是優質軟體,而是要有好的後端不斷支援才能稱得上好軟體,所以持續不斷的補丁便成為一套完善軟體必備的,CACTI 同樣也提供 Official Patches 不斷的為自家軟體做問題及漏洞更新,也就是它們的用心我們才有這樣方便的軟體使用,真的太感謝這些為 Opensouce 一直努力開發奉獻的團隊。到今天為止我安裝的 cacti-0.8.6c Release 版本,官方已公告了 3 個 patches :

#cd /usr/local/www/data-diste/cacti # 切換到 cacti 的目錄

#fetch http://www.cacti.net/downloads/patches/0.8.6c/rrd_fetch_negative_numbers.patch
Receiving rrd_fetch_negative_numbers.patch (601 bytes): 100%
601 bytes transferred in 0.0 seconds (1.76 MBps)
#patch -p1 -N < rrd_fetch_negative_numbers.patch
Hmm... Looks like a unified diff to me...
The text leading up to this was:
--------------------------
|--- cacti-0.8.6c/lib/rrd.php 2004-12-29 15:56:08.000000000 -0500
|+++ cacti-0.8.6c-new/lib/rrd.php 2004-12-29 15:56:48.000000000 -0500
--------------------------
Patching file lib/rrd.php using Plan A...
Hunk #1 succeeded at 368.
done


以下兩個補丁做法同上:

#fetch http://www.cacti.net/downloads/patches/0.8.6c/no_auth_no_graphs_in_tree_bug.patch
#fetch http://www.cacti.net/downloads/patches/0.8.6c/device_create_multiple_graphs.diff
#patch -p1 -N < no_auth_no_graphs_in_tree_bug.patch
#patch -p1 -N < device_create_multiple_graphs.diff

外掛 CACTI - Script & Templates

除了基本的 snmp 流量跟系統資訊監控外,cacti 也可外掛 Scripts 及加上 Templates 來作出各式各樣個監控圖,目前 cacti 官網已經開始進行官方版本的外掛開發收集,網址為:http://warehouse.cacti.net/index.php 如果等不及官方開發的套件的人,可到官網的討論區 http://forums.cacti.net/ 上面找尋,有很多使用者已經自己開發 scripts 跟 templates ,而且分享出來抓下來直接 Import Templates 即可。

Install Nagios in FreeBSD

用Nagios监控网络和网络服务器
nagios可以对服务器进行全面的监控,包括服务(apache、mysql、ntp、dns、disk、qmail和sshd等等)的状态,服务器的状态(up、down等等)。它是一个完全GPL协议的开源软件包,包含有nagios主程序和它的各个插件,配置非常灵活,可以监视的项目很多,可以自定义shell脚本进行监控服务,非常适合大型网络。

nagios的包含主动监控和被动监控。
主动检查是通过监控中心的主机发出请求,让运行在远程主机上的nrpe守护进程收集信息,然后报告它,它通过web接口把数据显示在页面上。
它的工作原理如下:

被动监控是当远程被监控主机处于防火墙之内的时候,只有远程主机可以访问到监控中心,防火墙之内可以设置另外一个监控中心,远程监控中心的nagios收集服务器信息以后,和nsca报告,由naca客户端报告naca的服务器端,然后报告监控中心的nagios,通过web接口显示监控结果。


nagios的功能非常强大,http://www.nagios.org/是它的窝,只有e文、法文和日文,没有中文,可惜啊。

我现在引用它的一段文字进行总结一下到底什么是nagios:
What Is This?
什么是nagios?
Nagios® is a system and network monitoring application. It watches hosts and services that you specify, alerting you when things go bad and when they get better.
Nagios was originally designed to run under Linux, although it should work under most other unices as well.
Some of the many features of Nagios® include:
Monitoring of network services (SMTP, POP3, HTTP, NNTP, PING, etc.)
Monitoring of host resources (processor load, disk usage, etc.)
Simple plugin design that allows users to easily develop their own service checks
Parallelized service checks
Ability to define network host hierarchy using "parent" hosts, allowing detection of and distinction between hosts that are down and those that are unreachable
Contact notifications when service or host problems occur and get resolved (via email, pager, or user-defined method)
Ability to define event handlers to be run during service or host events for proactive problem resolution
Automatic log file rotation
Support for implementing redundant monitoring hosts
Optional web interface for viewing current network status, notification and problem history, log file, etc.
Nagios是一个监视系统和网络的应用程序。它监视你所指定主机和服务,当监视的内容变好或者变坏时发出警告。Nagios最初是被设计在Linux平台上运行的,然而现在在其他平台上也运行良好。
Nagios的特性包括:
监视网络服务(SMTP, POP3, HTTP, NNTP, PING, 等等)
监视主机资源(处理器负载、磁盘空间等)
容许用户开发自己的插件去检查自定义的项目;
通过使用“父主机”,定义网络主机的分层,容许探测主机down掉或者不可到达。
可以定义在主机或服务运行期间,事件发生以后如何处理和解决方式;
自动记录错误日志;
支持冗余监视;
可选web接口,通过web页面查看当前网络状态,提示和报告故障历史,日志文件等;

Nagios的系统要求:
Linux、Unix等
apache
GD库(1.63以上)
zlib
pnglib
jpeglib
basic icons
等,其中apache的安装在blog中已经有相关的文章,搜索一下就行;gd、zlib、pnglib和jpeglib安装比较简单,步骤:
下载tarball
tar zxvf xxx.tar.gz
cd xxx
./configure
make && make install

----------------------------------------------------------------------
Nagios的安装过程(FreeBSD)
----------------------------------------------------------------------
nagios的安装比较简单,复杂的是设置和配置参数的设定。不过你要放松一点,毕竟我们要搞定它,不是吗?那就开始吧:

1:获得最新的安装包,http://www.nagios.org/download
2:以root身份登录服务器,目前最新的版本是2.5:
1)nagios,版本2.5:
fetch http://superb-west.dl.sourceforge.net/sour...gios-2.5.tar.gz
or
wget http://superb-west.dl.sourceforge.net/sour...gios-2.5.tar.gz

2)获得nagios插件,版本1.4.3:
http://surfnet.dl.sourceforge.net/sourcefo...ns-1.4.3.tar.gz

3)获得图库文件:
http://dl.sf.net/nagios/imagepak-base.tar.gz

4)NRPE,版本2.5.2
http://ufpr.dl.sourceforge.net/sourceforge...pe-2.5.2.tar.gz

5)NSCA,版本2.6
http://kent.dl.sourceforge.net/sourceforge...nsca-2.6.tar.gz

3:切换到root用户:
sudo su

4:解压缩
tar zxvf nagios-2.5.tar.gz

5:建立运行nagios的用户:
adduser nagios

6:建立安装nagios的文件夹,并使这个文件夹的所有者为nagios:nagios
mkdir /usr/local/nagios
chown nagios.nagios /usr/local/nagios

7:确认web服务器的用户
可能会通过web接口执行一些命令,必须确定web服务器以哪个用户运行的,通常为:apache:
grep "^User" /usr/local/apache2/conf/httpd.conf

8:建立命令文件组
这个新的组会包括apache的用户和nagios的用户
pw groupadd nagcmd
pw usermod apache -G nagcmd
pw usermod nagios -G nagcmd
----------------------------------
cat /etc/group
nagcmd:*:9007:apache,nagios
----------------------------------

8:运行配置脚本并安装nagios
cd nagios-2.5
./configure --prefix=/usr/local/nagios --with-gd-lib=/usr/local/lib --with-gd-inc=/usr/local/include
---------------------------------
*** Configuration summary for nagios 2.5 07-13-2006 ***:

General Options:
-------------------------
Nagios executable: nagios
Nagios user/group: nagios,nagios
Command user/group: nagios,nagios
Embedded Perl: no
Event Broker: yes
Install ${prefix}: /usr/local/nagios
Lock file: ${prefix}/var/nagios.lock
Init directory: /usr/local/etc/rc.d
Host OS: freebsd6.0

Web Interface Options:
------------------------
HTML URL: http://localhost/nagios/
CGI URL: http://localhost/nagios/cgi-bin/
Traceroute (used by WAP): /usr/sbin/traceroute


Review the options above for accuracy. If they look okay,
type 'make all' to compile the main program and CGIs.
---------------------------------
make all
make install
make install-init
make install-commandmode
make install-config

9:安装nagios-plugins
tar zxvf nagios-plugins-1.4.3.tar.gz
cd nagios-plugins-1.4.3
./configure --prefix=/usr/local/nagios-plugins
make all
make install
安装完成以后在/usr/local/nagios-plugins-plugins会产生一个libexec的目录,将该目录全部移动到/usr/local/nagios目录下即可。
mv /usr/local/nagios-plugins-plugins/libexec/ /usr/local/nagios/

10:imagepak-base.tar.gz的安装
tar –xvzf imagepak-base.tar.gz
解压以后是base目录
mv base/ /usr/local/nagios/share/images/logos/

----------------------------------------------------------------------
现在开始配置:
----------------------------------------------------------------------
1:配置web接口
假设你已经运行了apache,如果没有,请参考:
http://localhost/upload/blog.php?do-showone-tid-18.html

vi /usr/local/apache2/conf/httpd.conf
添加如下内容:
ScriptAlias /nagios/cgi-bin /usr/local/nagios/sbin


Options ExecCGI
AllowOverride None
Order allow,deny
Allow from all
AuthName "Nagios Access"
AuthType Basic
AuthUserFile /usr/local/nagios/etc/htpasswd.users
Require valid-user


Alias /nagios /usr/local/nagios/share


Options None
AllowOverride None
Order allow,deny
Allow from all
AuthName "Nagios Access"
AuthType Basic
AuthUserFile /usr/local/nagios/etc/htpasswd.users
Require valid-user

修改完毕,保存文件,并重启apache:
/usr/local/apahce2/bin/apachectl restart

2:配置apache的BASIC认证:
生成认证密码:
/usr/local/apache2/bin/htpasswd –c /usr/local/nagios/etc/htpasswd.users nagios nagios
apache接口配置完成。

开始配置nagios:
cd /usr/local/nagios/etc/
在/usr/local/nagios/etc下是nagios的配置模板文件-sample,把.cfg-sample文件全部拷贝成.cfg
例如:cp nagios.cfg-sample nagios.cfg
全部拷贝完成即可.

vi minimal.cfg
注释所有command:
注释的方法是在每一个定义语句前面添加”#“
修改cgi.cfg
修改use_authentication=1为use_authentication=0,即不用验证.不然有一些页面不会显示。

现在检查配置文件是否有语法错误:
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
如果正确,会显示以下结果:
Total Warnings: 0
Total Errors: 0
否则,需要根据提示进行修改配置文件。

配置文件等会再弄。现在启动nagios
/usr/local/nagios/bin/nagios -d /usr/local/nagios/etc/nagios.cfg

为了使nagios异常中断,我们使用daemontools启动:
安装daemontool:
mkdir -p /package
chmod 1755 /package
cd /package
fetch http://cr.yp.to/daemontools/daemontools-0.76.tar.gz
cd admin/daemontools-0.76/
package/install
检查svscan进程是否启动:
ps aux | grep svscan
root 376 0.0 0.0 1636 0 con- IW - 0:00.00 /bin/sh /command/svscanboot
root 411 0.0 0.0 1224 208 con- S 8Jul06 0:42.50 svscan /service

ok,启动正常了。
cd /service
mkdir nagios
chmod 1755 nagios
touch ./run
chmod 755 ./run
vi run
PATH=/usr/local/bin:/usr/bin:/bin
export PATH

exec env - PATH=$PATH \
/usr/local/nagios/bin/nagios /usr/local/nagios/etc/nagios.cfg

mkdir log
cd log
touch ./run
chmod 755 ./run
vi ./run
#!/bin/sh
exec setuidgid logadmin multilog t s1000000 n100 ./main

mkdir main
chmod 777 main
chown nagios.nagios main
touch status
chown nagios.nagios status

svc -u /service/nagios/
svstat /service/nagios/
root@## ps auxww | grep nagios
root 23276 0.0 0.1 1176 488 ?? I 5:00PM 0:01.71 supervise nagios
nagios 34251 0.0 0.3 2316 1552 ?? S 6:06PM 0:00.10 /usr/local/nagios/bin/nagios /usr/local/nagios/etc/nagios.cfg
root@##

ok,现在把nagios服务做成自动启动的服务了。
通过svc命令可以启动或者停止服务。
---------------------------------------------------------------------------------
svc opts services
opts is a series of getopt-style options. services consists of any number of arguments, each argument naming a directory used by supervise.

-u: Up. If the service is not running, start it. If the service stops, restart it.
-d: Down. If the service is running, send it a TERM signal and then a CONT signal. After it stops, do not restart it.
-o: Once. If the service is not running, start it. Do not restart it if it stops.
-p: Pause. Send the service a STOP signal.
-c: Continue. Send the service a CONT signal.
-h: Hangup. Send the service a HUP signal.
-a: Alarm. Send the service an ALRM signal.
-i: Interrupt. Send the service an INT signal.
-t: Terminate. Send the service a TERM signal.
-k: Kill. Send the service a KILL signal.
-x: Exit. supervise will exit as soon as the service is down. If you use this option on a stable system, you're doing something wrong; supervise is designed to run forever.
---------------------------------------------------------------------------------
比如:
停止nagios--svc -d /service/nagios/
重启nagios--svc -t /service/nagios/
启动nagios--svc -u /service/nagios/

当然,你也可以使用inited的方式进行:
/usr/local/etc/rc.d/nagios start/stop

好了,反正daemontools很强大,以后慢慢熟悉,转入正题。
现在打开网页:http://localhost/nagios/
一定会让你大吃一惊,呵呵,我的服务器和服务状态都清楚的看到了。
现在我们的nagios中只有一个,那就是它自己,localhost,呵呵,等会我们添加别的主机和主机服务,ok,我们认识一下nagios的庐山真面目:

配置nagios:

1)为主机添加服务
2)添加主机并添加服务
3)停止一个服务
4)删除一台主机和服务
5)查看所有主机的故障
6)查看一台特定的主机状态
7)改变报警的时间间隔
8)改变发现故障的重试次数
9)如何在nagios中使用外部命令


1)为主机添加一个服务
为localhost主机添加qmail服务的监控,方法如下:
vi minimal.cfg
define service{
use generic-service ; Name of service template to use
host_name localhost
service_description qmail_smtp
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_smtp!20%!10%!/
}

可以直接拷贝原有的进行修改,我这个就是拷贝的原有的check_local_disk进行的。
修改host_name,service_description,check_command等

define service{
use generic-service ; Name of service template to use
host_name localhost
service_description qmail_pop3
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_pop!20%!10%!/
}
照猫画虎的进行修改,然后去修改:
vi checkcommands.cfg
#'check_qmail' command definition
define command{
command_name check_qmail
command_line $USER1$/check_smtp -H 127.0.0.1
}
define command{
command_name check_pop3
command_line $USER1$/check_pop -H 127.0.0.1
}
保存,然后检查配置文件:
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
如果没有错误会显示:
Total Warnings: 0
Total Errors: 0
如果有错误,请根据提示进行错误的修正。
重启nagios
svc -d /service/nagios/ && svc -u /service/nagios/
通过web页面检查nagios的结果:
http://10.5.1.153/nagios/
点击“Service Detail”
会出现:

2)添加主机并添加服务
我们会监控这台主机的负载、磁盘等一些没有通过端口方式启动的服务器状态,以及它的服务,比如:apache、mysql、qmail和ntp等等吧。那么没有端口的nagios直接能监控到吗?答案是不行。所以我们必须在两台主机上安装nrpe,nrpe可以启动5666端口,把检测的信息源源不断的传给监控中心的主机。
ok,我们把apache、mysql、qmail和ntp先加上,这回我们把监控的主机和服务新建一个文件:
cd /usr/local/nagios/etc/
touch 10_5_1_156.cfg
vi nagios.cfg
cfg_file=/usr/local/nagios/etc/10_5_1_156.cfg

vi 10_5_1_156.cfg
定义一个主机:
define host{
use generic-host ; Name of host template to use
host_name test_nrpe
alias client
address 10.5.1.156
check_command check-host-alive
max_check_attempts 1
check_period 24x7
notification_interval 120
notification_period 24x7
notification_options d,r
contact_groups admins
}

定义主机需要检查的服务:
define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description PING
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_ping!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description apache
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_http!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description mysql
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_mysql!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description ntp
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_ntp!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description qmail_smtp
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_smtp!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description qmail_pop3
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_pop!100.0,20%!500.0,60%
}
现在我们象上次一样把服务也定义完了:
此时是不是多了一个主机和它下面的服务呢?那是肯定的,添加主机和服务可能出现的问题有如下情况:
1:配置参数出现问题,如果你没有检查配置就启动nagios,可能会启动成功,但是显示会不正常;
解决方法:调整配置参数
2:Connection refused
当出现这个问题的时候,我开始以为是ssh的无密码登录没有成功,但是其实我的服务器没有启动该服务造成的,启动服务即可。

但是这些是有端口的服务,没有使用端口的状态任何检测?
使用nrpe,ok,我们现在在服务器上安装nrpe:
一、远程主机的配置
1、安装nrpe与配置
fetch http://ufpr.dl.sourceforge.net/sourceforge...pe-2.5.2.tar.gz
tar zxvf nrpe-2.5.2.tar.gz
cd nrpe-2.5.2
./configure --enable-ssl --enable-command-args
make all
mkdir -p /usr/local/nagios/etc
mkdir /usr/local/nagios/bin
mkdir /usr/local/nagios/libexec
pw addgroup nagios
pw useradd nagios -g nagios -d /usr/local/nagios/ -s /sbin/nologin
chown -R nagios:nagios /usr/local/nagios
cp ./sample-config/nrpe.cfg /usr/local/nagios/etc
cp src/nrpe /usr/local/nagios/bin
2、启动nrpe,端口为5666
/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d
netstat -ant | grep 5666
tcp4 0 0 *.5666 *.* LISTEN

二、监控服务器上的配置
1、安装nrpe(主要是使用check_nrpe模块)
fetch http://ufpr.dl.sourceforge.net/sourceforge...pe-2.5.2.tar.gz
tar zxvf nrpe-2.5.2.tar.gz
cd nrpe-2.5.2
./configure --enable-ssl --enable-command-args
make all
cp src/check_nrpe /usr/local/nagios/libexec
2、nagios文件的配置
vi checkcommands.cfg
定义check_nrpe命令
# 'check_nrep' command definition
define command{
command_name check_nrpe
command_line /usr/local/nagios/libexec/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
}
三、上面我们已经配置了一部分参数,下面是配置的最终结果:
define host{
use generic-host ; Name of host template to use
host_name test_nrpe
alias client
address 10.5.1.156
check_command check-host-alive
max_check_attempts 1
check_period 24x7
notification_interval 120
notification_period 24x7
notification_options d,r
contact_groups admins
}

# 'check_load' command definition
define command{
command_name check_load
command_line $USER1$/check_load -w $ARG1$ -c $ARG2$
}

# 'check_load' command definition
define command{
command_name check_disk
command_line $USER1$/check_disk -w $ARG1$ -c $ARG2$
}
define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description PING
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_ping!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description apache
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_http!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description mysql
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_mysql!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description ntp
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_ntp!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description qmail_smtp
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_smtp!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description qmail_pop3
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_pop!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description test_load
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_load!100.0,20%!500.0,60%
}

define service{
use generic-service ; Name of service template to use
host_name test_nrpe
service_description test_disk
is_volatile 0
check_period 24x7
max_check_attempts 1
normal_check_interval 1
retry_check_interval 1
contact_groups admins
notification_options w,u,c,r
notification_interval 960
notification_period 24x7
check_command check_disk!100.0,20%!500.0,60%
}

四、检查配置参数并重启nagios


9)如何在nagios中使用外部命令
vi /usr/local/nagios/etc/nagios.cfg
check_external_commands=1

mkdir /usr/local/nagios/var/rw
chown nagios.nagcmd /usr/local/nagios/var/rw
chmod u+rw /usr/local/nagios/var/rw
chmod g+rw /usr/local/nagios/var/rw
chmod g+s /usr/local/nagios/var/rw

svc -t /service/nagios/
/usr/local/apache2/bin/apachectl restart

FreeBSD 6.2, Snort, and Base - IDS System

Step #1 – Initial Setup of FreeBSD and hardware
In this step I am not going to go into exact details since that would be a document all by itself. My example install will include a 20GB /var partition, plenty of room for the snort databases, and a minimal install profile.

For my hardware I have a 2Ghz P4, 1GB RAM, 80GB Hard Drive, and two Gigabit NICs. This should give me plenty of resources for my lab network and lab internet connection. One NIC will be used for the actual “sniffing” of the network while the other will be for accessing a web interface.
At this point you should have the following on your FreeBSD System:
-Minimal Installation
-Ports Tree
-Source (optional)
-Internet Connectivity
-Static IP for web interface
Step #2 – Installing the required software (via ports tree)
Install MySQL 4.1
cd /usr/ports/databases/mysql41-server
make BUILD_OPTIMIZED=yes install clean
Install Apache 2.2
cd /usr/ports/www/apache22
make install clean
-When prompted for install options, leave default
Install PHP5
cd /usr/ports/lang/php5
make install clean
Keep the default options and add: APACHE
Install PHP5 Extensions
cd /usr/ports/lang/php5-extensions
make install clean
Keep the default options and add: GETTEXT, GD, MYSQL, PDF, ZIP, ZLIB
Install Snort
cd /usr/ports/security/snort
make install clean
Keep the default options and add: MYSQL
Install Base
cd /usr/ports/security/base
make install clean
Keep the default options and add: MYSQL, PDF
Install PHPMyAdmin (optional)
cd /usr/ports/databases/phpmyadmin
make install clean
Keep the default options
Install Oinkmaster
cd /usr/ports/security/oinkmaster
make install clean
rehash
Step #3 – Configuring MySQL 4.1
Starting MySQL
/usr/local/etc/rc.d/mysql-server start
Changing the MySQL root password
mysqladmin –u root password
Setup #4 – Configure Apache22 (Bare minimum changes)
Adding a kernel module for Apache22
vi /boot/loader.conf
Add the line: accf_http_load=”YES”
:wq
Enter the command: kldload accf_http
DNS Name Resolution – Do this if your IP is not resolved by DNS
vi /etc/hosts
add the line:
example: 192.168.1.100 snort snort.lab1.local
Configuring the httpd.conf file
(Note: This is a general config and is not intended to cover all situations)
vi /usr/local/etc/apache22/httpd.conf
Change the following lines
ServerName :80
Listen :80
DirectoryIndex index.html index.php
Add the following lines(around line 290):
Alias /phpMyAdmin/ “/usr/local/www/phpMyAdmin/”

Order deny,allow
Allow from all
AuthType basic
AuthName “Private Area”
AuthUserFile “/usr/local/www/password”
Require valid-user

Alias /base/ “/usr/local/www/base/”

Order deny,allow
Allow from all
AuthType basic
AuthName “Private Area”
AuthUserFile “/usr/local/www/password”
Require valid-user

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
:wq
Set the password file for Apache access
Enter the command: htpasswd –c /usr/local/www/password
(This will prompt you to enter a password)
To add additional user or change existing users passwords:
Enter the command: htpasswd /usr/local/www/password
Configure PHP
Enter the command: cp /usr/local/etc/php.ini-recommended /usr/local/etc/php.ini
Change one line in /usr/local/etc/php.ini: error_reporting = E_NOTICE to error_reporting = E_ALL & ~E_NOTICE
Test Apache22 to verify it is working
Enter the command: apachectl start
Open a web browser and surf to http://
You should see a page displaying “It Works!”
Step #5 – Configuration of PhpMyAdmin (optional)
Edit configuration files
vi /usr/local/www/phpMyAdmin/libraries/config.default.php
edit line: $cfg[‘Servers’][$i][‘password’] = ‘’
:wq!
Test PhpMyAdmin
Using a web browser surf: http:///phpMyAdmin/
You should be prompted for a password and allowed access
Step #6 – SQL Snort Configuration
Setup MySQL databases for Snort
Using PhpMyAdmin create the following databases: snort and archive
Select the snort database in the dropdown on the left
Copy the SQL commands from the file /usr/local/share/examples/snort/create_mysql into the “Run SQL” box under the SQL tab in PHPMyAdmin and select “GO”
Select the archive database in the dropdown on the left
Copy the SQL commands from the file /usr/local/share/examples/snort/create_mysql into the “Run SQL” box under the SQL tab in PHPMyAdmin and select “GO”
Creating a Snort SQL user
On the main screen, click on “Privileges”
Verify that user root has a password associated with it for both localhost and your FQDN name
Click “Add a new User”
Add the following:
User name: snort
Host:
Password:
Click “GO”
Find the “Database-specific privileges”
Use the drop down to select the “snort” database
Select the following privledges: SELECT,INSERT,UPDATE,DELETE,CREATE,ALTER,INDEX,DROP
Click “GO”
Click the house icon in the upper left corner
On the main screen, click on “Privileges”
Click the edit icon
Find the “Database-specific privileges”
Use the drop down to select the “archive” database
Select the following privledges: SELECT,INSERT,UPDATE,DELETE,CREATE,ALTER,INDEX,DROP
Click “GO”
Edit the Snort Configuration File – (Note: This is a VERY basic snort config)
vi /usr/local/etc/snort/snort.conf
Delete EVERYTHING and add:
var HOME_NET [10.0.0.0/8,192.168.0.0/16,172.0.0.0/16,172.26.0.0/16]
var EXTERNAL_NET any
var DNS_SERVERS $HOME_NET
var SMTP_SERVERS $HOME_NET
var HTTP_SERVERS $HOME_NET
var SQL_SERVERS $HOME_NET
var TELNET_SERVERS $HOME_NET
var SNMP_SERVERS $HOME_NET
var HTTP_PORTS 80
var SHELLCODE_PORTS !80
var ORACLE_PORTS 1521
var AIM_SERVERS [64.12.24.0/23,64.12.28.0/23,64.12.161.0/24,64.12.163.0/24,64.12.200.0/24,205.188.3.0/24,205.188.5.0/24,205.188.7.0/24,205.188.9.0/24,205.188.153.0/24,205.188.179.0/24,205.188.248.0/24]
var RULE_PATH ./rules
dynamicpreprocessor directory /usr/local/lib/snort/dynamicpreprocessor/
dynamicengine /usr/local/lib/snort/dynamicengine/libsf_engine.so
preprocessor flow: stats_interval 0 hash 2
preprocessor frag3_global: max_frags 65536
preprocessor frag3_engine: policy first detect_anomalies
preprocessor stream4: disable_evasion_alerts
#preprocessor bo
preprocessor ftp_telnet: global \
encrypted_traffic yes \
inspection_type stateful
preprocessor ftp_telnet_protocol: telnet \
normalize \
ayt_attack_thresh 200
preprocessor ftp_telnet_protocol: ftp server default \
def_max_param_len 100 \
alt_max_param_len 200 { CWD } \
cmd_validity MODE < char ASBCZ > \
cmd_validity MDTM < [ date nnnnnnnnnnnnnn[.n[n[n]]] ] string > \
chk_str_fmt { USER PASS RNFR RNTO SITE MKD } \
telnet_cmds yes \
data_chan
preprocessor ftp_telnet_protocol: ftp client default \
max_resp_len 256 \
bounce yes \
telnet_cmds yes
preprocessor smtp: \
ports { 25 } \
inspection_type stateful \
normalize cmds \
normalize_cmds { EXPN VRFY RCPT } \
alt_max_command_line_len 260 { MAIL } \
alt_max_command_line_len 300 { RCPT } \
alt_max_command_line_len 500 { HELP HELO ETRN } \
alt_max_command_line_len 255 { EXPN VRFY }
preprocessor dcerpc: \
autodetect \
max_frag_size 3000 \
memcap 100000
preprocessor dns: \
ports { 53 } \
enable_rdata_overflow
output database: log, mysql, user=snort password=epic2533 dbname=snort host=localhost
output database: alert, mysql, user=snort password=epic2533 dbname=snort host=localhost
output alert_unified: filename /var/log/snort/snort.alert, limit 512
output log_unified: filename /var/log/snort/snort.log, limit 512
include classification.config
include reference.config
include $RULE_PATH/bleeding.rules
include $RULE_PATH/bleeding-attack_response.rules
include $RULE_PATH/bleeding-botcc.rules
include $RULE_PATH/bleeding-dos.rules
include $RULE_PATH/bleeding-drop.rules
include $RULE_PATH/bleeding-dshield.rules
include $RULE_PATH/bleeding-exploit.rules
include $RULE_PATH/bleeding-game.rules
include $RULE_PATH/bleeding-inappropriate.rules
include $RULE_PATH/bleeding-malware.rules
include $RULE_PATH/bleeding-p2p.rules
#include $RULE_PATH/bleeding-policy.rules
include $RULE_PATH/bleeding-scan.rules
include $RULE_PATH/bleeding-virus.rules
include $RULE_PATH/bleeding-voip.rules
include $RULE_PATH/bleeding-web.rules
Step #7 – Updating Snort Rules
Create script for updating snort rules
mkdir /root/scripts
vi /root/scripts/bleedingupdate.sh
oinkmaster –o /usr/local/etc/snort/rules/ -u \
http://www.bleedingsnort.com/bleeding.rules.tar.gz
:wq!
chmod 777 /root/scripts/bleedingupdate.sh
cp /usr/local/etc/oinkmaster.conf.sample /usr/local/etc/oinkmaster.conf
Test the script
/root/scripts/bleedingupdate.sh
ls /usr/local/etc/snort/rules
(You should see a bunch of files bleeding-.rules)
Set rules to automatically update
vi /etc/crontab
1 */3 * * * root /root/scripts/bleedingupdate.sh && /usr/local/etc/rc.d/snort restart
:wq!
Step #8 – Setting up everything to run on startup
Add the following to the /etc/rc.conf file
apache22_enable=”YES”
mysql_enable=”YES”
snort_enable=”YES”
snort_interface=”bge0”
Change bge0 interface to the interface you want to the interface “sniff” with, such as “xl0”.
Restart you FreeBSD box
reboot
Step #9 – Setting up and using BASE
BASE installation
chmod –R 777 /usr/local/www/base/
Use a web browser and got to http:///base/
Fill out the questions prompted
(Note: The path to Adodb is: /usr/local/share/adodb)
Make sure you enable the checkmark to use the Archive database
Checking to see if BASE is working
Use a web browser and got to http:///base/
If you see the base webpage and there are no errors, its working
Step #10 – Verify everything is working
Make use both you NICs are connected to you network traffic
Use a web browser and got to http:///base/
Need more information or help?
FreeBSD – http://www.freebsd.org
Snort – http://www.snort.org
BASE - http://sourceforge.net/projects/secureideas
Bleeding Snort Rules - http://www.bleedingsnort.com/
This document only addresses the installation of Snort as an IDS system and just scratches the surface of what Snort is capable of.

FreeBSD Tips

開機時關掉 APIC
可以在 loader prompt 時輸入
代碼:
set hint.apic.0.disabled=1


掛載光碟 ISO 檔
$ mkdir /mnt/5.2.1-RELEASE
$ mdconfig -a -t vnode -f /home/ftp/pub/ISO-IMAGES/FreeBSD/5.2.1-RELEASE/5.2.1-RELEASE-i386-disc1.iso -u 1
$ mount_cd9660 /dev/md1 /mnt/5.2.1-RELEASE

如有問題 (例:找不到 /dev/md1 或 mount 失敗)
請確定有將以下兩項編入核心
代碼:
device md # Memory "disks"
options CD9660 # ISO 9660 Filesystem

如 options CD9660 未編入核心
可直接執行 kldload cd9660.ko 後就可以 mount 了

記錄畫面中的所有顯示出的訊息 (以 make world 為例)
$ script /var/tmp/mw.out
Script started, output file is /var/tmp/mw.out
$ make world
… compile, compile, compile …
$ exit
Script done, …

刪除 path 路徑以下,所有 .php 文件每個行尾的 ^M 符號
$ find /path -name "*.php" | xargs -n 1 perl -pi -e "s/\r//g"


利用 pw 指令來增加/變換 user 的 group
例:帳號 abcd 所屬群組 abcd

變換帳號 abcd 的預設群組為 staff (當然得要先有 staff 這個群組)
$ pw user mod -n abcd -g staff
$ groups abcd
staff


變換帳號 abcd 的預設群組為 office,並加入到 www,mysql,squid 三群組中
$ pw user mod -n abcd -g office -G www,mysql,squid
$ groups abcd
office www mysql squid


不變換預設群組,只將帳號 abcd 加入到 office,staff,game,software 四群組中
$ pw user mod -n abcd -G office,staff,game,software
$ groups abcd
abcd www mysql squid


將帳號 abcd 維持在預設群組中,並從其它附屬的群組中移除
$ pw user mod -n abcd -G ""
$ groups abcd
abcd



用 postfix 本機測試寄信到自行假設的假 domain

/etc/hosts 中加入
192.168.1.100 aaa.bbb

然後在 /usr/local/etc/postfix/main.cf 最後加入
ignore_mx_lookup_error = yes
disable_dns_lookups = yes

重新載入 postfix 設定檔
postfix reload

就可以寄信給 test@aaa.bbb 囉...

註1:disable_dns_lookups = yes 包含 ignore_mx_lookup_error = yes
本例中,可以直接用 disable_dns_lookups = yes 選項解決無法寄信的問題

註2:
如果沒有設定 ignore_mx_lookup_error = yes (如果對方沒有設定 mx 可以用這個解決)
May 14 13:35:31 test postfix/smtp[99813]: D60AC40260: to=, relay=none, delay=3162, status=deferred (Name service error for name=aaa.bbb type=MX: Host not found, try again)

如果是一個完全假造的 domain,請加上 disable_dns_lookups = yes
May 14 13:42:02 test postfix/smtp[99844]: 249754026C: to=, relay=none, delay=3235, status=deferred (Name service error for name=aaa.bbb type=A: Host not found, try again)

後記:
在一個正常服務的 mail server 中,最好是不要加上 disable_dns_lookups = yes
否則他就不會去參考 resolv.conf 的設定,直接只參照 /etc/hosts 的設定值
這樣收信都沒問題....但是有許多的郵件都會寄送不出去


dmesg

/var/log/dmesg.today
/var/log/dmesg.yesterday
這兩個檔案會記錄兩天內在 consol 上出現有關硬體的訊息

指令 dmesg 僅會秀出 /var/log/dmesg.today 的訊息

而開機時的硬體訊息會保持在
/var/run/dmesg.boot

所以如果開機很多天了,要查本機相關的硬體訊息
最好是直接看 /var/run/dmesg.boot 的內容


MAKEDEV

FreeBAD 5.x 之後已經沒有 MAKEDEV,請改用 devfs


pkg_create 製作套件備份
代碼:
$ pkg_create -c amavisd -b amavisd-20020531_1 /tmp/amavisd-20020531_1.tgz
-c 註解
-b 套件名稱

tcpdump 的使用

監控 fxp0 這一張網卡上
來源 IP是 192.168.129.80 目的 IP 是192.168.129.82 並且目的 port 是 25 的封包
代碼:
$ tcpdump -npi fxp0 src host 192.168.0.80 and dst host 192.168.0.82 and dst port 25


註:
-n 是指以數字顯示 取代 domain 及協定,必須寫在 -i 之前
-p 是指不要讓網卡進入混雜模式 (promiscuous mode),必須寫在 -i 之前
-i 是指網卡
src host 是指來源位置
src port是指來源埠號
dst host 是指目的位置
dst port是指目的埠號

變更 FreeBSD 的 perl 版本

在 FreeBSD 4.x 版中...perl 是與系統一併安裝
到了 FreeBSd 5.x 才在安裝時把它分離出來

如果你使用 FreeBSD 4.x 的 OS
它的 perl 版本是比較舊的 5.0.x.x 的版本

我們可以透過 ports 來安裝較新的版本

不過在安裝完成之後,
還要使用 use.perl 這個指令才能讓系統使用新版的 perl
當然這個指令還能讓我們從新版本換回舊版本
以防止新版本的 perl 發生問題時,可以後悔
(其實新舊版本會同時存在於系統中)
代碼:
# use.perl
Usage:
/usr/local/bin/use.perl port -> /usr/bin/perl is the perl5 port
/usr/local/bin/use.perl system -> /usr/bin/perl is the system perl

所以我們使用下面的指令來讓系統使用 ports 安裝的版本
代碼:
#use.perl port

如果要換回舊版本
代碼:
#use.perl system


註:
1. 執行 use.perl port 時 /usr/bin/perl 會變成連結到 /usr/local/bin/perl 的 soft link
2. 執行 use.perl system 時 /usr/bin/perl 會換回原來系統安裝時的二進制檔案

SoftUpdates 提高檔案系統效能

從 FreeBSD 4.x 開始,ufs 檔案格式加入了一種叫做 SoftUpdates 的技術,可提高檔案系統的效能。除了 / 根目錄外,所有的 ufs slice 都建議打開 SoftUpdate,這樣對於提高系統整體校能很有好處。

雖然 / 根目錄也是 ufs slice,但是在 FreeBSD 文件的說明中有提到,在 / 根目錄打開 SoftUpdates 會造成系統不穩定。由於 / 根目錄的內容不需要經常變化,不打開 SoftUpdates 也不會影響到效能。

SoftUpdates 可以隨時透過 tunefs(8) 來打開或關閉。
如果要改變 / 根目錄的 SoftUpdates 狀態
請先進入 single-user-mode
代碼:
# tunefs -n disable /

如果是要改變其它掛載點的 SoftUpdates 狀態
請先 umount 該掛載點
代碼:
# umount /home
# tunefs -n enable /dev/ad0s2e

直接下 mount 指令,你可以看到那些掛載的 slice 是有開啟 SoftUpdates 的
# mount
代碼:
/dev/ad0s1a on / (ufs, local)
/dev/ad0s2e on /home (ufs, local, soft-updates)
/dev/ad0s2f on /usr (ufs, local, soft-updates)
/dev/ad0s1f on /var (ufs, local, soft-updates)
procfs on /proc (procfs, local)

而在初安裝 FreeBSD 的設定 label 步驟中,打開 SoftUpdates 會將檔案系統顯示為 utfs+s

掛載 Samba 或 Windows 所分享出來的檔案系統 (smbfs)

指令:mount_smbfs -I 主機IP //登入帳號@主機IP或名稱/分享目錄 /掛載點

例:
mount_smbfs -I 192.168.0.200 //jackie@192.168.0.200/sharefolder /mount/point
mount_smbfs -I 192.168.1.10 //ryan@192.168.1.10/ryan /mount/ryan

如果你是要掛載 Windows 所分享出來的目錄
則上述主機IP或名稱的部份
一定要使用網芳名稱才能被掛載

例:
mount_smbfs -I 192.168.1.10 //ryan@fileserver/AVCD /mount/AVCD
mount_smbfs -I 192.168.129.68 //administrator@jackie/mp3 /mount/mp3

後記:發現不用 -I 也可以直接掛載 Windows 的 share folder
轉貼自 http://phorum.study-area.org/viewtopic.php?t=21220
如果要修改掛上去的權限 可以用
mount_smbfs -f 664 -d 755 -L zh_TW.Big5 //user_name@netbios_name/folder /mnt

-f :修改檔案權限
-d:修改目錄權限

tcsh 環境變數

按兩下 Tab 顯示出可用的指令
代碼:
set autolist


讓 tcsh 在 idle 30 分鐘後,自動 logout
代碼:
set autologout = 30


FreeBSD 預設 rm、cp、mv 都沒有確認的提示
所以如果你要 rm 一個檔案,那它就直接刪了
這是一個很危險的動作,由其是常常用 root 工作的人
請在自己家目錄的 .cshrc 中加入以下三行,這樣會比較保險
代碼:
alias rm rm -i # 刪除確認
alias cp cp -i # 拷貝確認
alias mv mv -i # 搬移確認

讓你環境變數不管怎麼設定,vi 都能顯示中文
代碼:
alias vi 'env LC_CTYPE=en_US.ISO8859-1 vi'
alias mutt 'env LC_CTYPE=zh_TW.Big5 mutt'


For Screen 的設定

/usr/local/etc/screenrc 或 ~/.screenrc 中設定可加入
代碼:
bindkey ^f screen -t [ssh]test@backup ssh test@backup.idv.tw
sorendition rg
hardstatus alwayslastline "%{.w} %c:%s | %Y.%m.%d | %{gb} %w %{= dd} "
shell tcsh

screen -t "AAAA"
可以把該 screen session 定 Label 為 AAAA 以做識別

說明:
1. bindkey ^f screen -t [ssh]test@backup ssh test@backup.idv.tw
代表按下 Ctrl + f 可以執行後面的指令

2. sorendition rg
screen 訊息的文字及背景顏色
r 紅色 w 白色 g 綠色 b 藍色 .....

3. hardstatus 這一行表示在執行 screen 時,最後一行一直顯示時間及不同 session 的訊息
例如:
17:31 | 03.12.2003 | 0 tcsh 1* [ssh]test@backup

4. shell tcsh
表示 screen 中預設使用 tcsh

讓 screen 在提示字元後面顯示目前的 screen 數
例:
test@www[/home/test](0)
test@www[/home/test](1)

在 ~/.cshrc 中加入下面的文字
代碼:
if ( ! $?WINDOW ) then
set prompt = "%n@%m[%/] "
else
set prompt = "%n@%m[%/]($WINDOW) "
endif


設定時區

先到 /usr/share/zoneinfo/ 裏面找到你所在地區的檔案
再以 root 執行
代碼:
# tzsetup /usr/share/zoneinfo/Asia/Taipei


Is this machine's CMOS clock set to UTC?
要設定為格林威治時間嗎?==> NO

Use the default `/usr/share/zoneinfo/Asia/Taipei' zone?
設定為臺北時間嗎?==> YES

最後校時 (請先安裝 ntp)
代碼:
# ntpdate clock.stdtime.gov.tw


時間格式說明

CST => China time 中原標準時間 (GMT+8)
GMT => 格林威治標準時間

美國是有實施日光節約時間的國家
所以現在是 PDT, MDT, CDT, EDT
Pacific Time, Mountain Time, Central Time, Eastern Time
Chicago 應該是 Central time 吧

新增使用者
代碼:
# adduser -v <== 使用參數 v 可以知道建立帳號時的較細部流程及注意事項
/etc/adduser.conf: No such file or directory <== 出現這一行代表你可能是第一次新增使用者
Use option ``-silent'' if you don't want to see all warnings and questions.

Check /etc/shells
Check /etc/master.passwd
Check /etc/group
User ``test'' has gid 1091 but a group with this gid does not exist.
User ``cvsup'' has gid 908 but a group with this gid does not exist.
User ``cvsupin'' has gid 909 but a group with this gid does not exist.
Usernames must match regular expression:
[^[a-z0-9_][a-z0-9_-]*$]:
..... 以下略


rc.conf Configuration
代碼:

#--- rc.conf ---#
ifconfig_fxp0="inet 172.16.16.1 netmask 255.255.255.0"
#ifconfig_fxp0="DHCP" #設定成 dhcp client 自動分配 ip
defaultrouter="172.16.16.254"
hostname="test.abcd.com.tw"

sshd_enable="YES"
syslogd_enable="YES"
syslogd_flags="-ss"
# 註:-s 是啟用安全模式,不記錄遠端傳送過來的 log
# 如果 -ss 是關閉 port,而且也禁止將 log 傳送到遠端的電腦。
sendmail_enable="NO"
# 註:NO 是僅提供 localhost 的 mail 功能,如果要完全關閉 sendmail 要用 NONE
inetd_enable="NO"
# 註:4.4-Release 版之後的 FreeBSD 預設 /etc/initd.conf 中的所有服務都是 # 註解掉的
# 如果你確定你的 Server 不提供 inetd 服務,可以加上這行
tcp_drop_redirect="YES"
# Don't allow remote OS fingerprinting of your box
icmp_drop_redirect="YES"
# 註:防止 DoS 攻擊,最好把 ICMP 重導向的封包丟棄
icmp_log_redirect="YES"
# 註:將丟棄的 ICMP 重導向封包 log 記錄下來
clear_tmp_enable="YES"
# 開機時清除 /tmp 的內容
icmp_bmcastecho="NO"
# 不回應 broadcast ping 封包
fsck_y_enable="YES"
# 註:do fsck -y if the initial preen fails
update_motd="NO"
# 註:update version info in /etc/motd (or NO)
named_enable="YES"
# 提供 DNS 的服務
ntpdate_enable="YES"
ntpdate_flags="clock.stdtime.gov.tw"
# 開機自動校時
keyrate="fast"
# 重覆按下按鍵的速度


郵件設定

如果想把寄到主機中某一個帳號的信件全部直接刪除
(刪除的意思是指不佔用磁碟空間,而且寄信者以為信件已安全寄達給收件者,但實際上是被系統刪掉了)

以 mailtest 這個帳號舉例:
請修改 aliases
在 aliases 中加入
代碼:
mailtest: /dev/null


重新建立 aliases.db
代碼:
# postalias aliases

即可生效


保存畫面中的資訊

有的時候你在執行某些程式時,畫面會出現一大堆訊息
等程式執行完後,你捲動畫面卻只能看到一小部份的訊息文字
現在就是教你如何把畫面中出現的訊息記錄下來
代碼:
# telnet tw.yahoo.com 80 | tee /tmp/yahoo.log
Trying 202.1.237.21...
Connected to vip1.tw.tpe.yahoo.com.
Escape character is '^]'.
GET / HTTP/1.0 <=== 這裏按兩下 Enter

HTTP/1.1 200 OK
Date: Fri, 26 Dec 2003 03:02:04 GMT
P3P: policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi S
AMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"
Cache-Control: private
Connection: close
Content-Type: text/html
........ 以下網頁內容省略 ..........
#


這樣你就可以在 /tmp/yahoo.log 中看到所有在畫面中出現的訊息囉....
註:在某些程式中所輸入的指令並不會出現在所導出的文字檔案中
下面就是文字檔的前幾行,並不包含上面標示成紅色的文字
因為紅色的文字是在 telnet 連線下所輸入,並不會被導出到檔案中
代碼:
Trying 202.1.237.21...
Connected to vip1.tw.tpe.yahoo.com.
Escape character is '^]'.
HTTP/1.1 200 OK
Date: Fri, 26 Dec 2003 03:02:04 GMT
P3P: policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi S
AMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"
Cache-Control: private
Connection: close
Content-Type: text/html


排程相關技巧

FreeBSD系統預設的排程目錄
/etc/periodic/daily/
/etc/periodic/monthly/
/etc/periodic/weekly/

可看到系統預設排程的執行時間
less /etc/crontab
當然我們也可以把自己要執行的排程
寫到這個檔案中,系統便會自動執行

Postfix

查詢 postfix 設定檔 main.cf 可用的參數
代碼:
# postconf -d


查詢 postfix 的版本
代碼:
# postconf mail_version


讓 User Unknown 時,Postfix 回 550 error code
代碼:
soft_bounce = no


註:如果設定成 soft_bounce = yes,User Unknown 會回 450,造成對方持續重 try

ssh 相關
一行 ssh 指令直接完成登入、su、下命令
代碼:
# ssh -t david@abc.test.tw 'su root -c "vi /etc/hosts"'



秀出 routing table
代碼:
# netstat -rn
Routing tables

Internet:
Destination Gateway Flags Refs Use Netif Expire
default 192.168.129.254 UGSc 1 38974 lnc0
172.16.16/24 link#2 UC 2 0 lnc1
172.16.16.100 00:0c:29:a7:cb:e7 UHLW 1 6165 lnc1 917
172.16.16.150 00:0c:29:d3:f8:1f UHLW 1 884 lnc1 924
192.168.129 link#1 UC 5 0 lnc0
192.168.129.80 00:07:e9:13:a0:d4 UHLW 2 10052 lnc0 1094
192.168.129.81 00:0c:29:80:37:f0 UHLW 0 160 lo0
192.168.129.83 00:90:4b:00:6b:65 UHLW 1 1032 lnc0 607
192.168.129.253 00:90:fb:81:1f:ba UHLW 0 0 lnc0 1090
192.168.129.254 00:10:d1:01:be:30 UHLW 1 0 lnc0 452

FreeBSD for Linux Users

Today's article examines some of the common command differences a Linux user might encounter on a FreeBSD system.

One of the minor irritations that comes with using another operating system is the change in the environment. Some of the first things many Linux users discover about a default FreeBSD installation are that it doesn't include bash and doesn't colorize the output of ls. Fortunately, if you've become accustomed to these features, it only takes a moment or so to integrate them into FreeBSD. First, as the superuser, add the bash package:
# pkg_add -r bash
That command will go out on the Internet, find the pre-compiled package, install it for you, and update /etc/shells. Note that the path for bash is different on FreeBSD, as it is a third-party application rather than part of the base operating system install:
$ which bash
/usr/local/bin/bash
Hint: in FreeBSD, user binaries that come with the operating system go in /bin, system binaries in /sbin, and system configuration files in /etc. You'll find the equivalents for third-party applications in /usr/local/bin, /usr/local/sbin, and /usr/local/etc. This makes it easier to determine what did and didn't come with the operating system.
Then, from your regular user account, create an alias to ls to use the colorized switch:
$ vi ~/.bashrc
alias ls='ls -G'
Once you've saved your file, type bash to start the shell and issue an ls command to test your change.
Modifying Existing User Accounts
Rather than typing bash every time you log in, you'll probably want to change the default shell of your regular user account to bash; this will require modifying the password database. Like most Linux distros, FreeBSD uses a shadow database. Unlike Linux, this isn't /etc/shadow. Instead, it's /etc/master.passwd, and--this is very important--you don't send this file directly to an editor. (See "Adding a User to FreeBSD, Part 2.")
Instead, use the chpass utility to update all of the password databases correctly. Here, I set the shell for the user dru:
# chpass -s /usr/local/bin/bash dru
chpass: updating the database...
chpass: done
Like the Linux command usermod, chpass has other switches; see man chpass for details. Alternately, if you're comfortable using the vi editor and prefer to see exactly what you're editing, use vipw instead. This will open up the password database in vi and update it correctly when you save your edits.
That reminds me. If you learned how to use vi in Linux, you probably instead learned how to use vim. FreeBSD, by default, uses nvi. If you miss vim, simply type:
# pkg_add -r vim5
Then, set vim as your default editor by adding this line to your ~/.bashrc file:
export EDITOR=/usr/local/bin/vim
Don't forget to type . ~/.bashrc to notify bash of the change to its configuration file. Now vipw will use vim instead of vi. If you're editing files that don't use the $EDITOR variable, and don't think you'll remember to type vim filename instead of vi filename, add an alias to vim in your ~/.bashrc file.
Creating User Accounts
Unix provides several utilities to create user accounts, and you'll probably find the utility you're used to using on a FreeBSD system. The FreeBSD Handbook gives an overview and some working examples of each in the modifying users section. In particular, if you're used to using adduser, you'll find that FreeBSD's version uses an interactive mode.
If you prefer to use an ncurses-type GUI, use the /stand/sysinstall menu. Its Configure option allows you to install software, create users, configure networking, and configure X.
Device Names
You'll find some minor differences in device names. For example, your first Ethernet NIC won't be /dev/eth0. Instead, the device name will indicate the chipset used in your NIC. Here's one way to find out your NIC name(s):
$ dmesg | grep Ethernet
rl0: Ethernet address: 00:05:5d:d2:19:b7
rl1: Ethernet address: 00:05:5d:d1:ff:9d
ed0: port 0x9800-0x981f irq 10 at
device 11.0 on pci0
This particular system has three Ethernet cards: two Realtek cards (rl0 and rl1) and one generic card (ed0). I found the names of the chipsets by sending those NIC names (minus their numbers) to whatis:
$ whatis rl
rl(4) - RealTek 8129/8139 Fast Ethernet device driver

$ whatis ed
ed(1), red(1) - text editor
ed(4) - ethernet device driver
man 4 rl and man 4 ed describe which particular NIC models the specified chipset covers.
You'll also find that the names for your hard drives and partitions are different:
$ df
Filesystem 1K-blocks Used Avail Capacity Mounted on
/dev/ad0s1a 253678 65594 167790 28% /
devfs 1 1 0 100% /dev
/dev/ad0s1e 253678 18482 214902 8% /tmp
/dev/ad0s1f 13147670 6526230 5569628 54% /usr
/dev/ad0s1d 253678 42232 191152 18% /var
linprocfs 4 4 0 100% /usr/compat/linux/proc
Compare that to the df output from a Red Hat system:
$ df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/hda2 9506024 2080628 6942516 24% /
/dev/hda1 99043 9275 84654 10% /boot
none 63016 0 63016 0% /dev/shm
/dev/cdrom 636408 636408 0 100% /mnt/cdrom
Red Hat uses hd to represent an IDE hard drive; FreeBSD uses ad. Red Hat uses a to represent the primary master; FreeBSD uses 0. Red Hat follows the a with a number representing the partition--in this case, 1 and 2 are the first two primary partitions. FreeBSD uses slices (hence the s) and this system has 1 FreeBSD slice divided into several partitions. By convention, partition a is / and b is /swap. This particular system also has d mounted on /var, e mounted on /tmp, and f mounted on /usr.
Note: like Linux, FreeBSD uses the file /etc/fstab to determine how to mount filesystems; however, it does not use the file /etc/mtab. (If you've installed Linux compatibility, use more /usr/compat/linux/proc/mtab instead.) The commands mount and df list the currently mounted filesystems.
What Happened to /proc?
You're in for a surprise if you habitually poke about /proc for information on your hardware and the state of your running Linux system. Again, if you've installed Linux compatibility, you'll find most of what you're looking for in /usr/compat/linux/proc. However, also experiment with FreeBSD's powerful sysctl mechanism.
Typing sysctl -a | more (a for "all") is the equivalent of viewing every /proc entry at once, and then some. This is an excellent way not only to watch what happens on a running system but also to understand what the term "kernel state" means. I recommend you try this command at least once.
A judicious use of grep can help when you know what you're looking for. For example, to see current memory usage:
% sysctl -a | grep -i memory
Virtual Memory: (Total: 614K, Active 185444K)
Real Memory: (Total: 295928K Active 100972K)
Shared Virtual Memory: (Total: 74960K Active: 68524K)
Shared Real Memory: (Total: 43296K Active: 40048K)
Free Memory Pages: 36412K
p1003_1b.memory_protection: 0
p1003_1b.shared_memory_objects: 1
The superuser has the capability of changing many of the sysctl tunables on the fly. For example, to view the system's TTL:
# sysctl -a | grep ttl
net.inet.ip.ttl: 64
To change (write to) it:
# sysctl -w net.inet.ip.ttl=100
net.inet.ip.ttl: 64 -> 100

#sysctl net.inet.ip.ttl
net.inet.ip.ttl: 100
man sysctl and the tuning with sysctl section of the Handbook have more information.
Many Linux commands (e.g., ps, top, and free, to name a very few) query /proc for information on what is currently happening on the system. Similarly, many FreeBSD commands query sysctl. While you could manually send the information in /proc to a pager or grep through sysctl -a, it's often easier to have a command do the query and format the results for you. For example, on a FreeBSD 5.x system, devinfo will show your system resources, categorized by type of resource:
$ devinfo -ru
Interrupt request lines:
0x0 (root0)
0x1 (atkbd0)
0x3 (sio1)
0x4 (sio0)
0x5 (rl0)
0x6 (fdc0)
0x7-0x8 (root0)
0x9 (acpi0)
0xa (pcm0)
0xb (uhci0)
0xc (psm0)
0xd (root0)
0xe (ata0)
0xf (ata1)
DMA request lines:
0-1 (root0)
2 (fdc0)
3-7 (root0)
I/O ports:
0x0-0xf (root0)
0x10-0x1f (acpi_sysresource0)
0x20-0x21 (root0)

I/O memory addresses:
0x0-0x9ffff (root0)
0xa0000-0xbffff (vga0)
0xc0000-0xcbfff (orm0)
0xcc000-0xfbffffff (root0)
0xfc000000-0xfdffffff (agp0)
0xfe000000-0xffffffff (root0)
open if_tun units:
0-32767 (root0)
swapinfo will show your currently mounted swap devices:
$ swapinfo
Device 1K-blocks Used Avail Capacity
/dev/ad0s1b 637704 156 637548 0%
There are dozens of other useful utilities available. To find them, try these commands:
$ apropos info | grep 8
$ apropos stat | grep 1
$ apropos stat | grep 8
Modules
Like Linux, the FreeBSD kernel supports the loading and unloading of modules. This allows an administrator to add or remove driver support without having to recompile the kernel or reboot the system. The possible modules are the files ending with the .ko extension in /boot/kernel.
To list the currently loaded modules:
$ kldstat
Id Refs Address Size Name
1 10 0xc0400000 3348d8 kernel
2 1 0xc0735000 51ac8 acpi.ko
3 1 0xc3168000 6000 linprocfs.ko
4 1 0xc316e000 19000 linux.ko
If you're curious as to the meaning of each of the columns, see man 2 kldstat. Note that the usage and output is similar to Linux's lsmod command.
Linux also provides the insmod and rmmod commands to load and unload modules. The FreeBSD equivalents are kldload and kldunload. For example, to load USB scanner support:
# kldload uscanner.ko
To remove it when you're finished:
# kldunload uscanner.ko
Loading something that is already statically compiled into the kernel produces this error message:
# kldload snd_pcm.ko
kldload: can't load snd_pcm.ko: File exists
If you don't know what a module does, ask whatis. Suppose that I'm curious about the module if_pcn.ko. I won't include the .ko in my query. I also won't include the if_; it categorizes the module as an interface type. (Similarly, snd_ represents the sound category.) That leaves pcn, making this command:
$ whatis pcn
pcn(4) - AMD PCnet/PCI fast ethernet device driver
I think my NIC might fall into that category. man 4 pcn gives the actual NIC models covered by this particular kernel module.
FreeBSD Terminology
To end this article, here are the FreeBSD equivalents to some common Linux tasks, as well as some document references to start you in your own research.
You won't find ipfwadm, ipchains, or ipfilter on a FreeBSD system. However, FreeBSD does come with several built-in firewalls. ipfw provides a stateful firewall with an easily understandable rule syntax. Ipfilter, or ipf, provides a more complex rulebase that supports the chaining of rules. Newer FreeBSD versions also support OpenBSD's pf. The firewall section of the Handbook is a good place start. It contains hyperlinks to several sites with more detailed documentation.
FreeBSD also supports NAT (IP masquerading) and bandwidth limiting (known as dummynet). Start with the Advanced Networking section of the Handbook.
The author of dummynet has a useful dummynet tutorial and Erudition has a comprehensive NAT tutorial.
FreeBSD uses vinum to provide software RAID. Dan Langille details real-world vinum usage at his FreeBSD Diary.
FreeBSD also supports netgraph (4) to augment the kernel's networking support. DaemonNews has an excellent netgraph article, and the See Also section of the manpage refers to the available netgraph modules. There are also several working examples found within the subdirectories of /usr/share/examples/netgraph.
Finally, FreeBSD 5.x supports the use of gbde to encrypt disk partitions. BSD News has a tutorial showing how to encrypt a USB thumbdrive using both GBDE and the CFS third-party application.
Conclusion
Once you're familiar with FreeBSD terminology and some of the design differences between Linux and FreeBSD, you'll find that most of your Linux skills easily transfer over to FreeBSD. As you read the FreeBSD handbook and manpages, you're likely to discover new skills that you can practice on both operating systems.

FreeBSD Jumpstart Guide

1 Introduction
Warning: This procedure will make the ``Server'' both insecure and dangerous, it is best to just keep the ``Server'' on its own hub and not in any way accessible by any machines other than the ``Clients''.
Terminology:
Server The machine offering netboot and install options.
Client The machine that will have FreeBSD installed on it.
Requires: Clients supporting the Intel PXE netboot option, an Ethernet connection.
Please let me know if you come across anything you have problems with or suggestions for additional documentation.
If you would like someone to train/implement a specific netinstall system for you, please send email so that we can discuss terms.
I would also like to thank Paul Saab and John Baldwin for doing most of the programming work on pxeboot, the interface to the Intel PXE (netboot) system.
________________________________________
2 Server Configuration
1. Install DHCP: Install net/isc-dhcp3 you can use this config file dhcpd.conf, stick it in /usr/local/etc/.
2. Enable tftp:
1. Make a directory /usr/tftpboot
2. Add this line to your /etc/inetd.conf:
3. tftp dgram udp wait nobody /usr/libexec/tftpd tftpd /usr/tftpboot
3. Enable NFS:
1. Add this to /etc/rc.conf:
2. nfs_server_enable="YES"
3. Add this to /etc/exports:
4. /usr -alldirs -ro
4. Reboot to enable the new services or start them manually.
________________________________________
3 Bootstrap Setup
1. Download bootfiles: Download the kern.flp and mfsroot.flp floppy images.
2. Set up tftp/pxe-boot directory:
1. Put pxeboot in the boot directory:
2. # rm -rf /usr/obj/*
3. # cd /usr/src/sys/boot
4. # make
5. # cp /usr/src/sys/boot/i386/pxeldr/pxeboot /usr/tftpboot
6. Using the vndevice mount the kern.flp file and copy its contents to /usr/tftpboot:
7. # vnconfig vn0 kern.flp # associate a vndevice with the file
8. # mount /dev/vn0 /mnt # mount it
9. # cp -R /mnt /usr/tftpboot # copy the contents to /usr/tftpboot
10. # umount /mnt # unmount it
11. # vnconfig -u vn0 # disassociate the vndevice from the file
3. Compile a custom kernel for the clients (particularly to avoid the device config screen at boot) and stick it in /usr/tftpboot.
4. Make a special loader.rc to and install it in /usr/tftpboot/boot/loader.rc so that it does not prompt for the second disk, here is mine.
5. Extract the installer and helper utilities from the mfsroot disk and uncompress them, put them in /usr/tftpboot as well:
6. # vnconfig vn0 mfsroot.flp # associate a vndevice with the file
7. # mount /dev/vn0 /mnt # mount it
8. # cp /mnt/mfsroot.gz /usr/tftpboot # copy the contents to /usr/tftpboot
9. # umount /mnt # unmount it
10. # vnconfig -u vn0 # disassociate the vndevice from the file
11. # cd /usr/tftpboot # get into the pxeboot directory
12. # gunzip mfsroot.gz # uncompress the mfsroot
13. Make your sysinstall script install.cfg, you can use mine as a template, but you must edit it.
14. Copy the sysinstall script into the extracted and uncompressed mfsroot image:
15. # cd /usr/tftpboot
16. # vnconfig vn0 mfsroot
17. # mount /dev/vn0 /mnt
18. # cp install.cfg /mnt
19. # umount /mnt
20. # vnconfig -u vn0
________________________________________
4 Install Setup
1. Put the install files in an NFS accessible location on the Server. Make a directory corresponding the 'nfs' directive in the install.cfg file and mirror the FreeBSD install files there, you will want it to look somewhat like this:
2. ABOUT.TXT TROUBLE.TXT compat20 floppies ports
3. ERRATA.TXT UPGRADE.TXT compat21 games proflibs
4. HARDWARE.TXT XF86336 compat22 info src
5. INSTALL.TXT bin compat3x kern.flp
6. LAYOUT.TXT catpages crypto manpages
7. README.TXT cdrom.inf dict mfsroot.flp
8. RELNOTES.TXT compat1x doc packages
9. Copy the compressed packages into the packages/All directory under nfs.
10. Make sure you have an INDEX file prepared in the packages directory. You can make your own INDEX entries like so:
11. alfred-1.0||/|Alfred install bootstrap||alfred@FreeBSD.org||||
Then you can install custom packages, particularly your own custom post-install package.
________________________________________
5 Custom Post-Install Package
You can use the script pkgmaker.sh to create a custom package for post install, the idea is to have it install and configure any special things you may need done. pkgmaker is run in the directory above the package you wish to create with the single argument of the package (ie mypkg) which will then create a mypkg.tgz for you to include in your sysinstall package.
Inside your custom package dir you will want a file called PLIST which contains all the files that you wish to install and be incorporated into your package.
You will also want files called pre and post in the directory, these are shell scripts that you want to execute before and after your package is installed.
Since this package is in your install.cfg file it should be run and do the final configuration for you.

FreeBSD Snap Shot

File System Snapshots-檔案系統快照,顧名思義就是將當時的檔案系統照一張像,當我們想要用的時候可以在拿出來用,拿來備份也不失為一個好的方法,整個過程大概就是利用指令將指定的分割區(Mount Poing)給快照起來,然後利用 MD (Memory Disk) 把快照檔案模擬成檔案系統讓我們查看當時快照下來的檔案系統,在執行 File System Snapshots 之前注意事項如下:


一個檔案系統中最多只能有 20 個檔案系統快照
快照只能針對獨立的分割區作用 (ex. /dev/ad0s1g /home)
在執行檔案系統快照時檔案只能存放於該檔案系統(ex. /var/snapshot /var)當快照完畢後才可進行搬移
快照出來的檔案你會發現跟分割區大小一樣(若在原分割區是不佔什麼空間的)
若將快照檔案複製到其它分割區就會佔實際空間了
若是快照根目錄 (/),則當 mount 來用時會發現其它分割區內是空的(ex./var、/usr)
可以使用 rm 來刪除快照檔案
【作業環境】

FreeBSD 6.2-STABLE


Filesystem Size Used Avail Capacity Mounted on
/dev/ad0s1a 496M 79M 377M 17% /
devfs 1.0K 1.0K 0B 100% /dev
/dev/ad0s1g 63G 43M 58G 0% /home
/dev/ad0s1e 496M 18K 456M 0% /tmp
/dev/ad0s1f 7.7G 1.5G 5.6G 21% /usr
/dev/ad0s1d 1.4G 32M 1.3G 2% /var

【安裝及設定】

Step1.使用 mount 或 mksnap_ffs 建立 Snapshot

我們可以使用 mount 或 mksnap_ffs 建立 File System Snapshots,下例為對 /dev/ad0s1g /home 進行快照,而快照檔案名稱為 snapshot20070515。

使用 mount


#mount -u -o snapshot /snapshot20070515 /

使用 mksnap_ffs


#mksnap_ffs / /snapshot20070515

執行快照後可以發現快照檔案跟分割區大小竟然一樣?但實際是不佔什麼空間的,但若是將快照檔案搬離建立的分割區就會佔實際的大小了。


#cd / ; ll -h snapshot20070515
-r--r----- 1 root operator 512M 5 15 10:48 snapshot20070515 //快照檔案跟分割區大小一樣

但實際上我的根目錄依然只有使用 79 MB


Filesystem Size Used Avail Capacity Mounted on
/dev/ad0s1a 496M 79M 377M 17% /
devfs 1.0K 1.0K 0B 100% /dev
/dev/ad0s1g 63G 4.7M 58G 0% /home
/dev/ad0s1e 496M 18K 456M 0% /tmp
/dev/ad0s1f 7.7G 1.5G 5.6G 21% /usr
/dev/ad0s1d 1.4G 32M 1.3G 2% /var

查看快照檔案實際佔用空間(前提是放在該分割區)


#du -sh /snapshot20070515 //可以看到快照檔案實際才佔 480 KB 而以
480K /snapshot20070515

把 snapshot20070515 複製到 /home 下 (目前 /home 才使用 4.7 MB)可以發現快照檔案佔用實際分割區大小一樣的空間 (/home 成長到 517 MB)


Filesystem Size Used Avail Capacity Mounted on
/dev/ad0s1a 496M 79M 377M 17% /
devfs 1.0K 1.0K 0B 100% /dev
/dev/ad0s1g 63G 517M 58G 1% /home
/dev/ad0s1e 496M 18K 456M 0% /tmp
/dev/ad0s1f 7.7G 1.5G 5.6G 21% /usr
/dev/ad0s1d 1.4G 32M 1.3G 2% /var

Step2.掛載快照檔案


#mdconfig -a -t vnode -f /snapshot20070515 -u 2
#mount -r /dev/md2 /mnt
# df -h
Filesystem Size Used Avail Capacity Mounted on
/dev/ad0s1a 496M 79M 377M 17% /
devfs 1.0K 1.0K 0B 100% /dev
/dev/ad0s1g 63G 517M 58G 1% /home
/dev/ad0s1e 496M 18K 456M 0% /tmp
/dev/ad0s1f 7.7G 1.5G 5.6G 21% /usr
/dev/ad0s1d 1.4G 32M 1.3G 2% /var
/dev/md2 496M 78M 378M 17% /mnt //將快照檔案順便 mount 來使用

此時進入 /mnt/etc 可以發現裡面檔案跟你在快照時是一模一樣的,以後要拿來備份 /etc 下的檔案很方便。不過要注意的是前面有提到只能針對獨立的分割區,所以你進入 /mnt/home、/mnt/tmp、/mnt/usr、/mnt/var 會發現都是空的。

Step3.卸載快照檔案


#umount /mnt //卸載 (記得先離開 /mnt 哦)
#mdconfig -d -u 2 //卸載 md2

Step4.尋找分割區內所有的 snapshot


#find /var -flags snapshot //尋找 /var 分割區內所有的 snapshot