Infoaddict Just another site for Infoaddict's

19Feb/120

Fine-Grained Access to Network Services in Oracle Database 11g Release 1

Posted by Infoaddict

Oracle allows access to external network services using several PL/SQL APIs (UTL_TCP, UTL_SMTP, UTL_MAIL, UTL_HTTP and UTL_INADDR), all of which are implemented using the TCP protocol. In previous versions of the database, access to external services was effectively an on/off switch based on whether a user was granted execute permissions on a specific package or not. Oracle 11g introduces fine grained access to network services using access control lists (ACL) in the XML DB repository, allowing control over which users access which network resources, regardless of package grants.

Access control lists can be created, amended and deleted in the XML DB repository directly using FTP or WebDav. In addition, Oracle provide the DBMS_NETWORK_ACL_ADMIN and DBMS_NETWORK_ACL_UTILITY packages to allow ACL management from PL/SQL. These APIs are the subject of this article.

Create an Access Control List (ACL)
Assign an ACL to a Network
ACL Views
Checking Privileges
Test the ACL
Other Security Considerations
Open ACL

Create an Access Control List (ACL)

Access control lists are manipulated using the DBMS_NETWORK_ACL_ADMIN package. The CREATE_ACL procedure uses the following parameters to create a new ACL:

acl - The name of the access control list XML file, generated relative to the "/sys/acls" directory in the XML DB Repository.
description - A description of the ACL.
principal - The first user account or role being granted or denied permissions. The text is case sensitive.
is_grant - TRUE to grant, FALSE to deny the privilege.
privilege - Use 'connect' for UTL_TCP, UTL_SMTP, UTL_MAIL and UTL_HTTP access. Use 'resolve' for UTL_INADDR name/IP resolution. The text is case sensitive.
start_date - Default value NULL. When specified, the ACL will only be active on or after the specified date.
end_date - An optional end date for the ACL.

The following code creates two test users to act as principals, then creates a new ACL.

CONN sys/password@db11g AS SYSDBA

CREATE USER test1 IDENTIFIED BY test1;
GRANT CONNECT TO test1;

CREATE USER test2 IDENTIFIED BY test2;
GRANT CONNECT TO test2;

BEGIN
DBMS_NETWORK_ACL_ADMIN.create_acl (
acl          => 'test_acl_file.xml',
description  => 'A test of the ACL functionality',
principal    => 'TEST1',
is_grant     => TRUE,
privilege    => 'connect',
start_date   => SYSTIMESTAMP,
end_date     => NULL);

COMMIT;
END;
/

Once created, the ACL is visible in the "http://host:port/sys/acls/" directory.

Additional users or roles are added to the ACL using the ADD_PRIVILEGE procedure. Its parameter list is similar to the CREATE_ACL procedure, with the omission of the DESCRIPTION parameter and the addition of a POSITION parameter, which sets the order of precedence.

BEGIN
DBMS_NETWORK_ACL_ADMIN.add_privilege (
acl         => 'test_acl_file.xml',
principal   => 'TEST2',
is_grant    => FALSE,
privilege   => 'connect',
position    => NULL,
start_date  => NULL,
end_date    => NULL);

COMMIT;
END;
/

Each principal is defined as a separate access control element (ACE), within the ACL. When multiple principles are defined, they are evaluated in order from top to bottom, with the last relevant reference used to define the privilege. This means a role that denies access to a resource can be granted to a user, but if the user is defined as a principal further down the file, that definition will override the role definition for that user. Use the POSITION parameter to ensure privileges are evaluated in order.

Privileges are removed using the DELETE_PRIVILEGE procedure. If the IS_GRANT or PRIVILEGE parameters are NULL, all grants or privileges for the ACL and principal are removed.

BEGIN
DBMS_NETWORK_ACL_ADMIN.delete_privilege (
acl         => 'test_acl_file.xml',
principal   => 'TEST2',
is_grant    => FALSE,
privilege   => 'connect');

COMMIT;
END;
/

ACLs are deleted using the DROP_ACL procedure.

BEGIN
DBMS_NETWORK_ACL_ADMIN.drop_acl (
acl         => 'test_acl_file.xml');

COMMIT;
END;
/

Assign an ACL to a Network

Access control lists are assigned to networks using the ASSIGN_ACL procedure, whose parameters are listed below:

acl - The name of the access control list XML file.
host - The hostname, domain, IP address or subnet to be assigned. Hostnames are case sensitive, and wildcards are allowed for IP addresses and domains.
lower_port - Defaults to NULL. Specifies the lower port range for the 'connect' privilege.
upper_port - Defaults to NULL. If the lower_port is specified, and the upper_port is NULL, it is assumed the upper_port matches the lower_port.

The code below shows the ACL created previously being assigned to a specific IP address and a subnet.

BEGIN
DBMS_NETWORK_ACL_ADMIN.assign_acl (
acl         => 'test_acl_file.xml',
host        => '192.168.2.3',
lower_port  => 80,
upper_port  => NULL);

DBMS_NETWORK_ACL_ADMIN.assign_acl (
acl         => 'test_acl_file.xml',
host        => '10.1.10.*',
lower_port  => NULL,
upper_port  => NULL);

COMMIT;
END;
/

Only one ACL can be assigned to a specific host and port-range combination. Assigning a new ACL to a specific host and port-range results in the deletion of the previous assignment. You must take care when making a new assignment that you are not opening ports that were closed by a previous ACL assignment, or you could be opening yourself to attack. When wildcard usage causes overlapping assignments, the most specific assignment will take precedence, so an ACL assigned to 192.168.2.3:80 takes precedence over once assigned to 192.168.2.* etc.

The UNASSIGN_ACL procedure allows you to manually drop ACL assignments. It uses the same parameter list as the ASSIGN_ACL procedure, with any NULL parameters acting as wildcards.

BEGIN
DBMS_NETWORK_ACL_ADMIN.unassign_acl (
acl         => 'test_acl_file.xml',
host        => '192.168.2.3',
lower_port  => 80,
upper_port  => NULL);

COMMIT;
END;
/

ACL Views

The DBA_NETWORK_ACLS, DBA_NETWORK_ACL_PRIVILEGES and USER_NETWORK_ACL_PRIVILEGES views display the current ACL settings. The expected output below assumes none of the delete/drop/unassign operations have been performed.

The DBA_NETWORK_ACLS view displays information about network and ACL assignments.

COLUMN host FORMAT A30
COLUMN acl FORMAT A30

SELECT host, lower_port, upper_port, acl
FROM   dba_network_acls;

HOST                           LOWER_PORT UPPER_PORT ACL
------------------------------ ---------- ---------- ------------------------------
10.1.10.*                                            /sys/acls/test_acl_file.xml
192.168.2.3                            80         80 /sys/acls/test_acl_file.xml

2 rows selected.

SQL>

The DBA_NETWORK_ACL_PRIVILEGES view displays information about privileges associated with the ACL.

COLUMN acl FORMAT A30
COLUMN principal FORMAT A30

SELECT acl,
principal,
privilege,
is_grant,
TO_CHAR(start_date, 'DD-MON-YYYY') AS start_date,
TO_CHAR(end_date, 'DD-MON-YYYY') AS end_date
FROM   dba_network_acl_privileges;

ACL                            PRINCIPAL                      PRIVILE IS_GR START_DATE  END_DATE
------------------------------ ------------------------------ ------- ----- ----------- -----------
/sys/acls/test_acl_file.xml    TEST1                          connect true  02-APR-2008
/sys/acls/test_acl_file.xml    TEST2                          connect false

2 rows selected.

SQL>

The USER_NETWORK_ACL_PRIVILEGES view displays the current users network ACL settings.

CONN test1/test1@db11g

COLUMN host FORMAT A30

SELECT host, lower_port, upper_port, privilege, status
FROM   user_network_acl_privileges;

HOST                           LOWER_PORT UPPER_PORT PRIVILE STATUS
------------------------------ ---------- ---------- ------- -------
10.1.10.*                                            connect GRANTED
192.168.2.3                            80         80 connect GRANTED

2 rows selected.

SQL>

CONN test2/test2@db11g

COLUMN host FORMAT A30

SELECT host, lower_port, upper_port, privilege, status
FROM   user_network_acl_privileges;

HOST                           LOWER_PORT UPPER_PORT PRIVILE STATUS
------------------------------ ---------- ---------- ------- -------
10.1.10.*                                            connect DENIED
192.168.2.3                            80         80 connect DENIED

2 rows selected.

SQL>

Checking Privileges

In addition to the ACL views, privileges can be checked using the CHECK_PRIVILEGE and CHECK_PRIVILEGE_ACLID functions of the DBMS_NETWORK_ACL_ADMIN package.

CONN sys/password@db11g AS SYSDBA

SELECT DECODE(
DBMS_NETWORK_ACL_ADMIN.check_privilege('test_acl_file.xml', 'TEST1', 'connect'),
1, 'GRANTED', 0, 'DENIED', NULL) privilege
FROM dual;

PRIVILE
-------
GRANTED

1 row selected.

SQL>

COLUMN acl FORMAT A30
COLUMN host FORMAT A30

SELECT acl,
host,
DECODE(
DBMS_NETWORK_ACL_ADMIN.check_privilege_aclid(aclid, 'TEST2', 'connect'),
1, 'GRANTED', 0, 'DENIED', NULL) privilege
FROM   dba_network_acls;

PRIVILE
-------
DENIED

1 row selected.

SQL>

The DBMS_NETWORK_ACL_UTILITY package contains functions to help determine possible matching domains. The DOMAINS table function returns a collection of all possible references that may affect the specified host, domain, IP address or subnet, in order of precedence.

SELECT *
FROM   TABLE(DBMS_NETWORK_ACL_UTILITY.domains('oel5-11g.localdomain'));

COLUMN_VALUE
-------------------------------
oel5-11g.localdomain
*.localdomain
*

3 rows selected.

SQL>

SELECT *
FROM   TABLE(DBMS_NETWORK_ACL_UTILITY.domains('192.168.2.3'));

COLUMN_VALUE
-------------------------------
192.168.2.3
192.168.2.*
192.168.*
192.*
*

5 rows selected.

SQL>

The DOMAIN_LEVEL function returns the level of the specified host, domain, IP address or subnet.

SELECT DBMS_NETWORK_ACL_UTILITY.domain_level('oel5-11g.localdomain')
FROM   dual;

DBMS_NETWORK_ACL_UTILITY.DOMAIN_LEVEL('OEL5-11G.LOCALDOMAIN')
-------------------------------------------------------------
2

1 row selected.

SQL>

SELECT DBMS_NETWORK_ACL_UTILITY.domain_level('192.168.2.3')
FROM   dual;

DBMS_NETWORK_ACL_UTILITY.DOMAIN_LEVEL('192.168.2.3')
----------------------------------------------------
4

1 row selected.

SQL>

These functions may be useful for when querying the ACL views for possible matches to a specific host, domain, IP address or subnet.

SELECT host,
lower_port,
upper_port,
acl,
DECODE(
DBMS_NETWORK_ACL_ADMIN.check_privilege_aclid(aclid,  'TEST1', 'connect'),
1, 'GRANTED', 0, 'DENIED', null) PRIVILEGE
FROM   dba_network_acls
WHERE  host IN (SELECT *
FROM   TABLE(DBMS_NETWORK_ACL_UTILITY.domains('10.1.10.191')))
ORDER BY
DBMS_NETWORK_ACL_UTILITY.domain_level(host) desc, lower_port, upper_port;

HOST                           LOWER_PORT UPPER_PORT ACL                            PRIVILE
------------------------------ ---------- ---------- ------------------------------ -------
10.1.10.*                                            /sys/acls/test_acl_file.xml    GRANTED

1 row selected.

SQL>

Test the ACL

The TEST1 and TEST2 users have the ACL allowed and denied respectively. This means we can test the ACL functionality by comparing their responses to calls to external network services. The following code grants execute permission on the UTL_HTTP package to both users, then attempts to access a web page from each user.

CONN sys/password@db11g AS SYSDBA
GRANT EXECUTE ON UTL_HTTP TO test1, test2;

CONN test1/test1@db11g

DECLARE
l_url            VARCHAR2(50) := 'http://192.168.2.3:80';
l_http_request   UTL_HTTP.req;
l_http_response  UTL_HTTP.resp;
BEGIN
-- Make a HTTP request and get the response.
l_http_request  := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
UTL_HTTP.end_response(l_http_response);
END;
/

PL/SQL procedure successfully completed.

SQL>

CONN test2/test2@db11g

DECLARE
l_url            VARCHAR2(50) := 'http://192.168.2.3:80';
l_http_request   UTL_HTTP.req;
l_http_response  UTL_HTTP.resp;
BEGIN
-- Make a HTTP request and get the response.
l_http_request  := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
UTL_HTTP.end_response(l_http_response);
END;
/
DECLARE
*
ERROR at line 1:
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1029
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at line 7

SQL>

From this we can see that the TEST1 user was able to access the web page, while the TEST2 user was denied access by the ACL.

The default action of the server is to deny access to external network service, as shown by the following test on a new user.

CONN sys/password@db11g AS SYSDBA

CREATE USER test3 IDENTIFIED BY test3;
GRANT CONNECT TO test3;
GRANT EXECUTE ON UTL_HTTP TO test3;

CONN test3/test3@db11g

DECLARE
l_url            VARCHAR2(50) := 'http://192.168.2.3:80';
l_http_request   UTL_HTTP.req;
l_http_response  UTL_HTTP.resp;
BEGIN
-- Make a HTTP request and get the response.
l_http_request  := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
UTL_HTTP.end_response(l_http_response);
END;
/
DECLARE
*
ERROR at line 1:
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1029
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at line 7

SQL>

This may cause some confusion when upgrading databases that access external network services from 10g to 11g. In these situations, it will be necessary to implement suitable access control lists before your original functionality is possible.
Other Security Considerations

Pete Finnigan commented on his blog and in his security presentations about the fact that the ACLs are not tied to a specific package. This means opening a port on a server with the 'connect' privilege makes it accessible by UTL_TCP, UTL_SMTP, UTL_MAIL and UTL_HTTP. With this in mind there are some things to consider:

The use of fine-grained access to network services is not an excuse to ignore basic security measures, like revoking unnecessary privileges on network service related packages.
Control over the services you make available is possible by limiting access to the specific ports. If you only need HTTP access to port 80, specify the port rather than opening access to all ports on the server.
Wildcards can be dangerous as you may be granting access to more servers that you should.
You must protect your ACLs. If people can alter them, they become useless as a protection mechanism. Prevent direct access to the ACLs in the XML DB repository and make sure users don't have access to the management APIs.

Thanks to Pete Finnigan for his input.
Open ACL

From a security standpoint, it's not a good idea to allow complete network access from the database, but for testing features I sometimes find it useful to create an open ACL for an instance.

CONN / AS SYSDBA
BEGIN
DBMS_NETWORK_ACL_ADMIN.create_acl (
acl          => 'open_acl_file.xml',
description  => 'A test of the ACL functionality',
principal    => 'TEST',
is_grant     => TRUE,
privilege    => 'connect',
start_date   => SYSTIMESTAMP,
end_date     => NULL);

DBMS_NETWORK_ACL_ADMIN.assign_acl (
acl         => 'open_acl_file.xml',
host        => '*',
lower_port  => 1,
upper_port  => 9999);

COMMIT;
END;
/

For more information see:

Print Friendly
Tagged as: No Comments
19Feb/120

Email From Oracle PL/SQL (UTL_SMTP)

Posted by Infoaddict

The UTL_SMTP package was introduced in Oracle 8i and can be used to send emails from PL/SQL.

Simple Emails
Multi-Line Emails
HTML Emails
Emails with Attachments
BLOB Attachment
CLOB Attachment
Miscellaneous

Related articles.

UTL_MAIL in Oracle 10g
HTML with Embedded Images from PL/SQL
Fine-Grained Access to Network Services in Oracle Database 11g Release 1

Simple Emails

In it's simplest form a single string or variable can be sent as the message body using the following procedure. In this case we have not included any header information or subject line in the message, so it is not very useful, but it is small.

CREATE OR REPLACE PROCEDURE send_mail (p_to        IN VARCHAR2,
p_from      IN VARCHAR2,
p_message   IN VARCHAR2,
p_smtp_host IN VARCHAR2,
p_smtp_port IN NUMBER DEFAULT 25)
AS
l_mail_conn   UTL_SMTP.connection;
BEGIN
l_mail_conn := UTL_SMTP.open_connection(p_smtp_host, p_smtp_port);
UTL_SMTP.helo(l_mail_conn, p_smtp_host);
UTL_SMTP.mail(l_mail_conn, p_from);
UTL_SMTP.rcpt(l_mail_conn, p_to);
UTL_SMTP.data(l_mail_conn, p_message || UTL_TCP.crlf || UTL_TCP.crlf);
UTL_SMTP.quit(l_mail_conn);
END;
/

The code below shows how the procedure is called.

BEGIN
send_mail(p_to        => 'me@mycompany.com',
p_from      => 'admin@mycompany.com',
p_message   => 'This is a test message.',
p_smtp_host => 'smtp.mycompany.com');
END;
/

Multi-Line Emails

Multi-line messages can be written by expanding the UTL_SMTP.DATA command using the UTL_SMTP.WRITE_DATA command as follows. This is a better method to use as the total message size is no longer constrained by the 32K limit on a VARCHAR2 variable. In the following example the header information has been included in the message also.

CREATE OR REPLACE PROCEDURE send_mail (p_to        IN VARCHAR2,
p_from      IN VARCHAR2,
p_subject   IN VARCHAR2,
p_message   IN VARCHAR2,
p_smtp_host IN VARCHAR2,
p_smtp_port IN NUMBER DEFAULT 25)
AS
l_mail_conn   UTL_SMTP.connection;
BEGIN
l_mail_conn := UTL_SMTP.open_connection(p_smtp_host, p_smtp_port);
UTL_SMTP.helo(l_mail_conn, p_smtp_host);
UTL_SMTP.mail(l_mail_conn, p_from);
UTL_SMTP.rcpt(l_mail_conn, p_to);

UTL_SMTP.open_data(l_mail_conn);

UTL_SMTP.write_data(l_mail_conn, 'Date: ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'To: ' || p_to || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'From: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Subject: ' || p_subject || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Reply-To: ' || p_from || UTL_TCP.crlf || UTL_TCP.crlf);

UTL_SMTP.write_data(l_mail_conn, p_message || UTL_TCP.crlf || UTL_TCP.crlf);
UTL_SMTP.close_data(l_mail_conn);

UTL_SMTP.quit(l_mail_conn);
END;
/

The code below shows how the procedure is called.

BEGIN
send_mail(p_to        => 'me@mycompany.com',
p_from      => 'admin@mycompany.com',
p_subject   => 'Test Message',
p_message   => 'This is a test message.',
p_smtp_host => 'smtp.mycompany.com');
END;
/

HTML Emails

The following procedure builds on the previous version, allowing it include plain text and/or HTML versions of the email. The format of the message is explained here.

CREATE OR REPLACE PROCEDURE send_mail (p_to        IN VARCHAR2,
p_from      IN VARCHAR2,
p_subject   IN VARCHAR2,
p_text_msg  IN VARCHAR2 DEFAULT NULL,
p_html_msg  IN VARCHAR2 DEFAULT NULL,
p_smtp_host IN VARCHAR2,
p_smtp_port IN NUMBER DEFAULT 25)
AS
l_mail_conn   UTL_SMTP.connection;
l_boundary    VARCHAR2(50) := '----=*#abc1234321cba#*=';
BEGIN
l_mail_conn := UTL_SMTP.open_connection(p_smtp_host, p_smtp_port);
UTL_SMTP.helo(l_mail_conn, p_smtp_host);
UTL_SMTP.mail(l_mail_conn, p_from);
UTL_SMTP.rcpt(l_mail_conn, p_to);

UTL_SMTP.open_data(l_mail_conn);

UTL_SMTP.write_data(l_mail_conn, 'Date: ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'To: ' || p_to || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'From: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Subject: ' || p_subject || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Reply-To: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'MIME-Version: 1.0' || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: multipart/alternative; boundary="' || l_boundary || '"' || UTL_TCP.crlf || UTL_TCP.crlf);

IF p_text_msg IS NOT NULL THEN
UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: text/plain; charset="iso-8859-1"' || UTL_TCP.crlf || UTL_TCP.crlf);

UTL_SMTP.write_data(l_mail_conn, p_text_msg);
UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
END IF;

IF p_html_msg IS NOT NULL THEN
UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: text/html; charset="iso-8859-1"' || UTL_TCP.crlf || UTL_TCP.crlf);

UTL_SMTP.write_data(l_mail_conn, p_html_msg);
UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
END IF;

UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || '--' || UTL_TCP.crlf);
UTL_SMTP.close_data(l_mail_conn);

UTL_SMTP.quit(l_mail_conn);
END;
/

The code below shows how the procedure is called.

DECLARE
l_html VARCHAR2(32767);
BEGIN
l_html := '<html>
<head>
<title>Test HTML message</title>
</head>
<body>
<p>This is a <b>HTML</b> <i>version</i> of the test message.</p>
<p><img src="http://www.oracle-base.com/images/site_logo.gif" alt="Site Logo" />
</body>
</html>';

send_mail(p_to        => 'me@mycompany.com',
p_from      => 'admin@mycompany.com',
p_subject   => 'Test Message',
p_text_msg  => 'This is a test message.',
p_html_msg  => l_html,
p_smtp_host => 'smtp.mycompany.com');
END;
/

Emails with Attachments

Sending an email with an attachment is similar to the previous example as the message and the attachment must be separated by a boundary and identified by a name and mime type.
BLOB Attachment

Attaching a BLOB requires the binary data to be encoded and converted to text so it can be sent using SMTP.

CREATE OR REPLACE PROCEDURE send_mail (p_to          IN VARCHAR2,
p_from        IN VARCHAR2,
p_subject     IN VARCHAR2,
p_text_msg    IN VARCHAR2 DEFAULT NULL,
p_attach_name IN VARCHAR2 DEFAULT NULL,
p_attach_mime IN VARCHAR2 DEFAULT NULL,
p_attach_blob IN BLOB DEFAULT NULL,
p_smtp_host   IN VARCHAR2,
p_smtp_port   IN NUMBER DEFAULT 25)
AS
l_mail_conn   UTL_SMTP.connection;
l_boundary    VARCHAR2(50) := '----=*#abc1234321cba#*=';
l_step        PLS_INTEGER  := 24573;
BEGIN
l_mail_conn := UTL_SMTP.open_connection(p_smtp_host, p_smtp_port);
UTL_SMTP.helo(l_mail_conn, p_smtp_host);
UTL_SMTP.mail(l_mail_conn, p_from);
UTL_SMTP.rcpt(l_mail_conn, p_to);

UTL_SMTP.open_data(l_mail_conn);

UTL_SMTP.write_data(l_mail_conn, 'Date: ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'To: ' || p_to || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'From: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Subject: ' || p_subject || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Reply-To: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'MIME-Version: 1.0' || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: multipart/mixed; boundary="' || l_boundary || '"' || UTL_TCP.crlf || UTL_TCP.crlf);

IF p_text_msg IS NOT NULL THEN
UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: text/plain; charset="iso-8859-1"' || UTL_TCP.crlf || UTL_TCP.crlf);

UTL_SMTP.write_data(l_mail_conn, p_text_msg);
UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
END IF;

IF p_attach_name IS NOT NULL THEN
UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: ' || p_attach_mime || '; name="' || p_attach_name || '"' || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Transfer-Encoding: base64' || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Disposition: attachment; filename="' || p_attach_name || '"' || UTL_TCP.crlf || UTL_TCP.crlf);

FOR i IN 0 .. TRUNC((DBMS_LOB.getlength(p_attach_blob) - 1 )/l_step) LOOP
UTL_SMTP.write_data(l_mail_conn, UTL_RAW.cast_to_varchar2(UTL_ENCODE.base64_encode(DBMS_LOB.substr(p_attach_blob, l_step, i * l_step + 1))));
END LOOP;

UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
END IF;

UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || '--' || UTL_TCP.crlf);
UTL_SMTP.close_data(l_mail_conn);

UTL_SMTP.quit(l_mail_conn);
END;
/

The code below shows how the procedure is called.

DECLARE
l_name images.name%TYPE := 'site_logo.gif';
l_blob images.image%TYPE;
BEGIN
SELECT image
INTO   l_blob
FROM   images
WHERE  name = l_name;

send_mail(p_to          => 'me@mycompany.com',
p_from        => 'admin@mycompany.com',
p_subject     => 'Test Message',
p_text_msg    => 'This is a test message.',
p_attach_name => 'site_logo.gif',
p_attach_mime => 'image/gif',
p_attach_blob => l_blob,
p_smtp_host   => 'smtp.mycompany.com');
END;
/

CLOB Attachment

Attaching a CLOB is similar to attaching a BLOB, but we don't have to worry about encoding the data because it is already plain text.

CREATE OR REPLACE PROCEDURE send_mail (p_to          IN VARCHAR2,
p_from        IN VARCHAR2,
p_subject     IN VARCHAR2,
p_text_msg    IN VARCHAR2 DEFAULT NULL,
p_attach_name IN VARCHAR2 DEFAULT NULL,
p_attach_mime IN VARCHAR2 DEFAULT NULL,
p_attach_clob IN CLOB DEFAULT NULL,
p_smtp_host   IN VARCHAR2,
p_smtp_port   IN NUMBER DEFAULT 25)
AS
l_mail_conn   UTL_SMTP.connection;
l_boundary    VARCHAR2(50) := '----=*#abc1234321cba#*=';
l_step        PLS_INTEGER  := 24573;
BEGIN
l_mail_conn := UTL_SMTP.open_connection(p_smtp_host, p_smtp_port);
UTL_SMTP.helo(l_mail_conn, p_smtp_host);
UTL_SMTP.mail(l_mail_conn, p_from);
UTL_SMTP.rcpt(l_mail_conn, p_to);

UTL_SMTP.open_data(l_mail_conn);

UTL_SMTP.write_data(l_mail_conn, 'Date: ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'To: ' || p_to || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'From: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Subject: ' || p_subject || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Reply-To: ' || p_from || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'MIME-Version: 1.0' || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: multipart/mixed; boundary="' || l_boundary || '"' || UTL_TCP.crlf || UTL_TCP.crlf);

IF p_text_msg IS NOT NULL THEN
UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: text/plain; charset="iso-8859-1"' || UTL_TCP.crlf || UTL_TCP.crlf);

UTL_SMTP.write_data(l_mail_conn, p_text_msg);
UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
END IF;

IF p_attach_name IS NOT NULL THEN
UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Type: ' || p_attach_mime || '; name="' || p_attach_name || '"' || UTL_TCP.crlf);
UTL_SMTP.write_data(l_mail_conn, 'Content-Disposition: attachment; filename="' || p_attach_name || '"' || UTL_TCP.crlf || UTL_TCP.crlf);

FOR i IN 0 .. TRUNC((DBMS_LOB.getlength(p_attach_clob) - 1 )/l_step) LOOP
UTL_SMTP.write_data(l_mail_conn, DBMS_LOB.substr(p_attach_clob, l_step, i * l_step + 1));
END LOOP;

UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
END IF;

UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || '--' || UTL_TCP.crlf);
UTL_SMTP.close_data(l_mail_conn);

UTL_SMTP.quit(l_mail_conn);
END;
/

The code below shows how the procedure is called.

DECLARE
l_clob CLOB := 'This is a very small CLOB!';
BEGIN
send_mail(p_to          => 'me@mycompany.com',
p_from        => 'admin@mycompany.com',
p_subject     => 'Test Message',
p_text_msg    => 'This is a test message.',
p_attach_name => 'test.txt',
p_attach_mime => 'text/plain',
p_attach_clob => l_clob,
p_smtp_host   => 'smtp.mycompany.com');
END;
/

Miscellaneous

For emails with multiple recipients, simply call the RCPT procedure once for each separate email address.

The UTL_SMTP package requires Jserver which can be installed by running the following scripts as SYS.

SQL> @$ORACLE_HOME/javavm/install/initjvm.sql
SQL> @$ORACLE_HOME/rdbms/admin/initplsj.sql

f you are attempting to use this method from Oracle 11g, you must remember to configure fine grained access to network services for the mail server.

Print Friendly
Tagged as: No Comments
19Feb/120

Images from Oracle Over HTTP

Posted by Infoaddict

This articles defines a process for getting images out of the database over HTTP but it could easily be extended to serve a variety of binary documents. The database functionality used is available in later versions of Oracle 8i also.

Database Access Descriptor Configuration
Create Schema
Create PL/SQL Code
Load Images
Test It

Database Access Descriptor Configuration (DAD)

First we must set up a Database Access Descriptor (DAD) to allow the webserver to connect to the database when a specific URL is requested.

Access the database HTTP server main page via a browser (http://yourServer:7777/). The correct port number is listed in the $ORACLE_HOME/Apache/Apache/setupinfo.txt file
Click on the "Mod_plsql Configuration Menu" link.
Click on the "Gateway Database Access Descriptor Settings" link.
Click on the "Add Default (blank configuration)" link.
Enter SCOTT as the Database Access Descriptor Name. This will be used in the requesting URL.
Enter the username (SCOTT), password (TIGER) and connect string (W2K1) for the desired database connection.
Select the "Basic" authentication mode.
Click the OK button at the top right of the screen.

The list of DADs will now contain the SCOTT entry, which can be edited if necessary by clicking the edit icon next to it.
Create Schema

Next we create a schema to hold our images.

CREATE TABLE images (
id     NUMBER(10)    NOT NULL,
name   VARCHAR2(50)  NOT NULL,
image  BLOB          NOT NULL
)
/

ALTER TABLE images ADD (
CONSTRAINT images_pk PRIMARY KEY (id)
)
/

ALTER TABLE images ADD (
CONSTRAINT images_uk UNIQUE (name)
)
/

CREATE SEQUENCE images_seq
/

CREATE OR REPLACE DIRECTORY image_dir AS 'C:'
/

Create PL/SQL Code

Next we create the code to load and retrieve the images.

CREATE OR REPLACE PACKAGE images_api AS

PROCEDURE load (p_name  IN  images.name%TYPE);
PROCEDURE get  (p_name  IN  images.name%TYPE,
p_type  IN  VARCHAR2 DEFAULT 'gif');

PROCEDURE get_gif  (p_name  IN  images.name%TYPE);
PROCEDURE get_jpeg (p_name  IN  images.name%TYPE);

END;
/

CREATE OR REPLACE PACKAGE BODY images_api AS

PROCEDURE Load (p_name  IN  images.name%TYPE) IS
v_bfile  BFILE;
v_blob   BLOB;
BEGIN
INSERT INTO images (id, name, image)
VALUES (images_seq.NEXTVAL, p_name, EMPTY_BLOB())
RETURN image INTO v_blob;

v_bfile := BFILENAME('IMAGE_DIR', p_name);
DBMS_LOB.fileopen(v_bfile, DBMS_LOB.file_readonly);
DBMS_LOB.loadfromfile(v_blob, v_bfile, DBMS_LOB.getlength(v_bfile));
DBMS_LOB.fileclose(v_bfile);

COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END;

PROCEDURE Get (p_name  IN  images.name%TYPE,
p_type  IN  VARCHAR2 DEFAULT 'gif') IS
v_blob  BLOB;
v_amt   NUMBER := 30;
v_off   NUMBER := 1;
v_raw   RAW(4096);
BEGIN
SELECT image
INTO   v_blob
FROM   images
WHERE  name = p_name;

OWA_UTIL.mime_header('image/' || p_type);

BEGIN
LOOP
DBMS_LOB.read(v_blob, v_amt, v_off, v_raw);

HTP.prn(UTL_RAW.cast_to_varchar2(v_raw));
v_off := v_off + v_amt;
v_amt := 4096;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
END;

PROCEDURE get_gif  (p_name   IN images.name%TYPE) IS
BEGIN
get (p_name, 'gif');
END;

PROCEDURE get_jpeg (p_name  IN  images.name%TYPE) IS
BEGIN
get (p_name, 'jpeg');
END;

END;
/

Load Images

Next we load some images into the database.

EXEC images_api.load('OCP.gif');
EXEC images_api.load('opn_logo2.gif');
EXEC images_api.load('Title.gif');
EXEC images_api.load('Google.gif');

Test It

With the DAD configured and the PL/SQL code in place the XML document can be retrieved by entering the correct URL into a browser.

http://yourServer:7777/pls/SCOTT/Images_API.Get_Gif?p_name=OCP.gif

For security reasons you may wish to access the data over SSL.

https://yourServer:443/pls/SCOTT/Images_API.Get_Gif?p_name=OCP.gif

The SSL port is listed in the $ORACLE_HOME/Apache/Apache/setupinfo.txt file.

Print Friendly
Tagged as: No Comments
19Feb/120

UTL_MAIL

Posted by Infoaddict

The UTL_MAIL package provides a simple API to allow email to be sent from PL/SQL. In prior versions this was possible using the UTL_SMTP package, but this required knowledge of the SMTP protocol.

The package is loaded by running the following scripts.

CONN sys/password AS SYSDBA
@$ORACLE_HOME/rdbms/admin/utlmail.sql
@$ORACLE_HOME/rdbms/admin/prvtmail.plb

In addition the SMTP_OUT_SERVER parameter must be set to identify the SMTP server.

CONN sys/password AS SYSDBA
ALTER SYSTEM SET smtp_out_server='smtp.domain.com' SCOPE=SPFILE;
SHUTDOWN IMMEDIATE
STARTUP

With the configuration complete we can now send a mail.

BEGIN
UTL_MAIL.send(sender     => 'me@domain.com',
recipients => 'person1@domain.com,person2@domain.com',
cc         => 'person3@domain.com',
bcc        => 'myboss@domain.com',
subject    => 'UTL_MAIL Test',
message    => 'If you get this message it worked!');
END;
/

The package also supports sending mails with RAW and VARCHAR2 attachments.

Print Friendly
Tagged as: No Comments
19Feb/120

Oracle Database 10g R2(10.2.0.1) on RHEL5

Posted by Infoaddict

I'll describe the installation of Oracle Database 10g Release 2 (10.2.0.1) on Red Hat Enterprise Linux 5 (RHEL5). The article is based on a server installation similar to this, with a minimum of 2G swap, secure Linux disabled and the following package groups installed.

GNOME Desktop Environment
Editors
Graphical Internet
Text-based Internet
Development Libraries
Development Tools
Legacy Software Development
Server Configuration Tools
Administration Tools
Base
Legacy Software Support
System Tools
X Window System

Alternative installations may require more packages to be loaded, in addition to the ones listed below.

Download Software
Unpack Files
Hosts File
Set Kernel Parameters
Setup
Installation
Post Installation

Download Software

Download the following software.

Oracle Database 10g Release 2 (10.2.0.1) Software

Unpack Files

Unzip the files.

unzip 10201_database_linux32.zip

You should now have a single directory containing installation files. Depending on the age of the download this may either be named "db/Disk1" or "database".
Hosts File

The "/etc/hosts" file must contain a fully qualified name for the server.

<IP-address>  <fully-qualified-machine-name>  <machine-name>

Set Kernel Parameters

Add the following lines to the "/etc/sysctl.conf" file.

#kernel.shmall = 2097152
#kernel.shmmax = 2147483648
kernel.shmmni = 4096
# semaphores: semmsl, semmns, semopm, semmni
kernel.sem = 250 32000 100 128
#fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
net.core.rmem_default=262144
net.core.rmem_max=262144
net.core.wmem_default=262144
net.core.wmem_max=262144

Run the following command to change the current kernel parameters.

/sbin/sysctl -p

Add the following lines to the "/etc/security/limits.conf" file.

*               soft    nproc   2047
*               hard    nproc   16384
*               soft    nofile  1024
*               hard    nofile  65536

Add the following line to the "/etc/pam.d/login" file, if it does not already exist.

session    required     pam_limits.so

Disable secure linux by editing the "/etc/selinux/config" file, making sure the SELINUX flag is set as follows.

SELINUX=disabled

Alternatively, this alteration can be done using the GUI tool (System > Administration > Security Level and Firewall). Click on the SELinux tab and disable the feature.
Setup

Install the following packages.

# From RedHat AS5 Disk 1
cd /media/cdrom/Server
rpm -Uvh setarch-2*
rpm -Uvh make-3*
rpm -Uvh glibc-2*
rpm -Uvh libaio-0*
cd /
eject

# From RedHat AS5 Disk 2
cd /media/cdrom/Server
rpm -Uvh compat-libstdc++-33-3*
rpm -Uvh compat-gcc-34-3*
rpm -Uvh compat-gcc-34-c++-3*
rpm -Uvh gcc-4*
rpm -Uvh libXp-1*
cd /
eject

# From RedHat AS5 Disk 3
cd /media/cdrom/Server
rpm -Uvh openmotif-2*
rpm -Uvh compat-db-4*
cd /
eject

Create the new groups and users.

groupadd oinstall
groupadd dba
groupadd oper

useradd -g oinstall -G dba oracle
passwd oracle

Create the directories in which the Oracle software will be installed.

mkdir -p /u01/app/oracle/product/10.2.0/db_1
chown -R oracle.oinstall /u01

Login as root and issue the following command.

xhost +<machine-name>

Edit the "/etc/redhat-release" file replacing the current release information (Red Hat Enterprise Linux Server release 5 (Tikanga)) with the following:

redhat-4

Login as the oracle user and add the following lines at the end of the ".bash_profile" file.

# Oracle Settings
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR

ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1; export ORACLE_HOME
ORACLE_SID=TSH1; export ORACLE_SID
ORACLE_TERM=xterm; export ORACLE_TERM
PATH=/usr/sbin:$PATH; export PATH
PATH=$ORACLE_HOME/bin:$PATH; export PATH

LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export CLASSPATH

if [ $USER = "oracle" ]; then
if [ $SHELL = "/bin/ksh" ]; then
ulimit -p 16384
ulimit -n 65536
else
ulimit -u 16384 -n 65536
fi
fi

Installation

Log into the oracle user. If you are using X emulation then set the DISPLAY environmental variable.

DISPLAY=<machine-name>:0.0; export DISPLAY

Start the Oracle Universal Installer (OUI) by issuing the following command in the database directory.

./runInstaller

During the installation enter the appropriate ORACLE_HOME and name then continue installation. For a more detailed look at the installation process, click on the links below to see screen shots of each stage.

Select Installation Method
Specify Inventory Directory and Credentials
Select Installation Type
Specify Home Details
Product-Specific Prerequisite Checks
Select Configuration Option
Select Database Configuration
Specify Database Configuration Options
Select Database Management Option
Specify Database Storage Option
Specify Backup and Recovery Options
Specify Database Schema Passwords
Summary
Install
Configuration Assistants
Database Configuration Assistant
Database Configuration Assistant Password Management
Execute Configuration Scripts
End Of Installation

Post Installation

Edit the "/etc/redhat-release" file restoring the original release information.

Red Hat Enterprise Linux Server release 5 (Tikanga)

Edit the "/etc/oratab" file setting the restart flag for each instance to 'Y'.

TSH1:/u01/app/oracle/product/10.2.0/db_1:Y

Print Friendly
Tagged as: , No Comments
19Feb/120

Oracle Database 11g R2(11.2)(64-bit) on Oracle Linux 5 (64-bit)

Posted by Infoaddict

The installation of Oracle Database 11g Release 2 (11.2) (64-bit) on Oracle Linux 5 (64-bit). The article is based on a server installation with a minimum of 2G swap, secure Linux disabled. Oracle recommend a default server installation, but for these installations the following package groups installed:

GNOME Desktop Environment
Editors
Graphical Internet
Text-based Internet
Development Libraries
Development Tools
Server Configuration Tools
Administration Tools
Base
System Tools
X Window System

An example of this type of Linux installations can be seen here. Alternative installations may require more packages to be loaded, in addition to the ones listed below.

Download Software
Unpack Files
Hosts File
Set Kernel Parameters
Setup
Installation
Post Installation

Download Software
Download the following software.

Oracle Database 11g Release 2 (11.2) Software (64-bit)

Unpack Files
Unzip the files.

unzip linux.x64_11gR2_database_1of2.zip
unzip linux.x64_11gR2_database_2of2.zip

You should now have a single directory called "database" containing installation files.
Hosts File
The "/etc/hosts" file must contain a fully qualified name for the server.

<IP-address>  <fully-qualified-machine-name>  <machine-name>

For example.

127.0.0.1       localhost.localdomain  localhost
192.168.2.181   ol5-11gr2.localdomain  ol5-11gr2

Set Kernel Parameters
Oracle recommend the following minimum parameter settings.

fs.suid_dumpable = 1
fs.aio-max-nr = 1048576
fs.file-max = 6815744
kernel.shmall = 2097152
kernel.shmmax = 536870912
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default = 262144
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 1048586

The current values can be tested using the following command.

/sbin/sysctl -a | grep <param-name>

Add or amend the following lines in the "/etc/sysctl.conf" file.

fs.suid_dumpable = 1
fs.aio-max-nr = 1048576
fs.file-max = 6815744
kernel.shmall = 2097152
kernel.shmmax = 536870912
kernel.shmmni = 4096
# semaphores: semmsl, semmns, semopm, semmni
kernel.sem = 250 32000 100 128
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default=4194304
net.core.rmem_max=4194304
net.core.wmem_default=262144
net.core.wmem_max=1048586

Run the following command to change the current kernel parameters.

/sbin/sysctl -p

Add the following lines to the "/etc/security/limits.conf" file.

oracle              soft    nproc   2047
oracle              hard    nproc   16384
oracle              soft    nofile  1024
oracle              hard    nofile  65536
oracle              soft    stack   10240

Disable secure linux by editing the "/etc/selinux/config" file, making sure the SELINUX flag is set as follows.

SELINUX=disabled

Alternatively, this alteration can be done using the GUI tool (Applications > System Settings > Security Level). Click on the SELinux tab and disable the feature. If SELinux is disabled after installation, the server will need a reboot for the change to take effect.
Setup
Install the following packages if they are not already present.

# From Oracle Linux 5 DVD
cd /media/cdrom/Server
rpm -Uvh binutils-2.*
rpm -Uvh compat-libstdc++-33*
rpm -Uvh compat-libstdc++-33*.i386.rpm
rpm -Uvh elfutils-libelf*
rpm -Uvh gcc-4.*
rpm -Uvh gcc-c++-4.*
rpm -Uvh glibc-2.*
rpm -Uvh glibc-common-2.*
rpm -Uvh glibc-devel-2.*
rpm -Uvh glibc-headers-2.*
rpm -Uvh ksh*
rpm -Uvh libaio-0.*
rpm -Uvh libaio-devel-0.*
rpm -Uvh libgomp-4.*
rpm -Uvh libgcc-4.*
rpm -Uvh libstdc++-4.*
rpm -Uvh libstdc++-devel-4.*
rpm -Uvh make-3.*
rpm -Uvh sysstat-7.*
rpm -Uvh unixODBC-2.*
rpm -Uvh unixODBC-devel-2.*
rpm -Uvh numactl-devel-2*
cd /
eject

Create the new groups and users.

groupadd oinstall
groupadd dba
groupadd oper
groupadd asmadmin

useradd -g oinstall -G dba,oper,asmadmin oracle
passwd oracle

Note. We are not going to use the "asmadmin" group, since this installation will not use ASM.

Create the directories in which the Oracle software will be installed.

mkdir -p /u01/app/oracle/product/11.2.0/db_1
chown -R oracle:oinstall /u01
chmod -R 775 /u01

Login as root and issue the following command.

xhost +<machine-name>

Login as the oracle user and add the following lines at the end of the ".bash_profile" file.

# Oracle Settings
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR

ORACLE_HOSTNAME=ol5-11gr2.localdomain; export ORACLE_HOSTNAME
ORACLE_UNQNAME=DB11G; export ORACLE_UNQNAME
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1; export ORACLE_HOME
ORACLE_SID=DB11G; export ORACLE_SID
PATH=/usr/sbin:$PATH; export PATH
PATH=$ORACLE_HOME/bin:$PATH; export PATH

LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export CLASSPATH

Installation
Log into the oracle user. If you are using X emulation then set the DISPLAY environmental variable:

DISPLAY=<machine-name>:0.0; export DISPLAY

Start the Oracle Universal Installer (OUI) by issuing the following command in the database directory:

./runInstaller

Proceed with the installation of your choice. You can see the type of installation I performed by clicking on the links below to see screen shots of each stage.

Configure Security Updates
Select Install Option
System Class
Node Selection
Select Install Type
Typical Install Configuration
Create Inventory
Perform Prerequisite Checks
Summary
Install Product
Database Configuration Assistant
Database Configuration Assistant 2
Execute Configuration Scripts
Finish

Post Installation

Edit the "/etc/oratab" file setting the restart flag for each instance to 'Y'.

DB11G:/u01/app/oracle/product/11.2.0/db_1:Y

Print Friendly
Tagged as: , No Comments
18Feb/120

LAMP INSTALLATION WITH CONFIGURATION ON CENTOSE 5.3

Posted by Infoaddict

[root@fedorasmpp ~]#vi /etc/sysconfig/network-scripts/ifcfg-eth0

192.168.1.200

255.255.255.0

192.168.1.1

[root@fedorasmpp ~]#vi /etc/hosts

192.168.1.200 fedorasmpp.xxx.com fedorasmpp

:wq!

mysqladmin -h fedorasmpp.dataslices.com -u root password

[root@fedorasmpp ~]# yum install mysql mysql-server

[root@fedorasmpp ~]# chkconfig --levels 235 mysqld on

[root@fedorasmpp ~]# /etc/init.d/mysqld start

Starting mysqld:                                            [  OK  ]

[root@fedorasmpp ~]# mysqladmin -u root password redhat

[root@fedorasmpp ~]# mysqladmin -h fedorasmpp.dataslices.com -u root password redhat

[root@fedorasmpp ~]# yum install httpd

[root@fedorasmpp ~]# chkconfig --levels 235 httpd on

[root@fedorasmpp ~]# /etc/init.d/httpd start

Starting httpd:                                             [  OK  ]

[root@fedorasmpp ~]# yum install php

[root@fedorasmpp ~]#/etc/inid.d/httpd restart

open Browser mention in url

http://192.168.1.9/info.php

[root@fedorasmpp ~]# yum install php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc

Loaded plugins: fastestmirror

Loading mirror speeds from cached hostfile

 * addons: mirror.eshk.hk

 * base: mirror.eshk.hk

 * extras: mirrors.digipower.vn

 * updates: mirrors.digipower.vn

Setting up Install Process

Package php-mysql-5.1.6-27.el5_5.3.i386 already installed and latest version

Package php-ldap-5.1.6-27.el5_5.3.i386 already installed and latest version

Package php-odbc-5.1.6-27.el5_5.3.i386 already installed and latest version

Package 1:php-pear-1.4.9-6.el5.noarch already installed and latest version

Resolving Dependencies

--> Running transaction check

---> Package php-gd.i386 0:5.1.6-27.el5_5.3 set to be updated

---> Package php-imap.i386 0:5.1.6-27.el5_5.3 set to be updated

--> Processing Dependency: libc-client.so.1 for package: php-imap

---> Package php-xml.i386 0:5.1.6-27.el5_5.3 set to be updated

---> Package php-xmlrpc.i386 0:5.1.6-27.el5_5.3 set to be updated

--> Running transaction check

---> Package libc-client.i386 0:2004g-2.2.1 set to be updated

--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================

 Package                        Arch                    Version                             Repository                  Size

=============================================================================================================================

Installing:

 php-gd                         i386                    5.1.6-27.el5_5.3                    updates                    117 k

 php-imap                       i386                    5.1.6-27.el5_5.3                    updates                     54 k

 php-xml                        i386                    5.1.6-27.el5_5.3                    updates                     97 k

 php-xmlrpc                     i386                    5.1.6-27.el5_5.3                    updates                     58 k

Installing for dependencies:

 libc-client                    i386                    2004g-2.2.1                         base                       516 k

Transaction Summary

=============================================================================================================================

Install       5 Package(s)

Upgrade       0 Package(s)

Total download size: 842 k

Is this ok [y/N]: y

Downloading Packages:

(1/5): php-imap-5.1.6-27.el5_5.3.i386.rpm                                                             |  54 kB     00:00

(2/5): php-xmlrpc-5.1.6-27.el5_5.3.i386.rpm                                                           |  58 kB     00:00

(3/5): php-xml-5.1.6-27.el5_5.3.i386.rpm                                                              |  97 kB     00:00

(4/5): php-gd-5.1.6-27.el5_5.3.i386.rpm                                                               | 117 kB     00:00

(5/5): libc-client-2004g-2.2.1.i386.rpm                                                               | 516 kB     00:01

-----------------------------------------------------------------------------------------------------------------------------

Total                                                                                        103 kB/s | 842 kB     00:08

Running rpm_check_debug

Running Transaction Test

Finished Transaction Test

Transaction Test Succeeded

Running Transaction

  Installing     : libc-client                                                                                           1/5

  Installing     : php-xmlrpc                                                                                            2/5

  Installing     : php-imap                                                                                              3/5

  Installing     : php-xml                                                                                               4/5

  Installing     : php-gd                                                                                                5/5

Installed:

  php-gd.i386 0:5.1.6-27.el5_5.3             php-imap.i386 0:5.1.6-27.el5_5.3         php-xml.i386 0:5.1.6-27.el5_5.3

  php-xmlrpc.i386 0:5.1.6-27.el5_5.3

Dependency Installed:

  libc-client.i386 0:2004g-2.2.1

Complete!

[root@fedorasmpp ~]# /etc/init.d/httpd restart

Stopping httpd:                                            [  OK  ]

Starting httpd:                                            [  OK  ]

[root@fedorasmpp ~]# wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm

--2011-01-16 14:07:03--  http://packages.sw.be/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm

Resolving packages.sw.be... 85.13.226.40

Connecting to packages.sw.be|85.13.226.40|:80... connected.

HTTP request sent, awaiting response... 302 Found

Location: http://rpmforge.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm [following]

--2011-01-16 14:07:03--  http://rpmforge.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm

Resolving rpmforge.sw.be... 85.13.226.40

Reusing existing connection to packages.sw.be:80.

HTTP request sent, awaiting response... 200 OK

Length: 16698 (16K) [application/x-rpm]

Saving to: `rpmforge-release-0.3.6-1.el5.rf.i386.rpm'

100%[===================================================================================>] 16,698      --.-K/s   in 0.1s

2011-01-16 14:07:04 (111 KB/s) - `rpmforge-release-0.3.6-1.el5.rf.i386.rpm' saved [16698/16698]

[root@fedorasmpp ~]# rpm -Uvh rpmforge-release-0.3.6-1.el5.rf.i386.rpm

warning: rpmforge-release-0.3.6-1.el5.rf.i386.rpm: Header V3 DSA signature: NOKEY, key ID 6b8d79e6

Preparing...                ########################################### [100%]

   1:rpmforge-release       ########################################### [100%]

[root@fedorasmpp ~]# yum install phpmyadmin

Loaded plugins: fastestmirror

Loading mirror speeds from cached hostfile

 * addons: mirror.eshk.hk

 * base: mirror.eshk.hk

 * extras: mirrors.digipower.vn

 * rpmforge: fr2.rpmfind.net

 * updates: mirrors.digipower.vn

rpmforge                                                                                              | 1.1 kB     00:00

rpmforge/primary                                                                                      | 2.2 MB     00:22

rpmforge                                                                                                         10369/10369

Setting up Install Process

Resolving Dependencies

--> Running transaction check

---> Package phpmyadmin.noarch 0:2.11.11.1-1.el5.rf set to be updated

--> Processing Dependency: php-mbstring >= 4.1.0 for package: phpmyadmin

--> Processing Dependency: php-mcrypt for package: phpmyadmin

--> Running transaction check

---> Package php-mbstring.i386 0:5.1.6-27.el5_5.3 set to be updated

---> Package php-mcrypt.i386 0:5.1.6-15.el5.centos.1 set to be updated

--> Processing Dependency: libmcrypt.so.4 for package: php-mcrypt

--> Running transaction check

---> Package libmcrypt.i386 0:2.5.8-4.el5.centos set to be updated

--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================

 Package                      Arch                   Version                                  Repository                Size

=============================================================================================================================

Installing:

 phpmyadmin                   noarch                 2.11.11.1-1.el5.rf                       rpmforge                 4.2 M

Installing for dependencies:

 libmcrypt                    i386                   2.5.8-4.el5.centos                       extras                   116 k

 php-mbstring                 i386                   5.1.6-27.el5_5.3                         updates                  995 k

 php-mcrypt                   i386                   5.1.6-15.el5.centos.1                    extras                    16 k

Transaction Summary

=============================================================================================================================

Install       4 Package(s)

Upgrade       0 Package(s)

Total download size: 5.3 M

Is this ok [y/N]: y

Is this ok [y/N]: y

Downloading Packages:

(1/4): php-mcrypt-5.1.6-15.el5.centos.1.i386.rpm                                                      |  16 kB     00:00

(2/4): libmcrypt-2.5.8-4.el5.centos.i386.rpm                                                          | 116 kB     00:00

(3/4): php-mbstring-5.1.6-27.el5_5.3.i386.rpm                                                         | 995 kB     00:02

(4/4): phpmyadmin-2.11.11.1-1.el5.rf.noarch.rpm                                                       | 4.2 MB     00:09

-----------------------------------------------------------------------------------------------------------------------------

Total                                                                                        365 kB/s | 5.3 MB     00:14

Running rpm_check_debug

Running Transaction Test

Finished Transaction Test

Transaction Test Succeeded

Running Transaction

  Installing     : libmcrypt                                                                                             1/4

  Installing     : php-mcrypt                                                                                            2/4

  Installing     : php-mbstring                                                                                          3/4

  Installing     : phpmyadmin                                                                                            4/4

Installed:

  phpmyadmin.noarch 0:2.11.11.1-1.el5.rf

Dependency Installed:

  libmcrypt.i386 0:2.5.8-4.el5.centos    php-mbstring.i386 0:5.1.6-27.el5_5.3    php-mcrypt.i386 0:5.1.6-15.el5.centos.1

Complete!

[root@fedorasmpp ~]# vi /etc/httpd/conf.d/phpmyadmin.conf

#  Web application to manage MySQL

#

<Directory "/usr/share/phpmyadmin">

  Order Deny,Allow

  Deny from all

  Allow from 127.0.0.1

</Directory>

Alias /phpmyadmin /usr/share/phpmyadmin

Alias /phpMyAdmin /usr/share/phpmyadmin

Alias /mysqladmin /usr/share/phpmyadmin

:wq!

Next Configuration Step we change the authentication in phpMyAdmin for cookie by http:

========================

BY DEFAULT CONFIGURATION

========================

/* Authentication type */

$cfg['Servers'][$i]['auth_type'] = 'cookie';

s

==========================

AFTER CHANGE CONFIGURATION

==========================

/* Authentication type */

$cfg['Servers'][$i]['auth_type'] = 'http';

[root@fedorasmpp ~]# /etc/init.d/httpd restart

Stopping httpd:                                            [  OK  ]

Starting httpd:                                            [  OK  ]

you can access phpMyAdmin under http://192.168.1.9/phpmyadmin/:

Print Friendly
Tagged as: No Comments
18Feb/120

How to Install and Configure SARG

Posted by Infoaddict

SARG (Squid Analysis Report Generator) is a tool that allow you to view "where" your users are going to on the Internet.
Sarg it self, provide to end user a generic interface to create reports based on squid access log (begin of log to current date).
sarg-reports (this script) is useful because it allow you to easily create and manage Daily, Weekly and Monthly reports.
Using sarg-reports is very easy, read the following steps to know how to installing and configuring this tools:

Requirements
a) An unix system with bash shell (like GNU/Linux, FreeBSD, etc...)
b) Squid - http://www.squid-cache.org
c) Sarg - http://sarg.sourceforge.net/
d) Apche web server - http://www.apache.org/

1. Download the package from here.

2. Unzip the package by following command.

#unzip sarg-2.2.5-1.el5.rf.i386.zip

3. This is the RPM package, so I can install the package easily, I use the following command.

# rpm -ivh sarg-2.2.5-1.el5.rfi386.rpm

4. Edit configuration file as shown bellow

# vim /etc/sarg/sarg.conf

This is my configuration file, of course you can change it like you want

access_log /var/log/squid/access.log
graphs yes
graph_days_bytes_bar_color orange
title "Squid User Access Reports"
output_dir /var/www/htdocs/sarg
resolve_ip no
topuser_sort_field BYTES reverse
user_sort_field BYTES reverse
lastlog 3
remove_temp_files yes
index yes
overwrite_report yes
topsites_num 100
topsites_sort_order CONNECT D
index_sort_order D
max_elapsed 28800000
report_type topsites sites_users users_sites date_time denied auth_failures site_user_time_date
show_successful_message yes
show_read_statistics yes
topuser_fields NUM DATE_TIME USERID CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
user_report_fields CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
topuser_num 0
show_sarg_logo yes

6. To Generate the log report, simply run the command

#sarg - l /var/log/squid/access.log

The reports will be saved in /var/www/sarg/ONE-SHOT directory

To generate the log report by the cron job you can make entry in "/etc/crontab" file

00 23 * * * root /usr/bin/sarg

It will generate the log report every day at 11.00 P.M

You can also see all command line switches by following command

#sarg -h

7. Example To generate report by manually :

#sarg -l /var/log/squid/access.log -o /var/www/sarg/daily -z -d 21/06/2009

It will generate the log report date 21/6/2009 into /var/www/sarg/daily directory

If you want log report from 21/06/2009 to 28/06/2009 then run this command

#sarg -l /var/log/squid/access.log -o /var/www/sarg/ONE-SHOT -z -d 21/06/2009-28/06/2009

8. To view the log report generated by sarg start httpd service

/etc/init.d/httpd start

And browes url "http://ip_of_linux box/sarg" eg.

http://10.0.0.1/sarg

make sure that apache is working and publish squidlogs..

If you want apache ask password to allow sarg report you can configure .htaccess file and .htpassword.

Source: http://sarg.sourceforge.net/

Print Friendly
18Feb/120

Linux Load Balancer of Webserver

Posted by Infoaddict

6 Nodes Load Balancer

Two nodes for LVS (Piranha Pulse nannay Ipvsadm) as Load balancer
Two nodes for Web servers can be multiple upto your requirement.
Two nodes for mysql database server using Drbd & heartbeat for highly avaliable mysql database.

3 types of LoadBalancers
1. Nating
2. Direct Routing
3. Tunneling

CentOS 5.3 is used as Operating System.

In this setup we are using LVS(Linux virtual server) using Direct Routing Method these packages are available on Redhat5.x/CentOs5.x.

We will cover these in few steps.

1 . we will setup basic setup for whole 6 nodes

> Host file configuration (In real network use DNS or both.)
> Ssh key generation (For authentication betwen all 6 nodes)
> NTP Configuration (For time syncronization if possible use dedicated NTP server otherwise 1 node can be used)

2 . We need to configure LVS setup for the two highly available Load balancers. (If one down other will do the same function)

3 . We need to configure web servers for the Load balancing the web service. (Both will have apache php php-mysql php-gd service installaed We also install joomla on both server to check our web and Mysql service working.)

4 . We need to configure Drbd & heartbeat service on two db servers.(Db1 and Db2 will be active passive mode to give highly availabe mysql database service and it's data/databses).

5 . We need to configure joomla on both web server's and make thier connection with mysql databses servers.

1. Basic configurations of all 6 nodes.

On all Nodes. Please copy this file on all servers/nodes

[root@lb1 /]# cat /etc/hosts
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6

##### IP's of Load Balancers #####
10.0.0.1 lb1.infoaddict.org lb1
10.0.0.2 lb2.infoaddict.org lb2

##### IP's of Web Servers #####
10.0.0.30 www1.infoaddict.org www1
10.0.0.40 www2.infoaddict.org www2

##### IP's of MySQL DB servers #####
10.0.0.50 db1.infoaddict.org db1
10.0.0.51 db2.infoaddict.org db2

########## Here is Virtual IP/Service IP of Webserver and MySQL DB ##########

10.0.0.3 www.infoaddict.org www
10.0.0.190 db.infoaddict.org db

Copy this /etc/hosts file to all the servers

[root@lb1 /]#

Now generate ssh keys

[root@lb1 ~]# ssh-keygen -t rsa

[root@lb1 ~]# ssh-keygen -t dsa

[root@lb1 ~]# cd /root/.ssh/

[root@lb1 ~]# cat *.pub > authorized_keys

[root@lb1 ~]#scp -r /root/.ssh/ lb2:/root/

[root@lb1 ~]#scp -r /root/.ssh/ www1:/root/

[root@lb1 ~]#scp -r /root/.ssh/ www2:/root/

[root@lb1 ~]#scp -r /root/.ssh/ db1:/root/

[root@lb1 ~]#scp -r /root/.ssh/ db2:/root/

[root@lb1 ~]#ssh-keyscan -t dsa lb1 lb2 db1 db2 www1 www2

[root@lb1 ~]#ssh-keyscan -t rsa lb1 lb2 db1 db2 www1 www2

Stop Unwanted services on all nodes.

[root@lb1 ~]# /etc/init/sendmail stop

[root@lb1 ~]# chkconfig --level 235 sendmail off

3. NTP configuration.

Run this command on all nodes & Make sure the ntp is installed on all nodes.

[root@lb1 ~]# rpm -qa | grep ntp
ntp-4.2.2p1-9.el5.centos
chkfontpath-1.10.1-1.1
[root@lb1 ~]#
[root@lb1 ~]# vim /etc/ntp.conf ###Configuration for NTP server###
restrict 127.0.0.1

server 127.127.1.0 # local clock

save & quit
[root@lb1 ~]#
[root@lb1 ~]# /etc/init.d/ntpd restart
Shutting down ntpd: [ OK ]
Starting ntpd: [ OK ]
[root@lb1 ~]#

Clinet side configuration

[root@db2 /]# vim /etc/ntp.conf

#restrict 127.0.0.1
#restrict -6 ::1

server 10.0.0.1 ##Put Server IP here##

#server 0.centos.pool.ntp.org
#server 1.centos.pool.ntp.org
#server 2.centos.pool.ntp.org

#server 127.127.1.0 # local clock
#fudge 127.127.1.0 stratum 10

save & quit

[root@db2 /]# /etc/init.d/ntpd restart
Shutting down ntpd: [ OK ]
Starting ntpd: [ OK ]
[root@db2 /]#

[root@db2 /]#
[root@db2 /]# ntpdate -u 10.0.0.1
16 Jul 11:55:34 ntpdate[12101]: step time server 10.0.0.1 offset -3.069414 sec
[root@db2 /]#

Copy this file /etc/ntp.conf on all 4 nodes .i.e www1 www2 db1 db2 and restart the ntp service on those nodes.

Run this command on all nodes.

[root@db2 /]# ntpdate -u 10.0.0.1

LVS Setup configuration on LB1 and LB2

We need to install Piranha package it will automaticaly instll pulse,ipvsadm,nanny

install piranha on both nodes

[root@lb1 ~]# yum install piranha -y

[root@lb2 ~]# yum install piranha -y

[root@lb1 ~]# vim /etc/sysconfig/ha/lvs.cf

serial_no = 14
primary = 10.0.0.1
service = lvs
rsh_command = ssh
backup_active = 1
backup = 10.0.0.2
heartbeat = 1
heartbeat_port = 1050
keepalive = 2
deadtime = 10
network = direct ### use nat if nating method is used ###
debug_level = NONE
monitor_links = 1
virtual server1 {
active = 1
address = 10.0.0.3 eth0:1
port = 80
send = "GET / HTTP/1.1\r\n\r\n"
expect = "HTTP"
load_monitor = uptime
scheduler = rr
protocol = tcp
timeout = 10
reentry = 180
quiesce_server = 0
server www1 {
address = 10.0.0.30
active = 1
weight = 1
}
server www2 {
address = 10.0.0.40
active = 1
weight = 1
}
}

save & exit

[root@lb1 ~]# scp /etc/sysconfig/ha/lvs.cf lb2:/etc/sysconfig/ha/

[root@lb1 ~]# cat /etc/sysctl.conf

net.ipv4.ip_forward = 1

net.ipv4.conf.eth0.arp_ignore = 1

net.ipv4.conf.all.arp_announce = 2

net.ipv4.conf.eth0.arp_announce = 2

save & exit

[root@lb1 ~]# scp /etc/sysctl.conf lb2:/etc/

Run this command on both nodes

[root@lb1 ~]# [root@lb1 ~]# sysctl -p
net.ipv4.ip_forward = 1
net.ipv4.conf.eth0.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.eth0.arp_announce = 2
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 4294967295
kernel.shmall = 268435456
[root@lb1 ~]#

Before starting service pulse start httpd on both web servers.

[root@www1 ~]#/etc/init.d/httpd start
[root@www1 ~]#/etc/init.d/httpd start

Start pulse service on both lvs/LoadBalancer servers

[root@lb1 ~]# /etc/init.d/pulse start
Starting pulse:
[root@lb1 ~]#

[root@lb1 ~]# /etc/init.d/pulse restart
Shutting down pulse: [ OK ]
Starting pulse: [ OK ]
[root@lb1 ~]# tail -f /var/log/messages
Jul 16 12:24:18 lb1 pulse[6363]: STARTING PULSE AS MASTER
Jul 16 12:24:28 lb1 pulse[6363]: partner dead: activating lvs
Jul 16 12:24:28 lb1 avahi-daemon[2940]: Registering new address record for 10.0.0.3 on eth0.
Jul 16 12:24:28 lb1 lvs[6367]: starting virtual service server1 active: 80
Jul 16 12:24:28 lb1 nanny[6376]: starting LVS client monitor for 10.0.0.3:80
Jul 16 12:24:28 lb1 lvs[6367]: create_monitor for server1/www1 running as pid 6376
Jul 16 12:24:28 lb1 nanny[6377]: starting LVS client monitor for 10.0.0.3:80
Jul 16 12:24:28 lb1 lvs[6367]: create_monitor for server1/www2 running as pid 6377
Jul 16 12:24:28 lb1 nanny[6376]: [ active ] making 10.0.0.30:80 available
Jul 16 12:24:28 lb1 nanny[6377]: [ active ] making 10.0.0.40:80 available
Jul 16 12:24:33 lb1 pulse[6369]: gratuitous lvs arps finished

it seems good now our pulse is working fine.

3. Web servers configuration On both servers.

[root@www1 ~]# yum install httpd php php-mysql php-gd

[root@www1 ~]# yum install arptables_jf

[root@www1 ~]#echo "Load Balancing" > /var/www/html/test.html

[root@www2 ~]#echo "Load Balancing1" > /var/www/html/test.html

For both server we need to configure the Loopback interface

[root@www1 ~]# vim /etc/sysconfig/network-scripts/ifcfg-lo:0
DEVICE=lo:0
IPADDR=10.0.0.3
NETMASK=255.255.255.255
NETWORK=10.0.0.0
# If you're having problems with gated making 127.0.0.0/8 a martian,
# you can change this to something else (255.255.255.255, for example)
BROADCAST=10.255.255.255
ONBOOT=yes
NAME=loopback
[root@www1 ~]#
[root@www1 ~]#ifup lo:0

[root@www2 ~]# vim /etc/sysconfig/network-scripts/ifcfg-lo:0
DEVICE=lo:0
IPADDR=10.0.0.3
NETMASK=255.255.255.255
NETWORK=10.0.0.0
# If you're having problems with gated making 127.0.0.0/8 a martian,
# you can change this to something else (255.255.255.255, for example)
BROADCAST=10.255.255.255
ONBOOT=yes
NAME=loopback
[root@www2 ~]#
[root@www2 ~]# ifup lo:0

on both real servers

[root@www1 ~]#arptables -A IN -d 10.0.0.3 -j DROP
[root@www1 ~]#arptables -A OUT -d 10.0.0.3 -j mangle --mangle-ip-s 10.0.0.1
[root@www1 ~]#arptables -A OUT -d 10.0.0.3 -j mangle --mangle-ip-s 10.0.0.2
[root@www1 ~]#
[root@www1 ~]# /etc/init.d/arptables_jf save
Saving current rules to /etc/sysconfig/arptables: [ OK ]
[root@www1 ~]#

[root@www2 ~]#arptables -A IN -d 10.0.0.3 -j DROP
[root@www2 ~]#arptables -A OUT -d 10.0.0.3 -j mangle --mangle-ip-s 10.0.0.1
[root@www2 ~]#arptables -A OUT -d 10.0.0.3 -j mangle --mangle-ip-s 10.0.0.2
[root@www2 ~]# /etc/init.d/arptables_jf save
Saving current rules to /etc/sysconfig/arptables: [ OK ]
[root@www2 ~]#

We need to tell system to up lo:0 every time at boot.

[root@www1 ~]# echo "ifup lo:0" > /etc/rc.local
[root@www2 ~]# echo "ifup lo:0" > /etc/rc.local

Here we need to test the setup is working fine here we have two lvs and webservers

this command will show about the connections.

[root@lb1 ~]# ipvsadm -L
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP www.infoaddict.org:ht rr
-> www2.infoaddict.org:h Route 1 0 0
-> www1.infoaddict.org:h Route 1 0 0
[root@lb1 ~]#

[root@lb1 ~]# watch ipvsadm -Lcn

Configuration of Drbd & Heartbeat on Both database servers

Here we need to configure partitions on both servers

PARTITION SETUP On Both Servers.

Partion setup on both server identical same with fdisk

We have 4GB disks on both servers.

Partition Setup for Cluster Servers

We need to create LVM partition

[root@db1 ~]# fdisk -l

[root@db1 ~]# fdisk /dev/sdb

[root@db1 ~]# fdisk /dev/sd
sda sda1 sda2 sdb sdb1
[root@db2 ~]# fdisk /dev/sdb

Command (m for help): m
Command action
a toggle a bootable flag
b edit bsd disklabel
c toggle the dos compatibility flag
d delete a partition
l list known partition types
m print this menu
n add a new partition
o create a new empty DOS partition table
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition's system id
u change display/entry units
v verify the partition table
w write table to disk and exit
x extra functionality (experts only)

Command (m for help): p

Disk /dev/sdb: 4294 MB, 4294967296 bytes
255 heads, 63 sectors/track, 522 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sdb1 1 522 4192933+ 8e Linux LVM

Command (m for help): d
Selected partition 1

Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-522, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-522, default 522): +4000M

Command (m for help): p

Disk /dev/sdb: 4294 MB, 4294967296 bytes
255 heads, 63 sectors/track, 522 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sdb1 1 487 3911796 83 Linux

Command (m for help): t
Selected partition 1
Hex code (type L to list codes): 8e
Changed system type of partition 1 to 8e (Linux LVM)

Command (m for help): p

Disk /dev/sdb: 4294 MB, 4294967296 bytes
255 heads, 63 sectors/track, 522 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sdb1 1 487 3911796 8e Linux LVM

Command (m for help):

Command (m for help): w

[root@db1 ~]# partprobe

Create Physical Volume for LVM this is second step for LVM partition.

[root@db1 ~]# pvcreat /dev/sdb1 /dev/sdb2

Create Volume Group with this command

[root@db1 ~]# vgcreate vgdb /dev/sdb1

Create Logical volume partition

[root@db1 ~]# lvcreate -L +1000M -n /dev/mapper/vgdb/lvdb
[root@db1 ~]# lvcreate -L +256M -n /dev/mapper/vgdb/lvmeta

Note: Create LVM on Both servers identical same ...................

install drbd and configure it.

[root@db1 ~]# yum install drbd82 kmod-drbd82 -y

[root@db2 ~]# yum install drbd82 kmod-drbd82 -y

[root@db1 ~]modprobe drbd

[root@db2 ~]modprobe drbd

[root@db1 ~]echo "modprobe drbd" > /etc/rc.local

[root@db2 ~]echo "modprobe drbd" > /etc/rc.local

[root@db1 ~]#vim /etc/drbd.conf

global {
usage-count yes;
}

common {
syncer { rate 10M; }
}

resource r0 {
protocol C;
handlers {
pri-on-incon-degr "echo o > /proc/sysrq-trigger ; halt -f";
pri-lost-after-sb "echo o > /proc/sysrq-trigger ; halt -f";
local-io-error "echo o > /proc/sysrq-trigger ; halt -f";
outdate-peer "/usr/lib/heartbeat/drbd-peer-outdater -t 5";
}

startup {
}

disk {
on-io-error detach;
}

net {
after-sb-0pri disconnect;
after-sb-1pri disconnect;
after-sb-2pri disconnect;
rr-conflict disconnect;
}

syncer {
rate 10M;
al-extents 257;
}

on db1.infoaddict.org {
device /dev/drbd0;
disk /dev/vgdb/lvdb;
address 10.0.0.50:7788;
meta-disk /dev/vgdb/lvmeta[1];
}

on db2.infoaddict.org {
device /dev/drbd0;
disk /dev/vgdb/lvdb;
address 10.0.0.51:7788;
meta-disk /dev/vgdb/lvmeta[1];
}

}

save & exit

[root@db1 ~]#scp /etc/drbd.conf lb2:/etc/
[root@db1 ~]#vi /etc/sysctl.conf

net.ipv4.conf.eth0.arp_ignore = 1

net.ipv4.conf.all.arp_announce = 2

net.ipv4.conf.eth0.arp_announce = 2

save & quit

[root@db1 ~]# sysctl -p
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.eth0.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.eth0.arp_announce = 2
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 4294967295
kernel.shmall = 268435456
[root@db1 ~]#

save it........

[root@db1 ~]#
[root@db1 ~]# scp /etc/drbd.conf db2:/etc/drbd.conf

We need to run module on both servers to run drbd

Load DRBD module both nodes:

[root@db1 ~]# modprobe drbd

[root@db1 ~]# echo "modprobe drbd" >> /etc/rc.local

[root@db2 ~]# modprobe drbd

[root@db2 ~]# echo "modprobe drbd"  >> /etc/rc.local

##### run this on both servers ######

[root@db1 ~]#drbdadm create-md r0

[root@db2 ~]#drbdadm create-md r0

[root@db1 ~]#drbdadm attach r0

[root@db2 ~]#drbdadm attach r0

[root@db1 ~]#drbdadm syncer r0

[root@db2 ~]#drbdadm syncer r0

[root@db1 ~]#drbdadm connect r0

[root@db2 ~]#drbdadm connect r0

On Primary Node only

[root@db1 ~]#drbdadm -- --overwrite-data-of-peer primary r0

On both Nodes:

[root@db1 ~]#drbdadm up all

[root@db2 ~]#drbdadm up all

On Primary Node only

[root@db1 ~]#drbdadm -- primary all #### ON Node one Only ####

[root@db1 ~]#watch cat /proc/drbd

only on db1 ########## Primary Node ########

[root@db1 ~]#mkfs.ext3 /dev/drbd0

[root@db1 ~]#mkdir /data/

[root@db1 ~]#mount /dev/drbd0 /data/

[root@db1 ~]#
[root@db1 ~]# df -hk
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/VolGroup00-LogVol00
5967432 2625468 3033948 47% /
/dev/sda1 101086 12074 83793 13% /boot
tmpfs 257720 0 257720 0% /dev/shm
/dev/drbd0 4031516 107600 3719128 3% /data
[root@db1 ~]#
[root@db1 ~]# umount /dev/drbd0 /data

Note: HeartBeat will automatically handle this.

On db2 ####### Secondry Node #######

[root@db2 ~]#mkdir /data

Heartbeat Setup:
================

Install heartbeat package using yum

Note: Internet connection is required or configure yum repository on your local machine with extras.

[root@db1 ~]#yum install -y heartbeat heartbeat-pils heartbeat-stonith heartbeat-devel

[root@db1 ~]#vim /etc/ha.d/ha.cf ## Create this file and copy this text ##

logfacility local0
keepalive 2
#deadtime 30 # USE THIS!!!
deadtime 10
# we use two heartbeat links, eth2 and serial 0
bcast eth0
#serial /dev/ttyS0
baud 19200
auto_failback off
node db1.infoaddict.org
node db2.infoaddict.org

save & quit.

Server db1

[root@db1 ~]#vi /etc/ha.d/haresources

db1 IPaddr::10.0.0.190/8/eth0 drbddisk::r0 Filesystem::/dev/drbd0::/data::ext3 mysql

Server db2:

[root@db2 ~]#vi /etc/ha.d/haresources

db2 IPaddr::10.0.0.190/8/eth0 drbddisk::r0 Filesystem::/dev/drbd0::/data::ext3  mysql

On Both Servers:

[root@db1 ~]#vi /etc/ha.d/authkeys

auth 3
3 md5 redhat ######### Use Long name as password #########

both NODE:

[root@db1 ~]#chmod 600 /etc/ha.d/authkeys

[root@db1 ~]#scp /etc/ha.d/authkeys db2:/etc/ha.d/authkeys

[root@db1 ~]#chkconfig --level 235 heartbeat on

Note: if you have problem mounting /dev/drbd0 on /data then run these commands to check the status if you found the drbddisk stopped then start it.

Mysql Configuration.

cp /etc/my.cnf /etc/my.cnf.orig

vi /etc/my.cnf

[mysqld]
# datadir=/var/lib/mysql
datadir=/data/mysql
#socket=/var/lib/mysql/mysql.sock
socket=/data/mysql/mysql.sock
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1

[mysql.server]
user=mysql
#basedir=/var/lib
basedir=/data

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

[mysql]
socket=/data/mysql/mysql.sock

Now it is time to add users/hosts to mysql server:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.0.0.30' IDENTIFIED BY 'redhat'
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.0.0.40' IDENTIFIED BY 'redhat'
mysql> FLUSH PRIVILEGES;

mysql>quit

Now we need to install joomla on both web servers

On Webserver 1

[root@www1 /]# yum install php php-mysql php-gd -y

[root@www1 ~]# ls
anaconda-ks.cfg Desktop install.log install.log.syslog Joomla_1.5.13-Stable-Full_Package
[root@www1 ~]# cd Joomla_1.5.13-Stable-Full_Package/
[root@www1 Joomla_1.5.13-Stable-Full_Package]# ls
[root@www1 Joomla_1.5.13-Stable-Full_Package]# cp -avr * /var/www/html/

[root@www1 Joomla_1.5.13-Stable-Full_Package]# cd /var/www/html/
[root@www1 html]# ls
[root@www1 html]# cd ..
[root@www1 www]# ls
cgi-bin error html icons
[root@www1 www]# chown apache:apache html/ -R
[root@www1 www]#
[root@www1 www]# ls
cgi-bin error html icons
[root@www1 www]# cd html/
[root@www1 html]# ll
[root@www1 html]#

Now open internet explorer then open
http://10.0.0.30

Install Joomla follow the steps and give required information.

In Database section give

Host 10.0.0.190 IP use MySQL as database.
user root
passwdor redhat
database joomla

Must check install sample data.

Copy all the joomla code on www2

[root@www1 html]# scp -r * www2:/var/www/html/

We need to open this file and edit it on line 391 add index.php

[root@www1 html]#vim /etc/httpd/conf/httpd.conf

DirectoryIndex index.html index.html.var index.php

save & quit

[root@www1 /]#
[root@www1 ~]# scp /etc/httpd/conf/httpd.conf www2:/etc/httpd/conf/
httpd.conf 100% 33KB 32.9KB/s 00:00
[root@www1 ~]#
[root@www1 ~]# /etc/init.d/httpd restart
Stopping httpd: [ OK ]
Starting httpd: [ OK ]
[root@www1 ~]#

On Web Server 2
[root@www2 html]# chown apache:apache * -R
[root@www2 html]# ll
[root@www2 /]# yum install php php-mysql php-gd -y

[root@www2 ~]# /etc/init.d/httpd restart
Stopping httpd: [ OK ]
Starting httpd: [ OK ]
[root@www2 ~]#

Remeber that each machine(LVS+Real) must have default gw the ip of router connected to these servers

[root@www1 ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
10.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 eth0
0.0.0.0 10.0.0.20 0.0.0.0 UG 0 0 0 eth0
[root@www1 ~]#

Now you can test all the network by accessing web on http://10.0.0.3 or http://www.infoaddict.org/

[root@lb1 ~]# ipvsadm -L
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP www.infoaddict.org:ht rr
-> www2.infoaddict.org:h Route 1 0 0
-> www1.infoaddict.org:h Route 1 0 0
[root@lb1 ~]#

[root@lb1 ~]# watch ipvsadm -Lcn

Print Friendly
Tagged as: , , No Comments
18Feb/120

Configuration of DNS (Bind) server in chroot environment

Posted by Infoaddict

OS CentOS 5.4 X86_64
-------------------------------------
Please Install the bind packages
-------------------------------------
[root@ns1 ~]# yum install bind bind-utils bind-*
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * addons: virror.hanoilug.org
 * extras: ftp.hostrino.com
 * updates: ftp.hostrino.com
addons                                                                                                                                                     |  951 B     00:00
extras                                                                                                                                                     | 1.1 kB     00:00
ftp                                                                                                                                                        | 2.1 kB     00:00
updates                                                                                                                                                    | 1.9 kB     00:00
updates/primary_db                                                                                                                                         | 444 kB     00:00
Setting up Install Process
Package 30:bind-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-utils-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-sdb-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-chroot-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-devel-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-devel-9.3.6-4.P1.el5_4.1.i386 already installed and latest version
Package 30:bind-libs-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-libs-9.3.6-4.P1.el5_4.1.i386 already installed and latest version
Package 30:bind-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-utils-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-libbind-devel-9.3.6-4.P1.el5_4.1.x86_64 already installed and latest version
Package 30:bind-libbind-devel-9.3.6-4.P1.el5_4.1.i386 already installed and latest version
Nothing to do
----------------------------------------------
Please Configure Static IP and Default Gateway
----------------------------------------------
[root@ns1 ~]#  vi /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
IPADDR=192.168.150.100
NETMASK=255.255.255.0
ONBOOT=yes
HWADDR=00:16:36:73:7e:4f
wq!
[root@ns1 ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:16:36:73:7E:4F
          inet addr:192.168.150.100  Bcast:192.168.150.255  Mask:255.255.255.0
          inet6 addr: fe80::216:36ff:fe73:7e4f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1641 errors:0 dropped:0 overruns:0 frame:0
          TX packets:950 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:192907 (188.3 KiB)  TX bytes:117111 (114.3 KiB)
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:105 errors:0 dropped:0 overruns:0 frame:0
          TX packets:105 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:10213 (9.9 KiB)  TX bytes:10213 (9.9 KiB)
[root@ns1 ~]#
[root@ns1 ~]# vi /etc/sysconfig/network
NETWORKING=yes
NETWORKING_IPV6=no
HOSTNAME=dns.company.xy
GATEWAY=192.168.150.1
wq!
--------------------------------------------------------------------------------------------------------------------
Now we are going to configure the Bind service  please copy the files content and modify with your network settings
--------------------------------------------------------------------------------------------------------------------
[root@ns1 ~]#
[root@ns1 ~]# cd /var/named/chroot/
[root@ns1 chroot]# ll
total 24
drwxr-x---  2 root named 4096 Dec  1 00:00 dev
drwxr-x---  2 root named 4096 Jan  4 04:42 etc
dr-xr-xr-x 85 root root     0 Jan 11 22:41 proc
drwxr-x---  6 root named 4096 Dec  1 00:00 var
[root@ns1 chroot]#
-------------------------------
Now create zone file named.conf
-------------------------------
[root@ns1 chroot]#  vi etc/named.conf
options
{
        directory "/var/named"; // the default
        dump-file               "data/cache_dump.db";
        statistics-file         "data/named_stats.txt";
        memstatistics-file      "data/named_mem_stats.txt";
};
zone "." IN {
        type hint;
        file "named.root";
};
zone "localhost" IN {
        type master;
        file "localhost.fwd";
        allow-update { none; };
};
zone "0.0.127.in-addr.arpa" IN {
        type master;
        file "localhost.rev";
        allow-update { none; };
};
zone "company.xy" IN {
        type master;
        file "company.xy.fwd";
        allow-update { none; };
};
zone "1.168.192.in-addr.arpa" IN {
        type master;
        file "company.xy.rev";
        allow-update { none; };
};
 wq!
[root@ns1 chroot]# cd var/named
[root@ns1 named]#
--------------------------
Now create named.root file
--------------------------
[root@ns1 named]#
First We confiure named.root file for root dns
[root@ns1 named]# vi named.root
.                       6D  IN      NS      A.ROOT-SERVERS.NET.
.                       6D  IN      NS      B.ROOT-SERVERS.NET.
.                       6D  IN      NS      C.ROOT-SERVERS.NET.
.                       6D  IN      NS      D.ROOT-SERVERS.NET.
.                       6D  IN      NS      E.ROOT-SERVERS.NET.
.                       6D  IN      NS      F.ROOT-SERVERS.NET.
.                       6D  IN      NS      G.ROOT-SERVERS.NET.
.                       6D  IN      NS      H.ROOT-SERVERS.NET.
.                       6D  IN      NS      I.ROOT-SERVERS.NET.
.                       6D  IN      NS      J.ROOT-SERVERS.NET.
.                       6D  IN      NS      K.ROOT-SERVERS.NET.
.                       6D  IN      NS      L.ROOT-SERVERS.NET.
.                       6D  IN      NS      M.ROOT-SERVERS.NET.
A.ROOT-SERVERS.NET.     6D  IN      A       198.41.0.4
B.ROOT-SERVERS.NET.     6D  IN      A       192.228.79.201
C.ROOT-SERVERS.NET.     6D  IN      A       192.33.4.12
D.ROOT-SERVERS.NET.     6D  IN      A       128.8.10.90
E.ROOT-SERVERS.NET.     6D  IN      A       192.203.230.10
F.ROOT-SERVERS.NET.     6D  IN      A       192.5.5.241
G.ROOT-SERVERS.NET.     6D  IN      A       192.112.36.4
H.ROOT-SERVERS.NET.     6D  IN      A       128.63.2.53
I.ROOT-SERVERS.NET.     6D  IN      A       192.36.148.17
J.ROOT-SERVERS.NET.     6D  IN      A       192.58.128.30
K.ROOT-SERVERS.NET.     6D  IN      A       193.0.14.129
L.ROOT-SERVERS.NET.     6D  IN      A       199.7.83.42
M.ROOT-SERVERS.NET.     6D  IN      A       202.12.27.33
wq!
----------------------------------------------------------------------------------------------------------------------------------
Now create zone db files one by one  localhost.fwd and the localhost.rev are must then your network zone files forward and reverse
----------------------------------------------------------------------------------------------------------------------------------
[root@ns1 named]# vi localhost.fwd
$ORIGIN localhost.
$TTL    86400
@        IN     SOA     ns1.company.xy.  ns1.company.xy. (
                                20100104      ; Serial number
                                3H            ; Refresh     1 day
                                15M           ; Retry       2 hours
                                1W            ; Expire      41.67 days
                                1D  )         ; Minimum TTL 2 days
@       IN      NS      dns.company.xy.
localhost.              IN      A       127.0.0.1
wq!     ##### Save the file after copying the content from here. #####
[root@ns1 named]# vi localhost.rev
$ORIGIN 0.0.127.in-addr.arpa.
$TTL    86400
@        IN     SOA     ns1.company.xy.  ns1.company.xy. (
                                20100104      ; Serial number
                                3H            ; Refresh     1 day
                                15M           ; Retry       2 hours
                                1W            ; Expire      41.67 days
                                1D  )         ; Minimum TTL 2 days
@       IN      NS      ns1.company.xy.
1.0.0.127.in-addr.arpa. IN      PTR     localhost.
wq!
[root@ns1 named]# vi company.xy.fwd
$ORIGIN company.xy.
$TTL    86400
@        IN     SOA     ns1.company.xy.  ns1.company.xy. (
                                20100104      ; Serial number
                                3H            ; Refresh     1 day
                                15M           ; Retry       2 hours
                                1W            ; Expire      41.67 days
                                1D  )         ; Minimum TTL 2 days
@       IN      NS      ns1.company.xy.
ns1.company.xy.         IN      A       192.168.150.254
ftp.company.xy.         IN      A       192.168.150.101
www.company.xy.         IN      A       192.168.150.102
client3.company.xy.         IN      A       192.168.150.103
client4.company.xy.         IN      A       192.168.150.104
wq!
[root@ns1 named]# vi company.xy.rev
$ORIGIN 1.168.192.in-addr.arpa.
$TTL    86400
@        IN     SOA     ns1.company.xy.  root.company.xy. (
                                20100104      ; Serial number
                                3H            ; Refresh     1 day
                                15M           ; Retry       2 hours
                                1W            ; Expire      41.67 days
                                1D  )         ; Minimum TTL 2 days
@       IN      NS      ns1.company.xy.
254.150.168.192.in-addr.arpa.     IN      PTR     ns1.company.xy.
101.150.168.192.in-addr.arpa.     IN      PTR     ftp.company.xy.
102.150.168.192.in-addr.arpa.     IN      PTR     www.company.xy.
103.150.168.192.in-addr.arpa.     IN      PTR     client1.company.xy.
104.150.168.192.in-addr.arpa.     IN      PTR     clinet2.company.xy.
wq!
[root@ns1 ~]# vi /etc/resolv.conf
search company.xy
nameserver 192.168.150.254
wq!
-----------------------------------------------------------------
Configuration has been done now start "/etc/init.d/named" service
-----------------------------------------------------------------
[root@ns1 ~]# /etc/init.d/named start
Starting named:                                            [  OK  ]
[root@ns1 ~]# dig yahoo.com
; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_4.1 <<>> yahoo.com
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 46559
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 7, ADDITIONAL: 2
;; QUESTION SECTION:
;yahoo.com.                     IN      A
;; ANSWER SECTION:
yahoo.com.              21600   IN      A       209.191.93.53
yahoo.com.              21600   IN      A       69.147.114.224
yahoo.com.              21600   IN      A       209.131.36.159
;; AUTHORITY SECTION:
yahoo.com.              172800  IN      NS      ns1.yahoo.com.
yahoo.com.              172800  IN      NS      ns2.yahoo.com.
yahoo.com.              172800  IN      NS      ns3.yahoo.com.
yahoo.com.              172800  IN      NS      ns4.yahoo.com.
yahoo.com.              172800  IN      NS      ns5.yahoo.com.
yahoo.com.              172800  IN      NS      ns6.yahoo.com.
yahoo.com.              172800  IN      NS      ns8.yahoo.com.
;; ADDITIONAL SECTION:
ns6.yahoo.com.          172800  IN      A       202.43.223.170
ns8.yahoo.com.          172800  IN      A       202.165.104.22
;; Query time: 643 msec
;; SERVER: 192.168.150.100#53(192.168.150.100)
;; WHEN: Tue Jan 12 03:01:01 2010
;; MSG SIZE  rcvd: 233
[root@ns1 ~]#
--------------------------------------------------
Now please open ports for named server for network
--------------------------------------------------
[root@ns1 ~]# iptables -A INPUT -p tcp -m multiport --dport 53,953 -j ACCEPT
[root@ns1 ~]# iptables -A INPUT -p udp -m multiport --dport 53,953 -j ACCEPT
[root@ns1 ~]#
[root@ns1 ~]# /etc/init.d/iptables save
Saving firewall rules to /etc/sysconfig/iptables:          [  OK  ]
[root@ns1 ~]#
[root@ns1 ~]# dig ns1.company.xy
; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_4.1 <<>> ns1.company.xy
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 29732
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0
;; QUESTION SECTION:
;ns1.company.xy.            IN      A
;; ANSWER SECTION:
ns1.company.xy.     86400   IN      A       192.168.150.100
;; AUTHORITY SECTION:
company.xy.         86400   IN      NS      ns1.company.xy.
;; Query time: 1 msec
;; SERVER: 192.168.150.100#53(192.168.150.100)
;; WHEN: Tue Jan 12 03:13:33 2010
;; MSG SIZE  rcvd: 66
[root@ns1 ~]#
[root@ns1 ~]# dig www.company.xy
; <<>> DiG 9.3.6-P1-RedHat-9.3.6-4.P1.el5_4.1 <<>> www.company.xy
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10800
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 1
;; QUESTION SECTION:
;www.company.xy.            IN      A
;; ANSWER SECTION:
www.company.xy.     86400   IN      A       192.168.150.102
;; AUTHORITY SECTION:
company.xy.         86400   IN      NS      ns1.company.xy.
;; ADDITIONAL SECTION:
ns1.company.xy.     86400   IN      A       192.168.150.100
;; Query time: 1 msec
;; SERVER: 192.168.150.100#53(192.168.150.100)
;; WHEN: Tue Jan 12 03:14:09 2010
;; MSG SIZE  rcvd: 86
[root@ns1 ~]#
We have configured proper bind server on  CentOs 5.4
Note:Please install bind packages and then  copy the files text from this configuration  and paste to your server.
Also modify the settings as per your network machine names and their IP's.
Print Friendly
Tagged as: No Comments