简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM