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

(编辑:jimmy 日期: 2024/9/22 浏览:2)

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

1、使用 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()

因为执行完毕后,shell 会立即关闭通道

2、稍作修改,使用 invoke_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()

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。