解决Python paramiko远程执行SSH命令时nohup不生效的问题

一只小鹿
一只小鹿
发布时间:2026-10-12 | 2人浏览过
原创

本文探讨在使用Python paramiko模块通过SSH远程执行Linux命令时,nohup后台运行不生效的问题。根本原因在于exec_command执行完毕后shell通道立即关闭。解决方案是改用invoke_shell方法,并在命令后添加' & '及换行符,使进程在后台持续运行而不随通道关闭而终止。

Python - paramiko 模块远程执行ssh 命令 nohup 不生效的问题解决

在使用 paramiko 模块通过 SSH 登录到 Linux 系统并执行 nohup 命令时,可能会发现该命令并未按预期生效。

# 执行命令
def command(ssh_config, cmd, result_print=None, nohup=False):
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(hostname=ssh_config.hostname, port=ssh_config.port, username=ssh_config.username,
        password=ssh_config.password)
  print(ssh_config.hostname + '@' + ssh_config.username, ': ', cmd)
  stdin, stdout, stderr = ssh.exec_command(cmd)
  result = stdout.read()
  if result_print:
    lines = read_unicode(result)
    for line in lines:
      print(line)
  ssh.close()

造成这一现象的原因是,当使用 exec_command 执行命令完毕后,shell 会立即关闭通道,导致后台进程无法独立于 SSH 会话持续运行。

为解决此问题,可对代码稍作修改,改用 invoke_shell 方法来建立交互式 shell 会话。

# 执行命令
def command(ssh_config, cmd, result_print=None, nohup=False):
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(hostname=ssh_config.hostname, port=ssh_config.port, username=ssh_config.username,
        password=ssh_config.password)
  print(ssh_config.hostname + '@' + ssh_config.username, ': ', cmd)
  if nohup:
    cmd += ' & \n '
    invoke = ssh.invoke_shell()
    invoke.send(cmd)
    # 等待命令执行完成
    time.sleep(2)
  else:
    stdin, stdout, stderr = ssh.exec_command(cmd)
    result = stdout.read()
    if result_print:
      lines = read_unicode(result)
      for line in lines:
        print(line)
  ssh.close()

到此这篇关于解决Python paramiko 模块远程执行ssh 命令 nohup 不生效的问题的文章就介绍到这了,更多相关Python paramiko 模块远程执行ssh 命令 nohup 不生效内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表