Get Total Memory of a host with LINUX/EXPECT

2019-07-22 19:56发布

I would like to get the total memory of a host by using a '.exp' script.

After getting inside the host, I execute the following line:

"send "top -n 1 | grep Mem: | awk '{ print $(NF-7) }' | cut -d 'k' -f1\r""

While executing the script, it returns the following error:

 can't read "(NF-7)": no such variable

But if get manually inside the host, and execute the same line ( without the "send" part) , it returns me the expected number...

What I'm doing wrong? Any idea? Any proposal for other way of doing the same?

Best Regards and thanks in advance,

Antonio

2条回答
虎瘦雄心在
2楼-- · 2019-07-22 20:32

Expect is a Tcl extension. Tcl will substitute $variables in double quoted strings (see the tutorial chapter)

You want to use braces to send the literal string:

send {top -n 1 | grep Mem: | awk '{ print $(NF-7) }' | cut -d 'k' -f1}
send "\r"
查看更多
贪生不怕死
3楼-- · 2019-07-22 20:44

The output of top is not meant to be parsed this way. You can get the amount of memory in other, easier (better!) ways.

sed -n -e '/^MemTotal/s/^[^0-9]*//p' /proc/meminfo

Or you can parse the output of free, which also knows how to display in convenient sizes:

# total memory in megabytes
free -m | sed  -n -e '/^Mem:/s/^[^0-9]*\([0-9]*\) .*/\1/p'

EDIT: You always have to ask yourself "Who expands what?"

To send these commands with expect, try

send "sed -n -e '/^MemTotal/s/^\[^0-9\]*//p' /proc/meminfo\n"

# also removes kb suffix
send "sed -n -e '/^MemTotal/{s/^\[^0-9\]*//;s/ .*//p}' /proc/meminfo\n"

# displays in megabytes
send "free -m | sed -n -e '/^Mem:/{s/^\[^0-9\]*//;s/ .*//p}'\n"

This escapes from expect things that it would otherwise process and which were intended for sed.

And here's a (properly escaped) version of your original.

send "top -n 1 | grep Mem: | awk '{ print \$(NF-7) }' | cut -d 'k' -f1\n"
查看更多
登录 后发表回答