sed 명령 오류 레이블이 너무 깁니다: Solaris에서

sed 명령 오류 레이블이 너무 깁니다: Solaris에서

데이터베이스 이름이 주어지거나 oltt206다음 XML에서 해당 합계를 추출 DB01하고 싶습니다 .usernamepasswordconnection string

wladmin@myremhost:/tmp$ cat /web/bea_apps/uat/Tomcat_Home_v9.0.56/TomcatNode01/conf/server.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8048" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!-- APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
          <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />

    <Resource auth="Container"
        driverClassName="oracle.jdbc.OracleDriver"
        global="dsspeedCanweb"
        name="dsspeedCanweb"
        password="O9jYL3yhwMF_Ep8P"
        username="VEL_CAN_WEB_USER"
        url="jdbc:oracle:thin:@host36db06v.mybank.com:1521:DB01"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        initialSize="15" maxTotal="150" maxActive="100" maxWaitMillis="10000" minIdle="15"
        accessToUnderlyingConnectionAllowed="true"
        minEvictableIdleTimeMillis="90000"
        logAbandoned="true" removeAbandoned="true" removeAbandonedTimeout="7200"
        removeAbandonedOnBorrow="true" removeAbandonedOnMaintenance="true"
        jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer;org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer;SlowQueryReport(threshold=600000,logFailed=true)"
        testWhileIdle="true"
        validationQuery="select 1 from dual"
        validationInterval="30000"
        testOnBorrow="true" />

    <Resource auth="Container"
        driverClassName="oracle.jdbc.OracleDriver"
        global="canwebds"
        name="canwebds"
        password="bbgwfxt2Os_2024"
        username="CANADA_WEB_USER"
        url="jdbc:oracle:thin:@host36DB06V.mybank.com:1521/oltt206"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        initialSize="15" maxTotal="150" maxActive="100" maxWaitMillis="10000" minIdle="15"
        accessToUnderlyingConnectionAllowed="true"
        minEvictableIdleTimeMillis="90000"
        logAbandoned="true" removeAbandoned="true" removeAbandonedTimeout="7200"
        removeAbandonedOnBorrow="true" removeAbandonedOnMaintenance="true"
        jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer;org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer;SlowQueryReport(threshold=600000,logFailed=true)"
        testOnBorrow="true" />

</GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="12408" address="uswl1212mrshm01.host35as28v.mybank.com" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="12409" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="12404" address="uswl1212mrshm01.host35as28v.mybank.com" protocol="AJP/1.3" redirectPort="12409" requiredSecret="QmtmM3hWcEVzUW5VTDNLdQo=" />

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="worker8">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
        Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className='org.apache.catalina.valves.ErrorReportValve'
                showServerInfo='false' />

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

솔라리스에서 다음 명령을 시도했지만 실패했습니다.

오류 출력:

wladmin@remhost:$ sed -n '/<Resource/{:a; N; /DB01/!ba; s/.*password="\([^"]*\)".*/\1/p}' /web/bea_apps/perf/Tomcat_Home_v9.0.56/TomcatNode01/conf/server.xml
Label too long: /<Resource/{:a; N; /DB01/!ba; s/.*password="\([^"]*\)".*/\1/p}

원하는 결과:

        O9jYL3yhwMF_Ep8P
        VEL_CAN_WEB_USER
        host36db06v.mybank.com:1521:DB01

나는 결국 ansible에 대한 해결책을 제시할 것입니다.

도와주세요.

답변1

비밀번호에 대한 코드는 다음과 같습니다.

나머지를 얻으려면 조정하십시오.

xmllint --xpath 'string(//Resource[@auth="Container" and contains(@url, ":DB01")]/@password)' file.xml

산출

O9jYL3yhwMF_Ep8P

표현은.

답변2

주제의 질문에 답하려면 다음 내용을 포함하세요.

/<Resource/{:a; N; /DB01/!ba; s/.*password="\([^"]*\)".*/\1/p}

sedsed레거시 구현(Solaris와 같은 70년대의 원래 구현에서 파생된 구현)을 사용하는 스크립트는 :a; N; /DB01/!ba; s/.*password="\([^"]*\)".*/\1/p}라는 분기 레이블을 정의(정의하려고 시도)합니다 a; N; /DB01/!ba; s/.*password="\([^"]*\)".*/\1/p}. 즉, 명령과 분리 ;되지 않고 명령의 일부입니다. 태그 이름. , 명령도 마찬가지입니다 .:Nbt

이는 POSIX에서도 요구되었으며 완화되었습니다(내 요청) 존재하다2016년 버전의 표준.

:따라서 , b뒤에는 같은 줄에 다른 명령이 올 수 없습니다 t.

GNU는 레이블 이름에 사용을 sed허용하지 않지만 POSIX에서 요구하는 파일 이름 뒤에는 여전히 사용을 허용합니다. 예를 들어, 명명된 이라고 씁니다 . 따라서 (and 및 ) 뒤에는 아무 것도 올 수 없습니다.;;wrs///ww file;dfile;d#}

호환되지 않거나 이식 가능하지 않은 스크립트의 또 다른 점은 앞에 }개행 문자를 추가하지 않는다는 것입니다 ;.

따라서 다음이 필요합니다.

sed -n '
  /<Resource/{
   :a; N; /DB01/!ba
   s/.*password="\([^"]*\)".*/\1/p
  }'

또는 행이 필요한 경우:

sed -n -e '/<Resource/{:a' -e 'N;/DB01/!ba' -e 's/.*password="\([^"]*\)".*/\1/p;}'

답변3

사용 xq(의 일부Andrei Kislyuk의 yq배포; JSON 파서 위에 구축된 파서 세트 ) 관련 섹션에서 올바른 URL을 jq일치시키는 데 사용되는 문자열을 전달합니다 .Resource

query_string=DB01

xq -r --arg query "$query_string" '
    .Server.GlobalNamingResources.Resource |
    map(select(."@auth" == "Container" and (."@url" // empty | endswith($query)))."@password")[]' file.xml

보시다시피 표현식의 핵심( jq및 속성을 기반으로 관련 항목 선택)은 다음 솔루션과 같습니다.Resourceauthurl자일스의 대답. 여기서 차이점은 jq도구( xq래퍼)가 이를 허용한다는 것입니다 --arg. 이는 쉘 데이터를 표현식에 주입하지 않고도 명령을 매개변수화할 수 있다는 것을 의미합니다.

또한 테스트 URL을 사용하기로 선택했으므로 endswith()사용자가 제공한 문자열이 일치해야 합니다.URL.

위 명령을 실행하면 문자열이 반환됩니다 O9jYL3yhwMF_Ep8P.


사용Mike Farah의 yq파서XML을 구문 분석하려면 다음과 같이 할 수 있습니다.

query=$query_string yq '
    .Server.GlobalNamingResources.Resource |
    map(select(."+@auth" == "Container" and ."+@url" == "*" + env(query))."+@password") | .[]' file.xml

여기서 차이점은 yq환경 변수를 통해 사용자 제공 값을 전달 query하고 표현식에서 패턴 일치를 수행한다는 것입니다.무늬). 또한 Mike는 yq약간 다른 XML 속성 형식(접두사 포함 +)을 사용한다는 점에 유의하세요.

관련 정보