0

I want to extract ip address from 'arp -an' in a python script please.

In terminal, I can do

      arp -an | grep '192.168.'

Returns ? (192.168.1.10) at so:me:ma:ca:dd:rs [ether] on wlan0 And then I can use wild cards to get the ip address in the brackets out.

So I tried in python

ip_substr = '192.168.1'
arp_command = ['arp', '-an', '|', 'grep', ip_substr]
arp_entry = subprocess.call(arp_command)

Which gave error arp: grep: Host name lookup failure (happened when subprocess calling that)

Question: what did I do wrong when passing the commands please? I also tried having ' | ' and ' grep ', basically with spaces but no luck.

Or if this is not a feasible way, how should I be able to extract the ip address that matches '192.168.1' from the returned table 'arp -an'? I tried to process by row

for row in arp_result:
    if ip_substr in row:
        print 'found'

but it gave 'int objects not iterable' error.

Thanks.

sue
  • 35
  • 5
  • `subprocess` works different from a shell. See [Python subprocess command with pipe](http://stackoverflow.com/questions/13332268/python-subprocess-command-with-pipe) and [How do I use subprocess.Popen to connect multiple processes by pipes?](http://stackoverflow.com/questions/295459/how-do-i-use-subprocess-popen-to-connect-multiple-processes-by-pipes). – das-g Mar 01 '16 at 21:10

1 Answers1

0
arp_entry = subprocess.Popen('arp -an | grep "192.168.1"', shell=True).communicate()[0]

| is a shell feature, so you need to use Popen. Also need to use communicate function to print, otherwise it will return the address.

Ajean
  • 5,528
  • 14
  • 46
  • 69
sue
  • 35
  • 5