您好我正在尝试使用此程序中的整数ipaddress。但我需要在response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))
#!/usr/bin/python
import os
interface = os.system("ifconfig ge1 | grep UP")
ip = os.system("ifconfig ge1.1 | grep UP")
ipaddress = os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")
print ipaddress
mystring = repr(ipaddress)
print mystring
if interface == 0:
print interface, ' interface is UP!'
hostname = "8.8.8.8"
response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))
if response == 0:
print hostname, 'is up!'
else:
print hostname, 'is down!'
else:
print interface, ' interface is down!'
答案 0 :(得分:0)
os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")
不会返回您的IP地址而是退出状态代码,因此您需要使用一个模块来获取您的接口的IP地址(eth0,WLAN0..etc) ),
根据@stark链接评论的建议,使用netifaces package或socket module,示例来自this post:
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[2][0]['addr']
print ip
=============================================== ============================
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0')
EDIT-1:
建议您通过subprocess而非 os.system 运行终端命令,因为我已经阅读它更安全了。
现在,如果你想将ip_address的结果传递给你的ping
命令,我们就去:
import subprocess
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
hostname = "8.8.8.8"
cmdping = "ping -c 1 " + hostname + " -I " + get_ip_address('eth0')
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
#The following while loop is meant to get you the output in real time, not to wait for the process to finish until then print the output.
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()