方法1 def get_gateway(): cmd = "ip route | grep default | awk '{print $3}'" try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() results = p.stdout.readlines() if len(results) == 1: gateway = results[0].strip() return gateway except Exception, inst: print('cmd %s :%s' % (cmd, inst)) return None 方法2 def get_default_gateway(): with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))