此问题已在此处有答案:
Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko(1个答案)
Execute multiple commands in Paramiko so that commands are affected by their predecessors(2个答案)
4年前关闭。
我开始使用paramiko从我电脑上的python脚本调用我服务器上的命令。
我写了下面的代码:
from paramiko import client
class ssh:
client = None
def __init__(self, address, port, username="user", password="password"):
# Let the user know we're connecting to the server
print("Connecting to server.")
# Create a new SSH client
self.client = client.SSHClient()
# The following line is required if you want the script to be able to access a server that's not yet in the known_hosts file
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
# Make the connection
self.client.connect(address, port, username=username, password=password, look_for_keys=False)
def sendcommand(self, command):
# Check if connection is made previously
if self.client is not None:
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
_data = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
_data += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(_data, "utf8"))
else:
print("Connection not opened.")
def closeconnection(self):
if self.client is not None:
self.client.close()
def main():
connection = ssh('10.40.2.222', 2022 , "user" , "password")
connection.sendcommand("cd /opt/process/bin/; ./process_cli; scm")
print("here")
#connection.sendcommand("yes")
#connection.sendcommand("nsgadmin")
#connection.sendcommand("ls")
connection.closeconnection()
if __name__ == '__main__':
main()
现在,我发送到服务器的命令(scm)中的最后一个命令是一个应该发送到我在服务器中运行的进程“process_logic”的命令,并且应该向我打印该进程的输出(该进程从服务器shell的stdin获取输入,并将输出打印到服务器shell的stdout)。
当我在交互模式下运行时,一切正常,但当我运行脚本时,我成功连接到我的服务器并在此服务器上运行所有基本shell命令(例如:ls、pwd等),但我无法在此服务器内运行的进程上运行任何命令。
如何解决此问题?
1条答案
按热度按时间vmpqdwk31#
SSH“exec”通道(由
SSHClient.exec_command
使用)在单独的shell中执行每个命令。因此:cd /opt/process/bin/
对./process_cli
没有任何影响。scm
将作为shell命令执行,而不是process_cli
的子命令。您需要:
1.将
cd
和process_cli
作为一个命令执行(在同一个shell中):或
1.将
process_cli
的(子)命令馈送到其标准输入:类似问题: