1

尝试使用python结构获取主机的公共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''
4

4 回答 4

3

您正在运行的主机上可能未安装 Curl。无论如何你都不需要它,因为你可以像这样在 Python 中轻松地做到这一点:

import urllib2

u = urllib2.urlopen('http://checkip.dyndns.org')
line = u.next()
print line.split("<")[6].split().pop()
于 2012-07-16T12:17:04.903 回答
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()
于 2012-07-16T12:16:28.610 回答
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)
于 2012-07-16T12:23:01.020 回答
1

一个纯python实现是

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

就是这样。如果您需要 IP 地址以外的更多信息,请查看http://ipof.in

于 2016-01-25T17:33:22.313 回答