paramiko执行多个操作系统命令并返回

 

@csrf_exempt
def execute_multi_remote_command(request):

    # request_dict = json.loads(request.body)
    # cmd = request_dict.get("cmd")
    ip = '192.168.1.14'
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=ip, port=22, username='root', password='111111')
    commands = ['ls', 'who', 'uname -a']
    results = {}
    for cmd in commands:
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(cmd)
        # 获取命令结果
        result = stdout.read().decode('utf-8')
        error = stderr.read().decode('utf-8')
        # 如果有错误信息,添加到结果中
        #if error:
        #    results[cmd] = error
        #else:
        #    results[cmd] = result
        results[cmd] = result

    ssh.close()
    print(results)
    #return HttpResponse(results, content_type="text/plain")
    return JsonResponse(results, safe=False)

 

posted @ 2024-10-24 09:32  slnngk  阅读(17)  评论(0编辑  收藏  举报