簡體   English   中英

在Python中使用urllib模擬curl命令-httplib.InvalidURL:非數字端口:

[英]Simulate curl command using urllib in Python - httplib.InvalidURL: nonnumeric port:

我正在嘗試在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())

好的,看看您的導入,代碼應該可以正常工作。 問題在於,首先要將urllib2導入為urllib,然后再從urllib導入urlencode,因此您無法獲得所需的功能。

查看從urlib2 docs中檢索到的以下代碼:

鏈接: URLLIB2文檔

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()

祝好運!

問題是身份驗證(我們假設它是基本身份驗證)不能像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())

這應該工作,
開瓶器只需要實例化一次

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM