如何将bash变量移交给python脚本?

时间:2014-05-23 03:19:49

标签: bash scripting grep

我对bash脚本更新,更习惯批处理。无论如何,我想要做的是能够从一个从nmap扫描创建的bash变量中获取一个字符串,并使其成为python脚本的变量。我打算使用grep,但它太过分了。结果如下:

Starting Nmap 5.21 ( http://nmap.org ) at 2014-05-22 20:12 PDT
Nmap scan report for 192.168.1.201
Host is up (0.00020s latency).
Not shown: 96 filtered ports
PORT     STATE SERVICE
135/tcp  open  msrpc
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds
3389/tcp open  ms-term-serv
MAC Address: 02:21:9B:88:3C:06 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 4.77 seconds

我想得到的是:MAC Address: 02:21:9B:88:3C:06最后的空格。那就是MAC=$

提前谢谢

2 个答案:

答案 0 :(得分:2)

MAC=$(egrep -o '^MAC Address: (..:){5}.. ' filename.txt)

-o选项使egrep只输出与正则表达式匹配的行的部分,因此它只会到达地址后面的空格。

答案 1 :(得分:0)

您可以使用grep和管道(|)与awk

MAC=`grep -a 'MAC' Nmapscan.txt | awk -F ' ' {'print $1" "$2" "$3" " '}`

或者

MAC=`nmap 192.168.1.201 | grep 'MAC' | awk -F ' ' {'print $1" "$2" "$3" " '}`

如果可能的话,我强烈建议您为安全性添加此更改:

NMAP_FILE=`mktemp`

# start
nmap 192.168.1.201 > $NMAP_FILE

# middle
MAC=`grep -a 'MAC' $NMAP_FILE | awk -F ' ' {'print $1" "$2" "$3" " '}`

# end
rm -f $NMAP_FILE

要将$MAC传递给您的python脚本,您可以使用:

ALERT.py $MAC &

并将其添加到ALERT.py

import sys

mac_address = sys.argv[0]

# now `mac_address` is "MAC Address: 02:21:... "