shell 在交互式ssh模式下在进程中插入多个命令[duplicate]

kkih6yb8  于 8个月前  发布在  Shell
关注(0)|答案(1)|浏览(63)

此问题已在此处有答案

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等),但我无法在此服务器内运行的进程上运行任何命令。
如何解决此问题?

vmpqdwk3

vmpqdwk31#

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')

1.将process_cli的(子)命令馈送到其标准输入:

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

类似问题:

相关问题