Using python socket.gethostbyname to accept multiple arguments in the command Prompt - python

I have a text file with a list of about 50 hostnames and I am looking to script a way to run through them to get each associated IP address in the Command Prompt.
I thought pasting the hostname list in to the following code might be the easiest way but socket.gethostbyname will take no more than 1 argument at a time.
import socket
socket.gethostbyname("***hostnames***")
Is there a way to work around this argument issue, or is there a way to have the hostnames read from the textfile?

The easiest work around is to pass a filename and iterate through it:
#!/usr/bin/python
import sys
import socket
file_nm = sys.argv[1]
with open(file_nm, 'r') as f:
for host in f:
print socket.gethostbyname(host.strip())

Related

Getting Python to read text written in cmd

Not sure if screwed up my python in some way, but simple code below not functioning and not sure how to fix.
Using windows the idea is to open "cmd" in type: name.py books_looking_for and with that get the python to get the word (books_looking_for in this case) and open a browser with that search.
Problem is that the python doesn't "find" the text.
Code below:
import webbrowser, sys
#Get text from cmd
address = ' '.join(sys.argv[1:])
webbrowser.open('https://satakirjastot.finna.fi/Search/Results?lookfor={}&type=AllFields&dfApplied=1&limit=20'.format(address))
Trying with
print(address)
print(type(address))
results are
<class 'str'>
Any ideas how to fix?
Thanks
I'd suggest you to use the Argumentparser from the beginning.
It gives you many advantages, eg. automatic validation options and a autogenerated help page.
from argparse import ArgumentParser
arg_parser = ArgumentParser(description='Run Webbrowser with args')
arg_parser.add_argument('address', help='Look for given address')
args = arg_parser.parse_args()
webbrowser.open('https://satakirjastot.finna.fi/Search/Results?lookfor={}&type=AllFields&dfApplied=1&limit=20'.format(args.address))
Python Manual for ArgumentParser
Why are you slicing sys.argv this way? try simply taking the first index:
#Get text from cmd
address = sys.argv[1]
webbrowser.open('https://satakirjastot.finna.fi/Search/Results?lookfor={}&type=AllFields&dfApplied=1&limit=20'.format(address))

How do i read from the command line with Python?

This code writes google.de has address 216.239.34.117 to the shell
import os
os.system("host google.de")
Now i want to save the IP-Address into a string variable, but i can`t figure out how i read from the command line. Or is there even an easier way to get the IP-Adress to a variable?
Thanks and Greetings,
Alex
Why won't you use socket library instead of os?
import socket
host_ip = socket.gethostbyname('google.de')
print(host_ip)

Create a python script and use grep command?

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.

python sys.stdin.read() from tail -f

How come sys.stdin.read() doesn't read the piped input from tail -f?
#!/usr/bin/env python
import sys
from geoip import geolite2
def iplookup(srcip):
for ip in srcip.split("\n"):
try:
print(geolite2.lookup(ip))
except:
pass
source = sys.stdin.read()
iplookup(source)
tail -f /var/log/bleh.log | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | python mygeoip.py
You can use fileinput :
import sys
from geoip import geolite2
import fileinput
def iplookup(srcip):
for ip in srcip.split("\n"):
try:
print(geolite2.lookup(ip))
except:
pass
for line in fileinput.input():
iplookup(line)
On the plus side, your script automagically accepts filename as parameters as well.
None of the other answers (even fileinput) fully addresses the issue of buffering, and so will not work for small outputs of tail -f.
From the python man page:
Note that there is internal buffering in xreadlines(), readlines() and
file-object iterators ("for line in sys.stdin") which is not
influenced by this option. To work around this, you will want to use
"sys.stdin.readline()" inside a "while 1:" loop.
In other words what you want is:
while True:
line = sys.stdin.readline()
iplookup(line)
You can use sys.stdin as an iterator, rather than trying to read from it first.
def iplookup(srcip):
for ip in srcip:
ip = ip.strip()
try:
print(geolite2.lookup(ip))
except:
pass
iplookup(sys.stdin)
read() reads until EOF is reached.
EOF char is added when close() is performed or you can add it explicitly.
Your file does not have any EOF. Modify your program to read blocks of fixed size or iterate over leadline() instead.

Using python nmap module to scan hosts generated from a previous scan

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')

Categories