我需要创建一个查询网络接口的Python脚本,并返回主机名,IP地址和mac地址。
import java.util.Scanner;
import java.util.Random;
public class Nim {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int playernum;
int cpunum = rand.nextInt(3)+1;
int gamenum = 21;
boolean win = false;
boolean turn = true;
while((win = false) && (turn = true)){
System.out.println("The number is 21. Enter a number from 1 - 3");
playernum = input.nextInt();
int remaining = gamenum - playernum;
System.out.println("The number is now " + remaining);
turn = false;
if((turn = false) && (gamenum > 0)){
System.out.println("Computer is thinking...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
这是我正在使用的程序的一个版本。这似乎抓住了我需要的所有数据,但我不能让它打印干净或正确!我正在寻找类似的东西: " Nic:wlan0,ipaddr:10.0.0.1,mac:4651168584541"
我是编程的新手,也是python的新手,所以请任何帮助表示赞赏!
答案 0 :(得分:0)
请查看链接:
@ camflan的回复 Getting MAC Address
How to get the physical interface IP address from an interface
import netifaces
x = netifaces.interfaces()
for i in x:
if i != 'lo':
print(i)
print("mac:" + netifaces.ifaddresses(i)[netifaces.AF_LINK][0]['addr'] + " ipaddr:" + netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr'])
i += i
else:
continue
答案 1 :(得分:0)
首先这有点棘手,但这种格式应该允许你从netifaces的结果中获取数据。
import netifaces
x = netifaces.interfaces()
for i in x:
if i != 'lo':
print('\nInterface: ' + i)
mac = netifaces.ifaddresses(i)[netifaces.AF_LINK][0]['addr']
print('Mac addr: ' + mac)
try:
ip = netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr']
print('IP addr: {0} '.format(ip))
except KeyError:
print('NO IP')
continue
输出如下:
Interface: eth0
Mac add: eo:ie:9:38:ri
No IP
Interface: wlan0
Mac addr: 34:po:iu:66
IP addr: 10.0.0.1