首页 > 解决方案 > 在交互式 ssh 模式下调用进程内的多个命令

问题描述

我开始使用 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_cli”,并且应该打印出进程的输出(进程从服务器外壳的标准输入获取输入并将输出打印到服务器外壳的标准输出)。
当我在交互模式下运行时一切正常,但是当我运行脚本时,我成功连接到我的服务器并在该服务器上运行所有基本 shell 命令(例如:ls、pwd 等),但我无法运行任何命令在此服务器内部运行的进程上。

我该如何解决这个问题?

标签: pythonshellsshparamiko

解决方案


SSH“exec”通道(由 使用SSHClient.exec_command)在单独的 shell 中执行每个命令。作为结果:

  1. cd /opt/process/bin/对 完全没有影响./process_cli
  2. scm将作为 shell 命令执行,而不是作为process_cli.

你需要:

  1. 执行cdprocess_cli作为一个命令(在同一个 shell 中):

    stdin, stdout, stderr = client.exec_command('cd /opt/process/bin/ && ./process_cli') 
    

    或者

    stdin, stdout, stderr = client.exec_command('/opt/process/bin/process_cli') 
    
  2. 将 的(子)命令馈送process_cli到其标准输入:

    stdin.write('scm\n')
    stdin.flush()
    

类似的问题:


推荐阅读