代码之家  ›  专栏  ›  技术社区  ›  Piyush Bhagat

预期脚本:从ifconfig解析ip地址

  •  0
  • Piyush Bhagat  · 技术社区  · 7 年前

    pb791b@pb791b-VirtualBox:~/devtest/ngs/base/Tests/shellScripts$ ifconfig enp0s3 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'
    192.168.1.112
    

    但当我在expect脚本中使用它时,它会出错。

    #!/usr/bin/expect 
    
    set pidBash [ spawn bash ]
    
    set ipIfConfig {ifconfig enp0s3 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'}
    set clientIP [exec "echo $ipIfConfig"]
    puts "clientIP = $clientIP" 
    exit 1
    

    pb791b@pb791b-VirtualBox:~/devtest/ngs/base/Tests/shellScripts$ ./ifconfig_parse.sh 
    spawn bash
    couldn't execute "echo ifconfig enp0s3 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'": no such file or directory
        while executing
    "exec "echo $ipIfConfig""
        invoked from within
    "set clientIP [exec "echo $ipIfConfig"]"
        (file "./ifconfig_parse.sh" line 7)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   pynexj    7 年前

    set ip [exec ifconfig enp0s3 | sed -n {/inet addr/s/.*addr.\([^ ]*\) .*/\1/p}]
    puts ip=$ip
    

    看见 Command substitution exec 在里面 Tcl 的手册。

        2
  •  0
  •   Dudi Boy    5 年前

    这里有一个简洁简单的awk脚本来提取ip

    ip4

    ifconfig eno1 |awk '/inet /{print $2}'
    

    ip6

    ifconfig eno1 |awk '/inet6/{print $2}'
    

    对于两者 ip4级

    ifconfig eno1 | awk'/inet/{print$2}'

    基本上,脚本应该是:

    set ip [ ifconfig eno1 |awk '/inet /{print $2}' ]