python - EC2 SSH 进入其他 SSH 并运行 bash 脚本
问题描述
我将 Python 程序 sshs 放入不同的 EC2 盒子并运行 bash 脚本。但是,如果它在登录时位于默认目录中,它只会运行 bash 脚本。这是一些代码。
import boto3
import botocore
import paramiko
s3_client = boto3.client('s3')
s3_client.download_file('mybucket','keys/mykey.pem', '/tmp/mykey.pem')
k = paramiko.RSAKey.from_private_key_file('/tmp/mykey.pem')
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "Connecting to Box"
c.connect( hostname = '99.99.9999', username = 'centos',pkey = k )
print "Connected to Matching Box"
commands = [
"cd /dir1/dir2/dir3/", #<- This isn't working
"pwd",
"chmod +x file.sh",
"nohup ./file.sh > logs/myprogram"
]
for command in commands:
print "Executing {}".format(command)
stdin , stdout, stderr = c.exec_command(command)
print stdout.read()
print stderr.read()
quit() #use return when putting on the handler
{
'message' : "Script execution completed. See Cloudwatch logs for complete output"
}
问题是它没有改变目录。PWD 不断返回默认值,然后显然由于我的 bash 脚本不存在而引发错误消息。这是一个 Centos 构建 EC2 实例,不确定这是否重要。如果我正常登录并运行相同的更改目录命令,它可以 100% 工作。不知道我做错了什么。
解决方案
来自http://docs.paramiko.org/en/2.4/api/client.html#paramiko.client.SSHClient.exec_command:
A new Channel is opened and the requested command is executed.
如果你正常登录,你的4条命令都会在同一个频道执行,所以cd
生效。但是当您在 s 的循环中执行它们时,会产生并销毁exec_command()
4 个通道,可能是 4 个bash
进程,因此$PWD
不会持续存在。
command = 'cd /dir1/dir2/dir3/; pwd; chmod +x file.sh; nohup ./file.sh > logs/myprogram'
stdin, stdout, stderr = c.exec_command(command)
那会成功的。
推荐阅读
- php - 如何计算数组中的文本?
- c++ - Visual Studio Code:CMake 工具选项卡中的文件路径不正确
- c++ - 从矢量中擦除
- java - 如何以并行模式运行有序的 JUnit5 测试
- python - 通过 crontab 运行烧瓶命令
- r - 如何使用某些定义的逻辑根据特定日期范围及其价值查找每周二
- python - 可视化层输出时出现 Keras(带有 Tensorflow 2 后端)错误
- c# - 如何从没有属性的 XML 文件中获取节点并将其放入字符串列表
- php - PHP GD 库 - 文本/字体不显示
- javascript - Gatsby 节点错误:抛出“必须提供源”错误