服务器之家

服务器之家 > 正文

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

时间:2020-07-14 17:07     来源/作者:简简单单OnlineZuozuo

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

1、使用 paramiko 模块ssh 登陆到 linux 执行nohup命令不生效

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 执行命令
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 执行命令
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 不生效内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_15071263/article/details/107323963

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部