当paramiko抛出“无现有会话”异常时,标准输入流挂起

2024-07-02 21:04:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用java使用以下方法启动python脚本:

private String[] runScript(String args) {
        ArrayList<String> lines = new ArrayList<String>();
        try {
            String cmd = "python py/grabber/backdoor.py " + args;
            System.out.println(cmd);
            Runtime run = Runtime.getRuntime();
            Process pr = run.exec(cmd);
            InputStream stdout = pr.getInputStream();
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
            String line;
            System.out.println("Starting to read output:");
            while ((line = stdInput.readLine()) != null) {
                if(!pr.isAlive()) {
                    break;
                }
                System.out.println("" + line);
                lines.add(line);
            }
            stdInput.close();
        } catch (Exception e) {
            System.out.println("Exception in reading output" + e.toString());
        }
        return lines.toArray(new String[lines.size()]);
    }

python脚本开始对每个设备的新子线程上的设备列表执行以下方法:

def run_command(device, retry):
    try:
        if(retry != 0):
            save_log('Retrying '+device['ip']+'...')
        SSHClient = netmiko.ssh_dispatcher("cisco_ios")
        ssh_connection = SSHClient(**device)

        ruckus = ("ruckus" in str(device['device_type']))

        output = ssh_connection.send_command('show run | inc hostname')
        if(not ruckus):
            output = output.split('\n')[0]
            hostname = output.split(' ')[1] + '-' + today
        else:
            hostname = output.split(' ')[1] + '-' + today

        msg = (''+device['ip']+':Retry Success! Hostname:'+hostname+'\n',''+device['ip']+':hostname: ' + hostname + '\n')[retry == 0]
        save_log(msg)
        return True
    except Exception as e:
        if("Authentication" in str(e)):
            if(config.exe_i):
                save_log('\nAuthentication failed! Consider resetting credentials\n')
                if(not config.using_gui):
                    val = input("Continue with list? [y]/[n]: ")
                    if("n" in val):
                        return False
                else:
                    return True
            else:
                msg = '\nSwitch: ' + device['ip'] + '\nLogin Failure'
                save_error(msg)
                return True
        elif("SSH protocol banner" in str(e) and retry <= 3):
            retry += 1
            save_log('\nSwitch: ' + device['ip'] + ' - SSH Banner.. Attempt: '+str(retry))
            return run_command(device, retry=retry)
        elif("conn_timeout" in str(e) and retry <= 3):
            retry += 1
            save_log('\nSwitch: ' + device['ip'] + ' - Connection Timeout.. Attempt: '+str(retry))
            return run_command(device, retry=retry)
        error = 'error @ switch: ' + device['ip'] + ' with error: \n' + str(e)
        save_error(error)
        return True

当python脚本得到这个特殊的异常时

Paramiko: 'No existing session' error: try increasing 'conn_timeout' to 10 seconds or larger.

脚本将简单地重试连接并按预期正常进行,但是java程序开始挂起while循环,尽管python脚本成功地完成了执行。为什么当抛出此异常时,while循环中的标准输入流开始挂起

其他信息:

1.)从场景中取出线程时,如果引发“无现有会话”异常,while循环仍将挂起

2.)导致重试ssh尝试的另一个常见异常“ssh协议横幅”不会导致while循环挂起。因此,我的结论是,问题不在于我的程序堆栈中处理异常本身的方式


Tags: runinip脚本outputstringreturnif
1条回答
网友
1楼 · 发布于 2024-07-02 21:04:58

问题在于Java段,解决方案不仅是读取输入流,还读取输出流,因为如果两者都没有清空,进程将挂起。为了正确地执行此操作,需要在单独的线程上读取每个流。ProcessBuilder是一个更好的选择,因为它允许您将输入和输出流组合成一个流,然后只需要主线程

这篇文章是对这个概念的一个更规范的问题的参考: Java Process with Input/Output Stream

相关问题 更多 >