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

使用Python的paramiko模块通过SSH连接Linux时,直接执行nohup命令可能导致命令不生效,因shell会立即关闭。为解决此问题,可以改用invoke_shell方法,在命令末尾添加`&`符号使命令在后台运行。通过调整代码,确保nohup命令能在远程服务器上持续执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()

本文地址:https://blog.youkuaiyun.com/qq_15071263/article/details/107323963

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值