Листенер oracle что это
This chapter describes the commands and associated syntax of the Listener Control utility. The terms "SQL*Net" and "Net Services" are used interchangeably throughout Oracle documentation and both these terms refer to the same functionality.
To perform basic management functions on one or more listeners, you can use the Listener Control utility commands. You can also view and change parameter settings.
The SET and SHOW commands enable you to alter and view listener configuration parameters.
The Listener Control utility can perform operations on a local or a remote listener.
Authentication for listener administration depends on whether you access the listener locally, or remotely.
Use the Listener Control utility commands to manage and configure listeners.
Режимы работы Листенера
В зависимости от конфигурации, описанной в listener.ora, служба Листенера может работать в трех различных режимах:
- Database – предоставляет удаленный доступ к конкретной базе. Этот режим является стандартным и потому более всего распространен.
- PLSExtProc – предоставляет доступ к командам операционной системы через процедуры PL/SQL.
- Executable – предоставляет удаленный доступ к командам операционной системы. Он позволяет продуктам Oracle, таким как, например, Oracle EBusiness Suite и Oracle Database общаться между собой через Листенер.
На рисунке ниже показан Листенер, сконфигурированный в двух режимах: Database и PLSExtProc. За подключение к СУБД отвечает сервис с именем «orcl9» (режим Database), за выполнение внешних процедур отвечает сервис PLSExtProс.
Мы же в следующей статье блога перейдем к очень интересному вопросу – атакам на службу Листенера. Применим пошаговую стратегию, начав со стандартных атак на незащищенную службу и постепенно переходя ко все более сложным вариантам атак, на защищенную службу Листенера. Большинство примеров будет работать как старой версии СУБД Oracle 8i, которая, тем не менее, до сих пор (. ) встречается в корпоративных сетях, так и на самый распространенный на данный момент версии 11g.
Oracle Net Listener is a separate process that runs on the database server. It receives incoming client connection requests and manages the traffic of these requests to the database server. Find out how to configure the listener to accept client connections.
In Oracle Database 12 c release 2 (12.2), the listener password feature is no longer supported. This does not cause a loss of security because authentication is enforced through local operating system authentication.
Identifying and Accessing the Database for a description of how the listener is used during an initial connection request
Understanding the Communication Layers for an architectural overview of the listener
1.4 Oracle Net Listener Security
Local listener administration is secure through local operating system authentication, which restricts listener administration to the user who started the listener or to the super user. By default, remote listener administration is disabled.
Oracle recommends that you perform listener administration in the default mode, and access the system remotely using a remote login. When you administer the listener remotely, use Oracle Enterprise Manager Cloud Control or Secure Shell (SSH) to access the remote host.
Сетевая служба TNS Listener – достаточно мощный инструмент, почти полностью контролирующий доступ к СУБД и предоставляющий возможность доступа к командам ОС. Листенер состоит из двух исполняемых и нескольких конфигурационных файлов.
Исполняемые файлы tnslsnr и lsnrctl расположены в директории $ORACLE_HOME/bin (переменная $ORACLE_HOME отображает путь к директории, в которую установлена СУБД). Конфигурационные файлы расположены в директории $ORACLE_HOME/network/admin. Рассмотрим подробнее назначение этих файлов.
Sqlnet.ora
Этот конфигурационный файл отвечает за сетевые настройки Листенера. В нем нас прежде всего интересуют опции, связанные с безопасностью, - это на стройки шифрования передачи данных, аутентификации и разграничения прав доступа к Листенеру по IP-адресам (Valid Node Checking).
Listener.ora
Этот конфигурационный файл отвечает за связь Листенера с СУБД. Для нас важнейшим моментом является хранимая в нем строка подключения, которая со держит такие параметры подключения, как системный идентификатор (SID) и порт, на который будут приниматься запросы для данного SID. Как будет ясно в дальнейшем, эта информация является во многом определяющей при проведении начального этапа проникновения в СУБД Oracle. Этот файл очень важен для нас – получив к нему доступ с возможностью внесения модификаций, мы сможем обойти такие ограничения безопасности, как пароль на службу Листенера и протоколирование событий. Пример конфигурационного файла:
Здесь мы видим, что на хосте с именем Ora, на порту 1521 запущен экземпляр базы данных. Кроме того, в этом файле могут храниться такие параметры, как пароль на доступ к Листенеру, директория хранения логфайлов и пр. Изменения в конфигурации Листенера могут быть сделаны напрямую путем правки файла listener.ora или с использованием командного интерфейса утилиты lsnrctl.
Установка пароля для Oracle Listener
При первоначальной установке Listener утилита не имеет никакой защиты паролем. Любой пользователь, имеющий доступ к операционной системе, без труда может остановить Listener Oracle и воспрепятствовать клиентам подключаться, просто введя команду lsnrctl stop в командной строке.
На заметку! Установленный по умолчанию пароль службы слушателя — listener, и при использовании Listener этот пароль указывать не нужно.
Собственный пароль для утилиты Listener Oracle можно установить, как показано в листинге ниже.
После того как пароль успешно изменен, службу Listener нельзя будет останавливать или запускать как раньше — для этого придется ввести пароль пользователя. Для указания листенеру Оракл нового пароля необходимо использовать выражение set password в приглашении утилиты lsnrctl, после чего можно еще раз запустить или остановить службу Oracle Net Listener. Обратите внимание, что выражение set password не устанавливает новый пароль, а просто вынуждает слушателя запрашивать пароль для выполнения административных задач.
Результат неудачной попытки остановки Listener вследствие отсутствия предоставленного пароля показан в листинге ниже. Затем листенер был корректно остановлен посредством применения команды set password.
This chapter describes the commands and associated syntax of the Listener Control utility .
The terms "SQL*Net" and "Net Services" are used interchangeably throughout Oracle documentation and both these terms refer to the same functionality.
This chapter contains the following topics:
Установка размера очереди
Иногда большое количество одновременных запросов на подключение со стороны клиентов могут перегрузить службу слушателя. Чтобы уберечь Listener от сбоя, можно использовать параметр QUEUESIZE в файле конфигурации listener.ora для указания допустимого количества параллельно выполняющихся запросов на подключение.
Для большинства операционных систем значение параметра QUEUESIZE — достаточно небольшое число, наподобие 5. Ниже приведен пример установки параметра QUEUESIZE:
Несколько TNS Listener
На одном сервере могут действовать более одной службы Listener NET Oracle, но обычно такую конфигурацию придется применять в Oracle RAC. При использовании нескольких служб слушателя можно конфигурировать параметр CONNECT_TIME_FAILOVER, который определяет длительность ожидания клиентом подключения через одного Listener, прежде чем будет предпринята попытка подключения с помощью другого Listener Oracle.
1.1 Listener Control Utility Overview
The Listener Control utility enables you to administer listeners . To perform basic management functions on one or more listeners, you can use the Listener Control utility commands. You can also view and change parameter settings.
The basic syntax of Listener Control utility commands is as follows:
In the preceding command, listener_name is the name of the listener that you want to administer. If you do not specify a specific listener in the command string, then the command is directed to the default listener name, LISTENER .
You can also issue Listener Control utility commands at the LSNRCTL> program prompt. To obtain the prompt, enter lsnrctl with no arguments at the operating system command line. When you run lsnrctl , the program is started. You can then enter the necessary commands from the program prompt. The basic syntax of issuing commands from LSNRCTL> program prompt is as follows:
You can combine commands in a standard text file, and then run them as a sequence of commands. To run in batch mode, use the following format:
For most commands, the Listener Control utility establishes an Oracle Net connection with the listener that is used to transmit the command. To initiate an Oracle Net connection to the listener, the Listener Control utility must obtain the protocol addresses for the named listener or a listener named LISTENER . This is done by resolving the listener name with one of the following mechanisms:
listener.ora file in the directory specified by the TNS_ADMIN environment variable.
listener.ora file in the ORACLE_HOME /network/admin directory.
Naming method; for example, a tnsnames.ora file.
If none of the preceding mechanisms resolve the listener name, then the Listener Control utility uses the default listener name LISTENER , resolves the host name IP address, and uses port 1521.
Листенер (слушатель) Oracle Net Listener — служба, которая действует только на сервере и прослушивает входящие запросы на подключение. Oracle предоставляет утилиту lsnrctl, управляющую процессом листенера. Место слушателя в сетевой обработке Oracle можно кратко описать следующим образом.
- С помощью TNS Listener Oracle база данных регистрирует информацию о службах, экземплярах и обработчиках служб.
- Клиент устанавливает начальное соединение со слушателем.
- Слушатель принимает и проверяет запрос на подключение клиента и передает его обработчику службы базы данных. Как только слушатель передает запрос клиента, он устраняется из процесса обслуживания данного подключения.
Файл listener.ora, который по умолчанию размещается в каталоге $ORACLE_HOME/network/admin в системах UNIX и в каталоге $ORACLE_HOME\network\admin в системах Windows, содержит информацию о конфигурации Listener Oracle. Поскольку служба слушателя действует только на сервере, клиентские компьютеры не содержат никакого файла listener.ora. Типичный файл listener.ora приведен в листинге ниже.
Все параметры конфигурации в этом файле имеют значения по умолчанию. Поэтому службу листенера не обязательно конфигурировать вручную. После создания первой базы данных на сервере служба TNS Listener Oracle автоматически запускается, и файл конфигурации слушателя, listener.ora, помещается в каталог, определенный по умолчанию. При создании новой базы данных ее информация о сетевых подключений и службах автоматически добавляется в файл конфигурации tns listener Oracle. При запуске экземпляра база данных автоматически регистрируется в слушателе, и слушатель начинает прослушивать запросы на подключение к этой базе данных.
Процесс PMON Oracle отвечает за динамическую регистрацию имен служб баз данных Oracle в листенере (Listener) — при создании новые базы данных Oracle будут автоматически регистрироваться в службе TNS Listener Oracle. Процесс PMON будет обновлять файл listener.ora после создания каждой базы данных на сервере.
Для обеспечения возможности автоматической регистрации файл init.ora или SPFILE должен содержать следующие параметры:
Если значение параметра SERVICE_NAMES не указано, по умолчанию ему присваивается значение глобального имени базы данных, являющееся сочетанием параметров DB_NAME и DB_DOMAIN. Значение параметра INSTANCE_NAME, устанавливаемое по умолчанию — идентификатор SID, введенный во время установки Oracle или создания базы данных.
Состояние листенера на сервере можно проверить с помощью утилиты lsnrctl, как показано в листинге ниже. Вывод показывает длительность работы Listener Oracle и размещение файла конфигурации службы слушателя. Он содержит также имена баз данных, которые слушатель “прослушивает” на предмет запросов на подключение.
Состояние в разделе Services Summary (Сводка по службам) листинга выше может принимать одно из следующих значений:
Команды TNS Listener Oracle
После вызова утилиты lsnrctl помимо status можно выполнять и другие важные команды. Например, команда services позволяет выяснить, какие службы слушатель отслеживает на предмет запросов на подключение.
На заметку! Состояние службы листенера можно проверить из страницы Net Services Administration (Администрирование сетевых служб) в Oracle Enterprise Manager.
Ознакомиться с доступными командами утилиты lsnrctl можно с помощью команды help, введенной в интерфейсе lsnrctl, как показано в листинге ниже.
После вызова утилиты lsnrctl запуск Listener можно осуществить с помощью команды start, а его остановку — с помощью команды stop. Если эти команды требуется выдать из командной строки операционной системы, можно использовать команды lsnrctl start и lsnrctl stop.
При внесении изменений в файл listener.ora единственный способ ввода этих изменений в действие — перезапуск слушателя. Другой, более безопасный способ — просто перезагрузка информации Listener, в результате чего последние выполненные изменения слушателя будут внесены в файл конфигурации. Команда lsnrctl reload позволяет перезагрузить TNS Listener Oracle “на лету”, без его перезапуска. Подключенные в текущий момент клиенты останутся подключенными во время перезагрузки Listener (или даже при его перезапуске), поскольку слушатель уже “отдал” подключения базе данных и не участвует в обмене данными между клиентом и службой базы данных.
Внимание! Изменять файл listener.ora не рекомендуется, если только для этого не существует веской причины. Кроме того, при использовании динамической автоматической регистрации служб необходимость в модификации файла возникает значительно реже. Тем не менее, в некоторых случаях приходится изменять определенную часть файла Listener, содержащую информацию о конфигурации сети для всех служб, которые слушатель отслеживает на предмет запросов подключения.
Управление Listener
Хотя установка службы Listener Oracle достаточно проста, после ее выполнения можно предпринять ряд действий для более точной настройки процесса подключения и для обеспечения безопасности службы TNS Listener Oracle. Некоторые из этих параметров описаны в последующих разделах.
Tnsnames.ora
В этом файле хранится соответствие кратких имен (Net Service Names) длинным дескрипторам соединений для упрощения межсетевого взаимодействия. Нам это файл интересен тем, что в нем может находиться информация о SSL-сертификатах, используемых для аутентификации. В нем также могут храниться данные для подключения к другим серверам СУБД, в том числе и SID. Пример одной записи из файла Tnsnames.ora:
Здесь мы видим, что на хосте с IPадресом 192.168.40.14 на порту 1521 запущена служба Листенера. У базы данных, установленной на этом сервере, SID равно ORCL102.
9.2 Configuring Dynamic Service Registration
Service registration allows processes, such as an Oracle database, to identify their available services to the listener, which then acts as a port mapper for those services. The listener uses the dynamic service information about the database and instance received through service registration.
Dynamic service registration is configured in the database initialization file. It does not require any configuration in the listener.ora file. However, listener configuration must be set to listen on the ports named in the database initialization file, and must not have parameters set that prevent automatic registration, such as COST parameters.
This section contains the following configuration topics related to service registration:
9.2.1 Setting Initialization Parameters for Service Registration
To ensure service registration works properly, the initialization parameter file should contain the following parameters:
SERVICE_NAMES for the database service name
INSTANCE_NAME for the instance name
LOCAL_LISTENER for the local listener
REMOTE_LISTENER for the remote listener, if any
FORWARD_LISTENER for the forward listener
The value for the SERVICE_NAMES parameter defaults to the global database name , a name comprising the DB_NAME and DB_DOMAIN parameters in the initialization parameter file. The value for the INSTANCE_NAME parameter defaults to the Oracle system identifier (SID).
Starting with Oracle Database 19c, customer use of the SERVICE_NAMES parameter is deprecated. To manage your services, Oracle recommends that you use the SRVCTL or GDSCTL command line utilities, or the DBMS_SERVICE package.
Oracle Database Reference for additional information about the SERVICE_NAMES and INSTANCE_NAME parameters
9.2.2 Registering Information with a Local Listener
By default, the LREG process registers service information with its local listener on the default local address of TCP/IP, port 1521. If the listener configuration is synchronized with the database configuration, then LREG can register service information with a nondefault local listener or a remote listener on another node. Synchronization occurs when the protocol address of the listener is specified in the listener.ora file and the location of the listener is specified in the initialization parameter file.
To have the LREG process register with a local listener that does not use TCP/IP, port 1521, configure the LOCAL_LISTENER parameter in the initialization parameter file to locate the local listener.
For a shared server environment, you can use the LISTENER attribute of the DISPATCHERS parameter in the initialization parameter file to register the dispatchers with a nondefault local listener. Because the LOCAL_LISTENER parameter and the LISTENER attribute enable LREG to register dispatcher information with the listener, it is not necessary to specify both the parameter and the attribute if the listener values are the same.
LOCAL_LISTENER is a comma-delimited list parameter. If a comma appears in the string, then the entire string must be enclosed in double quotation marks. Set the LOCAL_LISTENER parameter as follows:
For example, if the listener address "ab,cd" is entered, then it resolves to one listener address. If the address is entered as ab,cd , then it resolves to two listener addresses, ab and cd .
For shared server connections, set the LISTENER attribute as follows:
In the preceding command, listener_address is resolved to the listener protocol addresses through a naming method, such as a tnsnames.ora file on the database server.
To dynamically update the LOCAL_LISTENER parameter, use the SQL statement ALTER SYSTEM as follows:
If you set the parameter to null using the following statement, then the default local address of TCP/IP, port 1521 is assumed:
The LISTENER attribute overrides the LOCAL_LISTENER parameter. As a result, the SQL statement ALTER SYSTEM SET LOCAL_LISTENER does not affect the setting of this attribute.
In Example 9-1, a database resides on host sales1-server . The listener on this host is named listener_sales1 and is configured to listen on port 1421 instead of port 1521.
Example 9-1 Registering a Local Listener in a Dedicated Server Environment
On the host where the local listener resides, configure the listener.ora file with the protocol address of the listener using Oracle Net Manager.
On the database, set the LOCAL_LISTENER parameter in the database initialization parameter file to the alias of the local listener. For example:
If the database is configured for shared server connections, then you could set the LISTENER attribute as follows:
Resolve the listener name alias for the LOCAL_LISTENER setting through a tnsnames.ora file on the database host using a text editor, as follows:
If you are registering a local listener and use Oracle Connection Manager, then do not include (DESCRIPTION = or its closing parenthesis.
A network service name entry can be created for the protocol address without the CONNECT_DATA section of the connect descriptor.
See Oracle Database SQL Reference for additional information about the ALTER SYSTEM statement.
9.2.3 Registering Information with a Remote Listener
A remote listener is a listener residing on one computer that redirects connections to a database instance on another computer. Remote listeners are typically used in an Oracle Real Application Clusters (Oracle RAC) environment. You can configure registration to remote listeners, such as with Oracle RAC, for dedicated or shared server environments.
In a dedicated server environment, you must enable the LREG background process to register with a remote listener. You do this by configuring the REMOTE_LISTENER parameter, which is a comma-delimited list parameter, in the initialization parameter file. The syntax of REMOTE_LISTENER is as follows:
In the preceding command, listener_address is resolved to the listener protocol addresses through a naming method such as a tnsnames.ora file on the database host. If a comma appears in the listener address, then the entire string must be enclosed in quotation marks.
In a shared server environment, you can use the same registration technique as for a dedicated server environment. Alternatively, you can set the LISTENER attribute of the DISPATCHERS parameter in the initialization parameter file to register the dispatchers with any listener. The syntax of the LISTENER attribute is as follows:
The LISTENER attribute overrides the REMOTE_LISTENER initialization parameter. Because the REMOTE_LISTENER initialization parameter and the LISTENER attribute enable LREG to register dispatcher information with the listener, you do not need specify both the parameter and the attribute if the listener values are the same.
For example, assume that a remote listener named listener-sales2 listens on port 1521 on host sales2-server , and a database resides on host sales1-server . You want the listener on sales2-server to redirect connection requests to this database. Figure 9-1 illustrates this scenario.
Figure 9-1 Remote Listener
Oracle Database SQL Reference for additional information about the ALTER SYSTEM SET statement
Example 9-2 shows how to register a remote listener in a dedicated server environment. In the example, the remote listener is sales2-server .
Example 9-2 Registering a Remote Listener in a Dedicated Server Environment
On the host where the remote listener resides, use Oracle Net Manager to configure the listener.ora file with the protocol addresses of the remote listener.
On the database to which you want requests to be redirected, set the REMOTE_LISTENER parameter in the database initialization parameter file to the alias of the remote listener, for example:
For shared server connections, set the DISPATCHER parameter in the initialization file for the database on host sales1-server as follows:
To statically update the REMOTE_LISTENER initialization parameter, use a text editor to de-register the information with the remote listener which it had previously registered information.
Resolve the listener name alias for the remote listener through a tnsnames.ora file on the database host. For example:
Oracle Database Reference to learn about the REMOTE_LISTENER initialization parameter
Oracle Real Application Clusters Administration and Deployment Guide to learn how to configure remote listeners (also called SCAN listeners) in an Oracle RAC environment
9.2.4 Registering Information with All Listeners in a Network
A network may contain multiple local and remote listeners. By default, all listeners are cross-registered with each other. By specifying a set of listeners in the LISTENER_NETWORKS initialization parameter, you can designate a subset of local listeners with a subset of remote listeners. Listeners specified by the LISTENER_NETWORKS parameter should not be specified by the LOCAL_LISTENER and REMOTE_LISTENER parameters.
The syntax of LISTENER_NETWORKS parameter is as follows:
In the preceding syntax, listener_address is resolved according to the rules of LOCAL_LISTENER and REMOTE_LISTENER.
Example 9-3 Using Two Networks on a Subnet
Assume there are two distinct networks, network1 and network2 . On network1 , there is a local listener named local1 , and a remote listener named remote1 . On network2 , there is a local listener named local2 , and a remote listener named remote2 . The following syntax sets up registration so that the listeners only redirect connections to listeners on the same network.
In the preceding example, local1 is registered only with remote1 , and remote1 only redirects connections to local1 . The listener local2 is registered only with remote2 , and remote2 only redirects connections to local2 .
Example 9-4 Configuring Multiple Listeners
Assume that multiple listeners are listening on a network named sales-network . The following conditions are true:
A database configured for dedicated server connections resides on host sales1-server . It is the only database in the network.
A local listener resides on sales1-server and listens on nondefault port 1421.
A remote listener named resides on host sales2-server and listens on port 1521.
Another remote listener resides on host sales3-server and listens on port 1521.
The following procedure describes how to register information with all listeners in a dedicated server environment:
On the hosts where the remote listeners reside (in this example, sales2-server and sales3-server ), configure the listener.ora file with the protocol addresses of the remote listener.
On the database to which you want requests to be redirected, set the REMOTE_LISTENER parameter in the database initialization parameter file to the alias of the remote listeners, and the LOCAL_LISTENER parameter to the alias of the local listener.
Set the parameters in the initialization file for the database on host sales1-server as follows:
Resolve the listener name alias for the LOCAL_LISTENER and REMOTE_LISTENER setting through a tnsnames.ora file on the database host.
In the tnsnames.ora on sales1-server , resolve the local listener alias and remote listener aliases listener_sales1 , listener_sales2 , and listener_sales3 as follows:
Tnslsnr
Сердце Листенера, отвечающее за весь основной функционал службы, – процесс tnslsnr, который выполняет роль прокси-сервера и перенаправляет запросы от клиента непосредственно к СУБД. Процесс tnslsnr по умолчанию запускается с привилегиями пользователя Oracle в ОС UNIX и с привилегиями пользователя
Local System в ОС Windows NT/2000/2003. Так как учетная запись «oracle», создаваемая при установке СУБД на UNIX-системах, не имеет административных привилегий, риск поставить под угрозу весь сервер при компрометации Листенера в UNIXсистемах по умолчанию ниже.
1.1 Listener Control Utility Overview
The Listener Control utility enables you to administer listeners .You can use its commands to perform basic management functions on one or more listeners. Additionally, you can view and change parameter settings.
The basic syntax of Listener Control utility commands is as follows:
In the preceding command, listener_name is the name of the listener to be administered. If no name is specified, then the default name, LISTENER , is assumed.
You can also issue Listener Control utility commands at the LSNRCTL> program prompt. To obtain the prompt, enter lsnrctl with no arguments at the operating system command line. When you run lsnrctl , the program is started. You can then enter the necessary commands from the program prompt. The basic syntax of issuing commands from LSNRCTL> program prompt is as follows:
You can combine commands in a standard text file, and then run them as a sequence of commands. To run in batch mode, use the format:
For most commands, the Listener Control utility establishes an Oracle Net connection with the listener that is used to transmit the command. To initiate an Oracle Net connection to the listener, the Listener Control utility must obtain the protocol addresses for the named listener or a listener named LISTENER . This is done by resolving the listener name with one of the following mechanisms:
listener.ora file in the directory specified by the TNS_ADMIN environment variable
listener.ora file in the ORACLE_HOME/network/admin directory
Naming method, for example, a tnsnames.ora file
If none of the preceding mechanisms resolve the listener name, then the Listener Control utility uses the default listener name LISTENER , resolves the host name IP address, and uses port 1521.
The Listener Control utility supports the following types of commands:
Operational commands, such as START, and STOP.
Modifier commands, such as SET TRC_LEVEL.
Informational commands, such as STATUS and SHOW LOG_FILE.
9.1 Overview of Oracle Net Listener
The release of the listener must be the same as or later than the latest release of all Oracle databases being serviced through the listener.
A listener is configured with one or more listening protocol addresses, information about supported services, and parameters that control its runtime behavior. The listener configuration is stored in a configuration file named listener.ora .
Because the configuration parameters have default values, it is possible to start and use a listener with no configuration. This default listener has a name of LISTENER , supports no services on startup, and listens on the following TCP/IP protocol address:
The listener forwards client requests to supported services. These services are dynamically registered with the listener. This dynamic registration feature is called service registration . The registration is performed by the Listener Registration (LREG) process. Dynamic service registration does not require any manual configuration in the listener.ora file.
Service registration offers the following benefits:
Because the listener always monitors the state of the instances, service registration facilitates automatic failover of a client connect request to a different instance if one instance is down.
Connection load balancing
Service registration enables the listener to forward client connect requests to the least-loaded instance and dispatcher or dedicated server . Service registration balances the load across the service handler s and nodes.
High-availability for Oracle Real Application Clusters and Oracle Data Guard
1.3 Distributed Operations
The Listener Control utility can perform operations on a local or a remote listener.
The following procedure describes how to set up a computer to remotely administer a listener:
Ensure that the Listener Control utility ( lsnrctl ) executable is installed in the ORACLE_HOME/bin directory.
Ensure that the name of the listener to administer can be resolved through a listener.ora file or a naming method, as described in "Listener Control Utility Overview" .
All commands except START can be issued when a listener is administered remotely. The Listener Control utility can only start the listener on the same computer from where the utility is running.
When issuing commands, specify the listener name as an argument. For example:
If the name is omitted, then listener name set with the SET CURRENT_LISTENER command is used, or the default name, LISTENER is assumed.
Lsnrctl
Lsnrctl является консольной утилитой, используемой для администрирования Листенера. С ее помощью можно управлять Листенером как локально, так и удаленно. Команды управления включают в себя возможность настройки протоколирования событий, смены пароля или удаленного перезапуска Листенера.
1.1 Listener Control Utility Overview
The Listener Control utility enables you to administer listeners . To perform basic management functions on one or more listeners, you can use the Listener Control utility commands. You can also view and change parameter settings.
The basic syntax of Listener Control utility commands is as follows:
In the preceding command, listener_name is the name of the listener that you want to administer. If you do not specify a specific listener in the command string, then the command is directed to the default listener name, LISTENER .
You can also issue Listener Control utility commands at the LSNRCTL> program prompt. To obtain the prompt, enter lsnrctl with no arguments at the operating system command line. When you run lsnrctl , the program is started. You can then enter the necessary commands from the program prompt. The basic syntax of issuing commands from LSNRCTL> program prompt is as follows:
You can combine commands in a standard text file, and then run them as a sequence of commands. To run in batch mode, use the following format:
For most commands, the Listener Control utility establishes an Oracle Net connection with the listener that is used to transmit the command. To initiate an Oracle Net connection to the listener, the Listener Control utility must obtain the protocol addresses for the named listener or a listener named LISTENER . This is done by resolving the listener name with one of the following mechanisms:
listener.ora file in the directory specified by the TNS_ADMIN environment variable.
listener.ora file in the ORACLE_HOME /network/admin directory.
Naming method; for example, a tnsnames.ora file.
If none of the preceding mechanisms resolve the listener name, then the Listener Control utility uses the default listener name LISTENER , resolves the host name IP address, and uses port 1521.
Листенер (слушатель) Oracle Net Listener — служба, которая действует только на сервере и прослушивает входящие запросы на подключение. Oracle предоставляет утилиту lsnrctl, управляющую процессом листенера. Место слушателя в сетевой обработке Oracle можно кратко описать следующим образом.
- С помощью TNS Listener Oracle база данных регистрирует информацию о службах, экземплярах и обработчиках служб.
- Клиент устанавливает начальное соединение со слушателем.
- Слушатель принимает и проверяет запрос на подключение клиента и передает его обработчику службы базы данных. Как только слушатель передает запрос клиента, он устраняется из процесса обслуживания данного подключения.
Файл listener.ora, который по умолчанию размещается в каталоге $ORACLE_HOME/network/admin в системах UNIX и в каталоге $ORACLE_HOME\network\admin в системах Windows, содержит информацию о конфигурации Listener Oracle. Поскольку служба слушателя действует только на сервере, клиентские компьютеры не содержат никакого файла listener.ora. Типичный файл listener.ora приведен в листинге ниже.
Все параметры конфигурации в этом файле имеют значения по умолчанию. Поэтому службу листенера не обязательно конфигурировать вручную. После создания первой базы данных на сервере служба TNS Listener Oracle автоматически запускается, и файл конфигурации слушателя, listener.ora, помещается в каталог, определенный по умолчанию. При создании новой базы данных ее информация о сетевых подключений и службах автоматически добавляется в файл конфигурации tns listener Oracle. При запуске экземпляра база данных автоматически регистрируется в слушателе, и слушатель начинает прослушивать запросы на подключение к этой базе данных.
Процесс PMON Oracle отвечает за динамическую регистрацию имен служб баз данных Oracle в листенере (Listener) — при создании новые базы данных Oracle будут автоматически регистрироваться в службе TNS Listener Oracle. Процесс PMON будет обновлять файл listener.ora после создания каждой базы данных на сервере.
Для обеспечения возможности автоматической регистрации файл init.ora или SPFILE должен содержать следующие параметры:
Если значение параметра SERVICE_NAMES не указано, по умолчанию ему присваивается значение глобального имени базы данных, являющееся сочетанием параметров DB_NAME и DB_DOMAIN. Значение параметра INSTANCE_NAME, устанавливаемое по умолчанию — идентификатор SID, введенный во время установки Oracle или создания базы данных.
Состояние листенера на сервере можно проверить с помощью утилиты lsnrctl, как показано в листинге ниже. Вывод показывает длительность работы Listener Oracle и размещение файла конфигурации службы слушателя. Он содержит также имена баз данных, которые слушатель “прослушивает” на предмет запросов на подключение.
Состояние в разделе Services Summary (Сводка по службам) листинга выше может принимать одно из следующих значений:
1.2 SET and SHOW Commands of the Listener Control utility
You can use the SET command to alter parameter values for a specified listener. You set the name of the listener to administer using the SET CURRENT_LISTENER command. Parameter values remain in effect until the listener is shut down. If you want these settings to persist, then use the SAVE_CONFIG command to save changes to the listener.ora .
You can use the SHOW command to display the current value of a configuration setting.
Читайте также: