【问题标题】:expect script: parse ip address from ifconfig期望脚本:从 ifconfig 解析 IP 地址
【发布时间】:2017-09-08 22:24:52
【问题描述】:

我正在尝试从 ifconfig 命令解析 IP 地址。当我在命令行上执行此操作时,它工作正常

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

但是当我在期望脚本中使用它时会出错。

#!/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)

【问题讨论】:

  • this question 有帮助吗?
  • 试试“bash ifconfig_parse.sh”

标签: parsing exec expect


【解决方案1】:

试试这样:

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

参见Tcl 的手册中的Command substitutionexec

【讨论】:

  • 你应该解释为什么,单引号和大括号。
  • @whjm 谢谢。在使用引号和大括号时必须小心。如果 {[regexp {inet addr:(\S+)} [exec ifconfig enp0s3] -> clientIP]} { puts "clientIP = $clientIP" }跨度>
【解决方案2】:

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

对于ip4

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

对于ip6

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

对于ip4ip6

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

基本上脚本应该是:

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

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2019-08-19
    • 2011-08-08
    相关资源
    最近更新 更多