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