我正在尝试在Python中复制以下CURL
命令(我正在尝试使用特定IP上的某些数据发出POST
请求):
curl -k --data "phonenr=a_number&smstxt=Test&Submit=SendSms" https://admin:pass@ip/txsms.cgi
其中ip
是远程服务器的IP,admin:pass
是所需的凭据。
此CURL命令正确执行,响应为200
。
使用以下python代码,我收到:
httplib.InvalidURL: nonnumeric port: 'pass@91.195.144.248'
有谁能告诉我我做错了什么?
import urllib2 as urllib
from os.path import join as joinPath
from urllib import urlencode
# constant
APPLICATION_PATH = '/srv/sms_alert/'
ALERT_POINT_PATH = joinPath(APPLICATION_PATH, 'alert_contact')
URL_REQUEST_TIMEOUT = 42
SMS_BOX_URL = 'https://admin:pass@ip/txsms.cgi'
with open(ALERT_POINT_PATH, 'r') as alertContactFile:
for line in alertContactFile:
line = line.strip('\n')
data = {
'phonenr': line,
'smstext': 'Test',
'Submit': 'SendSms'
}
url_data = urlencode(data)
url_data = url_data.encode('UTF-8')
req = urllib.Request(SMS_BOX_URL, url_data)
with urllib.urlopen(req) as response:
print(response.read())
答案 0 :(得分:0)
好的,看看你的导入,代码应该工作正常。问题是首先你要将urllib2作为urllib导入,然后从urllib导入urlencode,这样你就不会得到你想要的功能。
查看从urlib2 docs中检索到的以下代码:
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
祝你好运!
答案 1 :(得分:0)
问题是身份验证(我们假设它的基本身份验证)不能像curl命令一样发送,urllib会将用户视为主机名以及'之后的内容。 :'作为端口,这就是你有这个错误的原因,
您必须尝试使用以下凭据设置urllib开启器:
import urllib2 as urllib
SMS_BOX_URL = 'https://hostname/txsms.cgi'
# Prepare an authentication handler
auth_handler = urllib.HTTPBasicAuthHandler()
# Set your authentication Handler (catch the realm by parsing the authentication request with your navigator
auth_handler.add_password('realm', 'the realm of the authent', 'admin', 'pass')
opener = urllib.build_opener(auth_handler)
# Install your opener for later use
urllib.install_opener(opener)
# use it
url_data = urlencode(data)
url_data = url_data.encode('UTF-8')
req = urllib.Request(SMS_BOX_URL, url_data)
with urllib.urlopen(req) as response:
print(response.read())
这应该有效,
开启者只需要实例化一次