AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / unix / Perguntas / 783284
Accepted
hanjo
hanjo
Asked: 2024-09-10 22:13:35 +0800 CST2024-09-10 22:13:35 +0800 CST 2024-09-10 22:13:35 +0800 CST

jq - endereço ip mostrar em formato tabular

  • 772

Gostaria de imprimir os endereços IP e mostrar a saída em formato tabular, incluindo todos os metadados, como valid_lft, temporary, etc.

Descobri que isso ip -j addr show eth0está me dando o JSON que preciso. Se eu executar, ip -j addr show eth0 | jq -r '.[0].addr_info'os dados já estarão filtrados para o que estou interessado:

[
  {
    "family": "inet",
    "local": "192.168.x.y",
    "prefixlen": 24,
    "broadcast": "192.168.1.255",
    "scope": "global",
    "dynamic": true,
    "noprefixroute": true,
    "label": "eth0",
    "valid_life_time": 2339,
    "preferred_life_time": 2339
  },
  {
    "family": "inet6",
    "local": "2003:mm:nn:pp:ww:xx:yy:zz",
    "prefixlen": 64,
    "scope": "global",
    "temporary": true,
    "dynamic": true,
    "valid_life_time": 14342,
    "preferred_life_time": 1742
  },
  {
    "family": "inet6",
    "local": "2003:mm:nn:pp:qq:rr:ss:tt",
    "prefixlen": 64,
    "scope": "global",
    "dynamic": true,
    "mngtmpaddr": true,
    "noprefixroute": true,
    "valid_life_time": 14342,
    "preferred_life_time": 1742
  },
  {
    "family": "inet6",
    "local": "fd4e:gg:hh:ii:jj:kk:ll:mm",
    "prefixlen": 64,
    "scope": "global",
    "temporary": true,
    "dynamic": true,
    "valid_life_time": 14342,
    "preferred_life_time": 1742
  },
  {
    "family": "inet6",
    "local": "fd4e:gg:hh:ii:qq:rr:ss:tt",
    "prefixlen": 64,
    "scope": "global",
    "dynamic": true,
    "mngtmpaddr": true,
    "noprefixroute": true,
    "valid_life_time": 14342,
    "preferred_life_time": 1742
  },
  {
    "family": "inet6",
    "local": "fe80::qq:rr:ss:tt",
    "prefixlen": 64,
    "scope": "link",
    "noprefixroute": true,
    "valid_life_time": 4294967295,
    "preferred_life_time": 4294967295
  }
]

Eu sei que posso usar @tsvpara obter um formato de tabela e acomodar diferentes comprimentos de valores para os quais posso canalizar column -ts $'\t'.

O que não consigo descobrir é como posso iterar por todos os objetos e extrair as chaves primeiro, porque se eu não fizer isso, os valores de saída estarão em colunas incorretas, com base em quais chaves cada objeto tem (ou melhor, não tem). Já consegui extrair as chaves usando

$ ip -j addr show eth0 | jq -r '[.[0].addr_info | .[] | keys_unsorted[]] | reduce .[] as $a ([]; if IN(.[]; $a) then . else . += [$a] end)'
[
  "family",
  "local",
  "prefixlen",
  "broadcast",
  "scope",
  "dynamic",
  "noprefixroute",
  "label",
  "valid_life_time",
  "preferred_life_time",
  "temporary",
  "mngtmpaddr"
]

Agora não sei como combinar tudo isso.

Essencialmente, o seguinte está produzindo o resultado desejado, mas não gosto, porque os cabeçalhos/chaves são definidos manualmente:

$ ip -j addr show eth0 | jq -r '(["Family", "Local", "Prefixlen", "Broadcast", "Scope", "Dynamic", "Noprefixroute", "Label", "Valid_Life_Time", "Preferred_Life_Time", "Temporary", "Deprecated", "Mngtmpaddr"] | (., map(length*"-"))), (.[0].addr_info | .[] | [ .family, .local, .prefixlen, .broadcast, .scope, .dynamic, .noprefixroute, .label, .valid_life_time, .preferred_life_time, .temporary, .deprecated, .mngtmpaddr ] | map(.//"-")) | @tsv' | column -ts $'\t'
Family  Local                                  Prefixlen  Broadcast      Scope   Dynamic  Noprefixroute  Label  Valid_Life_Time  Preferred_Life_Time  Temporary  Deprecated  Mngtmpaddr
------  -----                                  ---------  ---------      -----   -------  -------------  -----  ---------------  -------------------  ---------  ----------  ----------
inet    192.168.x.y                            24         192.168.1.255  global  true     true           eth0   1917             1917                 -          -           -
inet6   2003:mm:nn:pp:ww:xx:yy:zz              64         -              global  true     -              -      14348            1748                 true       -           -
inet6   2003:mm:nn:pp:qq:rr:ss:tt              64         -              global  true     true           -      14348            1748                 -          -           true
inet6   fd4e:gg:hh:ii:jj:kk:ll:mm              64         -              global  true     -              -      14348            1748                 true       -           -
inet6   fd4e:gg:hh:ii:qq:rr:ss:tt              64         -              global  true     true           -      14348            1748                 -          -           true
inet6   fe80::qq:rr:ss:tt                      64         -              link    -        true           -      4294967295       4294967295           -          -           -

Qualquer ajuda é muito apreciada.

bash
  • 3 3 respostas
  • 150 Views

3 respostas

  • Voted
  1. Kusalananda
    2024-09-11T02:22:23+08:002024-09-11T02:22:23+08:00

    Combinando jq(para extrair a addr_infomatriz da primeira entrada de nível superior) e mlr(para formatação):

    $ ip -j addr show enp1s0 | jq 'first.addr_info' | mlr --j2p --barred unsparsify
    +--------+-------------------------+-----------+---------------+--------+---------+--------+-----------------+---------------------+
    | family | local                   | prefixlen | broadcast     | scope  | dynamic | label  | valid_life_time | preferred_life_time |
    +--------+-------------------------+-----------+---------------+--------+---------+--------+-----------------+---------------------+
    | inet   | 192.168.1.191           | 24        | 192.168.1.255 | global | true    | enp1s0 | 68465           | 68465               |
    | inet6  | fe80::2a0:aff:fe08:9aa6 | 64        |               | link   |         |        | 4294967295      | 4294967295          |
    +--------+-------------------------+-----------+---------------+--------+---------+--------+-----------------+---------------------+
    

    Se você quiser uma saída CSV simples, altere --j2p(JSON-to-pretty-printed) para --j2c(JSON-to-CSV) e remova a --barredopção (disponível somente para saída pretty-printed).

    Tenho certeza de que você pode extrair o addr_infoarray diretamente com mlr, mas isso foi rápido e fácil.

    O unsparsifyverbo of mlrgarante que todos os registros de saída tenham todos os campos e adiciona valores vazios a campos inexistentes (como no broadcastcampo no segundo registro acima).

    Dados os seus dados da questão (alimentados diretamente no mlrcomando acima, pois a addr_infomatriz já foi extraída), isso produziria

    +--------+---------------------------+-----------+---------------+--------+---------+---------------+-------+-----------------+---------------------+-----------+------------+
    | family | local                     | prefixlen | broadcast     | scope  | dynamic | noprefixroute | label | valid_life_time | preferred_life_time | temporary | mngtmpaddr |
    +--------+---------------------------+-----------+---------------+--------+---------+---------------+-------+-----------------+---------------------+-----------+------------+
    | inet   | 192.168.x.y               | 24        | 192.168.1.255 | global | true    | true          | eth0  | 2339            | 2339                |           |            |
    | inet6  | 2003:mm:nn:pp:ww:xx:yy:zz | 64        |               | global | true    |               |       | 14342           | 1742                | true      |            |
    | inet6  | 2003:mm:nn:pp:qq:rr:ss:tt | 64        |               | global | true    | true          |       | 14342           | 1742                |           | true       |
    | inet6  | fd4e:gg:hh:ii:jj:kk:ll:mm | 64        |               | global | true    |               |       | 14342           | 1742                | true      |            |
    | inet6  | fd4e:gg:hh:ii:qq:rr:ss:tt | 64        |               | global | true    | true          |       | 14342           | 1742                |           | true       |
    | inet6  | fe80::qq:rr:ss:tt         | 64        |               | link   |         | true          |       | 4294967295      | 4294967295          |           |            |
    +--------+---------------------------+-----------+---------------+--------+---------+---------------+-------+-----------------+---------------------+-----------+------------+
    
    • 6
  2. terdon
    2024-09-11T00:44:46+08:002024-09-11T00:44:46+08:00

    Aqui está uma solução alternativa horrível, desajeitada e complicada: execute ip addrduas vezes, colete os cabeçalhos da primeira passagem e então analise a segunda:

    
    #!/bin/bash
    
    ## Run `ip` once to get the headers
    headers=( $(ip -j addr show enp1s0 |
      jq -r \
         '[.[0].addr_info | .[] |
           keys_unsorted[]] | reduce .[] as $a
           ([]; if IN(.[]; $a) then . else . += [$a] end)' |
      perl -lne 's/([a-zA-Z]+)/\u$1/g;
                 if(/.*("[^"]+").*/){ push @k,"$1"}
                 END{print join(",",@k)}
     ') )
    
    ## Run it again to parse it
    ip -j addr show enp1s0 | jq -r '(['"${headers[@]}"']| (., map(length*"-"))), (.[0].addr_info | .[] | [ .family, .local, .prefixlen, .broadcast, .scope, .dynamic, .noprefixroute, .label, .valid_life_time, .preferred_life_time, .temporary, .deprecated, .mngtmpaddr ] | map(.//"-")) | @tsv' 
    

    O resultado final, executado no meu sistema, é:

    $ foo.sh
    Family  Local   Prefixlen   Broadcast   Scope   Dynamic Noprefixroute   Label   Valid_Life_Time Preferred_Life_Time
    ------  -----   ---------   ---------   -----   ------- -------------   -----   --------------- -------------------
    inet    192.168.178.57  24  192.168.178.255 global  true    true    wlp9s0  837776  837776  -   -   -
    inet6   2a03:8012:be3:0:929a:7dd0:d7df:53b1 128 -   global  true    true    -   6715    3115    -   -   -
    inet6   1a02:8012:de3:0:15a2:2c58:40e5:84ae 64  -   global  true    true    -   7196    3596    -   -   -
    inet6   ge80::929b:6ad0:c7df:53b1   64  -   link    -   true    -   4294967295  4294967295  -   -   -
    
    • 2
  3. Best Answer
    Stéphane Chazelas
    2024-09-11T14:22:32+08:002024-09-11T14:22:32+08:00

    Embora eu usasse mlr(ou perl/ pythonse você quisesse evitar instalar dependências adicionais como jqou mlr), se você tivesse que usar jq, isso poderia ser feito com algo como:

    ip -j address | jq -r '
      [
        .[].addr_info[]
      ] as $rows | 
      (
        $rows |
          add |
          keys_unsorted
      ) as $header |
      $header,
      ($header | map(gsub("."; "-"))),
      (
        $rows[] |
        (
          . as $row |
          (
            $header | map($row[.])
          )
        ) | map(.//"-")
      ) | @tsv' | column -ts $'\t'
    

    Com sua contribuição, isso dá:

    family  local                      prefixlen  broadcast      scope   dynamic  noprefixroute  label  valid_life_time  preferred_life_time  temporary  mngtmpaddr
    ------  -----                      ---------  ---------      -----   -------  -------------  -----  ---------------  -------------------  ---------  ----------
    inet    192.168.x.y                24         192.168.1.255  global  true     true           eth0   2339             2339                 -          -
    inet6   2003:mm:nn:pp:ww:xx:yy:zz  64         -              global  true     -              -      14342            1742                 true       -
    inet6   2003:mm:nn:pp:qq:rr:ss:tt  64         -              global  true     true           -      14342            1742                 -          true
    inet6   fd4e:gg:hh:ii:jj:kk:ll:mm  64         -              global  true     -              -      14342            1742                 true       -
    inet6   fd4e:gg:hh:ii:qq:rr:ss:tt  64         -              global  true     true           -      14342            1742                 -          true
    inet6   fe80::qq:rr:ss:tt          64         -              link    -        true           -      4294967295       4294967295           -          -
    

    Para adicionar o nome da interface como a primeira coluna:

    ip -j address | jq -r '
      [
        .[] |
          {"ifname"} as $ifname |
          .addr_info[] | 
          $ifname + .
      ] as $rows | 
      (
        $rows |
          add |
          keys_unsorted
      ) as $header |
      $header,
      ($header | map(gsub("."; "-"))),
      (
        $rows[] |
        (
          . as $row |
          (
            $header | map($row[.])
          )
        ) | map(.//"-")
      ) | @tsv' | column -ts $'\t'
    
    • 1

relate perguntas

  • exportar variáveis ​​​​env programaticamente, via stdout do comando [duplicado]

  • Problema estranho ao passar variáveis ​​do arquivo de texto

  • Enquanto a linha lê mantendo os espaços de escape?

  • ordem de substituição de processos `te` e `bash`

  • Execute um script muito lento até que seja bem-sucedido

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Possível firmware ausente /lib/firmware/i915/* para o módulo i915

    • 3 respostas
  • Marko Smith

    Falha ao buscar o repositório de backports jessie

    • 4 respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    user12345 Falha ao buscar o repositório de backports jessie 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl Por que a maioria dos exemplos do systemd contém WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve