bash 我试图在 Linux 中获取 MAC 地址作为变量,但它很少起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17950405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I'm trying to get the MAC address as a variable in Linux, but it rarely works
提问by McB
I'm using the following code to get the MAC address of eth0 into a variable for use in a filename, but it rarely every works. It isn't that it NEVER works, it is just unpredictable.
我正在使用以下代码将 eth0 的 MAC 地址放入一个变量中以用于文件名,但它很少能正常工作。并不是它永远不会起作用,它只是不可预测的。
ntpdate -b 0.centos.pool.ntp.org
DATE=$(date +%s)
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | sed 's/://g')
cp logfile logfilecp-$MAC-$DATE
Now, it seems to work less-frequently if I use the ntpdate line, but regardless, it is wholly unpredictable. Anyone have any idea what I could do to make this work better? I end up with a filename like
现在,如果我使用 ntpdate 行,它似乎不那么频繁地工作,但无论如何,它是完全不可预测的。任何人都知道我可以做些什么来使这项工作更好?我最终得到一个文件名
logfile--1375195808.bz2
New info
新信息
I've got the script setup to run as a cronjob (crontab -e). I notice that when it runs as a cronjob, it doesn't get the MAC, but when I run it manually ./runscript.bash it does get the MAC. Hopefully someone knows why this might be causing it.
我已经将脚本设置作为 cronjob (crontab -e) 运行。我注意到当它作为 cronjob 运行时,它没有获得 MAC,但是当我手动运行它时 ./runscript.bash 它确实获得了 MAC。希望有人知道为什么这可能会导致它。
Thanks.
谢谢。
回答by jderefinko
Try an easier method to get you mac address than through ifconfig, i.e.
尝试一种比通过 ifconfig 更简单的方法来获取 mac 地址,即
cat /sys/class/net/eth0/address
I've tested it in shell (not through script) and works like a charm :
我已经在 shell 中测试过它(不是通过脚本),并且效果很好:
TEST=`cat /sys/class/net/eth0/address`
touch /tmp/blabla-$TEST
EDIT for your second problem
编辑你的第二个问题
in you cron script, add the full path of the binaries you're using (i.e. /sbin/ifconfig), or use my method as above :)
在你的 cron 脚本中,添加你正在使用的二进制文件的完整路径(即 /sbin/ifconfig),或者使用我上面的方法:)
回答by CloudWalker
ip addr | grep link/ether | awk '{print }'