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