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

我是Linux和Paramiko的新手,但我遇到的问题是我尝试更改shell时远程Paramiko会话将挂起.远程主机默认位于/ etc / csh中我正在运行各种脚本,有些需要csh而其他需要bash.由于远程主机默认位于csh中,因此在csh中运行的...

我是Linux和Paramiko的新手,但我遇到的问题是我尝试更改shell时远程Paramiko会话将挂起.

远程主机默认位于/ etc / csh中
我正在运行各种脚本,有些需要csh而其他需要bash.由于远程主机默认位于csh中,因此在csh中运行的任何脚本都能正常工作.

要运行其他脚本,我需要使用bash.
每当我尝试使用bash或/ bin / bash更改shell时,paramiko连接就会挂起.我正在使用以下命令在连接之前和尝试临时更改shell以查看哪些有效,但没有任何内容之后验证shell.这是使用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')

这也被尝试为bash和chsh

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.")

解决方法:

你的问题与帕拉米科无关.尝试将您的命令粘贴到SSH终端 – 它也无法正常工作.

语法aaa; bbb一个接一个地执行命令.直到aaa结束才会执行bbb.同样,/ bin / bash; echo $shell执行bash并且在bash完成之前不会执行echo,它永远不会执行,因此挂起.

实际上你不想在bash之后执行echo – 你想在bash中执行echo.

如果要在不同的shell中执行脚本/命令,则有三个选项:

>使用shebang在脚本本身中指定脚本所需的shell – 这是脚本的正确方法.

#!/bin/bash

>使用shell命令行执行脚本/命令:

/bin/bash script.sh

要么

/bin/bash -c "command1 ; command2 ; ..."

>将要执行的脚本/命令写入shell输入,就像我在上一个问题中向您显示的那样:

Pass input/variables to bash script over SSH using Python Paramiko

本文标题为:python – 在SSH / Paramiko中使用不同的shell执行命令/脚本

基础教程推荐