我对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')
也已尝试将其用作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.")
答案 0 :(得分:1)
您的问题与Paramiko无关。尝试将命令粘贴到SSH终端中-也不起作用。
语法aaa ; bbb
依次执行命令 。在bbb
完成之前,不会执行aaa
。同样,/bin/bash ; echo $shell
执行bash
,echo
直到bash
完成才执行,它永远不会执行,因此挂起。
您实际上并不想执行echo
后 bash
-您想执行echo
{{1} }。
如果要在其他Shell中执行脚本/命令,则有三个选项:
使用shebang在脚本本身中指定脚本所需的外壳-这是脚本的正确方法。
bash
使用shell命令行执行脚本/命令:
#!/bin/bash
或
/bin/bash script.sh
将要执行的脚本/命令写到shell输入中,就像我在上一个问题中向您展示的那样:
Pass input/variables to bash script over SSH using Python Paramiko