首页 > 解决方案 > 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% 工作。不知道我做错了什么。

标签: pythonbashamazon-ec2

解决方案


来自http://docs.paramiko.org/en/2.4/api/client.html#paramiko.client.SSHClient.exec_commandA 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)

那会成功的。


推荐阅读