我用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的写入方式有关。在
如果有人以前遇到过这种情况,有什么建议吗。提前谢谢。在