2012-07-16 39 views
1

尝试获得主机的公网IP地址与蟒蛇面料蟒蛇面料得到公网IP地址

def publicip(): 
     ip = local("curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\'\1/g\'") 
     print (red(ip)) 

错误:(?执行外部命令)

Fatal error: local() encountered an error (return code 2) while executing 'curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/'/g'' 

回答

1

看来local()不支持要执行多个命令。您可以执行然而分成:

def publicip(): 
    ip = local("curl -s 'http://checkip.dyndns.org'", capture=True) 

然后IP将包含所需的HTML:

'<html><head><title>Current IP Check</title></head><body>Current IP Address: 1.2.3.4</body></html>' 

,你可以使用正则表达式解析,如:

r = re.compile(r'.*\<body>Current IP Address:\s(.*)\</body>.*') 
final_ip = r.match(ip).group(1) 
+0

最好使用stdlib这个比壳出来卷曲。 – Morgan 2012-07-16 17:42:03

+0

@Morgan:同意,这只是一个例子,如何使问题中的代码正常工作。 – Tisho 2012-07-16 18:15:01

2

我不知道什么local()是的,但使用requests库和re.search这是相当简单:

import requests, re 

r = requests.get('http://checkip.dyndns.org') 
myip = re.search(r'\d+\.\d+\.\d+\.\d+', r.text).group() 
3

Curl可能未安装在正在运行的主机上。你不需要它无论如何,你可以在Python中很容易做到这一点是这样的:

import urllib2 

u = urllib2.urlopen('http://checkip.dyndns.org') 
line = u.next() 
print line.split("<")[6].split().pop() 
+1

嗯......乔恩的正则表达式更好地发现IP地址。如果您的主机上没有安装请求,您可能仍然希望使用urllib2。但是,如果你的要求是更好的图书馆:) – 2012-07-16 12:19:16

1

纯蟒蛇实施是

import requests 
r = requests.get('http://ipof.in/txt') 
myip = r.text 

就是这样。检查出http://ipof.in如果你需要更多的信息,除了IP地址