You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Paramiko在默认shell为tcsh的远程服务器执行本地bash脚本

问题原因

直接将脚本内容传入exec_command执行时,远程服务器会调用默认shell解析命令,你遇到报错的环境默认shell为tcsh,和bash语法不兼容,因此会出现变量赋值失败、变量未定义的报错。

解决方法

显式调用bash -s接收脚本内容执行,-s参数的作用是让bash从标准输入读取命令内容,完全不受远程默认shell的影响。修改后的代码如下:

my_script = open("test.sh").read()
# 显式指定bash从标准输入读取脚本执行
stdin, stdout, stderr = ssh.exec_command("bash -s", timeout=15)
# 将脚本内容写入标准输入传给bash进程
stdin.write(my_script)
stdin.close()

print(stdout.read().decode())
err = stderr.read().decode()
if err:
    print(err)

如果远程服务器的bash没有加入环境变量PATH,可以将命令替换为绝对路径调用,例如/bin/bash -s即可正常执行。

内容的提问来源于stack exchange,提问作者aldron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 15:45:03