2012-07-16 47 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地址