简体   繁体   中英

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)    

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM