Linux environment (V)-host information and logs

Source: Internet
Author: User
Tags openlog
Host information

Just as we can determine the user information, the program can also determine the information of the computer on which it runs. The uname command provides this information. Uname also serves as a system call to provide the same information in a C program. We can use man 2 uname to view detailed information.

In many cases, host information is required. We may want to customize the behavior based on the name of the machine where a program runs on the network, that is, whether it is a student machine or an administrator machine. For Authorization purposes, we may want to restrict a program to run on only one machine. All this means that we need a method to determine the information of the machine where the program runs.

If the system has installed network components, we can easily get the network name through the gethostname function:

# Include <unistd. h>
Int gethostname (char * Name, size_t namelen );

The gethostname function writes the Network Name of the machine to the string indicated by name. Assume that the length of this string must be at least the length of the namelen character. If the call succeeds, the gethostname function returns 0; otherwise, the return value is-1.

We can get more detailed information about the host by calling the uname system:

# Include <sys/utsname. h>
Int uname (struct utsname * Name );

The uname function writes host information to the structure directed by the name parameter. The utsname structure is defined in sys/ustname. H. Most of them contain at least the following members:

Member description
Char sysname [] operating system name
Char nodename [] Host Name
Char release [] system release level
Char version [] System Version Number
Char Machine [] hardware type

If the call succeeds, the uname function returns a non-negative number. Otherwise, it returns-1 and errno to indicate an error.

Test-host information

The following is a program hostget. C to obtain the host information:

# Include <sys/utsname. h>
# Include <unistd. h>
# Include <stdio. h>
Int main ()
{
Char computer [256];
Struct utsname Uts;
If (gethostname (computer, 255 )! = 0 | uname (& UTs) <0 ){
Fprintf (stderr, "cocould not get host information/N ");
Exit (1 );
}
Printf ("Computer Host Name Is % s/n", computer );
Printf ("system is % s on % s hardware/N", UTS. sysname, UTS. Machine );
Printf ("nodename is % s/n", UTS. nodename );
Printf ("version is % s, % s/n", UTS. Release, UTS. version );
Exit (0 );
}

The program will generate the following specific Linux output. If our machine is on the network, we will find an extended Host Name containing the network:

$./Hostget
Computer Host Name Is beast
System is Linux on i686 hardware
Nodename is beast
Version is 2.4.19-4 Gbit/s, #1 wed Nov 27 00:56:40 UTC 2002

Working Principle

This program calls the gethostname function to obtain the Network Name of the host. In the previous example, the name is Tilde. More detailed information is obtained by calling the unmae function. Note that the string returned by the function uname depends on implementation. In this example, the version number contains the compiled kernel data.

The gethostid function can obtain a unique host number:

# Include <unistd. h>
Long gethostid (void );

The gethostid function returns a unique host number. Authorization management usually uses this function to ensure that software programs can run on only one machine with legal authorization. On the sun workstation, he will return a number set in the immutable memory of a machine during manufacturing. Therefore, this is the only system hardware.

For other systems, such as Linux, a value based on the machine network address is returned, which is usually safe enough for authorization.

Logs

Many programs need to record their actions. System programs usually write information to a terminal or a log file. This information may indicate errors, warnings, or more general information about the system status. For example, the su program may record the fact that a user attempts to obtain super permissions and fails.

Normally, these logs are recorded in a system file in a directory. This may be/usr/ADM or/var/log. In normal Linux installation, the/var/log/messages file contains the system information, And/var/log/mail contains the log information of other mail systems, /var/log/debug contains debugging information. We can view our system configuration in the/etc/syslog. conf file.

The following are some log information:

Here are some sample log messages:
Feb 8 08:38:37 beast kernel: klogd 1.4.1, log source =/proc/kmsg started.
Feb 8 08:38:37 beast kernel: Inspecting/boot/system. map-2.4.19-4GB
Feb 8 08:38:37 beast kernel: loaded 20716 symbols from/boot/system. Map-
2.4.19-4 GB.
Feb 8 08:38:37 beast kernel: symbols match kernel version 2.4.19.
Feb 8 08:38:37 beast kernel: loaded 372 symbols from 17 modules.
Feb 8 08:38:37 beast kernel: Linux tulip driver version 0.9.15-pre11 (May 11,
2002)
Feb 8 08:38:37 beast kernel: pci: Found IRQ 5 for device 00: 0d. 0
Feb 8 08:38:37 beast kernel: eth0: admtek comet rev 17 at 0xe400,
00: 04: 5A: 5f: 46: 52, IRQ 5.
...
Feb 8 08:39:20 beast/usr/sbin/cron [932]: (cron) Startup (fork OK)
Feb 8 09:50:35 beast su: (To root) Neil on/dev/pts/4

Here we can see the log record information. Earlier versions are reported by the kernel itself when the kernel starts and detects installed hardware. Task caller, Cron, reporting that it is started. Finally, the su Program reported that the user Neil accessed a super account.

Some UNIX systems do not provide log information in this readable way, but provide an administrator tool to read the database of system events. We can view our system documentation for detailed information.

Although the format and storage of system information change, the method for generating such information is standard. UNIX systems use the syslog function to provide an interface for log information generation:

# Include <syslog. h>
Void syslog (INT priority, const char * message, arguments ...);

The SYSLOG function sends the log information to the log tool. Each message has a priority parameter, which is a bit or a bit of the security level and tool value. The security level controls how these messages are generated, and the tool value records the message source.

The tool value includes log_user, which indicates that the message comes from a user program, log_local0, log_local1 until log_local7, which can be meaningful to the local administrator.

The following table lists the security levels in descending order:

Security level description
Log_emerg an emergency
Log_alert high-priority issues, such as database crashes
Log_crit emergency error, such as hardware failure
Log_err Error
Log_warning warning
Special notes for log_notice
Log_info message
Log_debug debugging message

Based on our system configuration, the log_emerg message may be broadcast to all users. The log_alert message may be sent to the Administrator by email, and the log_debug message will be ignored, other messages are written into the system day and night. We can write a simple program that calls the syslog log program when we want to create a log message.

A log message created by Syslog consists of a message header and a message body. The message header is created by the program indicator and date and time. The message body is created by the message parameter to syslog, and its function is similar to the printf format string. Other parameters passed to syslog are used to specify the printf style convention in the message string. In addition, the indicator % m can be used to insert an error message string associated with the current error variable errno. This is useful for logging error messages.

Test-syslog

In this program, we try to open a non-existent file:

# Include <syslog. h>
# Include <stdio. h>
Int main ()
{
File * F;
F = fopen ("not_here", "R ");
If (! F)
Syslog (log_err | log_user, "oops-% M/N ");
Exit (0 );
}

When we compile and run the program syslog. C, we will not see any output, but the file/var/log/messages now contains the following records:

Feb 8 09:59:14 beast syslog: Oops-no such file or directory

Working Principle

In this program, we try to open a non-existent file. When the operation fails, we will see that syslog records this in the system log.

We can note that the log message does not specify which program calls the log program; it only records the fact that syslog is called by a message. The % m Format Convention has been replaced by an error description. In this example, this file cannot be found. This is much more useful than simply printing the original error code.

Syslog. H also defines other functions that can be used to modify the behavior of log programs. They are:

# Include <syslog. h>
Void closelog (void );
Void openlog (const char * Ident, int logopt, int facility );
Int setlogmask (INT maskpri );

We can call the openlog function to modify the representation of our log messages. This will let us set a string, ident, which will be added to the front of our log message. We can use it to indicate which program creates the message. The facility parameter records the value of a SYSLOG call in the future. The default value is log_user. The logopt parameter configures future syslog call behavior. The following zero or multiple single-digit or result:

Logopt parameter description
Log_pid contains the process identifier in the message, which is the unique identifier assigned to the process by the system.
Log_cons sends a message to the terminal if it cannot be recorded
Log_odelay
Log_ndelay open the log program immediately, instead of the first call

The openlog function allocates and opens a file descriptor used to write the log program. We can call the closelog function to disable it. Note that you do not need to call openlog before calling the syslog function, because syslog itself will be opened as needed.

We can use the setlogmask function to set the log mask to control the priority of our log messages. In the future, those who call the syslog function with a priority that is not set in the log mask will be rejected. For example, we can use this method to disable the log_debug message without modifying the program body.

We can use log_mask (priority) to create a mask for log messages. This creates a mask that only contains one priority, or log_upto (priority ), this creates a mask that contains all the priority levels until priority and contains priority.

Test-logmask

In this example, we will take a look at the use of logmask:

# Include <syslog. h>
# Include <stdio. h>
# Include <unistd. h>
Int main ()
{
Int logmask;
Openlog ("logmask", log_pid | log_cons, log_user );
Syslog (log_info, "informative message, pid = % d", getpid ());
Syslog (log_debug, "debug message, shocould appear ");
Logmask = setlogmask (log_upto (log_notice ));
Syslog (log_debug, "debug message, shocould not appear ");
Exit (0 );
}

This logmask. C program does not produce any output, but on a specific Linux system, we will see the following line at the end of/var/log/messages:

Feb 8 10:00:50 beast logmask [1833]: informative message, pid = 1833

The file configured to receive debugging log messages should contain the following lines:

Feb 8 10:00:50 beast logmask [1833]: Debug message, shocould appear

Working Principle

The program uses its name, logmask to initialize the log program, and the request message contains the process identifier. Information messages are recorded in/var/log/messages, and debugging information is recorded in the/var/log/debug file. The second debugging information does not appear, because we call the setlogmask function to ignore all messages whose priority is lower than log_notice.

If our installation does not record the debugging information function or requires different configurations, we may not see the output of the debugging message. To allow all debugging messages, add the following line at the end of/etc/syslog. conf and restart. However, you must check our system documentation to get the exact configuration method:

*. Debug/var/log/debug

Logmask. c uses the getpid function. Its getppid function is defined as follows:

# Include <sys/types. h>
# Include <unistd. h>
Pid_t getpid (void );
Pid_t getppid (void );

The two functions return the process identifier of the calling process and its parent process. For more information about PID, see Chapter 11th.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.