C# paramiko SSH在执行远程处理命令时出错&引用;句柄无效";

C# paramiko SSH在执行远程处理命令时出错&引用;句柄无效";,c#,python,ssh,exe,paramiko,C#,Python,Ssh,Exe,Paramiko,我用Python在类中编写了一个方法(用于使用paramiko的SSH连接),用于在windows服务器上执行远程exe。 方法是: ''' Created on Feb 25, 2014 ''' """Friendly Python SSH interface.""" import os import paramiko from hashlib import md5 import stat import time import shutil import glob c

我用Python在类中编写了一个方法(用于使用paramiko的SSH连接),用于在windows服务器上执行远程exe。 方法是:

    '''
Created on Feb 25, 2014

    '''


"""Friendly Python SSH interface."""

import os
import paramiko
from hashlib import md5
import stat
import time
import shutil
import glob

class SSHConnection(object):

    """Connects and logs into the specified hostname.

     ALL functions return a tuple

     e.g.,
     return (False,{'msg'}:'RELEVANT MESSAGE')

     So while calling any of these methods, call like:
     e.g.,

     result, reply = get('./Raiden/example.txt','C:/tmp/example.txt')

     And check/print error if successfully executed or not, using:

     if not result:
        print(reply['msg'])

     """


    def __init__(self):

        pass


    def establish_conn(self, host,username="xxxx",password="xxxx",port=xx):

        self._sftp_live = False
        self._sftp = None

        # Begin the SSH transport.
        print ("Establishing an SSH Connection to : " +host );

        try:
            self._transport = paramiko.Transport((host, port))
            self._transport_live = True

        except Exception as e:
            print ('SSH error: ' + str(e))
            return False, {'msg':'SSH error: ' + str(e)}

        # Authenticate the transport.

        try:
            if password:
                msg = self._transport.connect(username=username, password=password)

        except Exception as e:
            print ('SSH error: '+str(e))
            return False, {'msg':'SSH error: ' + str(e)}

        return True, {'msg': 'Connection established'}


    def _sftp_connect(self):

        """Establish the SFTP connection."""

        if not self._sftp_live:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
            self._sftp_live = True


    def get(self, remotepath, localpath=None):

        """Copies a file from the remote host to the local host."""

        if not localpath:

            if not os.path.isdir("C:/tmp"):
                os.mkdir("C/tmp")
            localpath = "C:/tmp/" + (os.path.split(remotepath)[-1].split('.')[0]  + \
                                     "-" + time.strftime("%Y%m%d-%H%M%S") + '.' + os.path.split(remotepath)[-1].split('.')[1])
            print ("File will be downloaded to localpath: " +localpath)

        if not os.path.dirname(os.path.abspath(localpath)):
             print ("Local directory path does not exists! Enter a valid directory path or create the path manually. ")
             return False, {'msg': 'Localpath not present! '}

        else:

            try:

                self._sftp_connect()
                self._sftp.get(remotepath, localpath)

            except Exception as e:

                print('File to be downloaded not available at remote box')
                return False,{'msg':str(e)}


        return True, {'msg':'File downloaded successfully !'}


    def put(self, localpath, remotepath=None):

        """Copies a file from the local host to the remote host."""

        self._sftp_connect()
        self._sftp.put(localpath, remotepath)


    def execute(self, command, timeOut=100):

        """Execute the given commands on a remote machine."""

        try:
            channel = self._transport.open_session()

            x = channel.get_pty()

            channel.timeout = timeOut
            channel.exec_command('cmd /c' + command)
            output = channel.makefile('rb', -1).readlines()
            print (str(output) + " " + str(command))

            return True, {'msg': 'Command succesfully executed. '}

        except Exception as e:
            return False, {'msg': 'Command could not be executed on the remote server. ' + str(e)}


    def checkIsFileRemote(self, path=None):

        """ Checks whether a file is present in remote host or not"""

        if not path:
            return False, {'msg': 'File path not provided checking'}

        try:
            self._sftp_connect()
            x = self._sftp.stat(path)

        except Exception as e:
            return False, {'msg': 'Path could not be stat: ' + str(e)}

        if not stat.S_ISREG(x.st_mode):
            return False, {'msg': 'Not a file'}

        return True, {'msg': 'Path is a file'}


    def checkIsDirectoryRemote(self, path=None):

        """ Checks whether a directory is present in remote host or not"""

        if not path:
            return False, {'msg': 'Directory path not provided checking'}

        try:
            self._sftp_connect()
            x = self._sftp.stat(path)

            if x.__str__()[0] == 'd':
                return True, {'msg': 'Path is a directory.'}

        except Exception as e:

            errStr = 'Path could not be stat: ' + str(e)
            return False, {'msg': errStr}

        if stat.S_ISREG(x.st_mode):
            return False, {'msg': 'Its a file not a directory !!'}


    def close(self):

        """Closes the connection and cleans up."""

        try:
            # Close SFTP Connection.
            if self._sftp_live:
                self._sftp.close()
                self._sftp_live = False
            # Close the SSH Transport.
            if self._transport_live:
                self._transport.close()
                self._transport_live = False
        except Exception as e:
            return False, {'msg': 'Could not close the SSH connection. ' + str(e)}
        return True, {'msg': 'SSH connection closed successfully'}


if __name__ == '__main__':

    sshObj = SSHConnection()
    result, reply = sshObj.establish_conn('my-server-box')
    reply=sshObj.execute('E:\\abc1.exe /md5 0808197FB92CEF2939EB249E6E79FB6E /outdir E:\\one') #This is working fine
    reply=sshObj.execute('E:\\abc2.exe -collection=E:\\one') # This gives the reply : 'The handle is invalid.' 
所以我的方法没有问题。它工作得很好。 该错误可能与如何编写
abc2.exe
有关


如果有人以前遇到过这种情况,请提供任何建议。提前感谢。

如果还包含调用这两个execute()方法的实际代码(请参阅)@user1656850…感谢您的评论,那么调试可能会更容易。我已输入完整的代码供您参考。请查看是否可以在此提供帮助。由于我假定您没有E:\\abc2.exe的源代码,您可能希望了解如果您单独执行E:\\abc1.exe,或在E:\\abc2.exe之后,或单独执行E:\\abc2.exe,会发生什么情况。