Paramiko Channel在exec_command()之后关闭;脚本在之后立即中止

时间:2017-11-30 02:27:48

标签: python-2.7 ssh paramiko

我想ssh到主机并在那里执行shell命令。到目前为止,我有一个我实例化的类(使用paramiko)来处理所有ssh连接并在该连接中执行命令:

import paramiko
class ShellHandler:

def __init__(self, top, host, user, psw):
    self.ssh = paramiko.SSHClient()
    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    self.host = host
    self.user = user
    self.psw = psw
    self.top = top

## Connect to remote host
def connect(self):
    try:

        self.ssh.load_system_host_keys(filename=None)
        self.ssh.connect(self.host, username=self.user,
                         password=self.psw, port=22)

        channel = self.ssh.invoke_shell()
        # self.stdin = channel.makefile('wb')
        self.stdout = channel.makefile('r')

        print "Correct Username %s and Password %s\n" % (self.user, self.psw)

    except paramiko.ssh_exception.AuthenticationException as e:
        print "Incorrect Username %s and Password %s " % (self.user, self.pwd)
        return 2

    except socket.error as e:
        if e.errno == errno.ECONNREFUSED:
            print "Connection Error\n"
        else:
            print "Something went wrong\n"
            self.top.insert(INSERT, "Something went wrong\n")
        return 1

    return self.ssh, 0

## close connection to remote host
def __del__(self):
    self.ssh.close()

## Execute command on remote host
def execute(self, cmd):
    try:
        stdin, stdout, stderr = self.ssh.exec_command(cmd)
        if(stderr):
            for errors in stderr.readlines():
                print errors.encode('ascii')
                self.top.insert(INSERT, "Something went wrong: %s\n" % (
                    errors.encode('ascii')))
    finally:
        if self.ssh is not None:
            self.__del__()

    return self.ssh, stdin, stdout, stderr

(注意:我返回ssh客户端,因为我读了另一个StackOverflow问题,你应该返回客户端,否则连接将关闭,因为它现在超出了范围)

我有一个相当重要的脚本需要大约6小时才能运行。现在,当我使用正确的用户名,密码和主机实例化此类时,我能够成功登录。之后,我能够成功执行我想要的脚本。该脚本执行了一段时间,然后,我得到以下错误(来自stderr流):

Error: <paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0x3beb8d0L (unconnected)>>>
connection closed

然后脚本中止。

如果有人可以提供有关如何改进我的代码的任何提示,那么我可以通过ssh更好地执行我的脚本,我们将不胜感激!

0 个答案:

没有答案