expect script:从ifconfig解析ip地址

时间:2017-09-08 22:24:52

标签: parsing exec expect

我正在尝试从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)

2 个答案:

答案 0 :(得分:1)

试试这样:

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

请参阅Command substitution手册中的execTcl

答案 1 :(得分:0)

这里有一个简洁,简单的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}' ]