本文整理汇总了Python中paramiko.Transport.close方法的典型用法代码示例。如果您正苦于以下问题:Python Transport.close方法的具体用法?Python Transport.close怎么用?Python Transport.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko.Transport
的用法示例。
在下文中一共展示了Transport.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
def connect(username, hostname='lxplus.cern.ch', port=22):
"Connect to a given host"
print "Connecting to %[email protected]%s" % (username, hostname)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
except Exception as err:
print '*** Connect failed: ' + str(err)
sys.exit(1)
transport = Transport(sock)
try:
transport.start_client()
except paramiko.SSHException as err:
print "SSH negotiation failed\n%s" % str(err)
try:
keys = paramiko.util.load_host_keys(\
os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
try:
keys = paramiko.util.load_host_keys(\
os.path.expanduser('~/ssh/known_hosts'))
except IOError:
print '*** Unable to open host keys file'
keys = {}
# check server's host key -- this is important.
key = transport.get_remote_server_key()
if not keys.has_key(hostname):
print '*** WARNING: Unknown host key!'
elif not keys[hostname].has_key(key.get_name()):
print '*** WARNING: Unknown host key!'
elif keys[hostname][key.get_name()] != key:
print '*** WARNING: Host key has changed!!!'
sys.exit(1)
else:
pass
# get username
if username == '':
default_username = getpass.getuser()
username = raw_input('Username [%s]: ' % default_username)
if len(username) == 0:
username = default_username
agent_auth(transport, username)
if not transport.is_authenticated():
manual_auth(transport, username, hostname)
if not transport.is_authenticated():
print '*** Authentication failed. :('
transport.close()
sys.exit(1)
return transport, sock
示例2: sshAuthentication
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
def sshAuthentication(self, clientsock):
# setup logging
paramiko.util.log_to_file(C.SYSLOG_FILE)
# Check that SSH server parameters have been set:
if (self.sshData == None):
return clientsock, False, None
else:
# Load private key of the server
filekey = self.sshData["hostKeyFile"]
if (not filekey.startswith("/")):
filekey = C.YENCAP_CONF_HOME + "/" + filekey
# Build a key object from the file path:
if (self.sshData["hostKeyType"] == "dss"):
priv_host_key = paramiko.DSSKey(filename=filekey)
elif (self.sshData["hostKeyType"] == "rsa"):
priv_host_key = paramiko.RSAKey(filename=filekey)
try:
event = threading.Event()
# Create a new SSH session over an existing socket, or socket-like object.
t = Transport(clientsock)
# Add a host key to the list of keys used for server mode.
t.add_server_key(priv_host_key)
# paramiko.ServerInterface defines an interface for controlling the behavior of paramiko in server mode.
server = SSHServerModule()
# Negotiate a new SSH2 session as a server.
t.start_server(event, server)
while 1:
event.wait(0.1)
if not t.is_active():
return clientsock, False, None
if event.isSet():
break
# Return the next channel opened by the client over this transport, in server mode.
channel = t.accept(20)
if channel is None:
return clientsock, False, None
except Exception, e:
LogManager.getInstance().logError("Caught exception: %s: %s" % (str(e.__class__), str(e)))
traceback.print_exc()
try:
t.close()
except:
pass
return clientsock, False, None
示例3: upload_report_to_sftp
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
def upload_report_to_sftp(self, client_id, report_date, absolute_filename):
"""
Upload the given file, using SFTP, to the configured FTP server. The
file should be uploaded to the appropriate directory for the specified
client and the date of the report.
"""
try:
client = Clients.objects.get(id=client_id)
except Clients.DoesNotExist:
logger.exception(u'No configuration for client {0}.'.format(client_id))
raise
filename = basename(absolute_filename)
base_folder, env_folder, year_folder, month_folder = self._get_sftp_dirs(client, report_date)
try:
logger.debug(u'SFTP logging on to {0} as {1}'.format(settings.SFTP_SERVER, settings.SFTP_USERNAME))
transport = Transport((settings.SFTP_SERVER, settings.SFTP_PORT))
transport.connect(username=settings.SFTP_USERNAME, password=settings.SFTP_PASSWORD)
sftp = SFTPClient.from_transport(transport)
logger.debug(u'SFTP dir {0}/{1}/{2}/{3}'.format(base_folder, env_folder, year_folder, month_folder))
sftp.chdir(base_folder)
self._make_or_change_sftp_dir(sftp, env_folder)
self._make_or_change_sftp_dir(sftp, year_folder)
self._make_or_change_sftp_dir(sftp, month_folder)
logger.debug(u'SFTP uploading {0}'.format(filename))
sftp.put(absolute_filename, filename)
except Exception:
logger.exception(u'Unrecoverable exception during SFTP upload process.')
raise
finally:
logger.debug(u'SFTP logging off')
try:
sftp.close()
except Exception:
logger.exception(u'SFTP exception while closing SFTP session.')
try:
transport.close()
except Exception:
logger.exception(u'SFTP exception while closing SSH connection.')
示例4: MyTSFTPRequestHandler
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class MyTSFTPRequestHandler(SocketServer.BaseRequestHandler):
timeout = 60
auth_timeout = 60
def setup(self):
self.transport = Transport(self.request)
self.transport.load_server_moduli()
so = self.transport.get_security_options()
so.digests = ('hmac-sha1', )
so.compression = ('[email protected]', 'none')
self.transport.add_server_key(self.server.host_key)
self.transport.set_subsystem_handler(
'sftp', MyTSFTPServer, MyTSFTPServerInterface)
def handle(self):
self.transport.start_server(server=MyTServerInterface())
def handle_timeout(self):
self.transport.close()
示例5: run
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
def run(self, ip, port=22, timeout=2):
try:
socket.setdefaulttimeout(timeout)
s = socket.socket()
s.connect((ip, port))
banner = s.recv(50).strip('\r\n').split(' ')
try:
self.data.version = banner[0]
self.data.os = banner[1]
except IndexError:
pass
s.send('{}\r\n'.format(banner[0]))
self._raw_recv = s.recv(2048)
s.close()
self._parse_raw_data()
# use paramiko to get hostkey because of lazyless...
tran = Transport((ip, port))
tran.start_client()
pubkey = tran.get_remote_server_key()
self.data.pubkey_name = pubkey.get_name()
fp = pubkey.get_fingerprint()
self.data.pubkey_fingerprint = ':'.join(map(lambda x:x.encode('hex'), fp))
ServicesInfo.add(ip, port, 'ssh', self.data)
except Exception as e:
cprint(str(e), 'error')
return None
finally:
tran.close()
self.clear()
return True
示例6: AuthTest
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class AuthTest (unittest.TestCase):
def setUp(self):
self.socks = LoopSocket()
self.sockc = LoopSocket()
self.sockc.link(self.socks)
self.tc = Transport(self.sockc)
self.ts = Transport(self.socks)
def tearDown(self):
self.tc.close()
self.ts.close()
self.socks.close()
self.sockc.close()
def start_server(self):
host_key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
self.public_host_key = RSAKey(data=host_key.asbytes())
self.ts.add_server_key(host_key)
self.event = threading.Event()
self.server = NullServer()
self.assertTrue(not self.event.is_set())
self.ts.start_server(self.event, self.server)
def verify_finished(self):
self.event.wait(1.0)
self.assertTrue(self.event.is_set())
self.assertTrue(self.ts.is_active())
def test_1_bad_auth_type(self):
"""
verify that we get the right exception when an unsupported auth
type is requested.
"""
self.start_server()
try:
self.tc.connect(hostkey=self.public_host_key,
username='unknown', password='error')
self.assertTrue(False)
except:
etype, evalue, etb = sys.exc_info()
self.assertEqual(BadAuthenticationType, etype)
self.assertEqual(['publickey'], evalue.allowed_types)
def test_2_bad_password(self):
"""
verify that a bad password gets the right exception, and that a retry
with the right password works.
"""
self.start_server()
self.tc.connect(hostkey=self.public_host_key)
try:
self.tc.auth_password(username='slowdive', password='error')
self.assertTrue(False)
except:
etype, evalue, etb = sys.exc_info()
self.assertTrue(issubclass(etype, AuthenticationException))
self.tc.auth_password(username='slowdive', password='pygmalion')
self.verify_finished()
def test_3_multipart_auth(self):
"""
verify that multipart auth works.
"""
self.start_server()
self.tc.connect(hostkey=self.public_host_key)
remain = self.tc.auth_password(username='paranoid', password='paranoid')
self.assertEqual(['publickey'], remain)
key = DSSKey.from_private_key_file(test_path('test_dss.key'))
remain = self.tc.auth_publickey(username='paranoid', key=key)
self.assertEqual([], remain)
self.verify_finished()
def test_4_interactive_auth(self):
"""
verify keyboard-interactive auth works.
"""
self.start_server()
self.tc.connect(hostkey=self.public_host_key)
def handler(title, instructions, prompts):
self.got_title = title
self.got_instructions = instructions
self.got_prompts = prompts
return ['cat']
remain = self.tc.auth_interactive('commie', handler)
self.assertEqual(self.got_title, 'password')
self.assertEqual(self.got_prompts, [('Password', False)])
self.assertEqual([], remain)
self.verify_finished()
def test_5_interactive_auth_fallback(self):
"""
verify that a password auth attempt will fallback to "interactive"
if password auth isn't supported but interactive is.
"""
self.start_server()
self.tc.connect(hostkey=self.public_host_key)
remain = self.tc.auth_password('commie', 'cat')
self.assertEqual([], remain)
#.........这里部分代码省略.........
示例7: submitJobToFramework
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
def submitJobToFramework(self, **kwargs):
jobCommand = 'job'
daemonArgs = DaemonArgs(self.config)
daemonArgs.command = jobCommand
unScheduledJob = kwargs['unScheduledJob']
is_fileFeeder = False
fileFeederUploadedFile = None
del daemonArgs.param[:]
# go through all parameters
for parameter in unScheduledJob.parameters.all():
# add parameter to daemonArgs.param
if parameter.service and parameter.param_key and parameter.param_value:
# check if a file feeder is used
if parameter.service == settings.FILE_FEEDER_ID:
is_fileFeeder = True
fileFeederUploadedFile = parameter.param_value
remoteFeederFile = os.path.join(self.sftpRemotePath, parameter.param_value)
parameterString = '%s.%s=%s' % ( parameter.service, parameter.param_key, remoteFeederFile )
else:
parameterString = '%s.%s=%s' % ( parameter.service, parameter.param_key, parameter.param_value )
self.logger.debug("add parameter string: %s" % parameterString)
daemonArgs.param.append([parameterString])
# in case of a filefeeder upload file to framework server
if is_fileFeeder:
self.logger.debug("is file feeder")
sftp = None
transport = None
try:
transport = Transport((self.sftpHost, self.sftpPort))
if self.sftpPassword:
transport.connect(username=self.sftpUsername, password=self.sftpPassword)
else:
privateKey = None
if self.sftpPrivateKeyType and self.sftpPrivateKeyType.lower() == 'rsa':
privateKey = RSAKey.from_private_key_file(self.sftpPrivateKey, password=self.sftpPrivateKeyPassword )
if self.sftpPrivateKeyType and self.sftpPrivateKeyType.lower() == 'dss':
privateKey = DSSKey.from_private_key_file(self.sftpPrivateKey, password=self.sftpPrivateKeyPassword )
transport.connect(username=self.sftpUsername, pkey=privateKey)
sftp = SFTPClient.from_transport(transport)
filePath = os.path.join( settings.MEDIA_ROOT, fileFeederUploadedFile )
remotePath = os.path.join( self.sftpRemotePath, fileFeederUploadedFile )
self.logger.debug("uploading file from %s to %s on remote machine" % (filePath, remotePath))
sftp.put(filePath, remotePath)
# sftp.put(filePath, remotePath, confirm=False)
sftp.chmod( remotePath, 0644 )
self.logger.debug("put OK")
except IOError as e:
self.logger.error("IOError: %s. Will continue with next scheduled job." % e)
self.saveJob(Job.FAILED_STATUS, None, unScheduledJob)
except PasswordRequiredException as e:
self.logger.error("PasswordRequiredException: %s. Will continue with next scheduled job." % e)
self.saveJob(Job.FAILED_STATUS, None, unScheduledJob)
except SSHException as e:
self.logger.error("SSH Exception: %s. Will continue with next scheduled job." % e)
self.saveJob(Job.FAILED_STATUS, None, unScheduledJob)
except Exception as e:
self.logger.error("Unkown SFTP problem. Will continue with next scheduled job. %s" % e)
self.saveJob(Job.FAILED_STATUS, None, unScheduledJob)
finally:
if sftp is not None:
sftp.close()
if transport is not None:
transport.close()
# set job workflow
daemonArgs.jd_workflow = unScheduledJob.workflow.name
frameworkJobId = None
try:
setattr(daemonArgs, jobCommand, 'submit')
frameworkJobId = self.sendFrameworkCommand(jobCommand, daemonArgs)
self.saveJob(Job.PROCESSING_STATUS, frameworkJobId, unScheduledJob)
except WorkflowNotDeployedException:
# The workflow is not deployed in the framework. To prevent the scheduler retrying continuously
# we disable this job
unScheduledJob.status = Schedule.DEACTIVATE_STATUS
unScheduledJob.save()
except:
self.saveJob(Job.FAILED_STATUS, None, unScheduledJob)
finally:
daemonArgs.clean(jobCommand)
if unScheduledJob.scheduled_start is not None:
unScheduledJob.status = Schedule.DEACTIVATED_STATUS
#.........这里部分代码省略.........
示例8: TransportTest
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class TransportTest(ParamikoTest):
def setUp(self):
self.socks = LoopSocket()
self.sockc = LoopSocket()
self.sockc.link(self.socks)
self.tc = Transport(self.sockc)
self.ts = Transport(self.socks)
def tearDown(self):
self.tc.close()
self.ts.close()
self.socks.close()
self.sockc.close()
def setup_test_server(self, client_options=None, server_options=None):
host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = RSAKey(data=str(host_key))
self.ts.add_server_key(host_key)
if client_options is not None:
client_options(self.tc.get_security_options())
if server_options is not None:
server_options(self.ts.get_security_options())
event = threading.Event()
self.server = NullServer()
self.assert_(not event.isSet())
self.ts.start_server(event, self.server)
self.tc.connect(hostkey=public_host_key,
username='slowdive', password='pygmalion')
event.wait(1.0)
self.assert_(event.isSet())
self.assert_(self.ts.is_active())
def test_1_security_options(self):
o = self.tc.get_security_options()
self.assertEquals(type(o), SecurityOptions)
self.assert_(('aes256-cbc', 'blowfish-cbc') != o.ciphers)
o.ciphers = ('aes256-cbc', 'blowfish-cbc')
self.assertEquals(('aes256-cbc', 'blowfish-cbc'), o.ciphers)
try:
o.ciphers = ('aes256-cbc', 'made-up-cipher')
self.assert_(False)
except ValueError:
pass
try:
o.ciphers = 23
self.assert_(False)
except TypeError:
pass
def test_2_compute_key(self):
self.tc.K = long(123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929)
self.tc.H = unhexlify('0C8307CDE6856FF30BA93684EB0F04C2520E9ED3')
self.tc.session_id = self.tc.H
key = self.tc._compute_key('C', 32)
self.assertEquals('207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995',
hexlify(key).upper())
def test_3_simple(self):
"""
verify that we can establish an ssh link with ourselves across the
loopback sockets. this is hardly "simple" but it's simpler than the
later tests. :)
"""
host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = RSAKey(data=str(host_key))
self.ts.add_server_key(host_key)
event = threading.Event()
server = NullServer()
self.assert_(not event.isSet())
self.assertEquals(None, self.tc.get_username())
self.assertEquals(None, self.ts.get_username())
self.assertEquals(False, self.tc.is_authenticated())
self.assertEquals(False, self.ts.is_authenticated())
self.ts.start_server(event, server)
self.tc.connect(hostkey=public_host_key,
username='slowdive', password='pygmalion')
event.wait(1.0)
self.assert_(event.isSet())
self.assert_(self.ts.is_active())
self.assertEquals('slowdive', self.tc.get_username())
self.assertEquals('slowdive', self.ts.get_username())
self.assertEquals(True, self.tc.is_authenticated())
self.assertEquals(True, self.ts.is_authenticated())
def test_3a_long_banner(self):
"""
verify that a long banner doesn't mess up the handshake.
"""
host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = RSAKey(data=str(host_key))
self.ts.add_server_key(host_key)
event = threading.Event()
server = NullServer()
self.assert_(not event.isSet())
self.socks.send(LONG_BANNER)
self.ts.start_server(event, server)
self.tc.connect(hostkey=public_host_key,
username='slowdive', password='pygmalion')
#.........这里部分代码省略.........
示例9: SFTP
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class SFTP(FileBackend):
def __init__(self, config):
FileBackend.__init__(self, config)
self._init_config()
self.session = None
self._init_session()
DEFAULT_CONFIG = {
'sftp_host': 'localhost',
'sftp_port': 22,
'sftp_user': 'anonymous',
'sftp_password': '',
'output_path': ''}
def _init_config(self):
some_changes = False
if 'type' in self.config:
for option, value in SFTP.DEFAULT_CONFIG.items():
if not option in self.config:
self.config[option] = value
some_changes = True
logging.info('set default sftp config.')
else:
self.config['type'] = 'sftp'
self.config.update(SFTP.DEFAULT_CONFIG)
some_changes = True
logging.info('set default sftp config.')
if some_changes:
self.config.save()
# cast config types
self.config['sftp_port'] = int(self.config['sftp_port'])
def _init_session(self):
self.connect()
def connect(self):
self._authenticate()
self.state = self.STATE_CONNECTED
def _authenticate(self):
self._transport = SFTPTransport((self.config['sftp_host'],
self.config['sftp_port']))
self._transport.connect(username=self.config['sftp_user'],
password=self.config['sftp_password'])
self.session = SFTPClient.from_transport(self._transport)
logging.info('SFTP Authorization succeed')
def disconnect(self):
self.session.close()
self._transport.close()
def file_create_folder(self, path):
if self.state == self.STATE_CONNECTED:
dirlist = path.split('/')
current_dirlist = ['']
missing_dirlist = []
current_dirlist.extend(dirlist[:])
while len(current_dirlist) > 0:
current_path = '/'.join(current_dirlist)
try:
self.session.chdir(current_path)
break
except:
missing_dirlist.append(current_dirlist.pop())
missing_dirlist.reverse()
for dirname in missing_dirlist:
dir_contents = self.session.listdir()
if not dirname in dir_contents:
self.session.mkdir(dirname)
logging.info('Create remote directory %s' % self.session.getcwd() + '/' + dirname)
self.session.chdir(dirname)
elif self.state == self.STATE_DISCONNECTED:
raise self.ConnectionException('SFTP is %s' % self.state)
else:
raise NotImplementedError()
def put_file(self, path, file_handle):
if self.state == self.STATE_CONNECTED:
dirpath = '/'.join(path.split('/')[:-1])
self.file_create_folder(dirpath)
try:
self.session.putfo(fl=file_handle, remotepath='/' + path)
logging.info('Create remote file %s' % '/' + path)
except Exception as ex:
logging.error(ex)
elif self.state == self.STATE_DISCONNECTED:
raise self.ConnectionException('SFTP is %s' % self.state)
else:
raise NotImplementedError()
示例10: print
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
# -*- coding: utf-8 -*-
__author__ = 'Administrator'
from paramiko import Transport,RSAKey,SFTPClient
import os
host="54.187.91.18"
port=22
private_key_file=os.path.expanduser("~/.ssh/id_rsa")
key=RSAKey.from_private_key_file(private_key_file)
t=Transport((host,port))
t.connect(username="ec2-user",pkey=key)
sftp=SFTPClient.from_transport(t)
try:
sftp.put("/data/websites/test/a.php","/data/websites/")
except Exception,e:
print(e)
sftp.close()
t.close()
示例11: IrmaSFTP
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class IrmaSFTP(FTPInterface):
"""Irma SFTP handler
This class handles the connection with a sftp server
functions for interacting with it.
"""
_Exception = IrmaSFTPError
# ==================================
# Constructor and Destructor stuff
# ==================================
def __init__(self, host, port, auth, key_path, user, passwd,
dst_user=None, upload_path='uploads', hash_check=False,
autoconnect=True):
self._conn = None
self._client = None
super().__init__(host, port, auth, key_path, user, passwd, dst_user,
upload_path, hash_check, autoconnect)
def connected(self):
return self._conn is not None
# ============================
# Overridden private methods
# ============================
def _connect(self):
self._conn = Transport((self._host, self._port))
self._conn.window_size = pow(2, 27)
self._conn.packetizer.REKEY_BYTES = pow(2, 32)
self._conn.packetizer.REKEY_PACKETS = pow(2, 32)
if self._auth == 'key':
pkey = RSAKey.from_private_key_file(self._key_path)
self._conn.connect(username=self._user, pkey=pkey)
else:
self._conn.connect(username=self._user, password=self._passwd)
self._client = SFTPClient.from_transport(self._conn)
def _disconnect(self, *, force=False):
self._client = None
if not force:
self._conn.close()
self._conn = None
def _upload(self, remote, fobj):
self._client.putfo(fobj, remote)
def _download(self, remote, fobj):
self._client.getfo(remote, fobj)
def _ls(self, remote):
return self._client.listdir(remote)
def _is_file(self, remote):
return not self._is_dir(remote)
def _is_dir(self, remote):
st = self._client.stat(remote)
return stat.S_ISDIR(st.st_mode)
def _rm(self, remote):
self._client.remove(remote)
def _rmdir(self, remote):
self._client.rmdir(remote)
def _mkdir(self, remote):
self._client.mkdir(remote)
def _mv(self, oldremote, newremote):
self._client.rename(oldremote, newremote)
示例12: TransportTest
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class TransportTest (unittest.TestCase):
def setUp(self):
self.socks = LoopSocket()
self.sockc = LoopSocket()
self.sockc.link(self.socks)
self.tc = Transport(self.sockc)
self.ts = Transport(self.socks)
def tearDown(self):
self.tc.close()
self.ts.close()
self.socks.close()
self.sockc.close()
def setup_test_server(self):
host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = RSAKey(data=str(host_key))
self.ts.add_server_key(host_key)
event = threading.Event()
self.server = NullServer()
self.assert_(not event.isSet())
self.ts.start_server(event, self.server)
self.tc.connect(hostkey=public_host_key)
self.tc.auth_password(username='slowdive', password='pygmalion')
event.wait(1.0)
self.assert_(event.isSet())
self.assert_(self.ts.is_active())
def test_1_security_options(self):
o = self.tc.get_security_options()
self.assertEquals(type(o), SecurityOptions)
self.assert_(('aes256-cbc', 'blowfish-cbc') != o.ciphers)
o.ciphers = ('aes256-cbc', 'blowfish-cbc')
self.assertEquals(('aes256-cbc', 'blowfish-cbc'), o.ciphers)
try:
o.ciphers = ('aes256-cbc', 'made-up-cipher')
self.assert_(False)
except ValueError:
pass
try:
o.ciphers = 23
self.assert_(False)
except TypeError:
pass
def test_2_compute_key(self):
self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929L
self.tc.H = unhexlify('0C8307CDE6856FF30BA93684EB0F04C2520E9ED3')
self.tc.session_id = self.tc.H
key = self.tc._compute_key('C', 32)
self.assertEquals('207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995',
hexlify(key).upper())
def test_3_simple(self):
"""
verify that we can establish an ssh link with ourselves across the
loopback sockets. this is hardly "simple" but it's simpler than the
later tests. :)
"""
host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = RSAKey(data=str(host_key))
self.ts.add_server_key(host_key)
event = threading.Event()
server = NullServer()
self.assert_(not event.isSet())
self.assertEquals(None, self.tc.get_username())
self.assertEquals(None, self.ts.get_username())
self.assertEquals(False, self.tc.is_authenticated())
self.assertEquals(False, self.ts.is_authenticated())
self.ts.start_server(event, server)
self.tc.connect(hostkey=public_host_key,
username='slowdive', password='pygmalion')
event.wait(1.0)
self.assert_(event.isSet())
self.assert_(self.ts.is_active())
self.assertEquals('slowdive', self.tc.get_username())
self.assertEquals('slowdive', self.ts.get_username())
self.assertEquals(True, self.tc.is_authenticated())
self.assertEquals(True, self.ts.is_authenticated())
def test_4_special(self):
"""
verify that the client can demand odd handshake settings, and can
renegotiate keys in mid-stream.
"""
host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = RSAKey(data=str(host_key))
self.ts.add_server_key(host_key)
event = threading.Event()
server = NullServer()
self.assert_(not event.isSet())
self.ts.start_server(event, server)
options = self.tc.get_security_options()
options.ciphers = ('aes256-cbc',)
options.digests = ('hmac-md5-96',)
self.tc.connect(hostkey=public_host_key,
username='slowdive', password='pygmalion')
event.wait(1.0)
self.assert_(event.isSet())
#.........这里部分代码省略.........
示例13: upload_report
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
def upload_report(self, filepath, file_name, report_date):
"""
>>> a = CSVgenerator('123')
>>> a.upload_report(None, 'upload.txt', '2014-05-06')
"""
# appropriate changes required for doc test to run - dev only.
# test_file_path = join(settings.REPORTS_ROOT, '16b6a354-ff32-4be4-b648-fe51fc5b1508.csv')
# # trace.info('----- {}'.format(abspath(test_file_path)))
# absolute_filename = abspath(test_file_path)
# test_filename = '16b6a354-ff32-4be4-b648-fe51fc5b1508.csv'
#TODO remove after QA testing.
if not filepath:
test_file_path = join(settings.REPORTS_ROOT, file_name)
absolute_filename = abspath(test_file_path)
else:
absolute_filename = abspath(filepath)
try:
report_date = report_date if isinstance(report_date, str) else report_date.strftime(settings.DATE_FORMAT_YMD)
except Exception:
log.exception('')
try:
#TODO use sftp credentials, once available.
#TODO get client upload location for per-client report.
# ftp_client_dir = client.ftp_client_dir
# if ftp_client_dir == '':
# ftp_client_dir = getattr(settings, 'DEFAULT_SFTP_LOCATION', 'default')
# logger.exception(u'No FTP configuration for client {} using default value.'.format(client.name))
#
year_folder, month_folder, _ = report_date.split('-')
base_folder_path = self._sftp_settings.get('path', '')
base_path = base_folder_path.split('/')
base_folders = [i for i in base_path[1:-1]]
base_folder = '/' + join(*base_folders)
env_folder = str(base_path[-1:][0])
from paramiko import Transport, SFTPClient
try:
log.info(u'SFTP logging on to {0} as {1}'.format(settings.SFTP_SERVER, settings.SFTP_USERNAME))
transport = Transport((
self._sftp_settings.get('server', ''),
self._sftp_settings.get('port', 22))
)
transport.connect(
username=self._sftp_settings.get('username', ''),
password=self._sftp_settings.get('password', '')
)
sftp = SFTPClient.from_transport(transport)
log.info(u'SFTP dir {0}/{1}/{2}/{3}'.format(base_folder, env_folder, year_folder, month_folder))
try:
sftp.chdir(base_folder)
except Exception:
log.debug('Unable to change to base folder on ftp server.')
self._make_or_change_sftp_dir(sftp, env_folder)
self._make_or_change_sftp_dir(sftp, year_folder)
self._make_or_change_sftp_dir(sftp, month_folder)
log.debug(u'SFTP uploading {0}'.format(filepath))
sftp.put(absolute_filename, file_name)
except Exception:
log.exception(u'Unrecoverable exception during SFTP upload process.')
finally:
log.debug(u'SFTP logging off')
try:
sftp.close()
except Exception:
log.exception(u'SFTP exception while closing SFTP session.')
try:
transport.close()
except Exception:
log.exception(u'SFTP exception while closing SSH connection.')
except Exception:
log.debug('Error while uploading report.')
示例14: TransportTest
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class TransportTest(unittest.TestCase):
def setUp(self):
self.socks = LoopSocket()
self.sockc = LoopSocket()
self.sockc.link(self.socks)
self.tc = Transport(self.sockc)
self.ts = Transport(self.socks)
def tearDown(self):
self.tc.close()
self.ts.close()
self.socks.close()
self.sockc.close()
def setup_test_server(
self, client_options=None, server_options=None, connect_kwargs=None,
):
host_key = RSAKey.from_private_key_file(_support('test_rsa.key'))
public_host_key = RSAKey(data=host_key.asbytes())
self.ts.add_server_key(host_key)
if client_options is not None:
client_options(self.tc.get_security_options())
if server_options is not None:
server_options(self.ts.get_security_options())
event = threading.Event()
self.server = NullServer()
self.assertTrue(not event.is_set())
self.ts.start_server(event, self.server)
if connect_kwargs is None:
connect_kwargs = dict(
hostkey=public_host_key,
username='slowdive',
password='pygmalion',
)
self.tc.connect(**connect_kwargs)
event.wait(1.0)
self.assertTrue(event.is_set())
self.assertTrue(self.ts.is_active())
def test_1_security_options(self):
o = self.tc.get_security_options()
self.assertEqual(type(o), SecurityOptions)
self.assertTrue(('aes256-cbc', 'blowfish-cbc') != o.ciphers)
o.ciphers = ('aes256-cbc', 'blowfish-cbc')
self.assertEqual(('aes256-cbc', 'blowfish-cbc'), o.ciphers)
try:
o.ciphers = ('aes256-cbc', 'made-up-cipher')
self.assertTrue(False)
except ValueError:
pass
try:
o.ciphers = 23
self.assertTrue(False)
except TypeError:
pass
def test_1b_security_options_reset(self):
o = self.tc.get_security_options()
# should not throw any exceptions
o.ciphers = o.ciphers
o.digests = o.digests
o.key_types = o.key_types
o.kex = o.kex
o.compression = o.compression
def test_2_compute_key(self):
self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929
self.tc.H = b'\x0C\x83\x07\xCD\xE6\x85\x6F\xF3\x0B\xA9\x36\x84\xEB\x0F\x04\xC2\x52\x0E\x9E\xD3'
self.tc.session_id = self.tc.H
key = self.tc._compute_key('C', 32)
self.assertEqual(b'207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995',
hexlify(key).upper())
def test_3_simple(self):
"""
verify that we can establish an ssh link with ourselves across the
loopback sockets. this is hardly "simple" but it's simpler than the
later tests. :)
"""
host_key = RSAKey.from_private_key_file(_support('test_rsa.key'))
public_host_key = RSAKey(data=host_key.asbytes())
self.ts.add_server_key(host_key)
event = threading.Event()
server = NullServer()
self.assertTrue(not event.is_set())
self.assertEqual(None, self.tc.get_username())
self.assertEqual(None, self.ts.get_username())
self.assertEqual(False, self.tc.is_authenticated())
self.assertEqual(False, self.ts.is_authenticated())
self.ts.start_server(event, server)
self.tc.connect(hostkey=public_host_key,
username='slowdive', password='pygmalion')
event.wait(1.0)
self.assertTrue(event.is_set())
self.assertTrue(self.ts.is_active())
self.assertEqual('slowdive', self.tc.get_username())
self.assertEqual('slowdive', self.ts.get_username())
self.assertEqual(True, self.tc.is_authenticated())
#.........这里部分代码省略.........
示例15: SFTPStore
# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import close [as 别名]
class SFTPStore(Store):
"""implements the sftp:// storage backend
configuration via openssh/sftp style urls and
.ssh/config files
does not support password authentication or password
protected authentication keys"""
def __init__(self, url, **kw):
if self.netloc.find('@') != -1:
user, self.netloc = self.netloc.split('@')
else:
user = None
self.config = SSHHostConfig(self.netloc, user)
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
try:
self.hostkey = list(host_keys[self.config['hostkeyalias']].values())[0]
except:
print(str(self.config))
raise
if('identityfile' in self.config):
key_file = os.path.expanduser(self.config['identityfile'])
#not really nice but i don't see a cleaner way atm...
try:
self.auth_key = RSAKey (key_file)
except SSHException as e:
if e.message == 'Unable to parse file':
self.auth_key = DSAKey (key_file)
else:
raise
else:
filename = os.path.expanduser('~/.ssh/id_rsa')
if os.path.exists(filename):
self.auth_key = RSAKey(filename)
else:
filename = os.path.expanduser('~/.ssh/id_dsa')
if (os.path.exists(filename)):
self.auth_key = DSSKey (filename)
self.__connect()
def __connect(self):
self.t = Transport((self.config['hostname'], self.config['port']))
self.t.connect(username = self.config['user'], pkey = self.auth_key)
self.client = SFTPClient.from_transport(self.t)
self.client.chdir(self.path)
def __build_fn(self, name):
return "%s/%s" % (self.path, name)
def list(self, type):
return list(filter(type_patterns[type].match, self.client.listdir(self.path)))
def get(self, type, name):
return self.client.open(self.__build_fn(name), mode = 'rb')
def put(self, type, name, fp):
remote_file = self.client.open(self.__build_fn(name), mode = 'wb')
buf = fp.read(4096)
while (len(buf) > 0):
remote_file.write(buf)
buf = fp.read(4096)
remote_file.close()
def delete(self, type, name):
self.client.remove(self.__build_fn(name))
def stat(self, type, name):
try:
stat = self.client.stat(self.__build_fn(name))
return {'size': stat.st_size}
except IOError:
raise NotFoundError
def close(self):
"""connection has to be explicitly closed, otherwise
it will hold the process running idefinitly"""
self.client.close()
self.t.close()