通过python 执行 nohup 不生效的解决

所属分类: 脚本专栏 / python 阅读数: 1208
收藏 0 赞 0 分享

通过paramiko模块ssh登录linux,然后用exec_command方法执行带有nohup的shell命令不生效,python脚本如下:

import paramiko
import time
 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.2', 22, 'root', '123456')
ssh.exec_command('nohup ping localhost & \n')
time.sleep(1)

脚本执行完之后ping进程并没有继续运行,这可能是因为exec_command执行完之后立刻关闭通道的原因,换用invoke_shell可以正常运行:

import paramiko
import time
 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.2', 22, 'root', '123456')
chan = ssh.invoke_shell()
chan.send('nohup ping localhost & \n')
time.sleep(1)

注意,命令最后的回车\n和延时必不可少

补充知识:paramiko远程服务器nohup阻塞问题

一、需求描述:

需要来回切换多台服务器(脚本命令不太熟),就用了python的paramiko模块进行远程连接服务器,控制程序的停止和启动。安装:pip install paramiko

二、问题描述:

import paramiko
 
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='192.168.0.3', port=22, username='xxx')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('cd ~/ ; nohup python3.6 run_test.py > nohup_test.log 2>&1 &')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()

这样连接服务器的时候确实可以执行,但是遇到会阻塞的任务时,就无法生效,找了很多方法,最后发现这个比较有效。

三、解决方法

import paramiko
 
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='192.168.0.3', port=22, username='xxx', key=private_key)
# 添加下面代码
transport = ssh.get_transport()
channel = transport.open_session()
# 执行命令 此方法没有返回值
channel.exec_command('cd ~/ ; nohup python3.6 run_test.py > nohup_test.log 2>&1 &')
 
# 关闭连接
ssh.close()

四、类的调用实现:

简单测试,见下面代码

# -*- coding: utf-8 -*-
"""
20190330
"""
 
import paramiko
import time
from confs.log import logger # 自行导入logging模块即可
 
 
class EasyConnectHandle(object):
  """操作远程服务器"""
 
  def __init__(self, connect_host_name:dict):
    """初始化参数"""
    """
      "test":{
        "ip":"192.168.0.189",
        "user_name":"xxxx",
        "pwd":"huhuhu"
      },
    """
    self.connect_host = connect_host_name
    self.ssh = paramiko.SSHClient()
    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接陌生服务器
    self.ssh.connect(hostname=self.connect_host["ip"], port=22, username=self.connect_host["user_name"],
             password=self.connect_host["pwd"], timeout=10) # 初始化的时候连接到新的服务器
    logger.info(f"登录服务器---{self.connect_host['ip']}成功:")
 
  def __new__(cls, *args, **kwargs):
    """单例模式"""
    if not hasattr(cls, '_instance'):
      cls._instance = super(EasyConnectHandle, cls).__new__(cls)
    return cls._instance
 
  def exec(self, cmd=""):
    """执行操作"""
    stdin, stdout, stderr = self.ssh.exec_command(cmd)
    return stdout.read().decode()
 
  def quit(self):
    """断开服务器"""
    self.ssh.close()
    logger.info(f"退出服务器---{self.connect_host['ip']}成功")
 
if __name__ == '__main__':
  test_host = {
    "test": {
        "ip": "192.168.0.111",
        "user_name": "xxxx",
        "pwd": "xxxx",
        "jobs": [
          {
            "path": "/home/lemon",
            "type": "touch test_1.sh"
          },
          {
            "path": "/home/lemon",
            "type": "touch test_2.sh"
          }
        ]
      }
    }
  for i in ["test"]:
    easy_conn = EasyConnectHandle(test_host[i])
    transport = easy_conn.ssh.get_transport()
    if len(test_host[i].get("jobs", [])) >= 1:
      for job in test_host[i]["jobs"]:
        channel = transport.open_session()
        channel.exec_command(f"cd {job['path']};{job['type']}")
        logger.info(f"服务器---{easy_conn.connect_host['ip']}执行---cd {job['path']};{job['type']}---成功")
        time.sleep(2)
    else:
      logger.info(f"服务器---{easy_conn.connect_host['ip']}暂时没有任务")
    easy_conn.quit()

以上这篇通过python 执行 nohup 不生效的解决就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Python环境管理virtualenv&virtualenvwrapper的配置详解

这篇文章主要介绍了Python环境管理virtualenv&virtualenvwrapper的配置详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

ITK 实现多张图像转成单个nii.gz或mha文件案例

这篇文章主要介绍了ITK 实现多张图像转成单个nii.gz或mha文件案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

.img/.hdr格式转.nii格式的操作

这篇文章主要介绍了.img/.hdr格式转.nii格式的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python使用nibabel和sitk读取保存nii.gz文件实例

这篇文章主要介绍了python使用nibabel和sitk读取保存nii.gz文件实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

使用ITK-SNAP进行抠图操作并保存mask的实例

这篇文章主要介绍了使用ITK-SNAP进行抠图操作并保存mask的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

基于python实现音乐播放器代码实例

这篇文章主要介绍了基于python实现音乐播放器代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Python 存取npy格式数据实例

这篇文章主要介绍了Python 存取npy格式数据实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python代码执行时间测量模块timeit用法解析

这篇文章主要介绍了Python代码执行时间测量模块timeit用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

在keras里实现自定义上采样层

这篇文章主要介绍了在keras里实现自定义上采样层,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

用Python开发app后端有优势吗

在本篇文章里小编给大家整理的是关于app后端开发学PHP还是Python的先关问题内容,需要的朋友们可以参考下。
收藏 0 赞 0 分享
查看更多