Skip to content

Instantly share code, notes, and snippets.

@etagwerker
Forked from ctolsen/curl_to_ab.py
Last active April 11, 2020 11:15
Show Gist options
  • Save etagwerker/eeb54fa1fdcd8ea6d5b9b168fdfa9952 to your computer and use it in GitHub Desktop.
Save etagwerker/eeb54fa1fdcd8ea6d5b9b168fdfa9952 to your computer and use it in GitHub Desktop.
"Copy to cURL" in Chrome to Apache Bench command -- Script for Python3
#!/usr/bin/env python3
import sys
import os
def curl_to_ab(curl_cmd: list, num: int=200, cur: int=4) -> str:
"""
Translate a cURL command created by Chrome's developer tools into a
command for ``ab``, the ApacheBench HTTP benchmarking tool.
Parameters
----------
curl_cmd
The string given to you by the "Copy to cURL" context action in
Chrome's developer tools.
num : int
The number of requests ApacheBench should make in total
cur : int
The number of concurrent requests ApacheBench should make
Note
----
Not all headers play nice with ApacheBench, so ``headers_to_copy`` has
been set to a reasonable default. Tweak this if you need something
else in there.
"""
url = curl_cmd[1]
headers_to_copy = [
'Origin',
'Authorization',
'Accept',
'Cookie',
'User-Agent',
'Accept-Encoding',
'Accept-Language',
'Upgrade-Insecure-Requests'
]
headers = []
for i, part in enumerate(curl_cmd):
if part == '-H':
header = curl_cmd[i+1]
if any([h in header for h in headers_to_copy]):
headers.append("'{}'".format(header))
cmd = ['ab -n {} -c {}'.format(num, cur)]
cmd += ['-H {}'.format(part) for part in headers]
cmd.append("'{}'".format(url))
return ' '.join(cmd)
if __name__ == '__main__':
"""Usage: python curl_to_ab.py <cURL command from Chrome>
"""
os.system(curl_to_ab(sys.argv[1:]))
@myusufid
Copy link

myusufid commented Oct 12, 2019

I try running
python curl_to_ab.py curl 'http://test.awesomesite.id'

but get this

  File "curl_to_ab.py", line 6
    def curl_to_ab(curl_cmd: list, num: int=200, cur: int=4) -> str:
                           ^
SyntaxError: invalid syntax

@etagwerker
Copy link
Author

@Myusuf060696 The problem is that you are trying to use Python 2, not Python 3. Try with Python 3.

@dilab
Copy link

dilab commented Dec 31, 2019

Run python3 curl_to_ab.py

and get following errors:

Traceback (most recent call last):
  File "curl_to_ab.py", line 56, in <module>
    os.system(curl_to_ab(sys.argv[1:]))
  File "curl_to_ab.py", line 27, in curl_to_ab
    url = curl_cmd[1]
IndexError: list index out of range

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment