首页 > 编程语言 > 详细

Python 远程执行 shell 命令

时间:2021-04-02 17:11:27      阅读:21      评论:0      收藏:0      [点我收藏+]

Python 远程执行 cmd 命令,并实时获取结果

# 远程执行 CMD 命令, 并实时显示脚本执行情况
def ssh_Run_Cmd(host, username, password, cmd):
    """

    :param host:  主机 Ip
    :param username: 用户名 root
    :param password: 密码   Troila12
    :param cmd 想执行的命令
    :return:
    """
    import paramiko
    import requests
    ssh = paramiko.SSHClient()
    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器
    ssh.connect(hostname=host, port=22, username=username, password=password)
    # 执行命令
    # stdin, stdout, stderr = ssh.exec_command(‘/usr/bin/Rscript /tandelindata/code.R‘)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # 获取命令结果
    # result = stdout.read().decode(‘utf-8‘)
    res = []  # 用于判断脚本是否执行完毕
    while len(res) < 10:
        result = stdout.readline().strip()
        if result is not None and len(result) != 0:
            # requests.request(‘post‘, ‘url‘, data="result")
            print(result)
            res = []
        else:
            res.append(0)
    # 关闭连接
    ssh.close()
    # return result

Python 远程执行 shell 命令

原文:https://www.cnblogs.com/FutureHolmes/p/14611267.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!