Download search results and save them in a compressed JSON file.
(limit, filename, query)
| 259 | @click.argument('filename', metavar='<filename>') |
| 260 | @click.argument('query', metavar='<search query>', nargs=-1) |
| 261 | def download(limit, filename, query): |
| 262 | """Download search results and save them in a compressed JSON file.""" |
| 263 | key = get_api_key() |
| 264 | |
| 265 | # Create the query string out of the provided tuple |
| 266 | query = ' '.join(query).strip() |
| 267 | |
| 268 | # Make sure the user didn't supply an empty string |
| 269 | if query == '': |
| 270 | raise click.ClickException('Empty search query') |
| 271 | |
| 272 | filename = filename.strip() |
| 273 | if filename == '': |
| 274 | raise click.ClickException('Empty filename') |
| 275 | |
| 276 | # Add the appropriate extension if it's not there atm |
| 277 | if not filename.endswith('.json.gz'): |
| 278 | filename += '.json.gz' |
| 279 | |
| 280 | # Perform the search |
| 281 | api = shodan.Shodan(key) |
| 282 | |
| 283 | try: |
| 284 | total = api.count(query)['total'] |
| 285 | info = api.info() |
| 286 | except Exception: |
| 287 | raise click.ClickException('The Shodan API is unresponsive at the moment, please try again later.') |
| 288 | |
| 289 | # Print some summary information about the download request |
| 290 | click.echo('Search query:\t\t\t{}'.format(query)) |
| 291 | click.echo('Total number of results:\t{}'.format(total)) |
| 292 | click.echo('Query credits left:\t\t{}'.format(info['unlocked_left'])) |
| 293 | click.echo('Output file:\t\t\t{}'.format(filename)) |
| 294 | |
| 295 | if limit > total: |
| 296 | limit = total |
| 297 | |
| 298 | # A limit of -1 means that we should download all the data |
| 299 | if limit <= 0: |
| 300 | limit = total |
| 301 | |
| 302 | with helpers.open_file(filename, 'w') as fout: |
| 303 | count = 0 |
| 304 | try: |
| 305 | cursor = api.search_cursor(query, minify=False) |
| 306 | with click.progressbar(cursor, length=limit) as bar: |
| 307 | for banner in bar: |
| 308 | helpers.write_banner(fout, banner) |
| 309 | count += 1 |
| 310 | |
| 311 | if count >= limit: |
| 312 | break |
| 313 | except Exception: |
| 314 | pass |
| 315 | |
| 316 | # Let the user know we're done |
| 317 | if count < limit: |
| 318 | click.echo(click.style('Notice: fewer results were saved than requested', 'yellow')) |
nothing calls this directly
no test coverage detected