how to pass parameters to python script as JSON

How to call below python script through API and pass the parameters through JSON?

I need help to pass the hostname, credenials details and commands as parameters from an external application.

import paramiko  hostname = "127.0.0.1" username = "test" password = "abc1235"  commands = [     "pwd",     "id",     "uname -a",     "df -h" ]  # initialize the SSH client client = paramiko.SSHClient() # add to known hosts client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try:     client.connect(hostname=hostname, username=username, password=password) except:     print("[!] Cannot connect to the SSH Server")     exit()      # execute the commands for command in commands:     print("="*50, command, "="*50)     stdin, stdout, stderr = client.exec_command(command)     print(stdout.read().decode())     err = stderr.read().decode()     if err:         print(err)     
Add Comment
1 Answer(s)

Using argparse you can pass in the JSON as a command line argument and then using python’s built-in json package, parse the JSON like so:

import argparse import json  # Set up the argument parser parser = argparse.ArgumentParser() parser.add_argument('JSON', metavar='json',type=str, help='JSON to parse')  args = parser.parse_args()  # Get JSON data json_str = args.JSON  # Parse JSON data json_data = json.loads(json_str) print(json_data["hostname"]) 

But honestly you’d be way better off if you just separated the JSON values and them passed each of them on individually as a command line argument.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.