Буфер канала в TCL не очищен - PullRequest
0 голосов
/ 13 марта 2019

Я запускаю сеанс SSH между ПК с Windows и устройством Linux. Создание SSH-соединения осуществляется через Python. После подключения сеанс SSH получает команды от Thar, отправленные из TCL. Это общая идея. Все работает нормально, но после того, как я отправляю команду, она, похоже, «застревает» в потоке, а все остальные команды, которые я отправляю, отправляют предыдущее значение. Я попытался использовать flush (упомянуто в коде), но все еще не дал результатов:

Код Python для установки сеанса SSH:

импорт потоков, парамико из парамико импортный клиент время импорта класс ssh: клиент = нет оболочка = нет

def __init__(self, address, username):
    print("Connecting to server.")
    cert = paramiko.RSAKey.from_private_key_file("QA-SIP-Evgenyz.pem")
    self.client = client.SSHClient()
    self.client.set_missing_host_key_policy(client.AutoAddPolicy())
    self.client.connect(address, username=username, pkey=cert)
    self.transport = paramiko.Transport((address, 22))
    self.transport.connect(username=username, pkey=cert)
    thread = threading.Thread(target=self.process)
    thread.daemon = True
    thread.start()
    print("Connected")

def closeConnection(self):
    if self.client is not None:
        self.client.close()
        self.transport.close()

def openShell(self):
    self.shell = self.client.invoke_shell()

def sendShell(self, command):
    if self.shell:
        #print("trying to run command " + command)
        self.shell.send(command + "\r")
        time.sleep(0.6)
        #self.shell.send("\r")

    else:
        print("Shell not opened.")

def process(self):
    global connection
    while True:
        # Print data when available
        if self.shell is not None and self.shell.recv_ready():
            alldata = self.shell.recv(1024)
            while self.shell.recv_ready():
                alldata += self.shell.recv(1024)
            strdata = str(alldata, "utf8")
            strdata.replace('\r', '')
            print(strdata, end = "")
            if strdata.endswith("$ "):
                print("\n$ ", end = "")




def main():
IP = '54.171.226.239'
user = 'ubuntu'
a = 0
command = ''
connection = ssh(IP, user)
connection.openShell()
i=0
while 1:
     a = a+1
     if a == 1:
     command ='ls -l'
     connection.sendShell(command)
     command = input('$ ')

Процессы TCL, которые я написал, следующие:

    proc open_ssh_connection {} {
     set pystream [open "|bin/python -i MgrLoginCLass.py" r+]
     fconfigure $pystream  -blocking 0
     set flag 0
     while {1} {
        set L [gets $pystream OutPut]
        # Print it to the screen in Tcl
    if {$OutPut != ""} {
        puts "$OutPut \n"
            if {[regexp ".*drwxrwxr-x" $OutPut]== 1} {
                set flag 1
            }

            if {($flag == 1) && ([regexp ".*194:" $OutPut]== 1)} {
                puts "here11"
                set flag 2
                break
            }
    }


}
return $pystream   }

Приведенный выше процесс возвращает идентификатор канала, который я собираюсь использовать для отправки дополнительных команд в оболочку

    proc send_command_to_SSH {ssh_stream_id command} {
        while {1} {
            #tried to use this flush even here
            flush stdout    
            puts $ssh_stream_id "$command"
            #tried here also
            flush $ssh_stream_id
            flush stdout

            set L [gets $ssh_stream_id OutPut]
                if {$OutPut != ""} {
                    puts "$OutPut \n"
                    incr number_of_lines_sent_to_xsl 1
                    if {[regexp ".*194:" $OutPut]== 1} {
                    return "Done"
                      }

                    }

            }



         }

To execute the above procs I am executing the following commands: 
set a [open_ssh_connection]
set b [send_command_to_SSH $a "stack_mgr_cli" "xsl" 2]
set c [send_command_to_SSH $a "exit" "xsl" 2]

the output of "set a [open_ssh_connection]" is:
file38900e0

the output of "set b [send_command_to_SSH $a "stack_mgr_cli" "xsl" 2]" is:

More commands: 
stack_mgr --help 
stack_mgr@ip-172-32-43-194:~$  
16
(Call Generator) 53 %  Just as expected .

 The output of "set c [send_command_to_SSH $a "exit"]""
 expected : send command "exit" to the shell , and exit the above process.

 actual : (Call Generator) 53 % set c [send_command_to_SSH $a "exit"]
 $ $ stack_mgr_cli 

 -su: stack_mgr_cli: command not found 

  stack_mgr@ip-172-32-43-194:~$  

Как видно из вышесказанного, предыдущая команда была отправлена ​​еще раз, а не существует. Я подозреваю, что команда channel buffer \ flush, но изменение ее не помогло, возможно, я не изменил ее, как ожидалось.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...