在SSH / Paramiko中使用不同的Shell执行命令/脚本

时间:2018-06-25 15:37:16

标签: python bash shell ssh paramiko

我对Linux和Paramiko还是很陌生,但是我遇到的问题是,无论何时我尝试更改远程Paramiko会话将挂起的shell。

默认情况下,远程主机位于/etc/csh中 我正在运行各种脚本,有些需要csh,有些需要bash。我的任何在csh中运行的脚本都可以正常运行,因为默认情况下远程主机位于csh中。

要运行其他脚本,我需要位于bash中。 每当我尝试使用bash/bin/bash更改shell时,paramiko连接都会挂起。我正在使用以下命令在连接之前和尝试临时更改外壳以查看有效的方法之后验证外壳,但没有任何效果。这是使用 Paramiko Python 3.6.5 注意:相反,这也失败了;如果我默认将远程主机放在bash中,它将无法切换到csh

main.py

connection = SSH.SSH(hostname, username, password)
connection.changeShell('echo $0 ; echo $shell; /bin/bash ; echo $shell ; echo $0')

也已尝试将其用作bashchsh

SSH.py

class SSH:
    client = None

    def __init__(self, address, username, password):
        print("Login info sent.")
        print("Connecting to server.")
        self.client = client.SSHClient()    # Create a new SSH client
        self.client.set_missing_host_key_policy(client.AutoAddPolicy())
        self.client.connect(address, username=username,
                password=password, look_for_keys=False) # connect

    def changeShell(self, command):
        print("Sending your command")
        # Check in connection is made previously
        if (self.client):
            stdin, stdout, stderr = self.client.exec_command(command)
            while not stdout.channel.exit_status_ready():
                # Print stdout data when available
                if stdout.channel.recv_ready():
                    # Retrieve the first 1024 bytes
                    alldata = stdout.channel.recv(2048)
                    while stdout.channel.recv_ready():
                        # Retrieve the next 1024 bytes
                        alldata += stdout.channel.recv(2048)

                    # Print as string with utf8 encoding
                    print(str(alldata, "utf8"))

            stdin.close()
            stdout.close()
            stderr.close()

        else:
            print("Connection not opened.")

1 个答案:

答案 0 :(得分:1)

您的问题与Paramiko无关。尝试将命令粘贴到SSH终端中-也不起作用。


语法aaa ; bbb依次执行命令 。在bbb完成之前,不会执行aaa。同样,/bin/bash ; echo $shell执行bashecho直到bash完成才执行,它永远不会执行,因此挂起。

您实际上并不想执行echo bash-您想执行echo {{1} }。

如果要在其他Shell中执行脚本/命令,则有三个选项: