paramiko执行nohup无效,后台进程是起来的,但是没数据生成
但是,我手动执行nohup命令就没问题
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/2/7 17:29
# @Author : LinQ
import sys
import time
import paramiko
from Common.logger.logger import Log
log = Log().logger
class sshClient(object):
def __init__(self, port, hostname, username, password):
# 1 创建ssh_client实例
self.ssh_client = paramiko.SSHClient()
# 自动处理第一次连接的yes或者no的问题
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
self.port = port
self.hostname = hostname
self.username = username
self.password = password
self.ssh_client.connect(
port=self.port,
hostname=self.hostname,
username=self.username,
password=self.password
)
def exec_command(self, shell_command):
stdin, stdout, stderr = self.ssh_client.exec_command(shell_command)
log.info("shell_command:%s", shell_command)
stdout_info = stdout.read().decode('utf-8')
log.info("stdout_info:%s", stdout_info)
stderr_info = stderr.read().decode('utf-8')
log.info("stderr_info:%s", stderr_info)
def exec_commands(self, shell_commands):
for shell_command in shell_commands:
self.exec_command(shell_command)
def invoke_shell(self, shell_command):
channel = self.ssh_client.invoke_shell()
channel.send(shell_command)
time.sleep(3)
# stdin, stdout, stderr = self.ssh_client.exec_command(shell_command)
# log.info("shell_command:%s", shell_command)
# stdout_info = stdout.read().decode('utf-8')
# log.info("stdout_info:%s", stdout_info)
# stderr_info = stderr.read().decode('utf-8')
# log.info("stderr_info:%s", stderr_info)
if __name__ == '__main__':
sshclient = sshClient("22", "10.21.16.45", "root", "asiainfo123")
sshclient.exec_command(". ./.bash_profile ; nohup sh /home/datacollection_sdp/getCPU.sh >xx.log & ")
sshclient.exec_command("cd /home/datacollection_sdp;ll ")
shell脚本内容
#!/bin/bash
while true
do
sar -r 1 1 | tail -1 | awk '{print systime(),$2,$3,$4,$5,$6,$7,$8,$9,$10,$11 }'>>cpu.txt
sleep 1
done