I'm creating a script wherein I want to grep all a specific address based on the list?
before what I usually do run a grep 1 by 1 using this command ex. grep "192.168.1.1" *
Now I'm creating a script.
Example of the output.
print(i) output.
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
but how to call the list and put into loop under os.system so I can grep all the list?
Thanks
import ipaddress
import os
#Ask the ipaddress in CIDR format
ip = input("Enter the IP/CIDR: ")
os.chdir("/rs/configs")
print("pwd=%s" % os.getcwd())
for i in ipaddress.IPv4Network(ip):
print (i)
os.system("grep $i '*') #<--Grep from list and run to all directory *
The basic answer is "grep {} '*'".format(ip) but there are a number of problems with your script.
To improve usability, I would suggest you change the script so it accepts a list of IP addresses as command-line arguments instead.
You want to avoid os.system() in favor of subprocess.run()
There is no need to cd to the directory which contains the files you want to examine.
Finally, there is no need really to run grep, as Python itself is quite capable of searching a set of files.
import ipaddress
import glob
ips = set([ipaddress.IPv4Network(ip) for ip in sys.argv[1:]])
for file in glob.glob('/rs/configs/*'):
with open(file) as lines:
for line in lines:
if any(x in line for x in ips):
print("{0}:{1}".format(file, line))
This should be significantly more efficient by way of examining the files only once.
It's not entirely clear what you hope to gain by using ipaddress here if you are grepping for individual IP addresses anyway.
If I type "ipconfig" in cmd, its gives some IPs... I need the one who belongs to my network adapter\internal IP.
So. for example:
If I have 3 Ips:
10.100.102.2
192.168.231.1
192.168.233.1
And I need the first one. How do I make python know that this is the one I need\The one belongs to my internal IP?
The solution for extracting the first IPv4 address of ethernet adapter (Python on Windows):
- used modules: os, re
import os, re
addresses = os.popen('IPCONFIG | FINDSTR /R "Ethernet adapter Local Area Connection .* Address.*[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"')
first_eth_address = re.search(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', addresses.read()).group()
print(first_eth_address)
I'm trying to create a python script on linux that does a 'whois' command on every connected/connecting IP Address that is parsed from the 'netstat' command.
I am get an error saying "sh: 1: Syntax error: Unterminated quoted string"
and the whois usage options posted below that.
Can anyone explain to me what's wrong the script? I believe it's something to do with the for loop and the way it executes the whois command I just cant seem to find a solution. Below is the script in question:
#!/usr/bin/python
from os import system
answer = [system("netstat -alpntu46 |grep 'ESTABLISHED\|SYN_RECV' | awk '{print $5 }' |cut -d: -f1'")]
for i in answer:
system('whois')
EDIT So my original problem is completely fixed, I'm getting no errors. However, now all the script does is list the IP Addresses and underneath that it lists the whois usage examples:
-h HOST, --host HOST connect to server HOST
-p PORT, --port PORT connect to PORT
-H hide legal disclaimers
--verbose explain what is being done
--help display this help and exit
--version output version information and exit"
So it seems to be running the answer variable but not being able to run the whois command on each address.
Your command string (inside de system() command) has one ' more than needed (at the end of the string). Here it is corrected:
#!/usr/bin/python
from os import system
answer = [system("netstat -alpntu46 |grep 'ESTABLISHED\|SYN_RECV' | awk '{print $5 }' |cut -d: -f1")]
for i in answer:
system('whois')
EDIT (your second question):
When you do for i in answer in python you are looping through all items in your answer, that is correct, however for each IP address you are looping on you are executing only a 'whois' command, without passing any parameters. You should add the parameter to the string, as in:
for i in answer:
system('whois %s' % i)
that is assuming the variable i holds the ip string.
Please check the edit on my first answer (posting this just so you get notified.)
I've been playing with the module straight from the python command line to try and figure out how it all works, and start to piece together how the script I want to write is going to need to work. What I'd like to do, is do a simple host discovery scan first, such as -n -sP -PE, then use the all_hosts() function to generate the host list for the actual port scan. So if I do...
import nmap
nm = nmap.PortScanner()
nm.scan(hosts='XXX.XXX.XXX.X/24', arguments='-n -sP -PE')
Then nm.all_hosts() gives me exactly what I'm looking for, a shortened list of all the active hosts that the scan found. Now, the problem I'm having is passing that into the next scan. If you just do something like
hostlist = nm.all_hosts()
nm.scan(hosts=hostlist etc)
Then it complains about not being able to use a list for the hosts argument. Ok, makes sense. So I tried to make it comma separted, so they'd show up as aaa.aaa.aaa.aaa, bbb.bbb.bbb.bbb etc, by doing...
hostlist = ""
for item in nm.all_hosts():
hostlist = item + ", " + hostlist
Then, just dumping hostlist, it looks just how I'd like it to, but if you try to plug that into the hosts argument, it says "Failed to resolve "alltheipslisted" WARNING: No targets were specified, so 0 hosts scanned.
Does anyone have any good ideas for how to go about this? Maybe dumping the IPs to then pulling them from a file? Seems like I'd run into the same problem if a string isn't working...
If you remove the comma it will work. Multiple hosts are listed with only a space between them.
Example of use:
import nmap
nm = nmap.PortScanner()
hostlist = ' '.join(nm.all_hosts())
nm.scan(hosts=hostlist, arguments='-n -sP -PE')
I'm looking for a way (with python) to obtain the layer II address from a device on my local network. Layer III addresses are known.
The goal is to build a script that will poll a databases of IP addresses on regular intervals ensuring that the mac addresses have not changed and if they have, email alerts to myself.
To answer the question with Python depends on your platform. I don't have Windows handy, so the following solution works on the Linux box I wrote it on. A small change to the regular expression will make it work in OS X.
First, you must ping the target. That will place the target -- as long as it's within your netmask, which it sounds like in this situation it will be -- in your system's ARP cache. Observe:
13:40 jsmith#undertow% ping 97.107.138.15
PING 97.107.138.15 (97.107.138.15) 56(84) bytes of data.
64 bytes from 97.107.138.15: icmp_seq=1 ttl=64 time=1.25 ms
^C
13:40 jsmith#undertow% arp -n 97.107.138.15
Address HWtype HWaddress Flags Mask Iface
97.107.138.15 ether fe:fd:61:6b:8a:0f C eth0
Knowing that, you do a little subprocess magic -- otherwise you're writing ARP cache checking code yourself, and you don't want to do that:
>>> from subprocess import Popen, PIPE
>>> import re
>>> IP = "1.2.3.4"
>>> # do_ping(IP)
>>> # The time between ping and arp check must be small, as ARP may not cache long
>>> pid = Popen(["arp", "-n", IP], stdout=PIPE)
>>> s = pid.communicate()[0]
>>> mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
>>> mac
"fe:fd:61:6b:8a:0f"
There was a similar question answered not too long ago on this site. As mentioned in the answer chosen by the asker of that question, Python doesn't have a built-in way to do it. You must either call a system command such as arp to get ARP information, or generate your own packets using Scapy.
Edit: An example using Scapy from their website:
Here is another tool that will
constantly monitor all interfaces on a
machine and print all ARP request it
sees, even on 802.11 frames from a
Wi-Fi card in monitor mode. Note the
store=0 parameter to sniff() to avoid
storing all packets in memory for
nothing.
#! /usr/bin/env python
from scapy import *
def arp_monitor_callback(pkt):
if ARP in pkt and pkt[ARP].op in (1,2): #who-has or is-at
return pkt.sprintf("%ARP.hwsrc% %ARP.psrc%")
sniff(prn=arp_monitor_callback, filter="arp", store=0)
You could also do something similar to the verified answer. See https://scapy.readthedocs.io/en/latest/routing.html
>>> mac = getmacbyip("10.0.0.1")
>>> mac
'f3:ae:5e:76:31:9b'
This is fully cross platform.
Not exactly what you're looking for, but definitely on the right track. Enjoy!
In Linux sometimems you miss the command line util "arp". A base yocto linux embedded environment image for instance.
An alternative way without the "arp" tool would be to read and parse the file /proc/net/arp:
root#raspberrypi:~# cat /proc/net/arp
IP address HW type Flags HW address Mask Device
192.168.1.1 0x1 0x2 xx:xx:xx:xx:xx:xx * wlan0
192.168.1.33 0x1 0x2 yy:yy:yy:yy:yy:yy * wlan0
A simple solution using scapy, to scan the 192.168.0.0/24 subnet is as follows:
from scapy.all import *
ans,unans = arping("192.168.0.0/24", verbose=0)
for s,r in ans:
print("{} {}".format(r[Ether].src,s[ARP].pdst))
Sounds like you want to monitor ARP spoofers? In this case, all you need is arpwatch, available in every well-supplied Linux distribution near you. Download sources here: http://ee.lbl.gov/
for Unix based systems:
#!/usr/bin/env python2.7
import re
import subprocess
arp_out =subprocess.check_output(['arp','-lan'])
re.findall(r"((\w{2,2}\:{0,1}){6})",arp_out)
will return list of tuples with macs.
scapy is an amazing tool , but seems to be overkill for this case
an easier way, if on linux:
print os.system('arp -n ' + str(remoteIP))
you will get:
Address HWtype HWaddress Flags Mask Iface
192.168..... ether 9B:39:15:f2:45:51 C wlan0
General update for Python 3.7. Remark: the option -n for arp does not provide the arp list on windows systems as provided with certain answers for linux based systems. Use the option -a as stated in the answer here.
from subprocess import Popen, PIPE
pid = Popen(['arp', '-a', ip], stdout=PIPE, stderr=PIPE)
IP, MAC, var = ((pid.communicate()[0].decode('utf-8').split('Type\r\n'))[1]).split(' ')
IP = IP.strip(' ')
MAC = MAC.strip(' ')
if ip == IP:
print ('Remote Host : %s\n MAC : %s' % (IP, MAC))